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
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
//! An emulated Linux process.

use std::cell::{Cell, Ref, RefCell, RefMut};
use std::collections::BTreeMap;
use std::ffi::{c_char, c_void, CStr, CString};
use std::fmt::Write;
use std::num::TryFromIntError;
use std::ops::{Deref, DerefMut};
use std::os::fd::AsRawFd;
use std::path::{Path, PathBuf};
use std::sync::atomic::Ordering;
use std::sync::Arc;
#[cfg(feature = "perf_timers")]
use std::time::Duration;

use linux_api::errno::Errno;
use linux_api::fcntl::OFlag;
use linux_api::posix_types::Pid;
use linux_api::sched::{CloneFlags, SuidDump};
use linux_api::signal::{
    defaultaction, siginfo_t, sigset_t, LinuxDefaultAction, SigActionFlags, Signal,
    SignalFromI32Error,
};
use log::{debug, trace, warn};
use rustix::process::{WaitOptions, WaitStatus};
use shadow_shim_helper_rs::explicit_drop::{ExplicitDrop, ExplicitDropper};
use shadow_shim_helper_rs::rootedcell::rc::RootedRc;
use shadow_shim_helper_rs::rootedcell::refcell::RootedRefCell;
use shadow_shim_helper_rs::rootedcell::Root;
use shadow_shim_helper_rs::shim_shmem::ProcessShmem;
use shadow_shim_helper_rs::simulation_time::SimulationTime;
use shadow_shim_helper_rs::syscall_types::{ForeignPtr, ManagedPhysicalMemoryAddr};
use shadow_shim_helper_rs::HostId;
use shadow_shmem::allocator::ShMemBlock;

use super::descriptor::descriptor_table::{DescriptorHandle, DescriptorTable};
use super::descriptor::listener::StateEventSource;
use super::descriptor::{FileSignals, FileState};
use super::host::Host;
use super::memory_manager::{MemoryManager, ProcessMemoryRef, ProcessMemoryRefMut};
use super::syscall::formatter::StraceFmtMode;
use super::syscall::types::ForeignArrayPtr;
use super::thread::{Thread, ThreadId};
use super::timer::Timer;
use crate::core::configuration::{ProcessFinalState, RunningVal};
use crate::core::work::task::TaskRef;
use crate::core::worker::Worker;
use crate::cshadow;
use crate::host::context::ProcessContext;
use crate::host::descriptor::Descriptor;
use crate::host::managed_thread::ManagedThread;
use crate::host::syscall::formatter::FmtOptions;
use crate::utility::callback_queue::CallbackQueue;
#[cfg(feature = "perf_timers")]
use crate::utility::perf_timer::PerfTimer;
use crate::utility::{self, debug_assert_cloexec};

/// Virtual pid of a shadow process
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone, Ord, PartialOrd)]
pub struct ProcessId(u32);

impl ProcessId {
    // The first Process to run after boot is the "init" process, and has pid=1.
    // In Shadow simulations, this roughly corresponds to Shadow itself. e.g.
    // processes spawned by Shadow itself have a parent pid of 1.
    pub const INIT: Self = ProcessId(1);

    /// Returns what the `ProcessId` would be of a `Process` whose thread
    /// group leader has id `thread_group_leader_tid`.
    pub fn from_thread_group_leader_tid(thread_group_leader_tid: ThreadId) -> Self {
        ProcessId::try_from(libc::pid_t::from(thread_group_leader_tid)).unwrap()
    }
}

impl std::fmt::Display for ProcessId {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl TryFrom<u32> for ProcessId {
    type Error = TryFromIntError;

    fn try_from(val: u32) -> Result<Self, Self::Error> {
        // we don't actually want the value as a `pid_t`, we just want to make sure it can be
        // converted successfully
        let _ = libc::pid_t::try_from(val)?;
        Ok(ProcessId(val))
    }
}

impl TryFrom<libc::pid_t> for ProcessId {
    type Error = TryFromIntError;

    fn try_from(value: libc::pid_t) -> Result<Self, Self::Error> {
        Ok(ProcessId(value.try_into()?))
    }
}

impl From<ProcessId> for u32 {
    fn from(val: ProcessId) -> Self {
        val.0
    }
}

impl From<ProcessId> for libc::pid_t {
    fn from(val: ProcessId) -> Self {
        val.0.try_into().unwrap()
    }
}

impl From<ThreadId> for ProcessId {
    fn from(value: ThreadId) -> Self {
        ProcessId::try_from(libc::pid_t::from(value)).unwrap()
    }
}

#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ExitStatus {
    Normal(i32),
    Signaled(Signal),
    /// The process was killed by Shadow rather than exiting "naturally" as part
    /// of the simulation. Currently this only happens when the process is still
    /// running when the simulation stop_time is reached.
    ///
    /// A signal delivered via `shutdown_signal` does not result in this status;
    /// e.g. if the process is killed directly by the signal the ExitStatus will
    /// be `Signaled`; if the process handles the signal and exits by calling
    /// `exit`, the status will be `Normal`.
    StoppedByShadow,
}

#[derive(Debug)]
struct StraceLogging {
    file: RootedRefCell<std::fs::File>,
    options: FmtOptions,
}

/// Parts of the process that are present in all states.
struct Common {
    id: ProcessId,
    host_id: HostId,

    // Parent pid (aka `ppid`), as returned e.g. by `getppid`.  This can change
    // at runtime if the original parent exits and is reaped.
    parent_pid: Cell<ProcessId>,

    // Process group id (aka `pgid`), as returned e.g. by `getpgid`.
    group_id: Cell<ProcessId>,

    // Session id, as returned e.g. by `getsid`.
    session_id: Cell<ProcessId>,

    // Signal to send to parent on death.
    exit_signal: Option<Signal>,

    // unique id of the program that this process should run
    name: CString,

    // the name of the executable as provided in shadow's config, for logging purposes
    plugin_name: CString,

    // absolute path to the process's working directory.
    // This must remain in sync with the actual working dir of the native process.
    // See https://github.com/shadow/shadow/issues/2960
    working_dir: CString,
}

impl Common {
    fn id(&self) -> ProcessId {
        self.id
    }

    fn physical_address(&self, vptr: ForeignPtr<()>) -> ManagedPhysicalMemoryAddr {
        // We currently don't keep a true system-wide virtual <-> physical address
        // mapping. Instead we simply assume that no shadow processes map the same
        // underlying physical memory, and that therefore (pid, virtual address)
        // uniquely defines a physical address.
        //
        // If we ever want to support futexes in memory shared between processes,
        // we'll need to change this.  The most foolproof way to do so is probably
        // to change ManagedPhysicalMemoryAddr to be a bigger struct that identifies where
        // the mapped region came from (e.g. what file), and the offset into that
        // region. Such "fat" physical pointers might make memory management a
        // little more cumbersome though, e.g. when using them as keys in the futex
        // table.
        //
        // Alternatively we could hash the region+offset to a 64-bit value, but
        // then we'd need to deal with potential collisions. On average we'd expect
        // a collision after 2**32 physical addresses; i.e. they *probably*
        // wouldn't happen in practice for realistic simulations.

        // Linux uses the bottom 48-bits for user-space virtual addresses, giving
        // us 16 bits for the pid.
        const PADDR_BITS: i32 = 64;
        const VADDR_BITS: i32 = 48;
        const PID_BITS: i32 = 16;
        assert_eq!(PADDR_BITS, PID_BITS + VADDR_BITS);

        let high_part: u64 = u64::from(u32::from(self.id())) << VADDR_BITS;
        assert_eq!(
            ProcessId::try_from((high_part >> VADDR_BITS) as u32),
            Ok(self.id())
        );

        let low_part = u64::from(vptr);
        assert_eq!(low_part >> VADDR_BITS, 0);

        ManagedPhysicalMemoryAddr::from(high_part | low_part)
    }

    fn name(&self) -> &str {
        self.name.to_str().unwrap()
    }

    pub fn thread_group_leader_id(&self) -> ThreadId {
        // tid of the thread group leader is equal to the pid.
        ThreadId::from(self.id())
    }
}

/// A process that is currently runnable.
pub struct RunnableProcess {
    common: Common,

    // Expected end state, if any. We'll report an error if this is present and
    // doesn't match the actual exit status.
    //
    // This will be None e.g. for processes created via `fork` instead of
    // spawned directly from Shadow's config file. In those cases it's the
    // parent's responsibility to reap and interpret the exit status.
    expected_final_state: Option<ProcessFinalState>,

    // Shared memory allocation for shared state with shim.
    shim_shared_mem_block: ShMemBlock<'static, ProcessShmem>,

    // Shared with forked Processes
    strace_logging: Option<Arc<StraceLogging>>,

    // The shim's log file. This gets dup'd into the ManagedProcess
    // where the shim can write to it directly. We persist it to handle the case
    // where we need to recreatea a ManagedProcess and have it continue writing
    // to the same file.
    //
    // Shared with forked Processes
    shimlog_file: Arc<std::fs::File>,

    // "dumpable" state, as manipulated via the prctl operations PR_SET_DUMPABLE
    // and PR_GET_DUMPABLE.
    dumpable: Cell<SuidDump>,

    native_pid: Pid,

    // timer that tracks the amount of CPU time we spend on plugin execution and processing
    #[cfg(feature = "perf_timers")]
    cpu_delay_timer: RefCell<PerfTimer>,
    #[cfg(feature = "perf_timers")]
    total_run_time: Cell<Duration>,

    itimer_real: RefCell<Timer>,

    // The `RootedRc` lets us hold a reference to a thread without holding a
    // reference to the thread list. e.g. this lets us implement the `clone`
    // syscall, which adds a thread to the list while we have a reference to the
    // parent thread.
    threads: RefCell<BTreeMap<ThreadId, RootedRc<RootedRefCell<Thread>>>>,

    // References to `Self::memory_manager` cached on behalf of C code using legacy
    // C memory access APIs.
    // TODO: Remove these when we've migrated Shadow off of the APIs that need
    // them (probably by migrating all the calling code to Rust).
    //
    // SAFETY: Must be before memory_manager for drop order.
    unsafe_borrow_mut: RefCell<Option<UnsafeBorrowMut>>,
    unsafe_borrows: RefCell<Vec<UnsafeBorrow>>,

