summaryrefslogtreecommitdiffhomepage
path: root/src/builtin.c
blob: 9382a85bb76636932e0befb665258d371b92c058 (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
/**
 * @file builtin.c
 * @brief The builtin commands of POSIX `sh`, and the builtin table.
 *
 * A builtin writes to #out1 and #out2 and never to a file descriptor, so
 * that its output can be captured or piped without a process.  It reports
 * problems with sh_warn() and returns a status. Only the special builtins
 * raise errors.
 */
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/times.h>
#include <unistd.h>

#include "exec.h"
#include "var.h"
#include "sys.h"
#include "parser.h"
#include "interact.h"

/* ---- trivial ones ---------------------------------------------------- */

/**
 * @brief The `:` and `true` builtins.
 *
 * `:` stays a special builtin. Neither writes anything at all, which is
 * the strongest form of output-only, so `( : )` needs no process of its
 * own. That is the shape of `while ... ; do ( : ); done`, the subshell row
 * that cost 4.7 ms a turn on z/OS against ksh88's zero.
 */
static int b_true(int argc, char **argv) {
    (void)argc;
    (void)argv;
    return 0;
}

/**
 * @brief The `false` builtin.
 */
static int b_false(int argc, char **argv) {
    (void)argc;
    (void)argv;
    return 1;
}

/**
 * @brief The `echo` builtin.
 *
 * XSI behaviour: backslash escapes are interpreted and `-n` suppresses
 * the newline.  Use `printf` or `print -r` for exact output.
 */
static int b_echo(int argc, char **argv) {
    int i = 1;
    bool newline = true;
    if (i < argc && !strcmp(argv[i], "-n")) {
        newline = false;
        i++;
    }
    for (int first = i; i < argc; i++) {
        if (i > first)
            out_putc(&out1, ' ');
        if (!out_escaped(&out1, argv[i], true))
            return 0; /* \c: stop, no newline */
    }
    if (newline)
        out_putc(&out1, '\n');
    return 0;
}

/* ---- control flow ---------------------------------------------------- */

/**
 * @brief Parse the optional count of `break`, `continue`, `shift` and friends.
 * @param argc Argument count.
 * @param argv Arguments.
 * @param dflt Value when no count is given.
 * @return The count. A bad or negative one raises an error.
 */
static long count_arg(int argc, char **argv, long dflt) {
    if (argc < 2)
        return dflt;
    long n;
    if (!parse_long(argv[1], &n) || n < 0)
        sh_error("%s: %s: bad number", argv[0], argv[1]);
    return n;
}

/**
 * @brief The `exit` builtin: `exit [n]`.
 *
 * An interactive shell with stopped jobs refuses once.
 */
static int b_exit(int argc, char **argv) {
    /* Leaving would orphan stopped jobs: say so once, then let it happen. */
    static bool warned;
    if (opt.interactive && !in_subshell && !warned && jobs_stopped()) {
        warned = true;
        sh_warn("there are stopped jobs");
        return 1;
    }
    exitstatus = (int)(count_arg(argc, argv, exitstatus) & 0xff);
    exc_raise(EXC_EXIT);
}

/**
 * @brief The `return` builtin: `return [n]`, valid in a function or `.` file.
 */
static int b_return(int argc, char **argv) {
    int status = (int)(count_arg(argc, argv, exitstatus) & 0xff);
    if (!func_depth && !dot_depth) {
        exitstatus = status;
        exc_raise(EXC_EXIT);
    }
    skip_kind = SKIP_RETURN;
    return status;
}

/**
 * @brief Common part of `break` and `continue`: start leaving `n` loop levels.
 */
static int loop_skip(int argc, char **argv, skip_type kind) {
    long n = count_arg(argc, argv, 1);
    if (n < 1)
        sh_error("%s: %s: bad number", argv[0], argv[1]);
    if (loop_depth) {
        skip_kind = kind;
        skip_count = n > loop_depth ? loop_depth : (int)n;
    }
    return 0;
}

/**
 * @brief The `break` builtin.
 */
static int b_break(int argc, char **argv) {
    return loop_skip(argc, argv, SKIP_BREAK);
}

/**
 * @brief The `continue` builtin.
 */
static int b_continue(int argc, char **argv) {
    return loop_skip(argc, argv, SKIP_CONTINUE);
}

/**
 * @brief The `eval` builtin: join the arguments with spaces and run the result.
 */
static int b_eval(int argc, char **argv) {
    int i = 1;
    if (i < argc && !strcmp(argv[i], "--"))
        i++;
    if (i >= argc)
        return 0;
    strbuf sb;
    sb_init(&sb, &scratch);
    for (int first = i; i < argc; i++) {
        if (i > first)
            sb_putc(&sb, ' ');
        sb_puts(&sb, argv[i]);
    }
    exitstatus = 0;
    return eval_string(sb_cstr(&sb), 0);
}

/**
 * @brief The `.` builtin: run a file in the current shell.
 *
 * A name without a slash is looked up in PATH (it need not be
 * executable).
 */
static int b_dot(int argc, char **argv) {
    if (argc < 2)
        sh_error(".: file name required");
    const char *file = argv[1];
    if (!strchr(file, '/')) {
        const char *path = var_get("PATH");
        file = path_search(file, path ? path : "", false);
    }
    int fd = file ? sys_open(file, O_RDONLY, 0) : -1;
    if (fd < 0)
        sh_error(".: %s: not found", argv[1]);
    int high = sys_dupfd(fd, SYS_NFD);
    close(fd);
    if (high < 0)
        sh_error(".: %s: %s", argv[1], strerror(errno));

    input_push_fd(high, false);
    dot_depth++;
    exitstatus = 0;
    run_input(0);
    dot_depth--;
    input_pop();
    if (skip_kind == SKIP_RETURN)
        skip_kind = SKIP_NONE;
    return exitstatus;
}

/**
 * @brief The `exec` builtin.
 *
 * With a command, replaces the shell.  With only redirections, makes them
 * permanent.
 */
int builtin_exec(int argc, char **argv) {
    int i = 1;
    if (i < argc && !strcmp(argv[i], "--"))
        i++;
    if (i >= argc)
        return 0; /* redirections only: the caller makes them permanent */
    if (opt.interactive && !in_subshell)
        return shell_exec_try(argv + i, var_environ());
    shell_exec(argv + i, var_environ());
}

/* ---- variables ------------------------------------------------------- */

/**
 * @brief Common part of `export` and `readonly`.
 * @param argc Argument count.
 * @param argv Arguments.
 * @param flag V_EXPORT or V_READONLY.
 */
static int export_or_readonly(int argc, char **argv, unsigned flag) {
    int i = 1;
    for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
        if (!strcmp(argv[i], "--")) {
            i++;
            break;
        }
        if (!strcmp(argv[i], "-p"))
            continue;
        sh_error("%s: %s: bad option", argv[0], argv[i]);
    }
    if (i >= argc) {
        var_print_all(flag, flag == V_EXPORT ? "export " : "readonly ");
        return 0;
    }
    for (; i < argc; i++) {
        const char *arg = argv[i];
        size_t nlen = name_len(arg);
        if (!nlen || (arg[nlen] && arg[nlen] != '='))
            sh_error("%s: %s: bad variable name", argv[0], arg);
        if (arg[nlen])
            var_set_n(arg, nlen, arg + nlen + 1, flag);
        else
            var_set_flags(arg, flag);
    }
    return 0;
}

