annotate win64-msvc/include/kj/async-win32.h @ 64:eccd51b72864

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