    // `clone(2)` documents that if `CLONE_THREAD` is set, then `CLONE_VM` must
    // also be set. Hence all threads in a process always share the same virtual
    // address space, and hence we have a `MemoryManager` at the `Process` level
    // rather than the `Thread` level.
    // SAFETY: Must come after `unsafe_borrows` and `unsafe_borrow_mut`.
    // Boxed to avoid invalidating those if Self is moved.
    memory_manager: Box<RefCell<MemoryManager>>,

    // Listeners for child-events.
    // e.g. these listeners are notified when a child of this process exits.
    child_process_event_listeners: RefCell<StateEventSource>,
}

impl RunnableProcess {
    /// Spawn a `ManagedThread` corresponding to the given `exec` syscall
    /// parameters.  Intended for use by the `exec` syscall handlers. Whether it
    /// succeeds or fails, does *not* mutate `self`, though `self`'s strace and
    /// shim log files will be passed into the new `ManagedThread`.
    ///
    /// In case the native `exec` syscall fails, the corresponding error is returned.
    pub fn spawn_mthread_for_exec(
        &self,
        host: &Host,
        plugin_path: &CStr,
        argv: Vec<CString>,
        envv: Vec<CString>,
    ) -> Result<ManagedThread, Errno> {
        ManagedThread::spawn(
            plugin_path,
            argv,
            envv,
            self.strace_logging
                .as_ref()
                .map(|s| s.file.borrow(host.root()))
                .as_deref(),
            &self.shimlog_file,
            host.preload_paths(),
        )
    }

    /// Call after a thread has exited. Removes the thread and does corresponding cleanup and notifications.
    fn reap_thread(&self, host: &Host, threadrc: RootedRc<RootedRefCell<Thread>>) {
        let threadrc = ExplicitDropper::new(threadrc, |t| {
            t.explicit_drop_recursive(host.root(), host);
        });
        let thread = threadrc.borrow(host.root());

        assert!(!thread.is_running());

        // If the `clear_child_tid` attribute on the thread is set, and there are
        // any other threads left alive in the process, perform a futex wake on
        // that address. This mechanism is typically used in `pthread_join` etc.
        // See `set_tid_address(2)`.
        let clear_child_tid_pvp = thread.get_tid_address();
        if !clear_child_tid_pvp.is_null() && self.threads.borrow().len() > 0 {
            self.memory_manager
                .borrow_mut()
                .write(clear_child_tid_pvp, &0)
                .unwrap();

            // Wake the corresponding futex.
            let futexes = host.futextable_borrow();
            let addr = self
                .common
                .physical_address(clear_child_tid_pvp.cast::<()>());

            if let Some(futex) = futexes.get(addr) {
                futex.wake(1);
            }
        }
    }

    /// This cleans up memory references left over from legacy C code; usually
    /// a syscall handler.
    ///
    /// Writes the leftover mutable ref to memory (if any), and frees
    /// all memory refs.
    pub fn free_unsafe_borrows_flush(&self) -> Result<(), Errno> {
        self.unsafe_borrows.borrow_mut().clear();

        let unsafe_borrow_mut = self.unsafe_borrow_mut.borrow_mut().take();
        if let Some(borrow) = unsafe_borrow_mut {
            borrow.flush()
        } else {
            Ok(())
        }
    }

    /// This cleans up memory references left over from legacy C code; usually
    /// a syscall handler.
    ///
    /// Frees all memory refs without writing back to memory.
    pub fn free_unsafe_borrows_noflush(&self) {
        self.unsafe_borrows.borrow_mut().clear();

        let unsafe_borrow_mut = self.unsafe_borrow_mut.borrow_mut().take();
        if let Some(borrow) = unsafe_borrow_mut {
            borrow.noflush();
        }
    }

    #[track_caller]
    pub fn memory_borrow(&self) -> impl Deref<Target = MemoryManager> + '_ {
        self.memory_manager.borrow()
    }

    #[track_caller]
    pub fn memory_borrow_mut(&self) -> impl DerefMut<Target = MemoryManager> + '_ {
        self.memory_manager.borrow_mut()
    }

    pub fn strace_logging_options(&self) -> Option<FmtOptions> {
        self.strace_logging.as_ref().map(|x| x.options)
    }

    /// If strace logging is disabled, this function will do nothing and return `None`.
    pub fn with_strace_file<T>(&self, f: impl FnOnce(&mut std::fs::File) -> T) -> Option<T> {
        // TODO: get Host from caller. Would need t update syscall-logger.
        Worker::with_active_host(|host| {
            let strace_logging = self.strace_logging.as_ref()?;
            let mut file = strace_logging.file.borrow_mut(host.root());
            Some(f(&mut file))
        })
        .unwrap()
    }

    pub fn native_pid(&self) -> Pid {
        self.native_pid
    }

    #[track_caller]
    fn first_live_thread(&self, root: &Root) -> Option<Ref<RootedRc<RootedRefCell<Thread>>>> {
        Ref::filter_map(self.threads.borrow(), |threads| {
            threads.values().next().inspect(|thread| {
                // There shouldn't be any non-running threads in the table.
                assert!(thread.borrow(root).is_running());
            })
        })
        .ok()
    }

    /// Returns a dynamically borrowed reference to the first live thread.
    /// This is meant primarily for the MemoryManager.
    #[track_caller]
    pub fn first_live_thread_borrow(
        &self,
        root: &Root,
    ) -> Option<impl Deref<Target = RootedRc<RootedRefCell<Thread>>> + '_> {
        self.first_live_thread(root)
    }

    #[track_caller]
    fn thread(&self, virtual_tid: ThreadId) -> Option<Ref<RootedRc<RootedRefCell<Thread>>>> {
        Ref::filter_map(self.threads.borrow(), |threads| threads.get(&virtual_tid)).ok()
    }

    #[track_caller]
    pub fn thread_borrow(
        &self,
        virtual_tid: ThreadId,
    ) -> Option<impl Deref<Target = RootedRc<RootedRefCell<Thread>>> + '_> {
        self.thread(virtual_tid)
    }

    // Disposes of `self`, returning the internal `Common` for reuse.
    // Used internally when changing states.
    fn into_common(self) -> Common {
        // There shouldn't be any outstanding unsafe borrows when changing
        // states, since that would indicate C code might still have a pointer
        // to memory.
        assert!(self.unsafe_borrow_mut.take().is_none());
        assert!(self.unsafe_borrows.take().is_empty());

        self.common
    }

    /// Starts the CPU delay timer.
    /// Panics if the timer is already running.
    #[cfg(feature = "perf_timers")]
    pub fn start_cpu_delay_timer(&self) {
        self.cpu_delay_timer.borrow_mut().start()
    }

    /// Stop the timer and return the most recent (not cumulative) duration.
    /// Panics if the timer was not already running.
    #[cfg(feature = "perf_timers")]
    pub fn stop_cpu_delay_timer(&self, host: &Host) -> Duration {
        let mut timer = self.cpu_delay_timer.borrow_mut();
        timer.stop();
        let total_elapsed = timer.elapsed();
        let prev_total = self.total_run_time.replace(total_elapsed);
        let delta = total_elapsed - prev_total;

        if let Some(mut tracker) = host.tracker_borrow_mut() {
            unsafe {
                cshadow::tracker_addProcessingTimeNanos(
                    &mut *tracker,
                    delta.as_nanos().try_into().unwrap(),
                )
            };
            host.cpu_borrow_mut().add_delay(delta);
        }
        delta
    }

    fn interrupt_with_signal(&self, host: &Host, signal: Signal) {
        let threads = self.threads.borrow();
        for thread in threads.values() {
            let thread = thread.borrow(host.root());
            {
                let thread_shmem = thread.shmem();
                let host_lock = host.shim_shmem_lock_borrow().unwrap();
                let thread_shmem_protected = thread_shmem.protected.borrow(&host_lock.root);
                let blocked_signals = thread_shmem_protected.blocked_signals;
                if blocked_signals.has(signal) {
                    continue;
                }
            }
            let Some(mut cond) = thread.syscall_condition_mut() else {
                // Defensively handle this gracefully, but it probably shouldn't happen.
                // The only thread in the process not blocked on a syscall should be
                // the current-running thread (if any), but the caller should have
                // delivered the signal synchronously instead of using this function
                // in that case.
                warn!("thread {:?} has no syscall_condition. How?", thread.id());
                continue;
            };
            cond.wakeup_for_signal(host, signal);
            break;
        }
    }

    /// Send the signal described in `siginfo` to `process`. `current_thread`
    /// should be set if there is one (e.g. if this is being called from a syscall
    /// handler), and `None` otherwise (e.g. when called from a timer expiration event).
    ///
    /// An event will be scheduled to deliver the signal unless `current_thread`
    /// is set, and belongs to the process `self`, and doesn't have the signal
    /// blocked.  In that the signal will be processed synchronously when
    /// returning from the current syscall.
    pub fn signal(&self, host: &Host, current_thread: Option<&Thread>, siginfo_t: &siginfo_t) {
        let signal = match siginfo_t.signal() {
            Ok(s) => s,
            Err(SignalFromI32Error(0)) => return,
            Err(SignalFromI32Error(n)) => panic!("Bad signo {n}"),
        };

        // Scope for `process_shmem_protected`
        {
            let host_shmem = host.shim_shmem_lock_borrow().unwrap();
            let mut process_shmem_protected = self
                .shim_shared_mem_block
                .protected
                .borrow_mut(&host_shmem.root);
            // SAFETY: We don't try to call any of the function pointers.
            let action = unsafe { process_shmem_protected.signal_action(signal) };
            match unsafe { action.handler() } {
                linux_api::signal::SignalHandler::Handler(_) => (),
                linux_api::signal::SignalHandler::Action(_) => (),
                linux_api::signal::SignalHandler::SigIgn => return,
                linux_api::signal::SignalHandler::SigDfl => {
                    if defaultaction(signal) == LinuxDefaultAction::IGN {
                        return;
                    }
                }
            }

            if process_shmem_protected.pending_signals.has(signal) {
                // Signal is already pending. From signal(7):In the case where a
                // standard signal is already pending, the siginfo_t structure (see
                // sigaction(2)) associated with that signal is not overwritten on
                // arrival of subsequent instances of the same signal.
                return;
            }
            process_shmem_protected.pending_signals.add(signal);
            process_shmem_protected.set_pending_standard_siginfo(signal, siginfo_t);
        }

        if let Some(thread) = current_thread {
            if thread.process_id() == self.common.id() {
                let host_shmem = host.shim_shmem_lock_borrow().unwrap();
                let threadmem = thread.shmem();
                let threadprotmem = threadmem.protected.borrow(&host_shmem.root);
                if !threadprotmem.blocked_signals.has(signal) {
                    // Target process is this process, and current thread hasn't blocked
                    // the signal.  It will be delivered to this thread when it resumes.
                    return;
                }
            }
        }

        self.interrupt_with_signal(host, signal);
    }

    /// Adds a new thread to the process and schedules it to run.
    /// Intended for use by `clone`.
    pub fn add_thread(&self, host: &Host, thread: RootedRc<RootedRefCell<Thread>>) {
        let pid = self.common.id();
        let tid = thread.borrow(host.root()).id();
        self.threads.borrow_mut().insert(tid, thread);

        // Schedule thread to start. We're giving the caller's reference to thread
        // to the TaskRef here, which is why we don't increment its ref count to
        // create the TaskRef, but do decrement it on cleanup.
        let task = TaskRef::new(move |host| {
            host.resume(pid, tid);
        });
        host.schedule_task_with_delay(task, SimulationTime::ZERO);
    }

    /// Create a new `Process`, forked from `self`, with the thread `new_thread_group_leader`.
    pub fn new_forked_process(
        &self,
        host: &Host,
        flags: CloneFlags,
        exit_signal: Option<Signal>,
        new_thread_group_leader: RootedRc<RootedRefCell<Thread>>,
    ) -> RootedRc<RootedRefCell<Process>> {
        let new_tgl_tid;
        let native_pid;
        {
            let new_tgl = new_thread_group_leader.borrow(host.root());
            new_tgl_tid = new_tgl.id();
            native_pid = new_tgl.native_pid();
        }
        let pid = ProcessId::from_thread_group_leader_tid(new_tgl_tid);
        assert_eq!(
            pid,
            new_thread_group_leader.borrow(host.root()).process_id()
        );
        let plugin_name = self.common.plugin_name.clone();
        let name = make_name(host, plugin_name.to_str().unwrap(), pid);

        let parent_pid = if flags.contains(CloneFlags::CLONE_PARENT) {
            self.common.parent_pid.get()
        } else {
            self.common.id
        };

        // Process group is always inherited from the parent process.
        let process_group_id = self.common.group_id.get();

        // Session is always inherited from the parent process.
        let session_id = self.common.session_id.get();

        let common = Common {
            id: pid,
            host_id: host.id(),
            name,
            plugin_name,
            working_dir: self.common.working_dir.clone(),
            parent_pid: Cell::new(parent_pid),
            group_id: Cell::new(process_group_id),
            session_id: Cell::new(session_id),
            exit_signal,
        };

        // The child will log to the same strace log file. Entries contain thread IDs,
        // though it might be tricky to map those back to processes.
        let strace_logging = self.strace_logging.as_ref().cloned();

        // `fork(2)`:
        //  > The child does not inherit timers from its parent
        //  > (setitimer(2), alarm(2), timer_create(2)).
        let itimer_real = RefCell::new(Timer::new(move |host| itimer_real_expiration(host, pid)));

        let threads = RefCell::new(BTreeMap::from([(new_tgl_tid, new_thread_group_leader)]));

        let shim_shared_mem = ProcessShmem::new(
            &host.shim_shmem_lock_borrow().unwrap().root,
            host.shim_shmem().serialize(),
            host.id(),
            strace_logging
                .as_ref()
                .map(|x| x.file.borrow(host.root()).as_raw_fd()),
        );
        let shim_shared_mem_block = shadow_shmem::allocator::shmalloc(shim_shared_mem);

        let runnable_process = RunnableProcess {
            common,
            expected_final_state: None,
            shim_shared_mem_block,
            strace_logging,
            dumpable: self.dumpable.clone(),
            native_pid,
            #[cfg(feature = "perf_timers")]
            cpu_delay_timer: RefCell::new(PerfTimer::new()),
            #[cfg(feature = "perf_timers")]
            total_run_time: Cell::new(Duration::ZERO),
            itimer_real,
            threads,
            unsafe_borrow_mut: RefCell::new(None),
            unsafe_borrows: RefCell::new(Vec::new()),
            memory_manager: Box::new(RefCell::new(unsafe { MemoryManager::new(native_pid) })),
            child_process_event_listeners: Default::default(),
            shimlog_file: self.shimlog_file.clone(),
        };
        let child_process = Process {
            state: RefCell::new(Some(ProcessState::Runnable(runnable_process))),
        };
        RootedRc::new(host.root(), RootedRefCell::new(host.root(), child_process))
    }

    /// Shared memory for this process.
    pub fn shmem(&self) -> impl Deref<Target = ShMemBlock<'static, ProcessShmem>> + '_ {
        &self.shim_shared_mem_block
    }
}

