raz / examples / Sh.raz

388 lines · 13.1 KiB · raw · history · last change 264716cb

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