summaryrefslogtreecommitdiffstats
path: root/src/core/execute.c
blob: 1802ae05b30db4e6e9e891c47606f3d33709ca73 (plain)
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
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
/* SPDX-License-Identifier: LGPL-2.1-or-later */

#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/mount.h>
#include <sys/personality.h>
#include <sys/prctl.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/un.h>
#include <unistd.h>
#include <utmpx.h>

#if HAVE_PAM
#include <security/pam_appl.h>
#endif

#if HAVE_SELINUX
#include <selinux/selinux.h>
#endif

#if HAVE_SECCOMP
#include <seccomp.h>
#endif

#if HAVE_APPARMOR
#include <sys/apparmor.h>
#endif

#include "sd-messages.h"

#include "acl-util.h"
#include "af-list.h"
#include "alloc-util.h"
#if HAVE_APPARMOR
#include "apparmor-util.h"
#endif
#include "argv-util.h"
#include "async.h"
#include "barrier.h"
#include "bpf-lsm.h"
#include "cap-list.h"
#include "capability-util.h"
#include "cgroup-setup.h"
#include "chase.h"
#include "chown-recursive.h"
#include "constants.h"
#include "cpu-set-util.h"
#include "creds-util.h"
#include "data-fd-util.h"
#include "env-file.h"
#include "env-util.h"
#include "errno-list.h"
#include "escape.h"
#include "execute.h"
#include "exit-status.h"
#include "fd-util.h"
#include "fileio.h"
#include "format-util.h"
#include "glob-util.h"
#include "hexdecoct.h"
#include "io-util.h"
#include "ioprio-util.h"
#include "label-util.h"
#include "log.h"
#include "macro.h"
#include "manager.h"
#include "manager-dump.h"
#include "memory-util.h"
#include "missing_fs.h"
#include "missing_ioprio.h"
#include "missing_prctl.h"
#include "mkdir-label.h"
#include "mount-util.h"
#include "mountpoint-util.h"
#include "namespace.h"
#include "parse-util.h"
#include "path-util.h"
#include "proc-cmdline.h"
#include "process-util.h"
#include "psi-util.h"
#include "random-util.h"
#include "recurse-dir.h"
#include "rlimit-util.h"
#include "rm-rf.h"
#if HAVE_SECCOMP
#include "seccomp-util.h"
#endif
#include "securebits-util.h"
#include "selinux-util.h"
#include "signal-util.h"
#include "smack-util.h"
#include "socket-util.h"
#include "sort-util.h"
#include "special.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "syslog-util.h"
#include "terminal-util.h"
#include "tmpfile-util.h"
#include "umask-util.h"
#include "unit-serialize.h"
#include "user-util.h"
#include "utmp-wtmp.h"

#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)

#define SNDBUF_SIZE (8*1024*1024)

static int shift_fds(int fds[], size_t n_fds) {
        if (n_fds <= 0)
                return 0;

        /* Modifies the fds array! (sorts it) */

        assert(fds);

        for (int start = 0;;) {
                int restart_from = -1;

                for (int i = start; i < (int) n_fds; i++) {
                        int nfd;

                        /* Already at right index? */
                        if (fds[i] == i+3)
                                continue;

                        nfd = fcntl(fds[i], F_DUPFD, i + 3);
                        if (nfd < 0)
                                return -errno;

                        safe_close(fds[i]);
                        fds[i] = nfd;

                        /* Hmm, the fd we wanted isn't free? Then
                         * let's remember that and try again from here */
                        if (nfd != i+3 && restart_from < 0)
                                restart_from = i;
                }

                if (restart_from < 0)
                        break;

                start = restart_from;
        }

        return 0;
}

static int flags_fds(
                const int fds[],
                size_t n_socket_fds,
                size_t n_fds,
                bool nonblock) {

        int r;

        if (n_fds <= 0)
                return 0;

        assert(fds);

        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
         * O_NONBLOCK only applies to socket activation though. */

        for (size_t i = 0; i < n_fds; i++) {

                if (i < n_socket_fds) {
                        r = fd_nonblock(fds[i], nonblock);
                        if (r < 0)
                                return r;
                }

                /* We unconditionally drop FD_CLOEXEC from the fds,
                 * since after all we want to pass these fds to our
                 * children */

                r = fd_cloexec(fds[i], false);
                if (r < 0)
                        return r;
        }

        return 0;
}

static const char *exec_context_tty_path(const ExecContext *context) {
        assert(context);

        if (context->stdio_as_fds)
                return NULL;

        if (context->tty_path)
                return context->tty_path;

        return "/dev/console";
}

static int exec_context_tty_size(const ExecContext *context, unsigned *ret_rows, unsigned *ret_cols) {
        _cleanup_free_ char *rowskey = NULL, *rowsvalue = NULL, *colskey = NULL, *colsvalue = NULL;
        unsigned rows, cols;
        const char *tty;
        int r;

        assert(context);
        assert(ret_rows);
        assert(ret_cols);

        rows = context->tty_rows;
        cols = context->tty_cols;

        tty = exec_context_tty_path(context);
        if (!tty || (rows != UINT_MAX && cols != UINT_MAX)) {
                *ret_rows = rows;
                *ret_cols = cols;
                return 0;
        }

        tty = skip_dev_prefix(tty);
        if (!in_charset(tty, ALPHANUMERICAL)) {
                log_debug("%s contains non-alphanumeric characters, ignoring", tty);
                *ret_rows = rows;
                *ret_cols = cols;
                return 0;
        }

        rowskey = strjoin("systemd.tty.rows.", tty);
        if (!rowskey)
                return -ENOMEM;

        colskey = strjoin("systemd.tty.columns.", tty);
        if (!colskey)
                return -ENOMEM;

        r = proc_cmdline_get_key_many(/* flags = */ 0,
                                      rowskey, &rowsvalue,
                                      colskey, &colsvalue);
        if (r < 0)
                log_debug_errno(r, "Failed to read TTY size of %s from kernel cmdline, ignoring: %m", tty);

        if (rows == UINT_MAX && rowsvalue) {
                r = safe_atou(rowsvalue, &rows);
                if (r < 0)
                        log_debug_errno(r, "Failed to parse %s=%s, ignoring: %m", rowskey, rowsvalue);
        }

        if (cols == UINT_MAX && colsvalue) {
                r = safe_atou(colsvalue, &cols);
                if (r < 0)
                        log_debug_errno(r, "Failed to parse %s=%s, ignoring: %m", colskey, colsvalue);
        }

        *ret_rows = rows;
        *ret_cols = cols;

        return 0;
}

static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
        const char *path;

        assert(context);

        path = exec_context_tty_path(context);

        if (context->tty_vhangup) {
                if (p && p->stdin_fd >= 0)
                        (void) terminal_vhangup_fd(p->stdin_fd);
                else if (path)
                        (void) terminal_vhangup(path);
        }

        if (context->tty_reset) {
                if (p && p->stdin_fd >= 0)
                        (void) reset_terminal_fd(p->stdin_fd, true);
                else if (path)
                        (void) reset_terminal(path);
        }

        if (p && p->stdin_fd >= 0) {
                unsigned rows = context->tty_rows, cols = context->tty_cols;

                (void) exec_context_tty_size(context, &rows, &cols);
                (void) terminal_set_size_fd(p->stdin_fd, path, rows, cols);
        }

        if (context->tty_vt_disallocate && path)
                (void) vt_disallocate(path);
}

static bool is_terminal_input(ExecInput i) {
        return IN_SET(i,
                      EXEC_INPUT_TTY,
                      EXEC_INPUT_TTY_FORCE,
                      EXEC_INPUT_TTY_FAIL);
}

static bool is_terminal_output(ExecOutput o) {
        return IN_SET(o,
                      EXEC_OUTPUT_TTY,
                      EXEC_OUTPUT_KMSG_AND_CONSOLE,
                      EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
}

static bool is_kmsg_output(ExecOutput o) {
        return IN_SET(o,
                      EXEC_OUTPUT_KMSG,
                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
}

static bool exec_context_needs_term(const ExecContext *c) {
        assert(c);

        /* Return true if the execution context suggests we should set $TERM to something useful. */

        if (is_terminal_input(c->std_input))
                return true;

        if (is_terminal_output(c->std_output))
                return true;

        if (is_terminal_output(c->std_error))
                return true;

        return !!c->tty_path;
}

static int open_null_as(int flags, int nfd) {
        int fd;

        assert(nfd >= 0);

        fd = open("/dev/null", flags|O_NOCTTY);
        if (fd < 0)
                return -errno;

        return move_fd(fd, nfd, false);
}

static int connect_journal_socket(
                int fd,
                const char *log_namespace,
                uid_t uid,
                gid_t gid) {

        uid_t olduid = UID_INVALID;
        gid_t oldgid = GID_INVALID;
        const char *j;
        int r;

        j = log_namespace ?
                strjoina("/run/systemd/journal.", log_namespace, "/stdout") :
                "/run/systemd/journal/stdout";

        if (gid_is_valid(gid)) {
                oldgid = getgid();

                if (setegid(gid) < 0)
                        return -errno;
        }

        if (uid_is_valid(uid)) {
                olduid = getuid();

                if (seteuid(uid) < 0) {
                        r = -errno;
                        goto restore_gid;
                }
        }

        r = connect_unix_path(fd, AT_FDCWD, j);

        /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
           an LSM interferes. */

        if (uid_is_valid(uid))
                (void) seteuid(olduid);

 restore_gid:
        if (gid_is_valid(gid))
                (void) setegid(oldgid);

        return r;
}

static int connect_logger_as(
                const Unit *unit,
                const ExecContext *context,
                const ExecParameters *params,
                ExecOutput output,
                const char *ident,
                int nfd,
                uid_t uid,
                gid_t gid) {

        _cleanup_close_ int fd = -EBADF;
        int r;

        assert(context);
        assert(params);
        assert(output < _EXEC_OUTPUT_MAX);
        assert(ident);
        assert(nfd >= 0);

        fd = socket(AF_UNIX, SOCK_STREAM, 0);
        if (fd < 0)
                return -errno;

        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
        if (r < 0)
                return r;

        if (shutdown(fd, SHUT_RD) < 0)
                return -errno;

        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);

        if (dprintf(fd,
                "%s\n"
                "%s\n"
                "%i\n"
                "%i\n"
                "%i\n"
                "%i\n"
                "%i\n",
                context->syslog_identifier ?: ident,
                params->flags & EXEC_PASS_LOG_UNIT ? unit->id : "",
                context->syslog_priority,
                !!context->syslog_level_prefix,
                false,
                is_kmsg_output(output),
                is_terminal_output(output)) < 0)
                return -errno;

        return move_fd(TAKE_FD(fd), nfd, false);
}

static int open_terminal_as(const char *path, int flags, int nfd) {
        int fd;

        assert(path);
        assert(nfd >= 0);

        fd = open_terminal(path, flags | O_NOCTTY);
        if (fd < 0)
                return fd;

        return move_fd(fd, nfd, false);
}

static int acquire_path(const char *path, int flags, mode_t mode) {
        _cleanup_close_ int fd = -EBADF;
        int r;

        assert(path);

        if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR))
                flags |= O_CREAT;

        fd = open(path, flags|O_NOCTTY, mode);
        if (fd >= 0)
                return TAKE_FD(fd);

        if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
                return -errno;

        /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */

        fd = socket(AF_UNIX, SOCK_STREAM, 0);
        if (fd < 0)
                return -errno;

        r = connect_unix_path(fd, AT_FDCWD, path);
        if (IN_SET(r, -ENOTSOCK, -EINVAL))
                /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
                 * wasn't an AF_UNIX socket after all */
                return -ENXIO;
        if (r < 0)
                return r;

        if ((flags & O_ACCMODE) == O_RDONLY)
                r = shutdown(fd, SHUT_WR);
        else if ((flags & O_ACCMODE) == O_WRONLY)
                r = shutdown(fd, SHUT_RD);
        else
                r = 0;
        if (r < 0)
                return -errno;

        return TAKE_FD(fd);
}

static int fixup_input(
                const ExecContext *context,
                int socket_fd,
                bool apply_tty_stdin) {

        ExecInput std_input;

        assert(context);

        std_input = context->std_input;

        if (is_terminal_input(std_input) && !apply_tty_stdin)
                return EXEC_INPUT_NULL;

        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
                return EXEC_INPUT_NULL;

        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
                return EXEC_INPUT_NULL;

        return std_input;
}

static int fixup_output(ExecOutput output, int socket_fd) {

        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
                return EXEC_OUTPUT_INHERIT;

        return output;
}

static int setup_input(
                const ExecContext *context,
                const ExecParameters *params,
                int socket_fd,
                const int named_iofds[static 3]) {

        ExecInput i;
        int r;

        assert(context);
        assert(params);
        assert(named_iofds);

        if (params->stdin_fd >= 0) {
                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
                        return -errno;

                /* Try to make this the controlling tty, if it is a tty, and reset it */
                if (isatty(STDIN_FILENO)) {
                        unsigned rows = context->tty_rows, cols = context->tty_cols;

                        (void) exec_context_tty_size(context, &rows, &cols);
                        (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
                        (void) reset_terminal_fd(STDIN_FILENO, true);
                        (void) terminal_set_size_fd(STDIN_FILENO, NULL, rows, cols);
                }

                return STDIN_FILENO;
        }

        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);

        switch (i) {

        case EXEC_INPUT_NULL:
                return open_null_as(O_RDONLY, STDIN_FILENO);

        case EXEC_INPUT_TTY:
        case EXEC_INPUT_TTY_FORCE:
        case EXEC_INPUT_TTY_FAIL: {
                unsigned rows, cols;
                int fd;

                fd = acquire_terminal(exec_context_tty_path(context),
                                      i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
                                      i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
                                                                  ACQUIRE_TERMINAL_WAIT,
                                      USEC_INFINITY);
                if (fd < 0)
                        return fd;

                r = exec_context_tty_size(context, &rows, &cols);
                if (r < 0)
                        return r;

                r = terminal_set_size_fd(fd, exec_context_tty_path(context), rows, cols);
                if (r < 0)
                        return r;

                return move_fd(fd, STDIN_FILENO, false);
        }

        case EXEC_INPUT_SOCKET:
                assert(socket_fd >= 0);

                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));

        case EXEC_INPUT_NAMED_FD:
                assert(named_iofds[STDIN_FILENO] >= 0);

                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));

        case EXEC_INPUT_DATA: {
                int fd;

                fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0);
                if (fd < 0)
                        return fd;

                return move_fd(fd, STDIN_FILENO, false);
        }

        case EXEC_INPUT_FILE: {
                bool rw;
                int fd;

                assert(context->stdio_file[STDIN_FILENO]);

                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));

                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
                if (fd < 0)
                        return fd;

                return move_fd(fd, STDIN_FILENO, false);
        }

        default:
                assert_not_reached();
        }
}

static bool can_inherit_stderr_from_stdout(
                const ExecContext *context,
                ExecOutput o,
                ExecOutput e) {

        assert(context);

        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
         * stderr fd */

        if (e == EXEC_OUTPUT_INHERIT)
                return true;
        if (e != o)
                return false;

        if (e == EXEC_OUTPUT_NAMED_FD)
                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);

        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);

        return true;
}

static int setup_output(
                const Unit *unit,
                const ExecContext *context,
                const ExecParameters *params,
                int fileno,
                int socket_fd,
                const int named_iofds[static 3],
                const char *ident,
                uid_t uid,
                gid_t gid,
                dev_t *journal_stream_dev,
                ino_t *journal_stream_ino) {

        ExecOutput o;
        ExecInput i;
        int r;

        assert(unit);
        assert(context);
        assert(params);
        assert(ident);
        assert(journal_stream_dev);
        assert(journal_stream_ino);

        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {

                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
                        return -errno;

                return STDOUT_FILENO;
        }

        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
                        return -errno;

                return STDERR_FILENO;
        }

        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
        o = fixup_output(context->std_output, socket_fd);

        if (fileno == STDERR_FILENO) {
                ExecOutput e;
                e = fixup_output(context->std_error, socket_fd);

                /* This expects the input and output are already set up */

                /* Don't change the stderr file descriptor if we inherit all
                 * the way and are not on a tty */
                if (e == EXEC_OUTPUT_INHERIT &&
                    o == EXEC_OUTPUT_INHERIT &&
                    i == EXEC_INPUT_NULL &&
                    !is_terminal_input(context->std_input) &&
                    getppid() != 1)
                        return fileno;

                /* Duplicate from stdout if possible */
                if (can_inherit_stderr_from_stdout(context, o, e))
                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));

                o = e;

        } else if (o == EXEC_OUTPUT_INHERIT) {
                /* If input got downgraded, inherit the original value */
                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);

                /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
                if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));

                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
                if (getppid() != 1)
                        return fileno;

                /* We need to open /dev/null here anew, to get the right access mode. */
                return open_null_as(O_WRONLY, fileno);
        }

        switch (o) {

        case EXEC_OUTPUT_NULL:
                return open_null_as(O_WRONLY, fileno);

        case EXEC_OUTPUT_TTY:
                if (is_terminal_input(i))
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));

                /* We don't reset the terminal if this is just about output */
                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);

        case EXEC_OUTPUT_KMSG:
        case EXEC_OUTPUT_KMSG_AND_CONSOLE:
        case EXEC_OUTPUT_JOURNAL:
        case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
                r = connect_logger_as(unit, context, params, o, ident, fileno, uid, gid);
                if (r < 0) {
                        log_unit_warning_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m",
                                               fileno == STDOUT_FILENO ? "stdout" : "stderr");
                        r = open_null_as(O_WRONLY, fileno);
                } else {
                        struct stat st;

                        /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
                         * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
                         * services to detect whether they are connected to the journal or not.
                         *
                         * If both stdout and stderr are connected to a stream then let's make sure to store the data
                         * about STDERR as that's usually the best way to do logging. */

                        if (fstat(fileno, &st) >= 0 &&
                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
                                *journal_stream_dev = st.st_dev;
                                *journal_stream_ino = st.st_ino;
                        }
                }
                return r;

        case EXEC_OUTPUT_SOCKET:
                assert(socket_fd >= 0);

                return RET_NERRNO(dup2(socket_fd, fileno));

        case EXEC_OUTPUT_NAMED_FD:
                assert(named_iofds[fileno] >= 0);

                (void) fd_nonblock(named_iofds[fileno], false);
                return RET_NERRNO(dup2(named_iofds[fileno], fileno));

        case EXEC_OUTPUT_FILE:
        case EXEC_OUTPUT_FILE_APPEND:
        case EXEC_OUTPUT_FILE_TRUNCATE: {
                bool rw;
                int fd, flags;

                assert(context->stdio_file[fileno]);

                rw = context->std_input == EXEC_INPUT_FILE &&
                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);

                if (rw)
                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));

                flags = O_WRONLY;
                if (o == EXEC_OUTPUT_FILE_APPEND)
                        flags |= O_APPEND;
                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
                        flags |= O_TRUNC;

                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
                if (fd < 0)
                        return fd;

                return move_fd(fd, fileno, 0);
        }

        default:
                assert_not_reached();
        }
}

static int chown_terminal(int fd, uid_t uid) {
        int r;

        assert(fd >= 0);

        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
        if (isatty(fd) < 1) {
                if (IN_SET(errno, EINVAL, ENOTTY))
                        return 0; /* not a tty */

                return -errno;
        }

        /* This might fail. What matters are the results. */
        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
        if (r < 0)
                return r;

        return 1;
}

static int setup_confirm_stdio(
                const ExecContext *context,
                const char *vc,
                int *ret_saved_stdin,
                int *ret_saved_stdout) {

        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
        unsigned rows, cols;
        int r;

        assert(ret_saved_stdin);
        assert(ret_saved_stdout);

        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
        if (saved_stdin < 0)
                return -errno;

        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
        if (saved_stdout < 0)
                return -errno;

        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
        if (fd < 0)
                return fd;

        r = chown_terminal(fd, getuid());
        if (r < 0)
                return r;

        r = reset_terminal_fd(fd, true);
        if (r < 0)
                return r;

        r = exec_context_tty_size(context, &rows, &cols);
        if (r < 0)
                return r;

        r = terminal_set_size_fd(fd, vc, rows, cols);
        if (r < 0)
                return r;

        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
        TAKE_FD(fd);
        if (r < 0)
                return r;

        *ret_saved_stdin = TAKE_FD(saved_stdin);
        *ret_saved_stdout = TAKE_FD(saved_stdout);
        return 0;
}

static void write_confirm_error_fd(int err, int fd, const Unit *u) {
        assert(err < 0);

        if (err == -ETIMEDOUT)
                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", u->id);
        else {
                errno = -err;
                dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", u->id);
        }
}

static void write_confirm_error(int err, const char *vc, const Unit *u) {
        _cleanup_close_ int fd = -EBADF;

        assert(vc);

        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
        if (fd < 0)
                return;

        write_confirm_error_fd(err, fd, u);
}

static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
        int r = 0;

        assert(saved_stdin);
        assert(saved_stdout);

        release_terminal();

        if (*saved_stdin >= 0)
                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
                        r = -errno;

        if (*saved_stdout >= 0)
                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
                        r = -errno;

        *saved_stdin = safe_close(*saved_stdin);
        *saved_stdout = safe_close(*saved_stdout);

        return r;
}

enum {
        CONFIRM_PRETEND_FAILURE = -1,
        CONFIRM_PRETEND_SUCCESS =  0,
        CONFIRM_EXECUTE = 1,
};

static int ask_for_confirmation(const ExecContext *context, const char *vc, Unit *u, const char *cmdline) {
        int saved_stdout = -1, saved_stdin = -1, r;
        _cleanup_free_ char *e = NULL;
        char c;

        /* For any internal errors, assume a positive response. */
        r = setup_confirm_stdio(context, vc, &saved_stdin, &saved_stdout);
        if (r < 0) {
                write_confirm_error(r, vc, u);
                return CONFIRM_EXECUTE;
        }

        /* confirm_spawn might have been disabled while we were sleeping. */
        if (manager_is_confirm_spawn_disabled(u->manager)) {
                r = 1;
                goto restore_stdio;
        }

        e = ellipsize(cmdline, 60, 100);
        if (!e) {
                log_oom();
                r = CONFIRM_EXECUTE;
                goto restore_stdio;
        }

        for (;;) {
                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
                if (r < 0) {
                        write_confirm_error_fd(r, STDOUT_FILENO, u);
                        r = CONFIRM_EXECUTE;
                        goto restore_stdio;
                }

                switch (c) {
                case 'c':
                        printf("Resuming normal execution.\n");
                        manager_disable_confirm_spawn();
                        r = 1;
                        break;
                case 'D':
                        unit_dump(u, stdout, "  ");
                        continue; /* ask again */
                case 'f':
                        printf("Failing execution.\n");
                        r = CONFIRM_PRETEND_FAILURE;
                        break;
                case 'h':
                        printf("  c - continue, proceed without asking anymore\n"
                               "  D - dump, show the state of the unit\n"
                               "  f - fail, don't execute the command and pretend it failed\n"
                               "  h - help\n"
                               "  i - info, show a short summary of the unit\n"
                               "  j - jobs, show jobs that are in progress\n"
                               "  s - skip, don't execute the command and pretend it succeeded\n"
                               "  y - yes, execute the command\n");
                        continue; /* ask again */
                case 'i':
                        printf("  Description: %s\n"
                               "  Unit:        %s\n"
                               "  Command:     %s\n",
                               u->id, u->description, cmdline);
                        continue; /* ask again */
                case 'j':
                        manager_dump_jobs(u->manager, stdout, /* patterns= */ NULL, "  ");
                        continue; /* ask again */
                case 'n':
                        /* 'n' was removed in favor of 'f'. */
                        printf("Didn't understand 'n', did you mean 'f'?\n");
                        continue; /* ask again */
                case 's':
                        printf("Skipping execution.\n");
                        r = CONFIRM_PRETEND_SUCCESS;
                        break;
                case 'y':
                        r = CONFIRM_EXECUTE;
                        break;
                default:
                        assert_not_reached();
                }
                break;
        }

restore_stdio:
        restore_confirm_stdio(&saved_stdin, &saved_stdout);
        return r;
}

static int get_fixed_user(const ExecContext *c, const char **user,
                          uid_t *uid, gid_t *gid,
                          const char **home, const char **shell) {
        int r;
        const char *name;

        assert(c);

        if (!c->user)
                return 0;

        /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
         * (i.e. are "/" or "/bin/nologin"). */

        name = c->user;
        r = get_user_creds(&name, uid, gid, home, shell, USER_CREDS_CLEAN);
        if (r < 0)
                return r;

        *user = name;
        return 0;
}

static int get_fixed_group(const ExecContext *c, const char **group, gid_t *gid) {
        int r;
        const char *name;

        assert(c);

        if (!c->group)
                return 0;

        name = c->group;
        r = get_group_creds(&name, gid, 0);
        if (r < 0)
                return r;

        *group = name;
        return 0;
}

static int get_supplementary_groups(const ExecContext *c, const char *user,
                                    const char *group, gid_t gid,
                                    gid_t **supplementary_gids, int *ngids) {
        int r, k = 0;
        int ngroups_max;
        bool keep_groups = false;
        gid_t *groups = NULL;
        _cleanup_free_ gid_t *l_gids = NULL;

        assert(c);

        /*
         * If user is given, then lookup GID and supplementary groups list.
         * We avoid NSS lookups for gid=0. Also we have to initialize groups
         * here and as early as possible so we keep the list of supplementary
         * groups of the caller.
         */
        if (user && gid_is_valid(gid) && gid != 0) {
                /* First step, initialize groups from /etc/groups */
                if (initgroups(user, gid) < 0)
                        return -errno;

                keep_groups = true;
        }

        if (strv_isempty(c->supplementary_groups))
                return 0;

        /*
         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
         * be positive, otherwise fail.
         */
        errno = 0;
        ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
        if (ngroups_max <= 0)
                return errno_or_else(EOPNOTSUPP);

        l_gids = new(gid_t, ngroups_max);
        if (!l_gids)
                return -ENOMEM;

        if (keep_groups) {
                /*
                 * Lookup the list of groups that the user belongs to, we
                 * avoid NSS lookups here too for gid=0.
                 */
                k = ngroups_max;
                if (getgrouplist(user, gid, l_gids, &k) < 0)
                        return -EINVAL;
        } else
                k = 0;

        STRV_FOREACH(i, c->supplementary_groups) {
                const char *g;

                if (k >= ngroups_max)
                        return -E2BIG;

                g = *i;
                r = get_group_creds(&g, l_gids+k, 0);
                if (r < 0)
                        return r;

                k++;
        }

        /*
         * Sets ngids to zero to drop all supplementary groups, happens
         * when we are under root and SupplementaryGroups= is empty.
         */
        if (k == 0) {
                *ngids = 0;
                return 0;
        }

        /* Otherwise get the final list of supplementary groups */
        groups = memdup(l_gids, sizeof(gid_t) * k);
        if (!groups)
                return -ENOMEM;

        *supplementary_gids = groups;
        *ngids = k;

        groups = NULL;

        return 0;
}