impl ExplicitDrop for RunnableProcess {
    type ExplicitDropParam = Host;
    type ExplicitDropResult = ();

    fn explicit_drop(mut self, host: &Self::ExplicitDropParam) -> Self::ExplicitDropResult {
        let threads = std::mem::take(self.threads.get_mut());
        for thread in threads.into_values() {
            thread.explicit_drop_recursive(host.root(), host);
        }
    }
}

/// A process that has exited.
pub struct ZombieProcess {
    common: Common,

    exit_status: ExitStatus,
}

impl ZombieProcess {
    pub fn exit_status(&self) -> ExitStatus {
        self.exit_status
    }

    /// Process that can reap this zombie process, if any.
    pub fn reaper<'host>(
        &self,
        host: &'host Host,
    ) -> Option<impl Deref<Target = RootedRc<RootedRefCell<Process>>> + 'host> {
        let parent_pid = self.common.parent_pid.get();
        if parent_pid == ProcessId::INIT {
            return None;
        }
        let parentrc = host.process_borrow(parent_pid)?;

        // If the parent has *explicitly* ignored the exit signal, then it
        // doesn't reap.
        //
        // `waitpid(2)`:
        // > POSIX.1-2001 specifies that if the disposition of SIGCHLD is set to SIG_IGN or the SA_NOCLDWAIT flag is set for SIGCHLD  (see
        // > sigaction(2)),  then  children  that  terminate  do not become zombies and a call to wait() or waitpid() will block until all
        // > children have terminated, and then fail with errno set to ECHILD.  (The original POSIX standard left the behavior of  setting
        // > SIGCHLD to SIG_IGN unspecified.  Note that even though the default disposition of SIGCHLD is "ignore", explicitly setting the
        // > disposition to SIG_IGN results in different treatment of zombie process children.)
        //
        // TODO: validate that this applies to whatever signal is configured as the exit
        // signal, even if it's not SIGCHLD.
        if let Some(exit_signal) = self.common.exit_signal {
            let parent = parentrc.borrow(host.root());
            let parent_shmem = parent.shmem();
            let host_shmem_lock = host.shim_shmem_lock_borrow().unwrap();
            let parent_shmem_protected = parent_shmem.protected.borrow(&host_shmem_lock.root);
            // SAFETY: We don't dereference function pointers.
            let action = unsafe { parent_shmem_protected.signal_action(exit_signal) };
            if action.is_ignore() {
                return None;
            }
        }

        Some(parentrc)
    }

    fn notify_parent_of_exit(&self, host: &Host) {
        let Some(exit_signal) = self.common.exit_signal else {
            trace!("Not notifying parent of exit: no signal specified");
            return;
        };
        let parent_pid = self.common.parent_pid.get();
        if parent_pid == ProcessId::INIT {
            trace!("Not notifying parent of exit: parent is 'init'");
            return;
        }
        let Some(parent_rc) = host.process_borrow(parent_pid) else {
            trace!("Not notifying parent of exit: parent {parent_pid:?} not found");
            return;
        };
        let parent = parent_rc.borrow(host.root());
        let siginfo = self.exit_siginfo(exit_signal);

        let Some(parent_runnable) = parent.as_runnable() else {
            trace!("Not notifying parent of exit: {parent_pid:?} not running");
            debug_panic!("Non-running parent process shouldn't be possible.");
            #[allow(unreachable_code)]
            {
                return;
            }
        };
        parent_runnable.signal(host, None, &siginfo);
        CallbackQueue::queue_and_run_with_legacy(|q| {
            let mut parent_child_listeners =
                parent_runnable.child_process_event_listeners.borrow_mut();
            parent_child_listeners.notify_listeners(
                FileState::CHILD_EVENT,
                FileState::CHILD_EVENT,
                FileSignals::empty(),
                q,
            );
        });
    }

    /// Construct a siginfo containing information about how the process exited.
    /// Used internally to send a signal to the parent process, and by the
    /// `waitid` syscall handler.
    ///
    /// `exit_signal` is the signal to set in the `siginfo_t`.
    pub fn exit_siginfo(&self, exit_signal: Signal) -> siginfo_t {
        match self.exit_status {
            ExitStatus::Normal(exit_code) => siginfo_t::new_for_sigchld_exited(
                exit_signal,
                self.common.id.into(),
                0,
                exit_code,
                0,
                0,
            ),
            ExitStatus::Signaled(fatal_signal) => {
                // This ought to be `siginfo_t::new_for_sigchld_dumped` if
                // the child dumped core, but that depends on various other
                // system variables outside of our control. We always report
                // that no core was dropped for determinism.
                siginfo_t::new_for_sigchld_killed(
                    exit_signal,
                    self.common.id.into(),
                    0,
                    fatal_signal,
                    0,
                    0,
                )
            }

            ExitStatus::StoppedByShadow => unreachable!(),
        }
    }
}

/// Inner implementation of a simulated process.
enum ProcessState {
    Runnable(RunnableProcess),
    Zombie(ZombieProcess),
}

impl ProcessState {
    fn common(&self) -> &Common {
        match self {
            ProcessState::Runnable(r) => &r.common,
            ProcessState::Zombie(z) => &z.common,
        }
    }

    fn common_mut(&mut self) -> &mut Common {
        match self {
            ProcessState::Runnable(r) => &mut r.common,
            ProcessState::Zombie(z) => &mut z.common,
        }
    }

    fn as_runnable(&self) -> Option<&RunnableProcess> {
        match self {
            ProcessState::Runnable(r) => Some(r),
            ProcessState::Zombie(_) => None,
        }
    }

