yash_env/
trap.rs

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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
// 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/>.

//! Signal and other event handling settings.
//!
//! The trap is a mechanism of the shell that allows you to configure event
//! handlers for specific situations. A [`TrapSet`] is a mapping from [`Condition`]s to
//! [`Action`]s. When the mapping is modified, it updates the corresponding signal
//! disposition in the underlying system through a [`SignalSystem`] implementor.
//! Methods of `TrapSet` expect they are passed the same system instance in
//! every call to keep it in a correct state.
//!
//! `TrapSet` manages two types of signal handling configurations. One is
//! user-defined traps, which the user explicitly configures with the trap
//! built-in. The other is internal dispositions, which the shell implicitly
//! installs to the system to implement additional actions it needs to perform.
//! `TrapSet` merges the two configurations into a single [`Disposition`] for
//! each signal and sets it to the system.
//!
//! No signal disposition is involved for conditions other than signals, and the
//! trap set serves only as a storage for action settings.

mod cond;
mod state;

pub use self::cond::Condition;
pub use self::state::{Action, SetActionError, TrapState};
use self::state::{EnterSubshellOption, GrandState};
use crate::signal;
use crate::system::{Disposition, Errno};
#[cfg(doc)]
use crate::system::{SharedSystem, System};
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use yash_syntax::source::Location;

/// System interface for signal handling configuration
pub trait SignalSystem {
    /// Returns the name of a signal from its number.
    #[must_use]
    fn signal_name_from_number(&self, number: signal::Number) -> signal::Name;

    /// Returns the signal number from its name.
    ///
    /// This function returns the signal number corresponding to the signal name
    /// in the system. If the signal name is not supported, it returns `None`.
    ///
    /// Note that the `TrapSet` implementation assumes that the system supports
    /// all the following signals:
    ///
    /// - `SIGCHLD`
    /// - `SIGINT`
    /// - `SIGTERM`
    /// - `SIGQUIT`
    /// - `SIGTSTP`
    /// - `SIGTTIN`
    /// - `SIGTTOU`
    ///
    /// If this method returns `None` for any of these signals, `TrapSet` will
    /// panic.
    #[must_use]
    fn signal_number_from_name(&self, name: signal::Name) -> Option<signal::Number>;

    /// Sets how a signal is handled.
    ///
    /// This function updates the signal blocking mask and the disposition for
    /// the specified signal, and returns the previous disposition.
    fn set_disposition(
        &mut self,
        signal: signal::Number,
        disposition: Disposition,
    ) -> Result<Disposition, Errno>;
}

/// Iterator of trap actions configured in a [trap set](TrapSet).
///
/// [`TrapSet::iter`] returns this type of iterator.
#[must_use]
pub struct Iter<'a> {
    inner: std::collections::btree_map::Iter<'a, Condition, GrandState>,
}

impl<'a> Iterator for Iter<'a> {
    type Item = (&'a Condition, Option<&'a TrapState>, Option<&'a TrapState>);

    fn next(&mut self) -> Option<(&'a Condition, Option<&'a TrapState>, Option<&'a TrapState>)> {
        loop {
            let (cond, state) = self.inner.next()?;
            let (current, parent) = state.get_state();
            if current.is_some() || parent.is_some() {
                return Some((cond, current, parent));
            }
        }
    }
}

/// Collection of event handling settings.
///
/// See the [module documentation](self) for details.
#[derive(Clone, Debug, Default)]
pub struct TrapSet {
    traps: BTreeMap<Condition, GrandState>,
}

impl TrapSet {
    /// Returns the current state for a condition.
    ///
    /// This function returns a pair of optional trap states. The first is the
    /// currently configured trap action, and the second is the action set
    /// before [`enter_subshell`](Self::enter_subshell) was called.
    ///
    /// This function does not reflect the initial signal actions the shell
    /// inherited on startup.
    pub fn get_state<C: Into<Condition>>(
        &self,
        cond: C,
    ) -> (Option<&TrapState>, Option<&TrapState>) {
        self.get_state_impl(cond.into())
    }

    fn get_state_impl(&self, cond: Condition) -> (Option<&TrapState>, Option<&TrapState>) {
        match self.traps.get(&cond) {
            None => (None, None),
            Some(state) => state.get_state(),
        }
    }

    /// Sets a trap action for a condition.
    ///
    /// If the condition is a signal, this function installs a signal handler to
    /// the specified underlying system.
    ///
    /// If `override_ignore` is `false`, you cannot set a trap for a signal that
    /// has been ignored since the shell startup. An interactive shell should
    /// set `override_ignore` to `true` to bypass this restriction.
    ///
    /// You can never set a trap for `SIGKILL` or `SIGSTOP`.
    ///
    /// `origin` should be the location of the command performing this trap
    /// update. It is only informative: It does not affect the signal handling
    /// behavior and can be referenced later by [`get_state`](Self::get_state).
    ///
    /// This function clears all parent states remembered when [entering a
    /// subshell](Self::enter_subshell), not only for the specified condition
    /// but also for all other conditions.
    pub fn set_action<S: SignalSystem, C: Into<Condition>>(
        &mut self,
        system: &mut S,
        cond: C,
        action: Action,
        origin: Location,
        override_ignore: bool,
    ) -> Result<(), SetActionError> {
        self.set_action_impl(system, cond.into(), action, origin, override_ignore)
    }

