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
|
/**
* @file exec.c
* @brief The evaluator.
*
* The guiding rule (see DESIGN.md, "Process creation"): do the work in the
* shell when the language allows it, create a process with spawn() when
* one is needed, and fork() only when a copy of the shell itself is
* required. Everything a spawned child needs is prepared here in the
* parent: its arguments, its environment and a plan for its descriptors.
*/
#include "exec.h"
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <unistd.h>
#include "expand.h"
#include "interact.h"
#include "parser.h"
#include "sys.h"
/* POSIX may leave PIPE_BUF undefined when the limit varies by file (z/OS
does); _POSIX_PIPE_BUF is the guaranteed minimum. */
#ifndef PIPE_BUF
#define PIPE_BUF _POSIX_PIPE_BUF
#endif
/**
* @brief A `break`, `continue` or `return` is in progress.
*/
skip_type skip_kind;
/**
* @brief Loop levels a pending `break` or `continue` still has to leave.
*/
int skip_count;
/**
* @brief Number of enclosing loops.
*/
int loop_depth;
/**
* @brief Number of function calls in progress.
*/
int func_depth;
/**
* @brief Number of `.` files being read.
*/
int dot_depth;
/**
* @brief Processes created with spawn (reported by ZASH_PROCSTAT).
*/
long stat_spawns;
/**
* @brief Processes created with fork (reported by ZASH_PROCSTAT).
*/
long stat_forks;
/**
* @brief This process is a forked copy of the shell.
*/
bool in_subshell;
/**
* @brief A command substitution ran while the current command was expanded.
*/
static bool cmdsub_ran;
/**
* @brief Its exit status: the status of a command that is only assignments.
*/
static int cmdsub_status;
/* ---- command table --------------------------------------------------- */
/**
* @brief Number of buckets in the command table.
*/
#define CTAB_SIZE ((size_t)256)
/**
* @brief PATH used by `command -p` and when PATH is unset.
*/
static const char default_path[] = "/bin:/usr/bin";
/**
* @brief One name in the command table.
*
* One hash table answers "what is this command name?": it holds builtins,
* functions and the paths of external commands already found in PATH.
*/
typedef struct cmdent {
struct cmdent *next;
const builtin *bi;
func *fn;
char *path;
unsigned hash; /**< full hash of name: rules out collisions cheaply */
char name[];
} cmdent;
/**
* @brief The command table.
*/
static cmdent *ctab[CTAB_SIZE];
/**
* @brief Find a name in the command table.
* @param name Command name.
* @param create Add an empty entry if it is not there.
* @return The entry, or nullptr.
*/
static cmdent *cmd_lookup(const char *name, bool create) {
unsigned h = 5381;
for (const char *p = name; *p; p++)
h = h * 33 + (unsigned char)*p;
cmdent **bucket = &ctab[h % CTAB_SIZE];
for (cmdent *e = *bucket; e; e = e->next) {
if (e->hash == h && !strcmp(e->name, name))
return e;
}
if (!create)
return nullptr;
size_t len = strlen(name) + 1;
cmdent *e = xmalloc(sizeof *e + len);
*e = (cmdent){.next = *bucket, .hash = h};
memcpy(e->name, name, len);
*bucket = e;
return e;
}
/**
* @brief Forget every remembered command path (`hash -r`, or PATH changed).
*/
void hash_clear(void) {
for (size_t i = 0; i < CTAB_SIZE; i++) {
for (cmdent *e = ctab[i]; e; e = e->next) {
free(e->path);
e->path = nullptr;
}
}
}
/**
* @brief Print the remembered command paths (`hash`).
*/
void hash_print(void) {
for (size_t i = 0; i < CTAB_SIZE; i++) {
for (const cmdent *e = ctab[i]; e; e = e->next) {
if (e->path)
out_printf(&out1, "%s\n", e->path);
}
}
}
/**
* @brief Add a difference of two timevals, in microseconds, to a total.
*/
static long long tv_diff(struct timeval a, struct timeval b) {
return (long long)(b.tv_sec - a.tv_sec) * 1000000 +
(long long)(b.tv_usec - a.tv_usec);
}
/**
* @brief Print one line of `time` output.
* @param label "real", "user" or "sys".
* @param us The time in microseconds.
* @param posix `-p`: seconds with two decimals. Else `0m0.000s`.
*/
static void put_time(const char *label, long long us, bool posix) {
if (us < 0)
us = 0;
if (posix)
out_printf(&out2, "%s %lld.%02lld", label, us / 1000000,
us % 1000000 / 10000);
else
out_printf(&out2, "%s\t%lldm%lld.%03llds", label, us / 60000000,
us / 1000000 % 60, us % 1000000 / 1000);
}
/**
* @brief Run `time pipeline` and report where the time went.
*
* The report goes to standard error after the pipeline finishes:
*
* real 0m1.204s
* user 0m0.310s (shell 0m0.010s, children 0m0.300s)
* sys 0m0.052s (shell 0m0.002s, children 0m0.050s)
*
* The split is what an external `time` cannot give: CPU the shell itself
* used (builtins, expansion, loops) against CPU used by the processes it
* ran, which is the first question when a script costs too much. With
* `-p` the three POSIX lines are printed and nothing else.
*
* @param n The N_TIME node.
* @param flags Evaluation flags for the pipeline. `EV_EXIT` is dropped
* because the shell must survive to print the report.
* @return Status of the pipeline (0 if there is none).
*/
static int eval_time(const node *n, unsigned flags) {
struct rusage s0;
struct rusage c0;
struct rusage s1;
struct rusage c1;
struct timeval t0;
struct timeval t1;
getrusage(RUSAGE_SELF, &s0);
getrusage(RUSAGE_CHILDREN, &c0);
gettimeofday(&t0, nullptr);
int status =
n->u.time.body ? eval_node(n->u.time.body, flags & ~EV_EXIT) : 0;
gettimeofday(&t1, nullptr);
getrusage(RUSAGE_SELF, &s1);
getrusage(RUSAGE_CHILDREN, &c1);
bool posix = n->u.time.posix;
long long self[2] = {
tv_diff(s0.ru_utime, s1.ru_utime),
tv_diff(s0.ru_stime, s1.ru_stime),
};
long long kids[2] = {
tv_diff(c0.ru_utime, c1.ru_utime),
tv_diff(c0.ru_stime, c1.ru_stime),
};
static const char *const label[2] = {"user", "sys"};
out_flush(&out1);
put_time("real", tv_diff(t0, t1), posix);
out_putc(&out2, '\n');
for (int i = 0; i < 2; i++) {
put_time(label[i], self[i] + kids[i], posix);
if (!posix) {
put_time(" (shell", self[i], true);
put_time("s, children", kids[i], true);
out_puts(&out2, "s)");
}
out_putc(&out2, '\n');
}
out_flush(&out2);
return status;
}
/**
* @brief Is this byte allowed in an MVS job name?
*/
static bool jobname_char(char c) {
return (c >= 'A' && c <= 'I') || (c >= 'J' && c <= 'R') ||
(c >= 'S' && c <= 'Z') || (c >= '0' && c <= '9') || c == '@' ||
c == '#' || c == '$';
}
/**
* @brief Does an environment vector define a variable?
* @param envp The vector.
* @param name The name followed by `=`.
*/
static bool env_has(char **envp, const char *name) {
size_t n = strlen(name);
for (; *envp; envp++) {
if (!strncmp(*envp, name, n))
return true;
}
return false;
}
/**
* @brief Add the z/OS per-command variables to a command's environment.
*
* Called only when `set -o jobnames` or `set -o shareas` is on, so a
* shell that uses neither pays two byte tests per external command.
*
* - **jobnames:** `_BPX_JOBNAME` is set to the command's name in upper
* case (up to 8 characters valid in a job name), so that each command
* is visible under its own name in SDSF, SMF type 30 records and WLM
* classification, instead of as `USERID1` to `USERID9`. z/OS honours
* it only for a process that gets its own address space and only if
* the user may read `BPX.JOBNAME` in FACILITY (or is a superuser).
* - **shareas:** `_BPX_SHAREAS=YES` for a foreground command, which then
* runs in the shell's address space: no address space creation, which
* is most of the cost of starting a command on z/OS. Background
* commands and pipeline stages are left alone: they outlive or run
* beside the shell, and a shared address space serialises storage
* and is torn down with its owner.
*
* A variable the user has exported, or given on the command itself, is
* never overridden.
*
* @param envp The command's environment.
* @param name argv[0].
* @param foreground The shell waits for this command alone.
* @return The environment to use, in scratch memory.
*/
static char **zos_environ(char **envp, const char *name, bool foreground) {
char *add[2];
int nadd = 0;
if (opt.jobnames && !env_has(envp, "_BPX_JOBNAME=")) {
const char *base = strrchr(name, '/');
base = base ? base + 1 : name;
char *text = arena_alloc(&scratch, sizeof "_BPX_JOBNAME=" + 8);
memcpy(text, "_BPX_JOBNAME=", sizeof "_BPX_JOBNAME=" - 1);
char *p = text + sizeof "_BPX_JOBNAME=" - 1; /* no stpcpy on z/OS */
char *start = p;
for (; *base && p - start < 8; base++) {
char c = (char)toupper((unsigned char)*base);
if (!jobname_char(c) || (p == start && c >= '0' && c <= '9'))
continue;
*p++ = c;
}
*p = '\0';
if (p > start)
add[nadd++] = text;
}
if (opt.shareas && foreground && !env_has(envp, "_BPX_SHAREAS=")) {
static char shareas[] = "_BPX_SHAREAS=YES";
add[nadd++] = shareas;
}
if (!nadd)
return envp;
size_t n = 0;
while (envp[n])
n++;
char **env = arena_alloc(&scratch, (n + (size_t)nadd + 1) * sizeof *env);
memcpy(env, envp, n * sizeof *env);
for (int i = 0; i < nadd; i++)
env[n + (size_t)i] = add[i];
env[n + (size_t)nadd] = nullptr;
return env;
}
/**
* @brief PATH hook: remembered paths are no longer valid.
*/
static void path_changed(const char *value) {
(void)value;
hash_clear();
}
/**
* @brief Search a path list for a file.
* @param name File name without a slash.
* @param path Colon-separated directories.
* @param executable Require a regular file with execute permission.
* @return The full path in scratch memory, or nullptr.
*/
char *path_search(const char *name, const char *path, bool executable) {
size_t nlen = strlen(name);
for (const char *p = path;;) {
const char *colon = strchr(p, ':');
size_t dlen = colon ? (size_t)(colon - p) : strlen(p);
char *full = arena_alloc(&scratch, dlen + nlen + 2);
if (dlen) {
memcpy(full, p, dlen);
full[dlen] = '/';
memcpy(full + dlen + 1, name, nlen + 1);
} else {
memcpy(full, name, nlen + 1);
}
struct stat st;
if (stat(full, &st) == 0 && S_ISREG(st.st_mode) &&
(!executable || (st.st_mode & 0111)))
return full;
if (!colon)
return nullptr;
p = colon + 1;
}
}
/**
* @brief PATH from a `PATH=... command` prefix, used for that one lookup.
*/
static const char *path_override;
/**
* @brief Work out what a command name refers to.
*
* Order: special builtins, functions, regular builtins, then PATH. A path
* found in PATH is remembered for next time.
*
* @param name The command name.
* @param ci Receives the answer.
* @param flags FC_NOFUNC to skip functions, FC_DEFPATH to search the
* default PATH.
*/
void find_command(const char *name, cmdinfo *ci, unsigned flags) {
*ci = (cmdinfo){.kind = C_NOTFOUND};
if (strchr(name, '/')) {
ci->kind = C_EXTERNAL;
ci->path = name;
return;
}
cmdent *e = cmd_lookup(name, false);
if (e) {
if (e->bi && (e->bi->flags & BI_SPECIAL)) {
ci->kind = C_BUILTIN;
ci->bi = e->bi;
return;
}
if (e->fn && !(flags & FC_NOFUNC)) {
ci->kind = C_FUNC;
ci->fn = e->fn;
return;
}
if (e->bi) {
ci->kind = C_BUILTIN;
ci->bi = e->bi;
return;
}
if (e->path && !(flags & FC_DEFPATH) && !path_override) {
ci->kind = C_EXTERNAL;
ci->path = e->path;
return;
}
}
const char *path = (flags & FC_DEFPATH) ? default_path
: path_override ? path_override
: var_get("PATH");
char *full = path_search(name, path ? path : default_path, true);
if (!full)
return;
ci->kind = C_EXTERNAL;
ci->path = full;
if (!(flags & FC_DEFPATH) && !path_override) {
e = cmd_lookup(name, true);
e->path = xstrdup(full);
ci->path = e->path;
}
}
/**
* @brief Drop a reference to a function body, freeing it with the last one.
*/
static void func_unref(func *fn) {
if (--fn->refs == 0) {
arena_unref(fn->arena);
free(fn);
}
}
/**
* @brief Define (or redefine) a function.
* @param name Its name.
* @param body Its body.
* @param owner Arena that owns the body. A reference is taken.
*/
void func_define(const char *name, node *body, arena *owner) {
cmdent *e = cmd_lookup(name, true);
if (e->fn)
func_unref(e->fn);
e->fn = xmalloc(sizeof *e->fn);
*e->fn = (func){body, owner, 1};
owner->refs++;
}
/**
* @brief Call a function for the name of every shell function.
* @param fn Callback.
* @param arg Passed through to the callback.
*/
void func_each(void (*fn)(const char *name, void *arg), void *arg) {
for (size_t i = 0; i < CTAB_SIZE; i++) {
for (const cmdent *e = ctab[i]; e; e = e->next) {
if (e->fn)
fn(e->name, arg);
}
}
}
/**
* @brief Remove a function.
* @return false if there was none.
*/
bool func_unset(const char *name) {
cmdent *e = cmd_lookup(name, false);
if (!e || !e->fn)
return false;
func_unref(e->fn);
e->fn = nullptr;
return true;
}
/**
* @brief Fill the command table with the builtins and attach variable hooks.
*/
void exec_init(void) {
for (size_t i = 0; i < nbuiltins; i++)
cmd_lookup(builtins[i].name, true)->bi = &builtins[i];
var_find("PATH", 4, true)->hook = path_changed;
var_find("OPTIND", 6, true)->hook = getopts_reset;
}
/* ---- unwinding ------------------------------------------------------- */
/**
* @brief Record the state an exception handler must put back.
*/
void unwind_save(unwind *u) {
u->scope = var_scope;
u->redir = redir_top;
u->input = input;
}
/**
* @brief Undo redirections, variable scopes and inputs back to a saved state.
*/
void unwind_restore(const unwind *u) {
redir_unwind(u->redir);
scope_unwind(u->scope);
input_unwind(u->input);
}
/* ---- processes ------------------------------------------------------- */
/**
* @brief Temporary experiment: bit mask of fork-path steps to skip.
*/
int perf_ablate(void) {
static int bits = -1;
if (bits < 0) {
const char *s = getenv("ZASH_FORK_ABLATE");
bits = s ? atoi(s) : 0;
}
return bits;
}
/**
* @brief fork() a copy of the shell.
*
* The child is a subshell: it forgets the parent's jobs and traps, and
* under job control joins the process group of the job being launched.
*
* @return 0 in the child, the child's pid in the parent. A failed fork
* raises an error.
*/
pid_t fork_shell(void) {
if (!(perf_ablate() & 4))
flush_all();
(void)shell_pid(); /* fix $$ before the pid changes */
pid_t pid = fork();
if (pid < 0)
sh_error("cannot fork: %s", strerror(errno));
if (pid == 0) {
in_subshell = true;
stat_spawns = stat_forks = 0;
if (job_launching)
job_child_setup(); /* while SIGTTOU is still ignored */
if (!(perf_ablate() & 1))
jobs_forget();
if (!(perf_ablate() & 2))
trap_reset_child();
} else {
stat_forks++;
if (job_launching)
job_add_proc(job_launching, pid);
}
return pid;
}
/**
* @brief Run a command as the whole remaining life of this (forked) process.
*/
[[noreturn]] static void child_eval(node *n) {
if (perf_ablate() & 8)
_exit(0);
jmploc jl;
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
eval_node(n, EV_EXIT);
}
exit_shell(exitstatus);
}
/* ---- running external programs --------------------------------------- */
/**
* @brief Build the argument vector for a file the system refused to execute
* (ENOEXEC): the interpreter named on its `#!` line, or this shell.
* @param path The file.
* @param argv The arguments it was to be run with.
* @return The new vector in scratch memory, or nullptr if the file is not
* a script.
*/
static char **script_argv(const char *path, char **argv) {
char head[256];
int fd = open(path, O_RDONLY);
if (fd < 0)
return nullptr;
ssize_t n = read(fd, head, sizeof head - 1);
close(fd);
if (n < 0)
return nullptr;
if (memchr(head, '\0', (size_t)n)) {
errno = ENOEXEC; /* a binary we cannot run, not a script */
return nullptr;
}
head[n] = '\0';
int argc = 0;
while (argv[argc])
argc++;
char **nv = arena_alloc(&scratch, ((size_t)argc + 4) * sizeof *nv);
int k = 0;
if (head[0] == '#' && head[1] == '!') {
char *p = head + 2;
p[strcspn(p, "\n")] = '\0';
p += strspn(p, " \t");
char *interp = p;
p += strcspn(p, " \t");
if (*p) {
*p++ = '\0';
p += strspn(p, " \t");
}
size_t alen = strlen(p);
while (alen && (p[alen - 1] == ' ' || p[alen - 1] == '\t'))
alen--;
if (!*interp) {
errno = ENOEXEC;
return nullptr;
}
nv[k++] = arena_strndup(&scratch, interp, strlen(interp));
if (alen)
nv[k++] = arena_strndup(&scratch, p, alen);
} else {
nv[k++] = (char *)shell_path();
}
nv[k++] = (char *)path;
for (int i = 1; i < argc; i++)
nv[k++] = argv[i];
nv[k] = nullptr;
return nv;
}
/**
* @brief Report that a command could not be run.
* @return 127 if it does not exist, otherwise 126.
*/
static int exec_error(const char *name, int err) {
bool missing = err == ENOENT || err == ENOTDIR;
sh_warn("%s: %s", name, missing ? "not found" : strerror(err));
return missing ? 127 : 126;
}
/**
* @brief Replace the shell with a program. Does not return.
*/
[[noreturn]] static void exec_path(const char *path, char **argv, char **envp) {
flush_all();
trap_reset_child();
COVERAGE_FLUSH();
execve(path, argv, envp);
if (errno == ENOEXEC) {
char **nv = script_argv(path, argv);
if (nv)
execve(nv[0], nv, envp);
}
int status = exec_error(argv[0], errno);
flush_all();
_exit(status);
}
/**
* @brief The `exec` builtin with a command: find it and replace the shell.
*/
void shell_exec(char **argv, char **envp) {
cmdinfo ci;
find_command(argv[0], &ci, FC_NOFUNC);
const char *path = ci.kind == C_EXTERNAL ? ci.path : nullptr;
if (!path && !strchr(argv[0], '/')) {
const char *search = var_get("PATH");
path = path_search(argv[0], search ? search : default_path, true);
}
if (!path) {
int status = exec_error(argv[0], ENOENT);
flush_all();
_exit(status);
}
exec_path(path, argv, envp);
}
/**
* @brief spawn() a program.
*
* On failure the message goes where the command's own stderr would have
* gone, so `cmd 2>/dev/null` silences it.
*
* @param path Program file.
* @param argv Arguments.
* @param envp Environment.
* @param plan The child's descriptors.
* @param status Receives the exit status to report if the spawn fails.
* @return The child's pid, or -1.
*/
static pid_t spawn_command(const char *path, char **argv, char **envp,
const fdplan *plan, int *status) {
spawn_req rq = {
.path = path,
.argv = argv,
.envp = envp,
.fdmap = plan->map,
.open_mask = fd_open_mask,
.sigdfl = trap_spawn_defaults(),
.pgroup = job_launch_pgid(),
.tty_fd = job_launching ? job_tty() : -1,
};
flush_all();
pid_t pid = sys_spawn(&rq);
if (pid < 0 && errno == ENOEXEC) {
char **nv = script_argv(path, argv);
if (nv) {
rq.path = nv[0];
rq.argv = nv;
pid = sys_spawn(&rq);
}
}
if (pid < 0) {
/* Report it where the command's own stderr would have gone. */
int err = errno;
int saved = out2.fd;
out_flush(&out2);
if (plan->map[2] != FD_CLOSED)
out2.fd = plan->map[2];
*status = exec_error(argv[0], err);
out_flush(&out2);
out2.fd = saved;
return -1;
}
stat_spawns++;
if (job_launching)
job_add_proc(job_launching, pid);
return pid;
}
/* ---- simple commands ------------------------------------------------- */
/**
* @brief A simple command that has been expanded and looked up.
*/
typedef struct simple_cmd {
node *n;
int argc;
char **argv;
cmdinfo cmd;
bool via_command; /**< reached through the `command` builtin */
char **atext; /**< the expanded "name=value" of each assignment */
int nassign;
} simple_cmd;
/**
* @brief Print a command for `set -x`.
*/
static void xtrace(const simple_cmd *sc) {
const char *ps4 = var_get("PS4");
out_puts(&out2, ps4 ? ps4 : "+ ");
for (int i = 0; i < sc->argc; i++) {
if (i)
out_putc(&out2, ' ');
out_quote(&out2, sc->argv[i]);
}
out_putc(&out2, '\n');
out_flush(&out2);
}
/**
* @brief Expand a simple command's words and find out what it names.
*
* The words are expanded first and the assignments after them (the POSIX
* order). `command name ...` is resolved here to the command it names.
*
* @param n The N_SIMPLE node.
* @param sc Receives the prepared command.
*/
static void simple_prep(node *n, simple_cmd *sc) {
sc->n = n;
sc->via_command = false;
sc->cmd = (cmdinfo){0};
cmdsub_ran = false;
cur_lineno = n->lineno;
sc->atext = nullptr;
sc->nassign = 0;
sc->argv = expand_words(n->u.simple.args, &sc->argc);
if (!sc->argc)
return;
path_override = nullptr;
if (n->u.simple.assigns) {
/* Expanded once, here, after the words (POSIX order). */
for (const word *w = n->u.simple.assigns; w; w = w->next)
sc->nassign++;
sc->atext =
arena_alloc(&scratch, (size_t)sc->nassign * sizeof *sc->atext);
int k = 0;
for (const word *w = n->u.simple.assigns; w; w = w->next) {
sc->atext[k] = expand_assign(w);
if (w->assign_len == 4 && !memcmp(sc->atext[k], "PATH", 4))
path_override = sc->atext[k] + 5;
k++;
}
}
if (opt.xtrace)
xtrace(sc);
unsigned flags = 0;
for (;;) {
find_command(sc->argv[0], &sc->cmd, flags);
if (sc->cmd.kind != C_BUILTIN || sc->cmd.bi->fn != builtin_command) {
path_override = nullptr;
return;
}
/* "command [-p] name ...": look `name` up afresh, minus functions. */
int i = 1;
bool defpath = false;
if (i < sc->argc && !strcmp(sc->argv[i], "-p")) {
defpath = true;
i++;
}
if (i < sc->argc && !strcmp(sc->argv[i], "--"))
i++;
if (i >= sc->argc || sc->argv[i][0] == '-') {
path_override = nullptr;
return; /* -v, -V or nothing: the builtin handles it */
}
sc->argv += i;
sc->argc -= i;
sc->via_command = true;
flags = FC_NOFUNC | (defpath ? FC_DEFPATH : 0);
}
}
/**
* @brief simple_prep() on behalf of a child: an expansion error is the child's
* failure, not the shell's.
* @return false if expansion failed. `$?` holds the status.
*/
static bool guarded_prep(node *n, simple_cmd *sc) {
jmploc jl;
jmploc *prev = exc_handler;
unwind u;
bool ok = true;
unwind_save(&u);
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
simple_prep(n, sc);
} else {
unwind_restore(&u);
ok = false;
}
exc_handler = prev;
return ok;
}
/**
* @brief Perform one expanded `name=value` assignment.
*/
static void assign_text(const char *text, unsigned flags) {
size_t nlen = (size_t)(strchr(text, '=') - text);
var_set_n(text, nlen, text + nlen + 1, flags);
}
/**
* @brief Perform assignments that stand alone, each seeing the ones before it.
*/
static void assign_words(const word *assigns) {
for (const word *w = assigns; w; w = w->next)
assign_text(expand_assign(w), 0);
}
/**
* @brief Perform a prepared command's assignments permanently (special
* builtins).
*/
static void assign_all(const simple_cmd *sc) {
for (int i = 0; i < sc->nassign; i++)
assign_text(sc->atext[i], 0);
}
/**
* @brief Perform a prepared command's assignments for the current scope only,
* exported, as for `X=1 builtin` and `X=1 function`.
*/
static void assign_temp(const simple_cmd *sc) {
for (int i = 0; i < sc->nassign; i++) {
const char *text = sc->atext[i];
size_t nlen = (size_t)(strchr(text, '=') - text);
var_save(var_find(text, nlen, true), var_scope);
var_set_n(text, nlen, text + nlen + 1, V_EXPORT);
}
}
/**
* @brief Apply `_TAG_REDIR_*` assignments given on an external command.
*
* Assignments before an external command go only into its environment,
* never into the shell's variables, so the hooks that keep #tag_redir
* current do not see `_TAG_REDIR_OUT=TXT cmd >f`. This sets #tag_redir
* from them for the duration of the redirections, and applies them to
* the pipe ends the command gets in a pipeline, as /bin/sh does.
*
* @param sc The command.
* @param saved Receives #tag_redir as it was.
* @return true if anything changed (call tag_prefix_end()).
*/
static bool tag_prefix_begin(const simple_cmd *sc, tag_mode saved[3]) {
static const char *const name[3] = {
"_TAG_REDIR_IN=",
"_TAG_REDIR_OUT=",
"_TAG_REDIR_ERR=",
};
bool any = false;
memcpy(saved, tag_redir, sizeof tag_redir);
for (int i = 0; i < sc->nassign; i++) {
const char *a = sc->atext[i];
if (strncmp(a, "_TAG_REDIR_", 11))
continue;
for (int k = 0; k < 3; k++) {
size_t n = strlen(name[k]);
if (!strncmp(a, name[k], n)) {
tag_redir[k] = tag_value(a + n);
any = true;
}
}
}
return any;
}
/**
* @brief Tag the pipe ends of a pipeline stage per its prefix, then put
* #tag_redir back.
*/
static void tag_prefix_end(const tag_mode saved[3], int in, int out) {
if (out >= 0 && tag_redir[TAG_OUT] != saved[TAG_OUT])
sys_redir_tag(out, TAG_OUT, tag_redir[TAG_OUT], true);
if (in >= 0 && tag_redir[TAG_IN] != saved[TAG_IN])
sys_redir_tag(in, TAG_IN, tag_redir[TAG_IN], false);
memcpy(tag_redir, saved, sizeof tag_redir);
}
/**
* @brief Run an external command.
*
* @param sc The prepared command.
* @param flags EV_EXIT allows replacing the shell with exec.
* @param in Descriptor for its stdin, or -1.
* @param out Descriptor for its stdout, or -1.
* @param async When not nullptr, receives the pid and the command is not
* waited for (pipeline stages, `&`, command substitution).
* @return The exit status. 0 for an async launch.
*/
static int run_external(simple_cmd *sc, unsigned flags, int in, int out,
pid_t *async) {
const node *n = sc->n;
char **envp =
sc->nassign ? var_environ_with(sc->atext, sc->nassign) : var_environ();
if (opt.jobnames || opt.shareas)
envp = zos_environ(envp, sc->argv[0], !async && in < 0 && out < 0);
fdplan plan;
plan_init(&plan, in, out);
tag_mode saved_tags[3];
bool tags = SYS_MVS && sc->nassign && tag_prefix_begin(sc, saved_tags);
bool planned = plan_redirs(&plan, n->redirs);
if (tags)
tag_prefix_end(saved_tags, in, out);
if (!planned) {
plan_close(&plan);
return 2;
}
if ((flags & EV_EXIT) && !async && !trap_has_exit()) {
/* Nothing comes after this command: become it. */
plan_apply(&plan);
exec_path(sc->cmd.path, sc->argv, envp);
}
/* Under job control a foreground command is a job of its own. */
job *jb =
!async && jc_active() && !job_launching ? job_begin(n, true) : nullptr;
int status = 0;
pid_t pid = spawn_command(sc->cmd.path, sc->argv, envp, &plan, &status);
plan_close(&plan);
if (pid < 0) {
if (jb)
job_release(jb);
return status;
}
if (async) {
*async = pid;
return 0;
}
if (jb) {
status = job_wait_fg(jb);
job_release(jb);
return status;
}
return wait_fg(pid);
}
/**
* @brief Flush a builtin's output and turn a write error into a failure.
*/
static int finish_builtin(int status) {
out_flush(&out1);
if (out1.err) {
if (out1.err != EPIPE)
sh_warn("write error: %s", strerror(out1.err));
out1.err = 0;
if (!status)
status = 1;
}
return status;
}
/**
* @brief Run a special builtin reached through `command`.
*
* `command` takes away the special properties, and one of them is that
* an error in a special builtin exits a non-interactive shell. So an
* error raised inside it (a syntax error in `command eval`, a missing
* file or syntax error in `command .`, an arithmetic error) is caught
* here and becomes the builtin's status, as in dash, bash and ksh93.
* `exit` still exits. Only this rare path pays for the setjmp().
*
* @param bi The builtin.
* @param sc The command.
* @return Its status, or that of the error.
*/
static int run_special_guarded(const builtin *bi, simple_cmd *sc) {
jmploc jl;
jmploc *prev = exc_handler;
unwind u;
unwind_save(&u);
arena_marker mark = arena_mark(&scratch);
int saved_loop = loop_depth;
int saved_dot = dot_depth;
int saved_func = func_depth;
if (setjmp(jl.buf)) {
exc_handler = prev;
if (exc_code == EXC_EXIT)
exc_raise(EXC_EXIT);
unwind_restore(&u);
arena_release(&scratch, mark);
loop_depth = saved_loop;
dot_depth = saved_dot;
func_depth = saved_func;
skip_kind = SKIP_NONE;
return exitstatus ? exitstatus : 2;
}
exc_handler = &jl;
int status = bi->fn(sc->argc, sc->argv);
exc_handler = prev;
return status;
}
/**
* @brief Run a builtin with its assignments and redirections.
*
* Assignments before a special builtin persist. Before a regular builtin
* they last only for the call.
*/
static int run_builtin(simple_cmd *sc) {
const node *n = sc->n;
const builtin *bi = sc->cmd.bi;
bool special = (bi->flags & BI_SPECIAL) && !sc->via_command;
bool scoped = !special && n->u.simple.assigns;
varscope vs;
redirsave rs;
int status;
if (scoped) {
scope_push(&vs, false, false);
assign_temp(sc);
} else {
assign_all(sc);
}
if (n->redirs && !redir_push(n->redirs, &rs)) {
if (special) { /* POSIX: a failed redirection here is fatal */
exitstatus = 2;
exc_raise(EXC_ERROR);
}
status = 2;
} else {
status = finish_builtin(sc->via_command && (bi->flags & BI_SPECIAL)
? run_special_guarded(bi, sc)
: bi->fn(sc->argc, sc->argv));
if (n->redirs)
redir_pop(bi->fn == builtin_exec);
}
if (scoped)
scope_pop();
return status;
}
/**
* @brief Call a shell function.
* @param fn The function.
* @param argc Argument count, including the name.
* @param argv Arguments. Argv[0] is the name.
* @param flags EV_TESTED if the status is being tested.
* @return The function's exit status.
*/
int call_function(func *fn, int argc, char **argv, unsigned flags) {
if (stack_low())
sh_error("%s: functions nested too deeply", argv[0]);
shparam saved_param = shellparam;
int saved_loop = loop_depth;
jmploc jl;
jmploc *prev = exc_handler;
bool raised = false;
fn->refs++;
func_depth++;
loop_depth = 0;
shellparam = (shparam){argc - 1, argv + 1, nullptr};
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
eval_node(fn->body, flags & EV_TESTED);
} else {
raised = true;
}
exc_handler = prev;
params_free(&shellparam);
shellparam = saved_param;
loop_depth = saved_loop;
func_depth--;
func_unref(fn);
if (raised)
exc_raise(exc_code);
if (skip_kind == SKIP_RETURN)
skip_kind = SKIP_NONE;
return exitstatus;
}
/**
* @brief Run a function with its temporary assignments and redirections.
*/
static int run_function(simple_cmd *sc, unsigned flags) {
const node *n = sc->n;
varscope vs;
redirsave rs;
int status = 2;
scope_push(&vs, false, true);
assign_temp(sc);
if (!n->redirs || redir_push(n->redirs, &rs)) {
status = call_function(sc->cmd.fn, sc->argc, sc->argv, flags);
if (n->redirs)
redir_pop(false);
}
scope_pop();
return status;
}
/**
* @brief Run a command that has no command word: assignments and redirections
* only.
* @return The status of the last command substitution, else 0.
*/
static int run_assignments(simple_cmd *sc) {
const node *n = sc->n;
redirsave rs;
if (n->redirs) { /* "> file" alone still creates the file */
if (!redir_push(n->redirs, &rs))
return 2;
redir_pop(false);
}
assign_words(n->u.simple.assigns);
return cmdsub_ran ? cmdsub_status : 0;
}
/**
* @brief Run a prepared simple command, whatever it turned out to be.
*/
static int simple_run(simple_cmd *sc, unsigned flags) {
if (!sc->argc)
return run_assignments(sc);
switch (sc->cmd.kind) {
case C_BUILTIN:
return run_builtin(sc);
case C_FUNC:
return run_function(sc, flags);
case C_EXTERNAL:
return run_external(sc, flags, -1, -1, nullptr);
case C_NOTFOUND: {
/* The message belongs on the command's stderr, not ours. */
redirsave rs;
if (sc->n->redirs && !redir_push(sc->n->redirs, &rs))
return 2;
sh_warn("%s: not found", sc->argv[0]);
if (sc->n->redirs)
redir_pop(false);
return 127;
}
}
UNREACHABLE();
}
/**
* @brief Run a prepared simple command as the rest of a forked child's life.
*/
[[noreturn]] static void child_simple(simple_cmd *sc) {
jmploc jl;
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
exitstatus = simple_run(sc, EV_EXIT);
}
exit_shell(exitstatus);
}
/**
* @brief Can this command stand in for a subshell without a process?
*
* Only a builtin that does nothing but write to out1/out2, with no
* redirections or assignments of its own.
*/
static bool is_pure(const simple_cmd *sc) {
return sc->argc && sc->cmd.kind == C_BUILTIN &&
(sc->cmd.bi->flags & BI_PURE) && !sc->n->redirs &&
!sc->n->u.simple.assigns;
}
/**
* @brief Run a pure builtin with its standard output going to `o`.
* @return Its exit status.
*/
static int run_pure(simple_cmd *sc, output *o) {
output saved = out1;
jmploc jl;
jmploc *prev = exc_handler;
unwind u;
int status;
unwind_save(&u);
out1 = *o;
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
status = sc->cmd.bi->fn(sc->argc, sc->argv);
} else {
unwind_restore(&u);
status = exitstatus ? exitstatus : 2;
}
exc_handler = prev;
out_flush(&out1);
*o = out1;
out1 = saved;
return status;
}
/**
* @brief Can a subshell run without a process of its own?
*
* Its body has to be one command whose name is written literally, that
* name has to be a builtin which only writes output, and neither the
* subshell nor the command may redirect or assign. Then nothing the
* parent can see can change. A `fork()` copies the address space on
* z/OS, 4.7 ms against 0.3 ms for a `spawn()`, and ksh88 does not pay it
* for `( : )` either.
*/
static bool subshell_in_process(const node *n) {
const node *b = n->u.body;
if (n->redirs || !b || b->kind != N_SIMPLE || b->redirs ||
b->u.simple.assigns || !b->u.simple.args || !b->u.simple.args->plain)
return false;
cmdinfo ci;
find_command(b->u.simple.args->plain, &ci, 0);
return ci.kind == C_BUILTIN && (ci.bi->flags & BI_PURE);
}
/* ---- pipelines ------------------------------------------------------- */
/**
* @brief One command of a pipeline.
*/
typedef struct stage {
int in; /**< read end feeding this stage, or -1 */
int out; /**< write end this stage feeds, or -1 */
pid_t pid;
int status;
bool deferred; /**< a pure builtin to run in the shell */
simple_cmd sc;
} stage;
/**
* @brief Close the pipe ends a stage still holds.
*/
static void close_stage(stage *s) {
if (s->in >= 0)
close(s->in);
if (s->out >= 0)
close(s->out);
s->in = s->out = -1;
}
/**
* @brief Start one stage of a pipeline.
*
* An external command is spawned with the pipe ends in its fd plan. A
* pure builtin is deferred, to run in the shell once its reader exists.
* Anything else needs a copy of the shell and is forked.
*
* @param st The stages.
* @param nc Number of stages (for closing pipes in a forked child).
* @param i Which stage.
* @param c Its command.
*/
static void launch_stage(stage *st, int nc, int i, node *c) {
stage *s = &st[i];
bool prepped = false;
if (c->kind == N_SIMPLE) {
if (!guarded_prep(c, &s->sc)) {
s->status = exitstatus;
close_stage(s);
return;
}
prepped = true;
if (s->sc.argc && s->sc.cmd.kind == C_EXTERNAL) {
s->status = run_external(&s->sc, 0, s->in, s->out, &s->pid);
close_stage(s);
return;
}
if (is_pure(&s->sc) && s->out >= 0) {
s->deferred = true; /* run once its reader exists */
return;
}
if (s->sc.argc && s->sc.cmd.kind == C_NOTFOUND) {
s->status = simple_run(&s->sc, 0); /* only complains */
close_stage(s);
return;
}
}
pid_t pid = fork_shell();
if (pid == 0) {
if (s->in >= 0)
dup2(s->in, 0);
if (s->out >= 0)
dup2(s->out, 1);
for (int j = 0; j < nc; j++)
close_stage(&st[j]);
if (prepped)
child_simple(&s->sc);
child_eval(c);
}
s->pid = pid;
close_stage(s);
}
/**
* @brief Run a deferred pure builtin, sending its output down the pipe.
*
* If the reader is already a process, the builtin writes straight into
* the pipe. If the reader is this shell (the last stage, or another
* deferred stage) nobody would drain the pipe while we write, so the
* output is collected in memory first: up to PIPE_BUF bytes are certain
* to fit in an empty pipe and cost no process at all. Anything larger is
* handed to a forked writer.
*
* @param st The stages.
* @param nc Number of stages.
* @param i Which stage.
* @param stream false when the far end of the whole pipeline is the shell
* (command substitution): then even a writer with a live
* reader could fill every pipe in the chain and block.
*/
static void run_deferred(stage *st, int nc, int i, bool stream) {
stage *s = &st[i];
if (stream && st[i + 1].pid > 0) {
char buf[1024];
output o = {buf, 0, sizeof buf, s->out, 0};
s->status = run_pure(&s->sc, &o);
close_stage(s);
return;
}
output o = {.fd = OUT_MEM};
s->status = run_pure(&s->sc, &o);
if (o.len <= PIPE_BUF) {
output direct = {o.buf, o.len, o.len, s->out, 0};
out_flush(&direct);
} else {
pid_t pid = fork_shell();
if (pid == 0) {
int out = s->out;
s->out = -1;
for (int j = 0; j < nc; j++)
close_stage(&st[j]); /* or we would never see EPIPE */
signal(SIGPIPE, SIG_DFL);
output direct = {o.buf, o.len, o.len, out, 0};
out_flush(&direct);
_exit(0);
}
s->pid = -pid; /* reap it, but keep the builtin's own status */
}
free(o.buf);
close_stage(s);
}
static void read_all(int fd, strbuf *sb);
/**
* @brief Close what is left of a pipeline, reap every child, and work out the
* status.
* @param st The stages.
* @param nc Number of commands.
* @param total Number of stage slots (one more when capturing).
* @param jb The job, under job control. Else nullptr.
* @return Status of the last command, or with `pipefail` of the last one
* that failed.
*/
static int pipe_finish(stage *st, int nc, int total, job *jb) {
for (int i = 0; i < total; i++)
close_stage(&st[i]);
if (jb) {
/* Job control: the job is waited for (and may stop) as a unit. */
job_wait_fg(jb);
for (int i = 0; i < nc; i++) {
if (st[i].pid > 0)
st[i].status = job_status_of(jb, st[i].pid);
}
job_release(jb);
} else {
for (int i = 0; i < nc; i++) {
if (st[i].pid > 0)
st[i].status = wait_fg(st[i].pid);
else if (st[i].pid < 0)
wait_fg(-st[i].pid);
}
}
int status = st[nc - 1].status;
if (opt.pipefail && !status) {
for (int i = 0; i < nc; i++) {
if (st[i].status)
status = st[i].status;
}
}
return status;
}
/**
* @brief Run a pipeline.
*
* Normally the last stage runs in this shell unless it is an external
* command. With `cap`, the pipeline is the body of a command
* substitution: every stage is launched as a child, the last one writing
* to a pipe that is collected into `cap`, so `$(grep x f | cut -f1)`
* costs two spawns and no fork.
*
* @param n The N_PIPE node.
* @param flags Evaluation flags.
* @param cap Where to collect the output, or nullptr.
* @return The pipeline's exit status.
*/
static int eval_pipe(node *n, unsigned flags, strbuf *cap) {
int nc = n->u.pipe.n;
int total = cap ? nc + 1 : nc; /* slot nc holds the capture pipe */
node **cmds = n->u.pipe.cmds;
stage *st = arena_alloc(&scratch, (size_t)total * sizeof *st);
stage *last = &st[nc - 1];
node *lc = cmds[nc - 1];
for (int i = 0; i < total; i++)
st[i] = (stage){.in = -1, .out = -1};
for (int i = 0; i < total - 1; i++) {
int p[2];
if (sys_pipe(p) < 0) {
int err = errno;
for (int j = 0; j < total; j++)
close_stage(&st[j]);
sh_error("cannot create pipe: %s", strerror(err));
}
st[i].out = p[1];
st[i + 1].in = p[0];
}
/*
* Whatever preparing the earlier stages does to shell variables must
* not outlive them: they are, notionally, subshells.
*/
/*
* Under job control the pipeline is one job in one process group, and
* every stage is a process, the last included: a stage running inside
* the shell could not be stopped with the rest of the job.
*/
job *jb = !cap && jc_active() && !job_launching ? job_begin(n, true) : nullptr;
varscope vs;
scope_push(&vs, true, false);
bool any_deferred = false;
int nlaunch = cap || jb ? nc : nc - 1;
for (int i = 0; i < nlaunch; i++) {
launch_stage(st, total, i, cmds[i]);
any_deferred |= st[i].deferred;
}
scope_pop();
if (cap || jb) {
if (any_deferred) {
struct sigaction ignore = {.sa_handler = SIG_IGN};
struct sigaction old;
sigaction(SIGPIPE, &ignore, &old);
for (int i = nc - 1; i >= 0; i--) {
if (st[i].deferred)
run_deferred(st, total, i, !cap);
}
sigaction(SIGPIPE, &old, nullptr);
}
if (cap)
read_all(st[nc].in, cap);
return pipe_finish(st, nc, total, jb);
}
/*
* The last stage runs in this shell unless it is an external command.
* An error from here on must not strand the pipes or the children.
*/
jmploc jl;
jmploc *prev = exc_handler;
unwind u;
volatile bool raised = false;
unwind_save(&u);
if (setjmp(jl.buf) == 0) {
exc_handler = &jl;
bool last_started = false;
if (lc->kind == N_SIMPLE) {
simple_prep(lc, &last->sc);
if (last->sc.argc && last->sc.cmd.kind == C_EXTERNAL) {
/* Start the reader before any in-shell writer runs. */
last->status =
run_external(&last->sc, 0, last->in, -1, &last->pid);
close_stage(last);
last_started = true;
}
}
if (any_deferred) {
/* A reader that has gone away must not kill the shell. */
struct sigaction ignore = {.sa_handler = SIG_IGN};
struct sigaction old;
sigaction(SIGPIPE, &ignore, &old);
for (int i = nc - 2; i >= 0; i--) {
if (st[i].deferred)
run_deferred(st, nc, i, true);
}
sigaction(SIGPIPE, &old, nullptr);
}
if (!last_started) {
redirsave rs;
redir_push_fd(&rs, 0, last->in);
last->in = -1;
if (lc->kind == N_SIMPLE)
last->status = simple_run(&last->sc, flags & EV_TESTED);
else
last->status = eval_node(lc, flags & EV_TESTED);
redir_pop(false);
}
} else {
unwind_restore(&u);
raised = true;
}
exc_handler = prev;
if (raised) {
pipe_finish(st, nc, total, nullptr);
exc_raise(exc_code);
}
return pipe_finish(st, nc, total, nullptr);
}
/* ---- background commands --------------------------------------------- */
/**
* @brief Run a command in the background (`command &`).
*
* An external command is spawned. Anything else is forked. Without job
* control the child ignores SIGINT and SIGQUIT and reads /dev/null.
*/
static int eval_background(node *body) {
simple_cmd sc;
bool prepped = false;
pid_t pid = 0;
struct sigaction ignore = {.sa_handler = SIG_IGN};
varscope vs;
scope_push(&vs, true, false);
if (body->kind == N_SIMPLE) {
if (!guarded_prep(body, &sc)) {
scope_pop();
return exitstatus;
}
prepped = true;
}
/*
* With job control the command gets a process group of its own and
* keeps its stdin and signal settings: it is the group, not ignored
* signals, that protects it from the keyboard.
*/
job *jb = jc_active() ? job_begin(body, false) : nullptr;
if (prepped && sc.argc && sc.cmd.kind == C_EXTERNAL) {
if (jb) {
run_external(&sc, 0, -1, -1, &pid);
} else {
/* The child inherits "ignored", which spawn cannot set. */
struct sigaction old_int;
struct sigaction old_quit;
int null = sys_open("/dev/null", O_RDONLY, 0);
sigaction(SIGINT, &ignore, &old_int);
sigaction(SIGQUIT, &ignore, &old_quit);
run_external(&sc, 0, null, -1, &pid);
sigaction(SIGINT, &old_int, nullptr);
sigaction(SIGQUIT, &old_quit, nullptr);
if (null >= 0)
close(null);
}
scope_pop();
if (jb)
job_end_bg(jb);
else if (pid > 0)
jobs_add(pid, body);
return 0;
}
pid = fork_shell();
if (pid == 0) {
if (!jb) {
sigaction(SIGINT, &ignore, nullptr);
sigaction(SIGQUIT, &ignore, nullptr);
int null = open("/dev/null", O_RDONLY);
if (null >= 0) {
dup2(null, 0);
close(null);
}
}
if (prepped)
child_simple(&sc);
child_eval(body);
}
scope_pop();
if (jb)
job_end_bg(jb);
else
jobs_add(pid, body);
return 0;
}
/* ---- command substitution -------------------------------------------- */
/**
* @brief Read a descriptor to end of file into a string builder.
*/
static void read_all(int fd, strbuf *sb) {
for (;;) {
sb_reserve(sb, 4096);
ssize_t n = read(fd, sb->s + sb->len, 4096);
if (n < 0 && errno == EINTR)
continue;
if (n <= 0)
return;
sb->len += (size_t)n;
}
}
/**
* @brief Run a command substitution in a forked subshell (the general case).
* @param n The command.
* @param sc Its prepared form if it is a simple command, else nullptr.
* @param sb Receives the output.
* @return The exit status.
*/
static int cmdsub_fork(node *n, simple_cmd *sc, strbuf *sb) {
int p[2];
if (sys_pipe(p) < 0)
sh_error("cannot create pipe: %s", strerror(errno));
pid_t pid = fork_shell();
if (pid == 0) {
dup2(p[1], 1);
close(p[0]);
close(p[1]);
if (sc)
child_simple(sc);
child_eval(n);
}
close(p[1]);
read_all(p[0], sb);
close(p[0]);
return wait_fg(pid);
}
/**
* @brief Pick the cheapest way to run a command substitution and collect its
* output.
*
* `$(<file)` is read directly. A pure builtin runs in the shell. An
* external command is spawned. A pipeline spawns its stages. Only the
* rest forks.
*/
static int cmdsub_collect(node *n, strbuf *sb) {
if (n->kind == N_PIPE)
return eval_pipe(n, 0, sb);
if (n->kind != N_SIMPLE)
return cmdsub_fork(n, nullptr, sb);
const redir *r = n->redirs;
if (!n->u.simple.args && !n->u.simple.assigns && r && !r->next &&
r->op == R_IN) {
/* $(<file): read the file ourselves. */
const char *path = expand_string(r->target->parts, XS_TILDE);
int fd = sys_open(path, O_RDONLY, 0);
if (fd < 0) {
sh_warn("cannot open %s: %s", path, strerror(errno));
return 1;
}
read_all(fd, sb);
close(fd);
return 0;
}
simple_cmd sc;
if (!guarded_prep(n, &sc))
return exitstatus;
if (sc.argc && sc.cmd.kind == C_EXTERNAL) {
int p[2];
pid_t pid = 0;
if (sys_pipe(p) < 0)
sh_error("cannot create pipe: %s", strerror(errno));
int status = run_external(&sc, 0, -1, p[1], &pid);
close(p[1]);
if (pid > 0) {
read_all(p[0], sb);
status = wait_fg(pid);
}
close(p[0]);
return status;
}
if (is_pure(&sc)) {
output o = {.fd = OUT_MEM};
int status = run_pure(&sc, &o);
sb_put(sb, o.buf, o.len);
free(o.buf);
return status;
}
if (sc.argc && sc.cmd.kind == C_NOTFOUND)
return simple_run(&sc, 0); /* only complains: no process needed */
return cmdsub_fork(n, &sc, sb);
}
/**
* @brief Run a command substitution.
* @param n The command, or nullptr for an empty `$()`.
* @param lenp Receives the length of the output.
* @return The output with trailing newlines removed, in scratch memory.
*/
char *cmdsub_run(node *n, size_t *lenp) {
strbuf sb;
sb_init(&sb, &scratch);
int status = 0;
if (n) {
/* Its processes are the shell's own, never part of a job that
* happens to be half launched (a pipeline stage's arguments). */
job *launching = job_launching;
varscope vs;
job_launching = nullptr;
scope_push(&vs, true, false);
status = cmdsub_collect(n, &sb);
scope_pop();
job_launching = launching;
}
while (sb.len && sb.s[sb.len - 1] == '\n')
sb.len--;
exitstatus = status;
cmdsub_ran = true;
cmdsub_status = status;
*lenp = sb.len;
return sb_cstr(&sb);
}
/* ---- compound commands ----------------------------------------------- */
/**
* @brief After a loop body: must the loop stop?
*
* A `continue` for this loop is absorbed and the loop carries on.
*/
static bool loop_should_stop(void) {
if (skip_kind == SKIP_NONE)
return false;
if (skip_kind == SKIP_RETURN)
return true;
if (--skip_count > 0)
return true; /* aimed at an enclosing loop */
bool is_break = skip_kind == SKIP_BREAK;
skip_kind = SKIP_NONE;
return is_break;
}
/**
* @brief Run a `while` or `until` loop.
*/
static int eval_loop(node *n, unsigned flags) {
int status = 0;
loop_depth++;
for (;;) {
int test = eval_node(n->u.loop.cond, EV_TESTED);
if (skip_kind != SKIP_NONE) {
if (loop_should_stop())
break;
continue;
}
if ((test == 0) != (n->kind == N_WHILE))
break;
status = eval_node(n->u.loop.body, flags & EV_TESTED);
if (loop_should_stop())
break;
}
loop_depth--;
return status;
}
/**
* @brief Run a `for` loop.
*/
static int eval_for(node *n, unsigned flags) {
int count;
char **words;
if (n->u.for_.has_in) {
words = expand_words(n->u.for_.words, &count);
} else {
count = shellparam.n;
words = arena_alloc(&scratch, ((size_t)count + 1) * sizeof *words);
memcpy(words, shellparam.p, (size_t)count * sizeof *words);
}
int status = 0;
loop_depth++;
for (int i = 0; i < count; i++) {
var_set(n->u.for_.var, words[i], 0);
status = eval_node(n->u.for_.body, flags & EV_TESTED);
if (loop_should_stop())
break;
}
loop_depth--;
return status;
}
/**
* @brief Run a `case` command.
*/
static int eval_case(node *n, unsigned flags) {
const char *subject = expand_string(n->u.case_.subject->parts, XS_TILDE);
const char *end = subject + strlen(subject);
for (caseitem *it = n->u.case_.items; it; it = it->next) {
for (const word *w = it->patterns; w; w = w->next) {
if (pat_match(expand_pattern(w->parts), subject, end))
return it->body ? eval_node(it->body, flags) : 0;
}
}
return 0;
}
/**
* @brief Run `( list )` in a forked copy of the shell, or in this process if
* the shell was about to exit anyway.
*/
static int eval_subshell(node *n, unsigned flags) {
if (!(flags & EV_EXIT) || trap_has_exit()) {
if (!job_launching && !opt.errexit && subshell_in_process(n)) {
simple_cmd sc;
varscope vs;
/* Expansion may assign (${x=1}), so undo it on the way out. */
scope_push(&vs, true, false);
bool ok = guarded_prep(n->u.body, &sc);
if (ok && is_pure(&sc)) {
int status = run_pure(&sc, &out1);
scope_pop();
return status;
}
scope_pop();
if (!ok)
return exitstatus;
}
job *jb = jc_active() && !job_launching ? job_begin(n, true) : nullptr;
pid_t pid = fork_shell();
if (pid) {
if (!jb)
return wait_fg(pid);
int status = job_wait_fg(jb);
job_release(jb);
return status;
}
} else {
trap_reset_child(); /* already the last thing this shell does */
in_subshell = true;
}
/* `( false; echo x ) || y`: errexit is ignored inside, too. */
if (flags & EV_TESTED)
opt.errexit = false;
redirsave rs;
if (n->redirs && !redir_push(n->redirs, &rs))
exit_shell(1);
child_eval(n->u.body);
}
/**
* @brief Evaluate a command tree.
*
* Scratch memory used by the command is released when it finishes. After
* a failing command the ERR trap and `errexit` are applied, and pending
* trap actions run.
*
* @param n The command, or nullptr for an empty one.
* @param flags EV_EXIT if nothing follows the command, EV_TESTED if its
* status is being tested.
* @return The exit status, also left in `$?`.
*/
int eval_node(node *n, unsigned flags) {
if (!n)
return exitstatus = 0;
if (opt.noexec && !opt.interactive)
return exitstatus;
arena_marker mark = arena_mark(&scratch);
redirsave rs;
bool redirected = false;
bool leaf = false; /* a command whose failure triggers errexit */
int status = 0;
if (n->redirs && n->kind != N_SIMPLE && n->kind != N_SUBSHELL) {
if (!redir_push(n->redirs, &rs)) {
arena_release(&scratch, mark);
return exitstatus = 2;
}
redirected = true;
flags &= ~EV_EXIT;
}
switch (n->kind) {
case N_SIMPLE: {
simple_cmd sc;
simple_prep(n, &sc);
status = simple_run(&sc, flags);
leaf = true;
break;
}
case N_PIPE:
status = eval_pipe(n, flags, nullptr);
leaf = true;
break;
case N_SUBSHELL:
status = eval_subshell(n, flags);
leaf = true;
break;
case N_SEQ:
/* Walk the right-leaning chain without recursing on it. */
for (;;) {
eval_node(n->u.bin.left, flags & EV_TESTED);
status = exitstatus;
if (skip_kind != SKIP_NONE)
break;
n = n->u.bin.right;
if (n->kind != N_SEQ) {
status = eval_node(n, flags);
break;
}
}
break;
case N_AND:
case N_OR:
status = eval_node(n->u.bin.left, EV_TESTED);
if (skip_kind == SKIP_NONE && (status == 0) == (n->kind == N_AND))
status = eval_node(n->u.bin.right, flags);
break;
case N_NOT:
status = !eval_node(n->u.body, EV_TESTED);
break;
case N_TIME:
status = eval_time(n, flags);
break;
case N_BG:
status = eval_background(n->u.body);
break;
case N_GROUP:
status = eval_node(n->u.body, flags);
break;
case N_IF:
if (eval_node(n->u.if_.cond, EV_TESTED) == 0 && skip_kind == SKIP_NONE)
status = eval_node(n->u.if_.then_part, flags);
else if (skip_kind == SKIP_NONE)
status = eval_node(n->u.if_.else_part, flags);
break;
case N_WHILE:
case N_UNTIL:
status = eval_loop(n, flags);
break;
case N_FOR:
status = eval_for(n, flags);
break;
case N_CASE:
status = eval_case(n, flags);
break;
case N_FUNC:
func_define(n->u.func.name, n->u.func.body, n->u.func.arena);
break;
case N_COND:
cur_lineno = n->lineno;
if (opt.xtrace) {
char *text = node_text(n);
out_printf(&out2, "%s%s\n", var_get("PS4") ? var_get("PS4") : "+ ",
text);
out_flush(&out2);
free(text);
}
status = eval_cond(n->u.cond);
leaf = true;
break;
case N_ARITH:
/* (( expr )): true when the value is not zero. */
cur_lineno = n->lineno;
status = !strcmp(expand_string(n->u.arith, 0), "0");
leaf = true;
break;
}
if (redirected)
redir_pop(false);
arena_release(&scratch, mark);
exitstatus = status;
if (leaf && status && !(flags & EV_TESTED) && skip_kind == SKIP_NONE) {
/* Only reached when a command has failed: the ERR trap and
* errexit cost a successful command nothing. */
if (trap_err_set)
trap_run_err();
if (opt.errexit)
exc_raise(EXC_EXIT);
}
if (trap_pending)
trap_poll();
return status;
}
/* ---- the read-eval loop ---------------------------------------------- */
/**
* @brief Read commands from the current input and run them until it ends.
* @param flags RI_TOP for the main loop (recover from errors at a
* terminal), RI_EXEC_LAST if the last command may replace
* the shell.
* @return The status of the last command.
*/
int run_input(unsigned flags) {
arena *volatile pa = arena_new();
arena_marker mark = arena_mark(&scratch);
jmploc jl;
jmploc *prev = exc_handler;
unwind u;
int saved_loop = loop_depth;
bool recover =
((flags & RI_TOP) && opt.interactive) || (flags & RI_RECOVER);
unwind_save(&u);
if (stack_low()) {
arena_unref(pa);
sh_error("eval nested too deeply");
}
if (!recover) {
/*
* An error or exit unwinding through here drops this level's
* parse arena. Without this it leaks once per error that an
* outer handler (command, a subshell, the prompt) catches.
* One setjmp() per eval, `.` or script, not per command.
*/
if (setjmp(jl.buf)) {
exc_handler = prev;
arena_unref(pa);
exc_raise(exc_code);
}
exc_handler = &jl;
}
for (;;) {
if (recover) {
if (setjmp(jl.buf)) {
/* An error at the prompt: tidy up and prompt again. */
if (exc_code == EXC_EXIT) {
exc_handler = prev;
arena_unref(pa);
exc_raise(EXC_EXIT);
}
unwind_restore(&u);
arena_release(&scratch, mark);
parser_reset();
input_discard_line();
skip_kind = SKIP_NONE;
loop_depth = saved_loop;
dot_depth = 0;
job_launching = nullptr;
}
exc_handler = &jl;
if (flags & RI_TOP)
prompt_state = 1;
}
bool eof = false;
node *n = parse_command(pa, &eof);
if (n && (!opt.noexec || opt.interactive)) {
input_sync();
bool last = (flags & RI_EXEC_LAST) && (eof || input_at_end());
eval_node(n, last ? EV_EXIT : 0);
if (job_list && !opt.interactive)
jobs_reap();
}
arena_release(&scratch, mark);
if (pa->refs > 1) { /* a function now owns this arena */
arena_unref(pa);
pa = arena_new();
} else {
arena_reset(pa);
}
if (eof && recover && input->tty && interact_refuse_eof()) {
input->eof = false; /* ^D ignored: prompt again */
continue;
}
if (eof || skip_kind == SKIP_RETURN)
break;
}
exc_handler = prev;
arena_unref(pa);
return exitstatus;
}
/**
* @brief Run the commands in a string (`eval`, trap actions, `-c`).
*/
int eval_string(const char *s, unsigned flags) {
input_push_string(s, strlen(s));
run_input(flags);
input_pop();
return exitstatus;
}
|