    fn as_runnable_mut(&mut self) -> Option<&mut RunnableProcess> {
        match self {
            ProcessState::Runnable(r) => Some(r),
            ProcessState::Zombie(_) => None,
        }
    }

    fn as_zombie(&self) -> Option<&ZombieProcess> {
        match self {
            ProcessState::Runnable(_) => None,
            ProcessState::Zombie(z) => Some(z),
        }
    }
}

impl ExplicitDrop for ProcessState {
    type ExplicitDropParam = Host;
    type ExplicitDropResult = ();

    fn explicit_drop(self, host: &Self::ExplicitDropParam) -> Self::ExplicitDropResult {
        match self {
            ProcessState::Runnable(r) => r.explicit_drop(host),
            ProcessState::Zombie(_) => (),
        }
    }
}

/// A simulated process.
pub struct Process {
    // Most of the implementation should be in [`ProcessState`].
    // This wrapper allows us to change the state.
    state: RefCell<Option<ProcessState>>,
}

fn itimer_real_expiration(host: &Host, pid: ProcessId) {
    let Some(process) = host.process_borrow(pid) else {
        debug!("Process {:?} no longer exists", pid);
        return;
    };
    let process = process.borrow(host.root());
    let Some(runnable) = process.as_runnable() else {
        debug!("Process {:?} no longer running", &*process.name());
        return;
    };
    let timer = runnable.itimer_real.borrow();
    // The siginfo_t structure only has an i32. Presumably we want to just truncate in
    // case of overflow.
    let expiration_count = timer.expiration_count() as i32;
    let siginfo_t = siginfo_t::new_for_timer(Signal::SIGALRM, 0, expiration_count);
    process.signal(host, None, &siginfo_t);
}

impl Process {
    fn common(&self) -> Ref<Common> {
        Ref::map(self.state.borrow(), |state| {
            state.as_ref().unwrap().common()
        })
    }

    fn common_mut(&self) -> RefMut<Common> {
        RefMut::map(self.state.borrow_mut(), |state| {
            state.as_mut().unwrap().common_mut()
        })
    }

    fn as_runnable(&self) -> Option<Ref<RunnableProcess>> {
        Ref::filter_map(self.state.borrow(), |state| {
            state.as_ref().unwrap().as_runnable()
        })
        .ok()
    }

    fn as_runnable_mut(&self) -> Option<RefMut<RunnableProcess>> {
        RefMut::filter_map(self.state.borrow_mut(), |state| {
            state.as_mut().unwrap().as_runnable_mut()
        })
        .ok()
    }

