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