Landin library reference discuss source

hosted/system/windows_programs.ldn

1--  Starting a program on Windows, as programs.ldn does over platform/posix:
2--  `start` makes the child's three standard streams, starts it with
3--  `CreateProcessW` and does not wait.  A piped stream is a named pipe
4--  whose parent end is overlapped and carries `pipe_mark`, so that a
5--  provider built over this one reads and writes it through an
6--  overlapped call and waits as its own waiting does (D2271).  The child
7--  inherits exactly its three streams, through the attribute list
8--  `PROC_THREAD_ATTRIBUTE_HANDLE_LIST` names, and no other handle.
9
10import core/atomic
11import core/io
12import core/mem
13import core/text
14import platform/windows
15
16fixed if compiler.os == windows then
17    --  A pipe's parent end carries this bit beside its handle.
18    pipe_mark: usize = 0x2000000000000000
19
20    --- Whether `opened` is a pipe end `start` made, which a provider built
21    --- over this one reads and writes with an overlapped call.
22    public is_pipe: (opened: io.file) -> (yes: bool) =
23        yes = (usize(opened) & pipe_mark) <> 0
24    end is_pipe
25
26    --  Each pipe's name is the process's ID and a number no other pipe of
27    --  the process has had.
28    mut pipe_count: atomic.cell(u64) = zeroed
29
30    --  One end of the child's stream: the handle the child is given, the
31    --  parent's end of a pipe, and whether each is open.
32    stream_end: type = struct
33        child_side: windows.handle
34        parent_side: windows.handle
35        piped: bool
36    end stream_end
37
38    --  Keep a failure's code and fail.
39    lost: (self: host, code: u32) -> none ! io.io_failed =
40        record(self, code)
41        fail io.io_failed
42    end lost
43
44    no_end: stream_end = (child_side: windows.no_handle,
45                          parent_side: windows.no_handle, piped: false)
46
47    --  Put `value`'s hexadecimal digits into `into` from `at`, and return
48    --  where they end.
49    hexadecimal: (value: u64, into: []mut u8, at: usize) -> (next: usize) =
50        digits: []u8 = "0123456789abcdef"
51        mut shift: u64 = 64
52        next = at
53        while shift > 0 do
54            shift -= 4
55            into[next] = digits[usize((value >> shift) & 0xF)]
56            inc next
57        end while
58    end hexadecimal
59
60    --  The attributes that make a handle a child may inherit.
61    inheritable: () -> (attributes: windows.security_attributes) =
62        attributes = (length: u32(sizeof windows.security_attributes),
63                      descriptor: 0, inherit: 1)
64    end inheritable
65
66    --  A named pipe the child writes to, `child_writes`, or reads from:
67    --  the parent's end overlapped and not inherited, the child's
68    --  inheritable and plain.
69    pipe: (self: host, child_writes: bool) -> (made: stream_end) ! io.io_failed =
70        mut name_bytes: [64]u8 = zeroed
71        prefix: []u8 = "\\\\.\\pipe\\landin-"
72        for at in usize(0)..<lenof prefix do name_bytes[at] = prefix[at] end for
73        mut length: usize = hexadecimal(u64(windows.current_process_id()),
74                                        name_bytes, lenof prefix)
75        name_bytes[length] = u8('-')
76        number: u64 = atomic.add(item: u64, at: addr pipe_count, value: 1)
77        length = hexadecimal(number, name_bytes, length + 1)
78        mut room: [64]u16 = zeroed
79        name: ptr u16 = windows.terminate(text.os_string_over(name_bytes[0..<length]),
80                                          room) else (problem)
81            try lost(self, windows.code_of(problem))
82            fail io.io_failed
83        end
84        access: u32 = if child_writes then windows.pipe_access_inbound
85                      else windows.pipe_access_outbound end if
86        parent: windows.handle = windows.create_named_pipe(
87            name, access | windows.flag_overlapped | windows.pipe_first_instance,
88            windows.pipe_byte_wait_local, 1, 65536, 65536, 0, 0)
89        if parent == windows.invalid_handle then
90            try lost(self, windows.last_error())
91        end if
92        security: windows.security_attributes = inheritable()
93        child_access: u32 = if child_writes then windows.generic_write
94                            else windows.generic_read
95                                 | windows.file_write_attributes end if
96        child: windows.handle = windows.create_file(
97            name, child_access, 0, usize(addr security), windows.open_existing,
98            0, 0)
99        if child == windows.invalid_handle then
100            code: u32 = windows.last_error()
101            _ = windows.close_handle(parent)
102            try lost(self, code)
103        end if
104        made = (child_side: child, parent_side: parent, piped: true)
105    end pipe
106
107    nul_name: [4]u16 = [78, 85, 76, 0]
108
109    --  The child's end of one stream, as `choice` says; `which` is the
110    --  parent's own standard handle that an inherited stream duplicates.
111    prepared: (self: host, choice: io.stream_choice, which: u32,
112               child_writes: bool) -> (made: stream_end) ! io.io_failed =
113        made = no_end
114        if choice == io.piped then
115            made = try pipe(self, child_writes)
116        elsif choice == io.discarded then
117            security: windows.security_attributes = inheritable()
118            opened: windows.handle = windows.create_file(
119                addr nul_name[0], windows.generic_read | windows.generic_write,
120                windows.share_all, usize(addr security), windows.open_existing,
121                0, 0)
122            if opened == windows.invalid_handle then
123                try lost(self, windows.last_error())
124            end if
125            made = (child_side: opened, parent_side: windows.no_handle,
126                    piped: false)
127        else
128            own: windows.handle = windows.get_std_handle(which)
129            return when own == windows.no_handle or own == windows.invalid_handle
130            self_process: windows.handle = windows.current_process()
131            mut copy: windows.handle = windows.no_handle
132            if windows.duplicate_handle(self_process, own, self_process,
133                                        addr copy, 0, 1,
134                                        windows.duplicate_same_access) == 0 then
135                try lost(self, windows.last_error())
136            end if
137            made = (child_side: copy, parent_side: windows.no_handle,
138                    piped: false)
139        end if
140    end prepared
141
142    --  Close what `made` holds: the child's end always, the parent's too
143    --  when `everything`.
144    dropped: (made: stream_end, everything: bool) -> none =
145        if made.child_side <> windows.no_handle then
146            _ = windows.close_handle(made.child_side)
147        end if
148        if everything and made.parent_side <> windows.no_handle then
149            _ = windows.close_handle(made.parent_side)
150        end if
151    end dropped
152
153    blank_or_quote: (byte: u8) -> (yes: bool) =
154        yes = byte == 32 or byte == 9 or byte == 10 or byte == 11
155              or byte == 34
156    end blank_or_quote
157
158    --  The bytes `quoted` writes for `argument`, at most.
159    quoted_room: (argument: []u8) -> (room: usize) =
160        room = 2 * lenof argument + 3
161    end quoted_room
162
163    --  Write `argument` into `into` from `at` as Microsoft's C runtime
164    --  splits it back, quoted when it is empty or holds a blank or a quote:
165    --  each backslash before a quote or the closing quote doubled, and each
166    --  quote escaped.  A space goes before it unless it is the first.
167    quoted: (argument: []u8, into: []mut u8, at: usize, first: bool)
168            -> (next: usize) =
169        next = at
170        if not first then
171            into[next] = 32
172            inc next
173        end if
174        mut plain: bool = lenof argument > 0
175        for byte in argument do
176            if blank_or_quote(byte) then plain = false end if
177        end for
178        if plain then
179            for byte in argument do
180                into[next] = byte
181                inc next
182            end for
183            return
184        end if
185        into[next] = 34
186        inc next
187        mut slashes: usize = 0
188        for byte in argument do
189            if byte == 92 then
190                inc slashes
191            elsif byte == 34 then
192                while slashes > 0 do
193                    into[next] = 92
194                    into[next + 1] = 92
195                    next += 2
196                    dec slashes
197                end while
198                into[next] = 92
199                into[next + 1] = 34
200                next += 2
201                continue
202            else
203                while slashes > 0 do
204                    into[next] = 92
205                    inc next
206                    dec slashes
207                end while
208            end if
209            if byte <> 92 then
210                into[next] = byte
211                inc next
212            end if
213        end for
214        while slashes > 0 do
215            into[next] = 92
216            into[next + 1] = 92
217            next += 2
218            dec slashes
219        end while
220        into[next] = 34
221        inc next
222    end quoted
223
224    --  Storage taken from the system for one start and given back.
225    block: type = struct
226        address: usize
227        size: usize
228    end block
229
230    taken: (self: host, size: usize) -> (made: block) ! io.io_failed =
231        address: usize = windows.virtual_alloc(0, size,
232                                               windows.mem_reserve
233                                               | windows.mem_commit,
234                                               windows.page_readwrite)
235        if address == 0 then
236            try lost(self, windows.last_error())
237        end if
238        made = (address: address, size: size)
239    end taken
240
241    given_back: (made: block) -> none =
242        _ = windows.virtual_free(made.address, 0, windows.mem_release)
243    end given_back
244
245    bytes_of: (made: block) -> (bytes: []mut u8) =
246        whole: ptr mut [1]u8 = ptr(made.address)
247        bytes = whole.val[0..<0]
248        unchecked begin
249            bytes = whole.val[0..<made.size]
250        end unchecked
251    end bytes_of
252
253    units_of: (made: block) -> (units: []mut u16) =
254        whole: ptr mut [1]u16 = ptr(made.address)
255        units = whole.val[0..<0]
256        unchecked begin
257            units = whole.val[0..<made.size / 2]
258        end unchecked
259    end units_of
260
261    --  The longest command line Windows takes, in units, its NUL counted.
262    longest_line: usize = 32768
263
264    --  The command line: the program's path, then each argument, quoted,
265    --  as units ending in a NUL.  The parent's own name goes first, as a C
266    --  parent gives `argv[0]`.
267    command_line: (self: host, path: text.os_string,
268                   arguments: []text.os_string) -> (made: block) ! io.io_failed =
269        mut size: usize = quoted_room(text.os_string_bytes(path))
270        for argument in arguments do
271            size += quoted_room(text.os_string_bytes(argument))
272        end for
273        if size >= longest_line then
274            try lost(self, windows.error_filename_exceeds_range)
275        end if
276        bytes: block = try taken(self, size + 1)
277        defer given_back(bytes)
278        room: []mut u8 = bytes_of(bytes)
279        mut at: usize = quoted(text.os_string_bytes(path), room, 0, true)
280        for argument in arguments do
281            at = quoted(text.os_string_bytes(argument), room, at, false)
282        end for
283        made = try taken(self, 2 * (at + 1))
284        units: []mut u16 = units_of(made)
285        count: usize = windows.to_units(room[0..<at], units) else (problem)
286            given_back(made)
287            try lost(self, windows.code_of(problem))
288            fail io.io_failed
289        end
290        units[count] = 0
291    end command_line
292
293    --  The environment block: each `name=value` as units ending in a NUL,
294    --  and a NUL after the last, which an empty block holds twice.
295    environment_block: (self: host, environment: []text.os_variable)
296                       -> (made: block) ! io.io_failed =
297        mut size: usize = 2
298        for item in environment do
299            size += lenof text.os_string_bytes(item.name)
300                    + lenof text.os_string_bytes(item.value) + 2
301        end for
302        made = try taken(self, 2 * size)
303        units: []mut u16 = units_of(made)
304        mut at: usize = 0
305        equals: [1]u8 = [61]
306        for item in environment do
307            name: []u8 = text.os_string_bytes(item.name)
308            if lenof name == 0 or mem.find(name[1..<lenof name], u8('=')) < lenof name - 1 then
309                given_back(made)
310                try lost(self, windows.error_invalid_parameter)
311            end if
312            pieces: [3][]u8 = [name, equals[0..<1],
313                               text.os_string_bytes(item.value)]
314            for piece in pieces do
315                at += windows.to_units(piece, units[at..<lenof units]) else (problem)
316                    given_back(made)
317                    try lost(self, windows.code_of(problem))
318                    fail io.io_failed
319                end
320            end for
321            units[at] = 0
322            inc at
323        end for
324        units[at] = 0
325        if at == 0 then units[1] = 0 end if
326    end environment_block
327
328    --  The attribute list's room: one attribute needs about fifty bytes.
329    attribute_room: type = [16]usize
330
331    launched: (self: host, path: text.os_string, arguments: []text.os_string,
332               environment: []text.os_variable, streams: io.child_streams)
333              -> (started: io.child)
334              ! mem.not_found | io.no_access | io.io_failed =
335        mut application: windows.path_room = zeroed
336        program: ptr u16 = windows.terminate(path, application) else (problem)
337            try lost(self, windows.code_of(problem))
338            fail io.io_failed
339        end
340        line: block = try command_line(self, path, arguments)
341        defer given_back(line)
342        variables: block = try environment_block(self, environment)
343        defer given_back(variables)
344        input: stream_end = try prepared(self, streams.input, windows.std_input,
345                                         false)
346        undo dropped(input, true)
347        output: stream_end = try prepared(self, streams.output, windows.std_output,
348                                          true)
349        undo dropped(output, true)
350        errors: stream_end = try prepared(self, streams.errors, windows.std_error,
351                                          true)
352        undo dropped(errors, true)
353        mut handles: [3]windows.handle = zeroed
354        mut count: usize = 0
355        sides: [3]windows.handle = [input.child_side, output.child_side,
356                                    errors.child_side]
357        for side in sides do
358            if side <> windows.no_handle then
359                handles[count] = side
360                inc count
361            end if
362        end for
363        mut list: attribute_room = zeroed
364        mut size: usize = sizeof attribute_room
365        if windows.initialize_attributes(usize(addr list), 1, 0,
366                                         addr size) == 0 then
367            try lost(self, windows.last_error())
368        end if
369        defer windows.delete_attributes(usize(addr list))
370        if count > 0 then
371            if windows.update_attribute(usize(addr list), 0,
372                                        windows.attribute_handle_list,
373                                        usize(addr handles[0]),
374                                        count * sizeof windows.handle,
375                                        0, 0) == 0 then
376                try lost(self, windows.last_error())
377            end if
378        end if
379        mut startup: windows.startup_information = zeroed
380        startup.size = u32(sizeof windows.startup_information)
381        startup.flags = windows.use_std_handles
382        startup.input = input.child_side
383        startup.output = output.child_side
384        startup.errors = errors.child_side
385        startup.attributes = usize(addr list)
386        mut made: windows.process_information = zeroed
387        units: []mut u16 = units_of(line)
388        if windows.create_process(program, addr units[0], 0, 0, 1,
389                                  windows.unicode_environment
390                                  | windows.extended_startup,
391                                  variables.address, 0, addr startup,
392                                  addr made) == 0 then
393            try path_failure(self, windows.last_error())
394        end if
395        _ = windows.close_handle(made.thread)
396        dropped(input, false)
397        dropped(output, false)
398        dropped(errors, false)
399        started = (handle: made.process,
400                   input: io.file(input.parent_side | pipe_mark),
401                   output: io.file(output.parent_side | pipe_mark),
402                   errors: io.file(errors.parent_side | pipe_mark),
403                   input_open: input.piped, output_open: output.piped,
404                   errors_open: errors.piped)
405    end launched
406
407    --  On Windows `path` is not looked up on a search path and is given no
408    --  extension.  A discarded stream is the system's `NUL`; a piped one a
409    --  named pipe whose parent end is overlapped, which `is_pipe` says of
410    --  it; an inherited one the parent's own standard handle, duplicated.
411    --  The child inherits those three handles and no other, and the code
412    --  kept is the Win32 error.
413    --- Start the program at `path` as `io.programs`' `spawn` says. It is for a
414    --- provider built over this handle that supplies `io.programs`: `start`
415    --- starts the child and does not wait. The provider itself reads, writes
416    --- and closes the parent's ends of the child's pipes, files of this
417    --- provider, and waits for the child through whatever waiting it does
418    --- (D479). It fails `not_found` for a missing program, `no_access` for one
419    --- the caller may not run and `io_failed` for the rest, the system's code
420    --- kept in the handle's last-error cell. On any failure no child was
421    --- started and nothing `start` made is left open. `io.child`'s `handle`
422    --- names the child as `process_of` gives it.
423    public start: (handle: host, path: text.os_string,
424                   arguments: []text.os_string,
425                   environment: []text.os_variable, streams: io.child_streams)
426                  -> (started: io.child)
427                  ! mem.not_found | io.no_access | io.io_failed =
428        keep_failure(handle, 0)
429        started = try launched(handle, path, arguments, environment, streams)
430    end start
431
432    --- Return the process handle of a child `start` started, for a provider
433    --- to wait for. The provider closes it once the child has ended.
434    public process_of: (started: io.child) -> (child: windows.handle) =
435        child = started.handle
436    end process_of
437
438    --- The portable ending of a child whose exit code a provider built over
439    --- this handle read: Windows ends a process only with a code, so it is
440    --- `exited` with the code's 32 bits, and the last-signal cell is zero.
441    public ended: (handle: host, code: u32) -> (result: io.ending) =
442        keep_signal(handle, 0)
443        result = (how: io.exited(code: i32(code)))
444    end ended
445end if