static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
        int r;

        /* Handle SupplementaryGroups= if it is not empty */
        if (ngids > 0) {
                r = maybe_setgroups(ngids, supplementary_gids);
                if (r < 0)
                        return r;
        }

        if (gid_is_valid(gid)) {
                /* Then set our gids */
                if (setresgid(gid, gid, gid) < 0)
                        return -errno;
        }

        return 0;
}

static int set_securebits(unsigned bits, unsigned mask) {
        unsigned applied;
        int current;

        current = prctl(PR_GET_SECUREBITS);
        if (current < 0)
                return -errno;

        /* Clear all securebits defined in mask and set bits */
        applied = ((unsigned) current & ~mask) | bits;
        if ((unsigned) current == applied)
                return 0;

        if (prctl(PR_SET_SECUREBITS, applied) < 0)
                return -errno;

        return 1;
}

static int enforce_user(
                const ExecContext *context,
                uid_t uid,
                uint64_t capability_ambient_set) {
        assert(context);
        int r;

        if (!uid_is_valid(uid))
                return 0;

        /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
         * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
         * case. */

        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {

                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
                if (r < 0)
                        return r;
        }

        /* Second step: actually set the uids */
        if (setresuid(uid, uid, uid) < 0)
                return -errno;

        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
         * outside of this call. */
        return 0;
}

#if HAVE_PAM

static int null_conv(
                int num_msg,
                const struct pam_message **msg,
                struct pam_response **resp,
                void *appdata_ptr) {

        /* We don't support conversations */

        return PAM_CONV_ERR;
}

#endif

static int setup_pam(
                const char *name,
                const char *user,
                uid_t uid,
                gid_t gid,
                const char *tty,
                char ***env, /* updated on success */
                const int fds[], size_t n_fds) {

#if HAVE_PAM

        static const struct pam_conv conv = {
                .conv = null_conv,
                .appdata_ptr = NULL
        };

        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
        _cleanup_strv_free_ char **e = NULL;
        pam_handle_t *handle = NULL;
        sigset_t old_ss;
        int pam_code = PAM_SUCCESS, r;
        bool close_session = false;
        pid_t pam_pid = 0, parent_pid;
        int flags = 0;

        assert(name);
        assert(user);
        assert(env);

        /* We set up PAM in the parent process, then fork. The child
         * will then stay around until killed via PR_GET_PDEATHSIG or
         * systemd via the cgroup logic. It will then remove the PAM
         * session again. The parent process will exec() the actual
         * daemon. We do things this way to ensure that the main PID
         * of the daemon is the one we initially fork()ed. */

        r = barrier_create(&barrier);
        if (r < 0)
                goto fail;

        if (log_get_max_level() < LOG_DEBUG)
                flags |= PAM_SILENT;

        pam_code = pam_start(name, user, &conv, &handle);
        if (pam_code != PAM_SUCCESS) {
                handle = NULL;
                goto fail;
        }

        if (!tty) {
                _cleanup_free_ char *q = NULL;

                /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
                 * out if that's the case, and read the TTY off it. */

                if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
                        tty = strjoina("/dev/", q);
        }

        if (tty) {
                pam_code = pam_set_item(handle, PAM_TTY, tty);
                if (pam_code != PAM_SUCCESS)
                        goto fail;
        }

        STRV_FOREACH(nv, *env) {
                pam_code = pam_putenv(handle, *nv);
                if (pam_code != PAM_SUCCESS)
                        goto fail;
        }

        pam_code = pam_acct_mgmt(handle, flags);
        if (pam_code != PAM_SUCCESS)
                goto fail;

        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
        if (pam_code != PAM_SUCCESS)
                log_debug("pam_setcred() failed, ignoring: %s", pam_strerror(handle, pam_code));

        pam_code = pam_open_session(handle, flags);
        if (pam_code != PAM_SUCCESS)
                goto fail;

        close_session = true;

        e = pam_getenvlist(handle);
        if (!e) {
                pam_code = PAM_BUF_ERR;
                goto fail;
        }

        /* Block SIGTERM, so that we know that it won't get lost in the child */

        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);

        parent_pid = getpid_cached();

        r = safe_fork("(sd-pam)", 0, &pam_pid);
        if (r < 0)
                goto fail;
        if (r == 0) {
                int sig, ret = EXIT_PAM;

                /* The child's job is to reset the PAM session on termination */
                barrier_set_role(&barrier, BARRIER_CHILD);

                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
                 * those fds are open here that have been opened by PAM. */
                (void) close_many(fds, n_fds);

                /* Drop privileges - we don't need any to pam_close_session and this will make
                 * PR_SET_PDEATHSIG work in most cases.  If this fails, ignore the error - but expect sd-pam
                 * threads to fail to exit normally */

                r = maybe_setgroups(0, NULL);
                if (r < 0)
                        log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
                if (setresgid(gid, gid, gid) < 0)
                        log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
                if (setresuid(uid, uid, uid) < 0)
                        log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");

                (void) ignore_signals(SIGPIPE);

                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
                 * this way. We rely on the control groups kill logic to do the rest for us. */
                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
                        goto child_finish;

                /* Tell the parent that our setup is done. This is especially important regarding dropping
                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
                 *
                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
                (void) barrier_place(&barrier);

                /* Check if our parent process might already have died? */
                if (getppid() == parent_pid) {
                        sigset_t ss;

                        assert_se(sigemptyset(&ss) >= 0);
                        assert_se(sigaddset(&ss, SIGTERM) >= 0);

                        for (;;) {
                                if (sigwait(&ss, &sig) < 0) {
                                        if (errno == EINTR)
                                                continue;

                                        goto child_finish;
                                }

                                assert(sig == SIGTERM);
                                break;
                        }
                }

                pam_code = pam_setcred(handle, PAM_DELETE_CRED | flags);
                if (pam_code != PAM_SUCCESS)
                        goto child_finish;

                /* If our parent died we'll end the session */
                if (getppid() != parent_pid) {
                        pam_code = pam_close_session(handle, flags);
                        if (pam_code != PAM_SUCCESS)
                                goto child_finish;
                }

                ret = 0;

        child_finish:
                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
                 * know about this. See pam_end(3) */
                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
                _exit(ret);
        }

        barrier_set_role(&barrier, BARRIER_PARENT);

        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
         * here. */
        handle = NULL;

        /* Unblock SIGTERM again in the parent */
        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);

        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
         * this fd around. */
        closelog();

        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
         * recover. However, warn loudly if it happens. */
        if (!barrier_place_and_sync(&barrier))
                log_error("PAM initialization failed");

        return strv_free_and_replace(*env, e);

fail:
        if (pam_code != PAM_SUCCESS) {
                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
                r = -EPERM;  /* PAM errors do not map to errno */
        } else
                log_error_errno(r, "PAM failed: %m");

        if (handle) {
                if (close_session)
                        pam_code = pam_close_session(handle, flags);

                (void) pam_end(handle, pam_code | flags);
        }

        closelog();
        return r;
#else
        return 0;
#endif
}

static void rename_process_from_path(const char *path) {
        _cleanup_free_ char *buf = NULL;
        const char *p;

        assert(path);

        /* This resulting string must fit in 10 chars (i.e. the length of "/sbin/init") to look pretty in
         * /bin/ps */

        if (path_extract_filename(path, &buf) < 0) {
                rename_process("(...)");
                return;
        }

        size_t l = strlen(buf);
        if (l > 8) {
                /* The end of the process name is usually more interesting, since the first bit might just be
                 * "systemd-" */
                p = buf + l - 8;
                l = 8;
        } else
                p = buf;

        char process_name[11];
        process_name[0] = '(';
        memcpy(process_name+1, p, l);
        process_name[1+l] = ')';
        process_name[1+l+1] = 0;

        rename_process(process_name);
}

static bool context_has_address_families(const ExecContext *c) {
        assert(c);

        return c->address_families_allow_list ||
                !set_isempty(c->address_families);
}

static bool context_has_syscall_filters(const ExecContext *c) {
        assert(c);

        return c->syscall_allow_list ||
                !hashmap_isempty(c->syscall_filter);
}

static bool context_has_syscall_logs(const ExecContext *c) {
        assert(c);

        return c->syscall_log_allow_list ||
                !hashmap_isempty(c->syscall_log);
}

static bool context_has_no_new_privileges(const ExecContext *c) {
        assert(c);

        if (c->no_new_privileges)
                return true;

        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
                return false;

        /* We need NNP if we have any form of seccomp and are unprivileged */
        return c->lock_personality ||
                c->memory_deny_write_execute ||
                c->private_devices ||
                c->protect_clock ||
                c->protect_hostname ||
                c->protect_kernel_tunables ||
                c->protect_kernel_modules ||
                c->protect_kernel_logs ||
                context_has_address_families(c) ||
                exec_context_restrict_namespaces_set(c) ||
                c->restrict_realtime ||
                c->restrict_suid_sgid ||
                !set_isempty(c->syscall_archs) ||
                context_has_syscall_filters(c) ||
                context_has_syscall_logs(c);
}

bool exec_context_has_credentials(const ExecContext *context) {

        assert(context);

        return !hashmap_isempty(context->set_credentials) ||
                !hashmap_isempty(context->load_credentials);
}

#if HAVE_SECCOMP

static bool skip_seccomp_unavailable(const Unit* u, const char* msg) {

        if (is_seccomp_available())
                return false;

        log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg);
        return true;
}

static int apply_syscall_filter(const Unit* u, const ExecContext *c, bool needs_ambient_hack) {
        uint32_t negative_action, default_action, action;
        int r;

        assert(u);
        assert(c);

        if (!context_has_syscall_filters(c))
                return 0;

        if (skip_seccomp_unavailable(u, "SystemCallFilter="))
                return 0;

        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);

        if (c->syscall_allow_list) {
                default_action = negative_action;
                action = SCMP_ACT_ALLOW;
        } else {
                default_action = SCMP_ACT_ALLOW;
                action = negative_action;
        }

        if (needs_ambient_hack) {
                r = seccomp_filter_set_add(c->syscall_filter, c->syscall_allow_list, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID);
                if (r < 0)
                        return r;
        }

        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
}

static int apply_syscall_log(const Unit* u, const ExecContext *c) {
#ifdef SCMP_ACT_LOG
        uint32_t default_action, action;
#endif

        assert(u);
        assert(c);

        if (!context_has_syscall_logs(c))
                return 0;

#ifdef SCMP_ACT_LOG
        if (skip_seccomp_unavailable(u, "SystemCallLog="))
                return 0;

        if (c->syscall_log_allow_list) {
                /* Log nothing but the ones listed */
                default_action = SCMP_ACT_ALLOW;
                action = SCMP_ACT_LOG;
        } else {
                /* Log everything but the ones listed */
                default_action = SCMP_ACT_LOG;
                action = SCMP_ACT_ALLOW;
        }

        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
#else
        /* old libseccomp */
        log_unit_debug(u, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
        return 0;
#endif
}

static int apply_syscall_archs(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (set_isempty(c->syscall_archs))
                return 0;

        if (skip_seccomp_unavailable(u, "SystemCallArchitectures="))
                return 0;

        return seccomp_restrict_archs(c->syscall_archs);
}

static int apply_address_families(const Unit* u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!context_has_address_families(c))
                return 0;

        if (skip_seccomp_unavailable(u, "RestrictAddressFamilies="))
                return 0;

        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
}

static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) {
        int r;

        assert(u);
        assert(c);

        if (!c->memory_deny_write_execute)
                return 0;

        /* use prctl() if kernel supports it (6.3) */
        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
        if (r == 0) {
                log_unit_debug(u, "Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
                return 0;
        }
        if (r < 0 && errno != EINVAL)
                return log_unit_debug_errno(u, errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
        /* else use seccomp */
        log_unit_debug(u, "Kernel doesn't support PR_SET_MDWE: falling back to seccomp");

        if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute="))
                return 0;

        return seccomp_memory_deny_write_execute();
}

static int apply_restrict_realtime(const Unit* u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!c->restrict_realtime)
                return 0;

        if (skip_seccomp_unavailable(u, "RestrictRealtime="))
                return 0;

        return seccomp_restrict_realtime();
}

static int apply_restrict_suid_sgid(const Unit* u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!c->restrict_suid_sgid)
                return 0;

        if (skip_seccomp_unavailable(u, "RestrictSUIDSGID="))
                return 0;

        return seccomp_restrict_suid_sgid();
}

static int apply_protect_sysctl(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
         * let's protect even those systems where this is left on in the kernel. */

        if (!c->protect_kernel_tunables)
                return 0;

        if (skip_seccomp_unavailable(u, "ProtectKernelTunables="))
                return 0;

        return seccomp_protect_sysctl();
}

static int apply_protect_kernel_modules(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        /* Turn off module syscalls on ProtectKernelModules=yes */

        if (!c->protect_kernel_modules)
                return 0;

        if (skip_seccomp_unavailable(u, "ProtectKernelModules="))
                return 0;

        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
}

static int apply_protect_kernel_logs(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!c->protect_kernel_logs)
                return 0;

        if (skip_seccomp_unavailable(u, "ProtectKernelLogs="))
                return 0;

        return seccomp_protect_syslog();
}

static int apply_protect_clock(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!c->protect_clock)
                return 0;

        if (skip_seccomp_unavailable(u, "ProtectClock="))
                return 0;

        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
}

static int apply_private_devices(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */

        if (!c->private_devices)
                return 0;

        if (skip_seccomp_unavailable(u, "PrivateDevices="))
                return 0;

        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
}

static int apply_restrict_namespaces(const Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!exec_context_restrict_namespaces_set(c))
                return 0;

        if (skip_seccomp_unavailable(u, "RestrictNamespaces="))
                return 0;

        return seccomp_restrict_namespaces(c->restrict_namespaces);
}

static int apply_lock_personality(const Unit* u, const ExecContext *c) {
        unsigned long personality;
        int r;

        assert(u);
        assert(c);

        if (!c->lock_personality)
                return 0;

        if (skip_seccomp_unavailable(u, "LockPersonality="))
                return 0;

        personality = c->personality;

        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
        if (personality == PERSONALITY_INVALID) {

                r = opinionated_personality(&personality);
                if (r < 0)
                        return r;
        }

        return seccomp_lock_personality(personality);
}

#endif

#if HAVE_LIBBPF
static int apply_restrict_filesystems(Unit *u, const ExecContext *c) {
        assert(u);
        assert(c);

        if (!exec_context_restrict_filesystems_set(c))
                return 0;

        if (!u->manager->restrict_fs) {
                /* LSM BPF is unsupported or lsm_bpf_setup failed */
                log_unit_debug(u, "LSM BPF not supported, skipping RestrictFileSystems=");
                return 0;
        }

        return lsm_bpf_unit_restrict_filesystems(u, c->restrict_filesystems, c->restrict_filesystems_allow_list);
}
#endif

static int apply_protect_hostname(const Unit *u, const ExecContext *c, int *ret_exit_status) {
        assert(u);
        assert(c);

        if (!c->protect_hostname)
                return 0;

        if (ns_type_supported(NAMESPACE_UTS)) {
                if (unshare(CLONE_NEWUTS) < 0) {
                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
                                *ret_exit_status = EXIT_NAMESPACE;
                                return log_unit_error_errno(u, errno, "Failed to set up UTS namespacing: %m");
                        }

                        log_unit_warning(u, "ProtectHostname=yes is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.");
                }
        } else
                log_unit_warning(u, "ProtectHostname=yes is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.");

#if HAVE_SECCOMP
        int r;

        if (skip_seccomp_unavailable(u, "ProtectHostname="))
                return 0;

        r = seccomp_protect_hostname();
        if (r < 0) {
                *ret_exit_status = EXIT_SECCOMP;
                return log_unit_error_errno(u, r, "Failed to apply hostname restrictions: %m");
        }
#endif

        return 0;
}

static void do_idle_pipe_dance(int idle_pipe[static 4]) {
        assert(idle_pipe);

        idle_pipe[1] = safe_close(idle_pipe[1]);
        idle_pipe[2] = safe_close(idle_pipe[2]);

        if (idle_pipe[0] >= 0) {
                int r;

                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);

                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
                        ssize_t n;

                        /* Signal systemd that we are bored and want to continue. */
                        n = write(idle_pipe[3], "x", 1);
                        if (n > 0)
                                /* Wait for systemd to react to the signal above. */
                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
                }

                idle_pipe[0] = safe_close(idle_pipe[0]);

        }

        idle_pipe[3] = safe_close(idle_pipe[3]);
}

static const char *exec_directory_env_name_to_string(ExecDirectoryType t);

static int build_environment(
                const Unit *u,
                const ExecContext *c,
                const ExecParameters *p,
                const CGroupContext *cgroup_context,
                size_t n_fds,
                char **fdnames,
                const char *home,
                const char *username,
                const char *shell,
                dev_t journal_stream_dev,
                ino_t journal_stream_ino,
                const char *memory_pressure_path,
                char ***ret) {

        _cleanup_strv_free_ char **our_env = NULL;
        size_t n_env = 0;
        char *x;
        int r;

        assert(u);
        assert(c);
        assert(p);
        assert(ret);

#define N_ENV_VARS 19
        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
        if (!our_env)
                return -ENOMEM;

        if (n_fds > 0) {
                _cleanup_free_ char *joined = NULL;

                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
                        return -ENOMEM;
                our_env[n_env++] = x;

                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
                        return -ENOMEM;
                our_env[n_env++] = x;

                joined = strv_join(fdnames, ":");
                if (!joined)
                        return -ENOMEM;

                x = strjoin("LISTEN_FDNAMES=", joined);
                if (!x)
                        return -ENOMEM;
                our_env[n_env++] = x;
        }

        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
                        return -ENOMEM;
                our_env[n_env++] = x;

                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
                        return -ENOMEM;
                our_env[n_env++] = x;
        }

        /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
         * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
         * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
        if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
                x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
                if (!x)
                        return -ENOMEM;
                our_env[n_env++] = x;
        }

        if (home) {
                x = strjoin("HOME=", home);
                if (!x)
                        return -ENOMEM;

                path_simplify(x + 5);
                our_env[n_env++] = x;
        }

        if (username) {
                x = strjoin("LOGNAME=", username);
                if (!x)
                        return -ENOMEM;
                our_env[n_env++] = x;

                x = strjoin("USER=", username);
                if (!x)
                        return -ENOMEM;
                our_env[n_env++] = x;
        }

        if (shell) {
                x = strjoin("SHELL=", shell);
                if (!x)
                        return -ENOMEM;

                path_simplify(x + 6);
                our_env[n_env++] = x;
        }

        if (!sd_id128_is_null(u->invocation_id)) {
                if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
                        return -ENOMEM;

                our_env[n_env++] = x;
        }

        if (exec_context_needs_term(c)) {
                _cleanup_free_ char *cmdline = NULL;
                const char *tty_path, *term = NULL;

                tty_path = exec_context_tty_path(c);

                /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
                 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
                 * container manager passes to PID 1 ends up all the way in the console login shown. */

                if (path_equal_ptr(tty_path, "/dev/console") && getppid() == 1)
                        term = getenv("TERM");
                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
                        _cleanup_free_ char *key = NULL;

                        key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
                        if (!key)
                                return -ENOMEM;

                        r = proc_cmdline_get_key(key, 0, &cmdline);
                        if (r < 0)
                                log_debug_errno(r, "Failed to read %s from kernel cmdline, ignoring: %m", key);
                        else if (r > 0)
                                term = cmdline;
                }

                if (!term)
                        term = default_term_for_tty(tty_path);

                x = strjoin("TERM=", term);
                if (!x)
                        return -ENOMEM;
                our_env[n_env++] = x;
        }

        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
                        return -ENOMEM;

                our_env[n_env++] = x;
        }

        if (c->log_namespace) {
                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
                if (!x)
                        return -ENOMEM;

                our_env[n_env++] = x;
        }

        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                _cleanup_free_ char *joined = NULL;
                const char *n;

                if (!p->prefix[t])
                        continue;

                if (c->directories[t].n_items == 0)
                        continue;

                n = exec_directory_env_name_to_string(t);
                if (!n)
                        continue;

                for (size_t i = 0; i < c->directories[t].n_items; i++) {
                        _cleanup_free_ char *prefixed = NULL;

                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
                        if (!prefixed)
                                return -ENOMEM;

                        if (!strextend_with_separator(&joined, ":", prefixed))
                                return -ENOMEM;
                }

                x = strjoin(n, "=", joined);
                if (!x)
                        return -ENOMEM;

                our_env[n_env++] = x;
        }

        if (exec_context_has_credentials(c) && p->prefix[EXEC_DIRECTORY_RUNTIME]) {
                x = strjoin("CREDENTIALS_DIRECTORY=", p->prefix[EXEC_DIRECTORY_RUNTIME], "/credentials/", u->id);
                if (!x)
                        return -ENOMEM;

                our_env[n_env++] = x;
        }

        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
                return -ENOMEM;

        our_env[n_env++] = x;

        if (memory_pressure_path) {
                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
                if (!x)
                        return -ENOMEM;

                our_env[n_env++] = x;

                if (cgroup_context && !path_equal(memory_pressure_path, "/dev/null")) {
                        _cleanup_free_ char *b = NULL, *e = NULL;

                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
                                     MEMORY_PRESSURE_DEFAULT_TYPE,
                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
                                return -ENOMEM;

                        if (base64mem(b, strlen(b) + 1, &e) < 0)
                                return -ENOMEM;

                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
                        if (!x)
                                return -ENOMEM;

                        our_env[n_env++] = x;
                }
        }

        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
#undef N_ENV_VARS

        *ret = TAKE_PTR(our_env);

        return 0;
}

static int build_pass_environment(const ExecContext *c, char ***ret) {
        _cleanup_strv_free_ char **pass_env = NULL;
        size_t n_env = 0;

        STRV_FOREACH(i, c->pass_environment) {
                _cleanup_free_ char *x = NULL;
                char *v;

                v = getenv(*i);
                if (!v)
                        continue;
                x = strjoin(*i, "=", v);
                if (!x)
                        return -ENOMEM;

                if (!GREEDY_REALLOC(pass_env, n_env + 2))
                        return -ENOMEM;

                pass_env[n_env++] = TAKE_PTR(x);
                pass_env[n_env] = NULL;
        }

        *ret = TAKE_PTR(pass_env);

        return 0;
}

bool exec_needs_network_namespace(const ExecContext *context) {
        assert(context);

        return context->private_network || context->network_namespace_path;
}

static bool exec_needs_ipc_namespace(const ExecContext *context) {
        assert(context);

        return context->private_ipc || context->ipc_namespace_path;
}

bool exec_needs_mount_namespace(
                const ExecContext *context,
                const ExecParameters *params,
                const ExecRuntime *runtime) {

        assert(context);

        if (context->root_image)
                return true;

        if (!strv_isempty(context->read_write_paths) ||
            !strv_isempty(context->read_only_paths) ||
            !strv_isempty(context->inaccessible_paths) ||
            !strv_isempty(context->exec_paths) ||
            !strv_isempty(context->no_exec_paths))
                return true;

        if (context->n_bind_mounts > 0)
                return true;

        if (context->n_temporary_filesystems > 0)
                return true;

        if (context->n_mount_images > 0)
                return true;

        if (context->n_extension_images > 0)
                return true;

        if (!strv_isempty(context->extension_directories))
                return true;

        if (!IN_SET(context->mount_propagation_flag, 0, MS_SHARED))
                return true;

        if (context->private_tmp && runtime && runtime->shared && (runtime->shared->tmp_dir || runtime->shared->var_tmp_dir))
                return true;

        if (context->private_devices ||
            context->private_mounts > 0 ||
            (context->private_mounts < 0 && exec_needs_network_namespace(context)) ||
            context->protect_system != PROTECT_SYSTEM_NO ||
            context->protect_home != PROTECT_HOME_NO ||
            context->protect_kernel_tunables ||
            context->protect_kernel_modules ||
            context->protect_kernel_logs ||
            context->protect_control_groups ||
            context->protect_proc != PROTECT_PROC_DEFAULT ||
            context->proc_subset != PROC_SUBSET_ALL ||
            exec_needs_ipc_namespace(context))
                return true;

        if (context->root_directory) {
                if (exec_context_get_effective_mount_apivfs(context))
                        return true;

                for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                        if (params && !params->prefix[t])
                                continue;

                        if (context->directories[t].n_items > 0)
                                return true;
                }
        }

        if (context->dynamic_user &&
            (context->directories[EXEC_DIRECTORY_STATE].n_items > 0 ||
             context->directories[EXEC_DIRECTORY_CACHE].n_items > 0 ||
             context->directories[EXEC_DIRECTORY_LOGS].n_items > 0))
                return true;

        if (context->log_namespace)
                return true;

        return false;
}

static int setup_private_users(uid_t ouid, gid_t ogid, uid_t uid, gid_t gid) {
        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
        _cleanup_close_pair_ int errno_pipe[2] = PIPE_EBADF;
        _cleanup_close_ int unshare_ready_fd = -EBADF;
        _cleanup_(sigkill_waitp) pid_t pid = 0;
        uint64_t c = 1;
        ssize_t n;
        int r;

        /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
         * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
         * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
         * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
         * which waits for the parent to create the new user namespace while staying in the original namespace. The
         * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
         * continues execution normally.
         * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
         * does not need CAP_SETUID to write the single line mapping to itself. */

        /* Can only set up multiple mappings with CAP_SETUID. */
        if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid))
                r = asprintf(&uid_map,
                             UID_FMT " " UID_FMT " 1\n"     /* Map $OUID → $OUID */
                             UID_FMT " " UID_FMT " 1\n",    /* Map $UID → $UID */
                             ouid, ouid, uid, uid);
        else
                r = asprintf(&uid_map,
                             UID_FMT " " UID_FMT " 1\n",    /* Map $OUID → $OUID */
                             ouid, ouid);

        if (r < 0)
                return -ENOMEM;

        /* Can only set up multiple mappings with CAP_SETGID. */
        if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid))
                r = asprintf(&gid_map,
                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
                             ogid, ogid, gid, gid);
        else
                r = asprintf(&gid_map,
                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
                             ogid, ogid);

        if (r < 0)
                return -ENOMEM;

        /* Create a communication channel so that the parent can tell the child when it finished creating the user
         * namespace. */
        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
        if (unshare_ready_fd < 0)
                return -errno;

        /* Create a communication channel so that the child can tell the parent a proper error code in case it
         * failed. */
        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
                return -errno;

        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid);
        if (r < 0)
                return r;
        if (r == 0) {
                _cleanup_close_ int fd = -EBADF;
                const char *a;
                pid_t ppid;

                /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
                 * here, after the parent opened its own user namespace. */

                ppid = getppid();
                errno_pipe[0] = safe_close(errno_pipe[0]);

                /* Wait until the parent unshared the user namespace */
                if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
                        r = -errno;
                        goto child_fail;
                }

                /* Disable the setgroups() system call in the child user namespace, for good. */
                a = procfs_file_alloca(ppid, "setgroups");
                fd = open(a, O_WRONLY|O_CLOEXEC);
                if (fd < 0) {
                        if (errno != ENOENT) {
                                r = -errno;
                                goto child_fail;
                        }

                        /* If the file is missing the kernel is too old, let's continue anyway. */
                } else {
                        if (write(fd, "deny\n", 5) < 0) {
                                r = -errno;
                                goto child_fail;
                        }

                        fd = safe_close(fd);
                }

                /* First write the GID map */
                a = procfs_file_alloca(ppid, "gid_map");
                fd = open(a, O_WRONLY|O_CLOEXEC);
                if (fd < 0) {
                        r = -errno;
                        goto child_fail;
                }
                if (write(fd, gid_map, strlen(gid_map)) < 0) {
                        r = -errno;
                        goto child_fail;
                }
                fd = safe_close(fd);

                /* The write the UID map */
                a = procfs_file_alloca(ppid, "uid_map");
                fd = open(a, O_WRONLY|O_CLOEXEC);
                if (fd < 0) {
                        r = -errno;
                        goto child_fail;
                }
                if (write(fd, uid_map, strlen(uid_map)) < 0) {
                        r = -errno;
                        goto child_fail;
                }

                _exit(EXIT_SUCCESS);

        child_fail:
                (void) write(errno_pipe[1], &r, sizeof(r));
                _exit(EXIT_FAILURE);
        }

        errno_pipe[1] = safe_close(errno_pipe[1]);

        if (unshare(CLONE_NEWUSER) < 0)
                return -errno;

        /* Let the child know that the namespace is ready now */
        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
                return -errno;

        /* Try to read an error code from the child */
        n = read(errno_pipe[0], &r, sizeof(r));
        if (n < 0)
                return -errno;
        if (n == sizeof(r)) { /* an error code was sent to us */
                if (r < 0)
                        return r;
                return -EIO;
        }
        if (n != 0) /* on success we should have read 0 bytes */
                return -EIO;

        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
        if (r < 0)
                return r;
        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
                return -EIO;

        return 0;
}

static bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) {
        assert(context);

        if (!context->dynamic_user)
                return false;

        if (type == EXEC_DIRECTORY_CONFIGURATION)
                return false;

        if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
                return false;

        return true;
}

static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
        _cleanup_free_ char *src_abs = NULL;
        int r;

        assert(source);

        src_abs = path_join(root, source);
        if (!src_abs)
                return -ENOMEM;

        STRV_FOREACH(dst, symlinks) {
                _cleanup_free_ char *dst_abs = NULL;

                dst_abs = path_join(root, *dst);
                if (!dst_abs)
                        return -ENOMEM;

                r = mkdir_parents_label(dst_abs, 0755);
                if (r < 0)
                        return r;

                r = symlink_idempotent(src_abs, dst_abs, true);
                if (r < 0)
                        return r;
        }

        return 0;
}

static int setup_exec_directory(
                const ExecContext *context,
                const ExecParameters *params,
                uid_t uid,
                gid_t gid,
                ExecDirectoryType type,
                bool needs_mount_namespace,
                int *exit_status) {

        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
                [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
                [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
                [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
                [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
        };
        int r;

        assert(context);
        assert(params);
        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
        assert(exit_status);

        if (!params->prefix[type])
                return 0;

        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
                if (!uid_is_valid(uid))
                        uid = 0;
                if (!gid_is_valid(gid))
                        gid = 0;
        }

        for (size_t i = 0; i < context->directories[type].n_items; i++) {
                _cleanup_free_ char *p = NULL, *pp = NULL;

                p = path_join(params->prefix[type], context->directories[type].items[i].path);
                if (!p) {
                        r = -ENOMEM;
                        goto fail;
                }

                r = mkdir_parents_label(p, 0755);
                if (r < 0)
                        goto fail;

                if (exec_directory_is_private(context, type)) {
                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
                         * case we want to avoid leaving a directory around fully accessible that is owned by
                         * a dynamic user whose UID is later on reused. To lock this down we use the same
                         * trick used by container managers to prohibit host users to get access to files of
                         * the same UID in containers: we place everything inside a directory that has an
                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
                         * for unprivileged host code. We then use fs namespacing to make this directory
                         * permeable for the service itself.
                         *
                         * Specifically: for a service which wants a special directory "foo/" we first create
                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
                         * unprivileged host users can't look into it. Inside of the namespace of the unit
                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
                         * for the service and making sure it only gets access to the dirs it needs but no
                         * others. Tricky? Yes, absolutely, but it works!
                         *
                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
                         * to be owned by the service itself.
                         *
                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
                         * for sharing files or sockets with other services. */

                        pp = path_join(params->prefix[type], "private");
                        if (!pp) {
                                r = -ENOMEM;
                                goto fail;
                        }

                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
                        if (r < 0)
                                goto fail;

                        if (!path_extend(&pp, context->directories[type].items[i].path)) {
                                r = -ENOMEM;
                                goto fail;
                        }

                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
                        r = mkdir_parents_label(pp, 0755);
                        if (r < 0)
                                goto fail;

                        if (is_dir(p, false) > 0 &&
                            (laccess(pp, F_OK) < 0 && errno == ENOENT)) {

                                /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
                                 * it over. Most likely the service has been upgraded from one that didn't use
                                 * DynamicUser=1, to one that does. */

                                log_info("Found pre-existing public %s= directory %s, migrating to %s.\n"
                                         "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
                                         exec_directory_type_to_string(type), p, pp);

                                if (rename(p, pp) < 0) {
                                        r = -errno;
                                        goto fail;
                                }
                        } else {
                                /* Otherwise, create the actual directory for the service */

                                r = mkdir_label(pp, context->directories[type].mode);
                                if (r < 0 && r != -EEXIST)
                                        goto fail;
                        }

                        if (!context->directories[type].items[i].only_create) {
                                /* And link it up from the original place.
                                 * Notes
                                 * 1) If a mount namespace is going to be used, then this symlink remains on
                                 *    the host, and a new one for the child namespace will be created later.
                                 * 2) It is not necessary to create this symlink when one of its parent
                                 *    directories is specified and already created. E.g.
                                 *        StateDirectory=foo foo/bar
                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
                                 *        pp = "/var/lib/private/foo/bar"
                                 *        p = "/var/lib/foo/bar"
                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
                                 *    we do not need to create the symlink, but we cannot create the symlink.
                                 *    See issue #24783. */
                                r = symlink_idempotent(pp, p, true);
                                if (r < 0)
                                        goto fail;
                        }

                } else {
                        _cleanup_free_ char *target = NULL;

                        if (type != EXEC_DIRECTORY_CONFIGURATION &&
                            readlink_and_make_absolute(p, &target) >= 0) {
                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;

                                /* This already exists and is a symlink? Interesting. Maybe it's one created
                                 * by DynamicUser=1 (see above)?
                                 *
                                 * We do this for all directory types except for ConfigurationDirectory=,
                                 * since they all support the private/ symlink logic at least in some
                                 * configurations, see above. */

                                r = chase(target, NULL, 0, &target_resolved, NULL);
                                if (r < 0)
                                        goto fail;

                                q = path_join(params->prefix[type], "private", context->directories[type].items[i].path);
                                if (!q) {
                                        r = -ENOMEM;
                                        goto fail;
                                }

                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
                                if (r < 0)
                                        goto fail;

                                if (path_equal(q_resolved, target_resolved)) {

                                        /* Hmm, apparently DynamicUser= was once turned on for this service,
                                         * but is no longer. Let's move the directory back up. */

                                        log_info("Found pre-existing private %s= directory %s, migrating to %s.\n"
                                                 "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
                                                 exec_directory_type_to_string(type), q, p);

                                        if (unlink(p) < 0) {
                                                r = -errno;
                                                goto fail;
                                        }

                                        if (rename(q, p) < 0) {
                                                r = -errno;
                                                goto fail;
                                        }
                                }
                        }

                        r = mkdir_label(p, context->directories[type].mode);
                        if (r < 0) {
                                if (r != -EEXIST)
                                        goto fail;

                                if (type == EXEC_DIRECTORY_CONFIGURATION) {
                                        struct stat st;

                                        /* Don't change the owner/access mode of the configuration directory,
                                         * as in the common case it is not written to by a service, and shall
                                         * not be writable. */

                                        if (stat(p, &st) < 0) {
                                                r = -errno;
                                                goto fail;
                                        }

                                        /* Still complain if the access mode doesn't match */
                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
                                                log_warning("%s \'%s\' already exists but the mode is different. "
                                                            "(File system: %o %sMode: %o)",
                                                            exec_directory_type_to_string(type), context->directories[type].items[i].path,
                                                            st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);

                                        continue;
                                }
                        }
                }

                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
                 * current UID/GID ownership.) */
                r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID);
                if (r < 0)
                        goto fail;

                /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we
                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
                 * assignments to exist. */
                r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777);
                if (r < 0)
                        goto fail;
        }

        /* If we are not going to run in a namespace, set up the symlinks - otherwise
         * they are set up later, to allow configuring empty var/run/etc. */
        if (!needs_mount_namespace)
                for (size_t i = 0; i < context->directories[type].n_items; i++) {
                        r = create_many_symlinks(params->prefix[type],
                                                 context->directories[type].items[i].path,
                                                 context->directories[type].items[i].symlinks);
                        if (r < 0)
                                goto fail;
                }

        return 0;

fail:
        *exit_status = exit_status_table[type];
        return r;
}

static int write_credential(
                int dfd,
                const char *id,
                const void *data,
                size_t size,
                uid_t uid,
                bool ownership_ok) {

        _cleanup_(unlink_and_freep) char *tmp = NULL;
        _cleanup_close_ int fd = -EBADF;
        int r;

        r = tempfn_random_child("", "cred", &tmp);
        if (r < 0)
                return r;

        fd = openat(dfd, tmp, O_CREAT|O_RDWR|O_CLOEXEC|O_EXCL|O_NOFOLLOW|O_NOCTTY, 0600);
        if (fd < 0) {
                tmp = mfree(tmp);
                return -errno;
        }

        r = loop_write(fd, data, size, /* do_poll = */ false);
        if (r < 0)
                return r;

        if (fchmod(fd, 0400) < 0) /* Take away "w" bit */
                return -errno;

        if (uid_is_valid(uid) && uid != getuid()) {
                r = fd_add_uid_acl_permission(fd, uid, ACL_READ);
                if (r < 0) {
                        if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
                                return r;

                        if (!ownership_ok) /* Ideally we use ACLs, since we can neatly express what we want
                                            * to express: that the user gets read access and nothing
                                            * else. But if the backing fs can't support that (e.g. ramfs)
                                            * then we can use file ownership instead. But that's only safe if
                                            * we can then re-mount the whole thing read-only, so that the
                                            * user can no longer chmod() the file to gain write access. */
                                return r;

                        if (fchown(fd, uid, GID_INVALID) < 0)
                                return -errno;
                }
        }

        if (renameat(dfd, tmp, dfd, id) < 0)
                return -errno;

        tmp = mfree(tmp);
        return 0;
}

static char **credential_search_path(
                const ExecParameters *params,
                bool encrypted) {

        _cleanup_strv_free_ char **l = NULL;

        assert(params);

        /* Assemble a search path to find credentials in. We'll look in /etc/credstore/ (and similar
         * directories in /usr/lib/ + /run/) for all types of credentials. If we are looking for encrypted
         * credentials, also look in /etc/credstore.encrypted/ (and similar dirs). */

        if (encrypted) {
                if (strv_extend(&l, params->received_encrypted_credentials_directory) < 0)
                        return NULL;

                if (strv_extend_strv(&l, CONF_PATHS_STRV("credstore.encrypted"), /* filter_duplicates= */ true) < 0)
                        return NULL;
        }

        if (params->received_credentials_directory)
                if (strv_extend(&l, params->received_credentials_directory) < 0)
                        return NULL;

        if (strv_extend_strv(&l, CONF_PATHS_STRV("credstore"), /* filter_duplicates= */ true) < 0)
                return NULL;

        if (DEBUG_LOGGING) {
                _cleanup_free_ char *t = strv_join(l, ":");

                log_debug("Credential search path is: %s", strempty(t));
        }

        return TAKE_PTR(l);
}

static int load_credential(
                const ExecContext *context,
                const ExecParameters *params,
                const char *id,
                const char *path,
                bool encrypted,
                const char *unit,
                int read_dfd,
                int write_dfd,
                uid_t uid,
                bool ownership_ok,
                uint64_t *left) {

        ReadFullFileFlags flags = READ_FULL_FILE_SECURE|READ_FULL_FILE_FAIL_WHEN_LARGER;
        _cleanup_strv_free_ char **search_path = NULL;
        _cleanup_(erase_and_freep) char *data = NULL;
        _cleanup_free_ char *bindname = NULL;
        const char *source = NULL;
        bool missing_ok = true;
        size_t size, add, maxsz;
        int r;

        assert(context);
        assert(params);
        assert(id);
        assert(path);
        assert(unit);
        assert(read_dfd >= 0 || read_dfd == AT_FDCWD);
        assert(write_dfd >= 0);
        assert(left);

        if (read_dfd >= 0) {
                /* If a directory fd is specified, then read the file directly from that dir. In this case we
                 * won't do AF_UNIX stuff (we simply don't want to recursively iterate down a tree of AF_UNIX
                 * IPC sockets). It's OK if a file vanishes here in the time we enumerate it and intend to
                 * open it. */

                if (!filename_is_valid(path)) /* safety check */
                        return -EINVAL;

                missing_ok = true;
                source = path;

        } else if (path_is_absolute(path)) {
                /* If this is an absolute path, read the data directly from it, and support AF_UNIX
                 * sockets */

                if (!path_is_valid(path)) /* safety check */
                        return -EINVAL;

                flags |= READ_FULL_FILE_CONNECT_SOCKET;

                /* Pass some minimal info about the unit and the credential name we are looking to acquire
                 * via the source socket address in case we read off an AF_UNIX socket. */
                if (asprintf(&bindname, "@%" PRIx64"/unit/%s/%s", random_u64(), unit, id) < 0)
                        return -ENOMEM;

                missing_ok = false;
                source = path;

        } else if (credential_name_valid(path)) {
                /* If this is a relative path, take it as credential name relative to the credentials
                 * directory we received ourselves. We don't support the AF_UNIX stuff in this mode, since we
                 * are operating on a credential store, i.e. this is guaranteed to be regular files. */

                search_path = credential_search_path(params, encrypted);
                if (!search_path)
                        return -ENOMEM;

                missing_ok = true;
        } else
                source = NULL;

        if (encrypted)
                flags |= READ_FULL_FILE_UNBASE64;

        maxsz = encrypted ? CREDENTIAL_ENCRYPTED_SIZE_MAX : CREDENTIAL_SIZE_MAX;

        if (search_path) {
                STRV_FOREACH(d, search_path) {
                        _cleanup_free_ char *j = NULL;

                        j = path_join(*d, path);
                        if (!j)
                                return -ENOMEM;

                        r = read_full_file_full(
                                        AT_FDCWD, j, /* path is absolute, hence pass AT_FDCWD as nop dir fd here */
                                        UINT64_MAX,
                                        maxsz,
                                        flags,
                                        NULL,
                                        &data, &size);
                        if (r != -ENOENT)
                                break;
                }
        } else if (source)
                r = read_full_file_full(
                                read_dfd, source,
                                UINT64_MAX,
                                maxsz,
                                flags,
                                bindname,
                                &data, &size);
        else
                r = -ENOENT;

        if (r == -ENOENT && (missing_ok || hashmap_contains(context->set_credentials, id))) {
                /* Make a missing inherited credential non-fatal, let's just continue. After all apps
                 * will get clear errors if we don't pass such a missing credential on as they
                 * themselves will get ENOENT when trying to read them, which should not be much
                 * worse than when we handle the error here and make it fatal.
                 *
                 * Also, if the source file doesn't exist, but a fallback is set via SetCredentials=
                 * we are fine, too. */
                log_debug_errno(r, "Couldn't read inherited credential '%s', skipping: %m", path);
                return 0;
        }
        if (r < 0)
                return log_debug_errno(r, "Failed to read credential '%s': %m", path);

        if (encrypted) {
                _cleanup_free_ void *plaintext = NULL;
                size_t plaintext_size = 0;

                r = decrypt_credential_and_warn(id, now(CLOCK_REALTIME), NULL, NULL, data, size, &plaintext, &plaintext_size);
                if (r < 0)
                        return r;

                free_and_replace(data, plaintext);
                size = plaintext_size;
        }

        add = strlen(id) + size;
        if (add > *left)
                return -E2BIG;

        r = write_credential(write_dfd, id, data, size, uid, ownership_ok);
        if (r < 0)
                return log_debug_errno(r, "Failed to write credential '%s': %m", id);

        *left -= add;
        return 0;
}

struct load_cred_args {
        const ExecContext *context;
        const ExecParameters *params;
        bool encrypted;
        const char *unit;
        int dfd;
        uid_t uid;
        bool ownership_ok;
        uint64_t *left;
};

static int load_cred_recurse_dir_cb(
                RecurseDirEvent event,
                const char *path,
                int dir_fd,
                int inode_fd,
                const struct dirent *de,
                const struct statx *sx,
                void *userdata) {

        struct load_cred_args *args = ASSERT_PTR(userdata);
        _cleanup_free_ char *sub_id = NULL;
        int r;

        if (event != RECURSE_DIR_ENTRY)
                return RECURSE_DIR_CONTINUE;

        if (!IN_SET(de->d_type, DT_REG, DT_SOCK))
                return RECURSE_DIR_CONTINUE;

        sub_id = strreplace(path, "/", "_");
        if (!sub_id)
                return -ENOMEM;

        if (!credential_name_valid(sub_id))
                return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Credential would get ID %s, which is not valid, refusing", sub_id);

        if (faccessat(args->dfd, sub_id, F_OK, AT_SYMLINK_NOFOLLOW) >= 0) {
                log_debug("Skipping credential with duplicated ID %s at %s", sub_id, path);
                return RECURSE_DIR_CONTINUE;
        }
        if (errno != ENOENT)
                return log_debug_errno(errno, "Failed to test if credential %s exists: %m", sub_id);

        r = load_credential(
                        args->context,
                        args->params,
                        sub_id,
                        de->d_name,
                        args->encrypted,
                        args->unit,
                        dir_fd,
                        args->dfd,
                        args->uid,
                        args->ownership_ok,
                        args->left);
        if (r < 0)
                return r;

        return RECURSE_DIR_CONTINUE;
}

static int acquire_credentials(
                const ExecContext *context,
                const ExecParameters *params,
                const char *unit,
                const char *p,
                uid_t uid,
                bool ownership_ok) {

        uint64_t left = CREDENTIALS_TOTAL_SIZE_MAX;
        _cleanup_close_ int dfd = -EBADF;
        ExecLoadCredential *lc;
        ExecSetCredential *sc;
        int r;

        assert(context);
        assert(p);

        dfd = open(p, O_DIRECTORY|O_CLOEXEC);
        if (dfd < 0)
                return -errno;

        /* First, load credentials off disk (or acquire via AF_UNIX socket) */
        HASHMAP_FOREACH(lc, context->load_credentials) {
                _cleanup_close_ int sub_fd = -EBADF;

                /* If this is an absolute path, then try to open it as a directory. If that works, then we'll
                 * recurse into it. If it is an absolute path but it isn't a directory, then we'll open it as
                 * a regular file. Finally, if it's a relative path we will use it as a credential name to
                 * propagate a credential passed to us from further up. */

                if (path_is_absolute(lc->path)) {
                        sub_fd = open(lc->path, O_DIRECTORY|O_CLOEXEC|O_RDONLY);
                        if (sub_fd < 0 && !IN_SET(errno,
                                                  ENOTDIR,  /* Not a directory */
                                                  ENOENT))  /* Doesn't exist? */
                                return log_debug_errno(errno, "Failed to open '%s': %m", lc->path);
                }

                if (sub_fd < 0)
                        /* Regular file (incl. a credential passed in from higher up) */
                        r = load_credential(
                                        context,
                                        params,
                                        lc->id,
                                        lc->path,
                                        lc->encrypted,
                                        unit,
                                        AT_FDCWD,
                                        dfd,
                                        uid,
                                        ownership_ok,
                                        &left);
                else
                        /* Directory */
                        r = recurse_dir(
                                        sub_fd,
                                        /* path= */ lc->id, /* recurse_dir() will suffix the subdir paths from here to the top-level id */
                                        /* statx_mask= */ 0,
                                        /* n_depth_max= */ UINT_MAX,
                                        RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE,
                                        load_cred_recurse_dir_cb,
                                        &(struct load_cred_args) {
                                                .context = context,
                                                .params = params,
                                                .encrypted = lc->encrypted,
                                                .unit = unit,
                                                .dfd = dfd,
                                                .uid = uid,
                                                .ownership_ok = ownership_ok,
                                                .left = &left,
                                        });
                if (r < 0)
                        return r;
        }

        /* Second, we add in literally specified credentials. If the credentials already exist, we'll not add
         * them, so that they can act as a "default" if the same credential is specified multiple times. */
        HASHMAP_FOREACH(sc, context->set_credentials) {
                _cleanup_(erase_and_freep) void *plaintext = NULL;
                const char *data;
                size_t size, add;

                /* Note that we check ahead of time here instead of relying on O_EXCL|O_CREAT later to return
                 * EEXIST if the credential already exists. That's because the TPM2-based decryption is kinda
                 * slow and involved, hence it's nice to be able to skip that if the credential already
                 * exists anyway. */
                if (faccessat(dfd, sc->id, F_OK, AT_SYMLINK_NOFOLLOW) >= 0)
                        continue;
                if (errno != ENOENT)
                        return log_debug_errno(errno, "Failed to test if credential %s exists: %m", sc->id);

                if (sc->encrypted) {
                        r = decrypt_credential_and_warn(sc->id, now(CLOCK_REALTIME), NULL, NULL, sc->data, sc->size, &plaintext, &size);
                        if (r < 0)
                                return r;

                        data = plaintext;
                } else {
                        data = sc->data;
                        size = sc->size;
                }

                add = strlen(sc->id) + size;
                if (add > left)
                        return -E2BIG;

                r = write_credential(dfd, sc->id, data, size, uid, ownership_ok);
                if (r < 0)
                        return r;

                left -= add;
        }

        if (fchmod(dfd, 0500) < 0) /* Now take away the "w" bit */
                return -errno;

        /* After we created all keys with the right perms, also make sure the credential store as a whole is
         * accessible */

        if (uid_is_valid(uid) && uid != getuid()) {
                r = fd_add_uid_acl_permission(dfd, uid, ACL_READ | ACL_EXECUTE);
                if (r < 0) {
                        if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
                                return r;

                        if (!ownership_ok)
                                return r;

                        if (fchown(dfd, uid, GID_INVALID) < 0)
                                return -errno;
                }
        }

        return 0;
}

static int setup_credentials_internal(
                const ExecContext *context,
                const ExecParameters *params,
                const char *unit,
                const char *final,        /* This is where the credential store shall eventually end up at */
                const char *workspace,    /* This is where we can prepare it before moving it to the final place */
                bool reuse_workspace,     /* Whether to reuse any existing workspace mount if it already is a mount */
                bool must_mount,          /* Whether to require that we mount something, it's not OK to use the plain directory fall back */
                uid_t uid) {

        int r, workspace_mounted; /* negative if we don't know yet whether we have/can mount something; true
                                   * if we mounted something; false if we definitely can't mount anything */
        bool final_mounted;
        const char *where;

        assert(context);
        assert(final);
        assert(workspace);

        if (reuse_workspace) {
                r = path_is_mount_point(workspace, NULL, 0);
                if (r < 0)
                        return r;
                if (r > 0)
                        workspace_mounted = true; /* If this is already a mount, and we are supposed to reuse it, let's keep this in mind */
                else
                        workspace_mounted = -1; /* We need to figure out if we can mount something to the workspace */
        } else
                workspace_mounted = -1; /* ditto */

        r = path_is_mount_point(final, NULL, 0);
        if (r < 0)
                return r;
        if (r > 0) {
                /* If the final place already has something mounted, we use that. If the workspace also has
                 * something mounted we assume it's actually the same mount (but with MS_RDONLY
                 * different). */
                final_mounted = true;

                if (workspace_mounted < 0) {
                        /* If the final place is mounted, but the workspace isn't, then let's bind mount
                         * the final version to the workspace, and make it writable, so that we can make
                         * changes */

                        r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL);
                        if (r < 0)
                                return r;

                        r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL);
                        if (r < 0)
                                return r;

                        workspace_mounted = true;
                }
        } else
                final_mounted = false;

        if (workspace_mounted < 0) {
                /* Nothing is mounted on the workspace yet, let's try to mount something now */
                for (int try = 0;; try++) {

                        if (try == 0) {
                                /* Try "ramfs" first, since it's not swap backed */
                                r = mount_nofollow_verbose(LOG_DEBUG, "ramfs", workspace, "ramfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, "mode=0700");
                                if (r >= 0) {
                                        workspace_mounted = true;
                                        break;
                                }

                        } else if (try == 1) {
                                _cleanup_free_ char *opts = NULL;

                                if (asprintf(&opts, "mode=0700,nr_inodes=1024,size=%zu", (size_t) CREDENTIALS_TOTAL_SIZE_MAX) < 0)
                                        return -ENOMEM;

                                /* Fall back to "tmpfs" otherwise */
                                r = mount_nofollow_verbose(LOG_DEBUG, "tmpfs", workspace, "tmpfs", MS_NODEV|MS_NOEXEC|MS_NOSUID, opts);
                                if (r >= 0) {
                                        workspace_mounted = true;
                                        break;
                                }

                        } else {
                                /* If that didn't work, try to make a bind mount from the final to the workspace, so that we can make it writable there. */
                                r = mount_nofollow_verbose(LOG_DEBUG, final, workspace, NULL, MS_BIND|MS_REC, NULL);
                                if (r < 0) {
                                        if (!ERRNO_IS_PRIVILEGE(r)) /* Propagate anything that isn't a permission problem */
                                                return r;

                                        if (must_mount) /* If we it's not OK to use the plain directory
                                                         * fallback, propagate all errors too */
                                                return r;

                                        /* If we lack privileges to bind mount stuff, then let's gracefully
                                         * proceed for compat with container envs, and just use the final dir
                                         * as is. */

                                        workspace_mounted = false;
                                        break;
                                }

                                /* Make the new bind mount writable (i.e. drop MS_RDONLY) */
                                r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL);
                                if (r < 0)
                                        return r;

                                workspace_mounted = true;
                                break;
                        }
                }
        }

        assert(!must_mount || workspace_mounted > 0);
        where = workspace_mounted ? workspace : final;

        (void) label_fix_full(AT_FDCWD, where, final, 0);

        r = acquire_credentials(context, params, unit, where, uid, workspace_mounted);
        if (r < 0)
                return r;

        if (workspace_mounted) {
                bool install;

                /* Determine if we should actually install the prepared mount in the final location by bind
                 * mounting it there. We do so only if the mount is not established there already, and if the
                 * mount is actually non-empty (i.e. carries at least one credential). Not that in the best
                 * case we are doing all this in a mount namespace, thus no one else will see that we
                 * allocated a file system we are getting rid of again here. */
                if (final_mounted)
                        install = false; /* already installed */
                else {
                        r = dir_is_empty(where, /* ignore_hidden_or_backup= */ false);
                        if (r < 0)
                                return r;

                        install = r == 0; /* install only if non-empty */
                }

                if (install) {
                        /* Make workspace read-only now, so that any bind mount we make from it defaults to read-only too */
                        r = mount_nofollow_verbose(LOG_DEBUG, NULL, workspace, NULL, MS_BIND|MS_REMOUNT|MS_RDONLY|MS_NODEV|MS_NOEXEC|MS_NOSUID, NULL);
                        if (r < 0)
                                return r;

                        /* And mount it to the final place, read-only */
                        r = mount_nofollow_verbose(LOG_DEBUG, workspace, final, NULL, MS_MOVE, NULL);
                } else
                        /* Otherwise get rid of it */
                        r = umount_verbose(LOG_DEBUG, workspace, MNT_DETACH|UMOUNT_NOFOLLOW);
                if (r < 0)
                        return r;
        } else {
                _cleanup_free_ char *parent = NULL;

                /* If we do not have our own mount put used the plain directory fallback, then we need to
                 * open access to the top-level credential directory and the per-service directory now */

                r = path_extract_directory(final, &parent);
                if (r < 0)
                        return r;
                if (chmod(parent, 0755) < 0)
                        return -errno;
        }

        return 0;
}