/**
 * @brief The `export` builtin.
 */
static int b_export(int argc, char **argv) {
    return export_or_readonly(argc, argv, V_EXPORT);
}

/**
 * @brief The `readonly` builtin.
 */
static int b_readonly(int argc, char **argv) {
    return export_or_readonly(argc, argv, V_READONLY);
}

/**
 * @brief The `unset` builtin: `unset [-fv] name...`.
 */
static int b_unset(int argc, char **argv) {
    int i = 1;
    bool functions = false;
    for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
        if (!strcmp(argv[i], "-f"))
            functions = true;
        else if (!strcmp(argv[i], "-v"))
            functions = false;
        else if (!strcmp(argv[i], "--")) {
            i++;
            break;
        } else
            sh_error("unset: %s: bad option", argv[i]);
    }
    int status = 0;
    for (; i < argc; i++) {
        if (functions)
            func_unset(argv[i]);
        else if (!var_unset(argv[i]))
            status = 1;
    }
    return status;
}

/**
 * @brief The `local` builtin: make variables local to the current function.
 */
static int b_local(int argc, char **argv) {
    if (!func_depth) {
        sh_warn("local: not in a function");
        return 1;
    }
    for (int i = 1; i < argc; i++) {
        const char *arg = argv[i];
        size_t nlen = name_len(arg);
        if (!nlen || (arg[nlen] && arg[nlen] != '=')) {
            sh_warn("local: %s: bad variable name", arg);
            return 1;
        }
        var_make_local(arena_strndup(&scratch, arg, nlen));
        if (arg[nlen])
            var_set_n(arg, nlen, arg + nlen + 1, 0);
    }
    return 0;
}

/**
 * @brief The `set` builtin: options, positional parameters, or a listing of
 * every variable.
 */
static int b_set(int argc, char **argv) {
    if (argc == 1) {
        var_print_all(0, "");
        return 0;
    }
    bool set_params = false;
    int i = parse_set_options(argc, argv, &set_params);
    if (set_params)
        params_set(argv + i, argc - i);
    jc_sync(); /* "set -m" and "set +m" take effect at once */
    return 0;
}

