Skip to main content

xila_abi_application_c_tests/
lib.rs

1#[cfg(test)]
2mod tests {
3    use abi_application::*;
4    use core::ptr::{self, NonNull};
5
6    /// The heap and host state of a test run. They are leaked, like the other
7    /// fixtures here, so the coroutine entry holds only pointers to them.
8    fn run_state(
9        arguments: Vec<String>,
10        input: Option<File>,
11        output: Option<File>,
12        error: Option<File>,
13    ) -> (NonNull<HostState>, NonNull<Heap>) {
14        (
15            NonNull::from(Box::leak(Box::new(HostState::new(
16                arguments, input, output, error,
17            )))),
18            NonNull::from(Box::leak(Box::new(Heap::new()))),
19        )
20    }
21    testing::instantiate_global_allocator!();
22
23    #[unsafe(no_mangle)]
24    pub extern "C" fn application_c_pause() {
25        std::thread::sleep(core::time::Duration::from_millis(1));
26    }
27
28    // C only passes this opaque object through; it never reads the Rust layout.
29    #[allow(improper_ctypes)]
30    unsafe extern "C" {
31        fn application_c_round_trip(api: *const XilaApi, directory: *const Directory) -> i32;
32        fn application_c_file_system(api: *const XilaApi, directory: *const Directory) -> i32;
33        fn startup_test_main(startup: *const XilaStartup) -> i32;
34        fn sdk_test_versions();
35        fn sdk_test_startup(startup: *const XilaStartup) -> i32;
36        fn startup_heap_main(startup: *const XilaStartup) -> i32;
37        fn startup_empty_main(startup: *const XilaStartup) -> i32;
38        fn startup_clock_random_main(startup: *const XilaStartup) -> i32;
39        fn threads_main(startup: *const XilaStartup) -> i32;
40        fn process_parent_main(startup: *const XilaStartup) -> i32;
41        fn process_test_entry(name: *const core::ffi::c_char, length: usize) -> Option<ChildEntry>;
42        fn application_c_network(
43            api: *const XilaApi,
44            network: *const Network,
45            denied: *const Network,
46            listen_only: *const Network,
47            cooperative: bool,
48        ) -> i32;
49    }
50
51    #[test]
52    fn sdk_checks_compatibility_at_major_and_minor_boundaries() {
53        unsafe { sdk_test_versions() };
54    }
55
56    type ChildEntry = unsafe extern "C" fn(*const XilaStartup) -> i32;
57
58    /// Starts the C children of `process.c` as coroutine tasks of the caller's executor,
59    /// choosing the entry by the file name of the spawned path, as Core's host does
60    /// with the executable it finds there.
61    #[cfg(all(
62        target_os = "linux",
63        any(target_arch = "x86_64", target_arch = "aarch64")
64    ))]
65    struct TestHost {
66        tasks: &'static task::Manager,
67        vfs: &'static virtual_file_system::VirtualFileSystem,
68    }
69    #[cfg(all(
70        target_os = "linux",
71        any(target_arch = "x86_64", target_arch = "aarch64")
72    ))]
73    impl ProcessHost for TestHost {
74        fn task_manager(&self) -> &'static task::Manager {
75            self.tasks
76        }
77        fn virtual_file_system(&self) -> &'static virtual_file_system::VirtualFileSystem {
78            self.vfs
79        }
80        fn spawn(&'static self, request: SpawnRequest) -> SpawnFuture {
81            Box::pin(async move {
82                let name = request
83                    .path
84                    .as_str()
85                    .rsplit('/')
86                    .next()
87                    .unwrap()
88                    .to_string();
89                // SAFETY: the C table only reads the name.
90                let entry = unsafe { process_test_entry(name.as_ptr().cast(), name.len()) }
91                    .ok_or(Status::NotFound)?;
92                let SpawnRequest {
93                    arguments,
94                    environment,
95                    standard_input,
96                    standard_output,
97                    standard_error,
98                    home,
99                    network,
100                    ..
101                } = request;
102                let launch = ProcessLaunch {
103                    host: self,
104                    environment,
105                    home,
106                    network,
107                };
108                // The spawn future runs on the spawner's task, which is the child's parent.
109                let parent = self.tasks.get_current_task_identifier().await;
110                let stream = |file: virtual_file_system::File<'static>| {
111                    Some(File::new(file.into_synchronous_file()))
112                };
113                let (input, output, error) = (
114                    stream(standard_input),
115                    stream(standard_output),
116                    stream(standard_error),
117                );
118                let (state, heap) = run_state(arguments, input, output, error);
119                // SAFETY: the bounded C children fit the stack and never unwind; the closure
120                // moves every owned value into `run`, as the exit contract requires.
121                let spawned = unsafe {
122                    stackful::spawn_with_result(
123                        self.tasks,
124                        parent,
125                        &name,
126                        stackful::Stack::new(64 * 1024),
127                        move || launch.run(state, entry, heap),
128                        |status| status as isize,
129                    )
130                    .await
131                }
132                .map_err(|error| {
133                    Status::from(file_system::IntoIoErrorKind::into_io_error_kind(error))
134                })?;
135                Ok(spawned)
136            })
137        }
138    }
139
140    /// Entropy source that reads at most three bytes at a time, is pending on every
141    /// other read, fills with 0xA5, is unavailable for 13-byte requests, makes
142    /// no progress for 17-byte requests and never answers 19-byte requests. It keeps no
143    /// per-test mode, so tests that share the process-wide installation cannot
144    /// disturb each other.
145    struct ScriptedEntropy(portable_atomic::AtomicUsize);
146    static ENTROPY: ScriptedEntropy = ScriptedEntropy(portable_atomic::AtomicUsize::new(0));
147    impl file_system::DirectBaseOperations for ScriptedEntropy {
148        fn read(
149            &self,
150            cx: &mut core::task::Context<'_>,
151            buffer: &mut [u8],
152            _: file_system::Size,
153        ) -> core::task::Poll<file_system::Result<usize>> {
154            match buffer.len() {
155                13 => {
156                    return core::task::Poll::Ready(Err(
157                        file_system::IoErrorKind::DeviceUnavailable,
158                    ));
159                }
160                17 => return core::task::Poll::Ready(Ok(0)),
161                19 => return core::task::Poll::Pending,
162                _ => {}
163            }
164            if self
165                .0
166                .fetch_add(1, portable_atomic::Ordering::Relaxed)
167                .is_multiple_of(2)
168            {
169                cx.waker().wake_by_ref();
170                return core::task::Poll::Pending;
171            }
172            let count = buffer.len().min(3);
173            buffer[..count].fill(0xA5);
174            core::task::Poll::Ready(Ok(count))
175        }
176        fn write(
177            &self,
178            _: &mut core::task::Context<'_>,
179            _: &[u8],
180            _: file_system::Size,
181        ) -> core::task::Poll<file_system::Result<usize>> {
182            core::task::Poll::Ready(Err(file_system::IoErrorKind::Unsupported))
183        }
184    }
185    impl file_system::MountOperations for ScriptedEntropy {
186        fn unmount(&self) -> file_system::Result<()> {
187            Ok(())
188        }
189    }
190    impl file_system::DirectCharacterDevice for ScriptedEntropy {}
191    async fn install_entropy() -> &'static virtual_file_system::VirtualFileSystem {
192        use virtual_file_system::{ItemStatic, VirtualFileSystem};
193
194        // The task test harness serializes these tests and reuses its manager.
195        static VFS: std::sync::OnceLock<&'static VirtualFileSystem> = std::sync::OnceLock::new();
196        if VFS.get().is_none() {
197            let tasks = task::test_manager();
198            let parent = tasks.get_current_task_identifier().await;
199            let users = Box::leak(Box::new(users::Manager::new()));
200            let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
201            let device = file_system::MemoryDevice::<512>::new_static(128 * 1024);
202            let fs =
203                little_fs::FileSystem::new_format(device, little_fs::Options::new(128)).unwrap();
204            let vfs = Box::leak(Box::new(VirtualFileSystem::new(tasks, users, time, fs)));
205            vfs.create_directory(parent, &"/devices").await.unwrap();
206            vfs.create_directory(parent, &"/devices/random")
207                .await
208                .unwrap();
209            vfs.mount_static(
210                parent,
211                "/devices/random/source",
212                ItemStatic::CharacterDevice(&ENTROPY),
213            )
214            .await
215            .unwrap();
216            assert!(VFS.set(vfs).is_ok());
217        }
218        initialize_random(VFS.get().unwrap()).await;
219        VFS.get().unwrap()
220    }
221
222    #[test]
223    fn process_heap_reclaims_c_allocations_on_return() {
224        let before = testing::MemoryManager::thread_allocations();
225        let mut heap = Heap::new();
226        let result = unsafe { run_main(startup_heap_main, &mut heap, &[], None, None, None, None) };
227        assert!(
228            testing::MemoryManager::thread_allocations()
229                .since(before)
230                .net_bytes()
231                > 0
232        );
233        drop(heap);
234        let delta = testing::MemoryManager::thread_allocations().since(before);
235        assert_eq!(result, 0);
236        assert!(delta.allocations() >= 2);
237        assert_eq!(delta.net_bytes(), 0);
238    }
239
240    #[test]
241    fn sdk_startup_dispatches_through_supplied_api() {
242        let result = unsafe {
243            run_main(
244                sdk_test_startup,
245                &mut Heap::new(),
246                &[],
247                None,
248                None,
249                None,
250                None,
251            )
252        };
253        assert_eq!(result, 42);
254    }
255
256    #[task::test]
257    async fn real_vfs_and_c_client() {
258        let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
259        let tasks = Box::leak(Box::new(task::Manager::new()));
260        let users = Box::leak(Box::new(users::Manager::new()));
261        let task = tasks.get_current_task_identifier().await;
262        let device = file_system::MemoryDevice::<512>::new_static(1024 * 512);
263        let fs = little_fs::FileSystem::new_format(device, little_fs::Options::new(256)).unwrap();
264        let vfs = Box::leak(Box::new(
265            virtual_file_system::initialize(tasks, users, time, fs).unwrap(),
266        ));
267        abi_application::initialize(time);
268        virtual_file_system::create_default_hierarchy(vfs, task)
269            .await
270            .unwrap();
271        let network: &'static network::Manager = Box::leak(Box::new(network::Manager::new(
272            tasks,
273            vfs,
274            time,
275            &testing::RandomDevice,
276        )));
277        // The C client blocks its thread, so the interface runner needs its own
278        // executor. `mount_interface` spawns the runner on the calling executor:
279        // mount from a task sent to that thread.
280        let spawner = testing::new_thread_executor(tasks).await;
281        tasks
282            .spawn_send(task, "Mount loopback", Some(spawner), move |_| async move {
283                let (device, controller) = network::create_loopback_device();
284                network
285                    .mount_interface(task, "loopback0", device, controller, None)
286                    .await
287            })
288            .await
289            .unwrap()
290            .0
291            .join()
292            .await
293            .unwrap();
294        let mut interface = virtual_file_system::File::open(
295            vfs,
296            task,
297            "/devices/network/loopback0",
298            file_system::AccessFlags::Write.into(),
299        )
300        .await
301        .unwrap();
302        interface
303            .control(
304                network::ADD_IP_ADDRESS,
305                &network::IpCidrAbi::from(network::IpCidr::new_ipv4([127, 0, 0, 1], 8)),
306            )
307            .await
308            .unwrap();
309        interface.close(vfs).await.unwrap();
310        assert!(matches!(
311            Network::new(network, 8),
312            Err(Status::InvalidArgument)
313        ));
314        let authority = Network::new(network, 7).unwrap();
315        let denied = Network::new(network, 0).unwrap();
316        let listen_only = Network::new(network, XILA_NETWORK_LISTEN).unwrap();
317        #[cfg(all(
318            target_os = "linux",
319            any(target_arch = "x86_64", target_arch = "aarch64")
320        ))]
321        {
322            // Run socket waits on a coroutine while the loopback runner wakes it from
323            // its executor thread. The C fixture fits the stack and cannot unwind.
324            let result = unsafe {
325                stackful::Coroutine::new(stackful::Stack::new(64 * 1024), move || {
326                    application_c_network(&XILA_API, &authority, &denied, &listen_only, true)
327                })
328            }
329            .await;
330            assert_eq!(result, 0, "network C fixture failed");
331        }
332        #[cfg(not(all(
333            target_os = "linux",
334            any(target_arch = "x86_64", target_arch = "aarch64")
335        )))]
336        assert_eq!(
337            unsafe { application_c_network(&XILA_API, &authority, &denied, &listen_only, false) },
338            0
339        );
340
341        install_entropy().await;
342        unsafe {
343            let mut mono = 0;
344            let mut real = 17;
345            assert_eq!(xila_time_monotonic(&mut mono), Status::Ok);
346            time.invalidate();
347            assert_eq!(
348                run_main(
349                    startup_clock_random_main,
350                    &mut Heap::new(),
351                    &["unsynchronized"],
352                    None,
353                    None,
354                    None,
355                    None
356                ),
357                0
358            );
359            assert_eq!(xila_time_realtime(&mut real), Status::Unavailable);
360            assert_eq!(real, 17);
361            time.set_realtime(time::RealtimeSample {
362                timestamp: time::Timestamp::from_nanos(i128::from(i64::MAX) + 1_000_000_000),
363                resolution: core::time::Duration::from_nanos(1),
364                source: time::ClockSource::Manual,
365                accuracy: None,
366            })
367            .unwrap();
368            assert_eq!(xila_time_realtime(&mut real), Status::Overflow);
369            assert_eq!(real, 17);
370        }
371        time.set_realtime(time::RealtimeSample {
372            timestamp: time::Timestamp::from_nanos(1_700_000_000_000_000_000),
373            resolution: core::time::Duration::from_secs(1),
374            source: time::ClockSource::Manual,
375            accuracy: None,
376        })
377        .unwrap();
378        unsafe {
379            assert_eq!(
380                run_main(
381                    startup_clock_random_main,
382                    &mut Heap::new(),
383                    &["synchronized"],
384                    None,
385                    None,
386                    None,
387                    None
388                ),
389                0
390            );
391            assert_eq!(
392                run_main(
393                    startup_empty_main,
394                    &mut Heap::new(),
395                    &[],
396                    None,
397                    None,
398                    None,
399                    None
400                ),
401                -7
402            );
403            let path = file_system::Path::from_str("/startup-output");
404            let output = virtual_file_system::SynchronousFile::open(
405                vfs,
406                task,
407                path,
408                file_system::Flags::new(
409                    file_system::AccessFlags::READ_WRITE,
410                    Some(file_system::CreateFlags::Create),
411                    None,
412                ),
413            )
414            .unwrap();
415            assert_eq!(
416                run_main(
417                    startup_test_main,
418                    &mut Heap::new(),
419                    &["", "héllo"],
420                    None,
421                    Some(File::new(output)),
422                    None,
423                    Some(Directory::new(vfs, task, "/", 3).unwrap())
424                ),
425                23
426            );
427            let mut output = virtual_file_system::SynchronousFile::open(
428                vfs,
429                task,
430                path,
431                file_system::AccessFlags::Read.into(),
432            )
433            .unwrap();
434            let mut bytes = [0; 7];
435            assert_eq!(output.read(&mut bytes).unwrap(), 7);
436            assert_eq!(&bytes, b"startup");
437            let home_file = virtual_file_system::SynchronousFile::open(
438                vfs,
439                task,
440                file_system::Path::from_str("/startup-home"),
441                file_system::AccessFlags::Read.into(),
442            )
443            .unwrap();
444            drop(home_file);
445        }
446        let directory = Directory::new(vfs, task, "/./", 3).unwrap().into_raw();
447        unsafe {
448            assert_eq!(application_c_round_trip(&XILA_API, directory), 0);
449            assert_eq!(application_c_file_system(&XILA_API, directory), 0);
450            // Validate conversion independently from the C client, including overflow.
451            let mut source = vfs
452                .get_statistics_for_task(task, &file_system::Path::ROOT)
453                .await
454                .unwrap();
455            source.access = file_system::Time::new(1);
456            source.modification = file_system::Time::new(2);
457            source.status = file_system::Time::new(3);
458            let statistics = Statistics::try_from(source.clone()).unwrap();
459            assert_eq!(statistics.access_nanoseconds, 1_000_000_000);
460            assert_eq!(statistics.modification_nanoseconds, 2_000_000_000);
461            assert_eq!(statistics.status_change_nanoseconds, 3_000_000_000);
462            source.access = file_system::Time::new(u64::MAX);
463            assert_eq!(Statistics::try_from(source), Err(Status::Overflow));
464            let mut file = ptr::null_mut();
465            for (path, length) in [
466                (c"/outside".as_ptr(), 8),
467                (c"../outside".as_ptr(), 10),
468                (c"".as_ptr(), 0),
469                (c"nul".as_ptr(), 4),
470            ] {
471                assert_eq!(
472                    xila_file_open(directory, path, length, 1, &mut file),
473                    Status::InvalidArgument
474                );
475                assert!(file.is_null());
476            }
477            assert_eq!(
478                xila_file_open(directory, ptr::null(), 0, 1, &mut file),
479                Status::InvalidArgument
480            );
481            assert_eq!(
482                xila_file_open(directory, c"c-file".as_ptr(), 6, 1, ptr::null_mut()),
483                Status::InvalidArgument
484            );
485            let invalid_utf8 = [255u8];
486            assert_eq!(
487                xila_file_open(directory, invalid_utf8.as_ptr().cast(), 1, 1, &mut file),
488                Status::InvalidArgument
489            );
490
491            assert_eq!(
492                xila_file_open(directory, c"c-file".as_ptr(), 6, 2 | 4 | 8, &mut file),
493                Status::AlreadyExists
494            );
495            assert!(file.is_null());
496            assert_eq!(
497                xila_file_open(directory, c"c-file".as_ptr(), 6, 2, &mut file),
498                Status::Ok
499            );
500            let mut count = 99;
501            let mut buffer = [0u8; 5];
502            assert_eq!(
503                xila_file_read(file, buffer.as_mut_ptr().cast(), 5, &mut count),
504                Status::BadDescriptor
505            );
506            assert_eq!(count, 99);
507            assert_eq!(
508                xila_file_write(file, ptr::null(), 0, &mut count),
509                Status::Ok
510            );
511            assert_eq!(count, 0);
512            assert_eq!(
513                xila_file_write(file, ptr::null(), 1, &mut count),
514                Status::InvalidArgument
515            );
516            assert_eq!(
517                xila_file_seek(file, -1, 0, ptr::null_mut()),
518                Status::InvalidArgument
519            );
520            assert_eq!(
521                xila_file_seek(file, 0, 3, ptr::null_mut()),
522                Status::InvalidArgument
523            );
524            assert_eq!(xila_file_close(file), Status::Ok);
525            let mut child = ptr::null_mut();
526            assert_eq!(
527                xila_directory_open(directory, c"c-file".as_ptr(), 6, 1, &mut child),
528                Status::NotADirectory
529            );
530            assert!(child.is_null());
531            assert_eq!(
532                xila_directory_open(directory, c".".as_ptr(), 1, 1, &mut child),
533                Status::Ok
534            );
535            let mut escalated = ptr::null_mut();
536            assert_eq!(
537                xila_directory_open(child, c".".as_ptr(), 1, 3, &mut escalated),
538                Status::PermissionDenied
539            );
540            assert_eq!(
541                xila_file_open(child, c"c-file".as_ptr(), 6, 2, &mut file),
542                Status::PermissionDenied
543            );
544            assert_eq!(
545                xila_file_open(child, c"c-file".as_ptr(), 6, 1, &mut file),
546                Status::Ok
547            );
548            assert_eq!(
549                xila_file_read(file, buffer.as_mut_ptr().cast(), 5, &mut count),
550                Status::Ok
551            );
552            assert_eq!(&buffer, b"hello");
553            assert_eq!(xila_file_seek(file, -1, 2, ptr::null_mut()), Status::Ok);
554            assert_eq!(xila_file_close(file), Status::Ok);
555            xila_directory_close(child);
556            xila_directory_close(directory);
557        }
558    }
559
560    #[cfg(all(
561        target_os = "linux",
562        any(target_arch = "x86_64", target_arch = "aarch64")
563    ))]
564    #[task::test]
565    async fn stackful_file_read_yields_to_executor_peer() {
566        use core::task::{Context as TaskContext, Poll, Waker};
567        use file_system::{
568            BaseOperations, CharacterDevice, Context as DeviceContext, MountOperations, Operation,
569            ReadyEvents, Size, notify_readiness,
570        };
571        use portable_atomic::{AtomicBool, AtomicUsize, Ordering};
572        use std::sync::Mutex;
573
574        #[derive(Default)]
575        struct ReadState {
576            ready: AtomicBool,
577            polls: AtomicUsize,
578            readiness_seen: AtomicBool,
579            control_polls: AtomicUsize,
580            waker: Mutex<Option<Waker>>,
581        }
582        struct PendingDevice(&'static ReadState);
583        impl BaseOperations for PendingDevice {
584            fn read(
585                &self,
586                _: &mut DeviceContext,
587                cx: &mut TaskContext<'_>,
588                buffer: &mut [u8],
589                _: Size,
590            ) -> Poll<file_system::Result<usize>> {
591                let polls = self.0.polls.fetch_add(1, Ordering::Relaxed);
592                if self.0.ready.load(Ordering::Relaxed) {
593                    buffer.copy_from_slice(b"ok");
594                    return Poll::Ready(Ok(2));
595                }
596                // Fail promptly if the caller polls again without letting the peer run.
597                if polls != 0 {
598                    return Poll::Ready(Err(file_system::IoErrorKind::Unsupported));
599                }
600                *self.0.waker.lock().unwrap() = Some(cx.waker().clone());
601                Poll::Pending
602            }
603
604            fn write(
605                &self,
606                _: &mut DeviceContext,
607                _: &mut TaskContext<'_>,
608                _: &[u8],
609                _: Size,
610            ) -> Poll<file_system::Result<usize>> {
611                Poll::Ready(Err(file_system::IoErrorKind::Unsupported))
612            }
613
614            fn control(
615                &self,
616                _: &mut DeviceContext,
617                cx: &mut TaskContext<'_>,
618                command: file_system::ControlCommandIdentifier,
619                _: &shared::AnyByLayout,
620                output: &mut shared::AnyByLayout,
621            ) -> Poll<file_system::Result<()>> {
622                use file_system::{ControlCommand, character_device::IS_A_TERMINAL};
623                if command != IS_A_TERMINAL::IDENTIFIER {
624                    return Poll::Ready(Err(file_system::IoErrorKind::Unsupported));
625                }
626                if self.0.control_polls.fetch_add(1, Ordering::Relaxed) == 0 {
627                    cx.waker().wake_by_ref();
628                    return Poll::Pending;
629                }
630                *IS_A_TERMINAL::cast_output(output).unwrap() = 1;
631                Poll::Ready(Ok(()))
632            }
633
634            fn clone_context(&self, _: &DeviceContext) -> file_system::Result<DeviceContext> {
635                Ok(DeviceContext::new_empty())
636            }
637
638            fn cancel_operation(&self, _: &mut DeviceContext, _: Operation) {
639                self.0.waker.lock().unwrap().take();
640            }
641        }
642        impl MountOperations for PendingDevice {}
643        impl CharacterDevice for PendingDevice {
644            fn readiness(
645                &self,
646                interests: ReadyEvents,
647            ) -> file_system::Result<Option<ReadyEvents>> {
648                self.0.readiness_seen.store(true, Ordering::Relaxed);
649                Ok(Some(if self.0.ready.load(Ordering::Relaxed) {
650                    interests
651                } else {
652                    ReadyEvents::empty()
653                }))
654            }
655        }
656
657        let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
658        let tasks = task::test_manager();
659        let users = Box::leak(Box::new(users::Manager::new()));
660        let task = tasks.get_current_task_identifier().await;
661        let spawner = tasks.get_spawner(task).await.unwrap();
662        let device = file_system::MemoryDevice::<512>::new_static(1024 * 512);
663        let fs = little_fs::FileSystem::new_format(device, little_fs::Options::new(256)).unwrap();
664        let vfs = Box::leak(Box::new(
665            virtual_file_system::initialize(tasks, users, time, fs).unwrap(),
666        ));
667        virtual_file_system::create_default_hierarchy(vfs, task)
668            .await
669            .unwrap();
670
671        let state: &'static ReadState = Box::leak(Box::new(ReadState::default()));
672        vfs.mount_character_device(task, "/devices/pending", PendingDevice(state))
673            .await
674            .unwrap();
675
676        vfs.mount_character_device(
677            task,
678            "/devices/default",
679            ScriptedEntropy(AtomicUsize::new(0)),
680        )
681        .await
682        .unwrap();
683
684        let root = Directory::new(vfs, task, "/", XILA_RIGHT_READ).unwrap();
685        let path = c"devices/default";
686        let mut default_file = ptr::null_mut();
687        unsafe {
688            assert_eq!(
689                xila_file_open(
690                    &root,
691                    path.as_ptr(),
692                    path.count_bytes(),
693                    XILA_OPEN_READ,
694                    &mut default_file
695                ),
696                Status::Ok
697            );
698            let mut entry = PollEntry {
699                handle: default_file.cast(),
700                kind: XILA_POLL_FILE,
701                events: XILA_POLL_IN | XILA_POLL_OUT,
702                revents: 0,
703            };
704            let mut ready = 0;
705            assert_eq!(xila_poll_wait(&mut entry, 1, 0, &mut ready), Status::Ok);
706            assert_eq!(ready, 1);
707            assert_eq!(entry.revents, XILA_POLL_IN);
708            assert_eq!(xila_file_close(default_file), Status::Ok);
709        }
710
711        let path = c"devices/pending";
712        let mut file = ptr::null_mut();
713        unsafe {
714            assert_eq!(
715                xila_file_open(
716                    &root,
717                    path.as_ptr(),
718                    path.count_bytes(),
719                    XILA_OPEN_READ,
720                    &mut file
721                ),
722                Status::Ok
723            );
724            let mut buffer = [0; 2];
725            let mut count = 99;
726            let status = xila_file_read(file, buffer.as_mut_ptr().cast(), buffer.len(), &mut count);
727            assert_eq!(status, Status::WouldBlock);
728            assert_eq!(count, 99);
729            let mut terminal = false;
730            assert_eq!(
731                xila_file_is_terminal(file, &mut terminal),
732                Status::WouldBlock
733            );
734            assert!(!terminal);
735        }
736        assert_eq!(state.control_polls.swap(0, Ordering::Relaxed), 1);
737        assert_eq!(state.polls.swap(0, Ordering::Relaxed), 1);
738        assert!(state.waker.lock().unwrap().is_none());
739
740        // SAFETY: The bounded ABI call chain fits within the supplied stack.
741        // The fixture closes the handle after both tasks complete.
742        let (reader, _) = unsafe {
743            stackful::spawn(
744                tasks,
745                task,
746                "ABI reader",
747                stackful::Stack::new(64 * 1024),
748                move || {
749                    let mut buffer = [0; 2];
750                    let mut count = 0;
751                    let status =
752                        xila_file_read(file, buffer.as_mut_ptr().cast(), buffer.len(), &mut count);
753                    let mut terminal = false;
754                    let terminal_status = xila_file_is_terminal(file, &mut terminal);
755                    i32::from(
756                        status != Status::Ok
757                            || count != 2
758                            || &buffer != b"ok"
759                            || terminal_status != Status::Ok
760                            || !terminal,
761                    )
762                },
763            )
764            .await
765            .unwrap()
766        };
767        // The readiness wait and the read are independently registered on
768        // the same handle. A readiness probe never consumes the data.
769        let (poller, _) = unsafe {
770            stackful::spawn(
771                tasks,
772                task,
773                "ABI poller",
774                stackful::Stack::new(64 * 1024),
775                move || {
776                    let mut entry = PollEntry {
777                        handle: file.cast(),
778                        kind: XILA_POLL_FILE,
779                        events: XILA_POLL_IN,
780                        revents: 0,
781                    };
782                    let mut ready = 0;
783                    let status = xila_poll_wait(&mut entry, 1, 1000, &mut ready);
784                    i32::from(status != Status::Ok || ready != 1 || entry.revents != XILA_POLL_IN)
785                },
786            )
787            .await
788            .unwrap()
789        };
790        let (peer, _) = tasks
791            .spawn(
792                task,
793                "device readiness",
794                Some(spawner),
795                move |_| async move {
796                    while state.polls.load(Ordering::Relaxed) == 0
797                        || !state.readiness_seen.load(Ordering::Relaxed)
798                    {
799                        task::yield_now().await;
800                    }
801                    assert_eq!(state.polls.load(Ordering::Relaxed), 1);
802                    state.ready.store(true, Ordering::Relaxed);
803                    notify_readiness();
804                    state.waker.lock().unwrap().take().unwrap().wake();
805                },
806            )
807            .await
808            .unwrap();
809
810        assert_eq!(reader.join().await, 0);
811        assert_eq!(poller.join().await, 0);
812        peer.join().await;
813        assert_eq!(unsafe { xila_file_close(file) }, Status::Ok);
814        assert_eq!(state.polls.load(Ordering::Relaxed), 2);
815        assert_eq!(state.control_polls.load(Ordering::Relaxed), 2);
816    }
817    #[cfg(all(
818        target_os = "linux",
819        any(target_arch = "x86_64", target_arch = "aarch64")
820    ))]
821    #[task::test]
822    async fn fallback_poll_yields_to_input_producer() {
823        use core::task::{Context, Poll};
824        use file_system::{DirectBaseOperations, DirectCharacterDevice, MountOperations, Size};
825        use portable_atomic::{AtomicUsize, Ordering};
826
827        struct Input(&'static AtomicUsize);
828        impl DirectBaseOperations for Input {
829            fn read(
830                &self,
831                _: &mut Context<'_>,
832                buffer: &mut [u8],
833                _: Size,
834            ) -> Poll<file_system::Result<usize>> {
835                if self.0.load(Ordering::Relaxed) == 2 {
836                    buffer[0] = b'x';
837                    Poll::Ready(Ok(1))
838                } else {
839                    self.0.store(1, Ordering::Relaxed);
840                    Poll::Pending
841                }
842            }
843
844            fn write(
845                &self,
846                _: &mut Context<'_>,
847                _: &[u8],
848                _: Size,
849            ) -> Poll<file_system::Result<usize>> {
850                Poll::Ready(Err(file_system::IoErrorKind::Unsupported))
851            }
852        }
853        impl MountOperations for Input {}
854        impl DirectCharacterDevice for Input {}
855
856        let tasks = task::test_manager();
857        let parent = tasks.get_current_task_identifier().await;
858        let spawner = tasks.get_spawner(parent).await.unwrap();
859        let users = Box::leak(Box::new(users::Manager::new()));
860        let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
861        let device = file_system::MemoryDevice::<512>::new_static(128 * 1024);
862        let fs = little_fs::FileSystem::new_format(device, little_fs::Options::new(128)).unwrap();
863        let vfs = Box::leak(Box::new(virtual_file_system::VirtualFileSystem::new(
864            tasks, users, time, fs,
865        )));
866        let input: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
867        vfs.mount_character_device(parent, "/input", Input(input))
868            .await
869            .unwrap();
870        let root = Directory::new(vfs, parent, "/", XILA_RIGHT_READ).unwrap();
871        let mut file = ptr::null_mut();
872        let path = c"input";
873        assert_eq!(
874            unsafe {
875                xila_file_open(
876                    &root,
877                    path.as_ptr(),
878                    path.count_bytes(),
879                    XILA_OPEN_READ | XILA_OPEN_NON_BLOCKING,
880                    &mut file,
881                )
882            },
883            Status::Ok
884        );
885
886        for timeout in [-1, 0] {
887            input.store(0, Ordering::Relaxed);
888            let (producer, _) = tasks
889                .spawn(
890                    parent,
891                    "input producer",
892                    Some(spawner),
893                    move |_| async move {
894                        while input.load(Ordering::Relaxed) == 0 {
895                            task::yield_now().await;
896                        }
897                        input.store(2, Ordering::Relaxed);
898                    },
899                )
900                .await
901                .unwrap();
902            // SAFETY: The bounded ABI call chain fits on the stack. The file
903            // remains live and this reader is its only user.
904            let (reader, _) = unsafe {
905                stackful::spawn(
906                    tasks,
907                    parent,
908                    "fallback poll reader",
909                    stackful::Stack::new(64 * 1024),
910                    move || {
911                        let mut entry = PollEntry {
912                            handle: file.cast(),
913                            kind: XILA_POLL_FILE,
914                            events: XILA_POLL_IN,
915                            revents: 0,
916                        };
917                        // Bound retries so starvation fails the test without hanging.
918                        for _ in 0..32 {
919                            let mut ready = 0;
920                            if xila_poll_wait(&mut entry, 1, timeout, &mut ready) != Status::Ok
921                                || ready != 1
922                                || entry.revents != XILA_POLL_IN
923                            {
924                                return 1;
925                            }
926                            let mut byte = 0u8;
927                            let mut count = 0;
928                            match xila_file_read(file, (&mut byte as *mut u8).cast(), 1, &mut count)
929                            {
930                                Status::WouldBlock => {}
931                                Status::Ok if count == 1 && byte == b'x' => return 0,
932                                _ => return 2,
933                            }
934                        }
935                        3
936                    },
937                )
938                .await
939                .unwrap()
940            };
941
942            assert_eq!(reader.join().await, 0, "fallback poll timeout {timeout}");
943            producer.join().await;
944        }
945        assert_eq!(unsafe { xila_file_close(file) }, Status::Ok);
946    }
947
948    #[cfg(all(
949        target_os = "linux",
950        any(target_arch = "x86_64", target_arch = "aarch64")
951    ))]
952    #[task::test]
953    async fn process_exit_cancels_suspended_pipe_poll() {
954        use core::{cell::Cell, ffi::c_void};
955        use file_system::{StateFlags, notify_readiness, readiness_waiter_count};
956
957        std::thread_local! {
958            static READER: Cell<*mut File> = const { Cell::new(ptr::null_mut()) };
959        }
960
961        unsafe extern "C" fn wait_for_input(file: *mut c_void) -> *mut c_void {
962            let mut entry = PollEntry {
963                handle: file,
964                kind: XILA_POLL_FILE,
965                events: XILA_POLL_IN,
966                revents: 0,
967            };
968            let mut ready = 0;
969            unsafe { xila_poll_wait(&mut entry, 1, -1, &mut ready) };
970            panic!("poll resumed after process shutdown");
971        }
972
973        unsafe extern "C" fn run(startup: *const XilaStartup) -> i32 {
974            let process = unsafe { (*startup).process };
975            let mut worker = 0;
976            unsafe {
977                assert_eq!(
978                    xila_thread_spawn(
979                        process,
980                        0,
981                        Some(wait_for_input),
982                        READER.get().cast(),
983                        &mut worker
984                    ),
985                    Status::Ok
986                );
987                assert_eq!(xila_thread_yield(), Status::Ok);
988                assert_eq!(readiness_waiter_count(), 1);
989                assert_eq!(xila_thread_stop_others(process), Status::Ok);
990                xila_process_exit(process, 37);
991            }
992            panic!("process exit returned");
993        }
994
995        let tasks = task::test_manager();
996        let users = Box::leak(Box::new(users::Manager::new()));
997        let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
998        let device = file_system::MemoryDevice::<512>::new_static(128 * 1024);
999        let fs = little_fs::FileSystem::new_format(device, little_fs::Options::new(128)).unwrap();
1000        let vfs = Box::leak(Box::new(virtual_file_system::VirtualFileSystem::new(
1001            tasks, users, time, fs,
1002        )));
1003        let host = Box::leak(Box::new(TestHost { tasks, vfs }));
1004        let (reader, writer) = vfs
1005            .create_unnamed_pipe(XILA_PIPE_CAPACITY, StateFlags::empty())
1006            .await
1007            .unwrap();
1008        let reader = File::new(reader.into_synchronous_file()).into_raw();
1009        READER.set(reader);
1010        let launch = ProcessLaunch {
1011            host,
1012            environment: None,
1013            home: None,
1014            network: 0,
1015        };
1016        let (state, heap) = run_state(Vec::new(), None, None, None);
1017        // The bounded probe fits the stack and leaves the pipe endpoints owned
1018        // by the test so their close notifications cannot clear the hub first.
1019        let coroutine = unsafe {
1020            stackful::Coroutine::new(stackful::Stack::new(64 * 1024), move || {
1021                launch.run(state, run, heap)
1022            })
1023        };
1024        assert_eq!(readiness_waiter_count(), 0);
1025        assert_eq!(drive_process(coroutine).await, 37);
1026        assert_eq!(readiness_waiter_count(), 0);
1027        assert_eq!(notify_readiness(), 0);
1028
1029        READER.set(ptr::null_mut());
1030        assert_eq!(unsafe { xila_file_close(reader) }, Status::Ok);
1031        writer.close(vfs).await.unwrap();
1032    }
1033
1034    #[cfg(all(
1035        target_os = "linux",
1036        any(target_arch = "x86_64", target_arch = "aarch64")
1037    ))]
1038    #[task::test]
1039    async fn stackful_sleep_and_random_yield_to_executor_peer() {
1040        use portable_atomic::{AtomicBool, AtomicUsize, Ordering};
1041
1042        install_entropy().await;
1043        let tasks = task::test_manager();
1044        let task = tasks.get_current_task_identifier().await;
1045        let spawner = tasks.get_spawner(task).await.unwrap();
1046        let finished: &'static AtomicBool = Box::leak(Box::new(AtomicBool::new(false)));
1047        let peer_turns: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
1048
1049        // SAFETY: The bounded ABI call chain fits within the supplied stack.
1050        let (sleeper, _) = unsafe {
1051            stackful::spawn(
1052                tasks,
1053                task,
1054                "ABI sleeper",
1055                stackful::Stack::new(64 * 1024),
1056                move || {
1057                    let start = ::time::MonotonicClock::now(&::time::EmbassyClock);
1058                    let slept = xila_time_sleep(20_000_000);
1059                    let elapsed = ::time::MonotonicClock::now(&::time::EmbassyClock) - start;
1060                    // The entropy source is pending on alternate reads, so this fill
1061                    // suspends the coroutine as well.
1062                    let mut buffer = [0u8; 8];
1063                    let filled = xila_random_fill(buffer.as_mut_ptr().cast(), buffer.len());
1064                    finished.store(true, Ordering::Relaxed);
1065                    i32::from(
1066                        slept != Status::Ok
1067                            || elapsed < core::time::Duration::from_millis(20)
1068                            || filled != Status::Ok
1069                            || buffer != [0xA5; 8],
1070                    )
1071                },
1072            )
1073            .await
1074            .unwrap()
1075        };
1076        // Runs on the same executor, so it only progresses while the sleeper is suspended.
1077        let (peer, _) = tasks
1078            .spawn(task, "sleep peer", Some(spawner), move |_| async move {
1079                while !finished.load(Ordering::Relaxed) {
1080                    peer_turns.fetch_add(1, Ordering::Relaxed);
1081                    task::yield_now().await;
1082                }
1083            })
1084            .await
1085            .unwrap();
1086        assert_eq!(sleeper.join().await, 0);
1087        peer.join().await;
1088        assert!(peer_turns.load(Ordering::Relaxed) > 1);
1089    }
1090
1091    #[cfg(all(
1092        target_os = "linux",
1093        any(target_arch = "x86_64", target_arch = "aarch64")
1094    ))]
1095    #[task::test]
1096    async fn stackful_sleep_forever_does_not_return() {
1097        use core::{future::poll_fn, pin::pin, task::Poll};
1098        use portable_atomic::{AtomicBool, Ordering};
1099
1100        static RETURNED: AtomicBool = AtomicBool::new(false);
1101        let tasks = task::test_manager();
1102        let task = tasks.get_current_task_identifier().await;
1103        let spawner = tasks.get_spawner(task).await.unwrap();
1104        // The task races the coroutine against a timer and then drops it, so
1105        // the test ends with no task left behind.
1106        let (watcher, _) = tasks
1107            .spawn(
1108                task,
1109                "forever sleeper",
1110                Some(spawner),
1111                move |_| async move {
1112                    // SAFETY: The bounded ABI call chain fits within the supplied stack.
1113                    let coroutine = unsafe {
1114                        stackful::Coroutine::new(stackful::Stack::new(64 * 1024), || {
1115                            let status = xila_time_sleep(u64::MAX);
1116                            RETURNED.store(true, Ordering::Relaxed);
1117                            i32::from(status != Status::Ok)
1118                        })
1119                    };
1120                    let mut sleeper = pin!(stackful::drive(coroutine));
1121                    let mut limit = pin!(task::sleep(core::time::Duration::from_millis(50)));
1122                    poll_fn(|context| {
1123                        if sleeper.as_mut().poll(context).is_ready() {
1124                            return Poll::Ready(true);
1125                        }
1126                        limit.as_mut().poll(context).map(|()| false)
1127                    })
1128                    .await
1129                },
1130            )
1131            .await
1132            .unwrap();
1133        assert!(!watcher.join().await, "sleep(u64::MAX) returned");
1134        assert!(!RETURNED.load(Ordering::Relaxed));
1135    }
1136
1137    #[cfg(all(
1138        target_os = "linux",
1139        any(target_arch = "x86_64", target_arch = "aarch64")
1140    ))]
1141    #[task::test]
1142    async fn stackful_processes_spawn_wait_exit_and_inherit_environment() {
1143        use file_system::{AccessFlags, CreateFlags, Flags, Path, PathOwned};
1144        use virtual_file_system::SynchronousFile;
1145
1146        let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
1147        let tasks = task::test_manager();
1148        let users = Box::leak(Box::new(users::Manager::new()));
1149        let task = tasks.get_current_task_identifier().await;
1150        let device = file_system::MemoryDevice::<512>::new_static(1024 * 512);
1151        let fs = little_fs::FileSystem::new_format(device, little_fs::Options::new(256)).unwrap();
1152        let vfs = Box::leak(Box::new(
1153            virtual_file_system::initialize(tasks, users, time, fs).unwrap(),
1154        ));
1155        virtual_file_system::create_default_hierarchy(vfs, task)
1156            .await
1157            .unwrap();
1158        let host: &'static TestHost = Box::leak(Box::new(TestHost { tasks, vfs }));
1159        let open = || {
1160            File::new(
1161                SynchronousFile::open(
1162                    vfs,
1163                    task,
1164                    Path::from_str("/process-output"),
1165                    Flags::new(AccessFlags::READ_WRITE, Some(CreateFlags::Create), None),
1166                )
1167                .unwrap(),
1168            )
1169        };
1170        let launch = ProcessLaunch {
1171            host,
1172            environment: Some(vec![task::EnvironmentVariable::new("SHARED", "parent")]),
1173            home: Some(HomeGrant {
1174                path: PathOwned::new("/".into()).unwrap(),
1175                rights: 3,
1176            }),
1177            network: 0,
1178        };
1179        let (input, output, error) = (open(), open(), open());
1180        let (state, heap) = run_state(Vec::new(), Some(input), Some(output), Some(error));
1181        // SAFETY: the bounded C parent fits the stack and never unwinds.
1182        let (parent, _) = unsafe {
1183            stackful::spawn_with_result(
1184                tasks,
1185                task,
1186                "process parent",
1187                stackful::Stack::new(128 * 1024),
1188                move || launch.run(state, process_parent_main, heap),
1189                |status| status as isize,
1190            )
1191            .await
1192            .unwrap()
1193        };
1194        // A nonzero status is the line of the failed check in process.c.
1195        assert_eq!(parent.join().await, 0);
1196
1197        let launch = ProcessLaunch {
1198            host,
1199            environment: None,
1200            home: None,
1201            network: 0,
1202        };
1203        let (state, heap) = run_state(Vec::new(), None, None, None);
1204        let (thread_test, _) = unsafe {
1205            stackful::spawn_with_driver(
1206                tasks,
1207                task,
1208                "thread test",
1209                stackful::Stack::new(64 * 1024),
1210                move || launch.run(state, threads_main, heap),
1211                drive_process,
1212                core::convert::identity,
1213            )
1214            .await
1215            .unwrap()
1216        };
1217        assert_eq!(thread_test.join().await, 0, "failed check in threads.c");
1218
1219        // The exiting child's stream was closed (flushed) by exit, and the child's home
1220        // capability created a file under the root.
1221        let mut written = [0u8; 3];
1222        let mut file = SynchronousFile::open(
1223            vfs,
1224            task,
1225            Path::from_str("/exit-output"),
1226            AccessFlags::Read.into(),
1227        )
1228        .unwrap();
1229        assert_eq!(file.read(&mut written).unwrap(), 3);
1230        assert_eq!(&written, b"bye");
1231        vfs.get_statistics_for_task(task, &Path::from_str("/child-home"))
1232            .await
1233            .unwrap();
1234    }
1235
1236    std::thread_local! {
1237        /// Start and length of the host state under test.
1238        static HOST_STATE: core::cell::Cell<(usize, usize)> = const { core::cell::Cell::new((0, 0)) };
1239    }
1240
1241    /// Whether `address` lies in the host state, not on the calling coroutine's stack.
1242    fn in_host_state(address: usize) -> bool {
1243        let (start, length) = HOST_STATE.get();
1244        (start..start + length).contains(&address)
1245    }
1246
1247    /// The line of the first failed check, so a failure names it.
1248    macro_rules! check {
1249        ($condition:expr) => {
1250            if !$condition {
1251                return line!() as i32;
1252            }
1253        };
1254    }
1255
1256    /// The streams `write(2)` and the SDK reach, and the exit path, are in the host state.
1257    unsafe fn streams_in_host_state(startup: *const XilaStartup) -> i32 {
1258        let startup = unsafe { &*startup };
1259        check!(in_host_state(startup as *const XilaStartup as usize));
1260        check!(in_host_state(startup.process as usize));
1261        check!(in_host_state(startup.standard_input as usize));
1262        check!(in_host_state(startup.standard_output as usize));
1263        check!(in_host_state(startup.standard_error as usize));
1264        check!(in_host_state(ptr::from_ref(&startup.program_name) as usize));
1265        check!(startup.program_name.length == b"streams".len());
1266        check!(!startup.program_name.data.is_null());
1267        check!(
1268            unsafe {
1269                core::slice::from_raw_parts(
1270                    startup.program_name.data.cast::<u8>(),
1271                    startup.program_name.length,
1272                )
1273            } == b"streams"
1274        );
1275        0
1276    }
1277
1278    unsafe extern "C" fn streams_return_entry(startup: *const XilaStartup) -> i32 {
1279        let failed = unsafe { streams_in_host_state(startup) };
1280        if failed != 0 { failed } else { 6 }
1281    }
1282
1283    unsafe extern "C" fn streams_exit_entry(startup: *const XilaStartup) -> i32 {
1284        let failed = unsafe { streams_in_host_state(startup) };
1285        if failed != 0 {
1286            return failed;
1287        }
1288        let startup = unsafe { &*startup };
1289        let api = unsafe { &*startup.api };
1290        let _ = unsafe { (api.process_exit)(startup.process, 7) };
1291        1 // Exit returned.
1292    }
1293
1294    /// The standard streams of a process live in the host state the loader owns, not in
1295    /// the coroutine's frames, whether the entry returns or exits early (#766).
1296    #[cfg(all(
1297        target_os = "linux",
1298        any(target_arch = "x86_64", target_arch = "aarch64")
1299    ))]
1300    #[task::test]
1301    async fn standard_streams_stay_off_the_coroutine_stack() {
1302        use file_system::StateFlags;
1303
1304        let tasks = task::test_manager();
1305        let task = tasks.get_current_task_identifier().await;
1306        let users = Box::leak(Box::new(users::Manager::new()));
1307        let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
1308        let device = file_system::MemoryDevice::<512>::new_static(128 * 1024);
1309        let fs = little_fs::FileSystem::new_format(device, little_fs::Options::new(128)).unwrap();
1310        let vfs = Box::leak(Box::new(virtual_file_system::VirtualFileSystem::new(
1311            tasks, users, time, fs,
1312        )));
1313        let host = Box::leak(Box::new(TestHost { tasks, vfs }));
1314        for (entry, expected) in [
1315            (
1316                streams_return_entry as unsafe extern "C" fn(*const XilaStartup) -> i32,
1317                6,
1318            ),
1319            (streams_exit_entry, 7),
1320        ] {
1321            let (input, kept_input) = vfs
1322                .create_unnamed_pipe(XILA_PIPE_CAPACITY, StateFlags::empty())
1323                .await
1324                .unwrap();
1325            let (kept_output, output) = vfs
1326                .create_unnamed_pipe(XILA_PIPE_CAPACITY, StateFlags::empty())
1327                .await
1328                .unwrap();
1329            let (kept_error, error) = vfs
1330                .create_unnamed_pipe(XILA_PIPE_CAPACITY, StateFlags::empty())
1331                .await
1332                .unwrap();
1333            let stream = |file: virtual_file_system::File<'static>| {
1334                Some(File::new(file.into_synchronous_file()))
1335            };
1336            let (state, heap) = run_state(Vec::new(), stream(input), stream(output), stream(error));
1337            HOST_STATE.set((state.as_ptr() as usize, core::mem::size_of::<HostState>()));
1338            let launch = ProcessLaunch {
1339                host,
1340                environment: None,
1341                home: None,
1342                network: 0,
1343            };
1344            // SAFETY: the bounded entries fit the stack and never unwind, and the closure
1345            // holds only pointers to the state and heap, which are leaked.
1346            let (handle, _) = unsafe {
1347                stackful::spawn_with_driver(
1348                    tasks,
1349                    task,
1350                    "streams",
1351                    stackful::Stack::new(64 * 1024),
1352                    move || launch.run(state, entry, heap),
1353                    drive_process,
1354                    |status| status as isize,
1355                )
1356                .await
1357                .unwrap()
1358            };
1359            assert_eq!(handle.join().await, expected, "line of the failed check");
1360            for kept in [kept_input, kept_output, kept_error] {
1361                kept.close(vfs).await.unwrap();
1362            }
1363        }
1364    }
1365
1366    /// A native process that is cancelled while it is suspended: the executor drops its
1367    /// task, the coroutine's frames are discarded without running anything on them, and the
1368    /// host releases what the process held from its own state (#731).
1369    #[cfg(all(
1370        target_os = "linux",
1371        any(target_arch = "x86_64", target_arch = "aarch64")
1372    ))]
1373    mod cancellation {
1374        use super::*;
1375        use core::{
1376            future::Future,
1377            pin::Pin,
1378            task::{Context as TaskContext, Poll},
1379        };
1380        use file_system::{AccessFlags, BaseOperations, CharacterDevice, MountOperations, Size};
1381        use virtual_file_system::{
1382            Directory as VfsDirectory, File as VfsFile, ItemStatic, VirtualFileSystem,
1383        };
1384
1385        /// A character device whose reads never finish. It is not zero-sized: the file system
1386        /// tells devices apart by address, which every box of a zero-sized type shares.
1387        struct Blocked(#[allow(dead_code)] u8);
1388        impl BaseOperations for Blocked {
1389            fn read(
1390                &self,
1391                _: &mut file_system::Context,
1392                _: &mut TaskContext<'_>,
1393                _: &mut [u8],
1394                _: Size,
1395            ) -> Poll<file_system::Result<usize>> {
1396                Poll::Pending
1397            }
1398
1399            fn write(
1400                &self,
1401                _: &mut file_system::Context,
1402                _: &mut TaskContext<'_>,
1403                _: &[u8],
1404                _: Size,
1405            ) -> Poll<file_system::Result<usize>> {
1406                Poll::Ready(Err(file_system::IoErrorKind::Unsupported))
1407            }
1408
1409            fn clone_context(
1410                &self,
1411                _: &file_system::Context,
1412            ) -> file_system::Result<file_system::Context> {
1413                Ok(file_system::Context::new_empty())
1414            }
1415        }
1416        impl MountOperations for Blocked {
1417            fn unmount(&self) -> file_system::Result<()> {
1418                Ok(())
1419            }
1420        }
1421        impl CharacterDevice for Blocked {}
1422
1423        type Entry = unsafe extern "C" fn(*const XilaStartup) -> i32;
1424
1425        struct World {
1426            task: task::TaskIdentifier,
1427            vfs: &'static VirtualFileSystem,
1428            host: &'static TestHost,
1429        }
1430
1431        /// A file system with two blocked devices, `/blocked` and `/device`, and a second
1432        /// file system at `/mnt`.
1433        async fn world() -> World {
1434            let tasks = task::test_manager();
1435            let task = tasks.get_current_task_identifier().await;
1436            let users = Box::leak(Box::new(users::Manager::new()));
1437            let time = Box::leak(Box::new(time::Manager::new(&testing::TimeDevice).unwrap()));
1438            let device = file_system::MemoryDevice::<512>::new_static(128 * 1024);
1439            let fs =
1440                little_fs::FileSystem::new_format(device, little_fs::Options::new(128)).unwrap();
1441            let vfs = Box::leak(Box::new(VirtualFileSystem::new(tasks, users, time, fs)));
1442            vfs.mount_character_device(task, "/blocked", Blocked(0))
1443                .await
1444                .unwrap();
1445            vfs.mount_character_device(task, "/device", Blocked(0))
1446                .await
1447                .unwrap();
1448            vfs.create_directory(task, &"/mnt").await.unwrap();
1449            let device = file_system::MemoryDevice::<512>::new_static(128 * 1024);
1450            let fs =
1451                little_fs::FileSystem::new_format(device, little_fs::Options::new(128)).unwrap();
1452            vfs.mount_file_system(fs, "/mnt", task).await.unwrap();
1453            let host = Box::leak(Box::new(TestHost { tasks, vfs }));
1454            World { task, vfs, host }
1455        }
1456
1457        /// One process, started the way the native loader starts one: its host state and
1458        /// heap are separate allocations, and the coroutine's entry holds only pointers to
1459        /// them. Dropping `driver` is the cancellation; the loader then releases the state.
1460        struct Run {
1461            state: NonNull<HostState>,
1462            heap: NonNull<Heap>,
1463            driver: Option<Pin<Box<dyn Future<Output = i32>>>>,
1464        }
1465
1466        impl Run {
1467            fn new(
1468                host: &'static TestHost,
1469                entry: Entry,
1470                standard_input: Option<File>,
1471                home: Option<HomeGrant>,
1472            ) -> Self {
1473                let (state, heap) = run_state(Vec::new(), standard_input, None, None);
1474                let launch = ProcessLaunch {
1475                    host,
1476                    environment: None,
1477                    home,
1478                    network: 0,
1479                };
1480                // SAFETY: the bounded entries fit the stack and never unwind, and the closure
1481                // holds only pointers to the state and heap, which `Run` frees last.
1482                let coroutine = unsafe {
1483                    stackful::Coroutine::new(stackful::Stack::new(64 * 1024), move || {
1484                        launch.run(state, entry, heap)
1485                    })
1486                };
1487                Self {
1488                    state,
1489                    heap,
1490                    driver: Some(Box::pin(drive_process(coroutine))),
1491                }
1492            }
1493
1494            /// Poll the process once, inside the calling task, as the process's own task
1495            /// would, so that it learns its identity from the real waker.
1496            async fn poll(&mut self) -> Poll<i32> {
1497                let driver = self.driver.as_mut().unwrap();
1498                core::future::poll_fn(|cx| Poll::Ready(driver.as_mut().poll(cx))).await
1499            }
1500
1501            fn open_handles(&self) -> usize {
1502                // SAFETY: the state is live until `Run` is dropped.
1503                unsafe { self.state.as_ref() }.open_handles()
1504            }
1505
1506            /// Drop the process's task future while it is suspended.
1507            fn cancel(&mut self) {
1508                self.driver = None;
1509            }
1510
1511            /// What the loader does once the coroutine is gone.
1512            fn release(&self) {
1513                // SAFETY: the coroutine is gone, or ran to its end.
1514                unsafe { HostState::release(self.state) };
1515            }
1516        }
1517
1518        impl Drop for Run {
1519            fn drop(&mut self) {
1520                self.driver = None;
1521                // SAFETY: both came from `Box::leak` in `run_state`, and nothing runs now.
1522                unsafe {
1523                    HostState::release(self.state);
1524                    drop(Box::from_raw(self.state.as_ptr()));
1525                    drop(Box::from_raw(self.heap.as_ptr()));
1526                }
1527            }
1528        }
1529
1530        fn home() -> Option<HomeGrant> {
1531            Some(HomeGrant {
1532                path: file_system::PathOwned::new("/".into()).unwrap(),
1533                rights: 3,
1534            })
1535        }
1536
1537        fn stream(file: VfsFile<'static>) -> Option<File> {
1538            Some(File::new(file.into_synchronous_file()))
1539        }
1540
1541        macro_rules! check {
1542            ($condition:expr) => {
1543                if !$condition {
1544                    return line!() as i32;
1545                }
1546            };
1547        }
1548
1549        /// Open every kind of handle the program can own without a network, then do what
1550        /// `finish` says.
1551        unsafe fn open_handles(startup: *const XilaStartup) -> i32 {
1552            let startup = unsafe { &*startup };
1553            let (mut file, mut directory, mut listing) =
1554                (ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
1555            let (mut reader, mut writer) = (ptr::null_mut(), ptr::null_mut());
1556            unsafe {
1557                check!(
1558                    xila_file_open(
1559                        startup.home,
1560                        c"device".as_ptr(),
1561                        6,
1562                        XILA_OPEN_READ,
1563                        &mut file
1564                    ) == Status::Ok
1565                );
1566                check!(
1567                    xila_directory_open(
1568                        startup.home,
1569                        c"mnt".as_ptr(),
1570                        3,
1571                        XILA_RIGHT_READ,
1572                        &mut directory
1573                    ) == Status::Ok
1574                );
1575                check!(
1576                    xila_directory_iterator_open(directory, c"".as_ptr(), 0, &mut listing)
1577                        == Status::Ok
1578                );
1579                check!(
1580                    xila_pipe_create(startup.process, 0, &mut reader, &mut writer) == Status::Ok
1581                );
1582            }
1583            0
1584        }
1585
1586        /// Opens its handles, then blocks reading its standard input.
1587        unsafe extern "C" fn open_then_block(startup: *const XilaStartup) -> i32 {
1588            let failed = unsafe { open_handles(startup) };
1589            if failed != 0 {
1590                return failed;
1591            }
1592            let (mut byte, mut count) = (0u8, 0);
1593            let _ = unsafe {
1594                xila_file_read(
1595                    (*startup).standard_input,
1596                    (&raw mut byte).cast(),
1597                    1,
1598                    &mut count,
1599                )
1600            };
1601            1 // The read never returns.
1602        }
1603
1604        /// Opens its handles and returns without closing them.
1605        unsafe extern "C" fn open_then_return(startup: *const XilaStartup) -> i32 {
1606            unsafe { open_handles(startup) }
1607        }
1608
1609        /// Opens its handles and exits without closing them.
1610        unsafe extern "C" fn open_then_exit(startup: *const XilaStartup) -> i32 {
1611            let failed = unsafe { open_handles(startup) };
1612            if failed != 0 {
1613                return failed;
1614            }
1615            let _ = unsafe { xila_process_exit((*startup).process, 5) };
1616            1 // Exit returned.
1617        }
1618
1619        /// A worker thread that opens a file and blocks reading it.
1620        unsafe extern "C" fn worker_opens_then_blocks(
1621            startup: *mut core::ffi::c_void,
1622        ) -> *mut core::ffi::c_void {
1623            let startup = unsafe { &*startup.cast::<XilaStartup>() };
1624            let mut file = ptr::null_mut();
1625            let opened = unsafe {
1626                xila_file_open(
1627                    startup.home,
1628                    c"device".as_ptr(),
1629                    6,
1630                    XILA_OPEN_READ,
1631                    &mut file,
1632                )
1633            };
1634            if opened != Status::Ok {
1635                return ptr::dangling_mut();
1636            }
1637            let (mut byte, mut count) = (0u8, 0);
1638            let _ = unsafe { xila_file_read(file, (&raw mut byte).cast(), 1, &mut count) };
1639            ptr::dangling_mut() // The read never returns.
1640        }
1641
1642        /// Starts a worker, lets it run, and blocks reading its standard input itself.
1643        unsafe extern "C" fn main_and_worker_block(startup: *const XilaStartup) -> i32 {
1644            let mut worker = 0;
1645            unsafe {
1646                check!(
1647                    xila_thread_spawn(
1648                        (*startup).process,
1649                        0,
1650                        Some(worker_opens_then_blocks),
1651                        startup.cast_mut().cast(),
1652                        &mut worker,
1653                    ) == Status::Ok
1654                );
1655                check!(xila_thread_yield() == Status::Ok);
1656                let (mut byte, mut count) = (0u8, 0);
1657                let _ = xila_file_read(
1658                    (*startup).standard_input,
1659                    (&raw mut byte).cast(),
1660                    1,
1661                    &mut count,
1662                );
1663            }
1664            1 // The read never returns.
1665        }
1666
1667        std::thread_local! {
1668            /// What `exercise` allocated inside the process: allocations and bytes.
1669            static MEASURED: core::cell::Cell<(usize, usize)> = const { core::cell::Cell::new((0, 0)) };
1670        }
1671
1672        /// Open and close one of each handle that needs no process capability, and report
1673        /// what that allocated. The calls are the same inside and outside a process: only
1674        /// inside one are the handles registered.
1675        unsafe fn exercise(home: *const Directory) -> (usize, usize) {
1676            let before = testing::MemoryManager::thread_allocations();
1677            let (mut file, mut directory, mut listing) =
1678                (ptr::null_mut(), ptr::null_mut(), ptr::null_mut());
1679            unsafe {
1680                assert_eq!(
1681                    xila_file_open(home, c"device".as_ptr(), 6, XILA_OPEN_READ, &mut file),
1682                    Status::Ok
1683                );
1684                assert_eq!(
1685                    xila_directory_open(home, c"mnt".as_ptr(), 3, XILA_RIGHT_READ, &mut directory),
1686                    Status::Ok
1687                );
1688                assert_eq!(
1689                    xila_directory_iterator_open(directory, c"".as_ptr(), 0, &mut listing),
1690                    Status::Ok
1691                );
1692                assert_eq!(xila_directory_iterator_close(listing), Status::Ok);
1693                assert_eq!(xila_directory_close(directory), Status::Ok);
1694                assert_eq!(xila_file_close(file), Status::Ok);
1695            }
1696            let delta = testing::MemoryManager::thread_allocations().since(before);
1697            assert_eq!(delta.net_bytes(), 0);
1698            (delta.allocations(), delta.allocated_bytes())
1699        }
1700
1701        unsafe extern "C" fn measure_in_process(startup: *const XilaStartup) -> i32 {
1702            // The first round settles anything the calls initialize once.
1703            unsafe { exercise((*startup).home) };
1704            MEASURED.set(unsafe { exercise((*startup).home) });
1705            0
1706        }
1707
1708        /// Blocks in a random fill that never finishes.
1709        unsafe extern "C" fn block_in_random_fill(_: *const XilaStartup) -> i32 {
1710            let mut bytes = [0u8; 19];
1711            let _ = unsafe { xila_random_fill(bytes.as_mut_ptr().cast(), bytes.len()) };
1712            1 // The fill never returns.
1713        }
1714
1715        async fn busy(vfs: &VirtualFileSystem, path: &str, when: &str) {
1716            assert!(
1717                vfs.unmount(path, false).await.is_err(),
1718                "{path} should still be in use {when}"
1719            );
1720        }
1721
1722        async fn unmounts(vfs: &VirtualFileSystem, path: &str, when: &str) {
1723            let result = vfs.unmount(path, false).await;
1724            assert!(
1725                result.is_ok(),
1726                "{path} should be free to unmount {when}: {result:?}"
1727            );
1728        }
1729
1730        /// The device handle a test keeps beside a process's: unmounting stays refused until
1731        /// the test closes it, which a process closing its own twice would break.
1732        async fn keep(world: &World, path: &str) -> VfsFile<'static> {
1733            VfsFile::open(world.vfs, world.task, path, AccessFlags::Read.into())
1734                .await
1735                .unwrap()
1736        }
1737
1738        #[task::test]
1739        async fn cancelled_process_releases_its_streams_and_handles() {
1740            let world = world().await;
1741            let World { vfs, task, .. } = world;
1742            let input = VfsFile::open(vfs, task, "/blocked", AccessFlags::Read.into())
1743                .await
1744                .unwrap();
1745            let mut run = Run::new(world.host, open_then_block, stream(input), home());
1746            // The process opens a file, a directory, a listing and a pipe, and blocks on a read
1747            // of its standard input.
1748            assert_eq!(run.poll().await, Poll::Pending);
1749            assert_eq!(run.open_handles(), 5, "file, directory, listing, pipe ends");
1750            for path in ["/blocked", "/device", "/mnt"] {
1751                busy(vfs, path, "(line 287)").await;
1752            }
1753
1754            // The test keeps one handle of each beside the process's.
1755            let kept_input = keep(&world, "/blocked").await;
1756            let kept_device = keep(&world, "/device").await;
1757            let kept_listing = VfsDirectory::open(vfs, task, "/mnt").await.unwrap();
1758
1759            run.cancel();
1760            run.release();
1761            assert_eq!(run.open_handles(), 0);
1762            // The process's handles are closed, and only once: the test's still hold each.
1763            for path in ["/blocked", "/device", "/mnt"] {
1764                busy(vfs, path, "(line 300)").await;
1765            }
1766            kept_input.close(vfs).await.unwrap();
1767            kept_device.close(vfs).await.unwrap();
1768            kept_listing.close(vfs).await.unwrap();
1769            for path in ["/blocked", "/device", "/mnt"] {
1770                unmounts(vfs, path, "(line 306)").await;
1771            }
1772            // Releasing again does nothing.
1773            run.release();
1774        }
1775
1776        #[task::test]
1777        async fn process_cancelled_before_its_first_poll_releases_its_streams() {
1778            let world = world().await;
1779            let World { vfs, task, .. } = world;
1780            let input = VfsFile::open(vfs, task, "/blocked", AccessFlags::Read.into())
1781                .await
1782                .unwrap();
1783            let mut run = Run::new(world.host, open_then_block, stream(input), home());
1784            let kept = keep(&world, "/blocked").await;
1785            busy(vfs, "/blocked", "(line 321)").await;
1786            // The coroutine never started: its entry is dropped unrun, with the launch request.
1787            run.cancel();
1788            assert_eq!(run.open_handles(), 0);
1789            run.release();
1790            busy(vfs, "/blocked", "(line 326)").await;
1791            kept.close(vfs).await.unwrap();
1792            unmounts(vfs, "/blocked", "(line 328)").await;
1793        }
1794
1795        #[task::test]
1796        async fn cancel_inside_a_random_fill_closes_the_entropy_source() {
1797            let world = world().await;
1798            let vfs = install_entropy().await;
1799            let source = "/devices/random/source";
1800            let mut run = Run::new(world.host, block_in_random_fill, None, None);
1801            assert_eq!(run.poll().await, Poll::Pending);
1802            // The fill holds the source open while it waits.
1803            busy(vfs, source, "(line 339)").await;
1804            let kept = VfsFile::open(vfs, world.task, source, AccessFlags::Read.into())
1805                .await
1806                .unwrap();
1807            run.cancel();
1808            run.release();
1809            // Closed once: only the test's own handle keeps it in use.
1810            busy(vfs, source, "(line 346)").await;
1811            kept.close(vfs).await.unwrap();
1812            unmounts(vfs, source, "(line 348)").await;
1813            // Put the shared device back for the other tests.
1814            vfs.mount_static(world.task, source, ItemStatic::CharacterDevice(&ENTROPY))
1815                .await
1816                .unwrap();
1817        }
1818
1819        /// The handles a worker thread opened belong to the process, so a cancellation closes
1820        /// them too, and the worker's stack goes with the main one.
1821        #[task::test]
1822        async fn cancel_closes_the_handles_of_worker_threads_and_frees_their_stacks() {
1823            let world = world().await;
1824            let World { vfs, task, .. } = world;
1825            let start = async || {
1826                let input = VfsFile::open(vfs, task, "/blocked", AccessFlags::Read.into())
1827                    .await
1828                    .unwrap();
1829                Run::new(world.host, main_and_worker_block, stream(input), home())
1830            };
1831            // The first round grows the task manager's retained pool.
1832            let mut warm = start().await;
1833            assert!(warm.poll().await.is_pending());
1834            warm.cancel();
1835            drop(warm);
1836
1837            let before = testing::MemoryManager::thread_allocations();
1838            let mut run = start().await;
1839            assert!(run.poll().await.is_pending());
1840            assert_eq!(run.open_handles(), 1, "the worker's file");
1841            let kept = keep(&world, "/device").await;
1842            busy(vfs, "/device", "while the worker holds its file").await;
1843            run.cancel();
1844            run.release();
1845            assert_eq!(run.open_handles(), 0);
1846            busy(vfs, "/device", "with only the test's handle open").await;
1847            drop(run);
1848            let delta = testing::MemoryManager::thread_allocations().since(before);
1849            kept.close(vfs).await.unwrap();
1850            assert_eq!(
1851                delta.net_bytes(),
1852                0,
1853                "both stacks and every handle are freed"
1854            );
1855            unmounts(vfs, "/device", "once the test's handle is closed").await;
1856        }
1857
1858        /// Registering a handle costs no allocation: the same calls allocate the same count and
1859        /// bytes inside a process, where the handles are registered, as outside one.
1860        #[task::test]
1861        async fn tracking_handles_allocates_nothing() {
1862            let world = world().await;
1863            let World { vfs, task, .. } = world;
1864            let mut run = Run::new(world.host, measure_in_process, None, home());
1865            assert_eq!(run.poll().await, Poll::Ready(0));
1866            drop(run);
1867            let inside = MEASURED.get();
1868
1869            let home = Directory::new(vfs, task, "/", XILA_RIGHT_READ | XILA_RIGHT_WRITE).unwrap();
1870            unsafe { exercise(&home) };
1871            let outside = unsafe { exercise(&home) };
1872            assert_eq!(inside, outside);
1873            assert!(inside.0 > 0, "the calls allocate their objects");
1874        }
1875
1876        /// A process that ends by returning or by exiting closes the handles it forgot, once.
1877        #[task::test]
1878        async fn handles_left_open_at_exit_are_closed_once() {
1879            for (entry, expected) in [(open_then_return as Entry, 0), (open_then_exit as Entry, 5)]
1880            {
1881                let world = world().await;
1882                let World { vfs, .. } = world;
1883                let mut run = Run::new(world.host, entry, None, home());
1884                let kept_device = keep(&world, "/device").await;
1885                let kept_listing = VfsDirectory::open(vfs, world.task, "/mnt").await.unwrap();
1886                assert_eq!(run.poll().await, Poll::Ready(expected));
1887                assert_eq!(run.open_handles(), 0);
1888                busy(vfs, "/device", "(line 373)").await;
1889                busy(vfs, "/mnt", "(line 374)").await;
1890                // Releasing a process that ended changes nothing.
1891                run.release();
1892                busy(vfs, "/device", "(line 377)").await;
1893                busy(vfs, "/mnt", "(line 378)").await;
1894                kept_device.close(vfs).await.unwrap();
1895                kept_listing.close(vfs).await.unwrap();
1896                unmounts(vfs, "/device", "(line 381)").await;
1897                unmounts(vfs, "/mnt", "(line 382)").await;
1898            }
1899        }
1900
1901        std::thread_local! {
1902            /// The file system whose namespace lock the lock holders below take, and the
1903            /// task that opens directories in it.
1904            static HELD: core::cell::Cell<Option<(&'static VirtualFileSystem, task::TaskIdentifier)>> =
1905                const { core::cell::Cell::new(None) };
1906        }
1907
1908        /// Suspend with the VFS namespace lock held, as a path call does while it waits for
1909        /// the task or user managers, until the thread is stopped.
1910        fn hold_namespace_lock() {
1911            let (vfs, _) = HELD.get().expect("set by the test");
1912            stackful::suspend_on_cancellable(
1913                vfs.hold_namespace_lock(core::future::pending::<()>()),
1914            );
1915        }
1916
1917        unsafe extern "C" fn worker_holds_lock(
1918            _: *mut core::ffi::c_void,
1919        ) -> *mut core::ffi::c_void {
1920            hold_namespace_lock();
1921            ptr::dangling_mut() // The hold never ends.
1922        }
1923
1924        /// Opens its handles, starts a worker that takes the namespace lock and lets it
1925        /// run, so that the lock is held when main ends.
1926        unsafe fn open_then_let_a_worker_hold_the_lock(startup: *const XilaStartup) -> i32 {
1927            let failed = unsafe { open_handles(startup) };
1928            if failed != 0 {
1929                return failed;
1930            }
1931            let mut worker = 0;
1932            unsafe {
1933                check!(
1934                    xila_thread_spawn(
1935                        (*startup).process,
1936                        0,
1937                        Some(worker_holds_lock),
1938                        ptr::null_mut(),
1939                        &mut worker,
1940                    ) == Status::Ok
1941                );
1942                check!(xila_thread_yield() == Status::Ok);
1943            }
1944            0
1945        }
1946
1947        unsafe extern "C" fn return_while_a_worker_holds_the_lock(
1948            startup: *const XilaStartup,
1949        ) -> i32 {
1950            unsafe { open_then_let_a_worker_hold_the_lock(startup) }
1951        }
1952
1953        unsafe extern "C" fn exit_while_a_worker_holds_the_lock(
1954            startup: *const XilaStartup,
1955        ) -> i32 {
1956            let failed = unsafe { open_then_let_a_worker_hold_the_lock(startup) };
1957            if failed != 0 {
1958                return failed;
1959            }
1960            let _ = unsafe { xila_process_exit((*startup).process, 5) };
1961            1 // Exit returned.
1962        }
1963
1964        unsafe extern "C" fn worker_exits(
1965            startup: *mut core::ffi::c_void,
1966        ) -> *mut core::ffi::c_void {
1967            let startup = startup.cast::<XilaStartup>();
1968            let _ = unsafe { xila_process_exit((*startup).process, 7) };
1969            ptr::dangling_mut() // Exit returned.
1970        }
1971
1972        /// Opens its handles, starts a worker that exits the process, and takes the
1973        /// namespace lock itself before the worker runs.
1974        unsafe extern "C" fn worker_exits_while_main_holds_the_lock(
1975            startup: *const XilaStartup,
1976        ) -> i32 {
1977            let failed = unsafe { open_handles(startup) };
1978            if failed != 0 {
1979                return failed;
1980            }
1981            let mut worker = 0;
1982            unsafe {
1983                check!(
1984                    xila_thread_spawn(
1985                        (*startup).process,
1986                        0,
1987                        Some(worker_exits),
1988                        startup.cast_mut().cast(),
1989                        &mut worker,
1990                    ) == Status::Ok
1991                );
1992            }
1993            hold_namespace_lock();
1994            1 // The hold never ends.
1995        }
1996
1997        /// A process that ends while another of its threads is suspended with the VFS
1998        /// namespace lock held stops that thread, which gives the lock back, before it
1999        /// closes what it holds: closing its listing and directory needs that lock.
2000        #[task::test]
2001        async fn ending_does_not_wait_for_a_lock_a_stopped_thread_held() {
2002            for (entry, expected, how) in [
2003                (
2004                    return_while_a_worker_holds_the_lock as Entry,
2005                    0,
2006                    "main returns",
2007                ),
2008                (exit_while_a_worker_holds_the_lock as Entry, 5, "main exits"),
2009                (
2010                    worker_exits_while_main_holds_the_lock as Entry,
2011                    7,
2012                    "a worker exits",
2013                ),
2014            ] {
2015                let world = world().await;
2016                let World { vfs, .. } = world;
2017                HELD.set(Some((vfs, world.task)));
2018                let mut run = Run::new(world.host, entry, None, home());
2019                let mut ended = Poll::Pending;
2020                for _ in 0..100 {
2021                    ended = run.poll().await;
2022                    if ended.is_ready() {
2023                        break;
2024                    }
2025                }
2026                assert_eq!(ended, Poll::Ready(expected), "{how}: the process must end");
2027                assert_eq!(run.open_handles(), 0, "{how}");
2028                // The lock is free and the process's handles are closed.
2029                unmounts(vfs, "/mnt", how).await;
2030                drop(run);
2031            }
2032        }
2033
2034        /// A worker whose cancellable wait owns an open directory, as a directory open does
2035        /// between its open and its close.
2036        unsafe extern "C" fn worker_holds_a_directory(
2037            _: *mut core::ffi::c_void,
2038        ) -> *mut core::ffi::c_void {
2039            let (vfs, task) = HELD.get().expect("set by the test");
2040            stackful::suspend_on_cancellable(async move {
2041                let directory = VfsDirectory::open(vfs, task, "/mnt").await;
2042                core::future::pending::<()>().await;
2043                drop(directory);
2044            });
2045            ptr::dangling_mut() // The wait never ends.
2046        }
2047
2048        /// Starts that worker, lets it open its directory, and returns.
2049        unsafe extern "C" fn return_while_a_worker_holds_a_directory(
2050            startup: *const XilaStartup,
2051        ) -> i32 {
2052            let mut worker = 0;
2053            unsafe {
2054                check!(
2055                    xila_thread_spawn(
2056                        (*startup).process,
2057                        0,
2058                        Some(worker_holds_a_directory),
2059                        ptr::null_mut(),
2060                        &mut worker,
2061                    ) == Status::Ok
2062                );
2063                check!(xila_thread_yield() == Status::Ok);
2064            }
2065            0
2066        }
2067
2068        /// Stopping a worker drops its wait, and so closes the directory the wait owns,
2069        /// without suspending the thread that ends the process, even while another task
2070        /// holds the namespace lock the close counts the directory under. The process ends
2071        /// under that lock, so no cancellation can catch its cleanup halfway; the directory
2072        /// is given back once, when the lock is next taken, and the worker's coroutine is
2073        /// freed with the process.
2074        #[task::test]
2075        async fn a_stopped_peer_closes_its_directory_while_the_lock_is_held() {
2076            let world = world().await;
2077            let World { vfs, task, .. } = world;
2078            HELD.set(Some((vfs, task)));
2079            let run_once = async || {
2080                let mut run = Run::new(
2081                    world.host,
2082                    return_while_a_worker_holds_a_directory,
2083                    None,
2084                    home(),
2085                );
2086                // The worker opens its directory, then main returns while the test holds
2087                // the namespace lock, which closing that directory would wait for.
2088                let mut ended = run.poll().await;
2089                if ended.is_pending() {
2090                    ended = vfs
2091                        .hold_namespace_lock(async {
2092                            let mut ended = Poll::Pending;
2093                            for _ in 0..100 {
2094                                ended = run.poll().await;
2095                                if ended.is_ready() {
2096                                    break;
2097                                }
2098                            }
2099                            ended
2100                        })
2101                        .await;
2102                }
2103                // What a host does with a process that has not ended: cancel it.
2104                if ended.is_pending() {
2105                    run.cancel();
2106                }
2107                drop(run);
2108                // A close takes the lock and gives back what was owed.
2109                VfsDirectory::open(vfs, task, "/")
2110                    .await
2111                    .unwrap()
2112                    .close(vfs)
2113                    .await
2114                    .unwrap();
2115                ended
2116            };
2117            // The first round grows the task manager's retained pool.
2118            assert_eq!(run_once().await, Poll::Ready(0));
2119            let before = testing::MemoryManager::thread_allocations();
2120            let ended = run_once().await;
2121            let delta = testing::MemoryManager::thread_allocations().since(before);
2122            assert_eq!(
2123                ended,
2124                Poll::Ready(0),
2125                "the process ends under the held lock"
2126            );
2127            assert_eq!(
2128                delta.net_bytes(),
2129                0,
2130                "the worker's coroutine and the owed reference are freed"
2131            );
2132            unmounts(
2133                vfs,
2134                "/mnt",
2135                "once every directory the worker opened is closed",
2136            )
2137            .await;
2138        }
2139
2140        /// Every way a process can end, cancellation included, gives back every byte it took:
2141        /// its stack, its state, its handles and its streams.
2142        #[task::test]
2143        async fn every_ending_returns_all_memory() {
2144            let world = world().await;
2145            let World { vfs, task, .. } = world;
2146            for _ in 0..2 {
2147                // The first rounds grow the task manager's retained pool.
2148                for entry in [open_then_return, open_then_exit] {
2149                    let mut run = Run::new(world.host, entry, None, home());
2150                    assert!(run.poll().await.is_ready());
2151                }
2152                let input = VfsFile::open(vfs, task, "/blocked", AccessFlags::Read.into())
2153                    .await
2154                    .unwrap();
2155                let mut run = Run::new(world.host, open_then_block, stream(input), home());
2156                assert!(run.poll().await.is_pending());
2157                run.cancel();
2158            }
2159            let mut counts = Vec::new();
2160            for entry in [open_then_return, open_then_exit] {
2161                let before = testing::MemoryManager::thread_allocations();
2162                let mut run = Run::new(world.host, entry, None, home());
2163                assert!(run.poll().await.is_ready());
2164                drop(run);
2165                let delta = testing::MemoryManager::thread_allocations().since(before);
2166                assert_eq!(delta.net_bytes(), 0, "a process that ends leaves nothing");
2167                counts.push(delta.allocations());
2168            }
2169            let before = testing::MemoryManager::thread_allocations();
2170            let input = VfsFile::open(vfs, task, "/blocked", AccessFlags::Read.into())
2171                .await
2172                .unwrap();
2173            let mut run = Run::new(world.host, open_then_block, stream(input), home());
2174            assert!(run.poll().await.is_pending());
2175            run.cancel();
2176            drop(run);
2177            let delta = testing::MemoryManager::thread_allocations().since(before);
2178            assert_eq!(
2179                delta.net_bytes(),
2180                0,
2181                "a cancelled process leaves nothing, its stack included"
2182            );
2183            // Returning and exiting allocate the same: tracking handles costs no allocation.
2184            assert_eq!(counts[0], counts[1]);
2185        }
2186    }
2187}