static int setup_credentials(
                const ExecContext *context,
                const ExecParameters *params,
                const char *unit,
                uid_t uid) {

        _cleanup_free_ char *p = NULL, *q = NULL;
        int r;

        assert(context);
        assert(params);

        if (!exec_context_has_credentials(context))
                return 0;

        if (!params->prefix[EXEC_DIRECTORY_RUNTIME])
                return -EINVAL;

        /* This where we'll place stuff when we are done; this main credentials directory is world-readable,
         * and the subdir we mount over with a read-only file system readable by the service's user */
        q = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials");
        if (!q)
                return -ENOMEM;

        r = mkdir_label(q, 0755); /* top-level dir: world readable/searchable */
        if (r < 0 && r != -EEXIST)
                return r;

        p = path_join(q, unit);
        if (!p)
                return -ENOMEM;

        r = mkdir_label(p, 0700); /* per-unit dir: private to user */
        if (r < 0 && r != -EEXIST)
                return r;

        r = safe_fork("(sd-mkdcreds)", FORK_DEATHSIG|FORK_WAIT|FORK_NEW_MOUNTNS, NULL);
        if (r < 0) {
                _cleanup_free_ char *t = NULL, *u = NULL;

                /* If this is not a privilege or support issue then propagate the error */
                if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
                        return r;

                /* Temporary workspace, that remains inaccessible all the time. We prepare stuff there before moving
                 * it into place, so that users can't access half-initialized credential stores. */
                t = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "systemd/temporary-credentials");
                if (!t)
                        return -ENOMEM;

                /* We can't set up a mount namespace. In that case operate on a fixed, inaccessible per-unit
                 * directory outside of /run/credentials/ first, and then move it over to /run/credentials/
                 * after it is fully set up */
                u = path_join(t, unit);
                if (!u)
                        return -ENOMEM;

                FOREACH_STRING(i, t, u) {
                        r = mkdir_label(i, 0700);
                        if (r < 0 && r != -EEXIST)
                                return r;
                }

                r = setup_credentials_internal(
                                context,
                                params,
                                unit,
                                p,       /* final mount point */
                                u,       /* temporary workspace to overmount */
                                true,    /* reuse the workspace if it is already a mount */
                                false,   /* it's OK to fall back to a plain directory if we can't mount anything */
                                uid);

                (void) rmdir(u); /* remove the workspace again if we can. */

                if (r < 0)
                        return r;

        } else if (r == 0) {

                /* We managed to set up a mount namespace, and are now in a child. That's great. In this case
                 * we can use the same directory for all cases, after turning off propagation. Question
                 * though is: where do we turn off propagation exactly, and where do we place the workspace
                 * directory? We need some place that is guaranteed to be a mount point in the host, and
                 * which is guaranteed to have a subdir we can mount over. /run/ is not suitable for this,
                 * since we ultimately want to move the resulting file system there, i.e. we need propagation
                 * for /run/ eventually. We could use our own /run/systemd/bind mount on itself, but that
                 * would be visible in the host mount table all the time, which we want to avoid. Hence, what
                 * we do here instead we use /dev/ and /dev/shm/ for our purposes. We know for sure that
                 * /dev/ is a mount point and we now for sure that /dev/shm/ exists. Hence we can turn off
                 * propagation on the former, and then overmount the latter.
                 *
                 * Yes it's nasty playing games with /dev/ and /dev/shm/ like this, since it does not exist
                 * for this purpose, but there are few other candidates that work equally well for us, and
                 * given that the we do this in a privately namespaced short-lived single-threaded process
                 * that no one else sees this should be OK to do. */

                r = mount_nofollow_verbose(LOG_DEBUG, NULL, "/dev", NULL, MS_SLAVE|MS_REC, NULL); /* Turn off propagation from our namespace to host */
                if (r < 0)
                        goto child_fail;

                r = setup_credentials_internal(
                                context,
                                params,
                                unit,
                                p,           /* final mount point */
                                "/dev/shm",  /* temporary workspace to overmount */
                                false,       /* do not reuse /dev/shm if it is already a mount, under no circumstances */
                                true,        /* insist that something is mounted, do not allow fallback to plain directory */
                                uid);
                if (r < 0)
                        goto child_fail;

                _exit(EXIT_SUCCESS);

        child_fail:
                _exit(EXIT_FAILURE);
        }

        /* If the credentials dir is empty and not a mount point, then there's no point in having it. Let's
         * try to remove it. This matters in particular if we created the dir as mount point but then didn't
         * actually end up mounting anything on it. In that case we'd rather have ENOENT than EACCESS being
         * seen by users when trying access this inode. */
        (void) rmdir(p);
        return 0;
}

#if ENABLE_SMACK
static int setup_smack(
                const Manager *manager,
                const ExecContext *context,
                int executable_fd) {
        int r;

        assert(context);
        assert(executable_fd >= 0);

        if (context->smack_process_label) {
                r = mac_smack_apply_pid(0, context->smack_process_label);
                if (r < 0)
                        return r;
        } else if (manager->default_smack_process_label) {
                _cleanup_free_ char *exec_label = NULL;

                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
                        return r;

                r = mac_smack_apply_pid(0, exec_label ?: manager->default_smack_process_label);
                if (r < 0)
                        return r;
        }

        return 0;
}
#endif

static int compile_bind_mounts(
                const ExecContext *context,
                const ExecParameters *params,
                BindMount **ret_bind_mounts,
                size_t *ret_n_bind_mounts,
                char ***ret_empty_directories) {

        _cleanup_strv_free_ char **empty_directories = NULL;
        BindMount *bind_mounts = NULL;
        size_t n, h = 0;
        int r;

        assert(context);
        assert(params);
        assert(ret_bind_mounts);
        assert(ret_n_bind_mounts);
        assert(ret_empty_directories);

        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);

        n = context->n_bind_mounts;
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                if (!params->prefix[t])
                        continue;

                for (size_t i = 0; i < context->directories[t].n_items; i++)
                        n += !context->directories[t].items[i].only_create;
        }

        if (n <= 0) {
                *ret_bind_mounts = NULL;
                *ret_n_bind_mounts = 0;
                *ret_empty_directories = NULL;
                return 0;
        }

        bind_mounts = new(BindMount, n);
        if (!bind_mounts)
                return -ENOMEM;

        for (size_t i = 0; i < context->n_bind_mounts; i++) {
                BindMount *item = context->bind_mounts + i;
                _cleanup_free_ char *s = NULL, *d = NULL;

                s = strdup(item->source);
                if (!s)
                        return -ENOMEM;

                d = strdup(item->destination);
                if (!d)
                        return -ENOMEM;

                bind_mounts[h++] = (BindMount) {
                        .source = TAKE_PTR(s),
                        .destination = TAKE_PTR(d),
                        .read_only = item->read_only,
                        .recursive = item->recursive,
                        .ignore_enoent = item->ignore_enoent,
                };
        }

        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                if (!params->prefix[t])
                        continue;

                if (context->directories[t].n_items == 0)
                        continue;

                if (exec_directory_is_private(context, t) &&
                    !exec_context_with_rootfs(context)) {
                        char *private_root;

                        /* So this is for a dynamic user, and we need to make sure the process can access its own
                         * directory. For that we overmount the usually inaccessible "private" subdirectory with a
                         * tmpfs that makes it accessible and is empty except for the submounts we do this for. */

                        private_root = path_join(params->prefix[t], "private");
                        if (!private_root)
                                return -ENOMEM;

                        r = strv_consume(&empty_directories, private_root);
                        if (r < 0)
                                return r;
                }

                for (size_t i = 0; i < context->directories[t].n_items; i++) {
                        _cleanup_free_ char *s = NULL, *d = NULL;

                        /* When one of the parent directories is in the list, we cannot create the symlink
                         * for the child directory. See also the comments in setup_exec_directory(). */
                        if (context->directories[t].items[i].only_create)
                                continue;

                        if (exec_directory_is_private(context, t))
                                s = path_join(params->prefix[t], "private", context->directories[t].items[i].path);
                        else
                                s = path_join(params->prefix[t], context->directories[t].items[i].path);
                        if (!s)
                                return -ENOMEM;

                        if (exec_directory_is_private(context, t) &&
                            exec_context_with_rootfs(context))
                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
                                 * directory is not created on the root directory. So, let's bind-mount the directory
                                 * on the 'non-private' place. */
                                d = path_join(params->prefix[t], context->directories[t].items[i].path);
                        else
                                d = strdup(s);
                        if (!d)
                                return -ENOMEM;

                        bind_mounts[h++] = (BindMount) {
                                .source = TAKE_PTR(s),
                                .destination = TAKE_PTR(d),
                                .read_only = false,
                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
                                .recursive = true,
                                .ignore_enoent = false,
                        };
                }
        }

        assert(h == n);

        *ret_bind_mounts = TAKE_PTR(bind_mounts);
        *ret_n_bind_mounts = n;
        *ret_empty_directories = TAKE_PTR(empty_directories);

        return (int) n;
}

/* ret_symlinks will contain a list of pairs src:dest that describes
 * the symlinks to create later on. For example, the symlinks needed
 * to safely give private directories to DynamicUser=1 users. */
static int compile_symlinks(
                const ExecContext *context,
                const ExecParameters *params,
                char ***ret_symlinks) {

        _cleanup_strv_free_ char **symlinks = NULL;
        int r;

        assert(context);
        assert(params);
        assert(ret_symlinks);

        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
                for (size_t i = 0; i < context->directories[dt].n_items; i++) {
                        _cleanup_free_ char *private_path = NULL, *path = NULL;

                        STRV_FOREACH(symlink, context->directories[dt].items[i].symlinks) {
                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;

                                src_abs = path_join(params->prefix[dt], context->directories[dt].items[i].path);
                                dst_abs = path_join(params->prefix[dt], *symlink);
                                if (!src_abs || !dst_abs)
                                        return -ENOMEM;

                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
                                if (r < 0)
                                        return r;
                        }

                        if (!exec_directory_is_private(context, dt) ||
                            exec_context_with_rootfs(context) ||
                            context->directories[dt].items[i].only_create)
                                continue;

                        private_path = path_join(params->prefix[dt], "private", context->directories[dt].items[i].path);
                        if (!private_path)
                                return -ENOMEM;

                        path = path_join(params->prefix[dt], context->directories[dt].items[i].path);
                        if (!path)
                                return -ENOMEM;

                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
                        if (r < 0)
                                return r;
                }
        }

        *ret_symlinks = TAKE_PTR(symlinks);

        return 0;
}

static bool insist_on_sandboxing(
                const ExecContext *context,
                const char *root_dir,
                const char *root_image,
                const BindMount *bind_mounts,
                size_t n_bind_mounts) {

        assert(context);
        assert(n_bind_mounts == 0 || bind_mounts);

        /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
         * would alter the view on the file system beyond making things read-only or invisible, i.e. would
         * rearrange stuff in a way we cannot ignore gracefully. */

        if (context->n_temporary_filesystems > 0)
                return true;

        if (root_dir || root_image)
                return true;

        if (context->n_mount_images > 0)
                return true;

        if (context->dynamic_user)
                return true;

        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
                return true;

        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
         * essential. */
        for (size_t i = 0; i < n_bind_mounts; i++)
                if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
                        return true;

        if (context->log_namespace)
                return true;

        return false;
}

static int apply_mount_namespace(
                const Unit *u,
                ExecCommandFlags command_flags,
                const ExecContext *context,
                const ExecParameters *params,
                const ExecRuntime *runtime,
                const char *memory_pressure_path,
                char **error_path) {

        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
                        **read_write_paths_cleanup = NULL;
        const char *tmp_dir = NULL, *var_tmp_dir = NULL;
        const char *root_dir = NULL, *root_image = NULL;
        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
                        *extension_dir = NULL;
        char **read_write_paths;
        NamespaceInfo ns_info;
        bool needs_sandboxing;
        BindMount *bind_mounts = NULL;
        size_t n_bind_mounts = 0;
        int r;

        assert(context);

        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);

        if (params->flags & EXEC_APPLY_CHROOT) {
                root_image = context->root_image;

                if (!root_image)
                        root_dir = context->root_directory;
        }

        r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
        if (r < 0)
                return r;

        /* Symlinks for exec dirs are set up after other mounts, before they are made read-only. */
        r = compile_symlinks(context, params, &symlinks);
        if (r < 0)
                return r;

        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
         * service will need to write to it in order to start the notifications. */
        if (context->protect_control_groups && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
                read_write_paths_cleanup = strv_copy(context->read_write_paths);
                if (!read_write_paths_cleanup)
                        return -ENOMEM;

                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
                if (r < 0)
                        return r;

                read_write_paths = read_write_paths_cleanup;
        } else
                read_write_paths = context->read_write_paths;

        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED);
        if (needs_sandboxing) {
                /* The runtime struct only contains the parent of the private /tmp,
                 * which is non-accessible to world users. Inside of it there's a /tmp
                 * that is sticky, and that's the one we want to use here.
                 * This does not apply when we are using /run/systemd/empty as fallback. */

                if (context->private_tmp && runtime && runtime->shared) {
                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
                                tmp_dir = runtime->shared->tmp_dir;
                        else if (runtime->shared->tmp_dir)
                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");

                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
                                var_tmp_dir = runtime->shared->var_tmp_dir;
                        else if (runtime->shared->var_tmp_dir)
                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
                }

                ns_info = (NamespaceInfo) {
                        .ignore_protect_paths = false,
                        .private_dev = context->private_devices,
                        .protect_control_groups = context->protect_control_groups,
                        .protect_kernel_tunables = context->protect_kernel_tunables,
                        .protect_kernel_modules = context->protect_kernel_modules,
                        .protect_kernel_logs = context->protect_kernel_logs,
                        .protect_hostname = context->protect_hostname,
                        .mount_apivfs = exec_context_get_effective_mount_apivfs(context),
                        .protect_home = context->protect_home,
                        .protect_system = context->protect_system,
                        .protect_proc = context->protect_proc,
                        .proc_subset = context->proc_subset,
                        .private_network = exec_needs_network_namespace(context),
                        .private_ipc = exec_needs_ipc_namespace(context),
                        /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
                        .mount_nosuid = context->no_new_privileges && !mac_selinux_use(),
                };
        } else if (!context->dynamic_user && root_dir)
                /*
                 * If DynamicUser=no and RootDirectory= is set then lets pass a relaxed
                 * sandbox info, otherwise enforce it, don't ignore protected paths and
                 * fail if we are enable to apply the sandbox inside the mount namespace.
                 */
                ns_info = (NamespaceInfo) {
                        .ignore_protect_paths = true,
                };
        else
                ns_info = (NamespaceInfo) {};

        if (context->mount_propagation_flag == MS_SHARED)
                log_unit_debug(u, "shared mount propagation hidden by other fs namespacing unit settings: ignoring");

        if (exec_context_has_credentials(context) &&
            params->prefix[EXEC_DIRECTORY_RUNTIME] &&
            FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
                creds_path = path_join(params->prefix[EXEC_DIRECTORY_RUNTIME], "credentials", u->id);
                if (!creds_path)
                        return -ENOMEM;
        }

        if (MANAGER_IS_SYSTEM(u->manager)) {
                propagate_dir = path_join("/run/systemd/propagate/", u->id);
                if (!propagate_dir)
                        return -ENOMEM;

                incoming_dir = strdup("/run/systemd/incoming");
                if (!incoming_dir)
                        return -ENOMEM;

                extension_dir = strdup("/run/systemd/unit-extensions");
                if (!extension_dir)
                        return -ENOMEM;
        } else
                if (asprintf(&extension_dir, "/run/user/" UID_FMT "/systemd/unit-extensions", geteuid()) < 0)
                        return -ENOMEM;

        r = setup_namespace(
                        root_dir,
                        root_image,
                        context->root_image_options,
                        context->root_image_policy ?: &image_policy_service,
                        &ns_info,
                        read_write_paths,
                        needs_sandboxing ? context->read_only_paths : NULL,
                        needs_sandboxing ? context->inaccessible_paths : NULL,
                        needs_sandboxing ? context->exec_paths : NULL,
                        needs_sandboxing ? context->no_exec_paths : NULL,
                        empty_directories,
                        symlinks,
                        bind_mounts,
                        n_bind_mounts,
                        context->temporary_filesystems,
                        context->n_temporary_filesystems,
                        context->mount_images,
                        context->n_mount_images,
                        context->mount_image_policy ?: &image_policy_service,
                        tmp_dir,
                        var_tmp_dir,
                        creds_path,
                        context->log_namespace,
                        context->mount_propagation_flag,
                        context->root_hash, context->root_hash_size, context->root_hash_path,
                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
                        context->root_verity,
                        context->extension_images,
                        context->n_extension_images,
                        context->extension_image_policy ?: &image_policy_sysext,
                        context->extension_directories,
                        propagate_dir,
                        incoming_dir,
                        extension_dir,
                        root_dir || root_image ? params->notify_socket : NULL,
                        error_path);

        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
         * completely different execution environment. */
        if (r == -ENOANO) {
                if (insist_on_sandboxing(
                                    context,
                                    root_dir, root_image,
                                    bind_mounts,
                                    n_bind_mounts))
                        return log_unit_debug_errno(u,
                                                    SYNTHETIC_ERRNO(EOPNOTSUPP),
                                                    "Failed to set up namespace, and refusing to continue since "
                                                    "the selected namespacing options alter mount environment non-trivially.\n"
                                                    "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
                                                    n_bind_mounts,
                                                    context->n_temporary_filesystems,
                                                    yes_no(root_dir),
                                                    yes_no(root_image),
                                                    yes_no(context->dynamic_user));

                log_unit_debug(u, "Failed to set up namespace, assuming containerized execution and ignoring.");
                return 0;
        }

        return r;
}

static int apply_working_directory(
                const ExecContext *context,
                const ExecParameters *params,
                const char *home,
                int *exit_status) {

        const char *d, *wd;

        assert(context);
        assert(exit_status);

        if (context->working_directory_home) {

                if (!home) {
                        *exit_status = EXIT_CHDIR;
                        return -ENXIO;
                }

                wd = home;

        } else
                wd = empty_to_root(context->working_directory);

        if (params->flags & EXEC_APPLY_CHROOT)
                d = wd;
        else
                d = prefix_roota(context->root_directory, wd);

        if (chdir(d) < 0 && !context->working_directory_missing_ok) {
                *exit_status = EXIT_CHDIR;
                return -errno;
        }

        return 0;
}

static int apply_root_directory(
                const ExecContext *context,
                const ExecParameters *params,
                const bool needs_mount_ns,
                int *exit_status) {

        assert(context);
        assert(exit_status);

        if (params->flags & EXEC_APPLY_CHROOT)
                if (!needs_mount_ns && context->root_directory)
                        if (chroot(context->root_directory) < 0) {
                                *exit_status = EXIT_CHROOT;
                                return -errno;
                        }

        return 0;
}

static int setup_keyring(
                const Unit *u,
                const ExecContext *context,
                const ExecParameters *p,
                uid_t uid, gid_t gid) {

        key_serial_t keyring;
        int r = 0;
        uid_t saved_uid;
        gid_t saved_gid;

        assert(u);
        assert(context);
        assert(p);

        /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
         * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
         * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
         * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
         * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
         * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */

        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
                return 0;

        /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
         * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
         * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
         * & group is just as nasty as acquiring a reference to the user keyring. */

        saved_uid = getuid();
        saved_gid = getgid();

        if (gid_is_valid(gid) && gid != saved_gid) {
                if (setregid(gid, -1) < 0)
                        return log_unit_error_errno(u, errno, "Failed to change GID for user keyring: %m");
        }

        if (uid_is_valid(uid) && uid != saved_uid) {
                if (setreuid(uid, -1) < 0) {
                        r = log_unit_error_errno(u, errno, "Failed to change UID for user keyring: %m");
                        goto out;
                }
        }

        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
        if (keyring == -1) {
                if (errno == ENOSYS)
                        log_unit_debug_errno(u, errno, "Kernel keyring not supported, ignoring.");
                else if (ERRNO_IS_PRIVILEGE(errno))
                        log_unit_debug_errno(u, errno, "Kernel keyring access prohibited, ignoring.");
                else if (errno == EDQUOT)
                        log_unit_debug_errno(u, errno, "Out of kernel keyrings to allocate, ignoring.");
                else
                        r = log_unit_error_errno(u, errno, "Setting up kernel keyring failed: %m");

                goto out;
        }

        /* When requested link the user keyring into the session keyring. */
        if (context->keyring_mode == EXEC_KEYRING_SHARED) {

                if (keyctl(KEYCTL_LINK,
                           KEY_SPEC_USER_KEYRING,
                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
                        r = log_unit_error_errno(u, errno, "Failed to link user keyring into session keyring: %m");
                        goto out;
                }
        }

        /* Restore uid/gid back */
        if (uid_is_valid(uid) && uid != saved_uid) {
                if (setreuid(saved_uid, -1) < 0) {
                        r = log_unit_error_errno(u, errno, "Failed to change UID back for user keyring: %m");
                        goto out;
                }
        }

        if (gid_is_valid(gid) && gid != saved_gid) {
                if (setregid(saved_gid, -1) < 0)
                        return log_unit_error_errno(u, errno, "Failed to change GID back for user keyring: %m");
        }

        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
        if (!sd_id128_is_null(u->invocation_id)) {
                key_serial_t key;

                key = add_key("user", "invocation_id", &u->invocation_id, sizeof(u->invocation_id), KEY_SPEC_SESSION_KEYRING);
                if (key == -1)
                        log_unit_debug_errno(u, errno, "Failed to add invocation ID to keyring, ignoring: %m");
                else {
                        if (keyctl(KEYCTL_SETPERM, key,
                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
                                r = log_unit_error_errno(u, errno, "Failed to restrict invocation ID permission: %m");
                }
        }

out:
        /* Revert back uid & gid for the last time, and exit */
        /* no extra logging, as only the first already reported error matters */
        if (getuid() != saved_uid)
                (void) setreuid(saved_uid, -1);

        if (getgid() != saved_gid)
                (void) setregid(saved_gid, -1);

        return r;
}

static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
        assert(array);
        assert(n);
        assert(pair);

        if (pair[0] >= 0)
                array[(*n)++] = pair[0];
        if (pair[1] >= 0)
                array[(*n)++] = pair[1];
}

static int close_remaining_fds(
                const ExecParameters *params,
                const ExecRuntime *runtime,
                int user_lookup_fd,
                int socket_fd,
                const int *fds, size_t n_fds) {

        size_t n_dont_close = 0;
        int dont_close[n_fds + 12];

        assert(params);

        if (params->stdin_fd >= 0)
                dont_close[n_dont_close++] = params->stdin_fd;
        if (params->stdout_fd >= 0)
                dont_close[n_dont_close++] = params->stdout_fd;
        if (params->stderr_fd >= 0)
                dont_close[n_dont_close++] = params->stderr_fd;

        if (socket_fd >= 0)
                dont_close[n_dont_close++] = socket_fd;
        if (n_fds > 0) {
                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
                n_dont_close += n_fds;
        }

        if (runtime && runtime->shared) {
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
        }

        if (runtime && runtime->dynamic_creds) {
                if (runtime->dynamic_creds->user)
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
                if (runtime->dynamic_creds->group)
                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
        }

        if (user_lookup_fd >= 0)
                dont_close[n_dont_close++] = user_lookup_fd;

        return close_all_fds(dont_close, n_dont_close);
}

static int send_user_lookup(
                Unit *unit,
                int user_lookup_fd,
                uid_t uid,
                gid_t gid) {

        assert(unit);

        /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
         * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
         * specified. */

        if (user_lookup_fd < 0)
                return 0;

        if (!uid_is_valid(uid) && !gid_is_valid(gid))
                return 0;

        if (writev(user_lookup_fd,
               (struct iovec[]) {
                           IOVEC_MAKE(&uid, sizeof(uid)),
                           IOVEC_MAKE(&gid, sizeof(gid)),
                           IOVEC_MAKE_STRING(unit->id) }, 3) < 0)
                return -errno;

        return 0;
}

static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
        int r;

        assert(c);
        assert(home);
        assert(buf);

        /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */

        if (*home)
                return 0;

        if (!c->working_directory_home)
                return 0;

        r = get_home_dir(buf);
        if (r < 0)
                return r;

        *home = *buf;
        return 1;
}

static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
        _cleanup_strv_free_ char ** list = NULL;
        int r;

        assert(c);
        assert(p);
        assert(ret);

        assert(c->dynamic_user);

        /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
         * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
         * directories. */

        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                if (t == EXEC_DIRECTORY_CONFIGURATION)
                        continue;

                if (!p->prefix[t])
                        continue;

                for (size_t i = 0; i < c->directories[t].n_items; i++) {
                        char *e;

                        if (exec_directory_is_private(c, t))
                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
                        else
                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
                        if (!e)
                                return -ENOMEM;

                        r = strv_consume(&list, e);
                        if (r < 0)
                                return r;
                }
        }

        *ret = TAKE_PTR(list);

        return 0;
}

static int exec_parameters_get_cgroup_path(
                const ExecParameters *params,
                const CGroupContext *c,
                char **ret) {

        const char *subgroup = NULL;
        char *p;

        assert(params);
        assert(ret);

        if (!params->cgroup_path)
                return -EINVAL;

        /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
         * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
         * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
         * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
         * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
         * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
         * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
         * flag, which is only passed for the former statements, not for the latter. */

        if (FLAGS_SET(params->flags, EXEC_CGROUP_DELEGATE) && (FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP) || c->delegate_subgroup)) {
                if (FLAGS_SET(params->flags, EXEC_IS_CONTROL))
                        subgroup = ".control";
                else
                        subgroup = c->delegate_subgroup;
        }

        if (subgroup)
                p = path_join(params->cgroup_path, subgroup);
        else
                p = strdup(params->cgroup_path);
        if (!p)
                return -ENOMEM;

        *ret = p;
        return !!subgroup;
}