    /// Borrows a reference to the internal [`RunnableProcess`] if `self` is runnable.
    pub fn borrow_as_runnable(&self) -> Option<impl Deref<Target = RunnableProcess> + '_> {
        self.as_runnable()
    }

    fn as_zombie(&self) -> Option<Ref<ZombieProcess>> {
        Ref::filter_map(self.state.borrow(), |state| {
            state.as_ref().unwrap().as_zombie()
        })
        .ok()
    }

    /// Borrows a reference to the internal [`ZombieProcess`] if `self` is a zombie.
    pub fn borrow_as_zombie(&self) -> Option<impl Deref<Target = ZombieProcess> + '_> {
        self.as_zombie()
    }

    /// Spawn a new process. The process will be runnable via [`Self::resume`]
    /// once it has been added to the `Host`'s process list.
    pub fn spawn(
        host: &Host,
        plugin_name: CString,
        plugin_path: &CStr,
        argv: Vec<CString>,
        envv: Vec<CString>,
        pause_for_debugging: bool,
        strace_logging_options: Option<FmtOptions>,
        expected_final_state: ProcessFinalState,
    ) -> Result<RootedRc<RootedRefCell<Process>>, Errno> {
        debug!("starting process '{:?}'", plugin_name);

        let main_thread_id = host.get_new_thread_id();
        let process_id = ProcessId::from(main_thread_id);

        let desc_table = RootedRc::new(
            host.root(),
            RootedRefCell::new(host.root(), DescriptorTable::new()),
        );
        let itimer_real = RefCell::new(Timer::new(move |host| {
            itimer_real_expiration(host, process_id)
        }));

        let name = make_name(host, plugin_name.to_str().unwrap(), process_id);

        let mut file_basename = PathBuf::new();
        file_basename.push(host.data_dir_path());
        file_basename.push(format!(
            "{exe_name}.{id}",
            exe_name = plugin_name.to_str().unwrap(),
            id = u32::from(process_id)
        ));

        let strace_logging = strace_logging_options.map(|options| {
            let file =
                std::fs::File::create(Self::static_output_file_name(&file_basename, "strace"))
                    .unwrap();
            debug_assert_cloexec(&file);
            Arc::new(StraceLogging {
                file: RootedRefCell::new(host.root(), file),
                options,
            })
        });

        let shim_shared_mem = ProcessShmem::new(
            &host.shim_shmem_lock_borrow().unwrap().root,
            host.shim_shmem().serialize(),
            host.id(),
            strace_logging
                .as_ref()
                .map(|x| x.file.borrow(host.root()).as_raw_fd()),
        );
        let shim_shared_mem_block = shadow_shmem::allocator::shmalloc(shim_shared_mem);

        let working_dir = utility::pathbuf_to_nul_term_cstring(
            std::fs::canonicalize(host.data_dir_path()).unwrap(),
        );

        #[cfg(feature = "perf_timers")]
        let cpu_delay_timer = {
            let mut t = PerfTimer::new();
            t.stop();
            RefCell::new(t)
        };

        // TODO: measure execution time of creating the main_thread with
        // cpu_delay_timer? We previously did, but it's a little complex to do so,
        // and it shouldn't matter much.

        {
            let mut descriptor_table = desc_table.borrow_mut(host.root());
            Self::open_stdio_file_helper(
                &mut descriptor_table,
                libc::STDIN_FILENO.try_into().unwrap(),
                "/dev/null".into(),
                OFlag::O_RDONLY,
            );

            let name = Self::static_output_file_name(&file_basename, "stdout");
            Self::open_stdio_file_helper(
                &mut descriptor_table,
                libc::STDOUT_FILENO.try_into().unwrap(),
                name,
                OFlag::O_WRONLY,
            );

            let name = Self::static_output_file_name(&file_basename, "stderr");
            Self::open_stdio_file_helper(
                &mut descriptor_table,
                libc::STDERR_FILENO.try_into().unwrap(),
                name,
                OFlag::O_WRONLY,
            );
        }

        let shimlog_file = Arc::new(
            std::fs::File::create(Self::static_output_file_name(&file_basename, "shimlog"))
                .unwrap(),
        );
        debug_assert_cloexec(&shimlog_file);

        let mthread = ManagedThread::spawn(
            plugin_path,
            argv,
            envv,
            strace_logging
                .as_ref()
                .map(|s| s.file.borrow(host.root()))
                .as_deref(),
            &shimlog_file,
            host.preload_paths(),
        )?;
        let native_pid = mthread.native_pid();
        let main_thread =
            Thread::wrap_mthread(host, mthread, desc_table, process_id, main_thread_id).unwrap();

        debug!("process '{:?}' started", plugin_name);

        if pause_for_debugging {
            // will block until logger output has been flushed
            // there is a race condition where other threads may log between the
            // `eprintln` and `raise` below, but it should be rare
            log::logger().flush();

            // Use a single `eprintln` to ensure we hold the lock for the whole message.
            // Defensively pre-construct a single string so that `eprintln` is
            // more likely to use a single `write` call, to minimize the chance
            // of more lines being written to stdout in the meantime, and in
            // case of C code writing to `STDERR` directly without taking Rust's
            // lock.
            let msg = format!(
                "\
              \n** Pausing with SIGTSTP to enable debugger attachment to managed process\
              \n** '{plugin_name:?}' (pid {native_pid:?}).\
              \n** If running Shadow under Bash, resume Shadow by pressing Ctrl-Z to background\
              \n** this task, and then typing \"fg\".\
              \n** If running GDB, resume Shadow by typing \"signal SIGCONT\"."
            );
            eprintln!("{}", msg);

            rustix::process::kill_process(rustix::process::getpid(), rustix::process::Signal::Tstp)
                .unwrap();
        }

        let memory_manager = unsafe { MemoryManager::new(native_pid) };
        let threads = RefCell::new(BTreeMap::from([(
            main_thread_id,
            RootedRc::new(host.root(), RootedRefCell::new(host.root(), main_thread)),
        )]));

        let common = Common {
            id: process_id,
            host_id: host.id(),
            working_dir,
            name,
            plugin_name,
            parent_pid: Cell::new(ProcessId::INIT),
            group_id: Cell::new(ProcessId::INIT),
            session_id: Cell::new(ProcessId::INIT),
            // Exit signal is moot; since parent is INIT there will never
            // be a valid target for it.
            exit_signal: None,
        };
        Ok(RootedRc::new(
            host.root(),
            RootedRefCell::new(
                host.root(),
                Self {
                    state: RefCell::new(Some(ProcessState::Runnable(RunnableProcess {
                        common,
                        expected_final_state: Some(expected_final_state),
                        shim_shared_mem_block,
                        memory_manager: Box::new(RefCell::new(memory_manager)),
                        itimer_real,
                        strace_logging,
                        dumpable: Cell::new(SuidDump::SUID_DUMP_USER),
                        native_pid,
                        unsafe_borrow_mut: RefCell::new(None),
                        unsafe_borrows: RefCell::new(Vec::new()),
                        threads,
                        #[cfg(feature = "perf_timers")]
                        cpu_delay_timer,
                        #[cfg(feature = "perf_timers")]
                        total_run_time: Cell::new(Duration::ZERO),
                        child_process_event_listeners: Default::default(),
                        shimlog_file,
                    }))),
                },
            ),
        ))
    }

    pub fn id(&self) -> ProcessId {
        self.common().id
    }

    pub fn parent_id(&self) -> ProcessId {
        self.common().parent_pid.get()
    }

    pub fn set_parent_id(&self, pid: ProcessId) {
        self.common().parent_pid.set(pid)
    }

    pub fn group_id(&self) -> ProcessId {
        self.common().group_id.get()
    }

    pub fn set_group_id(&self, id: ProcessId) {
        self.common().group_id.set(id)
    }

    pub fn session_id(&self) -> ProcessId {
        self.common().session_id.get()
    }

    pub fn set_session_id(&self, id: ProcessId) {
        self.common().session_id.set(id)
    }

    pub fn host_id(&self) -> HostId {
        self.common().host_id
    }

    /// Get process's "dumpable" state, as manipulated by the prctl operations `PR_SET_DUMPABLE` and
    /// `PR_GET_DUMPABLE`.
    pub fn dumpable(&self) -> SuidDump {
        self.as_runnable().unwrap().dumpable.get()
    }

    /// Set process's "dumpable" state, as manipulated by the prctl operations `PR_SET_DUMPABLE` and
    /// `PR_GET_DUMPABLE`.
    pub fn set_dumpable(&self, val: SuidDump) {
        assert!(val == SuidDump::SUID_DUMP_DISABLE || val == SuidDump::SUID_DUMP_USER);
        self.as_runnable().unwrap().dumpable.set(val)
    }

    /// Deprecated wrapper for `RunnableProcess::start_cpu_delay_timer`
    #[cfg(feature = "perf_timers")]
    pub fn start_cpu_delay_timer(&self) {
        self.as_runnable().unwrap().start_cpu_delay_timer()
    }

    /// Deprecated wrapper for `RunnableProcess::stop_cpu_delay_timer`
    #[cfg(feature = "perf_timers")]
    pub fn stop_cpu_delay_timer(&self, host: &Host) -> Duration {
        self.as_runnable().unwrap().stop_cpu_delay_timer(host)
    }

    pub fn thread_group_leader_id(&self) -> ThreadId {
        self.common().thread_group_leader_id()
    }

    /// Resume execution of `tid` (if it exists).
    /// Should only be called from `Host::resume`.
    pub fn resume(&self, host: &Host, tid: ThreadId) {
        trace!("Continuing thread {} in process {}", tid, self.id());

        let threadrc = {
            let Some(runnable) = self.as_runnable() else {
                debug!("Process {} is no longer running", &*self.name());
                return;
            };
            let threads = runnable.threads.borrow();
            let Some(thread) = threads.get(&tid) else {
                debug!("Thread {} no longer exists", tid);
                return;
            };
            // Clone the thread reference, so that we don't hold a dynamically
            // borrowed reference to the thread list while running the thread.
            thread.clone(host.root())
        };
        let threadrc = ExplicitDropper::new(threadrc, |t| {
            t.explicit_drop_recursive(host.root(), host);
        });
        let thread = threadrc.borrow(host.root());

        Worker::set_active_thread(&threadrc);

        #[cfg(feature = "perf_timers")]
        self.start_cpu_delay_timer();

        Process::set_shared_time(host);

        // Discard any unapplied latency.
        // We currently only want this mechanism to force a yield if the thread itself
        // never yields; we don't want unapplied latency to accumulate and force a yield
        // under normal circumstances.
        host.shim_shmem_lock_borrow_mut()
            .unwrap()
            .unapplied_cpu_latency = SimulationTime::ZERO;

        let ctx = ProcessContext::new(host, self);
        let res = thread.resume(&ctx);

        #[cfg(feature = "perf_timers")]
        {
            let delay = self.stop_cpu_delay_timer(host);
            debug!("process '{}' ran for {:?}", &*self.name(), delay);
        }
        #[cfg(not(feature = "perf_timers"))]
        debug!("process '{}' done continuing", &*self.name());

        match res {
            crate::host::thread::ResumeResult::Blocked => {
                debug!(
                    "thread {tid} in process '{}' still running, but blocked",
                    &*self.name()
                );
            }
            crate::host::thread::ResumeResult::ExitedThread(return_code) => {
                debug!(
                    "thread {tid} in process '{}' exited with code {return_code}",
                    &*self.name(),
                );
                let (threadrc, last_thread) = {
                    let runnable = self.as_runnable().unwrap();
                    let mut threads = runnable.threads.borrow_mut();
                    let threadrc = threads.remove(&tid).unwrap();
                    (threadrc, threads.is_empty())
                };
                self.as_runnable().unwrap().reap_thread(host, threadrc);
                if last_thread {
                    self.handle_process_exit(host, false);
                }
            }
            crate::host::thread::ResumeResult::ExitedProcess => {
                debug!(
                    "Process {} exited while running thread {tid}",
                    &*self.name(),
                );
                self.handle_process_exit(host, false);
            }
        };

        Worker::clear_active_thread();
    }

    /// Terminate the Process.
    ///
    /// Should only be called from [`Host::free_all_applications`].
    pub fn stop(&self, host: &Host) {
        // Scope for `runnable`
        {
            let Some(runnable) = self.as_runnable() else {
                debug!("process {} has already stopped", &*self.name());
                return;
            };
            debug!("terminating process {}", &*self.name());

            #[cfg(feature = "perf_timers")]
            runnable.start_cpu_delay_timer();

            if let Err(err) = rustix::process::kill_process(
                runnable.native_pid().into(),
                rustix::process::Signal::Kill,
            ) {
                warn!("kill: {:?}", err);
            }

            #[cfg(feature = "perf_timers")]
            {
                let delay = runnable.stop_cpu_delay_timer(host);
                debug!("process '{}' stopped in {:?}", &*self.name(), delay);
            }
            #[cfg(not(feature = "perf_timers"))]
            debug!("process '{}' stopped", &*self.name());
        }

        // Mutates `self.state`, so we need to have dropped `runnable`.
        self.handle_process_exit(host, true);
    }

    /// See `RunnableProcess::signal`.
    ///
    /// No-op if the `self` is a `ZombieProcess`.
    pub fn signal(&self, host: &Host, current_thread: Option<&Thread>, siginfo_t: &siginfo_t) {
        // Using full-match here to force update if we add more states later.
        match self.state.borrow().as_ref().unwrap() {
            ProcessState::Runnable(r) => r.signal(host, current_thread, siginfo_t),
            ProcessState::Zombie(_) => {
                // Sending a signal to a zombie process is a no-op.
                debug!("Process {} no longer running", &*self.name());
            }
        }
    }

    fn open_stdio_file_helper(
        descriptor_table: &mut DescriptorTable,
        fd: DescriptorHandle,
        path: PathBuf,
        access_mode: OFlag,
    ) {
        let stdfile = unsafe { cshadow::regularfile_new() };
        let cwd = rustix::process::getcwd(Vec::new()).unwrap();
        let path = utility::pathbuf_to_nul_term_cstring(path);
        // "Convert" to libc int, assuming here that the kernel's `OFlag` values
        // are compatible with libc's values.
        // XXX: We're assuming here that the kernel and libc flags are ABI
        // compatible, which isn't guaranteed, but is mostly true in practice.
        // TODO: We probably ought to change `regularfile_open` and friends to
        // use a direct syscall instead of libc's wrappers, and explicitly take
        // the kernel version of flags, mode, etc.
        let access_mode = access_mode.bits();
        let errorcode = unsafe {
            cshadow::regularfile_open(
                stdfile,
                path.as_ptr(),
                access_mode | libc::O_CREAT | libc::O_TRUNC,
                libc::S_IRUSR | libc::S_IWUSR | libc::S_IRGRP | libc::S_IROTH,
                cwd.as_ptr(),
            )
        };
        if errorcode != 0 {
            panic!(
                "Opening {}: {:?}",
                path.to_str().unwrap(),
                linux_api::errno::Errno::try_from(-errorcode).unwrap()
            );
        }
        let desc = unsafe {
            Descriptor::from_legacy_file(
                stdfile as *mut cshadow::LegacyFile,
                linux_api::fcntl::OFlag::empty(),
            )
        };
        let prev = descriptor_table.register_descriptor_with_fd(desc, fd);
        assert!(prev.is_none());
        trace!(
            "Successfully opened fd {} at {}",
            fd,
            path.to_str().unwrap()
        );
    }

    // Needed during early init, before `Self` is created.
    fn static_output_file_name(file_basename: &Path, extension: &str) -> PathBuf {
        let mut path = file_basename.to_owned().into_os_string();
        path.push(".");
        path.push(extension);
        path.into()
    }

    pub fn name(&self) -> impl Deref<Target = str> + '_ {
        Ref::map(self.common(), |c| c.name.to_str().unwrap())
    }

    pub fn plugin_name(&self) -> impl Deref<Target = str> + '_ {
        Ref::map(self.common(), |c| c.plugin_name.to_str().unwrap())
    }

    /// Deprecated wrapper for `RunnableProcess::memory_borrow_mut`
    #[track_caller]
    pub fn memory_borrow_mut(&self) -> impl DerefMut<Target = MemoryManager> + '_ {
        std_util::nested_ref::NestedRefMut::map(self.as_runnable().unwrap(), |runnable| {
            runnable.memory_manager.borrow_mut()
        })
    }

    /// Deprecated wrapper for `RunnableProcess::memory_borrow`
    #[track_caller]
    pub fn memory_borrow(&self) -> impl Deref<Target = MemoryManager> + '_ {
        std_util::nested_ref::NestedRef::map(self.as_runnable().unwrap(), |runnable| {
            runnable.memory_manager.borrow()
        })
    }

    /// Deprecated wrapper for `RunnableProcess::strace_logging_options`
    pub fn strace_logging_options(&self) -> Option<FmtOptions> {
        self.as_runnable().unwrap().strace_logging_options()
    }

    /// Deprecated wrapper for `RunnableProcess::with_strace_file`
    pub fn with_strace_file<T>(&self, f: impl FnOnce(&mut std::fs::File) -> T) -> Option<T> {
        self.as_runnable().unwrap().with_strace_file(f)
    }

    /// Deprecated wrapper for `RunnableProcess::native_pid`
    pub fn native_pid(&self) -> Pid {
        self.as_runnable().unwrap().native_pid()
    }

    /// Deprecated wrapper for `RunnableProcess::realtime_timer_borrow`
    #[track_caller]
    pub fn realtime_timer_borrow(&self) -> impl Deref<Target = Timer> + '_ {
        std_util::nested_ref::NestedRef::map(self.as_runnable().unwrap(), |runnable| {
            runnable.itimer_real.borrow()
        })
    }

    /// Deprecated wrapper for `RunnableProcess::realtime_timer_borrow_mut`
    #[track_caller]
    pub fn realtime_timer_borrow_mut(&self) -> impl DerefMut<Target = Timer> + '_ {
        std_util::nested_ref::NestedRefMut::map(self.as_runnable().unwrap(), |runnable| {
            runnable.itimer_real.borrow_mut()
        })
    }

    /// Deprecated wrapper for `RunnableProcess::first_live_thread_borrow`
    #[track_caller]
    pub fn first_live_thread_borrow(
        &self,
        root: &Root,
    ) -> Option<impl Deref<Target = RootedRc<RootedRefCell<Thread>>> + '_> {
        std_util::nested_ref::NestedRef::filter_map(self.as_runnable()?, |runnable| {
            runnable.first_live_thread(root)
        })
    }

    /// Deprecated wrapper for `RunnableProcess::thread_borrow`
    pub fn thread_borrow(
        &self,
        virtual_tid: ThreadId,
    ) -> Option<impl Deref<Target = RootedRc<RootedRefCell<Thread>>> + '_> {
        std_util::nested_ref::NestedRef::filter_map(self.as_runnable()?, |runnable| {
            runnable.thread(virtual_tid)
        })
    }

    /// Deprecated wrapper for [`RunnableProcess::free_unsafe_borrows_flush`].
    pub fn free_unsafe_borrows_flush(&self) -> Result<(), Errno> {
        self.as_runnable().unwrap().free_unsafe_borrows_flush()
    }

    /// Deprecated wrapper for [`RunnableProcess::free_unsafe_borrows_noflush`].
    pub fn free_unsafe_borrows_noflush(&self) {
        self.as_runnable().unwrap().free_unsafe_borrows_noflush()
    }

    pub fn physical_address(&self, vptr: ForeignPtr<()>) -> ManagedPhysicalMemoryAddr {
        self.common().physical_address(vptr)
    }

    pub fn is_running(&self) -> bool {
        self.as_runnable().is_some()
    }

    /// Transitions `self` from a `RunnableProcess` to a `ZombieProcess`.
    fn handle_process_exit(&self, host: &Host, killed_by_shadow: bool) {
        debug!(
            "process '{}' has completed or is otherwise no longer running",
            &*self.name()
        );

        // Take and dispose of all of the threads.
        // TODO: consider doing this while the `self.state` mutable reference is held
        // as with the other cleanup below. Right now this breaks some C code that expects
        // to be able to lookup the thread's process name.
        {
            let runnable = self.as_runnable().unwrap();
            let threads = std::mem::take(&mut *runnable.threads.borrow_mut());
            for (_tid, threadrc) in threads.into_iter() {
                threadrc.borrow(host.root()).handle_process_exit();
                runnable.reap_thread(host, threadrc);
            }
        }

        // Intentionally hold the borrow on self.state to ensure the state
        // transition is "atomic".
        let mut opt_state = self.state.borrow_mut();

        let state = opt_state.take().unwrap();
        let ProcessState::Runnable(runnable) = state else {
            unreachable!("Tried to handle process exit of non-running process");
        };

        #[cfg(feature = "perf_timers")]
        debug!(
            "total runtime for process '{}' was {:?}",
            runnable.common.name(),
            runnable.total_run_time.get()
        );

        let wait_res: Option<WaitStatus> =
            rustix::process::waitpid(Some(runnable.native_pid().into()), WaitOptions::empty())
                .unwrap_or_else(|e| {
                    panic!("Error waiting for {:?}: {:?}", runnable.native_pid(), e)
                });
        let wait_status = wait_res.unwrap();
        let exit_status = if killed_by_shadow {
            if wait_status.terminating_signal()
                != Some(Signal::SIGKILL.as_i32().try_into().unwrap())
            {
                warn!("Unexpected waitstatus after killed by shadow: {wait_status:?}");
            }
            ExitStatus::StoppedByShadow
        } else if let Some(code) = wait_status.exit_status() {
            ExitStatus::Normal(code.try_into().unwrap())
        } else if let Some(signal) = wait_status.terminating_signal() {
            ExitStatus::Signaled(Signal::try_from(i32::try_from(signal).unwrap()).unwrap())
        } else {
            panic!(
                "Unexpected status: {wait_status:?} for pid {:?}",
                runnable.native_pid()
            );
        };

        let (main_result_string, log_level) = {
            let mut s = format!(
                "process '{name}' exited with status {exit_status:?}",
                name = runnable.common.name()
            );
            if let Some(expected_final_state) = runnable.expected_final_state {
                let actual_final_state = match exit_status {
                    ExitStatus::Normal(i) => ProcessFinalState::Exited { exited: i },
                    ExitStatus::Signaled(s) => ProcessFinalState::Signaled {
                        // This conversion will fail on realtime signals, but that
                        // should currently be impossible since we don't support
                        // sending realtime signals.
                        signaled: s.try_into().unwrap(),
                    },
                    ExitStatus::StoppedByShadow => ProcessFinalState::Running(RunningVal::Running),
                };
                if expected_final_state == actual_final_state {
                    (s, log::Level::Debug)
                } else {
                    Worker::increment_plugin_error_count();
                    write!(s, "; expected end state was {expected_final_state} but was {actual_final_state}").unwrap();
                    (s, log::Level::Error)
                }
            } else {
                (s, log::Level::Debug)
            }
        };
        log::log!(log_level, "{}", main_result_string);

        let zombie = ZombieProcess {
            common: runnable.into_common(),
            exit_status,
        };
        zombie.notify_parent_of_exit(host);

        *opt_state = Some(ProcessState::Zombie(zombie));
    }

    /// Deprecated wrapper for `RunnableProcess::add_thread`
    pub fn add_thread(&self, host: &Host, thread: RootedRc<RootedRefCell<Thread>>) {
        self.as_runnable().unwrap().add_thread(host, thread)
    }

    /// FIXME: still needed? Time is now updated more granularly in the Thread code
    /// when xferring control to/from shim.
    fn set_shared_time(host: &Host) {
        let mut host_shmem = host.shim_shmem_lock_borrow_mut().unwrap();
        host_shmem.max_runahead_time = Worker::max_event_runahead_time(host);
        host.shim_shmem()
            .sim_time
            .store(Worker::current_time().unwrap(), Ordering::Relaxed);
    }

    /// Deprecated wrapper for `RunnableProcess::shmem`
    pub fn shmem(&self) -> impl Deref<Target = ShMemBlock<'static, ProcessShmem>> + '_ {
        Ref::map(self.as_runnable().unwrap(), |r| &r.shim_shared_mem_block)
    }

    /// Resource usage, as returned e.g. by the `getrusage` syscall.
    pub fn rusage(&self) -> linux_api::resource::rusage {
        warn_once_then_debug!(
            "resource usage (rusage) tracking unimplemented; Returning bogus zeroed values"
        );
        // TODO: Actually track some of these.
        // Assuming we want to support `RUSAGE_THREAD` in the `getrusage`
        // syscall, we'll actually want to track at the thread level, and either
        // increment at both thread and process level at the points where we do
        // the tracking, or dynamically iterate over the threads here and sum
        // the results.
        linux_api::resource::rusage {
            ru_utime: linux_api::time::kernel_old_timeval {
                tv_sec: 0,
                tv_usec: 0,
            },
            ru_stime: linux_api::time::kernel_old_timeval {
                tv_sec: 0,
                tv_usec: 0,
            },
            ru_maxrss: 0,
            ru_ixrss: 0,
            ru_idrss: 0,
            ru_isrss: 0,
            ru_minflt: 0,
            ru_majflt: 0,
            ru_nswap: 0,
            ru_inblock: 0,
            ru_oublock: 0,
            ru_msgsnd: 0,
            ru_msgrcv: 0,
            ru_nsignals: 0,
            ru_nvcsw: 0,
            ru_nivcsw: 0,
        }
    }

    /// Signal that will be sent to parent process on exit. Typically `Some(SIGCHLD)`.
    pub fn exit_signal(&self) -> Option<Signal> {
        self.common().exit_signal
    }

    pub fn current_working_dir(&self) -> impl Deref<Target = CString> + '_ {
        Ref::map(self.common(), |common| &common.working_dir)
    }

    /// Set the process's working directory.
    /// This must be kept in sync with the actual working dir of the native process.
    /// See <https://github.com/shadow/shadow/issues/2960>
    // TODO: This ought to be at the thread level, to support `CLONE_FS`.
    pub fn set_current_working_dir(&self, path: CString) {
        self.common_mut().working_dir = path;
    }

    /// Update `self` to complete an `exec` syscall from thread `tid`, replacing
    /// the running managed process with `mthread`.
    pub fn update_for_exec(&mut self, host: &Host, tid: ThreadId, mthread: ManagedThread) {
        let Some(mut runnable) = self.as_runnable_mut() else {
            // This could happen if another event runs before the "execve completion" event
            // and kills the process. e.g. another thread in the process could run and
            // execute the `exit_group` syscall.
            log::debug!(
                "Process {:?} exited before it could complete execve",
                self.id()
            );
            mthread.kill_and_drop();
            return;
        };
        let old_native_pid = std::mem::replace(&mut runnable.native_pid, mthread.native_pid());

        // Kill the previous native process
        rustix::process::kill_process(old_native_pid.into(), rustix::process::Signal::Kill)
            .expect("Unable to send kill signal to managed process {old_native_pid:?}");
        let wait_res = rustix::process::waitpid(Some(old_native_pid.into()), WaitOptions::empty())
            .unwrap()
            .unwrap();
        assert_eq!(
            wait_res.terminating_signal(),
            Some(Signal::SIGKILL.as_i32().try_into().unwrap())
        );

        let execing_thread = runnable.threads.borrow_mut().remove(&tid).unwrap();

        // Dispose of all threads other than the thread that's running `exec`.
        for (_tid, thread) in runnable.threads.replace(BTreeMap::new()) {
            // Notify the ManagedThread that the native process has exited.
            thread.borrow(host.root()).mthread().handle_process_exit();

            thread.explicit_drop_recursive(host.root(), host);
        }

        // Recreate the `MemoryManager`
        {
            // We can't safely replace the memory manager if there are outstanding
            // unsafe references in C code. There shouldn't be any, though, since
            // this is only called from the `execve` and `execveat` syscall handlers,
            // which are in Rust.
            let unsafe_borrow_mut = runnable.unsafe_borrow_mut.borrow();
            let unsafe_borrows = runnable.unsafe_borrows.borrow();
            assert!(unsafe_borrow_mut.is_none());
            assert!(unsafe_borrows.is_empty());
            // Replace the MM, while still holding the references to the unsafe borrows
            // to ensure none exist.
            runnable
                .memory_manager
                .replace(unsafe { MemoryManager::new(mthread.native_pid()) });
        }

        let new_tid = runnable.common.thread_group_leader_id();
        log::trace!(
            "updating for exec; pid:{pid}, tid:{tid:?}, new_tid:{new_tid:?}",
            pid = runnable.common.id
        );
        execing_thread
            .borrow_mut(host.root())
            .update_for_exec(host, mthread, new_tid);

        runnable
            .threads
            .borrow_mut()
            .insert(new_tid, execing_thread);

        // Exit signal is reset to SIGCHLD.
        runnable.common.exit_signal = Some(Signal::SIGCHLD);

        // Reset signal actions to default.
        // `execve(2)`:
        // POSIX.1 specifies that the dispositions of any signals that
        // are ignored or set to the default are left unchanged.  POSIX.1
        // specifies one exception: if SIGCHLD is being ignored, then an
        // implementation may leave the disposition unchanged or reset it
        // to the default; Linux does the former.
        let host_shmem_prot = host.shim_shmem_lock_borrow_mut().unwrap();
        let mut shmem_prot = runnable
            .shim_shared_mem_block
            .protected
            .borrow_mut(&host_shmem_prot.root);
        for signal in Signal::standard_signals() {
            let current_action = unsafe { shmem_prot.signal_action(signal) };
            if !(current_action.is_default()
                || current_action.is_ignore()
                || signal == Signal::SIGCHLD && current_action.is_ignore())
            {
                unsafe {
                    *shmem_prot.signal_action_mut(signal) = linux_api::signal::sigaction::new_raw(
                        linux_api::signal::SignalHandler::SigDfl,
                        SigActionFlags::empty(),
                        sigset_t::EMPTY,
                        None,
                    )
                };
            }
        }
    }
}