/**
 * @brief The `shift` builtin.
 */
static int b_shift(int argc, char **argv) {
    long n = count_arg(argc, argv, 1);
    if (n > shellparam.n)
        sh_error("shift: cannot shift %ld", n);
    shellparam.p += n;
    shellparam.n -= (int)n;
    return 0;
}

/**
 * @brief The `read` builtin: `read [-r] [-t seconds] [name...]`.
 *
 * The shell must not consume input beyond the line it returns, because
 * the next command may read the same descriptor.  On a seekable input the
 * line is read in blocks and the excess given back with lseek(). On a
 * pipe or terminal it is read a byte at a time.
 *
 * @return 0, 1 at end of input, over 128 if `-t` timed out or a trapped
 *         signal arrived.
 */
static int b_read(int argc, char **argv) {
    static char *default_vars[] = {"REPLY", nullptr};
    bool raw = false;
    double timeout = -1; /* seconds; negative: wait for ever */
    int i = 1;
    for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
        if (!strcmp(argv[i], "--")) {
            i++;
            break;
        }
        for (const char *p = argv[i] + 1; *p; p++) {
            if (*p == 'r') {
                raw = true;
            } else if (*p == 't') {
                const char *num = p[1] ? p + 1 : i + 1 < argc ? argv[++i] : "";
                char *end;
                timeout = strtod(num, &end);
                if (end == num || *end || !(timeout >= 0)) {
                    sh_warn("read: -t: bad timeout");
                    return 2;
                }
                if (timeout > 1e9) /* clamping keeps the deadline finite */
                    timeout = 1e9;
                break;
            } else {
                sh_warn("read: -%c: bad option", *p);
                return 2;
            }
        }
    }
    struct timeval deadline = {0};
    if (timeout >= 0) {
        gettimeofday(&deadline, nullptr);
        deadline.tv_sec += (time_t)timeout;
        deadline.tv_usec +=
            (suseconds_t)((timeout - (double)(time_t)timeout) * 1e6);
        if (deadline.tv_usec >= 1000000) {
            deadline.tv_sec++;
            deadline.tv_usec -= 1000000;
        }
    }
    char **vars = i < argc ? argv + i : default_vars;
    for (char **v = vars; *v; v++) {
        if (!is_name(*v)) {
            sh_warn("read: %s: bad variable name", *v);
            return 2;
        }
    }

    /*
     * Read exactly one line and nothing after it.  From a seekable file a
     * block is read and the surplus given back. From a pipe or terminal
     * there is no way to give bytes back, so they are read one at a time.
     */
    input_sync();
    strbuf line;
    strbuf esc; /* 1 where the byte was backslash-escaped */
    sb_init(&line, &scratch);
    sb_init(&esc, &scratch);
    bool seekable = lseek(0, 0, SEEK_CUR) != (off_t)-1;
    /*
     * A descriptor that cannot block is read without waiting for poll().
     * z/OS never reports /dev/null as readable, so `read -t 1 v </dev/null`
     * waited out the second and returned 128+SIGALRM instead of end of
     * input. A terminal still waits, because only it can make poll() block.
     */
    struct stat st;
    bool always_ready =
        fstat(0, &st) == 0 &&
        (S_ISREG(st.st_mode) || (S_ISCHR(st.st_mode) && !isatty(0)));
    bool eof = false;
    bool backslash = false;
    char buf[512];
    ssize_t have = 0;
    ssize_t pos = 0;
    for (;;) {
        if (pos == have) {
            if (timeout >= 0) {
                /* -t: give up (status > 128) if no input arrives in time. */
                struct timeval now;
                gettimeofday(&now, nullptr);
                long ms = (long)(deadline.tv_sec - now.tv_sec) * 1000 +
                          (long)(deadline.tv_usec - now.tv_usec) / 1000;
                struct pollfd pfd = {.fd = 0, .events = POLLIN};
                int ready = 1;
                if (!always_ready)
                    ready =
                        poll(&pfd, 1,
                             ms > 0 ? (ms < INT_MAX ? (int)ms : INT_MAX) : 0);
                if (ready == 0)
                    return 128 + SIGALRM;
                if (ready < 0 && errno == EINTR) {
                    if (trap_pending)
                        return 128 + (int)trap_pending;
                    continue;
                }
            }
            have = read(0, buf, seekable ? sizeof buf : 1);
            if (have < 0 && errno == EINTR) {
                have = pos = 0;
                if (trap_pending)
                    return 128 + (int)trap_pending;
                continue;
            }
            if (have <= 0) {
                eof = true;
                have = pos = 0;
                break;
            }
            pos = 0;
        }
        char c = buf[pos++];
        if (backslash) {
            backslash = false;
            if (c != '\n') {
                sb_putc(&line, c);
                sb_putc(&esc, 1);
            }
        } else if (c == '\\' && !raw) {
            backslash = true;
        } else if (c == '\n') {
            break;
        } else if (c) {
            sb_putc(&line, c);
            sb_putc(&esc, 0);
        }
    }
    if (seekable && pos < have)
        lseek(0, -(off_t)(have - pos), SEEK_CUR);

    /* Split into the variables; the last one takes the rest of the line. */
    const char *s = sb_cstr(&line);
    const char *e = sb_cstr(&esc);
    size_t n = line.len;
    size_t p = 0;