static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
        _cleanup_(cpu_set_reset) CPUSet s = {};
        int r;

        assert(c);
        assert(ret);

        if (!c->numa_policy.nodes.set) {
                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
                return 0;
        }

        r = numa_to_cpu_set(&c->numa_policy, &s);
        if (r < 0)
                return r;

        cpu_set_reset(ret);

        return cpu_set_add_all(ret, &s);
}

bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) {
        assert(c);

        return c->cpu_affinity_from_numa;
}

static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int fd, int *ret_fd) {
        int r;

        assert(fds);
        assert(n_fds);
        assert(*n_fds < fds_size);
        assert(ret_fd);

        if (fd < 0) {
                *ret_fd = -EBADF;
                return 0;
        }

        if (fd < 3 + (int) *n_fds) {
                /* Let's move the fd up, so that it's outside of the fd range we will use to store
                 * the fds we pass to the process (or which are closed only during execve). */

                r = fcntl(fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
                if (r < 0)
                        return -errno;

                close_and_replace(fd, r);
        }

        *ret_fd = fds[*n_fds] = fd;
        (*n_fds) ++;
        return 1;
}

static int connect_unix_harder(Unit *u, const OpenFile *of, int ofd) {
        union sockaddr_union addr = {
                .un.sun_family = AF_UNIX,
        };
        socklen_t sa_len;
        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
        int r;

        assert(u);
        assert(of);
        assert(ofd >= 0);

        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
        if (r < 0)
                return log_unit_error_errno(u, r, "Failed to set sockaddr for %s: %m", of->path);

        sa_len = r;

        for (size_t i = 0; i < ELEMENTSOF(socket_types); i++) {
                _cleanup_close_ int fd = -EBADF;

                fd = socket(AF_UNIX, socket_types[i] | SOCK_CLOEXEC, 0);
                if (fd < 0)
                        return log_unit_error_errno(u, errno, "Failed to create socket for %s: %m", of->path);

                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
                if (r == -EPROTOTYPE)
                        continue;
                if (r < 0)
                        return log_unit_error_errno(u, r, "Failed to connect socket for %s: %m", of->path);

                return TAKE_FD(fd);
        }

        return log_unit_error_errno(u, SYNTHETIC_ERRNO(EPROTOTYPE), "Failed to connect socket for \"%s\".", of->path);
}

static int get_open_file_fd(Unit *u, const OpenFile *of) {
        struct stat st;
        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;

        assert(u);
        assert(of);

        ofd = open(of->path, O_PATH | O_CLOEXEC);
        if (ofd < 0)
                return log_unit_error_errno(u, errno, "Could not open \"%s\": %m", of->path);

        if (fstat(ofd, &st) < 0)
                return log_unit_error_errno(u, errno, "Failed to stat %s: %m", of->path);

        if (S_ISSOCK(st.st_mode)) {
                fd = connect_unix_harder(u, of, ofd);
                if (fd < 0)
                        return fd;

                if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
                        return log_unit_error_errno(u, errno, "Failed to shutdown send for socket %s: %m",
                                                    of->path);

                log_unit_debug(u, "socket %s opened (fd=%d)", of->path, fd);
        } else {
                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
                        flags |= O_APPEND;
                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
                        flags |= O_TRUNC;

                fd = fd_reopen(ofd, flags | O_CLOEXEC);
                if (fd < 0)
                        return log_unit_error_errno(u, fd, "Failed to open file %s: %m", of->path);

                log_unit_debug(u, "file %s opened (fd=%d)", of->path, fd);
        }

        return TAKE_FD(fd);
}

static int collect_open_file_fds(
                Unit *u,
                OpenFile* open_files,
                int **fds,
                char ***fdnames,
                size_t *n_fds) {
        int r;

        assert(u);
        assert(fds);
        assert(fdnames);
        assert(n_fds);

        LIST_FOREACH(open_files, of, open_files) {
                _cleanup_close_ int fd = -EBADF;

                fd = get_open_file_fd(u, of);
                if (fd < 0) {
                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
                                log_unit_debug_errno(u, fd, "Failed to get OpenFile= file descriptor for %s, ignoring: %m", of->path);
                                continue;
                        }

                        return fd;
                }

                if (!GREEDY_REALLOC(*fds, *n_fds + 1))
                        return -ENOMEM;

                r = strv_extend(fdnames, of->fdname);
                if (r < 0)
                        return r;

                (*fds)[*n_fds] = TAKE_FD(fd);

                (*n_fds)++;
        }

        return 0;
}

static void log_command_line(Unit *unit, const char *msg, const char *executable, char **argv) {
        assert(unit);
        assert(msg);
        assert(executable);

        if (!DEBUG_LOGGING)
                return;

        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);

        log_unit_struct(unit, LOG_DEBUG,
                        "EXECUTABLE=%s", executable,
                        LOG_UNIT_MESSAGE(unit, "%s: %s", msg, strnull(cmdline)),
                        LOG_UNIT_INVOCATION_ID(unit));
}

static bool exec_context_need_unprivileged_private_users(const ExecContext *context, const Manager *manager) {
        assert(context);
        assert(manager);

        /* These options require PrivateUsers= when used in user units, as we need to be in a user namespace
         * to have permission to enable them when not running as root. If we have effective CAP_SYS_ADMIN
         * (system manager) then we have privileges and don't need this. */
        if (MANAGER_IS_SYSTEM(manager))
                return false;

        return context->private_users ||
               context->private_tmp ||
               context->private_devices ||
               context->private_network ||
               context->network_namespace_path ||
               context->private_ipc ||
               context->ipc_namespace_path ||
               context->private_mounts ||
               context->mount_apivfs ||
               context->n_bind_mounts > 0 ||
               context->n_temporary_filesystems > 0 ||
               context->root_directory ||
               !strv_isempty(context->extension_directories) ||
               context->protect_system != PROTECT_SYSTEM_NO ||
               context->protect_home != PROTECT_HOME_NO ||
               context->protect_kernel_tunables ||
               context->protect_kernel_modules ||
               context->protect_kernel_logs ||
               context->protect_control_groups ||
               context->protect_clock ||
               context->protect_hostname ||
               !strv_isempty(context->read_write_paths) ||
               !strv_isempty(context->read_only_paths) ||
               !strv_isempty(context->inaccessible_paths) ||
               !strv_isempty(context->exec_paths) ||
               !strv_isempty(context->no_exec_paths);
}

static int exec_child(
                Unit *unit,
                const ExecCommand *command,
                const ExecContext *context,
                const ExecParameters *params,
                ExecRuntime *runtime,
                const CGroupContext *cgroup_context,
                int socket_fd,
                const int named_iofds[static 3],
                int *params_fds,
                size_t n_socket_fds,
                size_t n_storage_fds,
                char **files_env,
                int user_lookup_fd,
                int *exit_status) {

        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
        int r, ngids = 0, exec_fd;
        _cleanup_free_ gid_t *supplementary_gids = NULL;
        const char *username = NULL, *groupname = NULL;
        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL;
        const char *home = NULL, *shell = NULL;
        char **final_argv = NULL;
        dev_t journal_stream_dev = 0;
        ino_t journal_stream_ino = 0;
        bool userns_set_up = false;
        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
                needs_ambient_hack;     /* Do we need to apply the ambient capabilities hack? */
#if HAVE_SELINUX
        _cleanup_free_ char *mac_selinux_context_net = NULL;
        bool use_selinux = false;
#endif
#if ENABLE_SMACK
        bool use_smack = false;
#endif
#if HAVE_APPARMOR
        bool use_apparmor = false;
#endif
        uid_t saved_uid = getuid();
        gid_t saved_gid = getgid();
        uid_t uid = UID_INVALID;
        gid_t gid = GID_INVALID;
        size_t n_fds = n_socket_fds + n_storage_fds, /* fds to pass to the child */
               n_keep_fds; /* total number of fds not to close */
        int secure_bits;
        _cleanup_free_ gid_t *gids_after_pam = NULL;
        int ngids_after_pam = 0;
        _cleanup_free_ int *fds = NULL;
        _cleanup_strv_free_ char **fdnames = NULL;

        assert(unit);
        assert(command);
        assert(context);
        assert(params);
        assert(exit_status);

        /* Explicitly test for CVE-2021-4034 inspired invocations */
        assert(command->path);
        assert(!strv_isempty(command->argv));

        rename_process_from_path(command->path);

        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
         * both of which will be demoted to SIG_DFL. */
        (void) default_signals(SIGNALS_CRASH_HANDLER,
                               SIGNALS_IGNORE);

        if (context->ignore_sigpipe)
                (void) ignore_signals(SIGPIPE);

        r = reset_signal_mask();
        if (r < 0) {
                *exit_status = EXIT_SIGNAL_MASK;
                return log_unit_error_errno(unit, r, "Failed to set process signal mask: %m");
        }

        if (params->idle_pipe)
                do_idle_pipe_dance(params->idle_pipe);

        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */

        log_forget_fds();
        log_set_open_when_needed(true);
        log_settle_target();

        /* In case anything used libc syslog(), close this here, too */
        closelog();

        fds = newdup(int, params_fds, n_fds);
        if (!fds) {
                *exit_status = EXIT_MEMORY;
                return log_oom();
        }

        fdnames = strv_copy((char**) params->fd_names);
        if (!fdnames) {
                *exit_status = EXIT_MEMORY;
                return log_oom();
        }

        r = collect_open_file_fds(unit, params->open_files, &fds, &fdnames, &n_fds);
        if (r < 0) {
                *exit_status = EXIT_FDS;
                return log_unit_error_errno(unit, r, "Failed to get OpenFile= file descriptors: %m");
        }

        int keep_fds[n_fds + 3];
        memcpy_safe(keep_fds, fds, n_fds * sizeof(int));
        n_keep_fds = n_fds;

        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->exec_fd, &exec_fd);
        if (r < 0) {
                *exit_status = EXIT_FDS;
                return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
        }

#if HAVE_LIBBPF
        if (unit->manager->restrict_fs) {
                int bpf_map_fd = lsm_bpf_map_restrict_fs_fd(unit);
                if (bpf_map_fd < 0) {
                        *exit_status = EXIT_FDS;
                        return log_unit_error_errno(unit, bpf_map_fd, "Failed to get restrict filesystems BPF map fd: %m");
                }

                r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, bpf_map_fd, &bpf_map_fd);
                if (r < 0) {
                        *exit_status = EXIT_FDS;
                        return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
                }
        }
#endif

        r = close_remaining_fds(params, runtime, user_lookup_fd, socket_fd, keep_fds, n_keep_fds);
        if (r < 0) {
                *exit_status = EXIT_FDS;
                return log_unit_error_errno(unit, r, "Failed to close unwanted file descriptors: %m");
        }

        if (!context->same_pgrp &&
            setsid() < 0) {
                *exit_status = EXIT_SETSID;
                return log_unit_error_errno(unit, errno, "Failed to create new process session: %m");
        }

        exec_context_tty_reset(context, params);

        if (unit_shall_confirm_spawn(unit)) {
                _cleanup_free_ char *cmdline = NULL;

                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
                if (!cmdline) {
                        *exit_status = EXIT_MEMORY;
                        return log_oom();
                }

                r = ask_for_confirmation(context, params->confirm_spawn, unit, cmdline);
                if (r != CONFIRM_EXECUTE) {
                        if (r == CONFIRM_PRETEND_SUCCESS) {
                                *exit_status = EXIT_SUCCESS;
                                return 0;
                        }
                        *exit_status = EXIT_CONFIRM;
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ECANCELED),
                                                    "Execution cancelled by the user");
                }
        }

        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
        if (setenv("SYSTEMD_ACTIVATION_UNIT", unit->id, true) != 0 ||
            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(unit->manager->runtime_scope), true) != 0) {
                *exit_status = EXIT_MEMORY;
                return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
        }

        if (context->dynamic_user && runtime && runtime->dynamic_creds) {
                _cleanup_strv_free_ char **suggested_paths = NULL;

                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
                        *exit_status = EXIT_USER;
                        return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
                }

                r = compile_suggested_paths(context, params, &suggested_paths);
                if (r < 0) {
                        *exit_status = EXIT_MEMORY;
                        return log_oom();
                }

                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
                if (r < 0) {
                        *exit_status = EXIT_USER;
                        if (r == -EILSEQ)
                                return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
                                                            "Failed to update dynamic user credentials: User or group with specified name already exists.");
                        return log_unit_error_errno(unit, r, "Failed to update dynamic user credentials: %m");
                }

                if (!uid_is_valid(uid)) {
                        *exit_status = EXIT_USER;
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid);
                }

                if (!gid_is_valid(gid)) {
                        *exit_status = EXIT_USER;
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid);
                }

                if (runtime->dynamic_creds->user)
                        username = runtime->dynamic_creds->user->name;

        } else {
                r = get_fixed_user(context, &username, &uid, &gid, &home, &shell);
                if (r < 0) {
                        *exit_status = EXIT_USER;
                        return log_unit_error_errno(unit, r, "Failed to determine user credentials: %m");
                }

                r = get_fixed_group(context, &groupname, &gid);
                if (r < 0) {
                        *exit_status = EXIT_GROUP;
                        return log_unit_error_errno(unit, r, "Failed to determine group credentials: %m");
                }
        }

        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
        r = get_supplementary_groups(context, username, groupname, gid,
                                     &supplementary_gids, &ngids);
        if (r < 0) {
                *exit_status = EXIT_GROUP;
                return log_unit_error_errno(unit, r, "Failed to determine supplementary groups: %m");
        }

        r = send_user_lookup(unit, user_lookup_fd, uid, gid);
        if (r < 0) {
                *exit_status = EXIT_USER;
                return log_unit_error_errno(unit, r, "Failed to send user credentials to PID1: %m");
        }

        user_lookup_fd = safe_close(user_lookup_fd);

        r = acquire_home(context, uid, &home, &home_buffer);
        if (r < 0) {
                *exit_status = EXIT_CHDIR;
                return log_unit_error_errno(unit, r, "Failed to determine $HOME for user: %m");
        }

        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
        if (socket_fd >= 0)
                (void) fd_nonblock(socket_fd, false);

        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
        if (params->cgroup_path) {
                _cleanup_free_ char *p = NULL;

                r = exec_parameters_get_cgroup_path(params, cgroup_context, &p);
                if (r < 0) {
                        *exit_status = EXIT_CGROUP;
                        return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
                }

                r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
                if (r == -EUCLEAN) {
                        *exit_status = EXIT_CGROUP;
                        return log_unit_error_errno(unit, r, "Failed to attach process to cgroup %s "
                                                    "because the cgroup or one of its parents or "
                                                    "siblings is in the threaded mode: %m", p);
                }
                if (r < 0) {
                        *exit_status = EXIT_CGROUP;
                        return log_unit_error_errno(unit, r, "Failed to attach to cgroup %s: %m", p);
                }
        }

        if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
                if (r < 0) {
                        *exit_status = EXIT_NETWORK;
                        return log_unit_error_errno(unit, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
                }
        }

        if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
                if (r < 0) {
                        *exit_status = EXIT_NAMESPACE;
                        return log_unit_error_errno(unit, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
                }
        }

        r = setup_input(context, params, socket_fd, named_iofds);
        if (r < 0) {
                *exit_status = EXIT_STDIN;
                return log_unit_error_errno(unit, r, "Failed to set up standard input: %m");
        }

        r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
        if (r < 0) {
                *exit_status = EXIT_STDOUT;
                return log_unit_error_errno(unit, r, "Failed to set up standard output: %m");
        }

        r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
        if (r < 0) {
                *exit_status = EXIT_STDERR;
                return log_unit_error_errno(unit, r, "Failed to set up standard error output: %m");
        }

        if (context->oom_score_adjust_set) {
                /* When we can't make this change due to EPERM, then let's silently skip over it. User namespaces
                 * prohibit write access to this file, and we shouldn't trip up over that. */
                r = set_oom_score_adjust(context->oom_score_adjust);
                if (ERRNO_IS_PRIVILEGE(r))
                        log_unit_debug_errno(unit, r, "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
                else if (r < 0) {
                        *exit_status = EXIT_OOM_ADJUST;
                        return log_unit_error_errno(unit, r, "Failed to adjust OOM setting: %m");
                }
        }

        if (context->coredump_filter_set) {
                r = set_coredump_filter(context->coredump_filter);
                if (ERRNO_IS_PRIVILEGE(r))
                        log_unit_debug_errno(unit, r, "Failed to adjust coredump_filter, ignoring: %m");
                else if (r < 0)
                        return log_unit_error_errno(unit, r, "Failed to adjust coredump_filter: %m");
        }

        if (context->nice_set) {
                r = setpriority_closest(context->nice);
                if (r < 0)
                        return log_unit_error_errno(unit, r, "Failed to set up process scheduling priority (nice level): %m");
        }

        if (context->cpu_sched_set) {
                struct sched_param param = {
                        .sched_priority = context->cpu_sched_priority,
                };

                r = sched_setscheduler(0,
                                       context->cpu_sched_policy |
                                       (context->cpu_sched_reset_on_fork ?
                                        SCHED_RESET_ON_FORK : 0),
                                       &param);
                if (r < 0) {
                        *exit_status = EXIT_SETSCHEDULER;
                        return log_unit_error_errno(unit, errno, "Failed to set up CPU scheduling: %m");
                }
        }

        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
                const CPUSet *cpu_set;

                if (context->cpu_affinity_from_numa) {
                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
                        if (r < 0) {
                                *exit_status = EXIT_CPUAFFINITY;
                                return log_unit_error_errno(unit, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
                        }

                        cpu_set = &converted_cpu_set;
                } else
                        cpu_set = &context->cpu_set;

                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
                        *exit_status = EXIT_CPUAFFINITY;
                        return log_unit_error_errno(unit, errno, "Failed to set up CPU affinity: %m");
                }
        }

        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
                r = apply_numa_policy(&context->numa_policy);
                if (r < 0) {
                        if (ERRNO_IS_NOT_SUPPORTED(r))
                                log_unit_debug_errno(unit, r, "NUMA support not available, ignoring.");
                        else {
                                *exit_status = EXIT_NUMA_POLICY;
                                return log_unit_error_errno(unit, r, "Failed to set NUMA memory policy: %m");
                        }
                }
        }

        if (context->ioprio_set)
                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
                        *exit_status = EXIT_IOPRIO;
                        return log_unit_error_errno(unit, errno, "Failed to set up IO scheduling priority: %m");
                }

        if (context->timer_slack_nsec != NSEC_INFINITY)
                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
                        *exit_status = EXIT_TIMERSLACK;
                        return log_unit_error_errno(unit, errno, "Failed to set up timer slack: %m");
                }

        if (context->personality != PERSONALITY_INVALID) {
                r = safe_personality(context->personality);
                if (r < 0) {
                        *exit_status = EXIT_PERSONALITY;
                        return log_unit_error_errno(unit, r, "Failed to set up execution domain (personality): %m");
                }
        }

        if (context->utmp_id) {
                const char *line = context->tty_path ?
                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
                        NULL;
                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
                                      line,
                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
                                      USER_PROCESS,
                                      username);
        }

        if (uid_is_valid(uid)) {
                r = chown_terminal(STDIN_FILENO, uid);
                if (r < 0) {
                        *exit_status = EXIT_STDIN;
                        return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m");
                }
        }

        if (params->cgroup_path) {
                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
                 * touch a single hierarchy too. */

                if (params->flags & EXEC_CGROUP_DELEGATE) {
                        _cleanup_free_ char *p = NULL;

                        r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
                        if (r < 0) {
                                *exit_status = EXIT_CGROUP;
                                return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m");
                        }

                        r = exec_parameters_get_cgroup_path(params, cgroup_context, &p);
                        if (r < 0) {
                                *exit_status = EXIT_CGROUP;
                                return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
                        }
                        if (r > 0) {
                                r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
                                if (r < 0) {
                                        *exit_status = EXIT_CGROUP;
                                        return log_unit_error_errno(unit, r, "Failed to adjust control subgroup access: %m");
                                }
                        }
                }

                if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
                                if (r < 0) {
                                        *exit_status = EXIT_MEMORY;
                                        return log_oom();
                                }

                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
                                if (r < 0) {
                                        log_unit_full_errno(unit, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
                                                            "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
                                        memory_pressure_path = mfree(memory_pressure_path);
                                }
                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_OFF) {
                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
                                if (!memory_pressure_path) {
                                        *exit_status = EXIT_MEMORY;
                                        return log_oom();
                                }
                        }
                }
        }

        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);

        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
                if (r < 0)
                        return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
        }

        if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
                r = setup_credentials(context, params, unit->id, uid);
                if (r < 0) {
                        *exit_status = EXIT_CREDENTIALS;
                        return log_unit_error_errno(unit, r, "Failed to set up credentials: %m");
                }
        }

        r = build_environment(
                        unit,
                        context,
                        params,
                        cgroup_context,
                        n_fds,
                        fdnames,
                        home,
                        username,
                        shell,
                        journal_stream_dev,
                        journal_stream_ino,
                        memory_pressure_path,
                        &our_env);
        if (r < 0) {
                *exit_status = EXIT_MEMORY;
                return log_oom();
        }

        r = build_pass_environment(context, &pass_env);
        if (r < 0) {
                *exit_status = EXIT_MEMORY;
                return log_oom();
        }

        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
         * not specify PATH but the unit has ExecSearchPath. */
        if (!strv_isempty(context->exec_search_path)) {
                _cleanup_free_ char *joined = NULL;

                joined = strv_join(context->exec_search_path, ":");
                if (!joined) {
                        *exit_status = EXIT_MEMORY;
                        return log_oom();
                }

                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
                if (r < 0) {
                        *exit_status = EXIT_MEMORY;
                        return log_oom();
                }
        }

        accum_env = strv_env_merge(params->environment,
                                   our_env,
                                   joined_exec_search_path,
                                   pass_env,
                                   context->environment,
                                   files_env);
        if (!accum_env) {
                *exit_status = EXIT_MEMORY;
                return log_oom();
        }
        accum_env = strv_env_clean(accum_env);

        (void) umask(context->umask);

        r = setup_keyring(unit, context, params, uid, gid);
        if (r < 0) {
                *exit_status = EXIT_KEYRING;
                return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m");
        }

        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
         * from it. */
        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);

        /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked
         * for it, and the kernel doesn't actually support ambient caps. */
        needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();

        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
         * excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not
         * desired. */
        if (needs_ambient_hack)
                needs_setuid = false;
        else
                needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));

        uint64_t capability_ambient_set = context->capability_ambient_set;

        if (needs_sandboxing) {
                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
                 * /sys being present. The actual MAC context application will happen later, as late as
                 * possible, to avoid impacting our own code paths. */

#if HAVE_SELINUX
                use_selinux = mac_selinux_use();
#endif
#if ENABLE_SMACK
                use_smack = mac_smack_use();
#endif
#if HAVE_APPARMOR
                use_apparmor = mac_apparmor_use();
#endif
        }

        if (needs_sandboxing) {
                int which_failed;

                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
                 * is set here. (See below.) */

                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
                if (r < 0) {
                        *exit_status = EXIT_LIMITS;
                        return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
                }
        }

        if (needs_setuid && context->pam_name && username) {
                /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
                 * wins here. (See above.) */

                /* All fds passed in the fds array will be closed in the pam child process. */
                r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
                if (r < 0) {
                        *exit_status = EXIT_PAM;
                        return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m");
                }

                if (ambient_capabilities_supported()) {
                        uint64_t ambient_after_pam;

                        /* PAM modules might have set some ambient caps. Query them here and merge them into
                         * the caps we want to set in the end, so that we don't end up unsetting them. */
                        r = capability_get_ambient(&ambient_after_pam);
                        if (r < 0) {
                                *exit_status = EXIT_CAPABILITIES;
                                return log_unit_error_errno(unit, r, "Failed to query ambient caps: %m");
                        }

                        capability_ambient_set |= ambient_after_pam;
                }

                ngids_after_pam = getgroups_alloc(&gids_after_pam);
                if (ngids_after_pam < 0) {
                        *exit_status = EXIT_MEMORY;
                        return log_unit_error_errno(unit, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
                }
        }

        if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, unit->manager)) {
                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
                 * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */

                r = setup_private_users(saved_uid, saved_gid, uid, gid);
                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
                 * the actual requested operations fail (or silently continue). */
                if (r < 0 && context->private_users) {
                        *exit_status = EXIT_USER;
                        return log_unit_error_errno(unit, r, "Failed to set up user namespacing for unprivileged user: %m");
                }
                if (r < 0)
                        log_unit_info_errno(unit, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
                else
                        userns_set_up = true;
        }

        if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {

                if (ns_type_supported(NAMESPACE_NET)) {
                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
                        if (r < 0) {
                                if (ERRNO_IS_PRIVILEGE(r))
                                        log_unit_warning_errno(unit, r,
                                                               "PrivateNetwork=yes is configured, but network namespace setup failed, ignoring: %m");
                                else {
                                        *exit_status = EXIT_NETWORK;
                                        return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m");
                                }
                        }
                } else if (context->network_namespace_path) {
                        *exit_status = EXIT_NETWORK;
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
                                                    "NetworkNamespacePath= is not supported, refusing.");
                } else
                        log_unit_warning(unit, "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
        }

        if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {

                if (ns_type_supported(NAMESPACE_IPC)) {
                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
                        if (r == -EPERM)
                                log_unit_warning_errno(unit, r,
                                                       "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
                        else if (r < 0) {
                                *exit_status = EXIT_NAMESPACE;
                                return log_unit_error_errno(unit, r, "Failed to set up IPC namespacing: %m");
                        }
                } else if (context->ipc_namespace_path) {
                        *exit_status = EXIT_NAMESPACE;
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
                                                    "IPCNamespacePath= is not supported, refusing.");
                } else
                        log_unit_warning(unit, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
        }

        if (needs_mount_namespace) {
                _cleanup_free_ char *error_path = NULL;

                r = apply_mount_namespace(unit, command->flags, context, params, runtime, memory_pressure_path, &error_path);
                if (r < 0) {
                        *exit_status = EXIT_NAMESPACE;
                        return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m",
                                                    error_path ? ": " : "", strempty(error_path));
                }
        }

        if (needs_sandboxing) {
                r = apply_protect_hostname(unit, context, exit_status);
                if (r < 0)
                        return r;
        }

        if (context->memory_ksm >= 0)
                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm) < 0) {
                        if (ERRNO_IS_NOT_SUPPORTED(errno))
                                log_unit_debug_errno(unit, errno, "KSM support not available, ignoring.");
                        else {
                                *exit_status = EXIT_KSM;
                                return log_unit_error_errno(unit, errno, "Failed to set KSM: %m");
                        }
                }

        /* Drop groups as early as possible.
         * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root.
         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
        if (needs_setuid) {
                _cleanup_free_ gid_t *gids_to_enforce = NULL;
                int ngids_to_enforce = 0;

                ngids_to_enforce = merge_gid_lists(supplementary_gids,
                                                   ngids,
                                                   gids_after_pam,
                                                   ngids_after_pam,
                                                   &gids_to_enforce);
                if (ngids_to_enforce < 0) {
                        *exit_status = EXIT_MEMORY;
                        return log_unit_error_errno(unit,
                                                    ngids_to_enforce,
                                                    "Failed to merge group lists. Group membership might be incorrect: %m");
                }

                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
                if (r < 0) {
                        *exit_status = EXIT_GROUP;
                        return log_unit_error_errno(unit, r, "Changing group credentials failed: %m");
                }
        }

        /* If the user namespace was not set up above, try to do it now.
         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
         * case of mount namespaces being less privileged when the mount point list is copied from a
         * different user namespace). */

        if (needs_sandboxing && context->private_users && !userns_set_up) {
                r = setup_private_users(saved_uid, saved_gid, uid, gid);
                if (r < 0) {
                        *exit_status = EXIT_USER;
                        return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m");
                }
        }

        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
         * shall execute. */

        _cleanup_free_ char *executable = NULL;
        _cleanup_close_ int executable_fd = -EBADF;
        r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
        if (r < 0) {
                if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
                        log_unit_struct_errno(unit, LOG_INFO, r,
                                              "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
                                              LOG_UNIT_INVOCATION_ID(unit),
                                              LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m",
                                                               command->path),
                                              "EXECUTABLE=%s", command->path);
                        return 0;
                }

                *exit_status = EXIT_EXEC;

                return log_unit_struct_errno(unit, LOG_INFO, r,
                                             "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
                                             LOG_UNIT_INVOCATION_ID(unit),
                                             LOG_UNIT_MESSAGE(unit, "Failed to locate executable %s: %m",
                                                              command->path),
                                             "EXECUTABLE=%s", command->path);
        }

        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd);
        if (r < 0) {
                *exit_status = EXIT_FDS;
                return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
        }

