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_exec.c

874 lines · 39350 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_exec.c -- execution service of the Linux host adapter (OSH_PLATFORM_ABI.md sections 7.2, 8.3, 8.4, 9, 10, 11, 12).
19 *
20 * DECISIONS where the ABI draft is silent (all UNVERIFIED against a second implementation; flagged in the PR):
21 * - Resolution classes: a request record carries no class. The adapter asks OshClassHook (RESOLVE). Anything other
22 * than OSH_CLASS_LINUX (omega native op, AIENOS artifact/service) is REFUSED for the whole pipeline before any
23 * effect: status 126, platform error UNAVAILABLE, each command FAILED_NO_EFFECT. Never forwarded, never retried
24 * as a Linux path. Without a hook every name is a Linux executable.
25 * - Authority: spawn/chdir/open-for-write need a valid binding (domain 1 or 2; domain 1 with generation above
26 * 0xFFFFFFFF is CAP_GEN_NARROW) and the PERM_CHECK hook. Failure: nothing runs, status 126, err DENIED (or the
27 * hook's reason). A Linux host has no capability authority: the embedder supplies the binding.
28 * - PATH comes from the shell's table (a prefix assignment PATH=... on the command counts, as in bash). PATH unset:
29 * bare names are not found (127); process-global environ is never consulted after osh_session_init. An empty
30 * element means the current directory (POSIX). Names containing '/' are used as given, never searched.
31 * - Statuses: not found 127; found but not executable, a directory, or execve refused (including ENOEXEC: a script
32 * without a shebang is NOT run through sh) 126; killed by signal 128+n, with a "Name (signal n)" line on stderr except for SIGINT and SIGPIPE (bash prints "Killed" and "Terminated" too).
33 * - STOPPED MEMBERS (no job control in R1): the wait loop notices a stop of ANY member (SIGSTOP, SIGTSTP, ...), sends
34 * SIGKILL to the pipeline (killpg when it has its own group, else to each unreaped member), reaps all, writes a
35 * diagnostic, and the pipeline status is 128+stopsig of the first member seen stopped. The stopped member is
36 * CANCELLED with err INTERRUPTED; members killed by that SIGKILL are CANCELLED too (termsig 9). Same for
37 * interactive and non-interactive sessions. Job control (fg/bg, resuming) is R1.2+.
38 * - PROCESS GROUPS AND SIGNALS. Non-interactive (osh -c, scripts, embedder default): no new process group; children
39 * stay in the shell's group, so a terminal ^C or a pgroup SIGINT reaches them and the shell together. While
40 * waiting, the shell does not die of SIGINT/SIGQUIT: it notes them (result sigint_seen) and acts on the child's
41 * status. If the last command died of SIGINT/SIGQUIT the session sets exit_requested with exit_status 128+sig
42 * (130 for SIGINT) after the pipeline, as bash does for scripts; osh_run_list stops there. A SIGINT sent only to
43 * the shell pid is not forwarded (nothing is in a separate group). If SIGINT/SIGQUIT were ignored when osh_exec
44 * was entered, they stay ignored and the children inherit that (POSIX). Interactive (s->interactive): every
45 * pipeline is its own process group; with tty_fd the shell hands it the terminal (tcsetpgrp) and takes the terminal
46 * back afterwards; the shell ignores SIGINT/SIGQUIT/SIGTSTP/SIGTTOU/SIGTTIN itself (noted, never fatal); a ^C goes
47 * to the foreground group = the pipeline; a SIGINT/SIGQUIT sent to the shell pid while it waits is forwarded once to
48 * the pipeline's group (killpg). Interactive children always start with default dispositions; the interactive
49 * session does not exit when a child dies of SIGINT (osh_run_list only stops the list). SIGINT/SIGQUIT stay blocked
50 * across fork so a signal cannot run the shell's handler inside a new child.
51 * - A failed redirection prints a diagnostic, the command does not run, its status is 1; its pipe ends are closed so
52 * neighbours see EOF/SIGPIPE. Redirections are applied in the CHILD for external commands (so opening a FIFO cannot
53 * deadlock the parent) and in the parent (on a private descriptor table, never on fds 0-2) for parent builtins and
54 * standalone assignments. A parent-side redirection of a FIFO with no peer therefore BLOCKS the shell in open(),
55 * exactly as bash does (`cd < fifo`, `A=1 > fifo`); only a signal ends it. Intentionally not worked around.
56 * - Standalone assignment (empty argv): redirections first, then variables set in the session; inside a multi-command
57 * pipeline it runs in a child and has no effect on the parent.
58 * - Fork failure after some commands started: PARTIAL_LAUNCH; the started ones get SIGTERM+SIGCONT (to their group
59 * when interactive, else to each pid) and are reaped (outcome CANCELLED); not-yet-started commands are NOT_STARTED; status 1.
60 * - waitpid ECHILD for a started child (someone else reaped it): that command is OUTCOME_UNKNOWN, status 1, err
61 * OUTCOME_UNKNOWN. A pipeline whose last command died of SIGINT/SIGQUIT sets killed_by_int and osh_run_list stops there.
62 * - DURABLE INTENT/OUTCOME (ABI section 10), when s->journal is set (osh_journal.h; the osh program always sets it).
63 * An effect is one external spawn or one write-class open (output/append redirection), so a command is an effect
64 * iff it is external or has such a redirection; builtins, standalone assignments and read-only/dup redirections
65 * are not (section 10 defines the term that way). Just before each effect an INTENT record is appended and fsynced
66 * (file; directory on creation); if that fails the command is NOT launched (FAILED_NO_EFFECT, err IO, status 1:
67 * mandatory records fail closed). After the pipeline is reaped one OUTCOME record per effect is appended and fsynced:
68 * a refusal or denial before the intent is an outcome with no intent (ref 0, FAILED_NO_EFFECT, nothing launched), a
69 * command never reached is NOT_STARTED. ONE ACCOUNT: the record and the result give the same outcome
70 * for every command. A command that died of a signal it was sent (^C, kill) is COMPLETED with status 128+sig
71 * (ABI 8.4 exit status convention); CANCELLED is the adapter's own act (stopped member, partial-launch cleanup). If an
72 * outcome cannot be made durable the intent stays open (recovery reports it UNKNOWN) and res->journal_failed is set.
73 * Recovery never launches anything. The journal holds no argument values (osh_journal.h, redaction rule). Without
74 * s->journal and without s->journal_required nothing is written and behaviour is unchanged (library embedders). With
75 * journal_required set and no journal open (the osh program when the journal cannot be opened) every effect is refused with
76 * a named diagnostic (status 1, FAILED_NO_EFFECT, err IO); commands that are not effects still run.
77 */
78#ifndef _GNU_SOURCE
79#define _GNU_SOURCE
80#endif
81#include "osh_host.h"
82#include "osh_priv.h"
83#include "osh_journal.h"
84
85#include <errno.h>
86#include <fcntl.h>
87#include <limits.h>
88#include <signal.h>
89#include <stdlib.h>
90#include <string.h>
91#include <sys/stat.h>
92#include <sys/types.h>
93#include <sys/wait.h>
94#include <unistd.h>
95
96/* ---------------- signals ---------------- */
97
98static volatile sig_atomic_t g_sig_seen, g_sig_count;
99static void on_sig(int sig) { g_sig_seen = sig; g_sig_count++; }
100static void on_chld(int sig) { (void)sig; } /* only here so that sigsuspend wakes on a child state change */
101
102static const int k_sigs[] = {SIGINT, SIGQUIT, SIGTSTP, SIGTTOU, SIGTTIN, SIGPIPE, SIGCHLD};
103#define NSIGS ((int)(sizeof k_sigs / sizeof k_sigs[0]))
104
105/* SIGINT / SIGQUIT were ignored when osh_exec was entered (nohup, `cmd &` in a parent shell, an embedder choice).
106 * POSIX: a non-interactive shell leaves them ignored and its children inherit that. Set by guard_enter. */
107static int g_entry_ign[2];
108
109typedef struct {
110 struct sigaction old[NSIGS];
111} SigGuard;
112
113static void guard_enter(SigGuard *g, int interactive)
114{
115 g_sig_seen = 0;
116 g_sig_count = 0;
117 g_entry_ign[0] = g_entry_ign[1] = 0;
118 for (int i = 0; i < NSIGS; i++) {
119 struct sigaction sa;
120 memset(&sa, 0, sizeof sa);
121 sigemptyset(&sa.sa_mask);
122 int sig = k_sigs[i];
123 sigaction(sig, NULL, &g->old[i]);
124 if (sig == SIGINT || sig == SIGQUIT) {
125 int ign = g->old[i].sa_handler == SIG_IGN;
126 g_entry_ign[sig == SIGQUIT] = ign && !interactive;
127 /* The shell never dies of these while it waits: it notes them (no SA_RESTART: waitpid/sigsuspend must see
128 * EINTR) and acts on the child's status. An inherited ignore stays an ignore (non-interactive only). */
129 sa.sa_handler = ign && !interactive ? SIG_IGN : on_sig;
130 } else if (sig == SIGCHLD) {
131 sa.sa_handler = on_chld;
132 } else {
133 sa.sa_handler = SIG_IGN; /* TSTP, TTOU, TTIN, PIPE */
134 }
135 sigaction(sig, &sa, NULL);
136 }
137}
138
139static void guard_leave(SigGuard *g)
140{
141 for (int i = 0; i < NSIGS; i++) sigaction(k_sigs[i], &g->old[i], NULL);
142}
143
144/* in a freshly forked child: everything back to default, nothing blocked. The one exception is a non-interactive
145 * shell that inherited SIGINT / SIGQUIT as ignored: its children keep them ignored (POSIX). */
146static void child_signals(void)
147{
148 struct sigaction sa;
149 memset(&sa, 0, sizeof sa);
150 sigemptyset(&sa.sa_mask);
151 sa.sa_handler = SIG_DFL;
152 for (int i = 0; i < NSIGS; i++) sigaction(k_sigs[i], &sa, NULL);
153 sa.sa_handler = SIG_IGN;
154 if (g_entry_ign[0]) sigaction(SIGINT, &sa, NULL);
155 if (g_entry_ign[1]) sigaction(SIGQUIT, &sa, NULL);
156 sigset_t all;
157 sigemptyset(&all);
158 sigprocmask(SIG_SETMASK, &all, NULL);
159}
160
161/* ---------------- resolution ---------------- */
162
163/* 0 executable regular file; 127 missing; 126 present but unusable (errno_out says why) */
164static int check_exec(const char *path, int *why)
165{
166 struct stat st;
167 if (stat(path, &st) != 0) {
168 if (errno == ENOENT || errno == ENOTDIR) { *why = ENOENT; return 127; }
169 *why = errno;
170 return 126;
171 }
172 if (S_ISDIR(st.st_mode)) { *why = EISDIR; return 126; }
173 if (!S_ISREG(st.st_mode) || access(path, X_OK) != 0) { *why = EACCES; return 126; }
174 return 0;
175}
176
177static int resolve_in(const char *pathvar, const char *name, char *out, size_t cap, int *why)
178{
179 *why = ENOENT;
180 if (!*name) return 127;
181 if (strchr(name, '/')) {
182 if (strlen(name) >= cap) { *why = ENAMETOOLONG; return 126; }
183 strcpy(out, name);
184 return check_exec(out, why);
185 }
186 if (!pathvar) return 127;
187 int denied = 0;
188 const char *p = pathvar;
189 for (;;) {
190 const char *e = strchr(p, ':');
191 size_t dl = e ? (size_t)(e - p) : strlen(p);
192 const char *dir = dl ? p : ".";
193 if (!dl) dl = 1;
194 if (dl + 1 + strlen(name) + 1 <= cap) {
195 memcpy(out, dir, dl);
196 out[dl] = '/';
197 strcpy(out + dl + 1, name);
198 int w, rc = check_exec(out, &w);
199 if (rc == 0) return 0;
200 if (rc == 126 && w == EACCES) denied = 1; /* a file named so exists but cannot run; keep looking */
201 }
202 if (!e) break;
203 p = e + 1;
204 }
205 *why = denied ? EACCES : ENOENT;
206 return denied ? 126 : 127;
207}
208
209int osh_resolve_linux(const OshSession *s, const char *name, char *out, size_t outsz)
210{
211 int why;
212 return resolve_in(osh_var_get(s, "PATH"), name, out, outsz, &why);
213}
214
215static const char *cmd_path_var(const OshSession *s, const OshCmd *c)
216{
217 const char *p = osh_var_get(s, "PATH");
218 for (int i = 0; i < c->nassign; i++)
219 if (strcmp(c->assign[i].name, "PATH") == 0) p = c->assign[i].value;
220 return p;
221}
222
223/* ---------------- authority ---------------- */
224
225static int authorize(const OshSession *s, const OshRequest *r)
226{
227 int ops = 0;
228 for (int i = 0; i < r->ncmds; i++) {
229 const OshCmd *c = &r->cmd[i];
230 if (c->nargv > 0 && c->builtin_id == OSH_B_NONE) ops |= 1 << OSH_OP_SPAWN;
231 if (c->builtin_id == OSH_B_CD) ops |= 1 << OSH_OP_CHDIR;
232 for (int k = 0; k < c->nredir; k++)
233 if (c->redir[k].kind == OSH_R_OUT || c->redir[k].kind == OSH_R_APPEND) ops |= 1 << OSH_OP_OPEN_WRITE;
234 }
235 if (!ops) return OSH_E_OK;
236 const OshBinding *b = &s->binding;
237 if (!b->valid) return OSH_E_DENIED;
238 if (b->domain != 1 && b->domain != 2) return OSH_E_CAP_DOMAIN_MISMATCH;
239 if (b->domain == 1 && b->cap_generation > 0xFFFFFFFFull) return OSH_E_CAP_GEN_NARROW;
240 if (s->perm_hook)
241 for (int op = 1; op <= 3; op++)
242 if (ops & (1 << op)) {
243 int rc = s->perm_hook(s->hook_ctx, b, op);
244 if (rc != OSH_E_OK) return rc;
245 }
246 return OSH_E_OK;
247}
248
249/* ---------------- per-effect authority (ABI section 9.2) ---------------- */
250
251static const char *e_name(int e)
252{
253 switch (e) {
254 case OSH_E_DENIED: return "DENIED";
255 case OSH_E_REVOKED: return "REVOKED";
256 case OSH_E_STALE: return "STALE";
257 case OSH_E_CAP_DOMAIN_MISMATCH: return "CAP_DOMAIN_MISMATCH";
258 case OSH_E_CAP_GEN_NARROW: return "CAP_GEN_NARROW";
259 default: return "REFUSED";
260 }
261}
262
263int osh_effect_check(const OshSession *s, int op, const char *path, int diagfd)
264{
265 if (!s->effect_hook) return OSH_E_OK;
266 int rc = s->effect_hook(s->effect_ctx, &s->binding, op, path);
267 if (rc == OSH_E_OK) return OSH_E_OK;
268 const char *what = op == OSH_OP_SPAWN ? "spawn" : op == OSH_OP_CHDIR ? "cd" : op == OSH_OP_OPEN_WRITE ? "write" : "read";
269 osh_diag(diagfd, "%s %s: denied (%s); nothing was done", what, path, e_name(rc));
270 return rc;
271}
272
273/* ---------------- descriptor tables and redirections ---------------- */
274
275typedef struct {
276 int fd[3];
277 int own[OSH_MAX_REDIR];
278 int nown;
279} FdTab;
280
281static void tab_init(FdTab *t, const OshSession *s)
282{
283 for (int i = 0; i < 3; i++) t->fd[i] = s->fd[i];
284 t->nown = 0;
285}
286
287static void tab_close_owned(FdTab *t)
288{
289 while (t->nown > 0) close(t->own[--t->nown]);
290}
291
292/* move fd to a CLOEXEC descriptor >= 10; always consumes fd */
293static int to_high(int fd)
294{
295 int h = fcntl(fd, F_DUPFD_CLOEXEC, 10);
296 int saved = errno;
297 close(fd);
298 errno = saved;
299 return h;
300}
301
302/* Apply redirections in record order on the table. 0 ok; -1 failed (diagnostic written to diagfd, owned fds stay
303 * recorded in the table so the caller can close them). Every descriptor opened here is O_CLOEXEC. */
304static int apply_redirs(const OshSession *s, FdTab *t, const OshCmd *c, int diagfd, int *err)
305{
306 for (int i = 0; i < c->nredir; i++) {
307 const OshRedir *d = &c->redir[i];
308 int nfd;
309 if (d->kind == OSH_R_DUP) {
310 nfd = fcntl(t->fd[d->src_fd], F_DUPFD_CLOEXEC, 10);
311 if (nfd < 0) { osh_diag(diagfd, "%d>&%d: %s", d->fd, d->src_fd, strerror(errno)); return -1; }
312 } else {
313 int ge = osh_effect_check(s, d->kind == OSH_R_IN ? OSH_OP_OPEN_READ : OSH_OP_OPEN_WRITE, d->path, diagfd);
314 if (ge != OSH_E_OK) { if (err) *err = ge; return -1; }
315 int fl = d->kind == OSH_R_IN ? O_RDONLY : O_WRONLY | O_CREAT | (d->kind == OSH_R_APPEND ? O_APPEND : O_TRUNC);
316 nfd = open(d->path, fl | O_CLOEXEC, 0666);
317 if (nfd >= 0 && nfd < 10) nfd = to_high(nfd);
318 if (nfd < 0) { osh_diag(diagfd, "%s: %s", d->path, strerror(errno)); return -1; }
319 }
320 t->own[t->nown++] = nfd;
321 t->fd[d->fd] = nfd;
322 }
323 return 0;
324}
325
326/* child only: make table entries the real descriptors 0..2 */
327static int child_install(FdTab *t)
328{
329 for (int i = 0; i < 3; i++)
330 if (t->fd[i] < 3 && t->fd[i] != i) {
331 int h = fcntl(t->fd[i], F_DUPFD_CLOEXEC, 10);
332 if (h < 0) return -1;
333 t->fd[i] = h;
334 }
335 for (int i = 0; i < 3; i++) {
336 if (t->fd[i] == i) { if (fcntl(i, F_SETFD, 0) < 0) return -1; }
337 else if (dup2(t->fd[i], i) < 0) return -1;
338 }
339 return 0;
340}
341
342/* ---------------- running one command ---------------- */
343
344typedef struct {
345 int pp[OSH_MAX_CMDS][2]; /* pipe i connects command i (write end) to command i+1 (read end) */
346 int n;
347} Pipes;
348
349static void close_pipes(Pipes *p)
350{
351 for (int i = 0; i < p->n; i++)
352 for (int e = 0; e < 2; e++)
353 if (p->pp[i][e] >= 0) { close(p->pp[i][e]); p->pp[i][e] = -1; }
354}
355
356static void set_cmd(OshCmdResult *r, int status, int outcome, int err)
357{
358 r->status = status;
359 r->outcome = outcome;
360 r->err = err;
361}
362
363static void fail_all(OshResult *res, int n, int status, int err)
364{
365 for (int i = 0; i < n; i++) set_cmd(&res->cmd[i], status, OSH_OUT_FAILED_NO_EFFECT, err);
366 res->status = status;
367 res->err = err;
368}
369
370/* ---------------- durable intent/outcome (ABI section 10) ---------------- */
371
372typedef struct {
373 OshJournal *j;
374 int required; /* mandatory journal: no journal means every effect is refused */
375 const char *why;
376 uint8_t dig[32];
377 uint64_t ref[OSH_MAX_CMDS]; /* intent rec per command, 0 = none */
378} JCtx;
379
380/* an effect per ABI section 10: one external spawn or one write-class open */
381static int cmd_effect(const OshCmd *c)
382{
383 if (c->nargv > 0 && c->builtin_id == OSH_B_NONE) return 1;
384 for (int k = 0; k < c->nredir; k++)
385 if (c->redir[k].kind == OSH_R_OUT || c->redir[k].kind == OSH_R_APPEND) return 1;
386 return 0;
387}
388
389static void jc_init(JCtx *jc, OshSession *s, const OshRequest *r)
390{
391 memset(jc, 0, sizeof *jc);
392 jc->j = s->journal;
393 jc->required = s->journal_required && !s->journal;
394 jc->why = s->journal_error ? s->journal_error : "not opened";
395 if (jc->j) osh_req_digest(jc->j, r, jc->dig);
396}
397
398/* 0: durable (or no journal / not an effect); -1: the intent could not be made durable and the effect must not run */
399static int jc_intent(JCtx *jc, const OshRequest *r, int idx)
400{
401 if (jc->required && cmd_effect(&r->cmd[idx])) return -2;
402 if (!jc->j || !cmd_effect(&r->cmd[idx])) return 0;
403 jc->ref[idx] = osh_journal_intent(jc->j, jc->dig, r, idx);
404 return jc->ref[idx] ? 0 : -1;
405}
406
407/* the named refusal: -2 = the journal is not open at all, -1 = the intent record was not durable */
408static void jc_refuse(OshSession *s, const JCtx *jc, int rc)
409{
410 if (rc == -2) osh_diag(s->fd[2], "effect journal unavailable (%s); effect refused, nothing was run", jc->why);
411 else if (jc->j && jc->j->poisoned) osh_diag(s->fd[2], "effect journal failed (a write or fsync did not succeed) and is closed for this session; effect refused, nothing was run");
412 else osh_diag(s->fd[2], "effect journal: intent could not be made durable; effect refused, nothing was run");
413}
414
415static int jc_outcome(const OshCmdResult *c) { return c->outcome; } /* one account: the record says exactly what the result says */
416
417/* one outcome per effect, one write, one fsync */
418static void jc_finish(JCtx *jc, const OshRequest *r, OshResult *res)
419{
420 if (!jc->j) return;
421 OshJournalOutcome o[OSH_MAX_CMDS];
422 int n = 0;
423 for (int i = 0; i < r->ncmds; i++) {
424 if (!cmd_effect(&r->cmd[i])) continue;
425 o[n].idx = i;
426 o[n].ref = jc->ref[i];
427 o[n].outcome = jc_outcome(&res->cmd[i]);
428 o[n].status = res->cmd[i].status;
429 o[n].err = res->cmd[i].err;
430 n++;
431 }
432 if (osh_journal_outcomes(jc->j, jc->dig, r->ncmds, o, n) != 0) {
433 res->journal_failed = 1;
434 osh_diag(2, "journal: an outcome could not be made durable; recovery will report it UNKNOWN");
435 }
436}
437
438/* single parent-side command: builtin, or standalone assignment / redirection-only */
439static void run_in_parent(OshSession *s, const OshRequest *rq, JCtx *jc, OshResult *res)
440{
441 const OshCmd *c = &rq->cmd[0];
442 FdTab t;
443 tab_init(&t, s);
444 int st;
445 int rerr = OSH_E_IO;
446 int jrc = jc_intent(jc, rq, 0);
447 if (jrc != 0) {
448 jc_refuse(s, jc, jrc);
449 set_cmd(&res->cmd[0], 1, OSH_OUT_FAILED_NO_EFFECT, OSH_E_IO);
450 res->status = 1;
451 return;
452 }
453 if (apply_redirs(s, &t, c, s->fd[2], &rerr) != 0) {
454 st = 1;
455 set_cmd(&res->cmd[0], st, OSH_OUT_FAILED_NO_EFFECT, rerr);
456 } else {
457 if (c->builtin_id) st = osh_builtin_run(s, c, t.fd, 1);
458 else {
459 st = 0;
460 for (int i = 0; i < c->nassign; i++)
461 if (osh_var_set(s, c->assign[i].name, c->assign[i].value)) { osh_diag(s->fd[2], "%s: cannot set", c->assign[i].name); st = 1; }
462 }
463 set_cmd(&res->cmd[0], st, OSH_OUT_COMPLETED, OSH_E_OK);
464 }
465 tab_close_owned(&t);
466 res->status = st;
467}
468
469typedef struct {
470 pid_t pid;
471 int done; /* reaped (or lost) */
472 int lost; /* waitpid said ECHILD: somebody else reaped it, the fate is unknown */
473 int stopped; /* stop signal seen */
474 int cancelled; /* we sent it SIGKILL because a member stopped */
475 int st; /* wait status when done */
476} Child;
477
478/* Send sig to every member that is still running. Interactive sessions put the pipeline in its own process group, so
479 * one killpg does it. Non-interactive sessions share the shell's group and must NEVER killpg: signal each pid, which
480 * is safe because an unreaped child's pid cannot be reused. */
481static void signal_kids(const Child *ch, int n, pid_t pgid, int own_pg, int sig)
482{
483 if (own_pg) {
484 if (pgid > 0) killpg(pgid, sig);
485 return;
486 }
487 for (int i = 0; i < n; i++)
488 if (ch[i].pid > 0 && !ch[i].done) kill(ch[i].pid, sig);
489}
490
491/* Wait for every member, noticing a stop of ANY member (not just the one being waited on). R1 has no job control: the
492 * first stop cancels the pipeline with SIGKILL (to the group when there is one, else to each member), then all are
493 * reaped. Returns the first stop signal seen, or 0. While waiting, SIGINT/SIGQUIT delivered to the shell itself are
494 * forwarded to the pipeline's group once per delivery when it has its own group (interactive); a non-interactive
495 * pipeline shares the shell's group and gets the terminal's signal directly, so nothing extra is sent. */
496static int wait_all(OshSession *s, OshResult *res, Child *ch, int n, pid_t pgid, int own_pg)
497{
498 sigset_t blk, old, susp;
499 sigemptyset(&blk);
500 sigaddset(&blk, SIGCHLD);
501 sigaddset(&blk, SIGINT);
502 sigaddset(&blk, SIGQUIT);
503 sigprocmask(SIG_BLOCK, &blk, &old); /* blocked while scanning: sigsuspend then wakes for anything that arrived */
504 susp = old;
505 sigdelset(&susp, SIGCHLD);
506 int pending = 0, first_stop = 0, cancel_sent = 0;
507 for (int i = 0; i < n; i++) if (ch[i].pid > 0) pending++;
508 int seen = 0; /* g_sig_count restarts at 0 for every osh_exec: a signal that landed during launch is forwarded too */
509 while (pending > 0) {
510 for (int i = 0; i < n; i++) {
511 if (ch[i].pid <= 0 || ch[i].done) continue;
512 int st = 0;
513 pid_t w = waitpid(ch[i].pid, &st, WNOHANG | WUNTRACED);
514 if (w == 0) continue;
515 if (w < 0) {
516 if (errno == EINTR) { i--; continue; }
517 ch[i].done = ch[i].lost = 1;
518 pending--;
519 continue;
520 }
521 if (WIFSTOPPED(st)) {
522 if (!ch[i].stopped) {
523 ch[i].stopped = WSTOPSIG(st);
524 if (!first_stop) first_stop = ch[i].stopped;
525 }
526 continue; /* it is killed below; the next pass reaps it */
527 }
528 ch[i].st = st;
529 ch[i].done = 1;
530 pending--;
531 }
532 if (pending == 0) break;
533 if (first_stop && !cancel_sent) {
534 cancel_sent = 1;
535 osh_diag(s->fd[2], "pipeline stopped (signal %d); there is no job control yet, so it is cancelled", first_stop);
536 for (int i = 0; i < n; i++) if (ch[i].pid > 0 && !ch[i].done) ch[i].cancelled = 1;
537 signal_kids(ch, n, pgid, own_pg, SIGKILL);
538 }
539 if (own_pg && !cancel_sent && g_sig_count != seen && pgid > 0) {
540 seen = g_sig_count;
541 killpg(pgid, g_sig_seen == SIGQUIT ? SIGQUIT : SIGINT);
542 }
543 sigsuspend(&susp); /* returns after a handled signal: SIGCHLD, or SIGINT/SIGQUIT noted for the next pass */
544 }
545 sigprocmask(SIG_SETMASK, &old, NULL);
546 for (int i = 0; i < n; i++) {
547 if (ch[i].pid <= 0) continue;
548 OshCmdResult *r = &res->cmd[i];
549 int st = ch[i].st;
550 if (ch[i].lost) {
551 set_cmd(r, 1, OSH_OUT_UNKNOWN, OSH_E_OUTCOME_UNKNOWN); /* fate cannot be determined */
552 } else if (ch[i].stopped) {
553 r->termsig = WIFSIGNALED(st) ? WTERMSIG(st) : 0;
554 set_cmd(r, 128 + ch[i].stopped, OSH_OUT_CANCELLED, OSH_E_INTERRUPTED);
555 } else if (WIFSIGNALED(st)) {
556 r->termsig = WTERMSIG(st);
557 if (ch[i].cancelled && r->termsig == SIGKILL) set_cmd(r, 128 + r->termsig, OSH_OUT_CANCELLED, OSH_E_INTERRUPTED);
558 else set_cmd(r, 128 + r->termsig, OSH_OUT_COMPLETED, OSH_E_OK);
559 } else {
560 set_cmd(r, WEXITSTATUS(st), OSH_OUT_COMPLETED, OSH_E_OK);
561 }
562 }
563 return first_stop;
564}
565
566/* bash's "Killed" / "Terminated" line for a member that died of a signal (omega#344 RISK-8); SIGINT and SIGPIPE
567 * stay silent, as in bash. */
568static const char *signame(int sig)
569{
570 switch (sig) {
571 case SIGHUP: return "Hangup";
572 case SIGQUIT: return "Quit";
573 case SIGILL: return "Illegal instruction";
574 case SIGABRT: return "Aborted";
575 case SIGBUS: return "Bus error";
576 case SIGFPE: return "Floating point exception";
577 case SIGKILL: return "Killed";
578 case SIGSEGV: return "Segmentation fault";
579 case SIGTERM: return "Terminated";
580 case SIGUSR1: return "User defined signal 1";
581 case SIGUSR2: return "User defined signal 2";
582 case SIGALRM: return "Alarm clock";
583 default: return "Signal";
584 }
585}
586
587static void run_pipeline(OshSession *s, const OshRequest *r, JCtx *jc, OshResult *res)
588{
589 int n = r->ncmds;
590 Pipes p;
591 p.n = n - 1;
592 for (int i = 0; i < OSH_MAX_CMDS; i++) p.pp[i][0] = p.pp[i][1] = -1;
593 for (int i = 0; i < n - 1; i++)
594 if (pipe2(p.pp[i], O_CLOEXEC) != 0) {
595 osh_diag(s->fd[2], "pipe: %s", strerror(errno));
596 close_pipes(&p);
597 fail_all(res, n, 1, OSH_E_LIMIT);
598 return;
599 }
600 Child ch[OSH_MAX_CMDS];
601 memset(ch, 0, sizeof ch);
602 pid_t pgid = 0;
603 int started = 0, launch_failed = 0;
604 /* Interactive: each pipeline is its own process group and (with a terminal) owns the terminal while it runs.
605 * Non-interactive: no new group at all; the children stay in the shell's group like bash does for scripts. */
606 int own_pg = s->interactive;
607 int tty = own_pg && s->tty_fd >= 0;
608 sigset_t fork_blk, fork_old;
609 sigemptyset(&fork_blk);
610 sigaddset(&fork_blk, SIGINT);
611 sigaddset(&fork_blk, SIGQUIT);
612
613 for (int i = 0; i < n; i++) {
614 const OshCmd *c = &r->cmd[i];
615 FdTab t;
616 tab_init(&t, s);
617 int rd = i > 0 ? p.pp[i - 1][0] : -1, wr = i < n - 1 ? p.pp[i][1] : -1;
618 if (rd >= 0) t.fd[0] = rd;
619 if (wr >= 0) t.fd[1] = wr;
620 char path[PATH_MAX];
621 char **envp = NULL;
622 int external = c->nargv > 0 && c->builtin_id == OSH_B_NONE;
623 int pre = OSH_E_OK;
624 for (int k = 0; k < c->nredir && pre == OSH_E_OK; k++)
625 if (c->redir[k].kind != OSH_R_DUP)
626 pre = osh_effect_check(s, c->redir[k].kind == OSH_R_IN ? OSH_OP_OPEN_READ : OSH_OP_OPEN_WRITE, c->redir[k].path, s->fd[2]);
627 if (pre != OSH_E_OK) { /* denied before any process exists; the child re-checks right before its own open() */
628 set_cmd(&res->cmd[i], 1, OSH_OUT_FAILED_NO_EFFECT, pre);
629 if (rd >= 0) { close(rd); p.pp[i - 1][0] = -1; }
630 if (wr >= 0) { close(wr); p.pp[i][1] = -1; }
631 continue;
632 }
633
634 if (external) {
635 int why, rc = resolve_in(cmd_path_var(s, c), c->argv[0], path, sizeof path, &why);
636 if (rc != 0) {
637 if (rc == 127 && !strchr(c->argv[0], '/')) osh_diag(s->fd[2], "%s: command not found", c->argv[0]);
638 else osh_diag(s->fd[2], "%s: %s", c->argv[0], strerror(why));
639 set_cmd(&res->cmd[i], rc, OSH_OUT_FAILED_NO_EFFECT, OSH_E_NOT_FOUND);
640 if (rd >= 0) { close(rd); p.pp[i - 1][0] = -1; }
641 if (wr >= 0) { close(wr); p.pp[i][1] = -1; }
642 continue;
643 }
644 int ge = osh_effect_check(s, OSH_OP_SPAWN, path, s->fd[2]);
645 if (ge != OSH_E_OK) {
646 set_cmd(&res->cmd[i], 126, OSH_OUT_FAILED_NO_EFFECT, ge);
647 if (rd >= 0) { close(rd); p.pp[i - 1][0] = -1; }
648 if (wr >= 0) { close(wr); p.pp[i][1] = -1; }
649 continue;
650 }
651 envp = osh_build_envp(s, c->assign, c->nassign, path);
652 if (!envp) { launch_failed = 1; set_cmd(&res->cmd[i], 1, OSH_OUT_NOT_STARTED, OSH_E_LIMIT); break; }
653 }
654
655 int jrc = jc_intent(jc, r, i);
656 if (jrc != 0) { /* mandatory record not durable: fail closed, launch nothing */
657 jc_refuse(s, jc, jrc);
658 osh_envp_free(envp);
659 set_cmd(&res->cmd[i], 1, OSH_OUT_FAILED_NO_EFFECT, OSH_E_IO);
660 if (rd >= 0) { close(rd); p.pp[i - 1][0] = -1; }
661 if (wr >= 0) { close(wr); p.pp[i][1] = -1; }
662 if (started > 0) { launch_failed = 1; break; } /* earlier members already run: cancel and reap them (PARTIAL_LAUNCH, ABI s10) */
663 continue;
664 }
665
666 pid_t pid;
667 /* SIGINT/SIGQUIT stay blocked across fork: a signal that lands before the child has reset its handlers would
668 * otherwise run the shell's handler inside the child. They are delivered once the child's signals are default. */
669 sigprocmask(SIG_BLOCK, &fork_blk, &fork_old);
670 if (s->fail_fork_at == i + 1) { pid = -1; errno = EAGAIN; }
671 else pid = fork();
672 if (pid < 0) {
673 int saved = errno;
674 sigprocmask(SIG_SETMASK, &fork_old, NULL);
675 errno = saved;
676 osh_diag(s->fd[2], "fork: %s", strerror(errno));
677 osh_envp_free(envp);
678 set_cmd(&res->cmd[i], 1, OSH_OUT_NOT_STARTED, OSH_E_LIMIT);
679 launch_failed = 1;
680 break;
681 }
682 if (pid == 0) {
683 /* ---- child ---- */
684 /* a forked builtin never execs, so the O_CLOEXEC journal descriptor (and its flock) would outlive the shell: close it now */
685 if (s->journal && s->journal->fd >= 0) close(s->journal->fd);
686 if (own_pg) setpgid(0, pgid); /* pgid 0 on the first one: become a leader */
687 if (tty && pgid == 0) tcsetpgrp(s->tty_fd, getpid()); /* SIGTTOU is still ignored here */
688 child_signals();
689 int st = 1;
690 if (apply_redirs(s, &t, c, s->fd[2], NULL) == 0 && child_install(&t) == 0) {
691 /* close every descriptor that is not 0..2, each exactly once (no double close) */
692 int cl[2 * OSH_MAX_CMDS + OSH_MAX_REDIR + 8], ncl = 0;
693 for (int k = 0; k < p.n; k++)
694 for (int e = 0; e < 2; e++) if (p.pp[k][e] >= 0) cl[ncl++] = p.pp[k][e];
695 for (int k = 0; k < t.nown; k++) cl[ncl++] = t.own[k];
696 for (int k = 0; k < 3; k++) {
697 cl[ncl++] = t.fd[k];
698 cl[ncl++] = s->fd[k];
699 }
700 if (tty) cl[ncl++] = s->tty_fd;
701 for (int k = 0; k < ncl; k++) {
702 int dup = cl[k] < 3;
703 for (int j = 0; j < k && !dup; j++) dup = cl[j] == cl[k];
704 if (!dup) close(cl[k]);
705 }
706 if (external) {
707 if (osh_effect_check(s, OSH_OP_SPAWN, path, 2) != OSH_E_OK) _exit(126); /* defensive: revoked between fork and exec; the osh program seals its policy before the first command, so it cannot trigger there (no test reaches it) */
708 execve(path, (char *const *)c->argv, envp);
709 osh_diag(2, "%s: %s", c->argv[0], strerror(errno));
710 st = (errno == ENOENT || errno == ENOTDIR) ? 127 : 126;
711 } else if (c->builtin_id) {
712 static const int io[3] = {0, 1, 2};
713 st = osh_builtin_run(s, c, io, 0);
714 } else {
715 st = 0; /* standalone assignment or redirections only: no parent effect in a pipeline */
716 }
717 }
718 _exit(st);
719 }
720 /* ---- parent ---- */
721 sigprocmask(SIG_SETMASK, &fork_old, NULL);
722 osh_envp_free(envp);
723 if (pgid == 0) pgid = pid;
724 if (own_pg) setpgid(pid, pgid);
725 if (tty && started == 0) tcsetpgrp(s->tty_fd, pgid);
726 ch[i].pid = pid;
727 res->cmd[i].pid = pid;
728 started++;
729 if (rd >= 0) { close(rd); p.pp[i - 1][0] = -1; }
730 if (wr >= 0) { close(wr); p.pp[i][1] = -1; }
731 }
732 close_pipes(&p);
733
734 if (launch_failed) {
735 if (started > 0) {
736 signal_kids(ch, n, pgid, own_pg, SIGTERM);
737 signal_kids(ch, n, pgid, own_pg, SIGCONT);
738 }
739 wait_all(s, res, ch, n, pgid, own_pg);
740 for (int i = 0; i < n; i++)
741 if (ch[i].pid > 0 && res->cmd[i].outcome == OSH_OUT_COMPLETED) res->cmd[i].outcome = OSH_OUT_CANCELLED;
742 if (tty) tcsetpgrp(s->tty_fd, getpgrp());
743 res->status = 1;
744 res->err = started > 0 ? OSH_E_PARTIAL_LAUNCH : OSH_E_LIMIT;
745 return;
746 }
747 if (s->after_launch_hook) s->after_launch_hook(s->after_launch_ctx);
748 int stopsig = wait_all(s, res, ch, n, pgid, own_pg);
749 if (tty) tcsetpgrp(s->tty_fd, getpgrp());
750 for (int i = 0; i < n; i++) {
751 const OshCmdResult *cr = &res->cmd[i];
752 if (cr->outcome == OSH_OUT_COMPLETED && cr->termsig && cr->termsig != SIGINT && cr->termsig != SIGPIPE)
753 osh_diag(s->fd[2], "%s: %s (signal %d)", r->cmd[i].nargv > 0 ? r->cmd[i].argv[0] : "?", signame(cr->termsig), cr->termsig);
754 }
755 res->status = stopsig ? 128 + stopsig : res->cmd[n - 1].status;
756 for (int i = 0; i < n; i++)
757 if (res->cmd[i].err != OSH_E_OK && res->cmd[i].err != OSH_E_NOT_FOUND && res->err == OSH_E_OK) res->err = res->cmd[i].err;
758}
759
760/* ---------------- public entry points ---------------- */
761
762int osh_exec(OshSession *s, const OshRequest *r, OshResult *res)
763{
764 memset(res, 0, sizeof *res);
765 res->ncmds = r->ncmds;
766 JCtx jc;
767 jc_init(&jc, s, r);
768 int a = authorize(s, r);
769 if (a != OSH_E_OK) {
770 osh_diag(s->fd[2], "%s: not permitted (platform error %d); nothing was run", r->cmd[0].nargv ? r->cmd[0].argv[0] : "request", a);
771 fail_all(res, r->ncmds, 126, a);
772 jc_finish(&jc, r, res);
773 s->last_status = res->status;
774 return res->status;
775 }
776 for (int i = 0; i < r->ncmds; i++) {
777 const OshCmd *c = &r->cmd[i];
778 if (c->nargv == 0 || c->builtin_id != OSH_B_NONE || !s->class_hook) continue;
779 int cls = s->class_hook(s->hook_ctx, c->argv[0]);
780 if (cls != OSH_CLASS_LINUX) {
781 osh_diag(s->fd[2], "%s: destination class %d is not a Linux executable and is unavailable on this host; refused", c->argv[0], cls);
782 fail_all(res, r->ncmds, 126, OSH_E_UNAVAILABLE);
783 jc_finish(&jc, r, res);
784 s->last_status = res->status;
785 return res->status;
786 }
787 }
788 SigGuard g;
789 guard_enter(&g, s->interactive);
790 if (r->ncmds == 1 && (r->cmd[0].builtin_id != OSH_B_NONE || r->cmd[0].nargv == 0)) run_in_parent(s, r, &jc, res);
791 else run_pipeline(s, r, &jc, res);
792 jc_finish(&jc, r, res);
793 res->sigint_seen = g_sig_seen == SIGINT;
794 const OshCmdResult *last = &res->cmd[r->ncmds - 1];
795 res->killed_by_int = last->termsig == SIGINT || last->termsig == SIGQUIT;
796 if (res->killed_by_int && !s->interactive) { /* bash, non-interactive: the foreground child died of SIGINT/SIGQUIT, so the shell ends too */
797 s->exit_requested = 1;
798 s->exit_status = 128 + last->termsig;
799 }
800 guard_leave(&g);
801 res->exit_requested = s->exit_requested;
802 s->last_status = res->status;
803 return res->status;
804}
805
806int osh_exec_record(OshSession *s, const uint64_t *rec, size_t nrec, const uint64_t *out, size_t nout, OshResult *res)
807{
808 OshRequest *r = malloc(sizeof *r);
809 memset(res, 0, sizeof *res);
810 if (!r) { res->status = 1; res->err = OSH_E_LIMIT; return 1; }
811 int rc = osh_req_decode(rec, nrec, out, nout, r);
812 if (rc) {
813 free(r);
814 osh_diag(s->fd[2], "request refused (code %d); nothing was run", rc);
815 res->refusal = rc;
816 res->status = 2; /* ABI 5.4: a refused list reports status 2 */
817 res->err = OSH_E_INVALID_ARG;
818 s->last_status = 2;
819 return 2;
820 }
821 int st = osh_exec(s, r, res);
822 free(r);
823 return st;
824}
825
826int osh_conn_should_run(int connector_after, int last_status)
827{
828 if (connector_after == OSH_CONN_AND) return last_status == 0;
829 if (connector_after == OSH_CONN_OR) return last_status != 0;
830 return 1;
831}
832
833int osh_run_list(OshSession *s, const OshRequest *const *reqs, int n, OshResult *res_out)
834{
835 for (int i = 0; i < n; i++) {
836 OshResult local;
837 OshResult *res = res_out ? &res_out[i] : &local;
838 if (i > 0 && !osh_conn_should_run(reqs[i - 1]->connector_after, s->last_status)) {
839 memset(res, 0, sizeof *res); /* skipped: $? is unchanged, the next connector sees the same status */
840 continue;
841 }
842 osh_exec(s, reqs[i], res);
843 if (s->exit_requested) return s->exit_status;
844 if (res->killed_by_int) break;
845 }
846 return s->last_status;
847}
848
849int osh_submit_argv(OshSession *s, const char *const *argv, int nargv, const OshAssign *ov, int nov,
850 const OshRedir *redirs, int nredir, OshResult *res)
851{
852 OshBuilder *b = malloc(sizeof *b);
853 if (!b) { memset(res, 0, sizeof *res); res->status = 1; res->err = OSH_E_LIMIT; return 1; }
854 osh_rb_init(b, OSH_REQ_FLAG_DIRECT, OSH_CONN_NONE);
855 osh_rb_cmd(b, OSH_B_NONE);
856 for (int i = 0; i < nargv; i++) osh_rb_arg(b, argv[i]);
857 for (int i = 0; i < nov; i++) osh_rb_assign(b, ov[i].name, ov[i].value);
858 for (int i = 0; i < nredir; i++) osh_rb_redir(b, redirs[i].kind, redirs[i].fd, redirs[i].path, redirs[i].src_fd);
859 osh_rb_seal(b);
860 int st;
861 if (b->err) { /* overflow while building: same refusal the decoder would give an oversized record */
862 memset(res, 0, sizeof *res);
863 osh_diag(s->fd[2], "direct request refused (code %d); nothing was run", b->err);
864 res->refusal = b->err;
865 res->status = 2;
866 res->err = OSH_E_INVALID_ARG;
867 s->last_status = 2;
868 st = 2;
869 } else {
870 st = osh_exec_record(s, b->rec, osh_rb_cells(b), b->out, b->out_used, res);
871 }
872 free(b);
873 return st;
874}