Landin library reference discuss source

core/io/memory.ldn

1import core/mem
2import core/text
3
4--- A memory file slot that no file is open on.
5public closed_slot: atom
6--- A memory file slot open for reading.
7public reading_slot: atom
8--- A memory file slot open for writing.
9public writing_slot: atom
10--- What a memory file slot is open for: `closed_slot`, `reading_slot` or
11--- `writing_slot`, the provider's to change.
12public slot_state: type = closed_slot | reading_slot | writing_slot
13
14--- Caller-supplied in-memory file slot holding its path, readable bytes and
15--- writable capacity.  The caller gives it `closed_slot`. Keep all referenced
16--- ranges alive and initialize the fields before constructing the provider.
17---
18--- The provider over these slots is finite and caller-backed. Handles are
19--- indexes, not ownership tokens.
20--- Clients preserve length <= capacity and supply all retained backing.
21public memory_file: type = struct
22    name: []u8
23    contents: []mut u8
24    length: usize
25    cursor: usize
26    readable: bool
27    writable: bool
28    state: slot_state
29end memory_file
30
31--- Caller-owned state of an in-memory world: how much standard input, output
32--- and error it has used, which standard streams are open, the injected
33--- limits and failures, and call counts. Declare it `zeroed` and give it to
34--- `memory_over`, which fills it; it must outlive the world's handle. Its
35--- fields may be read, and the limits and failure points set, while the
36--- handle is in use.
37public memory_space: type = struct
38    input_used: usize
39    output_used: usize
40    errors_used: usize
41    input_open: bool
42    output_open: bool
43    errors_open: bool
44    read_limit: usize
45    write_limit: usize
46    fail_read_at: usize
47    fail_write_at: usize
48    fail_close_at: usize
49    reads: usize
50    writes: usize
51    closes: usize
52    opens: usize
53end memory_space
54
55memory_value: type = struct
56    state: ptr mut memory_space
57    files: []mut memory_file
58    arguments: [][]u8
59    input: []u8
60    output: []mut u8
61    errors: []mut u8
62end memory_value
63
64--- In-memory world as a handle over caller-owned state, file slots,
65--- standard-input bytes, output buffers and argument bytes: copies share
66--- one world. No host handles or implicit allocator are used.
67public memory: type = memory_value
68
69--- Fill `state` for an in-memory world over the supplied records and buffers
70--- and return its handle. The handle retains their references; keep them
71--- alive and avoid conflicting access while it is used. `arguments` are the
72--- bytes of each process argument, which the world lends as host strings,
73--- so a firmware test can declare its table as data. `input` is what
74--- standard input reads, from its first byte to end of input; pass `""` for
75--- a world whose standard input is empty.
76public memory_over: (inout state: memory_space, files: []mut memory_file,
77                     arguments: [][]u8, input: []u8,
78                     output: []mut u8, errors: []mut u8)
79                    -> (host: memory from state, files, arguments, input,
80                        output, errors) =
81    state = (input_used: 0, output_used: 0, errors_used: 0,
82             input_open: true, output_open: true, errors_open: true,
83             read_limit: 0 -% 1, write_limit: 0 -% 1,
84             fail_read_at: 0, fail_write_at: 0, fail_close_at: 0,
85             reads: 0, writes: 0, closes: 0, opens: 0)
86    host = (state: addr state, files: files, arguments: arguments,
87            input: input, output: output, errors: errors)
88end memory_over
89
90memory_open: (self: memory, path: text.os_string, writing: bool)
91             -> (opened: file) ! mem.not_found | no_access | io_failed =
92    inc self.state.val.opens
93    wanted: []u8 = text.os_string_bytes(path)
94    mut at: usize = 0
95    while at < lenof self.files do
96        current: ptr mut memory_file = addr self.files[at]
97        if memory_same_bytes(wanted, current.val.name) then
98            fail no_access when writing and not current.val.writable
99            fail no_access when not writing and not current.val.readable
100            fail io_failed when current.val.state <> closed_slot
101              or current.val.length > lenof current.val.contents
102            current.val.cursor = 0
103            current.val.state = if writing then writing_slot
104                                else reading_slot end if
105            if writing then current.val.length = 0 end if
106            opened = file_value(at + 3)
107            return
108        end if
109        inc at
110    end while
111    fail mem.not_found
112end memory_open
113
114memory_open_read: (self: memory, path: text.os_string)
115                  -> (opened: file)
116                  ! mem.not_found | no_access | is_a_directory | io_failed =
117    opened = try memory_open(self, path, false)
118end memory_open_read
119
120memory_open_write: (self: memory, path: text.os_string)
121                   -> (opened: file)
122                   ! mem.not_found | no_access | is_a_directory | io_failed =
123    opened = try memory_open(self, path, true)
124end memory_open_write
125
126memory_same_file: (self: memory, left: text.os_string,
127                   right: text.os_string)
128                  -> (same: bool) ! io_failed =
129    same = false
130    left_name: []u8 = text.os_string_bytes(left)
131    right_name: []u8 = text.os_string_bytes(right)
132    mut left_index: usize = lenof self.files
133    mut right_index: usize = lenof self.files
134    for at in usize(0)..<lenof self.files do
135        if left_index == lenof self.files
136          and memory_same_bytes(left_name, self.files[at].name) then
137            left_index = at
138        end if
139        if right_index == lenof self.files
140          and memory_same_bytes(right_name, self.files[at].name) then
141            right_index = at
142        end if
143    end for
144    fail io_failed when left_index == lenof self.files
145    same = left_index == right_index
146end memory_same_file
147
148memory_close: (self: memory, sink opened: file) -> none ! io_failed =
149    state: ptr mut memory_space = self.state
150    inc state.val.closes
151    if usize(opened) == 0 then
152        fail io_failed when not state.val.input_open
153        state.val.input_open = false
154    elsif usize(opened) == 1 then
155        fail io_failed when not state.val.output_open
156        state.val.output_open = false
157    elsif usize(opened) == 2 then
158        fail io_failed when not state.val.errors_open
159        state.val.errors_open = false
160    else
161        fail io_failed when usize(opened) < 3
162        index: usize = usize(opened) - 3
163        fail io_failed when index >= lenof self.files
164        current: ptr mut memory_file = addr self.files[index]
165        fail io_failed when current.val.state == closed_slot
166        current.val.state = closed_slot
167    end if
168    fail io_failed when state.val.closes == state.val.fail_close_at
169end memory_close
170
171--  Copy what remains of SOURCE after START into INTO, at most LIMIT bytes:
172--  standard input and a file are read alike.
173memory_take: (source: []u8, start: usize, into: []mut u8, limit: usize)
174             -> (count: usize) ! io_failed =
175    fail io_failed when start > lenof source
176    count = lenof source - start
177    fail io_failed when count > 0 and limit == 0
178    if count > lenof into then count = lenof into end if
179    if count > limit then count = limit end if
180    mut at: usize = 0
181    while at < count do
182        into[at] = source[start + at]
183        inc at
184    end while
185end memory_take
186
187memory_read: (self: memory, opened: file, into: []mut u8)
188             -> (count: usize) ! io_failed =
189    state: ptr mut memory_space = self.state
190    if lenof into == 0 then
191        count = 0
192        return
193    end if
194    inc state.val.reads
195    fail io_failed when state.val.reads == state.val.fail_read_at
196    if usize(opened) == 0 then
197        fail io_failed when not state.val.input_open
198        count = try memory_take(self.input, state.val.input_used, into,
199                                state.val.read_limit)
200        state.val.input_used += count
201        return
202    end if
203    fail io_failed when usize(opened) < 3
204    index: usize = usize(opened) - 3
205    fail io_failed when index >= lenof self.files
206    current: ptr mut memory_file = addr self.files[index]
207    fail io_failed when current.val.state <> reading_slot
208      or current.val.length > lenof current.val.contents
209    count = try memory_take(current.val.contents[0..<current.val.length],
210                            current.val.cursor, into, state.val.read_limit)
211    current.val.cursor += count
212end memory_read
213
214memory_write_some: (self: memory, opened: file, bytes: []u8)
215                   -> (count: usize) ! io_failed =
216    state: ptr mut memory_space = self.state
217    if lenof bytes == 0 then
218        count = 0
219        return
220    end if
221    inc state.val.writes
222    fail io_failed when state.val.writes == state.val.fail_write_at
223      or state.val.write_limit == 0
224    count = lenof bytes
225    if count > state.val.write_limit then count = state.val.write_limit end if
226    if usize(opened) == 1 then
227        fail io_failed when not state.val.output_open
228          or state.val.output_used > lenof self.output
229        available: usize = lenof self.output - state.val.output_used
230        fail io_failed when available == 0
231        if count > available then count = available end if
232        mut n: usize = 0
233        while n < count do
234            self.output[state.val.output_used + n] = bytes[n]
235            inc n
236        end while
237        state.val.output_used += count
238    elsif usize(opened) == 2 then
239        fail io_failed when not state.val.errors_open
240          or state.val.errors_used > lenof self.errors
241        available: usize = lenof self.errors - state.val.errors_used
242        fail io_failed when available == 0
243        if count > available then count = available end if
244        mut n: usize = 0
245        while n < count do
246            self.errors[state.val.errors_used + n] = bytes[n]
247            inc n
248        end while
249        state.val.errors_used += count
250    else
251        fail io_failed when usize(opened) < 3
252        index: usize = usize(opened) - 3
253        fail io_failed when index >= lenof self.files
254        current: ptr mut memory_file = addr self.files[index]
255        fail io_failed when current.val.state <> writing_slot
256          or current.val.length > lenof current.val.contents
257        available: usize = lenof current.val.contents - current.val.length
258        fail io_failed when available == 0
259        if count > available then count = available end if
260        mut n: usize = 0
261        while n < count do
262            current.val.contents[current.val.length + n] = bytes[n]
263            inc n
264        end while
265        current.val.length += count
266        current.val.cursor = current.val.length
267    end if
268end memory_write_some
269
270memory_write: (self: memory, opened: file, bytes: []u8)
271              -> none ! io_failed =
272    mut at: usize = 0
273    while at < lenof bytes do
274        count: usize = try memory_write_some(self, opened, bytes[at..<lenof bytes])
275        at += count
276    end while
277end memory_write
278
279memory_input: (self: memory) -> (stream: file) =
280    _ = self.state.val.input_used
281    stream = file_value(0)
282end memory_input
283memory_out: (self: memory) -> (stream: file) =
284    _ = self.state.val.output_used
285    stream = file_value(1)
286end memory_out
287memory_err: (self: memory) -> (stream: file) =
288    _ = self.state.val.errors_used
289    stream = file_value(2)
290end memory_err
291memory_arguments_length: (self: memory) -> (count: usize) =
292    count = lenof self.arguments
293end memory_arguments_length
294memory_argument: (self: memory, index: usize)
295                 -> (value: text.os_string from self) ! mem.not_found =
296    fail mem.not_found when index >= lenof self.arguments
297    value = text.os_string_over(self.arguments[index])
298end memory_argument
299
300memory is reader (read: memory_read)
301memory is writer (write: memory_write, write_some: memory_write_some)
302memory is files
303    (open_read: memory_open_read, open_write: memory_open_write,
304     same_file: memory_same_file, close: memory_close)
305memory is process
306    (input: memory_input, out: memory_out, err: memory_err,
307     arguments_length: memory_arguments_length, argument: memory_argument)
308memory is world ()
309
310--  The memory world's directories are the parts of its slots' names before
311--  a `/`: slot "tree/a.txt" puts a regular file "a.txt" in directory
312--  "tree", "tree/sub/b.txt" a subdirectory "sub" in it, and a slot named
313--  "tree/empty/" an empty directory "empty".  An open directory's handle
314--  is the index of a slot under it and its stream the length of its path;
315--  position is the next slot a refill looks at.  Its buffer holds records
316--  of a kind byte, a two-byte length and the name.
317
318--  Whether NAME begins with PREFIX followed by a `/`.
319memory_under: (name: []u8, prefix: []u8) -> (yes: bool) =
320    yes = false
321    return when lenof name <= lenof prefix
322    for at in usize(0)..<lenof prefix do
323        return when name[at] <> prefix[at]
324    end for
325    yes = name[lenof prefix] == u8('/')
326end memory_under
327
328--  The first slot under the directory at PATH, or the slot count when no
329--  slot is under it.
330memory_directory_slot: (self: memory, path: text.os_string)
331                       -> (slot: usize) =
332    slot = lenof self.files
333    wanted: []u8 = text.os_string_bytes(path)
334    return when lenof wanted == 0
335    for at in usize(0)..<lenof self.files do
336        if memory_under(self.files[at].name, wanted) then
337            slot = at
338            return
339        end if
340    end for
341end memory_directory_slot
342
343--  The name a slot gives an entry of the directory PREFIX, with whether it
344--  is a subdirectory; an empty name when the slot gives none.
345memory_component: (name: []u8, prefix: []u8)
346                  -> (component: []u8 from name, below: bool) =
347    component = name[0..<0]
348    below = false
349    return when not memory_under(name, prefix)
350    start: usize = lenof prefix + 1
351    mut stop: usize = start
352    while stop < lenof name and name[stop] <> u8('/') do
353        inc stop
354    end while
355    component = name[start..<stop]
356    below = stop < lenof name
357end memory_component
358
359memory_same_bytes: (left: []u8, right: []u8) -> (yes: bool) =
360    yes = lenof left == lenof right
361    mut at: usize = 0
362    while yes and at < lenof left do
363        yes = left[at] == right[at]
364        inc at
365    end while
366end memory_same_bytes
367
368--  Whether a slot before INDEX already gave the directory PREFIX the entry
369--  COMPONENT.
370memory_seen: (files: []memory_file, index: usize, prefix: []u8,
371              component: []u8) -> (yes: bool) =
372    yes = false
373    for at in usize(0)..<index do
374        (component: earlier, below) := memory_component(files[at].name, prefix)
375        _ = below
376        if memory_same_bytes(earlier, component) then
377            yes = true
378            return
379        end if
380    end for
381end memory_seen
382
383memory_open_directory: (self: memory, path: text.os_string,
384                        buffer: []mut u8)
385                       -> (opened: directory from buffer)
386                       ! mem.not_found | no_access | io_failed =
387    inc self.state.val.opens
388    slot: usize = memory_directory_slot(self, path)
389    fail mem.not_found when slot == lenof self.files
390    opened = (handle: slot, stream: lenof text.os_string_bytes(path), position: 0,
391              buffer: buffer, filled: 0, consumed: 0, at_end: false)
392end memory_open_directory
393
394--  Fill the directory's buffer with the records of as many entries as fit,
395--  from its position on.
396memory_refill: (self: memory, inout opened: directory) -> none ! io_failed =
397    opened.filled = 0
398    opened.consumed = 0
399    prefix: []u8 = self.files[opened.handle].name[0..<opened.stream]
400    while opened.position < lenof self.files do
401        (component, below) := memory_component(
402            self.files[opened.position].name, prefix)
403        if lenof component > 0
404          and not memory_seen(self.files, opened.position, prefix, component)
405        then
406            fail io_failed when lenof component > 65535
407            needed: usize = lenof component + 3
408            if needed > lenof opened.buffer - opened.filled then
409                --  An entry larger than the whole buffer can never be read.
410                fail io_failed when opened.filled == 0
411                return
412            end if
413            at: usize = opened.filled
414            opened.buffer[at] = if below then 1 else 0 end if
415            opened.buffer[at + 1] = u8(lenof component & 255)
416            opened.buffer[at + 2] = u8(lenof component >> 8)
417            for n in usize(0)..<lenof component do
418                opened.buffer[at + 3 + n] = component[n]
419            end for
420            opened.filled += needed
421        end if
422        inc opened.position
423    end while
424    opened.at_end = true
425end memory_refill
426
427memory_read_entry: (self: memory, inout opened: directory)
428                   -> (item: entry from opened) ! io_failed =
429    if opened.consumed >= opened.filled and not opened.at_end then
430        try memory_refill(self, opened)
431    end if
432    if opened.consumed >= opened.filled then
433        item = (name: text.os_string_over(opened.buffer[0..<0]), kind: special,
434                at_end: true)
435        return
436    end if
437    fail io_failed when opened.filled - opened.consumed < 3
438    at: usize = opened.consumed
439    length: usize = usize(opened.buffer[at + 1])
440                    | (usize(opened.buffer[at + 2]) << 8)
441    fail io_failed when length > opened.filled - at - 3
442    opened.consumed = at + 3 + length
443    kind: entry_kind = if opened.buffer[at] == 1 then subdirectory
444                       else regular end if
445    item = (name: text.os_string_over(opened.buffer[at + 3..<at + 3 + length]),
446            kind: kind, at_end: false)
447end memory_read_entry
448
449memory_entry_size: (self: memory, opened: directory,
450                    name: text.os_string)
451                   -> (size: u64) ! mem.not_found | no_access | io_failed =
452    size = 0
453    wanted: []u8 = text.os_string_bytes(name)
454    fail mem.not_found when lenof wanted == 0
455    for byte in wanted do
456        fail mem.not_found when byte == 0 or byte == u8('/')
457    end for
458    fail io_failed when opened.handle >= lenof self.files
459    prefix: []u8 = self.files[opened.handle].name[0..<opened.stream]
460    for at in usize(0)..<lenof self.files do
461        (component, below) := memory_component(self.files[at].name, prefix)
462        if memory_same_bytes(component, wanted) then
463            current: ptr memory_file = addr self.files[at]
464            size = if below then 0 else u64(current.val.length) end if
465            return
466        end if
467    end for
468    fail mem.not_found
469end memory_entry_size
470
471memory_close_directory: (self: memory, sink opened: directory)
472                        -> none ! io_failed =
473    _ = opened.handle
474    state: ptr mut memory_space = self.state
475    inc state.val.closes
476    fail io_failed when state.val.closes == state.val.fail_close_at
477end memory_close_directory
478
479--  The memory world's tree is its caller's slots, which it cannot add to
480--  or take from: a directory it has already exists, and every other change
481--  is refused.
482memory_make_directory: (self: memory, path: text.os_string)
483                       -> none
484                       ! already_exists | mem.not_found | no_access | io_failed =
485    slot: usize = memory_directory_slot(self, path)
486    fail already_exists when slot < lenof self.files
487    wanted: []u8 = text.os_string_bytes(path)
488    for at in usize(0)..<lenof self.files do
489        fail already_exists when memory_same_bytes(wanted, self.files[at].name)
490    end for
491    fail no_access
492end memory_make_directory
493
494memory_remove_file: (self: memory, path: text.os_string)
495                    -> none ! mem.not_found | no_access | io_failed =
496    wanted: []u8 = text.os_string_bytes(path)
497    for at in usize(0)..<lenof self.files do
498        fail no_access when memory_same_bytes(wanted, self.files[at].name)
499    end for
500    fail mem.not_found
501end memory_remove_file
502
503memory_remove_directory: (self: memory, path: text.os_string)
504                         -> none ! mem.not_found | no_access | io_failed =
505    slot: usize = memory_directory_slot(self, path)
506    fail no_access when slot < lenof self.files
507    fail mem.not_found
508end memory_remove_directory
509
510memory is directories
511    (open_directory: memory_open_directory, read_entry: memory_read_entry,
512     entry_size: memory_entry_size, close_directory: memory_close_directory,
513     make_directory: memory_make_directory, remove_file: memory_remove_file,
514     remove_directory: memory_remove_directory)
515
516--- Lend the bytes written to standard output so far: the initialized prefix
517--- of the memory provider's output buffer.
518public written: (host: memory) -> (bytes: []u8 from host) =
519    output: []mut u8 = host.output
520    bytes = output[0..<host.state.val.output_used]
521end written
522--- Lend the bytes written to standard error so far: the initialized prefix
523--- of the memory provider's error buffer.
524public written_errors: (host: memory) -> (bytes: []u8 from host) =
525    errors: []mut u8 = host.errors
526    bytes = errors[0..<host.state.val.errors_used]
527end written_errors
528
529--  A memory environment, beside the memory world: an `environment`
530--  provider over the caller's entries.
531
532variables_value: type = struct
533    entries: [][]u8
534end variables_value
535
536--- An environment over the caller's entries, each the bytes of one
537--- `NAME=value` as a process is given them, so a firmware test declares
538--- them as data: a provider of `environment` alone, as a test's process
539--- has one.  The name is the bytes before the first `=`, and an entry
540--- with no `=` is a name with an empty value.  Copies share the entries.
541public memory_variables: type = variables_value
542
543--- An environment over `entries`, which the handle lends; keep them alive
544--- while it is used.
545public variables_over: (entries: [][]u8)
546                       -> (host: memory_variables from entries) =
547    host = (entries: entries)
548end variables_over
549
550--  The bytes of an environment entry before its first `=`, and those
551--  after it; an entry with no `=` is all name.
552memory_split: (entry: []u8) -> (name: []u8 from entry, value: []u8 from entry) =
553    at: usize = mem.find(entry, u8('='))
554    name = entry[0..<at]
555    value = entry[lenof entry..<lenof entry]
556    if at < lenof entry then value = entry[at + 1..<lenof entry] end if
557end memory_split
558
559memory_variables_length: (self: memory_variables) -> (count: usize) =
560    count = lenof self.entries
561end memory_variables_length
562
563memory_variable: (self: memory_variables, index: usize)
564                 -> (item: text.os_variable from self) ! mem.not_found =
565    fail mem.not_found when index >= lenof self.entries
566    (name, value) := memory_split(self.entries[index])
567    item = (name: text.os_string_over(name), value: text.os_string_over(value))
568end memory_variable
569
570memory_variable_named: (self: memory_variables, name: text.os_string)
571                       -> (value: text.os_string from self) ! mem.not_found =
572    wanted: []u8 = text.os_string_bytes(name)
573    for at in usize(0)..<lenof self.entries do
574        (name: found, value: given) := memory_split(self.entries[at])
575        if memory_same_bytes(found, wanted) then
576            value = text.os_string_over(given)
577            return
578        end if
579    end for
580    fail mem.not_found
581end memory_variable_named
582
583memory_variables is environment
584    (variables_length: memory_variables_length, variable: memory_variable,
585     variable_named: memory_variable_named)
586
587--  Scripted programs, beside the memory world: a `programs` provider whose
588--  children are the caller's records.
589
590scripted_value: type = struct
591    world: memory
592    programs: []mut scripted_program
593end scripted_value
594
595--- A scripted child: a program a scripted provider runs in place of a real
596--- one.  What it writes and how it ends are given, and what it was given is
597--- recorded.  `spawn` of a path equal to `path` starts it.  It writes
598--- `output` and `errors` all at once when it starts: to the world's own
599--- standard output and error when a stream is inherited, to nothing when
600--- one is discarded, and into its pipe when one is piped, from which
601--- `read_child` reads them, output first.  `wait` reports `ending`, that it
602--- exited with a code or was signalled.  What the parent writes to its
603--- piped input with `write_child` is kept in `input`, its first
604--- `input_length` bytes, and a write that does not fit is `io_failed`,
605--- where a real pipe would wait.  The child's pipes are no files of the
606--- world: `reader` and `writer` refuse them.  The caller sets `path`,
607--- `output`, `errors`, `ending` and `input` and zeroes the rest, which the
608--- provider keeps: how many times it was started, how many arguments and
609--- variables its last start gave it, how much of its output and errors the
610--- parent has read, and whether it is running.  One record is one child at
611--- a time: starting a running one is `io_failed`.
612public scripted_program: type = struct
613    path: []u8
614    output: []u8
615    errors: []u8
616    ending: ending
617    input: []mut u8
618    input_length: usize
619    starts: usize
620    arguments: usize
621    variables: usize
622    output_read: usize
623    errors_read: usize
624    running: bool
625end scripted_program
626
627--- A provider of `programs` whose children are the caller's scripted records.
628--- It writes an inherited stream into a memory world's own standard output or
629--- error, and counts its reads in that world's state, whose read limit and
630--- failure point apply to them.  Copies share the records.
631public scripted_programs: type = scripted_value
632
633--- Scripted programs over `programs`, beside the memory world `world`,
634--- which the handle copies; keep the records alive while it is used.
635public scripted_over: (world: memory, programs: []mut scripted_program)
636                      -> (host: scripted_programs from world, programs) =
637    host = (world: world, programs: programs)
638end scripted_over
639
640--  A child's pipes are no files of the world: the scripted program's
641--  output and errors are read through read_child alone, and its input is
642--  written through write_child, so a world that runs no program carries
643--  none of it.  The child's files count down from the largest `usize`,
644--  three to a program, so no read or write of the world's takes one for a
645--  slot or a standard stream.
646
647memory_pipe_file: (index: usize, stream: usize) -> (opened: file) =
648    opened = file_value((0 -% 1) - 3 * index - stream)
649end memory_pipe_file
650
651--  Put BYTES after what the world's standard output, or with ERRORS its
652--  standard error, already holds, as an inherited stream would; what does
653--  not fit is lost, as it would be on a full device.
654memory_inherit: (self: scripted_programs, bytes: []u8, errors: bool) -> none =
655    return when lenof bytes == 0
656    state: ptr mut memory_space = self.world.state
657    if errors then
658        return when not state.val.errors_open
659          or state.val.errors_used > lenof self.world.errors
660        mut n: usize = lenof self.world.errors - state.val.errors_used
661        if n > lenof bytes then n = lenof bytes end if
662        for at in usize(0)..<n do
663            self.world.errors[state.val.errors_used + at] = bytes[at]
664        end for
665        state.val.errors_used += n
666    else
667        return when not state.val.output_open
668          or state.val.output_used > lenof self.world.output
669        mut n: usize = lenof self.world.output - state.val.output_used
670        if n > lenof bytes then n = lenof bytes end if
671        for at in usize(0)..<n do
672            self.world.output[state.val.output_used + at] = bytes[at]
673        end for
674        state.val.output_used += n
675    end if
676end memory_inherit
677
678--  Whether a variable's name is one a child can be given: nonempty, with
679--  no `=` and no NUL, as a real system requires.
680memory_name_valid: (name: []u8) -> (yes: bool) =
681    yes = lenof name > 0 and mem.find(name, u8('=')) == lenof name
682          and mem.find(name, 0) == lenof name
683end memory_name_valid
684
685memory_spawn: (self: scripted_programs, path: text.os_string,
686               arguments: []text.os_string, environment: []text.os_variable,
687               streams: child_streams)
688              -> (started: child) ! mem.not_found | no_access | io_failed =
689    inc self.world.state.val.opens
690    for item in environment do
691        name: []u8 = text.os_string_bytes(item.name)
692        fail io_failed when not memory_name_valid(name)
693    end for
694    wanted: []u8 = text.os_string_bytes(path)
695    for index in usize(0)..<lenof self.programs do
696        program: ptr mut scripted_program = addr self.programs[index]
697        if memory_same_bytes(wanted, program.val.path) then
698            fail io_failed when program.val.running
699            inc program.val.starts
700            program.val.arguments = lenof arguments
701            program.val.variables = lenof environment
702            program.val.input_length = 0
703            program.val.output_read = 0
704            program.val.errors_read = 0
705            program.val.running = true
706            if streams.output == inherited then
707                memory_inherit(self, program.val.output, false)
708            end if
709            if streams.errors == inherited then
710                memory_inherit(self, program.val.errors, true)
711            end if
712            if streams.output <> piped then
713                program.val.output_read = lenof program.val.output
714            end if
715            if streams.errors <> piped then
716                program.val.errors_read = lenof program.val.errors
717            end if
718            started = (handle: index, input: memory_pipe_file(index, 0),
719                       output: memory_pipe_file(index, 1),
720                       errors: memory_pipe_file(index, 2),
721                       input_open: streams.input == piped,
722                       output_open: streams.output == piped,
723                       errors_open: streams.errors == piped)
724            return
725        end if
726    end for
727    fail mem.not_found
728end memory_spawn
729
730--  The running program a child is.
731memory_child: (self: scripted_programs, started: child)
732              -> (program: ptr mut scripted_program from self) ! io_failed =
733    fail io_failed when started.handle >= lenof self.programs
734    program = addr self.programs[started.handle]
735    fail io_failed when not program.val.running
736end memory_child
737
738memory_close_input: (self: scripted_programs, inout started: child)
739                    -> none ! io_failed =
740    _ = try memory_child(self, started)
741    fail io_failed when not started.input_open
742    started.input_open = false
743end memory_close_input
744
745--  Take what remains of a program's output or errors after READ into
746--  INTO, as the world's reads take, its read limit and failure point
747--  among them.
748memory_take_child: (self: scripted_programs, source: []u8, read: usize, into: []mut u8)
749                   -> (count: usize) ! io_failed =
750    state: ptr mut memory_space = self.world.state
751    inc state.val.reads
752    fail io_failed when state.val.reads == state.val.fail_read_at
753    count = try memory_take(source, read, into, state.val.read_limit)
754end memory_take_child
755
756--  The program's output is read before its errors: it wrote both before
757--  the parent could read either.
758memory_read_child: (self: scripted_programs, inout started: child, into: []mut u8)
759                   -> (taken: child_read) ! io_failed =
760    program: ptr mut scripted_program = try memory_child(self, started)
761    taken = (count: 0, stream: child_output,
762             finished: not started.output_open and not started.errors_open)
763    return when lenof into == 0
764    taken.finished = true
765    if started.output_open then
766        count: usize = try memory_take_child(self, program.val.output,
767                                             program.val.output_read, into)
768        if count > 0 then
769            program.val.output_read += count
770            taken = (count: count, stream: child_output, finished: false)
771            return
772        end if
773        started.output_open = false
774    end if
775    if started.errors_open then
776        count: usize = try memory_take_child(self, program.val.errors,
777                                             program.val.errors_read, into)
778        if count > 0 then
779            program.val.errors_read += count
780            taken = (count: count, stream: child_errors, finished: false)
781            return
782        end if
783        started.errors_open = false
784    end if
785end memory_read_child
786
787--  Keep what the parent writes to a running program's piped input, which
788--  refuses what does not fit, where a real pipe would wait.
789memory_write_child: (self: scripted_programs, inout started: child, bytes: []u8)
790                    -> none ! io_failed =
791    program: ptr mut scripted_program = try memory_child(self, started)
792    kept: []mut u8 = program.val.input
793    fail io_failed when not started.input_open
794      or program.val.input_length > lenof kept
795      or lenof bytes > lenof kept - program.val.input_length
796    ends: usize = program.val.input_length + lenof bytes
797    mem.copy(kept[program.val.input_length..<ends], bytes) else (problem)
798        _ = problem
799        fail io_failed
800    end
801    program.val.input_length = ends
802end memory_write_child
803
804memory_wait: (self: scripted_programs, sink started: child)
805             -> (ended: ending) ! io_failed =
806    program: ptr mut scripted_program = try memory_child(self, started)
807    program.val.running = false
808    ended = program.val.ending
809end memory_wait
810
811scripted_programs is programs
812    (spawn: memory_spawn, write_child: memory_write_child,
813     close_input: memory_close_input, read_child: memory_read_child,
814     wait: memory_wait)