#if HAVE_SELINUX
        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
                int fd = -EBADF;

                if (socket_fd >= 0)
                        fd = socket_fd;
                else if (params->n_socket_fds == 1)
                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
                         * use context from that fd to compute the label. */
                        fd = params->fds[0];

                if (fd >= 0) {
                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
                        if (r < 0) {
                                if (!context->selinux_context_ignore) {
                                        *exit_status = EXIT_SELINUX_CONTEXT;
                                        return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m");
                                }
                                log_unit_debug_errno(unit, r, "Failed to determine SELinux context, ignoring: %m");
                        }
                }
        }
#endif

        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
         * more. We do keep exec_fd however, if we have it, since we need to keep it open until the final
         * execve(). */

        r = close_all_fds(keep_fds, n_keep_fds);
        if (r >= 0)
                r = shift_fds(fds, n_fds);
        if (r >= 0)
                r = flags_fds(fds, n_socket_fds, n_fds, context->non_blocking);
        if (r < 0) {
                *exit_status = EXIT_FDS;
                return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m");
        }

        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
         * came this far. */

        secure_bits = context->secure_bits;

        if (needs_sandboxing) {
                uint64_t bset;

                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
                 * (Note this is placed after the general resource limit initialization, see above, in order
                 * to take precedence.) */
                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
                                *exit_status = EXIT_LIMITS;
                                return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
                        }
                }

#if ENABLE_SMACK
                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
                if (use_smack) {
                        r = setup_smack(unit->manager, context, executable_fd);
                        if (r < 0 && !context->smack_process_label_ignore) {
                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
                                return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m");
                        }
                }
#endif

                bset = context->capability_bounding_set;
                /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
                 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
                 * instead of us doing that */
                if (needs_ambient_hack)
                        bset |= (UINT64_C(1) << CAP_SETPCAP) |
                                (UINT64_C(1) << CAP_SETUID) |
                                (UINT64_C(1) << CAP_SETGID);

                if (!cap_test_all(bset)) {
                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
                        if (r < 0) {
                                *exit_status = EXIT_CAPABILITIES;
                                return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m");
                        }
                }

                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
                 * keep-caps set.
                 *
                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
                 * the ambient capabilities can be raised as they are present in the permitted and
                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
                 * without changing the user, so we also set the ambient capabilities here.
                 *
                 * The requested ambient capabilities are raised in the inheritable set if the second
                 * argument is true. */
                if (!needs_ambient_hack) {
                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
                        if (r < 0) {
                                *exit_status = EXIT_CAPABILITIES;
                                return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m");
                        }
                }
        }

        /* chroot to root directory first, before we lose the ability to chroot */
        r = apply_root_directory(context, params, needs_mount_namespace, exit_status);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m");

        if (needs_setuid) {
                if (uid_is_valid(uid)) {
                        r = enforce_user(context, uid, capability_ambient_set);
                        if (r < 0) {
                                *exit_status = EXIT_USER;
                                return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid);
                        }

                        if (!needs_ambient_hack && capability_ambient_set != 0) {

                                /* Raise the ambient capabilities after user change. */
                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
                                if (r < 0) {
                                        *exit_status = EXIT_CAPABILITIES;
                                        return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m");
                                }
                        }
                }
        }

        /* Apply working directory here, because the working directory might be on NFS and only the user running
         * this service might have the correct privilege to change to the working directory */
        r = apply_working_directory(context, params, home, exit_status);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m");

        if (needs_sandboxing) {
                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
                 * are restricted. */

#if HAVE_SELINUX
                if (use_selinux) {
                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;

                        if (exec_context) {
                                r = setexeccon(exec_context);
                                if (r < 0) {
                                        if (!context->selinux_context_ignore) {
                                                *exit_status = EXIT_SELINUX_CONTEXT;
                                                return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context);
                                        }
                                        log_unit_debug_errno(unit, r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
                                }
                        }
                }
#endif

#if HAVE_APPARMOR
                if (use_apparmor && context->apparmor_profile) {
                        r = aa_change_onexec(context->apparmor_profile);
                        if (r < 0 && !context->apparmor_profile_ignore) {
                                *exit_status = EXIT_APPARMOR_PROFILE;
                                return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile);
                        }
                }
#endif

                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
                 * requires CAP_SETPCAP. */
                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
                         * effective set here.
                         *
                         * The effective set is overwritten during execve() with the following values:
                         *
                         * - ambient set (for non-root processes)
                         *
                         * - (inheritable | bounding) set for root processes)
                         *
                         * Hence there is no security impact to raise it in the effective set before execve
                         */
                        r = capability_gain_cap_setpcap(/* return_caps= */ NULL);
                        if (r < 0) {
                                *exit_status = EXIT_CAPABILITIES;
                                return log_unit_error_errno(unit, r, "Failed to gain CAP_SETPCAP for setting secure bits");
                        }
                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
                                *exit_status = EXIT_SECUREBITS;
                                return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m");
                        }
                }

                if (context_has_no_new_privileges(context))
                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
                                return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m");
                        }

#if HAVE_SECCOMP
                r = apply_address_families(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_ADDRESS_FAMILIES;
                        return log_unit_error_errno(unit, r, "Failed to restrict address families: %m");
                }

                r = apply_memory_deny_write_execute(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m");
                }

                r = apply_restrict_realtime(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m");
                }

                r = apply_restrict_suid_sgid(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m");
                }

                r = apply_restrict_namespaces(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m");
                }

                r = apply_protect_sysctl(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m");
                }

                r = apply_protect_kernel_modules(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m");
                }

                r = apply_protect_kernel_logs(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m");
                }

                r = apply_protect_clock(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply clock restrictions: %m");
                }

                r = apply_private_devices(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to set up private devices: %m");
                }

                r = apply_syscall_archs(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m");
                }

                r = apply_lock_personality(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to lock personalities: %m");
                }

                r = apply_syscall_log(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply system call log filters: %m");
                }

                /* This really should remain the last step before the execve(), to make sure our own code is unaffected
                 * by the filter as little as possible. */
                r = apply_syscall_filter(unit, context, needs_ambient_hack);
                if (r < 0) {
                        *exit_status = EXIT_SECCOMP;
                        return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m");
                }
#endif

#if HAVE_LIBBPF
                r = apply_restrict_filesystems(unit, context);
                if (r < 0) {
                        *exit_status = EXIT_BPF;
                        return log_unit_error_errno(unit, r, "Failed to restrict filesystems: %m");
                }
#endif

        }

        if (!strv_isempty(context->unset_environment)) {
                char **ee = NULL;

                ee = strv_env_delete(accum_env, 1, context->unset_environment);
                if (!ee) {
                        *exit_status = EXIT_MEMORY;
                        return log_oom();
                }

                strv_free_and_replace(accum_env, ee);
        }

        if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
                replaced_argv = replace_env_argv(command->argv, accum_env);
                if (!replaced_argv) {
                        *exit_status = EXIT_MEMORY;
                        return log_oom();
                }
                final_argv = replaced_argv;
        } else
                final_argv = command->argv;

        log_command_line(unit, "Executing", executable, final_argv);

        if (exec_fd >= 0) {
                uint8_t hot = 1;

                /* We have finished with all our initializations. Let's now let the manager know that. From this point
                 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */

                if (write(exec_fd, &hot, sizeof(hot)) < 0) {
                        *exit_status = EXIT_EXEC;
                        return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m");
                }
        }

        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);

        if (exec_fd >= 0) {
                uint8_t hot = 0;

                /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
                 * that POLLHUP on it no longer means execve() succeeded. */

                if (write(exec_fd, &hot, sizeof(hot)) < 0) {
                        *exit_status = EXIT_EXEC;
                        return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m");
                }
        }

        *exit_status = EXIT_EXEC;
        return log_unit_error_errno(unit, r, "Failed to execute %s: %m", executable);
}

static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l);
static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]);

int exec_spawn(Unit *unit,
               ExecCommand *command,
               const ExecContext *context,
               const ExecParameters *params,
               ExecRuntime *runtime,
               const CGroupContext *cgroup_context,
               pid_t *ret) {

        int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL;
        _cleanup_free_ char *subcgroup_path = NULL;
        _cleanup_strv_free_ char **files_env = NULL;
        size_t n_storage_fds = 0, n_socket_fds = 0;
        pid_t pid;

        assert(unit);
        assert(command);
        assert(context);
        assert(ret);
        assert(params);
        assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0));

        LOG_CONTEXT_PUSH_UNIT(unit);

        if (context->std_input == EXEC_INPUT_SOCKET ||
            context->std_output == EXEC_OUTPUT_SOCKET ||
            context->std_error == EXEC_OUTPUT_SOCKET) {

                if (params->n_socket_fds > 1)
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");

                if (params->n_socket_fds == 0)
                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");

                socket_fd = params->fds[0];
        } else {
                socket_fd = -EBADF;
                fds = params->fds;
                n_socket_fds = params->n_socket_fds;
                n_storage_fds = params->n_storage_fds;
        }

        r = exec_context_named_iofds(context, params, named_iofds);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");

        r = exec_context_load_environment(unit, context, &files_env);
        if (r < 0)
                return log_unit_error_errno(unit, r, "Failed to load environment files: %m");

        /* Fork with up-to-date SELinux label database, so the child inherits the up-to-date db
           and, until the next SELinux policy changes, we save further reloads in future children. */
        mac_selinux_maybe_reload();

        /* We won't know the real executable path until we create the mount namespace in the child, but we
           want to log from the parent, so we use the possibly inaccurate path here. */
        log_command_line(unit, "About to execute", command->path, command->argv);

        if (params->cgroup_path) {
                r = exec_parameters_get_cgroup_path(params, cgroup_context, &subcgroup_path);
                if (r < 0)
                        return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
                if (r > 0) {
                        /* If there's a subcgroup, then let's create it here now (the main cgroup was already
                         * realized by the unit logic) */

                        r = cg_create(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path);
                        if (r < 0)
                                return log_unit_error_errno(unit, r, "Failed to create subcgroup '%s': %m", subcgroup_path);
                }
        }

        pid = fork();
        if (pid < 0)
                return log_unit_error_errno(unit, errno, "Failed to fork: %m");

        if (pid == 0) {
                int exit_status = EXIT_SUCCESS;

                r = exec_child(unit,
                               command,
                               context,
                               params,
                               runtime,
                               cgroup_context,
                               socket_fd,
                               named_iofds,
                               fds,
                               n_socket_fds,
                               n_storage_fds,
                               files_env,
                               unit->manager->user_lookup_fds[1],
                               &exit_status);

                if (r < 0) {
                        const char *status =
                                exit_status_to_string(exit_status,
                                                      EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD);

                        log_unit_struct_errno(unit, LOG_ERR, r,
                                              "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
                                              LOG_UNIT_INVOCATION_ID(unit),
                                              LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
                                                               status, command->path),
                                              "EXECUTABLE=%s", command->path);
                }

                _exit(exit_status);
        }

        log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);

        /* We add the new process to the cgroup both in the child (so that we can be sure that no user code is ever
         * executed outside of the cgroup) and in the parent (so that we can be sure that when we kill the cgroup the
         * process will be killed too). */
        if (subcgroup_path)
                (void) cg_attach(SYSTEMD_CGROUP_CONTROLLER, subcgroup_path, pid);

        exec_status_start(&command->exec_status, pid);

        *ret = pid;
        return 0;
}

void exec_context_init(ExecContext *c) {
        assert(c);

        c->umask = 0022;
        c->ioprio = IOPRIO_DEFAULT_CLASS_AND_PRIO;
        c->cpu_sched_policy = SCHED_OTHER;
        c->syslog_priority = LOG_DAEMON|LOG_INFO;
        c->syslog_level_prefix = true;
        c->ignore_sigpipe = true;
        c->timer_slack_nsec = NSEC_INFINITY;
        c->personality = PERSONALITY_INVALID;
        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
                c->directories[t].mode = 0755;
        c->timeout_clean_usec = USEC_INFINITY;
        c->capability_bounding_set = CAP_MASK_UNSET;
        assert_cc(NAMESPACE_FLAGS_INITIAL != NAMESPACE_FLAGS_ALL);
        c->restrict_namespaces = NAMESPACE_FLAGS_INITIAL;
        c->log_level_max = -1;
#if HAVE_SECCOMP
        c->syscall_errno = SECCOMP_ERROR_NUMBER_KILL;
#endif
        c->tty_rows = UINT_MAX;
        c->tty_cols = UINT_MAX;
        numa_policy_reset(&c->numa_policy);
        c->private_mounts = -1;
        c->memory_ksm = -1;
}

void exec_context_done(ExecContext *c) {
        assert(c);

        c->environment = strv_free(c->environment);
        c->environment_files = strv_free(c->environment_files);
        c->pass_environment = strv_free(c->pass_environment);
        c->unset_environment = strv_free(c->unset_environment);

        rlimit_free_all(c->rlimit);

        for (size_t l = 0; l < 3; l++) {
                c->stdio_fdname[l] = mfree(c->stdio_fdname[l]);
                c->stdio_file[l] = mfree(c->stdio_file[l]);
        }

        c->working_directory = mfree(c->working_directory);
        c->root_directory = mfree(c->root_directory);
        c->root_image = mfree(c->root_image);
        c->root_image_options = mount_options_free_all(c->root_image_options);
        c->root_hash = mfree(c->root_hash);
        c->root_hash_size = 0;
        c->root_hash_path = mfree(c->root_hash_path);
        c->root_hash_sig = mfree(c->root_hash_sig);
        c->root_hash_sig_size = 0;
        c->root_hash_sig_path = mfree(c->root_hash_sig_path);
        c->root_verity = mfree(c->root_verity);
        c->extension_images = mount_image_free_many(c->extension_images, &c->n_extension_images);
        c->extension_directories = strv_free(c->extension_directories);
        c->tty_path = mfree(c->tty_path);
        c->syslog_identifier = mfree(c->syslog_identifier);
        c->user = mfree(c->user);
        c->group = mfree(c->group);

        c->supplementary_groups = strv_free(c->supplementary_groups);

        c->pam_name = mfree(c->pam_name);

        c->read_only_paths = strv_free(c->read_only_paths);
        c->read_write_paths = strv_free(c->read_write_paths);
        c->inaccessible_paths = strv_free(c->inaccessible_paths);
        c->exec_paths = strv_free(c->exec_paths);
        c->no_exec_paths = strv_free(c->no_exec_paths);
        c->exec_search_path = strv_free(c->exec_search_path);

        bind_mount_free_many(c->bind_mounts, c->n_bind_mounts);
        c->bind_mounts = NULL;
        c->n_bind_mounts = 0;
        temporary_filesystem_free_many(c->temporary_filesystems, c->n_temporary_filesystems);
        c->temporary_filesystems = NULL;
        c->n_temporary_filesystems = 0;
        c->mount_images = mount_image_free_many(c->mount_images, &c->n_mount_images);

        cpu_set_reset(&c->cpu_set);
        numa_policy_reset(&c->numa_policy);

        c->utmp_id = mfree(c->utmp_id);
        c->selinux_context = mfree(c->selinux_context);
        c->apparmor_profile = mfree(c->apparmor_profile);
        c->smack_process_label = mfree(c->smack_process_label);

        c->restrict_filesystems = set_free(c->restrict_filesystems);

        c->syscall_filter = hashmap_free(c->syscall_filter);
        c->syscall_archs = set_free(c->syscall_archs);
        c->address_families = set_free(c->address_families);

        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
                exec_directory_done(&c->directories[t]);

        c->log_level_max = -1;

        exec_context_free_log_extra_fields(c);
        c->log_filter_allowed_patterns = set_free(c->log_filter_allowed_patterns);
        c->log_filter_denied_patterns = set_free(c->log_filter_denied_patterns);

        c->log_ratelimit_interval_usec = 0;
        c->log_ratelimit_burst = 0;

        c->stdin_data = mfree(c->stdin_data);
        c->stdin_data_size = 0;

        c->network_namespace_path = mfree(c->network_namespace_path);
        c->ipc_namespace_path = mfree(c->ipc_namespace_path);

        c->log_namespace = mfree(c->log_namespace);

        c->load_credentials = hashmap_free(c->load_credentials);
        c->set_credentials = hashmap_free(c->set_credentials);

        c->root_image_policy = image_policy_free(c->root_image_policy);
        c->mount_image_policy = image_policy_free(c->mount_image_policy);
        c->extension_image_policy = image_policy_free(c->extension_image_policy);
}

int exec_context_destroy_runtime_directory(const ExecContext *c, const char *runtime_prefix) {
        assert(c);

        if (!runtime_prefix)
                return 0;

        for (size_t i = 0; i < c->directories[EXEC_DIRECTORY_RUNTIME].n_items; i++) {
                _cleanup_free_ char *p = NULL;

                if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
                        p = path_join(runtime_prefix, "private", c->directories[EXEC_DIRECTORY_RUNTIME].items[i].path);
                else
                        p = path_join(runtime_prefix, c->directories[EXEC_DIRECTORY_RUNTIME].items[i].path);
                if (!p)
                        return -ENOMEM;

                /* We execute this synchronously, since we need to be sure this is gone when we start the
                 * service next. */
                (void) rm_rf(p, REMOVE_ROOT);

                STRV_FOREACH(symlink, c->directories[EXEC_DIRECTORY_RUNTIME].items[i].symlinks) {
                        _cleanup_free_ char *symlink_abs = NULL;

                        if (exec_directory_is_private(c, EXEC_DIRECTORY_RUNTIME))
                                symlink_abs = path_join(runtime_prefix, "private", *symlink);
                        else
                                symlink_abs = path_join(runtime_prefix, *symlink);
                        if (!symlink_abs)
                                return -ENOMEM;

                        (void) unlink(symlink_abs);
                }
        }

        return 0;
}

int exec_context_destroy_credentials(const ExecContext *c, const char *runtime_prefix, const char *unit) {
        _cleanup_free_ char *p = NULL;

        assert(c);

        if (!runtime_prefix || !unit)
                return 0;

        p = path_join(runtime_prefix, "credentials", unit);
        if (!p)
                return -ENOMEM;

        /* This is either a tmpfs/ramfs of its own, or a plain directory. Either way, let's first try to
         * unmount it, and afterwards remove the mount point */
        (void) umount2(p, MNT_DETACH|UMOUNT_NOFOLLOW);
        (void) rm_rf(p, REMOVE_ROOT|REMOVE_CHMOD);

        return 0;
}

int exec_context_destroy_mount_ns_dir(Unit *u) {
        _cleanup_free_ char *p = NULL;

        if (!u || !MANAGER_IS_SYSTEM(u->manager))
                return 0;

        p = path_join("/run/systemd/propagate/", u->id);
        if (!p)
                return -ENOMEM;

        /* This is only filled transiently (see mount_in_namespace()), should be empty or even non-existent*/
        if (rmdir(p) < 0 && errno != ENOENT)
                log_unit_debug_errno(u, errno, "Unable to remove propagation dir '%s', ignoring: %m", p);

        return 0;
}

static void exec_command_done(ExecCommand *c) {
        assert(c);

        c->path = mfree(c->path);
        c->argv = strv_free(c->argv);
}

void exec_command_done_array(ExecCommand *c, size_t n) {
        for (size_t i = 0; i < n; i++)
                exec_command_done(c+i);
}

ExecCommand* exec_command_free_list(ExecCommand *c) {
        ExecCommand *i;

        while ((i = c)) {
                LIST_REMOVE(command, c, i);
                exec_command_done(i);
                free(i);
        }

        return NULL;
}

void exec_command_free_array(ExecCommand **c, size_t n) {
        for (size_t i = 0; i < n; i++)
                c[i] = exec_command_free_list(c[i]);
}

void exec_command_reset_status_array(ExecCommand *c, size_t n) {
        for (size_t i = 0; i < n; i++)
                exec_status_reset(&c[i].exec_status);
}

void exec_command_reset_status_list_array(ExecCommand **c, size_t n) {
        for (size_t i = 0; i < n; i++)
                LIST_FOREACH(command, z, c[i])
                        exec_status_reset(&z->exec_status);
}

typedef struct InvalidEnvInfo {
        const Unit *unit;
        const char *path;
} InvalidEnvInfo;

static void invalid_env(const char *p, void *userdata) {
        InvalidEnvInfo *info = userdata;

        log_unit_error(info->unit, "Ignoring invalid environment assignment '%s': %s", p, info->path);
}

const char* exec_context_fdname(const ExecContext *c, int fd_index) {
        assert(c);

        switch (fd_index) {

        case STDIN_FILENO:
                if (c->std_input != EXEC_INPUT_NAMED_FD)
                        return NULL;

                return c->stdio_fdname[STDIN_FILENO] ?: "stdin";

        case STDOUT_FILENO:
                if (c->std_output != EXEC_OUTPUT_NAMED_FD)
                        return NULL;

                return c->stdio_fdname[STDOUT_FILENO] ?: "stdout";

        case STDERR_FILENO:
                if (c->std_error != EXEC_OUTPUT_NAMED_FD)
                        return NULL;

                return c->stdio_fdname[STDERR_FILENO] ?: "stderr";

        default:
                return NULL;
        }
}

