1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
// This file is part of yash, an extended POSIX shell.
// Copyright (C) 2021 WATANABE Yuki
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

//! This crate defines the shell execution environment.
//!
//! A shell execution environment, [`Env`], is a collection of data that may
//! affect or be affected by the execution of commands. The environment consists
//! of application-managed parts and system-managed parts. Application-managed
//! parts are implemented in pure Rust in this crate. Many application-managed
//! parts like [function]s and [variable]s can be manipulated independently of
//! interactions with the underlying system. System-managed parts, on the other
//! hand, depend on the underlying system. Attributes like the working directory
//! and umask are managed by the system to be accessed only by interaction with
//! the system interface.
//!
//! The [`System`] trait is the interface to the system-managed parts.
//! [`RealSystem`] provides an implementation for `System` that interacts with
//! the underlying system. [`VirtualSystem`] is a dummy for simulating the
//! system's behavior without affecting the actual system.

use self::builtin::getopts::GetoptsState;
use self::builtin::Builtin;
use self::function::FunctionSet;
use self::io::Fd;
use self::job::JobList;
use self::job::Pid;
use self::job::ProcessState;
use self::option::On;
use self::option::OptionSet;
use self::option::{AllExport, ErrExit, Interactive, Monitor};
use self::semantics::Divert;
use self::semantics::ExitStatus;
use self::stack::Frame;
use self::stack::Stack;
pub use self::system::r#virtual::VirtualSystem;
pub use self::system::real::RealSystem;
use self::system::Errno;
pub use self::system::SharedSystem;
use self::system::SignalHandling;
pub use self::system::System;
use self::system::SystemEx;
use self::trap::TrapSet;
use self::variable::Scope;
use self::variable::VariableRefMut;
use self::variable::VariableSet;
use self::variable::PPID;
use futures_util::task::noop_waker_ref;
use std::collections::HashMap;
use std::fmt::Debug;
use std::future::Future;
use std::ops::ControlFlow::{self, Break, Continue};
use std::rc::Rc;
use std::task::Context;
use std::task::Poll;
use yash_syntax::alias::AliasSet;

/// Whole shell execution environment.
///
/// The shell execution environment consists of application-managed parts and
/// system-managed parts. Application-managed parts are directly implemented in
/// the `Env` instance. System-managed parts are managed by a [`SharedSystem`]
/// that contains an instance of [`System`].
///
/// # Cloning
///
/// `Env::clone` effectively clones the application-managed parts of the
/// environment. Since [`SharedSystem`] is reference-counted, you will not get a
/// deep copy of the system-managed parts. See also
/// [`clone_with_system`](Self::clone_with_system).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Env {
    /// Aliases defined in the environment
    pub aliases: AliasSet,

    /// Name of the current shell executable or shell script
    ///
    /// Special parameter `0` expands to this value.
    pub arg0: String,

    /// Built-in utilities available in the environment
    pub builtins: HashMap<&'static str, Builtin>,

    /// Exit status of the last executed command
    pub exit_status: ExitStatus,

    /// Functions defined in the environment
    pub functions: FunctionSet,

    /// State of the previous invocation of the `getopts` built-in
    pub getopts_state: Option<GetoptsState>,

    /// Jobs managed in the environment
    pub jobs: JobList,

    /// Process group ID of the main shell process
    pub main_pgid: Pid,

    /// Process ID of the main shell process
    ///
    /// This PID represents the value of the `$` special parameter.
    pub main_pid: Pid,

    /// Shell option settings
    pub options: OptionSet,

    /// Runtime execution context stack
    pub stack: Stack,

    /// Traps defined in the environment
    pub traps: TrapSet,

    /// File descriptor to the controlling terminal
    ///
    /// [`get_tty`](Self::get_tty) saves a file descriptor in this variable, so
    /// you don't have to prepare it yourself.
    pub tty: Option<Fd>,

    /// Variables and positional parameters defined in the environment
    pub variables: VariableSet,

    /// Interface to the system-managed parts of the environment
    pub system: SharedSystem,
}