/**
 * @brief Splitting class of byte k of the line being split by `read` (an
 * escaped byte is never a separator).
 */
#define IFS_AT(k) (e[k] ? IFS_NONE : ifs_class[(unsigned char)s[k]])
    while (p < n && IFS_AT(p) == IFS_SPACE)
        p++;
    for (char **v = vars; *v; v++) {
        size_t start = p;
        size_t end;
        if (!v[1]) {
            end = n;
            while (end > start && IFS_AT(end - 1) == IFS_SPACE)
                end--;
            p = n;
        } else {
            while (p < n && IFS_AT(p) == IFS_NONE)
                p++;
            end = p;
            while (p < n && IFS_AT(p) == IFS_SPACE)
                p++;
            if (p < n && IFS_AT(p) == IFS_HARD) {
                p++;
                while (p < n && IFS_AT(p) == IFS_SPACE)
                    p++;
            }
        }
        var_set(*v, arena_strndup(&scratch, s + start, end - start), 0);
    }
#undef IFS_AT
    return eof ? 1 : 0;
}

/**
 * @brief Read one line into REPLY, for `select`.
 *
 * `select` reads its answer exactly as a script would with `read REPLY`,
 * so that is what it does: the backslash rules, the end-of-input status
 * and the variable are the builtin's.
 *
 * @return The status `read` returns: 0, or 1 at end of input.
 */
int builtin_read_reply(void) {
    char *argv[] = {"read", "REPLY", nullptr};
    return b_read(2, argv);
}

/* ---- getopts --------------------------------------------------------- */

/**
 * @brief `getopts`: position inside the argument being scanned.
 */
static size_t getopts_off; /**< position inside the current argument */
/**
 * @brief `getopts` itself is assigning OPTIND, so the hook must not reset.
 */
static bool getopts_setting;

/**
 * @brief OPTIND hook: an assignment by the script restarts the scan.
 */
void getopts_reset(const char *value) {
    (void)value;
    if (!getopts_setting)
        getopts_off = 0;
}

/**
 * @brief Assign OPTIND from inside `getopts` without triggering a reset.
 */
static void set_optind(long ind) {
    getopts_setting = true;
    var_set_long("OPTIND", ind);
    getopts_setting = false;
}

/**
 * @brief The `getopts` builtin: `getopts optstring name [arg...]`.
 */
static int b_getopts(int argc, char **argv) {
    if (argc < 3 || !is_name(argv[2])) {
        sh_warn("getopts: usage: getopts optstring name [arg ...]");
        return 2;
    }
    const char *optstring = argv[1];
    const char *name = argv[2];
    char **args = argc > 3 ? argv + 3 : shellparam.p;
    int nargs = argc > 3 ? argc - 3 : shellparam.n;
    bool silent = optstring[0] == ':';

    long ind = 1;
    const char *v = var_get("OPTIND");
    if (v && (!parse_long(v, &ind) || ind < 1))
        ind = 1;

    const char *arg = ind <= nargs ? args[ind - 1] : nullptr;
    if (getopts_off && (!arg || getopts_off >= strlen(arg)))
        getopts_off = 0; /* the arguments changed under us: start afresh */
    if (getopts_off == 0) {
        bool is_option = arg && arg[0] == '-' && arg[1];
        if (is_option && !strcmp(arg, "--")) {
            ind++;
            is_option = false;
        }
        if (!is_option) {
            var_set(name, "?", 0);
            set_optind(ind);
            return 1;
        }
        getopts_off = 1;
    }

    char c = arg[getopts_off++];
    char opt_name[2] = {c, '\0'};
    const char *result = opt_name;
    const char *optval = nullptr;
    const char *spec = c == ':' ? nullptr : strchr(optstring, c);
    bool took_arg = false;

    if (!spec) {
        result = "?";
        if (silent)
            optval = opt_name;
        else
            sh_warn("getopts: illegal option -- %c", c);
    } else if (spec[1] == ':') {
        took_arg = true;
        if (arg[getopts_off]) {
            optval = arg + getopts_off;
            ind++;
        } else if (ind < nargs) {
            optval = args[ind];
            ind += 2;
        } else {
            ind++;
            if (silent) {
                result = ":";
                optval = opt_name;
            } else {
                result = "?";
                sh_warn("getopts: option requires an argument -- %c", c);
            }
        }
    }
    if (took_arg) {
        getopts_off = 0;
    } else if (!arg[getopts_off]) {
        ind++;
        getopts_off = 0;
    }

    /* Copy before assigning: the strings may live in a variable. */
    const char *res = arena_strndup(&scratch, result, strlen(result));
    if (optval)
        var_set("OPTARG", arena_strndup(&scratch, optval, strlen(optval)), 0);
    else
        var_unset("OPTARG");
    var_set(name, res, 0);
    size_t off = getopts_off;
    set_optind(ind);
    getopts_off = off;
    return 0;
}

