summaryrefslogtreecommitdiffhomepage
path: root/src/builtin_ext.c
blob: 9b0ee9cb97636c98724da2fd7c2ff7f0f31d9194 (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
/**
 * @file builtin_ext.c
 * @brief Builtins that are extensions to POSIX `sh`.
 *
 * From the Korn shell (and so familiar to users of the z/OS `/bin/sh`):
 * `print`, `whence`, `typeset`, `integer` and `let`.  From FreeBSD `sh`:
 * `setvar` and `ulimit`.
 *
 * Each of these is only a row in the builtin table. A script that does
 * not call them is unaffected by their existence.
 */
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>

#include "exec.h"
#include "expand.h"
#include "sys.h"

/* ---- print ----------------------------------------------------------- */

/**
 * @brief The `print` builtin: `print [-nrR] [-u[fd]] [--] [arg ...]`.
 *
 * Writes its arguments separated by spaces and followed by a newline.
 * Backslash escapes are interpreted as by `echo` unless `-r` (or `-R`)
 * is given. `-n` suppresses the newline. `-u` selects a descriptor other
 * than standard output.  The co-process (`-p`) and history (`-s`) forms
 * of the Korn shell are not provided.
 *
 * @return 0, 1 on a write error, 2 for a bad option or descriptor.
 */
int builtin_print(int argc, char **argv) {
    bool newline = true;
    bool raw = false;
    long fd = 1;
    int i = 1;
    for (; i < argc && argv[i][0] == '-'; i++) {
        const char *a = argv[i];
        if (!a[1] || !strcmp(a, "--")) {
            i++;
            break;
        }
        bool stop = false;
        for (const char *p = a + 1; *p; p++) {
            if (*p == 'n') {
                newline = false;
            } else if (*p == 'r') {
                raw = true;
            } else if (*p == 'R') {
                raw = stop = true;
            } else if (*p == 'u') {
                const char *num = p[1] ? p + 1 : i + 1 < argc ? argv[++i] : "";
                if (!parse_long(num, &fd) || fd < 0) {
                    sh_warn("print: -u: bad file descriptor");
                    return 2;
                }
                break;
            } else {
                sh_warn("print: -%c: bad option", *p);
                return 2;
            }
        }
        if (stop) { /* after -R only -n is still an option */
            i++;
            while (i < argc && !strcmp(argv[i], "-n")) {
                newline = false;
                i++;
            }
            break;
        }
    }

    char buf[256];
    output other = {buf, 0, sizeof buf, (int)fd, 0};
    output *o = fd == 1 ? &out1 : fd == 2 ? &out2 : &other;
    if (o == &other && fcntl((int)fd, F_GETFD) == -1) {
        sh_warn("print: -u: bad file descriptor");
        return 2;
    }
    for (int first = i; i < argc; i++) {
        if (i > first)
            out_putc(o, ' ');
        if (raw) {
            out_puts(o, argv[i]);
        } else if (!out_escaped(o, argv[i], true)) {
            newline = false; /* \c */
            break;
        }
    }
    if (newline)
        out_putc(o, '\n');
    if (o != &out1) {
        out_flush(o);
        if (o->err && o->err != EPIPE) {
            sh_warn("print: write error: %s", strerror(o->err));
            o->err = 0;
            return 1;
        }
        o->err = 0;
    }
    return 0;
}

/* ---- whence ---------------------------------------------------------- */

/**
 * @brief The `whence` builtin: `whence [-pv] name ...`.
 *
 * Without options it prints what `command -v` prints. `-v` gives the
 * descriptive form that `type` gives. `-p` searches PATH only, ignoring
 * aliases, functions and builtins.
 *
 * @return 0 if every name was found, otherwise non-zero.
 */
int builtin_whence(int argc, char **argv) {
    bool verbose = false;
    bool path_only = false;
    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 == 'v') {
                verbose = true;
            } else if (*p == 'p') {
                path_only = true;
            } else {
                sh_warn("whence: -%c: bad option", *p);
                return 2;
            }
        }
    }
    int status = 0;
    for (; i < argc; i++) {
        if (!path_only) {
            status |= describe_command(argv[i], verbose);
            continue;
        }
        const char *path = var_get("PATH");
        const char *full = strchr(argv[i], '/')
                               ? (access(argv[i], X_OK) == 0 ? argv[i] : NULL)
                               : path_search(argv[i], path ? path : "", true);
        if (full)
            out_printf(&out1, "%s\n", full);
        else
            status = 1;
    }
    return status;
}

/* ---- setvar ---------------------------------------------------------- */

/**
 * @brief The `setvar` builtin (FreeBSD): `setvar name value`.
 *
 * Assigns to the variable whose name is the first argument.  This is the
 * safe replacement for `eval "$1=\$2"`: the name is checked, the value is
 * never parsed as shell text, and no parsing happens at all.
 *
 * @return 0, 2 for wrong usage or a bad name.
 */
