comparison win64-msvc/include/kj/async-win32.h @ 63:0f2d93caa50c

Update Win64 capnp builds to v0.6
author Chris Cannam
date Mon, 22 May 2017 18:56:49 +0100
parents
children
comparison
equal deleted inserted replaced
62:0994c39f1e94 63:0f2d93caa50c
1 // Copyright (c) 2016 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #ifndef KJ_ASYNC_WIN32_H_
23 #define KJ_ASYNC_WIN32_H_
24
25 #if !_WIN32
26 #error "This file is Windows-specific. On Unix, include async-unix.h instead."
27 #endif
28
29 #include "async.h"
30 #include "time.h"
31 #include "io.h"
32 #include <atomic>
33 #include <inttypes.h>
34
35 // Include windows.h as lean as possible. (If you need more of the Windows API for your app,
36 // #include windows.h yourself before including this header.)
37 #define WIN32_LEAN_AND_MEAN 1
38 #define NOSERVICE 1
39 #define NOMCX 1
40 #define NOIME 1
41 #include <windows.h>
42 #include "windows-sanity.h"
43
44 namespace kj {
45
46 class Win32EventPort: public EventPort {
47 // Abstract base interface for EventPorts that can listen on Win32 event types. Due to the
48 // absurd complexity of the Win32 API, it's not possible to standardize on a single
49 // implementation of EventPort. In particular, there is no way for a single thread to use I/O
50 // completion ports (the most efficient way of handling I/O) while at the same time waiting for
51 // signalable handles or UI messages.
52 //
53 // Note that UI messages are not supported at all by this interface because the message queue
54 // is implemented by user32.dll and we want libkj to depend only on kernel32.dll. A separate
55 // compat library could provide a Win32EventPort implementation that works with the UI message
56 // queue.
57
58 public:
59 // ---------------------------------------------------------------------------
60 // overlapped I/O
61
62 struct IoResult {
63 DWORD errorCode;
64 DWORD bytesTransferred;
65 };
66
67 class IoOperation {
68 public:
69 virtual LPOVERLAPPED getOverlapped() = 0;
70 // Gets the OVERLAPPED structure to pass to the Win32 I/O call. Do NOT modify it; just pass it
71 // on.
72
73 virtual Promise<IoResult> onComplete() = 0;
74 // After making the Win32 call, if the return value indicates that the operation was
75 // successfully queued (i.e. the completion event will definitely occur), call this to wait
76 // for completion.
77 //
78 // You MUST call this if the operation was successfully queued, and you MUST NOT call this
79 // otherwise. If the Win32 call failed (without queuing any operation or event) then you should
80 // simply drop the IoOperation object.
81 //
82 // Dropping the returned Promise cancels the operation via Win32's CancelIoEx(). The destructor
83 // will wait for the cancellation to complete, such that after dropping the proimse it is safe
84 // to free the buffer that the operation was reading from / writing to.
85 //
86 // You may safely drop the `IoOperation` while still waiting for this promise. You may not,
87 // however, drop the `IoObserver`.
88 };
89
90 class IoObserver {
91 public:
92 virtual Own<IoOperation> newOperation(uint64_t offset) = 0;
93 // Begin an I/O operation. For file operations, `offset` is the offset within the file at
94 // which the operation will start. For stream operations, `offset` is ignored.
95 };
96
97 virtual Own<IoObserver> observeIo(HANDLE handle) = 0;
98 // Given a handle which supports overlapped I/O, arrange to receive I/O completion events via
99 // this EventPort.
100 //
101 // Different Win32EventPort implementations may handle this in different ways, such as by using
102 // completion routines (APCs) or by using I/O completion ports. The caller should not assume
103 // any particular technique.
104 //
105 // WARNING: It is only safe to call observeIo() on a particular handle once during its lifetime.
106 // You cannot observe the same handle from multiple Win32EventPorts, even if not at the same
107 // time. This is because the Win32 API provides no way to disassociate a handle from an I/O
108 // completion port once it is associated.
109
110 // ---------------------------------------------------------------------------
111 // signalable handles
112 //
113 // Warning: Due to limitations in the Win32 API, implementations of EventPort may be forced to
114 // spawn additional threads to wait for signaled objects. This is necessary if the EventPort
115 // implementation is based on I/O completion ports, or if you need to wait on more than 64
116 // handles at once.
117
118 class SignalObserver {
119 public:
120 virtual Promise<void> onSignaled() = 0;
121 // Returns a promise that completes the next time the handle enters the signaled state.
122 //
123 // Depending on the type of handle, the handle may automatically be reset to a non-signaled
124 // state before the promise resolves. The underlying implementaiton uses WaitForSingleObject()
125 // or an equivalent wait call, so check the documentation for that to understand the semantics.
126 //
127 // If the handle is a mutex and it is abandoned without being unlocked, the promise breaks with
128 // an exception.
129
130 virtual Promise<bool> onSignaledOrAbandoned() = 0;
131 // Like onSingaled(), but instead of throwing when a mutex is abandoned, resolves to `true`.
132 // Resolves to `false` for non-abandoned signals.
133 };
134
135 virtual Own<SignalObserver> observeSignalState(HANDLE handle) = 0;
136 // Given a handle that supports waiting for it to become "signaled" via WaitForSingleObject(),
137 // return an object that can wait for this state using the EventPort.
138
139 // ---------------------------------------------------------------------------
140 // APCs
141
142 virtual void allowApc() = 0;
143 // If this is ever called, the Win32EventPort will switch modes so that APCs can be scheduled
144 // on the thread, e.g. through the Win32 QueueUserAPC() call. In the future, this may be enabled
145 // by default. However, as of this writing, Wine does not support the necessary
146 // GetQueuedCompletionStatusEx() call, thus allowApc() breaks Wine support. (Tested on Wine
147 // 1.8.7.)
148 //
149 // If the event port implementation can't support APCs for some reason, this throws.
150
151 // ---------------------------------------------------------------------------
152 // time
153
154 virtual Timer& getTimer() = 0;
155 };
156
157 class Win32WaitObjectThreadPool {
158 // Helper class that implements Win32EventPort::observeSignalState() by spawning additional
159 // threads as needed to perform the actual waiting.
160 //
161 // This class is intended to be used to assist in building Win32EventPort implementations.
162
163 public:
164 Win32WaitObjectThreadPool(uint mainThreadCount = 0);
165 // `mainThreadCount` indicates the number of objects the main thread is able to listen on
166 // directly. Typically this would be zero (e.g. if the main thread watches an I/O completion
167 // port) or MAXIMUM_WAIT_OBJECTS (e.g. if the main thread is a UI thread but can use
168 // MsgWaitForMultipleObjectsEx() to wait on some handles at the same time as messages).
169
170 Own<Win32EventPort::SignalObserver> observeSignalState(HANDLE handle);
171 // Implemetns Win32EventPort::observeSignalState().
172
173 uint prepareMainThreadWait(HANDLE* handles[]);
174 // Call immediately before invoking WaitForMultipleObjects() or similar in the main thread.
175 // Fills in `handles` with the handle pointers to wait on, and returns the number of handles
176 // in this array. (The array should be allocated to be at least the size passed to the
177 // constructor).
178 //
179 // There's no need to call this if `mainThreadCount` as passed to the constructor was zero.
180
181 bool finishedMainThreadWait(DWORD returnCode);
182 // Call immediately after invoking WaitForMultipleObjects() or similar in the main thread,
183 // passing the value returend by that call. Returns true if the event indicated by `returnCode`
184 // has been handled (i.e. it was WAIT_OBJECT_n or WAIT_ABANDONED_n where n is in-range for the
185 // last call to prepareMainThreadWait()).
186 };
187
188 class Win32IocpEventPort final: public Win32EventPort {
189 // An EventPort implementation which uses Windows I/O completion ports to listen for events.
190 //
191 // With this implementation, observeSignalState() requires spawning a separate thread.
192
193 public:
194 Win32IocpEventPort();
195 ~Win32IocpEventPort() noexcept(false);
196
197 // implements EventPort ------------------------------------------------------
198 bool wait() override;
199 bool poll() override;
200 void wake() const override;
201
202 // implements Win32IocpEventPort ---------------------------------------------
203 Own<IoObserver> observeIo(HANDLE handle) override;
204 Own<SignalObserver> observeSignalState(HANDLE handle) override;
205 Timer& getTimer() override { return timerImpl; }
206 void allowApc() override { isAllowApc = true; }
207
208 private:
209 class IoPromiseAdapter;
210 class IoOperationImpl;
211 class IoObserverImpl;
212
213 AutoCloseHandle iocp;
214 AutoCloseHandle thread;
215 Win32WaitObjectThreadPool waitThreads;
216 TimerImpl timerImpl;
217 mutable std::atomic<bool> sentWake {false};
218 bool isAllowApc = false;
219
220 static TimePoint readClock();
221
222 void waitIocp(DWORD timeoutMs);
223 // Wait on the I/O completion port for up to timeoutMs and pump events. Does not advance the
224 // timer; caller must do that.
225
226 bool receivedWake();
227
228 static AutoCloseHandle newIocpHandle();
229 static AutoCloseHandle openCurrentThread();
230 };
231
232 } // namespace kj
233
234 #endif // KJ_ASYNC_WIN32_H_