impl Env {
    /// Creates a new environment with the given system.
    ///
    /// Members of the new environments are default-constructed except that:
    /// - `main_pid` is initialized as `system.getpid()`
    /// - `system` is initialized as `SharedSystem::new(system)`
    #[must_use]
    pub fn with_system(system: Box<dyn System>) -> Env {
        Env {
            aliases: Default::default(),
            arg0: Default::default(),
            builtins: Default::default(),
            exit_status: Default::default(),
            functions: Default::default(),
            getopts_state: Default::default(),
            jobs: Default::default(),
            main_pgid: system.getpgrp(),
            main_pid: system.getpid(),
            options: Default::default(),
            stack: Default::default(),
            traps: Default::default(),
            tty: Default::default(),
            variables: Default::default(),
            system: SharedSystem::new(system),
        }
    }

    /// Creates a new environment with a default-constructed [`VirtualSystem`].
    #[must_use]
    pub fn new_virtual() -> Env {
        Env::with_system(Box::<VirtualSystem>::default())
    }

    /// Clones this environment.
    ///
    /// The application-managed parts of the environment are cloned normally.
    /// The system-managed parts are replaced with the provided `System`
    /// instance.
    #[must_use]
    pub fn clone_with_system(&self, system: Box<dyn System>) -> Env {
        Env {
            aliases: self.aliases.clone(),
            arg0: self.arg0.clone(),
            builtins: self.builtins.clone(),
            exit_status: self.exit_status,
            functions: self.functions.clone(),
            getopts_state: self.getopts_state.clone(),
            jobs: self.jobs.clone(),
            main_pgid: self.main_pgid,
            main_pid: self.main_pid,
            options: self.options,
            stack: self.stack.clone(),
            traps: self.traps.clone(),
            tty: self.tty,
            variables: self.variables.clone(),
            system: SharedSystem::new(system),
        }
    }

    /// Initializes default variables.
    ///
    /// This function assigns the following variables to `self`:
    ///
    /// - `IFS=' \t\n'`
    /// - `OPTIND=1`
    /// - `PS1='$ '`
    /// - `PS2='> '`
    /// - `PS4='+ '`
    /// - `PPID=(parent process ID)`
    /// - `PWD=(current working directory)` (See [`Env::prepare_pwd`])
    ///
    /// This function ignores any errors that may occur.
    ///
    /// TODO: PS1 should be set to `"# "` for root users.
    pub fn init_variables(&mut self) {
        self.variables.init();

        self.variables
            .get_or_new(PPID, Scope::Global)
            .assign(self.system.getppid().to_string(), None)
            .ok();

        self.prepare_pwd().ok();
    }

    /// Waits for some signals to be caught in the current process.
    ///
    /// Returns an array of signals caught.
    ///
    /// This function is a wrapper for [`SharedSystem::wait_for_signals`].
    /// Before the function returns, it passes the results to
    /// [`TrapSet::catch_signal`] so the trap set can remember the signals
    /// caught to be handled later.
    pub async fn wait_for_signals(&mut self) -> Rc<[signal::Number]> {
        let result = self.system.wait_for_signals().await;
        for signal in result.iter().copied() {
            self.traps.catch_signal(signal);
        }
        result
    }

    /// Waits for a specific signal to be caught in the current process.
    ///
    /// This function calls [`wait_for_signals`](Self::wait_for_signals)
    /// repeatedly until it returns results containing the specified `signal`.
    pub async fn wait_for_signal(&mut self, signal: signal::Number) {
        while !self.wait_for_signals().await.contains(&signal) {}
    }

    /// Returns signals that have been caught.
    ///
    /// This function is similar to
    /// [`wait_for_signals`](Self::wait_for_signals) but does not wait for
    /// signals to be caught. Instead, it only checks if any signals have been
    /// caught but not yet consumed in the [`SharedSystem`].
    pub fn poll_signals(&mut self) -> Option<Rc<[signal::Number]>> {
        let system = self.system.clone();

        let mut future = std::pin::pin!(self.wait_for_signals());

        let mut context = Context::from_waker(noop_waker_ref());
        if let Poll::Ready(signals) = future.as_mut().poll(&mut context) {
            return Some(signals);
        }

        system.select(true).ok();
        if let Poll::Ready(signals) = future.poll(&mut context) {
            return Some(signals);
        }
        None
    }

    /// Whether error messages should be printed in color
    ///
    /// This function decides whether messages printed to the standard error
    /// should contain ANSI color escape sequences. The result is true only if
    /// the standard error is a terminal.
    ///
    /// The current implementaion simply checks if the standard error is a
    /// terminal. This will be changed in the future to support user
    /// configuration.
    #[must_use]
    fn should_print_error_in_color(&self) -> bool {
        // TODO Enable color depending on user config (force/auto/never)
        // TODO Check if the terminal really supports color (needs terminfo)
        self.system.isatty(Fd::STDERR) == Ok(true)
    }