int builtin_setvar(int argc, char **argv) {
    if (argc != 3) {
        sh_warn("setvar: usage: setvar name value");
        return 2;
    }
    if (!is_name(argv[1])) {
        sh_warn("setvar: %s: bad variable name", argv[1]);
        return 2;
    }
    var_set(argv[1], argv[2], 0);
    return 0;
}

/* ---- typeset --------------------------------------------------------- */

/**
 * @brief The `typeset` builtin: `typeset [-irx] [+ix] [name[=value] ...]`.
 *
 * Gives variables attributes: `-x` exported, `-r` read-only, `-i`
 * integer (every value assigned is evaluated as an arithmetic
 * expression).  `+x` and `+i` remove an attribute.  Inside a function the
 * named variables become local to it, as with `local`.  With no names,
 * the variables that have the given attributes are listed.
 *
 * `integer` is `typeset -i`.
 *
 * @return 0, 1 for a bad name, 2 for a bad option.
 */
int builtin_typeset(int argc, char **argv) {
    unsigned on = !strcmp(argv[0], "integer") ? V_INTEGER : 0;
    unsigned off = 0;
    int i = 1;
    for (; i < argc && (argv[i][0] == '-' || argv[i][0] == '+') && argv[i][1];
         i++) {
        if (!strcmp(argv[i], "--")) {
            i++;
            break;
        }
        bool plus = argv[i][0] == '+';
        for (const char *p = argv[i] + 1; *p; p++) {
            unsigned f = *p == 'x'   ? V_EXPORT
                         : *p == 'i' ? V_INTEGER
                         : *p == 'r' ? V_READONLY
                                     : 0;
            if (!f || (plus && f == V_READONLY)) {
                sh_warn("%s: %c%c: bad option", argv[0], argv[i][0], *p);
                return 2;
            }
            if (plus)
                off |= f;
            else
                on |= f;
        }
    }
    if (i >= argc) {
        var_print_all(on, on & V_EXPORT     ? "export "
                          : on & V_READONLY ? "readonly "
                          : on & V_INTEGER  ? "integer "
                                            : "");
        return 0;
    }
    for (; i < argc; i++) {
        const char *arg = argv[i];
        size_t nlen = name_len(arg);
        if (!nlen || (arg[nlen] && arg[nlen] != '=')) {
            sh_warn("%s: %s: bad variable name", argv[0], arg);
            return 1;
        }
        const char *name = arena_strndup(&scratch, arg, nlen);
        if (func_depth)
            var_make_local(name);
        /* Attributes first, so that -i applies to this very value; but
         * read-only last, or the value could not be assigned. */
        if (on & ~V_READONLY)
            var_set_flags(name, on & ~V_READONLY);
        if (off)
            var_clear_flags(name, off);
        if (arg[nlen])
            var_set_n(arg, nlen, arg + nlen + 1, 0);
        if (on & V_READONLY)
            var_set_flags(name, V_READONLY);
    }
    return 0;
}

/* ---- let ------------------------------------------------------------- */

/**
 * @brief The `let` builtin: `let expression ...`.
 *
 * Evaluates each argument as an arithmetic expression.
 *
 * @return 0 if the last expression is non-zero, 1 if it is zero, 2 if
 *         there are no arguments.
 */
int builtin_let(int argc, char **argv) {
    if (argc < 2) {
        sh_warn("let: expression expected");
        return 2;
    }
    intmax_t v = 0;
    for (int i = 1; i < argc; i++)
        v = arith_eval(argv[i]);
    return v == 0;
}

/* ---- ulimit ---------------------------------------------------------- */

/** @brief One resource `ulimit` knows about. */
typedef struct limit {
    char opt;         /**< Option letter. */
    int resource;     /**< RLIMIT_* value. */
    const char *name; /**< Description for `ulimit -a`. */
    const char *unit; /**< Unit name for `ulimit -a`, or NULL. */
    unsigned scale;   /**< Bytes (or items) per unit shown to the user. */
} limit;

