| | @@ -0,0 +1,379 @@ |
| 1 | +(* A small shell: commands, pipelines (a | b), redirection (< f, > f, |
| 2 | + >> f, 2> f), quotes ('...' and "..."), $NAME and $?, comments, lists |
| 3 | + (a; b) and background programs (a &); and cd, wait and exit. Words |
| 4 | + aren't split after $NAME: "$x" and $x are one word each. |
| 5 | + |
| 6 | + Sh reads commands, a line at a time |
| 7 | + Sh -c 'echo hi' runs its argument |
| 8 | + Sh script runs the file |
| 9 | + |
| 10 | + On a terminal it does job control: each pipeline is a process group |
| 11 | + of its own, which has the terminal while it runs, so that Ctrl-C |
| 12 | + stops the pipeline and not the shell. Left out: stopped jobs (fg, |
| 13 | + bg), assignments, globs, $(...), if and while. *) |
| 14 | +module Sh; |
| 15 | +import Opt, Files, Sys, Str, Buf, Fmt, Out, Arena, Heap, Rt; |
| 16 | + |
| 17 | +const |
| 18 | + maxWords = 64; (* of a command *) |
| 19 | + maxCmds = 16; (* of a pipeline *) |
| 20 | + |
| 21 | +type |
| 22 | + Command = record |
| 23 | + args: [maxWords][]U8; |
| 24 | + n: I64; |
| 25 | + input, output, errors: []U8; (* the files of <, > or >>, and 2>; "" for none *) |
| 26 | + append: BOOL; (* output is >> *) |
| 27 | + end; |
| 28 | + Pipeline = record |
| 29 | + cmds: [maxCmds]Command; |
| 30 | + n: I64; |
| 31 | + background: BOOL; |
| 32 | + end; |
| 33 | + (* What the parser reads: a word, |, &, ; or a line's end, <, >, >>, 2>, |
| 34 | + and the end of the script. *) |
| 35 | + Token = (word, pipe, amp, sep, from, into, onto, errTo, eof); |
| 36 | + |
| 37 | +var |
| 38 | + status: I64; (* of the last pipeline: $? *) |
| 39 | + interactive: BOOL; (* commands come from a terminal: job control *) |
| 40 | + group: I64; (* the shell's process group *) |
| 41 | + arena: Arena.Arena; (* the words of what is being run *) |
| 42 | + s: []U8; (* the script being read *) |
| 43 | + at: I64; (* where in it *) |
| 44 | + text: []U8; (* the last word read *) |
| 45 | + |
| 46 | +(* "Sh: " and a message on standard error. *) |
| 47 | +proc say(f: []U8; args: []Fmt.Arg); |
| 48 | +var b: Buf.Buf; _n: I64; |
| 49 | +begin |
| 50 | + Buf.init(ADR(b), Heap.heap); |
| 51 | + Fmt.write(ADR(b), "Sh: ", []); |
| 52 | + Fmt.write(ADR(b), f, args); |
| 53 | + Buf.add(ADR(b), 10); |
| 54 | + _n := Sys.write(Sys.stderr, Buf.bytes(ADR(b))); |
| 55 | + Buf.done(ADR(b)); |
| 56 | +end; |
| 57 | + |
| 58 | +proc special(c: U8): BOOL; |
| 59 | +begin |
| 60 | + return (c = ' ') or (c = 9) or (c = 10) or (c = ';') or (c = '|') or (c = '&') |
| 61 | + or (c = '<') or (c = '>'); |
| 62 | +end; |
| 63 | + |
| 64 | +(* $NAME or $? at s[at], its value added to b; a $ before anything else |
| 65 | + is itself. *) |
| 66 | +proc dollar(b: ^Buf.Buf); |
| 67 | +var start: I64; |
| 68 | +begin |
| 69 | + INC(at); |
| 70 | + if (at < LEN(s)) and (s[at] = '?') then |
| 71 | + INC(at); |
| 72 | + Fmt.write(b, "{}", [Fmt.int(status)]); |
| 73 | + return; |
| 74 | + end; |
| 75 | + start := at; |
| 76 | + while (at < LEN(s)) and ((s[at] >= 'A') and (s[at] <= 'Z') or (s[at] >= 'a') and (s[at] <= 'z') |
| 77 | + or (s[at] >= '0') and (s[at] <= '9') or (s[at] = '_')) do INC(at); end; |
| 78 | + if at = start then Buf.add(b, '$'); else Buf.str(b, Sys.env(s[start..at])); end; |
| 79 | +end; |
| 80 | + |
| 81 | +(* A word, into text: up to a blank or a special character, its quotes |
| 82 | + taken away and its dollars put in. *) |
| 83 | +proc readWord; |
| 84 | +var b: Buf.Buf; q: U8; |
| 85 | +begin |
| 86 | + Buf.init(ADR(b), ADR(arena.base)); |
| 87 | + while (at < LEN(s)) and not special(s[at]) do |
| 88 | + q := s[at]; |
| 89 | + if q = 39 then (* '...': every character as it is *) |
| 90 | + INC(at); |
| 91 | + while (at < LEN(s)) and (s[at] # 39) do Buf.add(ADR(b), s[at]); INC(at); end; |
| 92 | + INC(at); |
| 93 | + elsif q = '"' then (* "...": dollars, and \" and \\ *) |
| 94 | + INC(at); |
| 95 | + while (at < LEN(s)) and (s[at] # '"') do |
| 96 | + if s[at] = '$' then dollar(ADR(b)); |
| 97 | + else |
| 98 | + if (s[at] = '\\') and (at + 1 < LEN(s)) and ((s[at + 1] = '"') or (s[at + 1] = '\\')) then INC(at); end; |
| 99 | + Buf.add(ADR(b), s[at]); |
| 100 | + INC(at); |
| 101 | + end; |
| 102 | + end; |
| 103 | + INC(at); |
| 104 | + elsif q = '$' then |
| 105 | + dollar(ADR(b)); |
| 106 | + else |
| 107 | + if (q = '\\') and (at + 1 < LEN(s)) then INC(at); end; |
| 108 | + Buf.add(ADR(b), s[at]); |
| 109 | + INC(at); |
| 110 | + end; |
| 111 | + end; |
| 112 | + text := Buf.bytes(ADR(b)); |
| 113 | +end; |
| 114 | + |
| 115 | +proc next: Token; |
| 116 | +var c: U8; |
| 117 | +begin |
| 118 | + while (at < LEN(s)) and ((s[at] = ' ') or (s[at] = 9)) do INC(at); end; |
| 119 | + if (at < LEN(s)) and (s[at] = '#') then |
| 120 | + while (at < LEN(s)) and (s[at] # 10) do INC(at); end; |
| 121 | + end; |
| 122 | + if at >= LEN(s) then return eof; end; |
| 123 | + c := s[at]; |
| 124 | + INC(at); |
| 125 | + if (c = ';') or (c = 10) then return sep; |
| 126 | + elsif c = '|' then return pipe; |
| 127 | + elsif c = '&' then return amp; |
| 128 | + elsif c = '<' then return from; |
| 129 | + elsif c = '>' then |
| 130 | + if (at < LEN(s)) and (s[at] = '>') then INC(at); return onto; end; |
| 131 | + return into; |
| 132 | + elsif (c = '2') and (at < LEN(s)) and (s[at] = '>') then |
| 133 | + INC(at); |
| 134 | + return errTo; |
| 135 | + end; |
| 136 | + DEC(at); |
| 137 | + readWord; |
| 138 | + return word; |
| 139 | +end; |
| 140 | + |
| 141 | +(* A pipeline, up to the ; or & or line that ends it, which is the |
| 142 | + result; or eof. false, after saying why, if it isn't one. *) |
| 143 | +proc parse(p: ^Pipeline): (Token, BOOL); |
| 144 | +var t: Token; c: ^Command; |
| 145 | +begin |
| 146 | + p^ := {n: 1}; |
| 147 | + c := ADR(p^.cmds[0]); |
| 148 | + t := next(); |
| 149 | + while (t # sep) and (t # amp) and (t # eof) do |
| 150 | + if t = word then |
| 151 | + if c^.n = maxWords then say("too many words", []); return t, false; end; |
| 152 | + c^.args[c^.n] := text; |
| 153 | + INC(c^.n); |
| 154 | + elsif t = pipe then |
| 155 | + if (c^.n = 0) or (p^.n = maxCmds) then say("a | without a command", []); return t, false; end; |
| 156 | + c := ADR(p^.cmds[p^.n]); |
| 157 | + INC(p^.n); |
| 158 | + else |
| 159 | + if next() # word then say("a redirection without a file", []); return t, false; end; |
| 160 | + if t = from then c^.input := text; |
| 161 | + elsif t = errTo then c^.errors := text; |
| 162 | + else c^.output := text; c^.append := t = onto; |
| 163 | + end; |
| 164 | + end; |
| 165 | + t := next(); |
| 166 | + end; |
| 167 | + if (c^.n = 0) and ((p^.n > 1) or (t = amp)) then say("a | or & without a command", []); return t, false; end; |
| 168 | + p^.background := t = amp; |
| 169 | + return t, true; |
| 170 | +end; |
| 171 | + |
| 172 | +(* The program a command names: the name itself if it has a /, else the |
| 173 | + first executable file of that name in a directory of $PATH. *) |
| 174 | +proc find(name: []U8): ([]U8, BOOL); |
| 175 | +var path, dir: []U8; i, start, err: I64; b: Buf.Buf; info: Sys.Info; |
| 176 | +begin |
| 177 | + if Str.find(name, "/") >= 0 then return name, true; end; |
| 178 | + path := Sys.env("PATH"); |
| 179 | + start := 0; |
| 180 | + for i := 0 to LEN(path) do |
| 181 | + if (i = LEN(path)) or (path[i] = ':') then |
| 182 | + dir := path[start..i]; |
| 183 | + start := i + 1; |
| 184 | + Buf.init(ADR(b), ADR(arena.base)); |
| 185 | + Fmt.write(ADR(b), "{}/{}", [Fmt.str(dir), Fmt.str(name)]); |
| 186 | + info, err := Sys.info(Buf.bytes(ADR(b))); |
| 187 | + if (err = 0) and info.file and (info.mode & 49H # 0) then return Buf.bytes(ADR(b)), true; end; |
| 188 | + end; |
| 189 | + end; |
| 190 | + return "", false; |
| 191 | +end; |
| 192 | + |
| 193 | +(* The fd of a redirection's file, or -1 after saying why not. *) |
| 194 | +proc redirect(path: []U8; how: Sys.Accesses): I64; |
| 195 | +var fd: I64; |
| 196 | +begin |
| 197 | + fd := Sys.open(path, how); |
| 198 | + if fd < 0 then say("{}: can't open it", [Fmt.str(path)]); return -1; end; |
| 199 | + return fd; |
| 200 | +end; |
| 201 | + |
| 202 | +(* cd, wait and exit, which change the shell itself, so it can't start |
| 203 | + them as programs; true if c is one. *) |
| 204 | +proc builtin(c: ^Command): BOOL; |
| 205 | +var dir: []U8; n, pid, _code: I64; ok: BOOL; _st: Sys.Status; |
| 206 | +begin |
| 207 | + if c^.args[0] = "cd" then |
| 208 | + if c^.n > 1 then dir := c^.args[1]; else dir := Sys.env("HOME"); end; |
| 209 | + status := 0; |
| 210 | + if Sys.setWorkDir(dir) < 0 then say("cd: can't go to {}", [Fmt.str(dir)]); status := 1; end; |
| 211 | + elsif c^.args[0] = "wait" then |
| 212 | + repeat pid, _st, _code := Sys.wait(-1, true); until pid < 0; |
| 213 | + status := 0; |
| 214 | + elsif c^.args[0] = "exit" then |
| 215 | + n := status; |
| 216 | + if c^.n > 1 then |
| 217 | + n, ok := Str.toInt(c^.args[1]); |
| 218 | + if not ok then say("exit: {} isn't a number", [Fmt.str(c^.args[1])]); n := 2; end; |
| 219 | + end; |
| 220 | + Rt.exit(n); |
| 221 | + else |
| 222 | + return false; |
| 223 | + end; |
| 224 | + return true; |
| 225 | +end; |
| 226 | + |
| 227 | +(* What the shell itself says on standard output, out before any |
| 228 | + program it starts writes. *) |
| 229 | +proc show(f: []U8; args: []Fmt.Arg); |
| 230 | +begin |
| 231 | + Fmt.print(f, args); |
| 232 | + Out.flush; |
| 233 | +end; |
| 234 | + |
| 235 | +(* The pipeline started, each program reading what the one before it |
| 236 | + writes; then, unless it runs in the background, waited for. On a |
| 237 | + terminal its programs are a process group, led by the first, which |
| 238 | + has the terminal until they end. *) |
| 239 | +proc start(p: ^Pipeline); |
| 240 | +var |
| 241 | + pids: [maxCmds]I64; fds: [3]I64; i, j, inNext, r, w, leader, joins, how, _pid: I64; |
| 242 | + c: ^Command; path: []U8; found, _ok: BOOL; st: Sys.Status; |
| 243 | +begin |
| 244 | + if (p^.n = 1) and not p^.background and builtin(ADR(p^.cmds[0])) then return; end; |
| 245 | + leader := 0; |
| 246 | + inNext := 0; |
| 247 | + for i := 0 to p^.n - 1 do |
| 248 | + c := ADR(p^.cmds[i]); |
| 249 | + fds := [inNext, 0, 0]; |
| 250 | + inNext := 0; |
| 251 | + if i < p^.n - 1 then r, w := Sys.pipe(); fds[1] := w; inNext := r; end; |
| 252 | + if LEN(c^.input) > 0 then fds[0] := redirect(c^.input, {Sys.reading}); end; |
| 253 | + if c^.append then fds[1] := redirect(c^.output, {Sys.writing, Sys.creating, Sys.appending}); |
| 254 | + elsif LEN(c^.output) > 0 then fds[1] := redirect(c^.output, {Sys.writing, Sys.creating, Sys.truncating}); |
| 255 | + end; |
| 256 | + if LEN(c^.errors) > 0 then fds[2] := redirect(c^.errors, {Sys.writing, Sys.creating, Sys.truncating}); end; |
| 257 | + pids[i] := -1; |
| 258 | + path, found := find(c^.args[0]); |
| 259 | + if not found then say("{}: not found", [Fmt.str(c^.args[0])]); |
| 260 | + elsif (fds[0] >= 0) and (fds[1] >= 0) and (fds[2] >= 0) then |
| 261 | + joins := 0; (* the shell's group *) |
| 262 | + if interactive and (leader = 0) then joins := -1; |
| 263 | + elsif interactive then joins := leader; |
| 264 | + end; |
| 265 | + pids[i] := Sys.spawn({path: path, args: c^.args[0..c^.n], fds: fds, group: joins, |
| 266 | + foreground: interactive and not p^.background}); |
| 267 | + if not interactive or (pids[i] < 0) then |
| 268 | + elsif leader = 0 then leader := pids[i]; |
| 269 | + else _ok := Sys.setGroup(pids[i], leader) = 0; (* whichever of it and the program runs first *) |
| 270 | + end; |
| 271 | + end; |
| 272 | + for j := 0 to 2 do |
| 273 | + if fds[j] > 0 then Sys.close(fds[j]); end; |
| 274 | + end; |
| 275 | + end; |
| 276 | + status := 0; |
| 277 | + if p^.background then |
| 278 | + if interactive then show("[{}]\n", [Fmt.int(pids[p^.n - 1])]); end; |
| 279 | + return; |
| 280 | + end; |
| 281 | + for i := 0 to p^.n - 1 do |
| 282 | + if pids[i] > 0 then |
| 283 | + repeat _pid, st, how := Sys.wait(pids[i], true); until st # Sys.stopped; |
| 284 | + end; |
| 285 | + end; |
| 286 | + if pids[p^.n - 1] < 0 then status := 127; |
| 287 | + elsif st = Sys.exited then status := how; |
| 288 | + else status := 128 + how; |
| 289 | + end; |
| 290 | + if interactive then |
| 291 | + _ok := Sys.foreground(Sys.stdin, group) = 0; (* the terminal back to the shell *) |
| 292 | + if (st = Sys.killed) and (how = Sys.sigInt) then show("\n", []); end; |
| 293 | + end; |
| 294 | +end; |
| 295 | + |
| 296 | +(* Runs script: each pipeline as it is read. *) |
| 297 | +proc run(script: []U8); |
| 298 | +var p: Pipeline; t: Token; ok: BOOL; |
| 299 | +begin |
| 300 | + Arena.reset(ADR(arena)); |
| 301 | + s := script; |
| 302 | + at := 0; |
| 303 | + repeat |
| 304 | + t, ok := parse(ADR(p)); |
| 305 | + if not ok then status := 2; return; end; |
| 306 | + if p.cmds[0].n > 0 then start(ADR(p)); end; |
| 307 | + until t = eof; |
| 308 | +end; |
| 309 | + |
| 310 | +(* A line from standard input, a byte at a time, so that what follows |
| 311 | + it is left for the programs the line starts; false at its end. *) |
| 312 | +proc readLine(b: ^Buf.Buf): BOOL; |
| 313 | +var c: [1]U8; |
| 314 | +begin |
| 315 | + Buf.reset(b); |
| 316 | + while Sys.read(Sys.stdin, c) = 1 do |
| 317 | + if c[0] = 10 then return true; end; |
| 318 | + Buf.add(b, c[0]); |
| 319 | + end; |
| 320 | + return LEN(Buf.bytes(b)) > 0; |
| 321 | +end; |
| 322 | + |
| 323 | +(* Before a prompt: the background programs that have ended. *) |
| 324 | +proc reap; |
| 325 | +var pid, _code: I64; _st: Sys.Status; |
| 326 | +begin |
| 327 | + repeat |
| 328 | + pid, _st, _code := Sys.wait(-1, false); |
| 329 | + if pid > 0 then show("[{}] done\n", [Fmt.int(pid)]); end; |
| 330 | + until pid <= 0; |
| 331 | +end; |
| 332 | + |
| 333 | +(* Commands from standard input. On a terminal, with a prompt, and the |
| 334 | + shell in a process group of its own, which ignores the keys that |
| 335 | + stop or end the pipeline in front of it. *) |
| 336 | +proc interact; |
| 337 | +var line: Buf.Buf; keys: [5]I64; i: I64; _ok: BOOL; |
| 338 | +begin |
| 339 | + interactive := Sys.isTerminal(Sys.stdin); |
| 340 | + if interactive then |
| 341 | + keys := [Sys.sigInt, Sys.sigQuit, Sys.sigTstp, Sys.sigTtin, Sys.sigTtou]; |
| 342 | + for i := 0 to 4 do _ok := Sys.ignore(keys[i], true) = 0; end; |
| 343 | + _ok := Sys.setGroup(0, 0) = 0; |
| 344 | + group := Sys.pid(); |
| 345 | + _ok := Sys.foreground(Sys.stdin, group) = 0; |
| 346 | + end; |
| 347 | + Buf.init(ADR(line), Heap.heap); |
| 348 | + if interactive then reap; show("$ ", []); end; |
| 349 | + while readLine(ADR(line)) do |
| 350 | + run(Buf.bytes(ADR(line))); |
| 351 | + if interactive then reap; show("$ ", []); end; |
| 352 | + end; |
| 353 | + if interactive then show("\n", []); end; |
| 354 | +end; |
| 355 | + |
| 356 | +proc main*: I64; |
| 357 | +var p: Opt.Parser; script, file: []U8; given, found: BOOL; b: Buf.Buf; |
| 358 | +begin |
| 359 | + if not Arena.init(ADR(arena), 1 shl 24) then Rt.stop("Sh: no memory"); end; |
| 360 | + Opt.init(ADR(p), "Sh", [ |
| 361 | + Opt.usage("", "Sh [-c script | file]"), |
| 362 | + Opt.option("", 'c', "command", "script", "run script, not standard input")]); |
| 363 | + while Opt.next(ADR(p)) do |
| 364 | + if p.letter = 'c' then script := p.value; given := true; end; |
| 365 | + end; |
| 366 | + file, found := Opt.operand(ADR(p)); |
| 367 | + if given then |
| 368 | + run(script); |
| 369 | + elsif found then |
| 370 | + Buf.init(ADR(b), Heap.heap); |
| 371 | + if not Files.read(file, ADR(b)) then say("{}: can't read it", [Fmt.str(file)]); return 127; end; |
| 372 | + run(Buf.bytes(ADR(b))); |
| 373 | + else |
| 374 | + interact; |
| 375 | + end; |
| 376 | + return status; |
| 377 | +end; |
| 378 | + |
| 379 | +end Sh. |