    /// Returns a file descriptor to the controlling terminal.
    ///
    /// This function returns `self.tty` if it is `Some` FD. Otherwise, it
    /// opens `/dev/tty` and saves the new FD to `self.tty` before returning it.
    pub fn get_tty(&mut self) -> Result<Fd, Errno> {
        if let Some(fd) = self.tty {
            return Ok(fd);
        }

        let first_fd = self.system.open(
            c"/dev/tty",
            crate::system::OFlag::O_RDWR | crate::system::OFlag::O_CLOEXEC,
            crate::system::Mode::empty(),
        )?;
        let final_fd = self.system.move_fd_internal(first_fd);
        self.tty = final_fd.ok();
        final_fd
    }

    /// Tests whether the current environment is an interactive shell.
    ///
    /// This function returns true if and only if:
    ///
    /// - the [`Interactive`] option is `On` in `self.options`, and
    /// - the current context is not in a subshell (no `Frame::Subshell` in `self.stack`).
    #[must_use]
    pub fn is_interactive(&self) -> bool {
        self.options.get(Interactive) == On && !self.stack.contains(&Frame::Subshell)
    }

    /// Tests whether the shell is performing job control.
    ///
    /// This function returns true if and only if:
    ///
    /// - the [`Monitor`] option is `On` in `self.options`, and
    /// - the current context is not in a subshell (no `Frame::Subshell` in `self.stack`).
    #[must_use]
    pub fn controls_jobs(&self) -> bool {
        self.options.get(Monitor) == On && !self.stack.contains(&Frame::Subshell)
    }

    /// Waits for a subshell to terminate, suspend, or resume.
    ///
    /// This function waits for a subshell to change its execution state. The
    /// `target` parameter specifies which child to wait for:
    ///
    /// - `-1`: any child
    /// - `0`: any child in the same process group as the current process
    /// - `pid`: the child whose process ID is `pid`
    /// - `-pgid`: any child in the process group whose process group ID is `pgid`
    ///
    /// When [`self.system.wait`](System::wait) returned a new state of the
    /// target, it is sent to `self.jobs` ([`JobList::update_status`]) before
    /// being returned from this function.
    ///
    /// If there is no matching target, this function returns
    /// `Err(Errno::ECHILD)`.
    ///
    /// If the target subshell is not job-controlled, you may want to use
    /// [`wait_for_subshell_to_finish`](Self::wait_for_subshell_to_finish)
    /// instead.
    pub async fn wait_for_subshell(&mut self, target: Pid) -> Result<(Pid, ProcessState), Errno> {
        // We need to set the signal handling before calling `wait` so we don't
        // miss any `SIGCHLD` that may arrive between `wait` and `wait_for_signal`.
        self.traps.enable_sigchld_handler(&mut self.system)?;

        let sigchld = self
            .system
            .signal_number_from_name(signal::Name::Chld)
            .unwrap();
        loop {
            if let Some((pid, state)) = self.system.wait(target)? {
                self.jobs.update_status(pid, state);
                return Ok((pid, state));
            }
            self.wait_for_signal(sigchld).await;
        }
    }

    /// Wait for a subshell to terminate.
    ///
    /// This function is similar to
    /// [`wait_for_subshell`](Self::wait_for_subshell), but returns only when
    /// the target is finished (either exited or killed by a signal).
    ///
    /// Returns the process ID of the awaited process and its exit status.
    pub async fn wait_for_subshell_to_finish(
        &mut self,
        target: Pid,
    ) -> Result<(Pid, ExitStatus), Errno> {
        loop {
            let (pid, state) = self.wait_for_subshell(target).await?;
            if let Ok(exit_status) = state.try_into() {
                if !state.is_alive() {
                    return Ok((pid, exit_status));
                }
            }
        }
    }

    /// Applies all job status updates to jobs in `self.jobs`.
    ///
    /// This function calls [`self.system.wait`](System::wait) repeatedly until
    /// all status updates available are applied to `self.jobs`
    /// ([`JobList::update_status`]).
    ///
    /// Note that updates of subshells that are not managed in `self.jobs` are
    /// lost when you call this function.
    pub fn update_all_subshell_statuses(&mut self) {
        while let Ok(Some((pid, state))) = self.system.wait(Pid::ALL) {
            self.jobs.update_status(pid, state);
        }
    }