static int exec_context_named_iofds(
                const ExecContext *c,
                const ExecParameters *p,
                int named_iofds[static 3]) {

        size_t targets;
        const char* stdio_fdname[3];
        size_t n_fds;

        assert(c);
        assert(p);
        assert(named_iofds);

        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
                  (c->std_error == EXEC_OUTPUT_NAMED_FD);

        for (size_t i = 0; i < 3; i++)
                stdio_fdname[i] = exec_context_fdname(c, i);

        n_fds = p->n_storage_fds + p->n_socket_fds;

        for (size_t i = 0; i < n_fds  && targets > 0; i++)
                if (named_iofds[STDIN_FILENO] < 0 &&
                    c->std_input == EXEC_INPUT_NAMED_FD &&
                    stdio_fdname[STDIN_FILENO] &&
                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {

                        named_iofds[STDIN_FILENO] = p->fds[i];
                        targets--;

                } else if (named_iofds[STDOUT_FILENO] < 0 &&
                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
                           stdio_fdname[STDOUT_FILENO] &&
                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {

                        named_iofds[STDOUT_FILENO] = p->fds[i];
                        targets--;

                } else if (named_iofds[STDERR_FILENO] < 0 &&
                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
                           stdio_fdname[STDERR_FILENO] &&
                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {

                        named_iofds[STDERR_FILENO] = p->fds[i];
                        targets--;
                }

        return targets == 0 ? 0 : -ENOENT;
}

static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***ret) {
        _cleanup_strv_free_ char **v = NULL;
        int r;

        assert(c);
        assert(ret);

        STRV_FOREACH(i, c->environment_files) {
                _cleanup_globfree_ glob_t pglob = {};
                bool ignore = false;
                char *fn = *i;

                if (fn[0] == '-') {
                        ignore = true;
                        fn++;
                }

                if (!path_is_absolute(fn)) {
                        if (ignore)
                                continue;
                        return -EINVAL;
                }

                /* Filename supports globbing, take all matching files */
                r = safe_glob(fn, 0, &pglob);
                if (r < 0) {
                        if (ignore)
                                continue;
                        return r;
                }

                /* When we don't match anything, -ENOENT should be returned */
                assert(pglob.gl_pathc > 0);

                for (unsigned n = 0; n < pglob.gl_pathc; n++) {
                        _cleanup_strv_free_ char **p = NULL;

                        r = load_env_file(NULL, pglob.gl_pathv[n], &p);
                        if (r < 0) {
                                if (ignore)
                                        continue;
                                return r;
                        }

                        /* Log invalid environment variables with filename */
                        if (p) {
                                InvalidEnvInfo info = {
                                        .unit = unit,
                                        .path = pglob.gl_pathv[n]
                                };

                                p = strv_env_clean_with_callback(p, invalid_env, &info);
                        }

                        if (!v)
                                v = TAKE_PTR(p);
                        else {
                                char **m = strv_env_merge(v, p);
                                if (!m)
                                        return -ENOMEM;

                                strv_free_and_replace(v, m);
                        }
                }
        }

        *ret = TAKE_PTR(v);

        return 0;
}

static bool tty_may_match_dev_console(const char *tty) {
        _cleanup_free_ char *resolved = NULL;

        if (!tty)
                return true;

        tty = skip_dev_prefix(tty);

        /* trivial identity? */
        if (streq(tty, "console"))
                return true;

        if (resolve_dev_console(&resolved) < 0)
                return true; /* if we could not resolve, assume it may */

        /* "tty0" means the active VC, so it may be the same sometimes */
        return path_equal(resolved, tty) || (streq(resolved, "tty0") && tty_is_vc(tty));
}

static bool exec_context_may_touch_tty(const ExecContext *ec) {
        assert(ec);

        return ec->tty_reset ||
                ec->tty_vhangup ||
                ec->tty_vt_disallocate ||
                is_terminal_input(ec->std_input) ||
                is_terminal_output(ec->std_output) ||
                is_terminal_output(ec->std_error);
}

bool exec_context_may_touch_console(const ExecContext *ec) {

        return exec_context_may_touch_tty(ec) &&
               tty_may_match_dev_console(exec_context_tty_path(ec));
}

static void strv_fprintf(FILE *f, char **l) {
        assert(f);

        STRV_FOREACH(g, l)
                fprintf(f, " %s", *g);
}

static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv) {
        assert(f);
        assert(prefix);
        assert(name);

        if (!strv_isempty(strv)) {
                fprintf(f, "%s%s:", prefix, name);
                strv_fprintf(f, strv);
                fputs("\n", f);
        }
}

void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
        int r;

        assert(c);
        assert(f);

        prefix = strempty(prefix);

        fprintf(f,
                "%sUMask: %04o\n"
                "%sWorkingDirectory: %s\n"
                "%sRootDirectory: %s\n"
                "%sNonBlocking: %s\n"
                "%sPrivateTmp: %s\n"
                "%sPrivateDevices: %s\n"
                "%sProtectKernelTunables: %s\n"
                "%sProtectKernelModules: %s\n"
                "%sProtectKernelLogs: %s\n"
                "%sProtectClock: %s\n"
                "%sProtectControlGroups: %s\n"
                "%sPrivateNetwork: %s\n"
                "%sPrivateUsers: %s\n"
                "%sProtectHome: %s\n"
                "%sProtectSystem: %s\n"
                "%sMountAPIVFS: %s\n"
                "%sIgnoreSIGPIPE: %s\n"
                "%sMemoryDenyWriteExecute: %s\n"
                "%sRestrictRealtime: %s\n"
                "%sRestrictSUIDSGID: %s\n"
                "%sKeyringMode: %s\n"
                "%sProtectHostname: %s\n"
                "%sProtectProc: %s\n"
                "%sProcSubset: %s\n",
                prefix, c->umask,
                prefix, empty_to_root(c->working_directory),
                prefix, empty_to_root(c->root_directory),
                prefix, yes_no(c->non_blocking),
                prefix, yes_no(c->private_tmp),
                prefix, yes_no(c->private_devices),
                prefix, yes_no(c->protect_kernel_tunables),
                prefix, yes_no(c->protect_kernel_modules),
                prefix, yes_no(c->protect_kernel_logs),
                prefix, yes_no(c->protect_clock),
                prefix, yes_no(c->protect_control_groups),
                prefix, yes_no(c->private_network),
                prefix, yes_no(c->private_users),
                prefix, protect_home_to_string(c->protect_home),
                prefix, protect_system_to_string(c->protect_system),
                prefix, yes_no(exec_context_get_effective_mount_apivfs(c)),
                prefix, yes_no(c->ignore_sigpipe),
                prefix, yes_no(c->memory_deny_write_execute),
                prefix, yes_no(c->restrict_realtime),
                prefix, yes_no(c->restrict_suid_sgid),
                prefix, exec_keyring_mode_to_string(c->keyring_mode),
                prefix, yes_no(c->protect_hostname),
                prefix, protect_proc_to_string(c->protect_proc),
                prefix, proc_subset_to_string(c->proc_subset));

        if (c->root_image)
                fprintf(f, "%sRootImage: %s\n", prefix, c->root_image);

        if (c->root_image_options) {
                fprintf(f, "%sRootImageOptions:", prefix);
                LIST_FOREACH(mount_options, o, c->root_image_options)
                        if (!isempty(o->options))
                                fprintf(f, " %s:%s",
                                        partition_designator_to_string(o->partition_designator),
                                        o->options);
                fprintf(f, "\n");
        }

        if (c->root_hash) {
                _cleanup_free_ char *encoded = NULL;
                encoded = hexmem(c->root_hash, c->root_hash_size);
                if (encoded)
                        fprintf(f, "%sRootHash: %s\n", prefix, encoded);
        }

        if (c->root_hash_path)
                fprintf(f, "%sRootHash: %s\n", prefix, c->root_hash_path);

        if (c->root_hash_sig) {
                _cleanup_free_ char *encoded = NULL;
                ssize_t len;
                len = base64mem(c->root_hash_sig, c->root_hash_sig_size, &encoded);
                if (len)
                        fprintf(f, "%sRootHashSignature: base64:%s\n", prefix, encoded);
        }

        if (c->root_hash_sig_path)
                fprintf(f, "%sRootHashSignature: %s\n", prefix, c->root_hash_sig_path);

        if (c->root_verity)
                fprintf(f, "%sRootVerity: %s\n", prefix, c->root_verity);

        STRV_FOREACH(e, c->environment)
                fprintf(f, "%sEnvironment: %s\n", prefix, *e);

        STRV_FOREACH(e, c->environment_files)
                fprintf(f, "%sEnvironmentFile: %s\n", prefix, *e);

        STRV_FOREACH(e, c->pass_environment)
                fprintf(f, "%sPassEnvironment: %s\n", prefix, *e);

        STRV_FOREACH(e, c->unset_environment)
                fprintf(f, "%sUnsetEnvironment: %s\n", prefix, *e);

        fprintf(f, "%sRuntimeDirectoryPreserve: %s\n", prefix, exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));

        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
                fprintf(f, "%s%sMode: %04o\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].mode);

                for (size_t i = 0; i < c->directories[dt].n_items; i++) {
                        fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), c->directories[dt].items[i].path);

                        STRV_FOREACH(d, c->directories[dt].items[i].symlinks)
                                fprintf(f, "%s%s: %s:%s\n", prefix, exec_directory_type_symlink_to_string(dt), c->directories[dt].items[i].path, *d);
                }
        }

        fprintf(f, "%sTimeoutCleanSec: %s\n", prefix, FORMAT_TIMESPAN(c->timeout_clean_usec, USEC_PER_SEC));

        if (c->nice_set)
                fprintf(f, "%sNice: %i\n", prefix, c->nice);

        if (c->oom_score_adjust_set)
                fprintf(f, "%sOOMScoreAdjust: %i\n", prefix, c->oom_score_adjust);

        if (c->coredump_filter_set)
                fprintf(f, "%sCoredumpFilter: 0x%"PRIx64"\n", prefix, c->coredump_filter);

        for (unsigned i = 0; i < RLIM_NLIMITS; i++)
                if (c->rlimit[i]) {
                        fprintf(f, "%sLimit%s: " RLIM_FMT "\n",
                                prefix, rlimit_to_string(i), c->rlimit[i]->rlim_max);
                        fprintf(f, "%sLimit%sSoft: " RLIM_FMT "\n",
                                prefix, rlimit_to_string(i), c->rlimit[i]->rlim_cur);
                }

        if (c->ioprio_set) {
                _cleanup_free_ char *class_str = NULL;

                r = ioprio_class_to_string_alloc(ioprio_prio_class(c->ioprio), &class_str);
                if (r >= 0)
                        fprintf(f, "%sIOSchedulingClass: %s\n", prefix, class_str);

                fprintf(f, "%sIOPriority: %d\n", prefix, ioprio_prio_data(c->ioprio));
        }

        if (c->cpu_sched_set) {
                _cleanup_free_ char *policy_str = NULL;

                r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
                if (r >= 0)
                        fprintf(f, "%sCPUSchedulingPolicy: %s\n", prefix, policy_str);

                fprintf(f,
                        "%sCPUSchedulingPriority: %i\n"
                        "%sCPUSchedulingResetOnFork: %s\n",
                        prefix, c->cpu_sched_priority,
                        prefix, yes_no(c->cpu_sched_reset_on_fork));
        }

        if (c->cpu_set.set) {
                _cleanup_free_ char *affinity = NULL;

                affinity = cpu_set_to_range_string(&c->cpu_set);
                fprintf(f, "%sCPUAffinity: %s\n", prefix, affinity);
        }

        if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) {
                _cleanup_free_ char *nodes = NULL;

                nodes = cpu_set_to_range_string(&c->numa_policy.nodes);
                fprintf(f, "%sNUMAPolicy: %s\n", prefix, mpol_to_string(numa_policy_get_type(&c->numa_policy)));
                fprintf(f, "%sNUMAMask: %s\n", prefix, strnull(nodes));
        }

        if (c->timer_slack_nsec != NSEC_INFINITY)
                fprintf(f, "%sTimerSlackNSec: "NSEC_FMT "\n", prefix, c->timer_slack_nsec);

        fprintf(f,
                "%sStandardInput: %s\n"
                "%sStandardOutput: %s\n"
                "%sStandardError: %s\n",
                prefix, exec_input_to_string(c->std_input),
                prefix, exec_output_to_string(c->std_output),
                prefix, exec_output_to_string(c->std_error));

        if (c->std_input == EXEC_INPUT_NAMED_FD)
                fprintf(f, "%sStandardInputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDIN_FILENO]);
        if (c->std_output == EXEC_OUTPUT_NAMED_FD)
                fprintf(f, "%sStandardOutputFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDOUT_FILENO]);
        if (c->std_error == EXEC_OUTPUT_NAMED_FD)
                fprintf(f, "%sStandardErrorFileDescriptorName: %s\n", prefix, c->stdio_fdname[STDERR_FILENO]);

        if (c->std_input == EXEC_INPUT_FILE)
                fprintf(f, "%sStandardInputFile: %s\n", prefix, c->stdio_file[STDIN_FILENO]);
        if (c->std_output == EXEC_OUTPUT_FILE)
                fprintf(f, "%sStandardOutputFile: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
        if (c->std_output == EXEC_OUTPUT_FILE_APPEND)
                fprintf(f, "%sStandardOutputFileToAppend: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
        if (c->std_output == EXEC_OUTPUT_FILE_TRUNCATE)
                fprintf(f, "%sStandardOutputFileToTruncate: %s\n", prefix, c->stdio_file[STDOUT_FILENO]);
        if (c->std_error == EXEC_OUTPUT_FILE)
                fprintf(f, "%sStandardErrorFile: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
        if (c->std_error == EXEC_OUTPUT_FILE_APPEND)
                fprintf(f, "%sStandardErrorFileToAppend: %s\n", prefix, c->stdio_file[STDERR_FILENO]);
        if (c->std_error == EXEC_OUTPUT_FILE_TRUNCATE)
                fprintf(f, "%sStandardErrorFileToTruncate: %s\n", prefix, c->stdio_file[STDERR_FILENO]);

        if (c->tty_path)
                fprintf(f,
                        "%sTTYPath: %s\n"
                        "%sTTYReset: %s\n"
                        "%sTTYVHangup: %s\n"
                        "%sTTYVTDisallocate: %s\n"
                        "%sTTYRows: %u\n"
                        "%sTTYColumns: %u\n",
                        prefix, c->tty_path,
                        prefix, yes_no(c->tty_reset),
                        prefix, yes_no(c->tty_vhangup),
                        prefix, yes_no(c->tty_vt_disallocate),
                        prefix, c->tty_rows,
                        prefix, c->tty_cols);

        if (IN_SET(c->std_output,
                   EXEC_OUTPUT_KMSG,
                   EXEC_OUTPUT_JOURNAL,
                   EXEC_OUTPUT_KMSG_AND_CONSOLE,
                   EXEC_OUTPUT_JOURNAL_AND_CONSOLE) ||
            IN_SET(c->std_error,
                   EXEC_OUTPUT_KMSG,
                   EXEC_OUTPUT_JOURNAL,
                   EXEC_OUTPUT_KMSG_AND_CONSOLE,
                   EXEC_OUTPUT_JOURNAL_AND_CONSOLE)) {

                _cleanup_free_ char *fac_str = NULL, *lvl_str = NULL;

                r = log_facility_unshifted_to_string_alloc(c->syslog_priority >> 3, &fac_str);
                if (r >= 0)
                        fprintf(f, "%sSyslogFacility: %s\n", prefix, fac_str);

                r = log_level_to_string_alloc(LOG_PRI(c->syslog_priority), &lvl_str);
                if (r >= 0)
                        fprintf(f, "%sSyslogLevel: %s\n", prefix, lvl_str);
        }

        if (c->log_level_max >= 0) {
                _cleanup_free_ char *t = NULL;

                (void) log_level_to_string_alloc(c->log_level_max, &t);

                fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
        }

        if (c->log_ratelimit_interval_usec > 0)
                fprintf(f,
                        "%sLogRateLimitIntervalSec: %s\n",
                        prefix, FORMAT_TIMESPAN(c->log_ratelimit_interval_usec, USEC_PER_SEC));

        if (c->log_ratelimit_burst > 0)
                fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst);

        if (!set_isempty(c->log_filter_allowed_patterns) || !set_isempty(c->log_filter_denied_patterns)) {
                fprintf(f, "%sLogFilterPatterns:", prefix);

                char *pattern;
                SET_FOREACH(pattern, c->log_filter_allowed_patterns)
                        fprintf(f, " %s", pattern);
                SET_FOREACH(pattern, c->log_filter_denied_patterns)
                        fprintf(f, " ~%s", pattern);
                fputc('\n', f);
        }

        for (size_t j = 0; j < c->n_log_extra_fields; j++) {
                fprintf(f, "%sLogExtraFields: ", prefix);
                fwrite(c->log_extra_fields[j].iov_base,
                       1, c->log_extra_fields[j].iov_len,
                       f);
                fputc('\n', f);
        }

        if (c->log_namespace)
                fprintf(f, "%sLogNamespace: %s\n", prefix, c->log_namespace);

        if (c->secure_bits) {
                _cleanup_free_ char *str = NULL;

                r = secure_bits_to_string_alloc(c->secure_bits, &str);
                if (r >= 0)
                        fprintf(f, "%sSecure Bits: %s\n", prefix, str);
        }

        if (c->capability_bounding_set != CAP_MASK_UNSET) {
                _cleanup_free_ char *str = NULL;

                r = capability_set_to_string(c->capability_bounding_set, &str);
                if (r >= 0)
                        fprintf(f, "%sCapabilityBoundingSet: %s\n", prefix, str);
        }

        if (c->capability_ambient_set != 0) {
                _cleanup_free_ char *str = NULL;

                r = capability_set_to_string(c->capability_ambient_set, &str);
                if (r >= 0)
                        fprintf(f, "%sAmbientCapabilities: %s\n", prefix, str);
        }

        if (c->user)
                fprintf(f, "%sUser: %s\n", prefix, c->user);
        if (c->group)
                fprintf(f, "%sGroup: %s\n", prefix, c->group);

        fprintf(f, "%sDynamicUser: %s\n", prefix, yes_no(c->dynamic_user));

        strv_dump(f, prefix, "SupplementaryGroups", c->supplementary_groups);

        if (c->pam_name)
                fprintf(f, "%sPAMName: %s\n", prefix, c->pam_name);

        strv_dump(f, prefix, "ReadWritePaths", c->read_write_paths);
        strv_dump(f, prefix, "ReadOnlyPaths", c->read_only_paths);
        strv_dump(f, prefix, "InaccessiblePaths", c->inaccessible_paths);
        strv_dump(f, prefix, "ExecPaths", c->exec_paths);
        strv_dump(f, prefix, "NoExecPaths", c->no_exec_paths);
        strv_dump(f, prefix, "ExecSearchPath", c->exec_search_path);

        for (size_t i = 0; i < c->n_bind_mounts; i++)
                fprintf(f, "%s%s: %s%s:%s:%s\n", prefix,
                        c->bind_mounts[i].read_only ? "BindReadOnlyPaths" : "BindPaths",
                        c->bind_mounts[i].ignore_enoent ? "-": "",
                        c->bind_mounts[i].source,
                        c->bind_mounts[i].destination,
                        c->bind_mounts[i].recursive ? "rbind" : "norbind");

        for (size_t i = 0; i < c->n_temporary_filesystems; i++) {
                const TemporaryFileSystem *t = c->temporary_filesystems + i;

                fprintf(f, "%sTemporaryFileSystem: %s%s%s\n", prefix,
                        t->path,
                        isempty(t->options) ? "" : ":",
                        strempty(t->options));
        }

        if (c->utmp_id)
                fprintf(f,
                        "%sUtmpIdentifier: %s\n",
                        prefix, c->utmp_id);

        if (c->selinux_context)
                fprintf(f,
                        "%sSELinuxContext: %s%s\n",
                        prefix, c->selinux_context_ignore ? "-" : "", c->selinux_context);

        if (c->apparmor_profile)
                fprintf(f,
                        "%sAppArmorProfile: %s%s\n",
                        prefix, c->apparmor_profile_ignore ? "-" : "", c->apparmor_profile);

        if (c->smack_process_label)
                fprintf(f,
                        "%sSmackProcessLabel: %s%s\n",
                        prefix, c->smack_process_label_ignore ? "-" : "", c->smack_process_label);

        if (c->personality != PERSONALITY_INVALID)
                fprintf(f,
                        "%sPersonality: %s\n",
                        prefix, strna(personality_to_string(c->personality)));

        fprintf(f,
                "%sLockPersonality: %s\n",
                prefix, yes_no(c->lock_personality));

        if (c->syscall_filter) {
                fprintf(f,
                        "%sSystemCallFilter: ",
                        prefix);

                if (!c->syscall_allow_list)
                        fputc('~', f);

#if HAVE_SECCOMP
                void *id, *val;
                bool first = true;
                HASHMAP_FOREACH_KEY(val, id, c->syscall_filter) {
                        _cleanup_free_ char *name = NULL;
                        const char *errno_name = NULL;
                        int num = PTR_TO_INT(val);

                        if (first)
                                first = false;
                        else
                                fputc(' ', f);

                        name = seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
                        fputs(strna(name), f);

                        if (num >= 0) {
                                errno_name = seccomp_errno_or_action_to_string(num);
                                if (errno_name)
                                        fprintf(f, ":%s", errno_name);
                                else
                                        fprintf(f, ":%d", num);
                        }
                }
#endif

                fputc('\n', f);
        }

        if (c->syscall_archs) {
                fprintf(f,
                        "%sSystemCallArchitectures:",
                        prefix);

#if HAVE_SECCOMP
                void *id;
                SET_FOREACH(id, c->syscall_archs)
                        fprintf(f, " %s", strna(seccomp_arch_to_string(PTR_TO_UINT32(id) - 1)));
#endif
                fputc('\n', f);
        }

        if (exec_context_restrict_namespaces_set(c)) {
                _cleanup_free_ char *s = NULL;

                r = namespace_flags_to_string(c->restrict_namespaces, &s);
                if (r >= 0)
                        fprintf(f, "%sRestrictNamespaces: %s\n",
                                prefix, strna(s));
        }

#if HAVE_LIBBPF
        if (exec_context_restrict_filesystems_set(c)) {
                char *fs;
                SET_FOREACH(fs, c->restrict_filesystems)
                        fprintf(f, "%sRestrictFileSystems: %s\n", prefix, fs);
        }
#endif

        if (c->network_namespace_path)
                fprintf(f,
                        "%sNetworkNamespacePath: %s\n",
                        prefix, c->network_namespace_path);

        if (c->syscall_errno > 0) {
                fprintf(f, "%sSystemCallErrorNumber: ", prefix);

#if HAVE_SECCOMP
                const char *errno_name = seccomp_errno_or_action_to_string(c->syscall_errno);
                if (errno_name)
                        fputs(errno_name, f);
                else
                        fprintf(f, "%d", c->syscall_errno);
#endif
                fputc('\n', f);
        }

        for (size_t i = 0; i < c->n_mount_images; i++) {
                fprintf(f, "%sMountImages: %s%s:%s", prefix,
                        c->mount_images[i].ignore_enoent ? "-": "",
                        c->mount_images[i].source,
                        c->mount_images[i].destination);
                LIST_FOREACH(mount_options, o, c->mount_images[i].mount_options)
                        fprintf(f, ":%s:%s",
                                partition_designator_to_string(o->partition_designator),
                                strempty(o->options));
                fprintf(f, "\n");
        }

        for (size_t i = 0; i < c->n_extension_images; i++) {
                fprintf(f, "%sExtensionImages: %s%s", prefix,
                        c->extension_images[i].ignore_enoent ? "-": "",
                        c->extension_images[i].source);
                LIST_FOREACH(mount_options, o, c->extension_images[i].mount_options)
                        fprintf(f, ":%s:%s",
                                partition_designator_to_string(o->partition_designator),
                                strempty(o->options));
                fprintf(f, "\n");
        }

        strv_dump(f, prefix, "ExtensionDirectories", c->extension_directories);
}

bool exec_context_maintains_privileges(const ExecContext *c) {
        assert(c);

        /* Returns true if the process forked off would run under
         * an unchanged UID or as root. */

        if (!c->user)
                return true;

        if (streq(c->user, "root") || streq(c->user, "0"))
                return true;

        return false;
}

int exec_context_get_effective_ioprio(const ExecContext *c) {
        int p;

        assert(c);

        if (c->ioprio_set)
                return c->ioprio;

        p = ioprio_get(IOPRIO_WHO_PROCESS, 0);
        if (p < 0)
                return IOPRIO_DEFAULT_CLASS_AND_PRIO;

        return ioprio_normalize(p);
}

bool exec_context_get_effective_mount_apivfs(const ExecContext *c) {
        assert(c);

        /* Explicit setting wins */
        if (c->mount_apivfs_set)
                return c->mount_apivfs;

        /* Default to "yes" if root directory or image are specified */
        if (exec_context_with_rootfs(c))
                return true;

        return false;
}

void exec_context_free_log_extra_fields(ExecContext *c) {
        assert(c);

        for (size_t l = 0; l < c->n_log_extra_fields; l++)
                free(c->log_extra_fields[l].iov_base);
        c->log_extra_fields = mfree(c->log_extra_fields);
        c->n_log_extra_fields = 0;
}

void exec_context_revert_tty(ExecContext *c) {
        _cleanup_close_ int fd = -EBADF;
        const char *path;
        struct stat st;
        int r;

        assert(c);

        /* First, reset the TTY (possibly kicking everybody else from the TTY) */
        exec_context_tty_reset(c, NULL);

        /* And then undo what chown_terminal() did earlier. Note that we only do this if we have a path
         * configured. If the TTY was passed to us as file descriptor we assume the TTY is opened and managed
         * by whoever passed it to us and thus knows better when and how to chmod()/chown() it back. */
        if (!exec_context_may_touch_tty(c))
                return;

        path = exec_context_tty_path(c);
        if (!path)
                return;

        fd = open(path, O_PATH|O_CLOEXEC);
        if (fd < 0)
                return (void) log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_WARNING, errno,
                                             "Failed to open TTY inode of '%s' to adjust ownership/access mode, ignoring: %m",
                                             path);

        if (fstat(fd, &st) < 0)
                return (void) log_warning_errno(errno, "Failed to stat TTY '%s', ignoring: %m", path);

        /* Let's add a superficial check that we only do this for stuff that looks like a TTY. We only check
         * if things are a character device, since a proper check either means we'd have to open the TTY and
         * use isatty(), but we'd rather not do that since opening TTYs comes with all kinds of side-effects
         * and is slow. Or we'd have to hardcode dev_t major information, which we'd rather avoid. Why bother
         * with this at all? → https://github.com/systemd/systemd/issues/19213 */
        if (!S_ISCHR(st.st_mode))
                return log_warning("Configured TTY '%s' is not actually a character device, ignoring.", path);

        r = fchmod_and_chown(fd, TTY_MODE, 0, TTY_GID);
        if (r < 0)
                log_warning_errno(r, "Failed to reset TTY ownership/access mode of %s, ignoring: %m", path);
}

int exec_context_get_clean_directories(
                ExecContext *c,
                char **prefix,
                ExecCleanMask mask,
                char ***ret) {

        _cleanup_strv_free_ char **l = NULL;
        int r;

        assert(c);
        assert(prefix);
        assert(ret);

        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
                if (!FLAGS_SET(mask, 1U << t))
                        continue;

                if (!prefix[t])
                        continue;

                for (size_t i = 0; i < c->directories[t].n_items; i++) {
                        char *j;

                        j = path_join(prefix[t], c->directories[t].items[i].path);
                        if (!j)
                                return -ENOMEM;

                        r = strv_consume(&l, j);
                        if (r < 0)
                                return r;

                        /* Also remove private directories unconditionally. */
                        if (t != EXEC_DIRECTORY_CONFIGURATION) {
                                j = path_join(prefix[t], "private", c->directories[t].items[i].path);
                                if (!j)
                                        return -ENOMEM;

                                r = strv_consume(&l, j);
                                if (r < 0)
                                        return r;
                        }

                        STRV_FOREACH(symlink, c->directories[t].items[i].symlinks) {
                                j = path_join(prefix[t], *symlink);
                                if (!j)
                                        return -ENOMEM;

                                r = strv_consume(&l, j);
                                if (r < 0)
                                        return r;
                        }
                }
        }

        *ret = TAKE_PTR(l);
        return 0;
}

int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret) {
        ExecCleanMask mask = 0;

        assert(c);
        assert(ret);

        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++)
                if (c->directories[t].n_items > 0)
                        mask |= 1U << t;

        *ret = mask;
        return 0;
}

bool exec_context_has_encrypted_credentials(ExecContext *c) {
        ExecLoadCredential *load_cred;
        ExecSetCredential *set_cred;

        assert(c);

        HASHMAP_FOREACH(load_cred, c->load_credentials)
                if (load_cred->encrypted)
                        return true;

        HASHMAP_FOREACH(set_cred, c->set_credentials)
                if (set_cred->encrypted)
                        return true;

        return false;
}

int exec_context_add_default_dependencies(Unit *u, const ExecContext *c) {
        assert(u);
        assert(u->default_dependencies);

        if (c && exec_context_needs_term(c))
                return unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_VCONSOLE_SETUP_SERVICE,
                                                   /* add_reference= */ true, UNIT_DEPENDENCY_DEFAULT);
        return 0;
}

void exec_status_start(ExecStatus *s, pid_t pid) {
        assert(s);

        *s = (ExecStatus) {
                .pid = pid,
        };

        dual_timestamp_get(&s->start_timestamp);
}

void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status) {
        assert(s);

        if (s->pid != pid)
                *s = (ExecStatus) {
                        .pid = pid,
                };

        dual_timestamp_get(&s->exit_timestamp);

        s->code = code;
        s->status = status;

        if (context && context->utmp_id)
                (void) utmp_put_dead_process(context->utmp_id, pid, code, status);
}

void exec_status_reset(ExecStatus *s) {
        assert(s);

        *s = (ExecStatus) {};
}

void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
        assert(s);
        assert(f);

        if (s->pid <= 0)
                return;

        prefix = strempty(prefix);

        fprintf(f,
                "%sPID: "PID_FMT"\n",
                prefix, s->pid);

        if (dual_timestamp_is_set(&s->start_timestamp))
                fprintf(f,
                        "%sStart Timestamp: %s\n",
                        prefix, FORMAT_TIMESTAMP(s->start_timestamp.realtime));

        if (dual_timestamp_is_set(&s->exit_timestamp))
                fprintf(f,
                        "%sExit Timestamp: %s\n"
                        "%sExit Code: %s\n"
                        "%sExit Status: %i\n",
                        prefix, FORMAT_TIMESTAMP(s->exit_timestamp.realtime),
                        prefix, sigchld_code_to_string(s->code),
                        prefix, s->status);
}

static void exec_command_dump(ExecCommand *c, FILE *f, const char *prefix) {
        _cleanup_free_ char *cmd = NULL;
        const char *prefix2;

        assert(c);
        assert(f);

        prefix = strempty(prefix);
        prefix2 = strjoina(prefix, "\t");

        cmd = quote_command_line(c->argv, SHELL_ESCAPE_EMPTY);

        fprintf(f,
                "%sCommand Line: %s\n",
                prefix, strnull(cmd));

        exec_status_dump(&c->exec_status, f, prefix2);
}

