Landin library reference discuss source

hosted/events/windows.ldn

1--  The event provider on Windows: its loop is an I/O completion port, and
2--  every wait is answered by the packet the system puts on it when the
3--  awaited thing has happened, the completion interface D486 foresaw.
4--  An operation on a pipe end `system.start` made or a socket, the
5--  handles that are opened overlapped, associates the handle with the
6--  port, issues the overlapped call with its `waiting` record's
7--  `overlapped`, and parks its fibre; the loop's wait,
8--  `GetQueuedCompletionStatusEx` limited by the earliest deadline, takes
9--  the call's packet and answers the record, and the fibre asks the call's
10--  result with `GetOverlappedResult`.  The system writes into the record
11--  and the caller's bytes until the packet is queued, so a fibre whose
12--  call is in flight does not return before its packet has come, whatever
13--  else answers it: a close through the provider or a deadline cancels the
14--  call and waits for the packet of its cancelling.  Every other handle, a
15--  file, a console or a pipe the process was given, was opened without
16--  overlapping and is read and written by a plain call that holds the
17--  thread, as a regular file is on the other systems.
18
19import core/fibre
20import core/io
21import hosted/system
22import platform/windows
23
24fixed if compiler.os == windows then
25    --  One operation waiting, kept on the stack of the fibre that waits:
26    --  the overlapped record of its call, which the system writes until
27    --  the call's packet is queued; the handle it was issued on, zero for
28    --  none, and whether the call sends or writes; the ID of a child whose end it waits for, zero for none;
29    --  whether it waits for a control event; its deadline, zero for none;
30    --  the answer; whether its call is in flight, which only the call's
31    --  packet answers; and the answer that packet gives when the call was
32    --  cancelled, `pending` when it was not.
33    waiting: type = struct
34        asked: windows.overlapped
35        next: usize
36        handle: windows.handle
37        output: bool
38        child: i32
39        signalled: bool
40        deadline: u64
41        answer: u8
42        flight: bool
43        cut: u8
44    end waiting
45
46    --  A record for an overlapped call on `made`, until `deadline`.
47    on_handle: (made: windows.handle, deadline: u64) -> (entry: waiting) =
48        entry = (asked: zeroed, next: 0, handle: made, output: false,
49                 child: 0,
50                 signalled: false, deadline: deadline, answer: pending,
51                 flight: true, cut: pending)
52    end on_handle
53
54    --  A record that waits for `deadline` alone.
55    on_deadline: (deadline: u64) -> (entry: waiting) =
56        entry = (asked: zeroed, next: 0, handle: windows.no_handle,
57                 output: false, child: 0,
58                 signalled: false, deadline: deadline, answer: pending,
59                 flight: false, cut: pending)
60    end on_deadline
61
62    --  The keys of the port's packets: an overlapped call's, the job's
63    --  and the control handler's.
64    call_key: usize = 1
65    job_key: usize = 2
66    control_key: usize = 3
67
68    --  The loop: its port, the list of waiting records, whether a fibre
69    --  took a turn of its own since the last wait, the job its children
70    --  are put in, zero until the first child is waited for, and the
71    --  control events: the watched kinds as bits by `signal.kind`'s index,
72    --  whether watching stopped, and the events not yet read, by their
73    --  codes, in arrival order.
74    loop_state: type = struct
75        queue: windows.handle
76        first: usize
77        turned: bool
78        job: windows.handle
79        watched: u32
80        stopped: bool
81        arrived: [6]u8
82        queued: usize
83        reports: [16]windows.completion_entry
84    end loop_state
85
86    --  The loop with nothing in it and no port yet.
87    emptied: (state: ptr mut loop_state) -> none =
88        state.val.queue = windows.no_handle
89        state.val.first = 0
90        state.val.turned = false
91        state.val.job = windows.no_handle
92        state.val.watched = 0
93        state.val.stopped = false
94        state.val.queued = 0
95    end emptied
96
97    --  Make the loop's port, or keep the code of why the system made none.
98    queue_made: (state: ptr mut loop_state, services: system.host)
99                -> none ! io.io_failed =
100        made: windows.handle = windows.completion_port(windows.invalid_handle,
101                                                       windows.no_handle, 0, 1)
102        if made == windows.no_handle then
103            system.record_errno(services, windows.last_error())
104            fail io.io_failed
105        end if
106        state.val.queue = made
107    end queue_made
108
109    --  Keep a failure's Win32 code in the system handle's cell.
110    record: (self: host, code: u32) -> none =
111        system.record_errno(self.services, code)
112    end record
113
114    --  Cancel the call `entry` has in flight, which its packet answers
115    --  with `cut` unless the call ended first.  A call that ended already
116    --  has its packet queued.
117    cut_short: (entry: ptr mut waiting, cut: u8) -> none =
118        if entry.val.cut == pending then entry.val.cut = cut end if
119        _ = windows.cancel_io(entry.val.handle, usize(addr entry.val.asked))
120    end cut_short
121
122    --  Answer every record whose deadline the clock has reached; a call in
123    --  flight is cancelled, and answered `expired` by its packet.
124    answer_expired: (state: ptr mut loop_state, now: u64) -> none =
125        mut at: usize = state.val.first
126        while at <> 0 do
127            here: ptr mut waiting = entry_at(at)
128            at = here.val.next
129            if here.val.deadline <> 0 and here.val.deadline <= now then
130                here.val.deadline = 0
131                if here.val.flight then
132                    cut_short(here, expired)
133                else
134                    settle(state, here, expired)
135                end if
136            end if
137        end while
138    end answer_expired
139
140    --  Answer the record whose call's overlapped record is at `address`;
141    --  a packet of a call no record waits for any longer, one hosted/blocking
142    --  made on a handle the port has, is let go.
143    answer_call: (state: ptr mut loop_state, address: usize) -> none =
144        mut at: usize = state.val.first
145        while at <> 0 do
146            here: ptr mut waiting = entry_at(at)
147            at = here.val.next
148            if here.val.flight and usize(addr here.val.asked) == address then
149                here.val.flight = false
150                settle(state, here, if here.val.cut <> pending then here.val.cut
151                                    else ready end if)
152                return
153            end if
154        end while
155    end answer_call
156
157    --  Wait for packets up to `milliseconds`, forever when negative: how
158    --  many it took.  A wait that fails is a wait that took none; the loop
159    --  looks again.
160    wait_events: (state: ptr mut loop_state, milliseconds: i32)
161                 -> (count: usize) =
162        count = 0
163        limit: u32 = if milliseconds < 0 then windows.infinite
164                     else u32(milliseconds) end if
165        mut taken: u32 = 0
166        return when windows.get_completions(state.val.queue,
167                                            addr state.val.reports[0],
168                                            u32(report_count), addr taken,
169                                            limit, 0) == 0
170        count = usize(taken)
171        if count > report_count then count = report_count end if
172    end wait_events
173
174    dispatch: (state: ptr mut loop_state, count: usize) -> none =
175        for index in usize(0)..<count do
176            got: windows.completion_entry = state.val.reports[index]
177            if got.key == call_key then
178                answer_call(state, got.record)
179            elsif got.key == job_key then
180                if got.moved == windows.job_exit_process
181                  or got.moved == windows.job_abnormal_exit_process then
182                    answer_child(state, i32(u32(got.record)))
183                end if
184            elsif got.key == control_key then
185                arrive(state, got.moved)
186                answer_signals(state, ready)
187            end if
188        end for
189    end dispatch
190
191    --  Take turns until the loop answers `entry`, which is on the list
192    --  and, with a call in flight, stays there until its packet comes.
193    answered: (self: host, entry: ptr mut waiting) -> (answer: u8) =
194        while entry.val.answer == pending do
195            fibre.yield(self.round)
196        end while
197        answer = entry.val.answer
198    end answered
199
200    --  Wait for a record that waits on no call.
201    parked: (self: host, entry: ptr mut waiting) -> none =
202        entry.val.answer = pending
203        link(self.state, entry)
204        _ = answered(self, entry)
205    end parked
206
207    --  Associate `made` with the loop's port, once: a handle associated
208    --  already, with this port or another, is refused as a bad parameter,
209    --  and is taken as associated.
210    joined: (self: host, made: windows.handle) -> none ! io.io_failed =
211        return when windows.completion_port(made, self.state.val.queue,
212                                            call_key, 0) <> windows.no_handle
213        code: u32 = windows.last_error()
214        return when code == windows.error_invalid_parameter
215        record(self, code)
216        fail io.io_failed
217    end joined
218
219    --  What an overlapped call ended with: the bytes it moved, and zero or
220    --  the reason it failed.
221    call_result: type = struct
222        moved: u32
223        code: u32
224        answer: u8
225    end call_result
226
227    --  Wait for the call `entry` records, which the system was given and
228    --  answered `issued` with, and return how it ended.  A call the system
229    --  refused at once queues no packet and is taken off the list.
230    completed: (self: host, made: windows.handle, entry: ptr mut waiting,
231                issued: i32) -> (result: call_result) =
232        if issued == 0 then
233            code: u32 = windows.last_error()
234            if code <> windows.error_io_pending then
235                unlink(self.state, entry)
236                result = (moved: 0, code: code, answer: failed)
237                return
238            end if
239        end if
240        answer: u8 = answered(self, entry)
241        mut got: u32 = 0
242        mut code: u32 = 0
243        if windows.overlapped_result(made, addr entry.val.asked, addr got,
244                                     0) == 0 then
245            code = windows.last_error()
246        end if
247        result = (moved: got, code: code, answer: answer)
248    end completed
249
250    --  How many bytes one call moves at most: what a DWORD counts.
251    most: usize = 0x40000000
252
253    --  The end of what a stream gives: a pipe whose writer has gone, or a
254    --  file read at its end.
255    finished: (code: u32) -> (yes: bool) =
256        yes = code == windows.error_broken_pipe
257              or code == windows.error_handle_eof
258              or code == windows.error_pipe_not_connected
259    end finished
260
261    --  Read once into `into` from `opened`, waiting as a fibre does when
262    --  the call goes through the port, a socket's or a child's pipe's: the
263    --  count, zero at the end.
264    read_once: (self: host, opened: io.file, into: []mut u8)
265               -> (count: usize) ! io.io_failed =
266        made: windows.handle = system.handle_of(opened)
267        mut want: usize = lenof into
268        if want > most then want = most end if
269        count = 0
270        mut got: u32 = 0
271        if system.is_socket(opened) then
272            ended: call_result = try received_once(self, made, into, 0)
273            return when ended.code == 0 and ended.moved == 0
274            if ended.code <> 0 then
275                record(self, ended.code)
276                fail io.io_failed
277            end if
278            got = ended.moved
279        elsif system.is_pipe(opened) then
280            try joined(self, made)
281            mut entry: waiting = on_handle(made, 0)
282            link(self.state, addr entry)
283            issued: i32 = windows.read_file(made, addr into[0], u32(want),
284                                            addr got,
285                                            usize(addr entry.asked))
286            ended: call_result = completed(self, made, addr entry, issued)
287            return when finished(ended.code)
288            if ended.code <> 0 then
289                record(self, ended.code)
290                fail io.io_failed
291            end if
292            got = ended.moved
293        elsif windows.read_file(made, addr into[0], u32(want), addr got,
294                                0) == 0 then
295            code: u32 = windows.last_error()
296            return when finished(code)
297            record(self, code)
298            fail io.io_failed
299        end if
300        fail io.io_failed when usize(got) > lenof into
301        count = usize(got)
302    end read_once
303
304    --  Write some of `bytes` to `opened` once, waiting as a fibre does when
305    --  the call goes through the port: the count accepted.
306    write_once: (self: host, opened: io.file, bytes: []u8)
307                -> (count: usize) ! io.io_failed =
308        made: windows.handle = system.handle_of(opened)
309        mut want: usize = lenof bytes
310        if want > most then want = most end if
311        mut put: u32 = 0
312        if system.is_socket(opened) then
313            ended: call_result = try sent_once(self, made, bytes, 0)
314            if ended.code <> 0 then
315                record(self, ended.code)
316                fail io.io_failed
317            end if
318            put = ended.moved
319        elsif system.is_pipe(opened) then
320            try joined(self, made)
321            mut entry: waiting = on_handle(made, 0)
322            entry.output = true
323            link(self.state, addr entry)
324            issued: i32 = windows.write_file(made, addr bytes[0], u32(want),
325                                             addr put,
326                                             usize(addr entry.asked))
327            ended: call_result = completed(self, made, addr entry, issued)
328            if ended.code <> 0 then
329                record(self, ended.code)
330                fail io.io_failed
331            end if
332            put = ended.moved
333        elsif windows.write_file(made, addr bytes[0], u32(want), addr put,
334                                 0) == 0 then
335            record(self, windows.last_error())
336            fail io.io_failed
337        end if
338        fail io.io_failed when usize(put) > want or put == 0
339        count = usize(put)
340    end write_once
341
342    events_read: (self: host, opened: io.file, into: []mut u8)
343                 -> (count: usize) ! io.io_failed =
344        cleared(self)
345        count = 0
346        return when lenof into == 0
347        count = try read_once(self, opened, into)
348    end events_read
349
350    write_all: (self: host, opened: io.file, bytes: []u8)
351               -> none ! io.io_failed =
352        mut written: usize = 0
353        while written < lenof bytes do
354            written += try write_once(self, opened,
355                                      bytes[written..<lenof bytes])
356        end while
357    end write_all
358
359    events_write: (self: host, opened: io.file, bytes: []u8)
360                  -> none ! io.io_failed =
361        cleared(self)
362        return when lenof bytes == 0
363        try write_all(self, opened, bytes)
364    end events_write
365
366    events_write_some: (self: host, opened: io.file, bytes: []u8)
367                       -> (count: usize) ! io.io_failed =
368        cleared(self)
369        count = 0
370        return when lenof bytes == 0
371        mut requested: usize = lenof bytes
372        if requested > 65536 then requested = 65536 end if
373        count = try write_once(self, opened, bytes[0..<requested])
374    end events_write_some
375
376    --  Wake every fibre waiting on `made`, failing its call: the handle is
377    --  about to be closed through the provider (D449).  A call in flight is
378    --  cancelled, and its fibre wakes when the cancelling's packet comes,
379    --  which the close does not wait for.
380    forget: (self: host, made: windows.handle) -> none =
381        state: ptr mut loop_state = self.state
382        mut at: usize = state.val.first
383        while at <> 0 do
384            here: ptr mut waiting = entry_at(at)
385            at = here.val.next
386            if here.val.handle == made then
387                if here.val.flight then
388                    cut_short(here, failed)
389                else
390                    settle(state, here, failed)
391                end if
392            end if
393        end while
394    end forget
395
396    events_close: (self: host, sink opened: io.file) -> none ! io.io_failed =
397        forget(self, system.handle_of(opened))
398        try io.close(self.services, opened)
399    end events_close
400end if