/* ---- directories ----------------------------------------------------- */

/**
 * @brief The logical working directory, found on first use.
 */
static char *curdir; /**< logical working directory, found on first use */

/**
 * @brief The logical working directory: `$PWD` if it is correct, else getcwd().
 */
static const char *get_curdir(void) {
    if (curdir)
        return curdir;
    const char *pwd = var_get("PWD");
    struct stat a;
    struct stat b;
    if (pwd && pwd[0] == '/' && stat(pwd, &a) == 0 && stat(".", &b) == 0 &&
        a.st_dev == b.st_dev && a.st_ino == b.st_ino) {
        curdir = xstrdup(pwd);
    } else {
        char buf[PATH_MAX];
        curdir = xstrdup(getcwd(buf, sizeof buf) ? buf : ".");
    }
    return curdir;
}

/**
 * @brief Remove `.`, `..` and repeated slashes from an absolute path, textually
 * (the logical view `cd -L` uses).
 * @return The cleaned path in scratch memory.
 */
static char *normalize_path(const char *path) {
    strbuf sb;
    sb_init(&sb, &scratch);
    for (const char *p = path; *p;) {
        while (*p == '/')
            p++;
        size_t len = strcspn(p, "/");
        if (len == 2 && p[0] == '.' && p[1] == '.') {
            while (sb.len && sb.s[sb.len - 1] != '/')
                sb.len--;
            if (sb.len)
                sb.len--;
        } else if (len && !(len == 1 && p[0] == '.')) {
            sb_putc(&sb, '/');
            sb_put(&sb, p, len);
        }
        p += len;
    }
    if (!sb.len)
        sb_putc(&sb, '/');
    return sb_cstr(&sb);
}

/**
 * @brief Join a directory and a relative path.
 */
static char *join_path(const char *dir, const char *name) {
    strbuf sb;
    sb_init(&sb, &scratch);
    sb_puts(&sb, dir);
    if (sb.len && sb.s[sb.len - 1] != '/')
        sb_putc(&sb, '/');
    sb_puts(&sb, name);
    return sb_cstr(&sb);
}

/**
 * @brief Is this path a directory?
 */
static bool is_directory(const char *path) {
    struct stat st;
    return stat(path, &st) == 0 && S_ISDIR(st.st_mode);
}

/**
 * @brief Find a relative directory through CDPATH.
 * @param dest  The directory asked for.
 * @param print Set if the result came from a non-empty CDPATH entry, in
 *              which case `cd` prints where it went.
 * @return The path to use, or nullptr if CDPATH has no match.
 */
static const char *cdpath_search(const char *dest, bool *print) {
    const char *cdpath = var_get("CDPATH");
    if (!cdpath || dest[0] == '/' || dest[0] == '.')
        return dest;
    for (const char *p = cdpath;;) {
        size_t len = strcspn(p, ":");
        if (len) {
            char *dir = arena_strndup(&scratch, p, len);
            char *full = join_path(dir, dest);
            if (is_directory(full)) {
                *print = true;
                return full;
            }
        } else if (is_directory(dest)) {
            return dest;
        }
        if (!p[len])
            return dest;
        p += len + 1;
    }
}

/**
 * @brief The `cd` and `chdir` builtins: `cd [-L | -P] [dir | -]`.
 *
 * Keeps PWD and OLDPWD up to date.
 */
