interplane.Get Omega
Read in your language

omega-mv

Omega: a language for verified programs, semantic identity and machine realization. Seed-born work and existing implementations have distinct provenance.

Brought by drakestapleton

branch main Branches Tags History

omega-mv / src / osh / host / osh_builtin.c

729 lines · 31040 bytes Raw Blame History
1/* SPDX-License-Identifier: Apache-2.0
2 * Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * osh_builtin.c -- in-process builtins: cd pwd printf export unset exit (builtin_id 1..6, ABI section 7.1).
19 *
20 * printf subset, exactly (anything else is refused with a diagnostic and status 1, before any output):
21 * conversions %s %d %i %u %x %o %c %% no flags, width, precision, length modifiers; no %b %f %e %g %X
22 * escapes in the FORMAT only: \\ \a \b \f \n \r \t \v \" and \NNN (1 to 3 octal digits); any other
23 * backslash sequence is printed verbatim (backslash included). Arguments are never escape-processed.
24 * format reuse while arguments remain, the whole format is applied again; a format with no conversion is
25 * printed once. Missing arguments read as "" for %s %c and 0 for numbers.
26 * numbers strtoimax/strtoumax base 0 (decimal, 0x hex, 0 octal); a leading ' or " gives the next byte's
27 * value; a bad number prints its numeric prefix (or 0), emits a diagnostic, and the status is 1.
28 * %c first byte of the argument, nothing for an empty argument.
29 * cd: cd [-L|-P] [--] [DIR | -]; DIR defaults to $HOME; -L (default): PWD is the lexical result, "." and ".."
30 * resolved textually; -P: PWD from getcwd; cd "" is a no-op (bash). CDPATH is NOT searched: a relative DIR not
31 * anchored with ./ or ../ is refused while CDPATH is set (omega#344).
32 */
33#ifndef _GNU_SOURCE
34#define _GNU_SOURCE
35#endif
36#include "osh_host.h"
37#include "osh_priv.h"
38
39#include <ctype.h>
40#include <errno.h>
41#include <inttypes.h>
42#include <limits.h>
43#include <stdarg.h>
44#include <stdio.h>
45#include <stdlib.h>
46#include <string.h>
47#include <sys/stat.h>
48#include <unistd.h>
49
50int osh_write_all(int fd, const char *buf, size_t n)
51{
52 while (n) {
53 ssize_t w = write(fd, buf, n);
54 if (w < 0) {
55 if (errno == EINTR) continue;
56 return -1;
57 }
58 buf += w;
59 n -= (size_t)w;
60 }
61 return 0;
62}
63
64void osh_diag(int fd, const char *fmt, ...)
65{
66 char buf[1024];
67 int n = snprintf(buf, sizeof buf, "osh: ");
68 va_list ap;
69 va_start(ap, fmt);
70 int m = vsnprintf(buf + n, sizeof buf - (size_t)n - 1, fmt, ap);
71 va_end(ap);
72 if (m < 0) return;
73 n += m;
74 if ((size_t)n > sizeof buf - 2) n = (int)sizeof buf - 2;
75 buf[n++] = '\n';
76 int saved = errno;
77 (void)osh_write_all(fd, buf, (size_t)n);
78 errno = saved;
79}
80
81/* ---------------- cd / pwd ---------------- */
82
83/* Lexical canonical form of an absolute path ("." and ".." removed, no trailing slash). */
84static int canon(const char *in, char *out, size_t cap)
85{
86 size_t n = 0;
87 out[0] = '/';
88 n = 1;
89 const char *p = in;
90 while (*p) {
91 while (*p == '/') p++;
92 const char *e = p;
93 while (*e && *e != '/') e++;
94 size_t l = (size_t)(e - p);
95 if (l == 0) break;
96 if (l == 1 && p[0] == '.') {
97 } else if (l == 2 && p[0] == '.' && p[1] == '.') {
98 while (n > 1 && out[n - 1] != '/') n--;
99 if (n > 1) n--; /* drop the slash before the removed component */
100 } else {
101 if (n + l + 2 > cap) return -1;
102 if (n > 1) out[n++] = '/';
103 memcpy(out + n, p, l);
104 n += l;
105 }
106 p = e;
107 }
108 out[n] = 0;
109 return 0;
110}
111
112/* The logical working directory: $PWD when it names ".", else getcwd. When the directory was removed getcwd fails
113 * (ENOENT) and bash keeps using the directory it remembered, so an absolute $PWD is used then (omega#344). */
114static int logical_pwd(const OshSession *s, char *out, size_t cap)
115{
116 const char *p = osh_var_get(s, "PWD");
117 struct stat a, b;
118 if (p && p[0] == '/' && strlen(p) < cap && stat(p, &a) == 0 && stat(".", &b) == 0 && a.st_dev == b.st_dev &&
119 a.st_ino == b.st_ino) {
120 strcpy(out, p);
121 return 0;
122 }
123 if (getcwd(out, cap)) return 0;
124 if (errno == ENOENT && p && p[0] == '/' && strlen(p) < cap) {
125 strcpy(out, p);
126 return 0;
127 }
128 return -1;
129}
130
131/* bash's message when getcwd cannot name a removed directory; printed without the shell-name prefix, as bash does. */
132static void getcwd_error(int fd, const char *who)
133{
134 char buf[256];
135 int n = snprintf(buf, sizeof buf, "%s: error retrieving current directory: getcwd: cannot access parent directories: %s\n",
136 who, strerror(errno));
137 (void)osh_write_all(fd, buf, (size_t)n);
138}
139
140static int bi_cd(OshSession *s, const OshCmd *c, const int io[3], int in_parent)
141{
142 int show = 0, physical = 0, i = 1;
143 const char *dir;
144 /* options as bash: -L (the default) and -P; "--" ends them; anything else is "invalid option", status 2 */
145 for (; i < c->nargv && c->argv[i][0] == '-' && c->argv[i][1]; i++) {
146 if (strcmp(c->argv[i], "--") == 0) { i++; break; }
147 for (const char *o = c->argv[i] + 1; *o; o++) {
148 if (*o == 'L') physical = 0;
149 else if (*o == 'P') physical = 1;
150 else { osh_diag(io[2], "cd: -%c: invalid option\ncd: usage: cd [-L|[-P [-e]] [-@]] [dir]", *o); return 2; }
151 }
152 }
153 if (c->nargv - i > 1) { osh_diag(io[2], "cd: too many arguments"); return 1; }
154 if (c->nargv == i) {
155 dir = osh_var_get(s, "HOME");
156 if (!dir || !*dir) { osh_diag(io[2], "cd: HOME not set"); return 1; }
157 } else if (strcmp(c->argv[i], "-") == 0) {
158 dir = osh_var_get(s, "OLDPWD");
159 if (!dir || !*dir) { osh_diag(io[2], "cd: OLDPWD not set"); return 1; }
160 show = 1;
161 } else {
162 dir = c->argv[i];
163 if (!*dir) return 0; /* bash 5.2: cd "" changes nothing and succeeds */
164 /* CDPATH is not searched. bash would go to $CDPATH/DIR when that exists, so a relative name that is not
165 * anchored with ./ or ../ could silently mean a different directory: refuse it while CDPATH is set. */
166 const char *cdpath = osh_var_get(s, "CDPATH");
167 int anchored = dir[0] == '/' || (dir[0] == '.' && (dir[1] == 0 || dir[1] == '/' || (dir[1] == '.' && (dir[2] == 0 || dir[2] == '/'))));
168 if (cdpath && *cdpath && !anchored) {
169 osh_diag(io[2], "cd: %s: CDPATH is set and osh does not search it; use ./%s or an absolute path", dir, dir);
170 return 1;
171 }
172 }
173 char old[PATH_MAX], joined[2 * PATH_MAX + 2], cur[PATH_MAX];
174 if (logical_pwd(s, old, sizeof old)) { osh_diag(io[2], "cd: cannot determine current directory"); return 1; }
175 if (dir[0] == '/') {
176 if (strlen(dir) >= sizeof joined) { osh_diag(io[2], "cd: %s: File name too long", dir); return 1; }
177 strcpy(joined, dir);
178 } else {
179 if (snprintf(joined, sizeof joined, "%s/%s", old, dir) >= (int)sizeof joined) {
180 osh_diag(io[2], "cd: %s: File name too long", dir);
181 return 1;
182 }
183 }
184 if (canon(joined, cur, sizeof cur)) { osh_diag(io[2], "cd: %s: File name too long", dir); return 1; }
185 if (osh_effect_check(s, OSH_OP_CHDIR, cur, io[2]) != OSH_E_OK) return 1;
186 if (chdir(cur) != 0) { osh_diag(io[2], "cd: %s: %s", dir, strerror(errno)); return 1; }
187 if (physical) { /* -P: PWD is the physical directory with symbolic links resolved; the lexical one if the kernel cannot say */
188 char phys[PATH_MAX];
189 if (getcwd(phys, sizeof phys)) strcpy(cur, phys);
190 }
191 /* A child context keeps its own copy of the table, so setting here is safe in both cases. */
192 (void)in_parent;
193 osh_var_export(s, "OLDPWD", old); /* bash exports OLDPWD */
194 osh_var_set(s, "PWD", cur);
195 if (show) {
196 char line[PATH_MAX + 1];
197 int n = snprintf(line, sizeof line, "%s\n", cur);
198 if (osh_write_all(io[1], line, (size_t)n)) { osh_diag(io[2], "cd: write error: %s", strerror(errno)); return 1; }
199 }
200 return 0;
201}
202
203static int bi_pwd(OshSession *s, const OshCmd *c, const int io[3])
204{
205 int physical = 0, i = 1;
206 for (; i < c->nargv && c->argv[i][0] == '-' && c->argv[i][1]; i++) {
207 if (strcmp(c->argv[i], "--") == 0) break;
208 for (const char *o = c->argv[i] + 1; *o; o++) {
209 if (*o == 'P') physical = 1;
210 else if (*o == 'L') physical = 0;
211 else { osh_diag(io[2], "pwd: -%c: invalid option\npwd: usage: pwd [-LP]", *o); return 2; }
212 }
213 }
214 /* bash 5.2 ignores operands of pwd */
215 char p[PATH_MAX + 1];
216 if (physical ? !getcwd(p, PATH_MAX) : logical_pwd(s, p, PATH_MAX)) {
217 if (errno == ENOENT) getcwd_error(io[2], "pwd");
218 else osh_diag(io[2], "pwd: %s", strerror(errno));
219 return 1;
220 }
221 strcat(p, "\n");
222 if (osh_write_all(io[1], p, strlen(p))) { osh_diag(io[2], "pwd: write error: %s", strerror(errno)); return 1; }
223 return 0;
224}
225
226/* ---------------- printf ---------------- */
227
228typedef struct {
229 int fd, err;
230 size_t n;
231 char buf[4096];
232} Out;
233
234static void out_flush(Out *o)
235{
236 if (o->n && !o->err && osh_write_all(o->fd, o->buf, o->n)) o->err = errno;
237 o->n = 0;
238}
239
240static void out_bytes(Out *o, const char *p, size_t n)
241{
242 while (n) {
243 if (o->n == sizeof o->buf) out_flush(o);
244 size_t k = sizeof o->buf - o->n;
245 if (k > n) k = n;
246 memcpy(o->buf + o->n, p, k);
247 o->n += k;
248 p += k;
249 n -= k;
250 }
251}
252
253/* printf FORMAT [ARG...] in bash 5.2's shape (#344 RISK-4): flags - + space # 0, width and precision as digits or
254 * `*` (taken from the arguments), length modifiers h l j z t L ignored as bash does, conversions
255 * d i o u x X c s b q e E f F g G a A and %%. The format is reused while arguments remain. %s %c %b %q pad with
256 * spaces even under the 0 flag (bash); %b expands \a \b \e \E \f \n \r \t \v \\ \' \" \0nnn \nnn \xHH \uHHHH
257 * \UHHHHHHHH and stops all output at \c; %q quotes for reuse as shell input (bash's backslash form, or $'...'
258 * when a control byte is present). Every conversion is validated before anything is printed (osh refuses where
259 * bash would print the prefix first). osh limit, not bash's: a width or precision above 1000000 is refused. */
260static int is_conv(char ch) { return ch && strchr("diouxXcsbqeEfFgGaA", ch) != NULL; }
261
262typedef struct {
263 int minus, plus, space, alt, zero;
264 int width, prec; /* -1: not given */
265 int star_w, star_p; /* taken from the arguments */
266 char conv;
267} PfSpec;
268
269enum { PF_MAX_WIDTH = 1000000 };
270
271/* Parse what follows a '%'. Returns the bytes consumed, or 0 with *bad set to the offending byte (NUL: the
272 * format ended inside the specification). */
273static int pf_parse(const char *p, PfSpec *sp, char *bad)
274{
275 const char *q = p;
276 memset(sp, 0, sizeof *sp);
277 sp->width = sp->prec = -1;
278 for (;; q++) {
279 if (*q == '-') sp->minus = 1;
280 else if (*q == '+') sp->plus = 1;
281 else if (*q == ' ') sp->space = 1;
282 else if (*q == '#') sp->alt = 1;
283 else if (*q == '0') sp->zero = 1;
284 else break;
285 }
286 if (*q == '*') { sp->star_w = 1; q++; }
287 else if (*q >= '1' && *q <= '9') {
288 int w = 0;
289 while (*q >= '0' && *q <= '9') { if (w <= PF_MAX_WIDTH) w = w * 10 + (*q - '0'); q++; }
290 sp->width = w;
291 }
292 if (*q == '.') {
293 q++;
294 if (*q == '*') { sp->star_p = 1; q++; }
295 else {
296 int pr = 0;
297 while (*q >= '0' && *q <= '9') { if (pr <= PF_MAX_WIDTH) pr = pr * 10 + (*q - '0'); q++; }
298 sp->prec = pr;
299 }
300 }
301 while (*q == 'h' || *q == 'l' || *q == 'j' || *q == 'z' || *q == 't' || *q == 'L') q++;
302 if (!is_conv(*q)) { *bad = *q; return 0; }
303 sp->conv = *q++;
304 return (int)(q - p);
305}
306
307typedef struct { char *p; size_t n, cap; int oom; } Buf;
308
309static void buf_add(Buf *b, const char *s, size_t n)
310{
311 if (b->oom) return;
312 if (b->n + n + 1 > b->cap) {
313 size_t cap = b->cap ? b->cap : 64;
314 while (cap < b->n + n + 1) cap *= 2;
315 char *np = realloc(b->p, cap);
316 if (!np) { b->oom = 1; return; }
317 b->p = np;
318 b->cap = cap;
319 }
320 memcpy(b->p + b->n, s, n);
321 b->n += n;
322 b->p[b->n] = 0;
323}
324
325static void buf_ch(Buf *b, char ch) { buf_add(b, &ch, 1); }
326
327/* bash's $'...' form: \a \b \t \n \v \f \r \E, \\ and \', other control bytes as three-digit octal; bytes above
328 * 0x7f as octal when octal_high (declare -x) or raw (%q). */
329static void ansi_c_quote(Buf *b, const char *v, int octal_high)
330{
331 buf_add(b, "$'", 2);
332 for (const unsigned char *q = (const unsigned char *)v; *q; q++) {
333 const char *esc = NULL;
334 switch (*q) {
335 case '\a': esc = "\\a"; break; case '\b': esc = "\\b"; break; case '\t': esc = "\\t"; break;
336 case '\n': esc = "\\n"; break; case '\v': esc = "\\v"; break; case '\f': esc = "\\f"; break;
337 case '\r': esc = "\\r"; break; case 0x1b: esc = "\\E"; break;
338 case '\\': esc = "\\\\"; break; case '\'': esc = "\\'"; break;
339 }
340 if (esc) { buf_add(b, esc, strlen(esc)); continue; }
341 if (*q < 0x20 || *q == 0x7f || (*q >= 0x80 && octal_high)) {
342 char oct[5];
343 snprintf(oct, sizeof oct, "\\%03o", *q);
344 buf_add(b, oct, 4);
345 continue;
346 }
347 buf_ch(b, (char)*q);
348 }
349 buf_ch(b, '\'');
350}
351
352/* %q: bash's sh_backslash_quote. Empty is ''; a control byte switches to $'...'; otherwise a backslash before
353 * space and the shell's special characters, and before ~ or # only at the start. Bytes above 0x7f pass raw. */
354static void quote_q(Buf *b, const char *v)
355{
356 if (!*v) { buf_add(b, "''", 2); return; }
357 for (const unsigned char *q = (const unsigned char *)v; *q; q++)
358 if (*q < 0x20 || *q == 0x7f) { ansi_c_quote(b, v, 0); return; }
359 for (const char *q = v; *q; q++) {
360 if (strchr(" `\"'\\$&()|;<>?![]*{},^", *q) || ((*q == '~' || *q == '#') && q == v)) buf_ch(b, '\\');
361 buf_ch(b, *q);
362 }
363}
364
365static void buf_utf8(Buf *b, unsigned long cp)
366{
367 char u[4];
368 int n;
369 if (cp < 0x80) { u[0] = (char)cp; n = 1; }
370 else if (cp < 0x800) { u[0] = (char)(0xc0 | (cp >> 6)); u[1] = (char)(0x80 | (cp & 0x3f)); n = 2; }
371 else if (cp < 0x10000) { u[0] = (char)(0xe0 | (cp >> 12)); u[1] = (char)(0x80 | ((cp >> 6) & 0x3f)); u[2] = (char)(0x80 | (cp & 0x3f)); n = 3; }
372 else { u[0] = (char)(0xf0 | (cp >> 18)); u[1] = (char)(0x80 | ((cp >> 12) & 0x3f)); u[2] = (char)(0x80 | ((cp >> 6) & 0x3f)); u[3] = (char)(0x80 | (cp & 0x3f)); n = 4; }
373 buf_add(b, u, (size_t)n);
374}
375
376/* %b argument: bash's escape set. Returns 1 when \c was seen (all further output stops). */
377static int expand_b(Buf *b, const char *v)
378{
379 for (const char *p = v; *p; p++) {
380 if (*p != '\\') { buf_ch(b, *p); continue; }
381 char e = p[1];
382 static const char esc_from[] = "abeEfnrtv\\'\"", esc_to[] = "\a\b\033\033\f\n\r\t\v\\'\"";
383 const char *m = e ? strchr(esc_from, e) : NULL;
384 if (m) { buf_ch(b, esc_to[m - esc_from]); p++; continue; }
385 if (e == 'c') return 1;
386 if (e >= '0' && e <= '7') {
387 int v8 = 0, k = 0, lim = e == '0' ? 4 : 3; /* \0nnn: up to three digits after the 0; \nnn: up to three */
388 while (k < lim && p[1] >= '0' && p[1] <= '7') { v8 = v8 * 8 + (p[1] - '0'); p++; k++; }
389 buf_ch(b, (char)(v8 & 0xff));
390 continue;
391 }
392 if (e == 'x' || e == 'u' || e == 'U') {
393 int lim = e == 'x' ? 2 : e == 'u' ? 4 : 8, k = 0;
394 unsigned long cp = 0;
395 const char *q = p + 2;
396 while (k < lim && isxdigit((unsigned char)*q)) { cp = cp * 16 + (unsigned long)(isdigit((unsigned char)*q) ? *q - '0' : (tolower((unsigned char)*q) - 'a' + 10)); q++; k++; }
397 if (k == 0) { buf_ch(b, '\\'); continue; } /* no digits: backslash kept, letter follows normally */
398 if (e == 'x') buf_ch(b, (char)(cp & 0xff)); else buf_utf8(b, cp);
399 p = q - 1;
400 continue;
401 }
402 buf_ch(b, '\\'); /* unknown escape: both bytes verbatim, as bash does */
403 if (!e) break;
404 }
405 return 0;
406}
407
408/* Pad with spaces to the width, honouring '-'. bash pads %s %c %b %q with spaces even under the 0 flag. */
409static void pad_out(Out *o, const char *s, size_t len, const PfSpec *sp)
410{
411 size_t w = sp->width > 0 ? (size_t)sp->width : 0;
412 if (!sp->minus) for (size_t k = len; k < w; k++) out_bytes(o, " ", 1);
413 out_bytes(o, s, len);
414 if (sp->minus) for (size_t k = len; k < w; k++) out_bytes(o, " ", 1);
415}
416
417/* Numeric conversions go through snprintf with the spec rebuilt from the parsed fields (no `*` reaches it). */
418static int num_out(Out *o, const PfSpec *sp, intmax_t sv, uintmax_t u, long double ld)
419{
420 char spec[64];
421 int n = 0;
422 spec[n++] = '%';
423 if (sp->minus) spec[n++] = '-';
424 if (sp->plus) spec[n++] = '+';
425 if (sp->space) spec[n++] = ' ';
426 if (sp->alt) spec[n++] = '#';
427 if (sp->zero) spec[n++] = '0';
428 if (sp->width >= 0) n += snprintf(spec + n, sizeof spec - (size_t)n, "%d", sp->width);
429 if (sp->prec >= 0) n += snprintf(spec + n, sizeof spec - (size_t)n, ".%d", sp->prec);
430 int isf = strchr("eEfFgGaA", sp->conv) != NULL, isd = sp->conv == 'd' || sp->conv == 'i';
431 spec[n++] = isf ? 'L' : 'j';
432 spec[n++] = sp->conv;
433 spec[n] = 0;
434 int len = isf ? snprintf(NULL, 0, spec, ld) : isd ? snprintf(NULL, 0, spec, sv) : snprintf(NULL, 0, spec, u);
435 if (len < 0) return -1;
436 char *buf = malloc((size_t)len + 1);
437 if (!buf) return -1;
438 if (isf) snprintf(buf, (size_t)len + 1, spec, ld);
439 else if (isd) snprintf(buf, (size_t)len + 1, spec, sv);
440 else snprintf(buf, (size_t)len + 1, spec, u);
441 out_bytes(o, buf, (size_t)len);
442 free(buf);
443 return 0;
444}
445
446/* An integer argument as bash reads it: 'x or "x is the byte value, otherwise strtoimax/strtoumax base 0;
447 * trailing junk or overflow is "invalid number" (status 1) with the parsed prefix (0 if none). */
448static int pf_int(const char *arg, int is_signed, intmax_t *sv, uintmax_t *u, int fd_err, int *status)
449{
450 *sv = 0; *u = 0;
451 if (!arg || !*arg) return 0;
452 if (arg[0] == '\'' || arg[0] == '"') { *u = (unsigned char)arg[1]; *sv = (intmax_t)*u; return 0; }
453 char *end;
454 errno = 0;
455 if (is_signed) *sv = strtoimax(arg, &end, 0); else *u = strtoumax(arg, &end, 0);
456 if (end == arg || *end || errno == ERANGE) {
457 if (end == arg) { *sv = 0; *u = 0; }
458 osh_diag(fd_err, "printf: '%s': invalid number", arg);
459 *status = 1;
460 return 1;
461 }
462 return 0;
463}
464
465static int bi_printf(const OshCmd *c, const int io[3])
466{
467 int ai = 1;
468 if (ai < c->nargv && strcmp(c->argv[ai], "--") == 0) ai++;
469 /* bash takes any other leading -x as an option: -v sets a variable and is refused here (not supported); any other
470 * letter is bash's "invalid option" with the usage line, status 2. Nothing is printed in either case. */
471 else if (ai < c->nargv && c->argv[ai][0] == '-' && c->argv[ai][1]) {
472 if (c->argv[ai][1] == 'v') osh_diag(io[2], "printf: %s: option not supported", c->argv[ai]);
473 else osh_diag(io[2], "printf: -%c: invalid option\nprintf: usage: printf [-v var] format [arguments]", c->argv[ai][1]);
474 return 2;
475 }
476 if (ai >= c->nargv) { /* bash: the bare usage line, no shell-name prefix, status 2 */
477 static const char u[] = "printf: usage: printf [-v var] format [arguments]\n";
478 (void)osh_write_all(io[2], u, sizeof u - 1);
479 return 2;
480 }
481 const char *fmt = c->argv[ai++];
482 int first = ai, nargs = 0; /* arguments one pass over the format consumes */
483 /* Validate EVERY conversion before anything is printed. The scan and the print loop below agree on what a
484 * backslash does: it always takes the next byte with it (a known escape, or an unknown one that is printed
485 * verbatim, as coreutils does), so `\%` is two literal bytes and never starts a conversion. A `%` or `\` that is
486 * the last byte never reads past the terminator. */
487 for (const char *p = fmt; *p; p++) {
488 if (*p == '\\') {
489 if (p[1]) p++;
490 continue;
491 }
492 if (*p != '%') continue;
493 p++;
494 if (*p == '%') continue;
495 PfSpec sp;
496 char bad = 0;
497 int k = pf_parse(p, &sp, &bad);
498 if (!k) {
499 if (!bad) osh_diag(io[2], "printf: `%%%s': missing format character", p);
500 else osh_diag(io[2], "printf: `%c': invalid format character", bad);
501 return 1;
502 }
503 if (sp.width > PF_MAX_WIDTH || sp.prec > PF_MAX_WIDTH) {
504 osh_diag(io[2], "printf: width or precision above %d is not supported", PF_MAX_WIDTH);
505 return 1;
506 }
507 nargs += 1 + sp.star_w + sp.star_p;
508 p += k - 1;
509 }
510 Out o = {.fd = io[1]};
511 int status = 0, ci = first, stop = 0;
512 do {
513 for (const char *p = fmt; *p && !stop; p++) {
514 if (*p == '\\') {
515 char e = p[1];
516 static const char esc_from[] = "\\abfnrtv\"", esc_to[] = "\\\a\b\f\n\r\t\v\"";
517 const char *m = e ? strchr(esc_from, e) : NULL;
518 if (m) {
519 out_bytes(&o, &esc_to[m - esc_from], 1);
520 p++;
521 } else if (e >= '0' && e <= '7') {
522 int v = 0, k = 0;
523 while (k < 3 && p[1] >= '0' && p[1] <= '7') { v = v * 8 + (p[1] - '0'); p++; k++; }
524 char b = (char)(v & 0xff);
525 out_bytes(&o, &b, 1);
526 } else if (e) {
527 out_bytes(&o, p, 2); /* unknown escape: both bytes verbatim, as coreutils does */
528 p++;
529 } else {
530 out_bytes(&o, p, 1); /* lone trailing backslash */
531 }
532 } else if (*p != '%') {
533 out_bytes(&o, p, 1);
534 } else {
535 p++;
536 if (*p == '%') { out_bytes(&o, "%", 1); continue; }
537 PfSpec sp;
538 char bad;
539 int k = pf_parse(p, &sp, &bad);
540 if (!k) break; /* unreachable: the scan admitted every specification */
541 p += k - 1;
542 if (sp.star_w) {
543 intmax_t sv; uintmax_t u;
544 pf_int(ci < c->nargv ? c->argv[ci++] : NULL, 1, &sv, &u, io[2], &status);
545 if (sv < 0) { sp.minus = 1; sv = -sv; }
546 sp.width = sv > PF_MAX_WIDTH ? PF_MAX_WIDTH : (int)sv;
547 }
548 if (sp.star_p) {
549 intmax_t sv; uintmax_t u;
550 pf_int(ci < c->nargv ? c->argv[ci++] : NULL, 1, &sv, &u, io[2], &status);
551 sp.prec = sv < 0 ? -1 : sv > PF_MAX_WIDTH ? PF_MAX_WIDTH : (int)sv;
552 }
553 const char *arg = ci < c->nargv ? c->argv[ci++] : NULL;
554 if (sp.conv == 's') {
555 size_t len = arg ? strlen(arg) : 0;
556 if (sp.prec >= 0 && (size_t)sp.prec < len) len = (size_t)sp.prec;
557 pad_out(&o, arg ? arg : "", len, &sp);
558 } else if (sp.conv == 'c') {
559 char ch = arg && *arg ? arg[0] : 0; /* coreutils: an empty or missing argument prints a NUL byte */
560 pad_out(&o, &ch, 1, &sp);
561 } else if (sp.conv == 'b' || sp.conv == 'q') {
562 Buf b = {0};
563 if (sp.conv == 'b') stop = expand_b(&b, arg ? arg : "");
564 else quote_q(&b, arg ? arg : "");
565 if (b.oom) { free(b.p); osh_diag(io[2], "printf: out of memory"); out_flush(&o); return 1; }
566 size_t len = b.n;
567 if (sp.prec >= 0 && (size_t)sp.prec < len) len = (size_t)sp.prec;
568 pad_out(&o, b.p ? b.p : "", len, &sp);
569 free(b.p);
570 } else if (strchr("eEfFgGaA", sp.conv)) {
571 long double ld = 0;
572 if (arg && (arg[0] == '\'' || arg[0] == '"')) ld = (unsigned char)arg[1];
573 else if (arg && *arg) {
574 char *end;
575 errno = 0;
576 ld = strtold(arg, &end);
577 if (end == arg || *end || errno == ERANGE) {
578 if (end == arg) ld = 0;
579 osh_diag(io[2], "printf: '%s': invalid number", arg);
580 status = 1;
581 }
582 }
583 if (num_out(&o, &sp, 0, 0, ld)) { osh_diag(io[2], "printf: out of memory"); out_flush(&o); return 1; }
584 } else {
585 intmax_t sv; uintmax_t u;
586 pf_int(arg, sp.conv == 'd' || sp.conv == 'i', &sv, &u, io[2], &status);
587 if (num_out(&o, &sp, sv, u, 0)) { osh_diag(io[2], "printf: out of memory"); out_flush(&o); return 1; }
588 }
589 }
590 }
591 } while (!stop && nargs > 0 && ci < c->nargv);
592 out_flush(&o);
593 if (o.err) { osh_diag(io[2], "printf: write error: %s", strerror(o.err)); return 1; }
594 return status;
595}
596
597/* ---------------- export / unset / exit ---------------- */
598
599static int cmp_var(const void *a, const void *b)
600{
601 return strcmp((*(const OshVar *const *)a)->name, (*(const OshVar *const *)b)->name);
602}
603
604/* `declare -x NAME="value"` quoting as bash 5.2 prints it: double quotes with \ before " \ $ `; when the value holds
605 * a control or non-ASCII byte, bash's $'...' form (ansi_c_quote, octal for bytes above 0x7f). */
606static void out_declare_value(Out *o, const char *v)
607{
608 int ansi = 0;
609 for (const unsigned char *q = (const unsigned char *)v; *q; q++)
610 if (*q < 0x20 || *q >= 0x7f) { ansi = 1; break; }
611 if (!ansi) {
612 out_bytes(o, "\"", 1);
613 for (const char *q = v; *q; q++) {
614 if (*q == '"' || *q == '\\' || *q == '$' || *q == '`') out_bytes(o, "\\", 1);
615 out_bytes(o, q, 1);
616 }
617 out_bytes(o, "\"", 1);
618 return;
619 }
620 Buf b = {0};
621 ansi_c_quote(&b, v, 1);
622 if (!b.oom) out_bytes(o, b.p, b.n);
623 free(b.p);
624}
625
626/* export [-fn] [name[=value] ...] | export -p (bash 5.2 shape, #344 RISK-6)
627 * -p with no names lists `declare -x` lines sorted by name; -p with names is a plain export and prints nothing.
628 * -n assigns NAME=value if given, then drops the export mark but keeps the variable. -f names functions, which osh
629 * does not have, so every -f name is "not a function" (status 1). An unknown option is status 2 with the usage line. */
630static int bi_export(OshSession *s, const OshCmd *c, const int io[3])
631{
632 int i = 1, status = 0, unexport = 0, fn = 0;
633 for (; i < c->nargv && c->argv[i][0] == '-' && c->argv[i][1]; i++) {
634 if (strcmp(c->argv[i], "--") == 0) { i++; break; }
635 for (const char *p = c->argv[i] + 1; *p; p++) {
636 if (*p == 'n') unexport = 1;
637 else if (*p == 'f') fn = 1;
638 else if (*p != 'p') {
639 osh_diag(io[2], "export: -%c: invalid option\nexport: usage: export [-fn] [name[=value] ...] or export -p", *p);
640 return 2;
641 }
642 }
643 }
644 if (i >= c->nargv) {
645 const OshVar **v = malloc((s->nvars + 1) * sizeof *v);
646 if (!v) return 1;
647 size_t n = 0;
648 for (size_t k = 0; k < s->nvars; k++)
649 if (s->vars[k].exported) v[n++] = &s->vars[k];
650 qsort(v, n, sizeof *v, cmp_var);
651 Out o = {.fd = io[1]};
652 for (size_t k = 0; k < n; k++) {
653 out_bytes(&o, "declare -x ", 11);
654 out_bytes(&o, v[k]->name, strlen(v[k]->name));
655 if (v[k]->value) { out_bytes(&o, "=", 1); out_declare_value(&o, v[k]->value); }
656 out_bytes(&o, "\n", 1);
657 }
658 out_flush(&o);
659 free(v);
660 return o.err ? 1 : 0;
661 }
662 for (; i < c->nargv; i++) {
663 const char *a = c->argv[i], *eq = strchr(a, '=');
664 char name[256];
665 size_t nl = eq ? (size_t)(eq - a) : strlen(a);
666 if (fn) { osh_diag(io[2], "export: %s: not a function", a); status = 1; continue; }
667 if (nl == 0 || nl >= sizeof name) { osh_diag(io[2], "export: `%s': not a valid identifier", a); status = 1; continue; }
668 memcpy(name, a, nl);
669 name[nl] = 0;
670 if (!osh_name_valid(name)) { osh_diag(io[2], "export: `%s': not a valid identifier", a); status = 1; continue; }
671 if (unexport) {
672 if (eq && osh_var_set(s, name, eq + 1)) { osh_diag(io[2], "export: out of memory"); status = 1; continue; }
673 osh_var_unexport(s, name);
674 } else if (osh_var_export(s, name, eq ? eq + 1 : NULL)) { osh_diag(io[2], "export: out of memory"); status = 1; }
675 }
676 return status;
677}
678
679static int bi_unset(OshSession *s, const OshCmd *c, const int io[3])
680{
681 int i = 1, status = 0;
682 for (; i < c->nargv && c->argv[i][0] == '-' && c->argv[i][1]; i++) {
683 if (strcmp(c->argv[i], "-v") == 0) continue;
684 if (strcmp(c->argv[i], "--") == 0) { i++; break; }
685 osh_diag(io[2], "unset: -%c: invalid option\nunset: usage: unset [-f] [-v] [-n] [name ...]", c->argv[i][1]);
686 return 2;
687 }
688 for (; i < c->nargv; i++) {
689 if (!osh_name_valid(c->argv[i])) continue; /* bash 5.2: unset of a non-identifier is silent and succeeds (omega#344) */
690 osh_var_unset(s, c->argv[i]);
691 }
692 return status;
693}
694
695static int bi_exit(OshSession *s, const OshCmd *c, const int io[3], int in_parent)
696{
697 int st = s->last_status & 0xff;
698 if (c->nargv > 2) {
699 osh_diag(io[2], "exit: too many arguments");
700 if (in_parent) s->abort_list = 1; /* bash: no exit, status 1, the rest of this list is not run */
701 return 1;
702 }
703 if (c->nargv == 2) {
704 char *end;
705 errno = 0;
706 long v = strtol(c->argv[1], &end, 10);
707 if (end == c->argv[1] || *end || errno == ERANGE) {
708 osh_diag(io[2], "exit: %s: numeric argument required", c->argv[1]);
709 st = 2;
710 } else {
711 st = (int)(v & 0xff);
712 }
713 }
714 if (in_parent) { s->exit_requested = 1; s->exit_status = st; }
715 return st;
716}
717
718int osh_builtin_run(OshSession *s, const OshCmd *c, const int io[3], int in_parent)
719{
720 switch (c->builtin_id) {
721 case OSH_B_CD: return bi_cd(s, c, io, in_parent);
722 case OSH_B_PWD: return bi_pwd(s, c, io);
723 case OSH_B_PRINTF: return bi_printf(c, io);
724 case OSH_B_EXPORT: return bi_export(s, c, io);
725 case OSH_B_UNSET: return bi_unset(s, c, io);
726 case OSH_B_EXIT: return bi_exit(s, c, io, in_parent);
727 default: return 1;
728 }
729}