void exec_command_dump_list(ExecCommand *c, FILE *f, const char *prefix) {
        assert(f);

        prefix = strempty(prefix);

        LIST_FOREACH(command, i, c)
                exec_command_dump(i, f, prefix);
}

void exec_command_append_list(ExecCommand **l, ExecCommand *e) {
        ExecCommand *end;

        assert(l);
        assert(e);

        if (*l) {
                /* It's kind of important, that we keep the order here */
                end = LIST_FIND_TAIL(command, *l);
                LIST_INSERT_AFTER(command, *l, end, e);
        } else
                *l = e;
}

int exec_command_set(ExecCommand *c, const char *path, ...) {
        va_list ap;
        char **l, *p;

        assert(c);
        assert(path);

        va_start(ap, path);
        l = strv_new_ap(path, ap);
        va_end(ap);

        if (!l)
                return -ENOMEM;

        p = strdup(path);
        if (!p) {
                strv_free(l);
                return -ENOMEM;
        }

        free_and_replace(c->path, p);

        return strv_free_and_replace(c->argv, l);
}

int exec_command_append(ExecCommand *c, const char *path, ...) {
        _cleanup_strv_free_ char **l = NULL;
        va_list ap;
        int r;

        assert(c);
        assert(path);

        va_start(ap, path);
        l = strv_new_ap(path, ap);
        va_end(ap);

        if (!l)
                return -ENOMEM;

        r = strv_extend_strv(&c->argv, l, false);
        if (r < 0)
                return r;

        return 0;
}

static void *remove_tmpdir_thread(void *p) {
        _cleanup_free_ char *path = p;

        (void) rm_rf(path, REMOVE_ROOT|REMOVE_PHYSICAL);
        return NULL;
}

static ExecSharedRuntime* exec_shared_runtime_free(ExecSharedRuntime *rt) {
        if (!rt)
                return NULL;

        if (rt->manager)
                (void) hashmap_remove(rt->manager->exec_shared_runtime_by_id, rt->id);

        rt->id = mfree(rt->id);
        rt->tmp_dir = mfree(rt->tmp_dir);
        rt->var_tmp_dir = mfree(rt->var_tmp_dir);
        safe_close_pair(rt->netns_storage_socket);
        safe_close_pair(rt->ipcns_storage_socket);
        return mfree(rt);
}

DEFINE_TRIVIAL_UNREF_FUNC(ExecSharedRuntime, exec_shared_runtime, exec_shared_runtime_free);
DEFINE_TRIVIAL_CLEANUP_FUNC(ExecSharedRuntime*, exec_shared_runtime_free);

ExecSharedRuntime* exec_shared_runtime_destroy(ExecSharedRuntime *rt) {
        int r;

        if (!rt)
                return NULL;

        assert(rt->n_ref > 0);
        rt->n_ref--;

        if (rt->n_ref > 0)
                return NULL;

        if (rt->tmp_dir && !streq(rt->tmp_dir, RUN_SYSTEMD_EMPTY)) {
                log_debug("Spawning thread to nuke %s", rt->tmp_dir);

                r = asynchronous_job(remove_tmpdir_thread, rt->tmp_dir);
                if (r < 0)
                        log_warning_errno(r, "Failed to nuke %s: %m", rt->tmp_dir);
                else
                        rt->tmp_dir = NULL;
        }

        if (rt->var_tmp_dir && !streq(rt->var_tmp_dir, RUN_SYSTEMD_EMPTY)) {
                log_debug("Spawning thread to nuke %s", rt->var_tmp_dir);

                r = asynchronous_job(remove_tmpdir_thread, rt->var_tmp_dir);
                if (r < 0)
                        log_warning_errno(r, "Failed to nuke %s: %m", rt->var_tmp_dir);
                else
                        rt->var_tmp_dir = NULL;
        }

        return exec_shared_runtime_free(rt);
}

static int exec_shared_runtime_allocate(ExecSharedRuntime **ret, const char *id) {
        _cleanup_free_ char *id_copy = NULL;
        ExecSharedRuntime *n;

        assert(ret);

        id_copy = strdup(id);
        if (!id_copy)
                return -ENOMEM;

        n = new(ExecSharedRuntime, 1);
        if (!n)
                return -ENOMEM;

        *n = (ExecSharedRuntime) {
                .id = TAKE_PTR(id_copy),
                .netns_storage_socket = PIPE_EBADF,
                .ipcns_storage_socket = PIPE_EBADF,
        };

        *ret = n;
        return 0;
}

static int exec_shared_runtime_add(
                Manager *m,
                const char *id,
                char **tmp_dir,
                char **var_tmp_dir,
                int netns_storage_socket[2],
                int ipcns_storage_socket[2],
                ExecSharedRuntime **ret) {

        _cleanup_(exec_shared_runtime_freep) ExecSharedRuntime *rt = NULL;
        int r;

        assert(m);
        assert(id);

        /* tmp_dir, var_tmp_dir, {net,ipc}ns_storage_socket fds are donated on success */

        r = exec_shared_runtime_allocate(&rt, id);
        if (r < 0)
                return r;

        r = hashmap_ensure_put(&m->exec_shared_runtime_by_id, &string_hash_ops, rt->id, rt);
        if (r < 0)
                return r;

        assert(!!rt->tmp_dir == !!rt->var_tmp_dir); /* We require both to be set together */
        rt->tmp_dir = TAKE_PTR(*tmp_dir);
        rt->var_tmp_dir = TAKE_PTR(*var_tmp_dir);

        if (netns_storage_socket) {
                rt->netns_storage_socket[0] = TAKE_FD(netns_storage_socket[0]);
                rt->netns_storage_socket[1] = TAKE_FD(netns_storage_socket[1]);
        }

        if (ipcns_storage_socket) {
                rt->ipcns_storage_socket[0] = TAKE_FD(ipcns_storage_socket[0]);
                rt->ipcns_storage_socket[1] = TAKE_FD(ipcns_storage_socket[1]);
        }

        rt->manager = m;

        if (ret)
                *ret = rt;
        /* do not remove created ExecSharedRuntime object when the operation succeeds. */
        TAKE_PTR(rt);
        return 0;
}

static int exec_shared_runtime_make(
                Manager *m,
                const ExecContext *c,
                const char *id,
                ExecSharedRuntime **ret) {

        _cleanup_(namespace_cleanup_tmpdirp) char *tmp_dir = NULL, *var_tmp_dir = NULL;
        _cleanup_close_pair_ int netns_storage_socket[2] = PIPE_EBADF, ipcns_storage_socket[2] = PIPE_EBADF;
        int r;

        assert(m);
        assert(c);
        assert(id);

        /* It is not necessary to create ExecSharedRuntime object. */
        if (!exec_needs_network_namespace(c) && !exec_needs_ipc_namespace(c) && !c->private_tmp) {
                *ret = NULL;
                return 0;
        }

        if (c->private_tmp &&
            !(prefixed_path_strv_contains(c->inaccessible_paths, "/tmp") &&
              (prefixed_path_strv_contains(c->inaccessible_paths, "/var/tmp") ||
               prefixed_path_strv_contains(c->inaccessible_paths, "/var")))) {
                r = setup_tmp_dirs(id, &tmp_dir, &var_tmp_dir);
                if (r < 0)
                        return r;
        }

        if (exec_needs_network_namespace(c)) {
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, netns_storage_socket) < 0)
                        return -errno;
        }

        if (exec_needs_ipc_namespace(c)) {
                if (socketpair(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0, ipcns_storage_socket) < 0)
                        return -errno;
        }

        r = exec_shared_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_storage_socket, ipcns_storage_socket, ret);
        if (r < 0)
                return r;

        return 1;
}

int exec_shared_runtime_acquire(Manager *m, const ExecContext *c, const char *id, bool create, ExecSharedRuntime **ret) {
        ExecSharedRuntime *rt;
        int r;

        assert(m);
        assert(id);
        assert(ret);

        rt = hashmap_get(m->exec_shared_runtime_by_id, id);
        if (rt)
                /* We already have an ExecSharedRuntime object, let's increase the ref count and reuse it */
                goto ref;

        if (!create) {
                *ret = NULL;
                return 0;
        }

        /* If not found, then create a new object. */
        r = exec_shared_runtime_make(m, c, id, &rt);
        if (r < 0)
                return r;
        if (r == 0) {
                /* When r == 0, it is not necessary to create ExecSharedRuntime object. */
                *ret = NULL;
                return 0;
        }

ref:
        /* increment reference counter. */
        rt->n_ref++;
        *ret = rt;
        return 1;
}

int exec_shared_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) {
        ExecSharedRuntime *rt;

        assert(m);
        assert(f);
        assert(fds);

        HASHMAP_FOREACH(rt, m->exec_shared_runtime_by_id) {
                fprintf(f, "exec-runtime=%s", rt->id);

                if (rt->tmp_dir)
                        fprintf(f, " tmp-dir=%s", rt->tmp_dir);

                if (rt->var_tmp_dir)
                        fprintf(f, " var-tmp-dir=%s", rt->var_tmp_dir);

                if (rt->netns_storage_socket[0] >= 0) {
                        int copy;

                        copy = fdset_put_dup(fds, rt->netns_storage_socket[0]);
                        if (copy < 0)
                                return copy;

                        fprintf(f, " netns-socket-0=%i", copy);
                }

                if (rt->netns_storage_socket[1] >= 0) {
                        int copy;

                        copy = fdset_put_dup(fds, rt->netns_storage_socket[1]);
                        if (copy < 0)
                                return copy;

                        fprintf(f, " netns-socket-1=%i", copy);
                }

                if (rt->ipcns_storage_socket[0] >= 0) {
                        int copy;

                        copy = fdset_put_dup(fds, rt->ipcns_storage_socket[0]);
                        if (copy < 0)
                                return copy;

                        fprintf(f, " ipcns-socket-0=%i", copy);
                }

                if (rt->ipcns_storage_socket[1] >= 0) {
                        int copy;

                        copy = fdset_put_dup(fds, rt->ipcns_storage_socket[1]);
                        if (copy < 0)
                                return copy;

                        fprintf(f, " ipcns-socket-1=%i", copy);
                }

                fputc('\n', f);
        }

        return 0;
}

int exec_shared_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) {
        _cleanup_(exec_shared_runtime_freep) ExecSharedRuntime *rt_create = NULL;
        ExecSharedRuntime *rt;
        int r;

        /* This is for the migration from old (v237 or earlier) deserialization text.
         * Due to the bug #7790, this may not work with the units that use JoinsNamespaceOf=.
         * Even if the ExecSharedRuntime object originally created by the other unit, we cannot judge
         * so or not from the serialized text, then we always creates a new object owned by this. */

        assert(u);
        assert(key);
        assert(value);

        /* Manager manages ExecSharedRuntime objects by the unit id.
         * So, we omit the serialized text when the unit does not have id (yet?)... */
        if (isempty(u->id)) {
                log_unit_debug(u, "Invocation ID not found. Dropping runtime parameter.");
                return 0;
        }

        if (hashmap_ensure_allocated(&u->manager->exec_shared_runtime_by_id, &string_hash_ops) < 0)
                return log_oom();

        rt = hashmap_get(u->manager->exec_shared_runtime_by_id, u->id);
        if (!rt) {
                if (exec_shared_runtime_allocate(&rt_create, u->id) < 0)
                        return log_oom();

                rt = rt_create;
        }

        if (streq(key, "tmp-dir")) {
                if (free_and_strdup_warn(&rt->tmp_dir, value) < 0)
                        return -ENOMEM;

        } else if (streq(key, "var-tmp-dir")) {
                if (free_and_strdup_warn(&rt->var_tmp_dir, value) < 0)
                        return -ENOMEM;

        } else if (streq(key, "netns-socket-0")) {
                int fd;

                if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd)) {
                        log_unit_debug(u, "Failed to parse netns socket value: %s", value);
                        return 0;
                }

                safe_close(rt->netns_storage_socket[0]);
                rt->netns_storage_socket[0] = fdset_remove(fds, fd);

        } else if (streq(key, "netns-socket-1")) {
                int fd;

                if ((fd = parse_fd(value)) < 0 || !fdset_contains(fds, fd)) {
                        log_unit_debug(u, "Failed to parse netns socket value: %s", value);
                        return 0;
                }

                safe_close(rt->netns_storage_socket[1]);
                rt->netns_storage_socket[1] = fdset_remove(fds, fd);

        } else
                return 0;

        /* If the object is newly created, then put it to the hashmap which manages ExecSharedRuntime objects. */
        if (rt_create) {
                r = hashmap_put(u->manager->exec_shared_runtime_by_id, rt_create->id, rt_create);
                if (r < 0) {
                        log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m");
                        return 0;
                }

                rt_create->manager = u->manager;

                /* Avoid cleanup */
                TAKE_PTR(rt_create);
        }

        return 1;
}

int exec_shared_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds) {
        _cleanup_free_ char *tmp_dir = NULL, *var_tmp_dir = NULL;
        char *id = NULL;
        int r, netns_fdpair[] = {-1, -1}, ipcns_fdpair[] = {-1, -1};
        const char *p, *v = ASSERT_PTR(value);
        size_t n;

        assert(m);
        assert(fds);

        n = strcspn(v, " ");
        id = strndupa_safe(v, n);
        if (v[n] != ' ')
                goto finalize;
        p = v + n + 1;

        v = startswith(p, "tmp-dir=");
        if (v) {
                n = strcspn(v, " ");
                tmp_dir = strndup(v, n);
                if (!tmp_dir)
                        return log_oom();
                if (v[n] != ' ')
                        goto finalize;
                p = v + n + 1;
        }

        v = startswith(p, "var-tmp-dir=");
        if (v) {
                n = strcspn(v, " ");
                var_tmp_dir = strndup(v, n);
                if (!var_tmp_dir)
                        return log_oom();
                if (v[n] != ' ')
                        goto finalize;
                p = v + n + 1;
        }

        v = startswith(p, "netns-socket-0=");
        if (v) {
                char *buf;

                n = strcspn(v, " ");
                buf = strndupa_safe(v, n);

                netns_fdpair[0] = parse_fd(buf);
                if (netns_fdpair[0] < 0)
                        return log_debug_errno(netns_fdpair[0], "Unable to parse exec-runtime specification netns-socket-0=%s: %m", buf);
                if (!fdset_contains(fds, netns_fdpair[0]))
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
                                               "exec-runtime specification netns-socket-0= refers to unknown fd %d: %m", netns_fdpair[0]);
                netns_fdpair[0] = fdset_remove(fds, netns_fdpair[0]);
                if (v[n] != ' ')
                        goto finalize;
                p = v + n + 1;
        }

        v = startswith(p, "netns-socket-1=");
        if (v) {
                char *buf;

                n = strcspn(v, " ");
                buf = strndupa_safe(v, n);

                netns_fdpair[1] = parse_fd(buf);
                if (netns_fdpair[1] < 0)
                        return log_debug_errno(netns_fdpair[1], "Unable to parse exec-runtime specification netns-socket-1=%s: %m", buf);
                if (!fdset_contains(fds, netns_fdpair[1]))
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
                                               "exec-runtime specification netns-socket-1= refers to unknown fd %d: %m", netns_fdpair[1]);
                netns_fdpair[1] = fdset_remove(fds, netns_fdpair[1]);
                if (v[n] != ' ')
                        goto finalize;
                p = v + n + 1;
        }

        v = startswith(p, "ipcns-socket-0=");
        if (v) {
                char *buf;

                n = strcspn(v, " ");
                buf = strndupa_safe(v, n);

                ipcns_fdpair[0] = parse_fd(buf);
                if (ipcns_fdpair[0] < 0)
                        return log_debug_errno(ipcns_fdpair[0], "Unable to parse exec-runtime specification ipcns-socket-0=%s: %m", buf);
                if (!fdset_contains(fds, ipcns_fdpair[0]))
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
                                               "exec-runtime specification ipcns-socket-0= refers to unknown fd %d: %m", ipcns_fdpair[0]);
                ipcns_fdpair[0] = fdset_remove(fds, ipcns_fdpair[0]);
                if (v[n] != ' ')
                        goto finalize;
                p = v + n + 1;
        }

        v = startswith(p, "ipcns-socket-1=");
        if (v) {
                char *buf;

                n = strcspn(v, " ");
                buf = strndupa_safe(v, n);

                ipcns_fdpair[1] = parse_fd(buf);
                if (ipcns_fdpair[1] < 0)
                        return log_debug_errno(ipcns_fdpair[1], "Unable to parse exec-runtime specification ipcns-socket-1=%s: %m", buf);
                if (!fdset_contains(fds, ipcns_fdpair[1]))
                        return log_debug_errno(SYNTHETIC_ERRNO(EBADF),
                                               "exec-runtime specification ipcns-socket-1= refers to unknown fd %d: %m", ipcns_fdpair[1]);
                ipcns_fdpair[1] = fdset_remove(fds, ipcns_fdpair[1]);
        }

finalize:
        r = exec_shared_runtime_add(m, id, &tmp_dir, &var_tmp_dir, netns_fdpair, ipcns_fdpair, NULL);
        if (r < 0)
                return log_debug_errno(r, "Failed to add exec-runtime: %m");
        return 0;
}

void exec_shared_runtime_vacuum(Manager *m) {
        ExecSharedRuntime *rt;

        assert(m);

        /* Free unreferenced ExecSharedRuntime objects. This is used after manager deserialization process. */

        HASHMAP_FOREACH(rt, m->exec_shared_runtime_by_id) {
                if (rt->n_ref > 0)
                        continue;

                (void) exec_shared_runtime_free(rt);
        }
}

int exec_runtime_make(ExecSharedRuntime *shared, DynamicCreds *creds, ExecRuntime **ret) {
        _cleanup_(exec_runtime_freep) ExecRuntime *rt = NULL;

        assert(ret);

        if (!shared && !creds) {
                *ret = NULL;
                return 0;
        }

        rt = new(ExecRuntime, 1);
        if (!rt)
                return -ENOMEM;

        *rt = (ExecRuntime) {
                .shared = shared,
                .dynamic_creds = creds,
        };

        *ret = TAKE_PTR(rt);
        return 1;
}

ExecRuntime* exec_runtime_free(ExecRuntime *rt) {
        if (!rt)
                return NULL;

        exec_shared_runtime_unref(rt->shared);
        dynamic_creds_unref(rt->dynamic_creds);
        return mfree(rt);
}

ExecRuntime* exec_runtime_destroy(ExecRuntime *rt) {
        if (!rt)
                return NULL;

        rt->shared = exec_shared_runtime_destroy(rt->shared);
        rt->dynamic_creds = dynamic_creds_destroy(rt->dynamic_creds);
        return exec_runtime_free(rt);
}

void exec_params_clear(ExecParameters *p) {
        if (!p)
                return;

        p->environment = strv_free(p->environment);
        p->fd_names = strv_free(p->fd_names);
        p->fds = mfree(p->fds);
        p->exec_fd = safe_close(p->exec_fd);
}

ExecSetCredential *exec_set_credential_free(ExecSetCredential *sc) {
        if (!sc)
                return NULL;

        free(sc->id);
        free(sc->data);
        return mfree(sc);
}

ExecLoadCredential *exec_load_credential_free(ExecLoadCredential *lc) {
        if (!lc)
                return NULL;

        free(lc->id);
        free(lc->path);
        return mfree(lc);
}

void exec_directory_done(ExecDirectory *d) {
        if (!d)
                return;

        for (size_t i = 0; i < d->n_items; i++) {
                free(d->items[i].path);
                strv_free(d->items[i].symlinks);
        }

        d->items = mfree(d->items);
        d->n_items = 0;
        d->mode = 0755;
}

static ExecDirectoryItem *exec_directory_find(ExecDirectory *d, const char *path) {
        assert(d);
        assert(path);

        for (size_t i = 0; i < d->n_items; i++)
                if (path_equal(d->items[i].path, path))
                        return &d->items[i];

        return NULL;
}

int exec_directory_add(ExecDirectory *d, const char *path, const char *symlink) {
        _cleanup_strv_free_ char **s = NULL;
        _cleanup_free_ char *p = NULL;
        ExecDirectoryItem *existing;
        int r;

        assert(d);
        assert(path);

        existing = exec_directory_find(d, path);
        if (existing) {
                r = strv_extend(&existing->symlinks, symlink);
                if (r < 0)
                        return r;

                return 0; /* existing item is updated */
        }

        p = strdup(path);
        if (!p)
                return -ENOMEM;

        if (symlink) {
                s = strv_new(symlink);
                if (!s)
                        return -ENOMEM;
        }

        if (!GREEDY_REALLOC(d->items, d->n_items + 1))
                return -ENOMEM;

        d->items[d->n_items++] = (ExecDirectoryItem) {
                .path = TAKE_PTR(p),
                .symlinks = TAKE_PTR(s),
        };

        return 1; /* new item is added */
}

static int exec_directory_item_compare_func(const ExecDirectoryItem *a, const ExecDirectoryItem *b) {
        assert(a);
        assert(b);

        return path_compare(a->path, b->path);
}

void exec_directory_sort(ExecDirectory *d) {
        assert(d);

        /* Sort the exec directories to make always parent directories processed at first in
         * setup_exec_directory(), e.g., even if StateDirectory=foo/bar foo, we need to create foo at first,
         * then foo/bar. Also, set .only_create flag if one of the parent directories is contained in the
         * list. See also comments in setup_exec_directory() and issue #24783. */

        if (d->n_items <= 1)
                return;

        typesafe_qsort(d->items, d->n_items, exec_directory_item_compare_func);

        for (size_t i = 1; i < d->n_items; i++)
                for (size_t j = 0; j < i; j++)
                        if (path_startswith(d->items[i].path, d->items[j].path)) {
                                d->items[i].only_create = true;
                                break;
                        }
}

ExecCleanMask exec_clean_mask_from_string(const char *s) {
        ExecDirectoryType t;

        assert(s);

        if (streq(s, "all"))
                return EXEC_CLEAN_ALL;
        if (streq(s, "fdstore"))
                return EXEC_CLEAN_FDSTORE;

        t = exec_resource_type_from_string(s);
        if (t < 0)
                return (ExecCleanMask) t;

        return 1U << t;
}

DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_set_credential_hash_ops, char, string_hash_func, string_compare_func, ExecSetCredential, exec_set_credential_free);
DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(exec_load_credential_hash_ops, char, string_hash_func, string_compare_func, ExecLoadCredential, exec_load_credential_free);

static const char* const exec_input_table[_EXEC_INPUT_MAX] = {
        [EXEC_INPUT_NULL] = "null",
        [EXEC_INPUT_TTY] = "tty",
        [EXEC_INPUT_TTY_FORCE] = "tty-force",
        [EXEC_INPUT_TTY_FAIL] = "tty-fail",
        [EXEC_INPUT_SOCKET] = "socket",
        [EXEC_INPUT_NAMED_FD] = "fd",
        [EXEC_INPUT_DATA] = "data",
        [EXEC_INPUT_FILE] = "file",
};

DEFINE_STRING_TABLE_LOOKUP(exec_input, ExecInput);

static const char* const exec_output_table[_EXEC_OUTPUT_MAX] = {
        [EXEC_OUTPUT_INHERIT] = "inherit",
        [EXEC_OUTPUT_NULL] = "null",
        [EXEC_OUTPUT_TTY] = "tty",
        [EXEC_OUTPUT_KMSG] = "kmsg",
        [EXEC_OUTPUT_KMSG_AND_CONSOLE] = "kmsg+console",
        [EXEC_OUTPUT_JOURNAL] = "journal",
        [EXEC_OUTPUT_JOURNAL_AND_CONSOLE] = "journal+console",
        [EXEC_OUTPUT_SOCKET] = "socket",
        [EXEC_OUTPUT_NAMED_FD] = "fd",
        [EXEC_OUTPUT_FILE] = "file",
        [EXEC_OUTPUT_FILE_APPEND] = "append",
        [EXEC_OUTPUT_FILE_TRUNCATE] = "truncate",
};

DEFINE_STRING_TABLE_LOOKUP(exec_output, ExecOutput);

static const char* const exec_utmp_mode_table[_EXEC_UTMP_MODE_MAX] = {
        [EXEC_UTMP_INIT] = "init",
        [EXEC_UTMP_LOGIN] = "login",
        [EXEC_UTMP_USER] = "user",
};

DEFINE_STRING_TABLE_LOOKUP(exec_utmp_mode, ExecUtmpMode);

static const char* const exec_preserve_mode_table[_EXEC_PRESERVE_MODE_MAX] = {
        [EXEC_PRESERVE_NO] = "no",
        [EXEC_PRESERVE_YES] = "yes",
        [EXEC_PRESERVE_RESTART] = "restart",
};

DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(exec_preserve_mode, ExecPreserveMode, EXEC_PRESERVE_YES);

/* This table maps ExecDirectoryType to the setting it is configured with in the unit */
static const char* const exec_directory_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
        [EXEC_DIRECTORY_RUNTIME] = "RuntimeDirectory",
        [EXEC_DIRECTORY_STATE] = "StateDirectory",
        [EXEC_DIRECTORY_CACHE] = "CacheDirectory",
        [EXEC_DIRECTORY_LOGS] = "LogsDirectory",
        [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectory",
};

DEFINE_STRING_TABLE_LOOKUP(exec_directory_type, ExecDirectoryType);

/* This table maps ExecDirectoryType to the symlink setting it is configured with in the unit */
static const char* const exec_directory_type_symlink_table[_EXEC_DIRECTORY_TYPE_MAX] = {
        [EXEC_DIRECTORY_RUNTIME]       = "RuntimeDirectorySymlink",
        [EXEC_DIRECTORY_STATE]         = "StateDirectorySymlink",
        [EXEC_DIRECTORY_CACHE]         = "CacheDirectorySymlink",
        [EXEC_DIRECTORY_LOGS]          = "LogsDirectorySymlink",
        [EXEC_DIRECTORY_CONFIGURATION] = "ConfigurationDirectorySymlink",
};

DEFINE_STRING_TABLE_LOOKUP(exec_directory_type_symlink, ExecDirectoryType);

/* And this table maps ExecDirectoryType too, but to a generic term identifying the type of resource. This
 * one is supposed to be generic enough to be used for unit types that don't use ExecContext and per-unit
 * directories, specifically .timer units with their timestamp touch file. */
static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
        [EXEC_DIRECTORY_RUNTIME] = "runtime",
        [EXEC_DIRECTORY_STATE] = "state",
        [EXEC_DIRECTORY_CACHE] = "cache",
        [EXEC_DIRECTORY_LOGS] = "logs",
        [EXEC_DIRECTORY_CONFIGURATION] = "configuration",
};

DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType);

/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
 * the service payload in. */
static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
        [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
        [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
        [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
        [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
};

DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);

static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = {
        [EXEC_KEYRING_INHERIT] = "inherit",
        [EXEC_KEYRING_PRIVATE] = "private",
        [EXEC_KEYRING_SHARED] = "shared",
};

DEFINE_STRING_TABLE_LOOKUP(exec_keyring_mode, ExecKeyringMode);