static int b_cd(int argc, char **argv) {
    bool physical = false;
    bool print = false;
    int i = 1;
    for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
        if (!strcmp(argv[i], "--")) {
            i++;
            break;
        }
        if (!strcmp(argv[i], "-P"))
            physical = true;
        else if (!strcmp(argv[i], "-L"))
            physical = false;
        else
            break;
    }
    const char *dest = i < argc ? argv[i] : var_get("HOME");
    if (!dest) {
        sh_warn("cd: HOME not set");
        return 1;
    }
    if (!strcmp(dest, "-")) {
        dest = var_get("OLDPWD");
        if (!dest) {
            sh_warn("cd: OLDPWD not set");
            return 1;
        }
        print = true;
    } else {
        dest = cdpath_search(dest, &print);
    }

    const char *old =
        arena_strndup(&scratch, get_curdir(), strlen(get_curdir()));
    const char *target = dest[0] == '/' ? dest : join_path(old, dest);
    if (!physical)
        target = normalize_path(target);
    char buf[PATH_MAX];
    if (chdir(target) < 0) {
        if (chdir(dest) < 0) {
            sh_warn("cd: %s: %s", dest, strerror(errno));
            return 1;
        }
        /* The logical path did not exist: record where we really are. */
        if (getcwd(buf, sizeof buf))
            target = buf;
    } else if (physical && getcwd(buf, sizeof buf)) {
        target = buf;
    }
    var_set("OLDPWD", old, V_EXPORT);
    var_set("PWD", target, V_EXPORT);
    free(curdir);
    curdir = xstrdup(target);
    if (print)
        out_printf(&out1, "%s\n", target);
    return 0;
}

/**
 * @brief Run `cd` in this process and put the shell back where it was.
 *
 * A subshell only needs the directory change to be invisible to its parent.
 * Saving the open directory, `PWD`, `OLDPWD` and the logical directory cache
 * lets `( cd dir )` skip the fork that z/OS makes expensive.
 *
 * @param argc  Argument count.
 * @param argv  Arguments.
 * @param status  Where the `cd` status goes.
 */
void builtin_cd_isolated(int argc, char **argv, int *status) {
    int cwd = open(".", O_RDONLY);
    char path[PATH_MAX];
    bool have_path = getcwd(path, sizeof path) != nullptr;
    char *saved = xstrdup(get_curdir());
    bool had_pwd = var_get("PWD") != nullptr;
    bool had_oldpwd = var_get("OLDPWD") != nullptr;
    char *pwd = had_pwd ? xstrdup(var_get("PWD")) : nullptr;
    char *oldpwd = had_oldpwd ? xstrdup(var_get("OLDPWD")) : nullptr;
    jmploc jl;
    jmploc *prev = exc_handler;
    int result;

    if (setjmp(jl.buf) == 0) {
        exc_catch(&jl);
        result = b_cd(argc, argv);
    } else {
        /* b_cd raised; the directory may still have moved. */
        result = exitstatus ? exitstatus : 2;
    }
    exc_handler = prev;

    bool restored = cwd >= 0 && fchdir(cwd) == 0;
    if (cwd >= 0)
        close(cwd);
    if (!restored)
        restored = chdir(saved) == 0;
    if (!restored && have_path)
        (void)chdir(path);
    if (had_pwd)
        var_set("PWD", pwd, V_EXPORT);
    else
        var_unset("PWD");
    if (had_oldpwd)
        var_set("OLDPWD", oldpwd, V_EXPORT);
    else
        var_unset("OLDPWD");
    free(curdir);
    curdir = saved;
    free(pwd);
    free(oldpwd);
    *status = result;
}

/**
 * @brief The `pwd` builtin: `pwd [-L | -P]`.
 */
static int b_pwd(int argc, char **argv) {
    char buf[PATH_MAX];
    if (argc > 1 && !strcmp(argv[1], "-P")) {
        if (!getcwd(buf, sizeof buf)) {
            sh_warn("pwd: %s", strerror(errno));
            return 1;
        }
        out_printf(&out1, "%s\n", buf);
    } else {
        out_printf(&out1, "%s\n", get_curdir());
    }
    return 0;
}

/* ---- commands -------------------------------------------------------- */

/**
 * @brief Is this word a reserved word of the shell language?
 */
static bool is_keyword(const char *s) {
    static const char *const words[] = {
        "if",   "then", "else",     "elif",  "fi",  "do",   "done",
        "case", "esac", "while",    "until", "for", "in",   "{",
        "}",    "!",    "function", "[[",    "]]",  "time", "select",
    };
    for (size_t i = 0; i < ARRAY_LEN(words); i++) {
        if (!strcmp(s, words[i]))
            return true;
    }
    return false;
}

/**
 * @brief Say what a command name refers to.
 * @param name    The name.
 * @param verbose The `type` / `command -V` form instead of the terse
 *                `command -v` form.
 * @return 0 if found, 127 if not.
 */