impl Drop for Process {
    fn drop(&mut self) {
        // Should have been explicitly dropped.
        debug_assert!(self.state.borrow().is_none());
    }
}

impl ExplicitDrop for Process {
    type ExplicitDropParam = Host;
    type ExplicitDropResult = ();

    fn explicit_drop(mut self, host: &Self::ExplicitDropParam) -> Self::ExplicitDropResult {
        // Should normally only be dropped in the zombie state.
        debug_assert!(self.as_zombie().is_some() || std::thread::panicking());

        let state = self.state.get_mut().take().unwrap();
        state.explicit_drop(host);
    }
}

/// Tracks a memory reference made by a legacy C memory-read API.
struct UnsafeBorrow {
    // Must come before `manager`, so that it's dropped first, since it's
    // borrowed from it.
    _memory: ProcessMemoryRef<'static, u8>,
    _manager: Ref<'static, MemoryManager>,
}

impl UnsafeBorrow {
    /// Creates a raw readable pointer, and saves an instance of `Self` into
    /// `process` for later clean-up.
    ///
    /// # Safety
    ///
    /// The pointer is invalidated when one of the Process memory flush methods is called.
    unsafe fn readable_ptr(
        process: &Process,
        ptr: ForeignArrayPtr<u8>,
    ) -> Result<*const c_void, Errno> {
        let runnable = process.as_runnable().unwrap();
        let manager = runnable.memory_manager.borrow();
        // SAFETY: We ensure that the `memory` is dropped before the `manager`,
        // and `Process` ensures that this whole object is dropped before
        // `MemoryManager` can be moved, freed, etc.
        let manager = unsafe {
            std::mem::transmute::<Ref<'_, MemoryManager>, Ref<'static, MemoryManager>>(manager)
        };
        let memory = manager.memory_ref(ptr)?;
        let memory = unsafe {
            std::mem::transmute::<ProcessMemoryRef<'_, u8>, ProcessMemoryRef<'static, u8>>(memory)
        };
        let vptr = memory.as_ptr() as *mut c_void;
        runnable.unsafe_borrows.borrow_mut().push(Self {
            _manager: manager,
            _memory: memory,
        });
        Ok(vptr)
    }