    fn set_action_impl<S: SignalSystem>(
        &mut self,
        system: &mut S,
        cond: Condition,
        action: Action,
        origin: Location,
        override_ignore: bool,
    ) -> Result<(), SetActionError> {
        if let Condition::Signal(number) = cond {
            match system.signal_name_from_number(number) {
                signal::Name::Kill => return Err(SetActionError::SIGKILL),
                signal::Name::Stop => return Err(SetActionError::SIGSTOP),
                _ => {}
            }
        }

        self.clear_parent_settings();

        let entry = self.traps.entry(cond);
        GrandState::set_action(system, entry, action, origin, override_ignore)
    }

    fn clear_parent_settings(&mut self) {
        for state in self.traps.values_mut() {
            state.clear_parent_setting();
        }
    }

    /// Returns an iterator over the signal actions configured in this trap set.
    ///
    /// The iterator yields tuples of the signal, the currently configured trap
    /// action, and the action set before
    /// [`enter_subshell`](Self::enter_subshell) was called.
    #[inline]
    pub fn iter(&self) -> Iter<'_> {
        let inner = self.traps.iter();
        Iter { inner }
    }

    /// Updates signal dispositions on entering a subshell.
    ///
    /// ## Resetting non-ignore traps
    ///
    /// POSIX requires that traps other than `Action::Ignore` be reset when
    /// entering a subshell. This function achieves that effect.
    ///
    /// The trap set will remember the original trap states as the parent
    /// states. You can get them from the second return value of
    /// [`get_state`](Self::get_state) or the third item of tuples yielded by an
    /// [iterator](Self::iter).
    ///
    /// Note that trap actions other than `Trap::Command` remain as before.
    ///
    /// ## Clearing internal dispositions
    ///
    /// Internal dispositions that have been installed are cleared except for
    /// the SIGCHLD signal.
    ///
    /// ## Ignoring SIGINT and SIGQUIT
    ///
    /// If `ignore_sigint_sigquit` is true, this function sets the dispositions
    /// for SIGINT and SIGQUIT to `Ignore`.
    ///
    /// ## Ignoring SIGTSTP, SIGTTIN, and SIGTTOU
    ///
    /// If `keep_internal_dispositions_for_stoppers` is true and the internal
    /// dispositions have been [enabled for SIGTSTP, SIGTTIN, and
    /// SIGTTOU](Self::enable_internal_dispositions_for_stoppers), this function
    /// leaves the dispositions for those signals set to `Ignore`.
    ///
    /// ## Errors
    ///
    /// This function ignores any errors that may occur when setting signal
    /// dispositions.
    pub fn enter_subshell<S: SignalSystem>(
        &mut self,
        system: &mut S,
        ignore_sigint_sigquit: bool,
        keep_internal_dispositions_for_stoppers: bool,
    ) {
        self.clear_parent_settings();

        for (&cond, state) in &mut self.traps {
            let option = match cond {
                Condition::Exit => EnterSubshellOption::ClearInternalDisposition,
                Condition::Signal(number) => {
                    use signal::Name::*;
                    match system.signal_name_from_number(number) {
                        Chld => EnterSubshellOption::KeepInternalDisposition,
                        Int | Quit if ignore_sigint_sigquit => EnterSubshellOption::Ignore,
                        Tstp | Ttin | Ttou
                            if keep_internal_dispositions_for_stoppers
                                && state.internal_disposition() != Disposition::Default =>
                        {
                            EnterSubshellOption::Ignore
                        }
                        _ => EnterSubshellOption::ClearInternalDisposition,
                    }
                }
            };
            _ = state.enter_subshell(system, cond, option);
        }

        if ignore_sigint_sigquit {
            for name in [signal::Name::Int, signal::Name::Quit] {
                let number = system
                    .signal_number_from_name(name)
                    .unwrap_or_else(|| panic!("missing support for signal {name}"));
                match self.traps.entry(Condition::Signal(number)) {
                    Entry::Vacant(vacant) => _ = GrandState::ignore(system, vacant),
                    // If the entry is occupied, the signal is already ignored in the loop above.
                    Entry::Occupied(_) => {}
                }
            }
        }
    }

    /// Sets the `pending` flag of the [`TrapState`] for the specified signal.
    ///
    /// This function does nothing if no trap action has been
    /// [set](Self::set_action) for the signal.
    pub fn catch_signal(&mut self, signal: signal::Number) {
        if let Some(state) = self.traps.get_mut(&Condition::Signal(signal)) {
            state.mark_as_caught();
        }
    }

