annotate osx/include/kj/async-win32.h @ 68:85d5306e114e

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