static const limit limits[] = {
#ifdef RLIMIT_CORE
    {'c', RLIMIT_CORE, "core file size", "512-blocks", 512},
#endif
#ifdef RLIMIT_DATA
    {'d', RLIMIT_DATA, "data seg size", "kbytes", 1024},
#endif
    {'f', RLIMIT_FSIZE, "file size", "512-blocks", 512},
#ifdef RLIMIT_MEMLOCK
    {'l', RLIMIT_MEMLOCK, "locked memory", "kbytes", 1024},
#endif
#ifdef RLIMIT_RSS
    {'m', RLIMIT_RSS, "max memory size", "kbytes", 1024},
#endif
#ifdef RLIMIT_NOFILE
    {'n', RLIMIT_NOFILE, "open files", NULL, 1},
#endif
#ifdef RLIMIT_STACK
    {'s', RLIMIT_STACK, "stack size", "kbytes", 1024},
#endif
#ifdef RLIMIT_CPU
    {'t', RLIMIT_CPU, "cpu time", "seconds", 1},
#endif
#ifdef RLIMIT_NPROC
    {'u', RLIMIT_NPROC, "max user processes", NULL, 1},
#endif
#ifdef RLIMIT_AS
    {'v', RLIMIT_AS, "virtual memory", "kbytes", 1024},
#endif
#ifdef RLIMIT_MEMLIMIT /* z/OS: storage above the 2 GB bar (MEMLIMIT) */
    {'M', RLIMIT_MEMLIMIT, "memory above the bar", "mbytes", 1048576},
#endif
};

/**
 * @brief Print one limit value, or "unlimited".
 * @param l    The resource.
 * @param hard Whether to show the hard limit rather than the soft one.
 */
static void limit_print(const limit *l, bool hard) {
    struct rlimit rl;
    if (getrlimit(l->resource, &rl) < 0) {
        out_puts(&out1, "unknown\n");
        return;
    }
    rlim_t v = hard ? rl.rlim_max : rl.rlim_cur;
    if (v == RLIM_INFINITY)
        out_puts(&out1, "unlimited\n");
    else
        out_printf(&out1, "%llu\n", (unsigned long long)(v / l->scale));
}

/**
 * @brief The `ulimit` builtin: `ulimit [-HSa] [-cdflmnstuv] [limit]`.
 *
 * Shows or sets a resource limit of the shell (inherited by the commands
 * it runs).  The default resource is the file size limit, `-f`.  `limit`
 * is a number in the resource's unit or the word `unlimited`.  Setting
 * changes both the hard and the soft limit unless `-H` or `-S` chooses
 * one. A query reports the soft limit unless `-H` is given.
 *
 * @return 0, 1 if the limit could not be set, 2 for wrong usage.
 */
int builtin_ulimit(int argc, char **argv) {
    bool hard = false;
    bool soft = false;
    bool all = false;
    const limit *l = NULL;
    int i = 1;
    for (; i < argc && argv[i][0] == '-' && argv[i][1]; i++) {
        for (const char *p = argv[i] + 1; *p; p++) {
            if (*p == 'H') {
                hard = true;
            } else if (*p == 'S') {
                soft = true;
            } else if (*p == 'a') {
                all = true;
            } else {
                const limit *found = NULL;
                for (size_t k = 0; k < ARRAY_LEN(limits); k++) {
                    if (limits[k].opt == *p)
                        found = &limits[k];
                }
                if (!found) {
                    sh_warn("ulimit: -%c: bad option", *p);
                    return 2;
                }
                l = found;
            }
        }
    }
    if (all) {
        for (size_t k = 0; k < ARRAY_LEN(limits); k++) {
            char label[64];
            const limit *e = &limits[k];
            size_t n = 0;
            for (const char *s = e->name; *s; s++)
                label[n++] = *s;
            label[n] = '\0';
            if (e->unit)
                out_printf(&out1, "%-20s (%s, -%c) ", label, e->unit, e->opt);
            else
                out_printf(&out1, "%-20s (-%c) ", label, e->opt);
            limit_print(e, hard && !soft);
        }
        return 0;
    }
    if (!l) {
        for (size_t k = 0; k < ARRAY_LEN(limits); k++) {
            if (limits[k].opt == 'f')
                l = &limits[k];
        }
    }
    if (i >= argc) {
        limit_print(l, hard && !soft);
        return 0;
    }
    struct rlimit rl;
    if (getrlimit(l->resource, &rl) < 0) {
        sh_warn("ulimit: %s", strerror(errno));
        return 1;
    }
    rlim_t v;
    if (!strcmp(argv[i], "unlimited")) {
        v = RLIM_INFINITY;
    } else {
        char *end;
        errno = 0;
        unsigned long long n = strtoull(argv[i], &end, 10);
        if (errno || *end || end == argv[i] || argv[i][0] == '-') {
            sh_warn("ulimit: %s: bad limit", argv[i]);
            return 2;
        }
        v = (rlim_t)n * l->scale;
    }
    if (hard || !soft)
        rl.rlim_max = v;
    if (soft || !hard)
        rl.rlim_cur = v;
    if (setrlimit(l->resource, &rl) < 0) {
        sh_warn("ulimit: %s", strerror(errno));
        return 1;
    }
    return 0;
}

/* ---- z/OS builtins: tag, alloc, free ---------------------------------- */