    /// Creates a raw readable string, and saves an instance of `Self` into
    /// `process` for later clean-up.
    ///
    /// # Safety
    ///
    /// The pointer is invalidated when one of the Process memory flush methods is called.
    unsafe fn readable_string(
        process: &Process,
        ptr: ForeignArrayPtr<c_char>,
    ) -> Result<(*const c_char, libc::size_t), Errno> {
        let runnable = process.as_runnable().unwrap();
        let manager = runnable.memory_manager.borrow();
        // SAFETY: We ensure that the `memory` is dropped before the `manager`,
        // and `Process` ensures that this whole object is dropped before
        // `MemoryManager` can be moved, freed, etc.
        let manager = unsafe {
            std::mem::transmute::<Ref<'_, MemoryManager>, Ref<'static, MemoryManager>>(manager)
        };
        let ptr = ptr.cast_u8();
        let memory = manager.memory_ref_prefix(ptr)?;
        let memory = unsafe {
            std::mem::transmute::<ProcessMemoryRef<'_, u8>, ProcessMemoryRef<'static, u8>>(memory)
        };
        if !memory.contains(&0) {
            return Err(Errno::ENAMETOOLONG);
        }
        assert_eq!(std::mem::size_of::<c_char>(), std::mem::size_of::<u8>());
        let ptr = memory.as_ptr() as *const c_char;
        let len = memory.len();
        runnable.unsafe_borrows.borrow_mut().push(Self {
            _manager: manager,
            _memory: memory,
        });
        Ok((ptr, len))
    }
}

// Safety: Normally the Ref would make this non-Send, since it could end then
// end up trying to manipulate the source RefCell (which is !Sync) from multiple
// threads.  We ensure that these objects never escape Process, which itself is
// non-Sync, ensuring this doesn't happen.
//
// This is admittedly hand-wavy and making some assumptions about the
// implementation of RefCell, but this whole type is temporary scaffolding to
// support legacy C code.
unsafe impl Send for UnsafeBorrow {}

/// Tracks a memory reference made by a legacy C memory-write API.
struct UnsafeBorrowMut {
    // Must come before `manager`, so that it's dropped first, since it's
    // borrowed from it.
    memory: Option<ProcessMemoryRefMut<'static, u8>>,
    _manager: RefMut<'static, MemoryManager>,
}

impl UnsafeBorrowMut {
    /// Creates a raw writable pointer, and saves an instance of `Self` into
    /// `process` for later clean-up. The initial contents of the pointer is unspecified.
    ///
    /// # Safety
    ///
    /// The pointer is invalidated when one of the Process memory flush methods is called.
    unsafe fn writable_ptr(
        process: &Process,
        ptr: ForeignArrayPtr<u8>,
    ) -> Result<*mut c_void, Errno> {
        let runnable = process.as_runnable().unwrap();
        let manager = runnable.memory_manager.borrow_mut();
        // SAFETY: We ensure that the `memory` is dropped before the `manager`,
        // and `Process` ensures that this whole object is dropped before
        // `MemoryManager` can be moved, freed, etc.
        let mut manager = unsafe {
            std::mem::transmute::<RefMut<'_, MemoryManager>, RefMut<'static, MemoryManager>>(
                manager,
            )
        };
        let memory = manager.memory_ref_mut_uninit(ptr)?;
        let mut memory = unsafe {
            std::mem::transmute::<ProcessMemoryRefMut<'_, u8>, ProcessMemoryRefMut<'static, u8>>(
                memory,
            )
        };
        let vptr = memory.as_mut_ptr() as *mut c_void;
        let prev = runnable.unsafe_borrow_mut.borrow_mut().replace(Self {
            _manager: manager,
            memory: Some(memory),
        });
        assert!(prev.is_none());
        Ok(vptr)
    }

    /// Creates a raw mutable pointer, and saves an instance of `Self` into
    /// `process` for later clean-up.
    ///
    /// # Safety
    ///
    /// The pointer is invalidated when one of the Process memory flush methods is called.
    unsafe fn mutable_ptr(
        process: &Process,
        ptr: ForeignArrayPtr<u8>,
    ) -> Result<*mut c_void, Errno> {
        let runnable = process.as_runnable().unwrap();
        let manager = runnable.memory_manager.borrow_mut();
        // SAFETY: We ensure that the `memory` is dropped before the `manager`,
        // and `Process` ensures that this whole object is dropped before
        // `MemoryManager` can be moved, freed, etc.
        let mut manager = unsafe {
            std::mem::transmute::<RefMut<'_, MemoryManager>, RefMut<'static, MemoryManager>>(
                manager,
            )
        };
        let memory = manager.memory_ref_mut(ptr)?;
        let mut memory = unsafe {
            std::mem::transmute::<ProcessMemoryRefMut<'_, u8>, ProcessMemoryRefMut<'static, u8>>(
                memory,
            )
        };
        let vptr = memory.as_mut_ptr() as *mut c_void;
        let prev = runnable.unsafe_borrow_mut.borrow_mut().replace(Self {
            _manager: manager,
            memory: Some(memory),
        });
        assert!(prev.is_none());
        Ok(vptr)
    }

    /// Free this reference, writing back to process memory.
    fn flush(mut self) -> Result<(), Errno> {
        self.memory.take().unwrap().flush()
    }

    /// Free this reference without writing back to process memory.
    fn noflush(mut self) {
        self.memory.take().unwrap().noflush()
    }
}

// Safety: Normally the RefMut would make this non-Send, since it could end then
// end up trying to manipulate the source RefCell (which is !Sync) from multiple
// threads.  We ensure that these objects never escape Process, which itself is
// non-Sync, ensuring this doesn't happen.
//
// This is admittedly hand-wavy and making some assumptions about the implementation of
// RefCell, but this whole type is temporary scaffolding to support legacy C code.
unsafe impl Send for UnsafeBorrowMut {}

fn make_name(host: &Host, exe_name: &str, id: ProcessId) -> CString {
    CString::new(format!(
        "{host_name}.{exe_name}.{id}",
        host_name = host.name(),
        exe_name = exe_name,
        id = u32::from(id)
    ))
    .unwrap()
}

mod export {
    use std::os::raw::c_void;

    use libc::size_t;
    use log::trace;
    use shadow_shim_helper_rs::notnull::*;
    use shadow_shim_helper_rs::shim_shmem::export::ShimShmemProcess;
    use shadow_shim_helper_rs::syscall_types::UntypedForeignPtr;