    /// Resets the `pending` flag of the [`TrapState`] for the specified signal.
    ///
    /// Returns the [`TrapState`] if the flag was set.
    pub fn take_signal_if_caught(&mut self, signal: signal::Number) -> Option<&TrapState> {
        self.traps
            .get_mut(&signal.into())
            .and_then(|state| state.handle_if_caught())
    }

    /// Returns a signal that has been [caught](Self::catch_signal).
    ///
    /// This function clears the `pending` flag of the [`TrapState`] for the
    /// specified signal.
    ///
    /// If there is more than one caught signal, it is unspecified which one of
    /// them is returned. If there is no caught signal, `None` is returned.
    pub fn take_caught_signal(&mut self) -> Option<(signal::Number, &TrapState)> {
        self.traps.iter_mut().find_map(|(&cond, state)| match cond {
            Condition::Signal(signal) => state.handle_if_caught().map(|trap| (signal, trap)),
            _ => None,
        })
    }

    fn set_internal_disposition<S: SignalSystem>(
        &mut self,
        signal: signal::Name,
        disposition: Disposition,
        system: &mut S,
    ) -> Result<(), Errno> {
        let number = system
            .signal_number_from_name(signal)
            .unwrap_or_else(|| panic!("missing support for signal {signal}"));
        let entry = self.traps.entry(Condition::Signal(number));
        GrandState::set_internal_disposition(system, entry, disposition)
    }

    /// Installs the internal disposition for `SIGCHLD`.
    ///
    /// You should install the internal disposition for `SIGCHLD` by using this
    /// function before waiting for `SIGCHLD` with [`System::wait`] and
    /// [`SharedSystem::wait_for_signal`]. The disposition allows catching
    /// `SIGCHLD`.
    ///
    /// This function remembers that the disposition has been installed, so a
    /// second call to the function will be a no-op.
    pub fn enable_internal_disposition_for_sigchld<S: SignalSystem>(
        &mut self,
        system: &mut S,
    ) -> Result<(), Errno> {
        self.set_internal_disposition(signal::Name::Chld, Disposition::Catch, system)
    }

    /// Installs the internal dispositions for `SIGINT`, `SIGTERM`, and `SIGQUIT`.
    ///
    /// An interactive shell should install the internal dispositions for these
    /// signals by using this function. The dispositions catch `SIGINT` and
    /// ignore `SIGTERM` and `SIGQUIT`.
    ///
    /// This function remembers that the dispositions have been installed, so a
    /// second call to the function will be a no-op.
    pub fn enable_internal_dispositions_for_terminators<S: SignalSystem>(
        &mut self,
        system: &mut S,
    ) -> Result<(), Errno> {
        self.set_internal_disposition(signal::Name::Int, Disposition::Catch, system)?;
        self.set_internal_disposition(signal::Name::Term, Disposition::Ignore, system)?;
        self.set_internal_disposition(signal::Name::Quit, Disposition::Ignore, system)
    }

    /// Installs the internal dispositions for `SIGTSTP`, `SIGTTIN`, and `SIGTTOU`.
    ///
    /// An interactive job-controlling shell should install the internal
    /// dispositions for these signals by using this function. The dispositions
    /// ignore the signals.
    ///
    /// This function remembers that the dispositions have been installed, so a
    /// second call to the function will be a no-op.
    pub fn enable_internal_dispositions_for_stoppers<S: SignalSystem>(
        &mut self,
        system: &mut S,
    ) -> Result<(), Errno> {
        self.set_internal_disposition(signal::Name::Tstp, Disposition::Ignore, system)?;
        self.set_internal_disposition(signal::Name::Ttin, Disposition::Ignore, system)?;
        self.set_internal_disposition(signal::Name::Ttou, Disposition::Ignore, system)
    }

    /// Uninstalls the internal dispositions for `SIGINT`, `SIGTERM`, and `SIGQUIT`.
    pub fn disable_internal_dispositions_for_terminators<S: SignalSystem>(
        &mut self,
        system: &mut S,
    ) -> Result<(), Errno> {
        self.set_internal_disposition(signal::Name::Int, Disposition::Default, system)?;
        self.set_internal_disposition(signal::Name::Term, Disposition::Default, system)?;
        self.set_internal_disposition(signal::Name::Quit, Disposition::Default, system)
    }

    /// Uninstalls the internal dispositions for `SIGTSTP`, `SIGTTIN`, and `SIGTTOU`.
    pub fn disable_internal_dispositions_for_stoppers<S: SignalSystem>(
        &mut self,
        system: &mut S,
    ) -> Result<(), Errno> {
        self.set_internal_disposition(signal::Name::Tstp, Disposition::Default, system)?;
        self.set_internal_disposition(signal::Name::Ttin, Disposition::Default, system)?;
        self.set_internal_disposition(signal::Name::Ttou, Disposition::Default, system)
    }