    /// Get an existing variable or create a new one.
    ///
    /// This method is a thin wrapper around [`VariableSet::get_or_new`].
    /// If the [`AllExport`] option is on, the variable is
    /// [exported](VariableRefMut::export) before being returned from the
    /// method.
    ///
    /// You should prefer using this method over [`VariableSet::get_or_new`] to
    /// make sure that the [`AllExport`] option is applied.
    pub fn get_or_create_variable<S>(&mut self, name: S, scope: Scope) -> VariableRefMut
    where
        S: Into<String>,
    {
        let mut variable = self.variables.get_or_new(name, scope);
        if self.options.get(AllExport) == On {
            variable.export(true);
        }
        variable
    }

    /// Tests whether the [`ErrExit`] option is applicable in the current context.
    ///
    /// This function returns true if and only if:
    /// - the [`ErrExit`] option is on, and
    /// - the current stack has no [`Condition`] frame.
    ///
    /// [`Condition`]: Frame::Condition
    pub fn errexit_is_applicable(&self) -> bool {
        self.options.get(ErrExit) == On && !self.stack.contains(&Frame::Condition)
    }

    /// Returns a `Divert` if the shell should exit because of the [`ErrExit`]
    /// shell option.
    ///
    /// The function returns `Break(Divert::Exit(None))` if the [`errexit`
    /// option is applicable](Self::errexit_is_applicable) and the current
    /// `self.exit_status` is non-zero. Otherwise, it returns `Continue(())`.
    pub fn apply_errexit(&self) -> ControlFlow<Divert> {
        if !self.exit_status.is_successful() && self.errexit_is_applicable() {
            Break(Divert::Exit(None))
        } else {
            Continue(())
        }
    }

    /// Updates the exit status from the given result.
    ///
    /// If `result` is a `Break(divert)` where `divert.exit_status()` is `Some`
    /// exit status, this function sets `self.exit_status` to that exit status.
    pub fn apply_result(&mut self, result: crate::semantics::Result) {
        match result {
            Continue(_) => {}
            Break(divert) => {
                if let Some(exit_status) = divert.exit_status() {
                    self.exit_status = exit_status;
                }
            }
        }
    }
}