int describe_command(const char *name, bool verbose) {
    cmdinfo ci;
    const char *what = nullptr;
    const alias *al = alias_count ? alias_find(name) : nullptr;
    if (al) {
        if (verbose) {
            out_printf(&out1, "%s is an alias for %s\n", name, al->value);
        } else {
            out_printf(&out1, "alias %s=", name);
            out_quote(&out1, al->value);
            out_putc(&out1, '\n');
        }
        return 0;
    }
    if (is_keyword(name)) {
        what = "a shell keyword";
    } else {
        find_command(name, &ci, 0);
        switch (ci.kind) {
        case C_BUILTIN:
            what = ci.bi->flags & BI_SPECIAL ? "a special shell builtin"
                                             : "a shell builtin";
            break;
        case C_FUNC:
            what = "a shell function";
            break;
        case C_EXTERNAL:
            if (access(ci.path, X_OK) == 0) {
                if (verbose)
                    out_printf(&out1, "%s is %s\n", name, ci.path);
                else
                    out_printf(&out1, "%s\n", ci.path);
                return 0;
            }
            [[fallthrough]];
        case C_NOTFOUND:
            if (verbose)
                sh_warn("%s: not found", name);
            return 127;
        }
    }
    if (verbose)
        out_printf(&out1, "%s is %s\n", name, what);
    else
        out_printf(&out1, "%s\n", name);
    return 0;
}

/**
 * @brief The `command` builtin when it is only asked to describe (`-v`, `-V`).
 *
 * Running a command through `command` is handled in simple_prep(), which
 * strips the prefix before the command is looked up.
 */
int builtin_command(int argc, char **argv) {
    int i = 1;
    bool verbose = false;
    bool describe = false;
    for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
        if (!strcmp(argv[i], "-v")) {
            describe = true;
        } else if (!strcmp(argv[i], "-V")) {
            describe = verbose = true;
        } else if (strcmp(argv[i], "-p")) {
            sh_warn("command: %s: bad option", argv[i]);
            return 2;
        }
    }
    int status = 0;
    for (; describe && i < argc; i++)
        status |= describe_command(argv[i], verbose);
    return status;
}

/**
 * @brief The `type` builtin.
 */
static int b_type(int argc, char **argv) {
    int status = 0;
    for (int i = 1; i < argc; i++)
        status |= describe_command(argv[i], true);
    return status;
}

/**
 * @brief The `bind` builtin: `bind [-l] ['keys'=action ...]`.
 *
 * The notation is the BSD shells' (`bind '^[[A'=up-history`). The
 * defaults stay bash's.  Macros (`-m`) are not supported.
 */
static int b_bind(int argc, char **argv) {
    bool list = false;
    int status = 0;
    for (int i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-l") == 0) {
            list = true;
            continue;
        }
        if (strcmp(argv[i], "-m") == 0) {
            sh_warn("bind: -m: macros are not supported");
            return 1;
        }
        if (edit_bind(argv[i]) < 0)
            status = 1;
    }
    if (list)
        edit_bind_list();
    return status;
}

/**
 * @brief The `hash` builtin: `hash [-r] [name...]`.
 */
static int b_hash(int argc, char **argv) {
    if (argc == 1) {
        hash_print();
        return 0;
    }
    int status = 0;
    for (int i = 1; i < argc; i++) {
        if (!strcmp(argv[i], "-r")) {
            hash_clear();
            continue;
        }
        cmdinfo ci;
        find_command(argv[i], &ci, FC_NOFUNC);
        if (ci.kind == C_NOTFOUND) {
            sh_warn("hash: %s: not found", argv[i]);
            status = 1;
        }
    }
    return status;
}

/* ---- process attributes ---------------------------------------------- */

/**
 * @brief Print a file mode mask in the `u=rwx,g=rx,o=rx` form.
 */
static void print_umask_symbolic(mode_t mask) {
    static const char who[] = "ugo";
    for (int i = 0; i < 3; i++) {
        unsigned bits = (~mask >> (6 - 3 * i)) & 7u;
        out_printf(&out1, "%s%c=%s%s%s", i ? "," : "", who[i],
                   bits & 4 ? "r" : "", bits & 2 ? "w" : "",
                   bits & 1 ? "x" : "");
    }
    out_putc(&out1, '\n');
}

/**
 * @brief Apply a symbolic mode such as `g-w,o=` to a mask.
 * @param s     The mode text.
 * @param maskp The current mask. Updated.
 * @return false if the text is not a valid mode.
 */
static bool parse_symbolic_umask(const char *s, mode_t *maskp) {
    mode_t perms = ~*maskp & 0777;
    while (*s) {
        mode_t who = 0;
        for (; *s == 'u' || *s == 'g' || *s == 'o' || *s == 'a'; s++) {
            who |= *s == 'u'   ? 0700u
                   : *s == 'g' ? 0070u
                   : *s == 'o' ? 0007u
                               : 0777u;
        }
        if (!who)
            who = 0777;
        char op = *s++;
        if (op != '+' && op != '-' && op != '=')
            return false;
        mode_t bits = 0;
        for (; *s == 'r' || *s == 'w' || *s == 'x'; s++)
            bits |= *s == 'r' ? 0444u : *s == 'w' ? 0222u : 0111u;
        bits &= who;
        if (op == '+')
            perms |= bits;
        else if (op == '-')
            perms &= ~bits;
        else
            perms = (perms & ~who) | bits;
        if (*s == ',')
            s++;
        else if (*s)
            return false;
    }
    *maskp = ~perms & 0777;
    return true;
}