    use super::*;
    use crate::utility::HostTreePointer;

    /// Copy `n` bytes from `src` to `dst`. Returns 0 on success or -EFAULT if any of
    /// the specified range couldn't be accessed. Always succeeds with n==0.
    #[no_mangle]
    pub extern "C-unwind" fn process_readPtr(
        proc: *const Process,
        dst: *mut c_void,
        src: UntypedForeignPtr,
        n: usize,
    ) -> i32 {
        let proc = unsafe { proc.as_ref().unwrap() };
        let src = ForeignArrayPtr::new(src.cast::<u8>(), n);
        let dst = unsafe { std::slice::from_raw_parts_mut(notnull_mut_debug(dst) as *mut u8, n) };

        match proc.memory_borrow().copy_from_ptr(dst, src) {
            Ok(_) => 0,
            Err(e) => {
                trace!("Couldn't read {:?} into {:?}: {:?}", src, dst, e);
                e.to_negated_i32()
            }
        }
    }

    /// Copy `n` bytes from `src` to `dst`. Returns 0 on success or -EFAULT if any of
    /// the specified range couldn't be accessed. The write is flushed immediately.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_writePtr(
        proc: *const Process,
        dst: UntypedForeignPtr,
        src: *const c_void,
        n: usize,
    ) -> i32 {
        let proc = unsafe { proc.as_ref().unwrap() };
        let dst = ForeignArrayPtr::new(dst.cast::<u8>(), n);
        let src = unsafe { std::slice::from_raw_parts(notnull_debug(src) as *const u8, n) };
        match proc.memory_borrow_mut().copy_to_ptr(dst, src) {
            Ok(_) => 0,
            Err(e) => {
                trace!("Couldn't write {:?} into {:?}: {:?}", src, dst, e);
                e.to_negated_i32()
            }
        }
    }

    /// Make the data at plugin_src available in shadow's address space.
    ///
    /// The returned pointer is invalidated when one of the process memory flush
    /// methods is called; typically after a syscall has completed.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getReadablePtr(
        proc: *const Process,
        plugin_src: UntypedForeignPtr,
        n: usize,
    ) -> *const c_void {
        let proc = unsafe { proc.as_ref().unwrap() };
        let plugin_src = ForeignArrayPtr::new(plugin_src.cast::<u8>(), n);
        unsafe { UnsafeBorrow::readable_ptr(proc, plugin_src).unwrap_or(std::ptr::null()) }
    }

    /// Returns a writable pointer corresponding to the named region. The
    /// initial contents of the returned memory are unspecified.
    ///
    /// The returned pointer is invalidated when one of the process memory flush
    /// methods is called; typically after a syscall has completed.
    ///
    /// CAUTION: if the unspecified contents aren't overwritten, and the pointer
    /// isn't explicitly freed via `process_freePtrsWithoutFlushing`, those
    /// unspecified contents may be written back into process memory.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getWriteablePtr(
        proc: *const Process,
        plugin_src: UntypedForeignPtr,
        n: usize,
    ) -> *mut c_void {
        let proc = unsafe { proc.as_ref().unwrap() };
        let plugin_src = ForeignArrayPtr::new(plugin_src.cast::<u8>(), n);
        unsafe { UnsafeBorrowMut::writable_ptr(proc, plugin_src).unwrap_or(std::ptr::null_mut()) }
    }

    /// Returns a writeable pointer corresponding to the specified src. Use when
    /// the data at the given address needs to be both read and written.
    ///
    /// The returned pointer is invalidated when one of the process memory flush
    /// methods is called; typically after a syscall has completed.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getMutablePtr(
        proc: *const Process,
        plugin_src: UntypedForeignPtr,
        n: usize,
    ) -> *mut c_void {
        let proc = unsafe { proc.as_ref().unwrap() };
        let plugin_src = ForeignArrayPtr::new(plugin_src.cast::<u8>(), n);
        unsafe { UnsafeBorrowMut::mutable_ptr(proc, plugin_src).unwrap_or(std::ptr::null_mut()) }
    }

    /// Reads up to `n` bytes into `str`.
    ///
    /// Returns:
    /// strlen(str) on success.
    /// -ENAMETOOLONG if there was no NULL byte in the first `n` characters.
    /// -EFAULT if the string extends beyond the accessible address space.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_readString(
        proc: *const Process,
        strbuf: *mut libc::c_char,
        ptr: UntypedForeignPtr,
        maxlen: libc::size_t,
    ) -> libc::ssize_t {
        let proc = unsafe { proc.as_ref().unwrap() };
        let memory_manager = proc.memory_borrow();
        let buf =
            unsafe { std::slice::from_raw_parts_mut(notnull_mut_debug(strbuf) as *mut u8, maxlen) };
        let cstr = match memory_manager
            .copy_str_from_ptr(buf, ForeignArrayPtr::new(ptr.cast::<u8>(), maxlen))
        {
            Ok(cstr) => cstr,
            Err(e) => return e.to_negated_i32() as isize,
        };
        cstr.to_bytes().len().try_into().unwrap()
    }

    /// Reads up to `n` bytes into `str`.
    ///
    /// Returns:
    /// strlen(str) on success.
    /// -ENAMETOOLONG if there was no NULL byte in the first `n` characters.
    /// -EFAULT if the string extends beyond the accessible address space.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getReadableString(
        proc: *const Process,
        plugin_src: UntypedForeignPtr,
        n: usize,
        out_str: *mut *const c_char,
        out_strlen: *mut size_t,
    ) -> i32 {
        let proc = unsafe { proc.as_ref().unwrap() };
        let ptr = ForeignArrayPtr::new(plugin_src.cast::<c_char>(), n);
        match unsafe { UnsafeBorrow::readable_string(proc, ptr) } {
            Ok((str, strlen)) => {
                assert!(!out_str.is_null());
                unsafe { out_str.write(str) };
                if !out_strlen.is_null() {
                    unsafe { out_strlen.write(strlen) };
                }
                0
            }
            Err(e) => e.to_negated_i32(),
        }
    }

    /// Returns the processID that was assigned to us in process_new
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getProcessID(proc: *const Process) -> libc::pid_t {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.id().into()
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getName(proc: *const Process) -> *const c_char {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.common().name.as_ptr()
    }

    /// Safety:
    ///
    /// The returned pointer is invalidated when the host shmem lock is released, e.g. via
    /// Host::unlock_shmem.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getSharedMem(
        proc: *const Process,
    ) -> *const ShimShmemProcess {
        let proc = unsafe { proc.as_ref().unwrap() };
        std::ptr::from_ref(proc.as_runnable().unwrap().shim_shared_mem_block.deref())
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getWorkingDir(proc: *const Process) -> *const c_char {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.common().working_dir.as_ptr()
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_straceLoggingMode(
        proc: *const Process,
    ) -> StraceFmtMode {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.strace_logging_options().into()
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getNativePid(proc: *const Process) -> libc::pid_t {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.native_pid().as_raw_nonzero().get()
    }

    /// Flushes and invalidates all previously returned readable/writable plugin
    /// pointers, as if returning control to the plugin. This can be useful in
    /// conjunction with `thread_nativeSyscall` operations that touch memory, or
    /// to gracefully handle failed writes.
    ///
    /// Returns 0 on success or a negative errno on failure.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_flushPtrs(proc: *const Process) -> i32 {
        let proc = unsafe { proc.as_ref().unwrap() };
        match proc.free_unsafe_borrows_flush() {
            Ok(_) => 0,
            Err(e) => e.to_negated_i32(),
        }
    }

    /// Frees all readable/writable foreign pointers. Unlike process_flushPtrs, any
    /// previously returned writable pointer is *not* written back. Useful
    /// if an uninitialized writable pointer was obtained via `process_getWriteablePtr`,
    /// and we end up not wanting to write anything after all (in particular, don't
    /// write back whatever garbage data was in the uninialized bueffer).
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_freePtrsWithoutFlushing(proc: *const Process) {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.free_unsafe_borrows_noflush();
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getThread(
        proc: *const Process,
        tid: libc::pid_t,
    ) -> *const Thread {
        let proc = unsafe { proc.as_ref().unwrap() };
        Worker::with_active_host(|host| {
            let tid = ThreadId::try_from(tid).unwrap();
            let Some(thread) = proc.thread_borrow(tid) else {
                return std::ptr::null();
            };
            let thread = thread.borrow(host.root());
            &*thread
        })
        .unwrap()
    }

    /// Returns a pointer to an arbitrary live thread in the process.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_firstLiveThread(proc: *const Process) -> *const Thread {
        let proc = unsafe { proc.as_ref().unwrap() };
        Worker::with_active_host(|host| {
            let Some(thread) = proc.first_live_thread_borrow(host.root()) else {
                return std::ptr::null();
            };
            let thread = thread.borrow(host.root());
            &*thread
        })
        .unwrap()
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_isRunning(proc: *const Process) -> bool {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.is_running()
    }

    // FIXME: still needed? Time is now updated more granularly in the Thread code
    // when xferring control to/from shim.
    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_setSharedTime() {
        Worker::with_active_host(Process::set_shared_time).unwrap();
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_getPhysicalAddress(
        proc: *const Process,
        vptr: UntypedForeignPtr,
    ) -> ManagedPhysicalMemoryAddr {
        let proc = unsafe { proc.as_ref().unwrap() };
        proc.physical_address(vptr)
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_addChildEventListener(
        host: *const Host,
        process: *const Process,
        listener: *mut cshadow::StatusListener,
    ) {
        let host = unsafe { host.as_ref().unwrap() };
        let process = unsafe { process.as_ref().unwrap() };
        let listener = HostTreePointer::new_for_host(host.id(), listener);
        process
            .borrow_as_runnable()
            .unwrap()
            .child_process_event_listeners
            .borrow_mut()
            .add_legacy_listener(listener)
    }

    #[no_mangle]
    pub unsafe extern "C-unwind" fn process_removeChildEventListener(
        _host: *const Host,
        process: *const Process,
        listener: *mut cshadow::StatusListener,
    ) {
        let process = unsafe { process.as_ref().unwrap() };
        process
            .borrow_as_runnable()
            .unwrap()
            .child_process_event_listeners
            .borrow_mut()
            .remove_legacy_listener(listener)
    }
}