mod alias;
pub mod builtin;
pub mod function;
pub mod input;
pub mod io;
pub mod job;
pub mod option;
pub mod pwd;
pub mod semantics;
pub mod signal;
pub mod stack;
pub mod subshell;
pub mod system;
pub mod trap;
pub mod variable;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::io::MIN_INTERNAL_FD;
    use crate::job::Job;
    use crate::subshell::Subshell;
    use crate::system::r#virtual::FileBody;
    use crate::system::r#virtual::INode;
    use crate::system::r#virtual::SystemState;
    use crate::system::r#virtual::SIGCHLD;
    use crate::trap::Action;
    use assert_matches::assert_matches;
    use futures_executor::LocalPool;
    use futures_util::task::LocalSpawnExt as _;
    use futures_util::FutureExt as _;
    use std::cell::RefCell;
    use std::str::from_utf8;
    use yash_syntax::source::Location;

    /// Helper function to perform a test in a virtual system with an executor.
    pub fn in_virtual_system<F, Fut, T>(f: F) -> T
    where
        F: FnOnce(Env, Rc<RefCell<SystemState>>) -> Fut,
        Fut: Future<Output = T> + 'static,
        T: 'static,
    {
        let system = VirtualSystem::new();
        let state = Rc::clone(&system.state);
        let mut executor = futures_executor::LocalPool::new();
        state.borrow_mut().executor = Some(Rc::new(executor.spawner()));

        let env = Env::with_system(Box::new(system));
        let shared_system = env.system.clone();
        let task = f(env, Rc::clone(&state));
        let mut task = executor.spawner().spawn_local_with_handle(task).unwrap();
        loop {
            if let Some(result) = (&mut task).now_or_never() {
                return result;
            }
            executor.run_until_stalled();
            shared_system.select(false).unwrap();
            SystemState::select_all(&state);
        }
    }

    /// Helper function for asserting on the content of /dev/stderr.
    pub fn assert_stderr<F, T>(state: &RefCell<SystemState>, f: F) -> T
    where
        F: FnOnce(&str) -> T,
    {
        let stderr = state.borrow().file_system.get("/dev/stderr").unwrap();
        let stderr = stderr.borrow();
        assert_matches!(&stderr.body, FileBody::Regular { content, .. } => {
            f(from_utf8(content).unwrap())
        })
    }

    #[test]
    fn wait_for_signal_remembers_signal_in_trap_set() {
        in_virtual_system(|mut env, state| async move {
            env.traps
                .set_action(
                    &mut env.system,
                    SIGCHLD,
                    Action::Command("".into()),
                    Location::dummy(""),
                    false,
                )
                .unwrap();
            {
                let mut state = state.borrow_mut();
                let process = state.processes.get_mut(&env.main_pid).unwrap();
                assert!(process.blocked_signals().contains(&SIGCHLD));
                let _ = process.raise_signal(SIGCHLD);
            }
            env.wait_for_signal(SIGCHLD).await;

            let trap_state = env.traps.get_state(SIGCHLD).0.unwrap();
            assert!(trap_state.pending);
        })
    }

    fn poll_signals_env() -> (Env, VirtualSystem) {
        let system = VirtualSystem::new();
        let shared_system = SharedSystem::new(Box::new(system.clone()));
        let mut env = Env::with_system(Box::new(shared_system));
        env.traps
            .set_action(
                &mut env.system,
                SIGCHLD,
                Action::Command("".into()),
                Location::dummy(""),
                false,
            )
            .unwrap();
        (env, system)
    }

    #[test]
    fn poll_signals_none() {
        let mut env = poll_signals_env().0;
        let result = env.poll_signals();
        assert_eq!(result, None);
    }

    #[test]
    fn poll_signals_some() {
        let (mut env, system) = poll_signals_env();
        {
            let mut state = system.state.borrow_mut();
            let process = state.processes.get_mut(&system.process_id).unwrap();
            assert!(process.blocked_signals().contains(&SIGCHLD));
            let _ = process.raise_signal(SIGCHLD);
        }

        let result = env.poll_signals().unwrap();
        assert_eq!(*result, [SIGCHLD]);
    }

    #[test]
    fn get_tty_opens_tty() {
        let system = VirtualSystem::new();
        let tty = Rc::new(RefCell::new(INode::new([])));
        system
            .state
            .borrow_mut()
            .file_system
            .save("/dev/tty", Rc::clone(&tty))
            .unwrap();
        let mut env = Env::with_system(Box::new(system.clone()));

        let fd = env.get_tty().unwrap();
        assert!(
            fd >= MIN_INTERNAL_FD,
            "get_tty returned {fd}, which should be >= {MIN_INTERNAL_FD}"
        );
        system
            .with_open_file_description(fd, |ofd| {
                assert!(Rc::ptr_eq(&ofd.file, &tty));
                Ok(())
            })
            .unwrap();

        system.state.borrow_mut().file_system = Default::default();

        // get_tty returns cached FD
        let fd = env.get_tty().unwrap();
        system
            .with_open_file_description(fd, |ofd| {
                assert!(Rc::ptr_eq(&ofd.file, &tty));
                Ok(())
            })
            .unwrap();
    }

    #[test]
    fn start_and_wait_for_subshell() {
        in_virtual_system(|mut env, _state| async move {
            let subshell = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(42) })
            });
            let (pid, _) = subshell.start(&mut env).await.unwrap();
            let result = env.wait_for_subshell(pid).await;
            assert_eq!(result, Ok((pid, ProcessState::exited(42))));
        });
    }

    #[test]
    fn start_and_wait_for_subshell_with_job_list() {
        in_virtual_system(|mut env, _state| async move {
            let subshell = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(42) })
            });
            let (pid, _) = subshell.start(&mut env).await.unwrap();
            let mut job = Job::new(pid);
            job.name = "my job".to_string();
            let job_index = env.jobs.add(job.clone());
            let result = env.wait_for_subshell(pid).await;
            assert_eq!(result, Ok((pid, ProcessState::exited(42))));
            job.state = ProcessState::exited(42);
            assert_eq!(env.jobs[job_index], job);
        });
    }

    #[test]
    fn wait_for_subshell_no_subshell() {
        let system = VirtualSystem::new();
        let mut executor = LocalPool::new();
        system.state.borrow_mut().executor = Some(Rc::new(executor.spawner()));
        let mut env = Env::with_system(Box::new(system));
        executor.run_until(async move {
            let result = env.wait_for_subshell(Pid::ALL).await;
            assert_eq!(result, Err(Errno::ECHILD));
        });
    }

    #[test]
    fn update_all_subshell_statuses_without_subshells() {
        let mut env = Env::new_virtual();
        env.update_all_subshell_statuses();
    }

    #[test]
    fn update_all_subshell_statuses_with_subshells() {
        let system = VirtualSystem::new();
        let mut executor = futures_executor::LocalPool::new();
        system.state.borrow_mut().executor = Some(Rc::new(executor.spawner()));

        let mut env = Env::with_system(Box::new(system));

        let [job_1, job_2, job_3] = executor.run_until(async {
            // Run a subshell.
            let subshell_1 = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(12) })
            });
            let (pid_1, _) = subshell_1.start(&mut env).await.unwrap();

            // Run another subshell.
            let subshell_2 = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(35) })
            });
            let (pid_2, _) = subshell_2.start(&mut env).await.unwrap();

            // This one will never finish.
            let subshell_3 =
                Subshell::new(|_env, _job_control| Box::pin(futures_util::future::pending()));
            let (pid_3, _) = subshell_3.start(&mut env).await.unwrap();

            // Yet another subshell. We don't make this into a job.
            let subshell_4 = Subshell::new(|env, _job_control| {
                Box::pin(async { env.exit_status = ExitStatus(100) })
            });
            let (_pid_4, _) = subshell_4.start(&mut env).await.unwrap();

            // Create jobs.
            let job_1 = env.jobs.add(Job::new(pid_1));
            let job_2 = env.jobs.add(Job::new(pid_2));
            let job_3 = env.jobs.add(Job::new(pid_3));
            [job_1, job_2, job_3]
        });

        // Let the jobs (except job_3) finish.
        executor.run_until_stalled();

        // We're not yet updated.
        assert_eq!(env.jobs[job_1].state, ProcessState::Running);
        assert_eq!(env.jobs[job_2].state, ProcessState::Running);
        assert_eq!(env.jobs[job_3].state, ProcessState::Running);

        env.update_all_subshell_statuses();

        // Now we have the results.
        // TODO assert_eq!(env.jobs[job_1].state, ProcessState::Exited(ExitStatus(12)));
        // TODO assert_eq!(env.jobs[job_2].state, ProcessState::Exited(ExitStatus(35)));
        assert_eq!(env.jobs[job_3].state, ProcessState::Running);
    }

    #[test]
    fn get_or_create_variable_with_all_export_off() {
        let mut env = Env::new_virtual();
        let mut a = env.get_or_create_variable("a", Scope::Global);
        assert!(!a.is_exported);
        a.export(true);
        let a = env.get_or_create_variable("a", Scope::Global);
        assert!(a.is_exported);
    }

    #[test]
    fn get_or_create_variable_with_all_export_on() {
        let mut env = Env::new_virtual();
        env.options.set(AllExport, On);
        let mut a = env.get_or_create_variable("a", Scope::Global);
        assert!(a.is_exported);
        a.export(false);
        let a = env.get_or_create_variable("a", Scope::Global);
        assert!(a.is_exported);
    }

    #[test]
    fn errexit_on() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus::FAILURE;
        env.options.set(ErrExit, On);
        assert_eq!(env.apply_errexit(), Break(Divert::Exit(None)));
    }

    #[test]
    fn errexit_with_zero_exit_status() {
        let mut env = Env::new_virtual();
        env.options.set(ErrExit, On);
        assert_eq!(env.apply_errexit(), Continue(()));
    }

    #[test]
    fn errexit_in_condition() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus::FAILURE;
        env.options.set(ErrExit, On);
        let env = env.push_frame(Frame::Condition);
        assert_eq!(env.apply_errexit(), Continue(()));
    }

    #[test]
    fn errexit_off() {
        let mut env = Env::new_virtual();
        env.exit_status = ExitStatus::FAILURE;
        assert_eq!(env.apply_errexit(), Continue(()));
    }

    #[test]
    fn apply_result_with_continue() {
        let mut env = Env::new_virtual();
        env.apply_result(Continue(()));
        assert_eq!(env.exit_status, ExitStatus::default());
    }

    #[test]
    fn apply_result_with_divert_without_exit_status() {
        let mut env = Env::new_virtual();
        env.apply_result(Break(Divert::Exit(None)));
        assert_eq!(env.exit_status, ExitStatus::default());
    }

    #[test]
    fn apply_result_with_divert_with_exit_status() {
        let mut env = Env::new_virtual();
        env.apply_result(Break(Divert::Exit(Some(ExitStatus(67)))));
        assert_eq!(env.exit_status, ExitStatus(67));
    }
}