/**
 * @brief The `umask` builtin: `umask [-S] [mask]`.
 */
static int b_umask(int argc, char **argv) {
    int i = 1;
    bool symbolic = false;
    if (i < argc && !strcmp(argv[i], "-S")) {
        symbolic = true;
        i++;
    }
    if (i < argc && !strcmp(argv[i], "--"))
        i++;
    mode_t mask = umask(0);
    umask(mask);
    if (i >= argc) {
        if (symbolic)
            print_umask_symbolic(mask);
        else
            out_printf(&out1, "%04o\n", (unsigned)mask);
        return 0;
    }
    const char *arg = argv[i];
    if (arg[0] >= '0' && arg[0] <= '7') {
        char *end;
        unsigned long v = strtoul(arg, &end, 8);
        if (*end || v > 0777) {
            sh_warn("umask: %s: bad mask", arg);
            return 1;
        }
        mask = (mode_t)v;
    } else if (!parse_symbolic_umask(arg, &mask)) {
        sh_warn("umask: %s: bad mask", arg);
        return 1;
    }
    umask(mask);
    return 0;
}

/**
 * @brief The `times` builtin: CPU time used by the shell and by its children.
 */
static int b_times(int argc, char **argv) {
    (void)argc;
    (void)argv;
    struct tms t;
    long hz = sysconf(_SC_CLK_TCK);
    times(&t);
    const clock_t v[4] = {t.tms_utime, t.tms_stime, t.tms_cutime, t.tms_cstime};
    for (int i = 0; i < 4; i++) {
        double secs = (double)v[i] / (double)hz;
        out_printf(&out1, "%dm%.2fs%c", (int)(secs / 60),
                   secs - 60 * (int)(secs / 60), i % 2 ? '\n' : ' ');
    }
    return 0;
}

/* ---- the table ------------------------------------------------------- */

const builtin builtins[] = {
#if SYS_MVS
    /* z/OS only: `free` in particular must not hide procps on Linux. */
    {"alloc", builtin_alloc, 0},
    {"free", builtin_free, 0},
    {"tag", builtin_tag, 0},
#endif
    {".", b_dot, BI_SPECIAL},
    {":", b_true, BI_SPECIAL | BI_PURE},
    {"[", builtin_test, BI_PURE},
    {"alias", builtin_alias, 0},
    {"bg", builtin_bg, 0},
    {"bind", b_bind, 0},
    {"break", b_break, BI_SPECIAL},
    {"cd", b_cd, BI_CD},
    {"chdir", b_cd, BI_CD},
    {"command", builtin_command, 0},
    {"continue", b_continue, BI_SPECIAL},
    {"echo", b_echo, BI_PURE},
    {"eval", b_eval, BI_SPECIAL},
    {"exec", builtin_exec, BI_SPECIAL},
    {"exit", b_exit, BI_SPECIAL},
    {"export", b_export, BI_SPECIAL},
    {"false", b_false, BI_PURE},
    {"fc", builtin_fc, 0},
    {"fg", builtin_fg, 0},
    {"getopts", b_getopts, 0},
    {"hash", b_hash, 0},
    {"integer", builtin_typeset, 0},
    {"jobs", builtin_jobs, BI_PURE},
    {"kill", builtin_kill, 0},
    {"let", builtin_let, 0},
    {"local", b_local, 0},
    {"print", builtin_print, BI_PURE},
    {"printf", builtin_printf, BI_PURE},
    {"pwd", b_pwd, BI_PURE},
    {"read", b_read, 0},
    {"readonly", b_readonly, BI_SPECIAL},
    {"return", b_return, BI_SPECIAL},
    {"set", b_set, BI_SPECIAL},
    {"setvar", builtin_setvar, 0},
    {"shift", b_shift, BI_SPECIAL},
    {"test", builtin_test, BI_PURE},
    {"times", b_times, BI_SPECIAL},
    {"trap", builtin_trap, BI_SPECIAL},
    {"true", b_true, BI_PURE},
    {"type", b_type, BI_PURE},
    {"typeset", builtin_typeset, 0},
    {"ulimit", builtin_ulimit, 0},
    {"umask", b_umask, 0},
    {"unalias", builtin_unalias, 0},
    {"unset", b_unset, BI_SPECIAL},
    {"wait", builtin_wait, 0},
    {"whence", builtin_whence, BI_PURE},
};

/**
 * @brief Number of entries in #builtins.
 */
const size_t nbuiltins = ARRAY_LEN(builtins);