    /// Uninstalls all internal dispositions.
    ///
    /// This function removes all internal dispositions that have been
    /// previously installed by `self`, except for the `SIGCHLD` signal.
    /// Dispositions for any existing user-defined traps are not affected.
    pub fn disable_internal_dispositions<S: SignalSystem>(
        &mut self,
        system: &mut S,
    ) -> Result<(), Errno> {
        self.set_internal_disposition(signal::Name::Chld, Disposition::Default, system)?;
        self.disable_internal_dispositions_for_terminators(system)?;
        self.disable_internal_dispositions_for_stoppers(system)
    }
}

impl<'a> IntoIterator for &'a TrapSet {
    type Item = (&'a Condition, Option<&'a TrapState>, Option<&'a TrapState>);
    type IntoIter = Iter<'a>;

    #[inline(always)]
    fn into_iter(self) -> Iter<'a> {
        self.iter()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::job::ProcessState;
    use crate::system::r#virtual::VirtualSystem;
    use crate::system::r#virtual::{
        SIGCHLD, SIGINT, SIGKILL, SIGQUIT, SIGSTOP, SIGTERM, SIGTSTP, SIGTTIN, SIGTTOU, SIGUSR1,
        SIGUSR2,
    };
    use crate::system::System as _;
    use crate::system::SystemEx as _;
    use crate::tests::in_virtual_system;
    use std::collections::HashMap;

    #[derive(Default)]
    pub struct DummySystem(pub HashMap<signal::Number, Disposition>);

    impl SignalSystem for DummySystem {
        fn signal_name_from_number(&self, number: signal::Number) -> signal::Name {
            VirtualSystem::new().signal_name_from_number(number)
        }

        fn signal_number_from_name(&self, name: signal::Name) -> Option<signal::Number> {
            VirtualSystem::new().signal_number_from_name(name)
        }

        fn set_disposition(
            &mut self,
            signal: signal::Number,
            disposition: Disposition,
        ) -> Result<Disposition, Errno> {
            Ok(self
                .0
                .insert(signal, disposition)
                .unwrap_or(Disposition::Default))
        }
    }

    #[test]
    fn default_trap() {
        let trap_set = TrapSet::default();
        assert_eq!(trap_set.get_state(SIGCHLD), (None, None));
    }

    #[test]
    fn setting_trap_for_two_signals() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin_1 = Location::dummy("foo");
        let result = trap_set.set_action(
            &mut system,
            SIGUSR1,
            Action::Ignore,
            origin_1.clone(),
            false,
        );
        assert_eq!(result, Ok(()));

        let command = Action::Command("echo".into());
        let origin_2 = Location::dummy("bar");
        let result = trap_set.set_action(
            &mut system,
            SIGUSR2,
            command.clone(),
            origin_2.clone(),
            false,
        );
        assert_eq!(result, Ok(()));