/**
 * @brief Print one file's tag in `chtag -p` style.
 *
 * Four fields: `t` (text), `b` (binary), `m` (mixed: a CCSID without the
 * text flag) or `-` (untagged). The code set, `binary` or `untagged`;
 * `T=on` or `T=off`. The file name.
 *
 * @return 0, or 1 if the file cannot be examined.
 */
static int tag_print(const char *path) {
    sys_tag t;
    if (sys_tag_get(path, &t) < 0) {
        sh_warn("tag: %s: %s", path, strerror(errno));
        return 1;
    }
    char kind = t.ccsid == 0       ? '-'
                : t.ccsid == 65535 ? 'b'
                : t.text           ? 't'
                                   : 'm';
    const char *cs = t.ccsid == 0       ? "untagged"
                     : t.ccsid == 65535 ? "binary"
                     : t.codeset[0]     ? t.codeset
                                        : "?";
    if (!t.codeset[0] && t.ccsid && t.ccsid != 65535)
        out_printf(&out1, "%c %-14d T=%s  %s\n", kind, t.ccsid,
                   t.text ? "on " : "off", path);
    else
        out_printf(&out1, "%c %-14s T=%s  %s\n", kind, cs,
                   t.text ? "on " : "off", path);
    return 0;
}

/**
 * @brief The `tag` builtin: show or change file tags without spawning
 *        `chtag` (z/OS only).
 *
 *     tag [-p] file...                  show, as chtag -p
 *     tag -t -c codeset file...         tag as text in codeset
 *     tag -m -c codeset file...         tag mixed (codeset, text flag off)
 *     tag -b file...                    tag as binary
 *     tag -r file...                    remove the tag
 *
 * @return 0, 1 if any file failed, 2 for wrong usage.
 */
int builtin_tag(int argc, char **argv) {
    char mode = 'p';
    const char *codeset = NULL;
    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 (strchr("ptmbr", *p)) {
                mode = *p;
            } else if (*p == 'c') {
                codeset = p[1] ? p + 1 : (i + 1 < argc ? argv[++i] : NULL);
                if (!codeset) {
                    sh_warn("tag: -c: code set required");
                    return 2;
                }
                break;
            } else {
                sh_warn("tag: -%c: bad option", *p);
                return 2;
            }
        }
    }
    if (i == argc || ((mode == 't' || mode == 'm') && !codeset)) {
        sh_warn("usage: tag [-p | -t -c codeset | -m -c codeset | -b | -r] "
                "file...");
        return 2;
    }
    int status = 0;
    for (; i < argc; i++) {
        if (mode == 'p') {
            status |= tag_print(argv[i]);
            continue;
        }
        int rc = mode == 'r'   ? sys_tag_set(argv[i], NULL, 0)
                 : mode == 'b' ? sys_tag_set(argv[i], "BINARY", 0)
                               : sys_tag_set(argv[i], codeset, mode == 't');
        if (rc < 0) {
            sh_warn("tag: %s: %s", argv[i],
                    errno == EINVAL ? "unknown code set" : strerror(errno));
            status = 1;
        }
    }
    return status;
}

/**
 * @brief Run one BPXWDYN request built from a keyword and the arguments.
 * @param verb  "alloc" or "free".
 * @param argc  Argument count.
 * @param argv  Arguments. argv[1..] are the request's keywords.
 * @return 0, or 1 if BPXWDYN failed (its message is printed).
 */
static int dynalloc(const char *verb, int argc, char **argv) {
    if (argc < 2) {
        sh_warn("usage: %s keyword...  (BPXWDYN syntax, e.g. %s)", verb,
                verb[0] == 'a' ? "alloc dd(in) da('sys1.maclib') shr"
                               : "free dd(in)");
        return 2;
    }
    strbuf sb;
    arena_marker mark = arena_mark(&scratch);
    sb_init(&sb, &scratch);
    sb_puts(&sb, verb);
    for (int i = 1; i < argc; i++) {
        sb_putc(&sb, ' ');
        sb_puts(&sb, argv[i]);
    }
    char msg[128];
    int rc = sys_dynalloc(sb_cstr(&sb), msg, sizeof msg);
    arena_release(&scratch, mark);
    if (rc) {
        sh_warn("%s: %s", verb, msg);
        return 1;
    }
    return 0;
}

/**
 * @brief The `alloc` builtin: dynamic allocation through BPXWDYN, so a
 *        DD exists in the shell's address space (z/OS only).
 *
 * `alloc dd(sysut1) da('my.data') shr msg(2)`.  A DD allocated here is
 * visible to commands that run in the same address space: builtins, and
 * external commands only with `_BPX_SHAREAS=YES` (`set -o shareas`).
 */
int builtin_alloc(int argc, char **argv) {
    return dynalloc("alloc", argc, argv);
}

/**
 * @brief The `free` builtin: release a dynamic allocation (z/OS only).
 */
int builtin_free(int argc, char **argv) {
    return dynalloc("free", argc, argv);
}