        assert_eq!(
            trap_set.get_state(SIGUSR1),
            (
                Some(&TrapState {
                    action: Action::Ignore,
                    origin: origin_1,
                    pending: false
                }),
                None
            )
        );
        assert_eq!(
            trap_set.get_state(SIGUSR2),
            (
                Some(&TrapState {
                    action: command,
                    origin: origin_2,
                    pending: false
                }),
                None
            )
        );
        assert_eq!(system.0[&SIGUSR1], Disposition::Ignore);
        assert_eq!(system.0[&SIGUSR2], Disposition::Catch);
    }

    #[test]
    fn setting_trap_for_sigkill() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin = Location::dummy("origin");
        let result = trap_set.set_action(&mut system, SIGKILL, Action::Ignore, origin, false);
        assert_eq!(result, Err(SetActionError::SIGKILL));
        assert_eq!(trap_set.get_state(SIGKILL), (None, None));
        assert_eq!(system.0.get(&SIGKILL), None);
    }

    #[test]
    fn setting_trap_for_sigstop() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin = Location::dummy("origin");
        let result = trap_set.set_action(&mut system, SIGSTOP, Action::Ignore, origin, false);
        assert_eq!(result, Err(SetActionError::SIGSTOP));
        assert_eq!(trap_set.get_state(SIGSTOP), (None, None));
        assert_eq!(system.0.get(&SIGSTOP), None);
    }

    #[test]
    fn basic_iteration() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin_1 = Location::dummy("foo");
        trap_set
            .set_action(
                &mut system,
                SIGUSR1,
                Action::Ignore,
                origin_1.clone(),
                false,
            )
            .unwrap();
        let command = Action::Command("echo".into());
        let origin_2 = Location::dummy("bar");
        trap_set
            .set_action(
                &mut system,
                SIGUSR2,
                command.clone(),
                origin_2.clone(),
                false,
            )
            .unwrap();

        let mut i = trap_set.iter();
        let first = i.next().unwrap();
        assert_eq!(first.0, &Condition::Signal(SIGUSR1));
        assert_eq!(first.1.unwrap().action, Action::Ignore);
        assert_eq!(first.1.unwrap().origin, origin_1);
        assert_eq!(first.2, None);
        let second = i.next().unwrap();
        assert_eq!(second.0, &Condition::Signal(SIGUSR2));
        assert_eq!(second.1.unwrap().action, command);
        assert_eq!(second.1.unwrap().origin, origin_2);
        assert_eq!(first.2, None);
        assert_eq!(i.next(), None);
    }

    #[test]
    fn iteration_after_entering_subshell() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin_1 = Location::dummy("foo");
        trap_set
            .set_action(
                &mut system,
                SIGUSR1,
                Action::Ignore,
                origin_1.clone(),
                false,
            )
            .unwrap();
        let command = Action::Command("echo".into());
        let origin_2 = Location::dummy("bar");
        trap_set
            .set_action(
                &mut system,
                SIGUSR2,
                command.clone(),
                origin_2.clone(),
                false,
            )
            .unwrap();
        trap_set.enter_subshell(&mut system, false, false);

        let mut i = trap_set.iter();
        let first = i.next().unwrap();
        assert_eq!(first.0, &Condition::Signal(SIGUSR1));
        assert_eq!(first.1.unwrap().action, Action::Ignore);
        assert_eq!(first.1.unwrap().origin, origin_1);
        assert_eq!(first.2, None);
        let second = i.next().unwrap();
        assert_eq!(second.0, &Condition::Signal(SIGUSR2));
        assert_eq!(second.1, None);
        assert_eq!(second.2.unwrap().action, command);
        assert_eq!(second.2.unwrap().origin, origin_2);
        assert_eq!(i.next(), None);
    }

    #[test]
    fn iteration_after_setting_trap_in_subshell() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin_1 = Location::dummy("foo");
        let command = Action::Command("echo".into());
        trap_set
            .set_action(&mut system, SIGUSR1, command, origin_1, false)
            .unwrap();
        trap_set.enter_subshell(&mut system, false, false);
        let origin_2 = Location::dummy("bar");
        let command = Action::Command("ls".into());
        trap_set
            .set_action(
                &mut system,
                SIGUSR2,
                command.clone(),
                origin_2.clone(),
                false,
            )
            .unwrap();

        let mut i = trap_set.iter();
        let first = i.next().unwrap();
        assert_eq!(first.0, &Condition::Signal(SIGUSR2));
        assert_eq!(first.1.unwrap().action, command);
        assert_eq!(first.1.unwrap().origin, origin_2);
        assert_eq!(first.2, None);
        assert_eq!(i.next(), None);
    }

    #[test]
    fn entering_subshell_resets_command_traps() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGCHLD, action.clone(), origin.clone(), false)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGCHLD),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGCHLD], Disposition::Default);
    }

    #[test]
    fn entering_subshell_keeps_ignore_traps() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGCHLD, Action::Ignore, origin.clone(), false)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGCHLD),
            (
                Some(&TrapState {
                    action: Action::Ignore,
                    origin,
                    pending: false
                }),
                None
            )
        );
        assert_eq!(system.0[&SIGCHLD], Disposition::Ignore);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigchld() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGCHLD, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGCHLD),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGCHLD], Disposition::Catch);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigint() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGINT, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGINT),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGINT], Disposition::Default);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigterm() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGTERM, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGTERM),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGTERM], Disposition::Default);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigquit() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGQUIT, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGQUIT),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGQUIT], Disposition::Default);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigtstp() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGTSTP, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGTSTP),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGTSTP], Disposition::Default);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigttin() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGTTIN, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGTTIN),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGTTIN], Disposition::Default);
    }

    #[test]
    fn entering_subshell_with_internal_disposition_for_sigttou() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let action = Action::Command("".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGTTOU, action.clone(), origin.clone(), false)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();

        trap_set.enter_subshell(&mut system, false, false);
        assert_eq!(
            trap_set.get_state(SIGTTOU),
            (
                None,
                Some(&TrapState {
                    action,
                    origin,
                    pending: false
                })
            )
        );
        assert_eq!(system.0[&SIGTTOU], Disposition::Default);
    }

    #[test]
    fn setting_trap_after_entering_subshell_clears_parent_states() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin_1 = Location::dummy("foo");
        let command = Action::Command("echo 1".into());
        trap_set
            .set_action(&mut system, SIGUSR1, command, origin_1, false)
            .unwrap();
        let origin_2 = Location::dummy("bar");
        let command = Action::Command("echo 2".into());
        trap_set
            .set_action(&mut system, SIGUSR2, command, origin_2, false)
            .unwrap();
        trap_set.enter_subshell(&mut system, false, false);

        let command = Action::Command("echo 9".into());
        let origin_3 = Location::dummy("qux");
        trap_set
            .set_action(
                &mut system,
                SIGUSR1,
                command.clone(),
                origin_3.clone(),
                false,
            )
            .unwrap();

        assert_eq!(
            trap_set.get_state(SIGUSR1),
            (
                Some(&TrapState {
                    action: command,
                    origin: origin_3,
                    pending: false
                }),
                None
            )
        );
        assert_eq!(trap_set.get_state(SIGUSR2), (None, None));
        assert_eq!(system.0[&SIGUSR1], Disposition::Catch);
        assert_eq!(system.0[&SIGUSR2], Disposition::Default);
    }

    #[test]
    fn entering_nested_subshell_clears_parent_states() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let origin_1 = Location::dummy("foo");
        let command = Action::Command("echo 1".into());
        trap_set
            .set_action(&mut system, SIGUSR1, command, origin_1, false)
            .unwrap();
        let origin_2 = Location::dummy("bar");
        let command = Action::Command("echo 2".into());
        trap_set
            .set_action(&mut system, SIGUSR2, command, origin_2, false)
            .unwrap();
        trap_set.enter_subshell(&mut system, false, false);
        trap_set.enter_subshell(&mut system, false, false);

        assert_eq!(trap_set.get_state(SIGUSR1), (None, None));
        assert_eq!(trap_set.get_state(SIGUSR2), (None, None));
        assert_eq!(system.0[&SIGUSR1], Disposition::Default);
        assert_eq!(system.0[&SIGUSR2], Disposition::Default);
    }

    #[test]
    fn ignoring_sigint_on_entering_subshell_with_action_set() {
        in_virtual_system(|mut env, state| async move {
            env.traps
                .set_action(
                    &mut env.system,
                    SIGINT,
                    Action::Command("".into()),
                    Location::dummy(""),
                    false,
                )
                .unwrap();
            env.system.kill(env.main_pid, Some(SIGINT)).await.unwrap();
            env.traps.enter_subshell(&mut env.system, true, false);

            let state = state.borrow();
            let process = &state.processes[&env.main_pid];
            assert_eq!(process.disposition(SIGINT), Disposition::Ignore);
            assert_eq!(process.state(), ProcessState::Running);
        })
    }

    #[test]
    fn ignoring_sigquit_on_entering_subshell_with_action_set() {
        in_virtual_system(|mut env, state| async move {
            env.traps
                .set_action(
                    &mut env.system,
                    SIGQUIT,
                    Action::Command("".into()),
                    Location::dummy(""),
                    false,
                )
                .unwrap();
            env.system.kill(env.main_pid, Some(SIGQUIT)).await.unwrap();
            env.traps.enter_subshell(&mut env.system, true, false);

            let state = state.borrow();
            let process = &state.processes[&env.main_pid];
            assert_eq!(process.disposition(SIGQUIT), Disposition::Ignore);
            assert_eq!(process.state(), ProcessState::Running);
        })
    }

    #[test]
    fn ignoring_sigint_and_sigquit_on_entering_subshell_without_action_set() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set.enter_subshell(&mut system, true, false);
        assert_eq!(system.0[&SIGINT], Disposition::Ignore);
        assert_eq!(system.0[&SIGQUIT], Disposition::Ignore);
    }

    #[test]
    fn keeping_stopper_internal_dispositions_ignored() {
        in_virtual_system(|mut env, state| async move {
            for signal in [SIGTSTP, SIGTTIN, SIGTTOU] {
                env.traps
                    .set_action(
                        &mut env.system,
                        signal,
                        Action::Command("".into()),
                        Location::dummy(""),
                        false,
                    )
                    .unwrap();
            }
            env.traps
                .enable_internal_dispositions_for_stoppers(&mut env.system)
                .unwrap();
            for signal in [SIGTSTP, SIGTTIN, SIGTTOU] {
                env.system.kill(env.main_pid, Some(signal)).await.unwrap();
            }
            env.traps.enter_subshell(&mut env.system, false, true);

            let state = state.borrow();
            let process = &state.processes[&env.main_pid];
            assert_eq!(process.disposition(SIGTSTP), Disposition::Ignore);
            assert_eq!(process.disposition(SIGTTIN), Disposition::Ignore);
            assert_eq!(process.disposition(SIGTTOU), Disposition::Ignore);
            assert_eq!(process.state(), ProcessState::Running);
        })
    }

    #[test]
    fn no_stopper_internal_dispositions_enabled_to_be_kept_ignored() {
        in_virtual_system(|mut env, state| async move {
            for signal in [SIGTSTP, SIGTTIN, SIGTTOU] {
                env.traps
                    .set_action(
                        &mut env.system,
                        signal,
                        Action::Command("".into()),
                        Location::dummy(""),
                        false,
                    )
                    .unwrap();
            }
            env.traps.enter_subshell(&mut env.system, false, true);

            let state = state.borrow();
            let process = &state.processes[&env.main_pid];
            assert_eq!(process.disposition(SIGTSTP), Disposition::Default);
            assert_eq!(process.disposition(SIGTTIN), Disposition::Default);
            assert_eq!(process.disposition(SIGTTOU), Disposition::Default);
        })
    }

    #[test]
    fn catching_signal() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let command = Action::Command("echo INT".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGINT, command, origin, false)
            .unwrap();
        let command = Action::Command("echo TERM".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGTERM, command, origin, false)
            .unwrap();

        trap_set.catch_signal(SIGCHLD);
        trap_set.catch_signal(SIGINT);

        let trap_state = trap_set.get_state(SIGINT).0.unwrap();
        assert!(trap_state.pending, "trap_state = {trap_state:?}");
        let trap_state = trap_set.get_state(SIGTERM).0.unwrap();
        assert!(!trap_state.pending, "trap_state = {trap_state:?}");
    }

    #[test]
    fn taking_signal_if_caught() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        let command = Action::Command("echo INT".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGINT, command, origin, false)
            .unwrap();

        let result = trap_set.take_signal_if_caught(SIGINT);
        assert_eq!(result, None);

        trap_set.catch_signal(SIGINT);

        let result = trap_set.take_signal_if_caught(SIGINT);
        assert!(!result.unwrap().pending);

        let result = trap_set.take_signal_if_caught(SIGINT);
        assert_eq!(result, None);
    }

    #[test]
    fn taking_caught_signal() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        assert_eq!(trap_set.take_caught_signal(), None);

        let command = Action::Command("echo INT".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGINT, command, origin, false)
            .unwrap();
        let command = Action::Command("echo TERM".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGTERM, command, origin, false)
            .unwrap();
        let command = Action::Command("echo USR1".into());
        let origin = Location::dummy("origin");
        trap_set
            .set_action(&mut system, SIGUSR1, command, origin, false)
            .unwrap();
        assert_eq!(trap_set.take_caught_signal(), None);

        trap_set.catch_signal(SIGINT);
        trap_set.catch_signal(SIGUSR1);
        // The order in which take_caught_signal returns the two signals is
        // unspecified, so we accept both the orders.
        let result = trap_set.take_caught_signal().unwrap();
        match result.0 {
            SIGINT => {
                assert_eq!(result.1.action, Action::Command("echo INT".into()));
                assert!(!result.1.pending);

                let result = trap_set.take_caught_signal().unwrap();
                assert_eq!(result.0, SIGUSR1);
                assert_eq!(result.1.action, Action::Command("echo USR1".into()));
                assert!(!result.1.pending);
            }
            SIGUSR1 => {
                assert_eq!(result.1.action, Action::Command("echo USR1".into()));
                assert!(!result.1.pending);

                let result = trap_set.take_caught_signal().unwrap();
                assert_eq!(result.0, SIGINT);
                assert_eq!(result.1.action, Action::Command("echo INT".into()));
                assert!(!result.1.pending);
            }
            _ => panic!("wrong signal: {result:?}"),
        }

        assert_eq!(trap_set.take_caught_signal(), None);
    }

    #[test]
    fn enabling_internal_disposition_for_sigchld() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        assert_eq!(system.0[&SIGCHLD], Disposition::Catch);
    }

    #[test]
    fn enabling_internal_dispositions_for_terminators() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        assert_eq!(system.0[&SIGINT], Disposition::Catch);
        assert_eq!(system.0[&SIGTERM], Disposition::Ignore);
        assert_eq!(system.0[&SIGQUIT], Disposition::Ignore);
    }

    #[test]
    fn enabling_internal_dispositions_for_stoppers() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        assert_eq!(system.0[&SIGTSTP], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTIN], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTOU], Disposition::Ignore);
    }

    #[test]
    fn disabling_internal_dispositions_for_initially_defaulted_signals() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        trap_set.disable_internal_dispositions(&mut system).unwrap();
        assert_eq!(system.0[&SIGCHLD], Disposition::Default);
        assert_eq!(system.0[&SIGINT], Disposition::Default);
        assert_eq!(system.0[&SIGTERM], Disposition::Default);
        assert_eq!(system.0[&SIGQUIT], Disposition::Default);
        assert_eq!(system.0[&SIGTSTP], Disposition::Default);
        assert_eq!(system.0[&SIGTTIN], Disposition::Default);
        assert_eq!(system.0[&SIGTTOU], Disposition::Default);
    }

    fn ignore_signals(system: &mut DummySystem) {
        system.0.extend(
            [SIGCHLD, SIGINT, SIGTERM, SIGQUIT, SIGTSTP, SIGTTIN, SIGTTOU]
                .into_iter()
                .map(|signal| (signal, Disposition::Ignore)),
        )
    }

    #[test]
    fn disabling_internal_dispositions_for_initially_ignored_signals() {
        let mut system = DummySystem::default();
        ignore_signals(&mut system);
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        trap_set.disable_internal_dispositions(&mut system).unwrap();
        assert_eq!(system.0[&SIGCHLD], Disposition::Ignore);
        assert_eq!(system.0[&SIGINT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTERM], Disposition::Ignore);
        assert_eq!(system.0[&SIGQUIT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTSTP], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTIN], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTOU], Disposition::Ignore);
    }

    #[test]
    fn disabling_internal_dispositions_after_enabling_twice() {
        let mut system = DummySystem::default();
        ignore_signals(&mut system);
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        trap_set.disable_internal_dispositions(&mut system).unwrap();
        assert_eq!(system.0[&SIGCHLD], Disposition::Ignore);
        assert_eq!(system.0[&SIGINT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTERM], Disposition::Ignore);
        assert_eq!(system.0[&SIGQUIT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTSTP], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTIN], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTOU], Disposition::Ignore);
    }

    #[test]
    fn disabling_internal_dispositions_without_enabling() {
        let mut system = DummySystem::default();
        ignore_signals(&mut system);
        let mut trap_set = TrapSet::default();
        trap_set.disable_internal_dispositions(&mut system).unwrap();
        assert_eq!(system.0[&SIGCHLD], Disposition::Ignore);
        assert_eq!(system.0[&SIGINT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTERM], Disposition::Ignore);
        assert_eq!(system.0[&SIGQUIT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTSTP], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTIN], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTOU], Disposition::Ignore);
    }

    #[test]
    fn reenabling_internal_dispositions() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        trap_set.disable_internal_dispositions(&mut system).unwrap();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();
        assert_eq!(system.0[&SIGCHLD], Disposition::Catch);
        assert_eq!(system.0[&SIGINT], Disposition::Catch);
        assert_eq!(system.0[&SIGTERM], Disposition::Ignore);
        assert_eq!(system.0[&SIGQUIT], Disposition::Ignore);
        assert_eq!(system.0[&SIGTSTP], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTIN], Disposition::Ignore);
        assert_eq!(system.0[&SIGTTOU], Disposition::Ignore);
    }

    #[test]
    fn setting_trap_to_ignore_after_enabling_internal_disposition() {
        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        let origin = Location::dummy("origin");
        let result = trap_set.set_action(&mut system, SIGCHLD, Action::Ignore, origin, false);
        assert_eq!(result, Ok(()));
        assert_eq!(system.0[&SIGCHLD], Disposition::Catch);
    }

    #[test]
    fn resetting_trap_from_ignore_no_override_after_enabling_internal_dispositions() {
        let mut system = DummySystem::default();
        ignore_signals(&mut system);
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();

        for signal in [SIGCHLD, SIGINT] {
            let origin = Location::dummy("origin");
            let result = trap_set.set_action(&mut system, signal, Action::Default, origin, false);
            assert_eq!(result, Err(SetActionError::InitiallyIgnored));
            assert_eq!(system.0[&signal], Disposition::Catch);
        }
        for signal in [SIGTERM, SIGQUIT, SIGTSTP, SIGTTIN, SIGTTOU] {
            let origin = Location::dummy("origin");
            let result = trap_set.set_action(&mut system, signal, Action::Default, origin, false);
            assert_eq!(result, Err(SetActionError::InitiallyIgnored));
            assert_eq!(system.0[&signal], Disposition::Ignore);
        }
    }

    #[test]
    fn resetting_trap_from_ignore_override_after_enabling_internal_dispositions() {
        let mut system = DummySystem::default();
        ignore_signals(&mut system);
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_stoppers(&mut system)
            .unwrap();

        for signal in [SIGCHLD, SIGINT] {
            let origin = Location::dummy("origin");
            let result =
                trap_set.set_action(&mut system, signal, Action::Ignore, origin.clone(), true);
            assert_eq!(result, Ok(()));
            assert_eq!(
                trap_set.get_state(signal),
                (
                    Some(&TrapState {
                        action: Action::Ignore,
                        origin,
                        pending: false
                    }),
                    None
                )
            );
            assert_eq!(system.0[&signal], Disposition::Catch);
        }
        for signal in [SIGTERM, SIGQUIT, SIGTSTP, SIGTTIN, SIGTTOU] {
            let origin = Location::dummy("origin");
            let result =
                trap_set.set_action(&mut system, signal, Action::Ignore, origin.clone(), true);
            assert_eq!(result, Ok(()));
            assert_eq!(
                trap_set.get_state(signal),
                (
                    Some(&TrapState {
                        action: Action::Ignore,
                        origin,
                        pending: false
                    }),
                    None
                )
            );
            assert_eq!(system.0[&signal], Disposition::Ignore);
        }
    }

    #[test]
    fn disabling_internal_disposition_with_ignore_trap() {
        let signals = [SIGCHLD, SIGINT, SIGTERM, SIGQUIT, SIGTSTP, SIGTTIN, SIGTTOU];

        let mut system = DummySystem::default();
        let mut trap_set = TrapSet::default();
        trap_set
            .enable_internal_disposition_for_sigchld(&mut system)
            .unwrap();
        trap_set
            .enable_internal_dispositions_for_terminators(&mut system)
            .unwrap();
        let origin = Location::dummy("origin");
        for signal in signals {
            trap_set
                .set_action(&mut system, signal, Action::Ignore, origin.clone(), false)
                .unwrap();
        }
        trap_set.disable_internal_dispositions(&mut system).unwrap();

        for signal in signals {
            assert_eq!(
                trap_set.get_state(signal),
                (
                    Some(&TrapState {
                        action: Action::Ignore,
                        origin: origin.clone(),
                        pending: false
                    }),
                    None
                )
            );
            assert_eq!(system.0[&signal], Disposition::Ignore);
        }
    }
}