annotate win32-mingw/include/kj/async-unix.h @ 142:75bf92aa2d1f

Fixes and updates for 32-bit Windows build
author Chris Cannam <cannam@all-day-breakfast.com>
date Mon, 09 Jan 2017 11:53:06 +0000
parents 38d1c0e7850b
children eccd51b72864
rev   line source
cannam@135 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@135 2 // Licensed under the MIT License:
cannam@135 3 //
cannam@135 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@135 5 // of this software and associated documentation files (the "Software"), to deal
cannam@135 6 // in the Software without restriction, including without limitation the rights
cannam@135 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@135 8 // copies of the Software, and to permit persons to whom the Software is
cannam@135 9 // furnished to do so, subject to the following conditions:
cannam@135 10 //
cannam@135 11 // The above copyright notice and this permission notice shall be included in
cannam@135 12 // all copies or substantial portions of the Software.
cannam@135 13 //
cannam@135 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@135 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@135 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@135 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@135 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@135 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@135 20 // THE SOFTWARE.
cannam@135 21
cannam@135 22 #ifndef KJ_ASYNC_UNIX_H_
cannam@135 23 #define KJ_ASYNC_UNIX_H_
cannam@135 24
cannam@135 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@135 26 #pragma GCC system_header
cannam@135 27 #endif
cannam@135 28
cannam@135 29 #include "async.h"
cannam@135 30 #include "time.h"
cannam@135 31 #include "vector.h"
cannam@135 32 #include "io.h"
cannam@135 33 #include <signal.h>
cannam@135 34
cannam@135 35 #if __linux__ && !__BIONIC__ && !defined(KJ_USE_EPOLL)
cannam@135 36 // Default to epoll on Linux, except on Bionic (Android) which doesn't have signalfd.h.
cannam@135 37 #define KJ_USE_EPOLL 1
cannam@135 38 #endif
cannam@135 39
cannam@135 40 namespace kj {
cannam@135 41
cannam@135 42 class UnixEventPort: public EventPort {
cannam@135 43 // An EventPort implementation which can wait for events on file descriptors as well as signals.
cannam@135 44 // This API only makes sense on Unix.
cannam@135 45 //
cannam@135 46 // The implementation uses `poll()` or possibly a platform-specific API (e.g. epoll, kqueue).
cannam@135 47 // To also wait on signals without race conditions, the implementation may block signals until
cannam@135 48 // just before `poll()` while using a signal handler which `siglongjmp()`s back to just before
cannam@135 49 // the signal was unblocked, or it may use a nicer platform-specific API like signalfd.
cannam@135 50 //
cannam@135 51 // The implementation reserves a signal for internal use. By default, it uses SIGUSR1. If you
cannam@135 52 // need to use SIGUSR1 for something else, you must offer a different signal by calling
cannam@135 53 // setReservedSignal() at startup.
cannam@135 54 //
cannam@135 55 // WARNING: A UnixEventPort can only be used in the thread and process that created it. In
cannam@135 56 // particular, note that after a fork(), a UnixEventPort created in the parent process will
cannam@135 57 // not work correctly in the child, even if the parent ceases to use its copy. In particular
cannam@135 58 // note that this means that server processes which daemonize themselves at startup must wait
cannam@135 59 // until after daemonization to create a UnixEventPort.
cannam@135 60
cannam@135 61 public:
cannam@135 62 UnixEventPort();
cannam@135 63 ~UnixEventPort() noexcept(false);
cannam@135 64
cannam@135 65 class FdObserver;
cannam@135 66 // Class that watches an fd for readability or writability. See definition below.
cannam@135 67
cannam@135 68 Promise<siginfo_t> onSignal(int signum);
cannam@135 69 // When the given signal is delivered to this thread, return the corresponding siginfo_t.
cannam@135 70 // The signal must have been captured using `captureSignal()`.
cannam@135 71 //
cannam@135 72 // If `onSignal()` has not been called, the signal will remain blocked in this thread.
cannam@135 73 // Therefore, a signal which arrives before `onSignal()` was called will not be "missed" -- the
cannam@135 74 // next call to 'onSignal()' will receive it. Also, you can control which thread receives a
cannam@135 75 // process-wide signal by only calling `onSignal()` on that thread's event loop.
cannam@135 76 //
cannam@135 77 // The result of waiting on the same signal twice at once is undefined.
cannam@135 78
cannam@135 79 static void captureSignal(int signum);
cannam@135 80 // Arranges for the given signal to be captured and handled via UnixEventPort, so that you may
cannam@135 81 // then pass it to `onSignal()`. This method is static because it registers a signal handler
cannam@135 82 // which applies process-wide. If any other threads exist in the process when `captureSignal()`
cannam@135 83 // is called, you *must* set the signal mask in those threads to block this signal, otherwise
cannam@135 84 // terrible things will happen if the signal happens to be delivered to those threads. If at
cannam@135 85 // all possible, call `captureSignal()` *before* creating threads, so that threads you create in
cannam@135 86 // the future will inherit the proper signal mask.
cannam@135 87 //
cannam@135 88 // To un-capture a signal, simply install a different signal handler and then un-block it from
cannam@135 89 // the signal mask.
cannam@135 90
cannam@135 91 static void setReservedSignal(int signum);
cannam@135 92 // Sets the signal number which `UnixEventPort` reserves for internal use. If your application
cannam@135 93 // needs to use SIGUSR1, call this at startup (before any calls to `captureSignal()` and before
cannam@135 94 // constructing an `UnixEventPort`) to offer a different signal.
cannam@135 95
cannam@135 96 TimePoint steadyTime() { return frozenSteadyTime; }
cannam@135 97 Promise<void> atSteadyTime(TimePoint time);
cannam@135 98
cannam@135 99 // implements EventPort ------------------------------------------------------
cannam@135 100 bool wait() override;
cannam@135 101 bool poll() override;
cannam@135 102 void wake() const override;
cannam@135 103
cannam@135 104 private:
cannam@135 105 struct TimerSet; // Defined in source file to avoid STL include.
cannam@135 106 class TimerPromiseAdapter;
cannam@135 107 class SignalPromiseAdapter;
cannam@135 108
cannam@135 109 Own<TimerSet> timers;
cannam@135 110 TimePoint frozenSteadyTime;
cannam@135 111
cannam@135 112 SignalPromiseAdapter* signalHead = nullptr;
cannam@135 113 SignalPromiseAdapter** signalTail = &signalHead;
cannam@135 114
cannam@135 115 TimePoint currentSteadyTime();
cannam@135 116 void processTimers();
cannam@135 117 void gotSignal(const siginfo_t& siginfo);
cannam@135 118
cannam@135 119 friend class TimerPromiseAdapter;
cannam@135 120
cannam@135 121 #if KJ_USE_EPOLL
cannam@135 122 AutoCloseFd epollFd;
cannam@135 123 AutoCloseFd signalFd;
cannam@135 124 AutoCloseFd eventFd; // Used for cross-thread wakeups.
cannam@135 125
cannam@135 126 sigset_t signalFdSigset;
cannam@135 127 // Signal mask as currently set on the signalFd. Tracked so we can detect whether or not it
cannam@135 128 // needs updating.
cannam@135 129
cannam@135 130 bool doEpollWait(int timeout);
cannam@135 131
cannam@135 132 #else
cannam@135 133 class PollContext;
cannam@135 134
cannam@135 135 FdObserver* observersHead = nullptr;
cannam@135 136 FdObserver** observersTail = &observersHead;
cannam@135 137
cannam@135 138 unsigned long long threadId; // actually pthread_t
cannam@135 139 #endif
cannam@135 140 };
cannam@135 141
cannam@135 142 class UnixEventPort::FdObserver {
cannam@135 143 // Object which watches a file descriptor to determine when it is readable or writable.
cannam@135 144 //
cannam@135 145 // For listen sockets, "readable" means that there is a connection to accept(). For everything
cannam@135 146 // else, it means that read() (or recv()) will return data.
cannam@135 147 //
cannam@135 148 // The presence of out-of-band data should NOT fire this event. However, the event may
cannam@135 149 // occasionally fire spuriously (when there is actually no data to read), and one thing that can
cannam@135 150 // cause such spurious events is the arrival of OOB data on certain platforms whose event
cannam@135 151 // interfaces fail to distinguish between regular and OOB data (e.g. Mac OSX).
cannam@135 152 //
cannam@135 153 // WARNING: The exact behavior of this class differs across systems, since event interfaces
cannam@135 154 // vary wildly. Be sure to read the documentation carefully and avoid depending on unspecified
cannam@135 155 // behavior. If at all possible, use the higher-level AsyncInputStream interface instead.
cannam@135 156
cannam@135 157 public:
cannam@135 158 enum Flags {
cannam@135 159 OBSERVE_READ = 1,
cannam@135 160 OBSERVE_WRITE = 2,
cannam@135 161 OBSERVE_URGENT = 4,
cannam@135 162 OBSERVE_READ_WRITE = OBSERVE_READ | OBSERVE_WRITE
cannam@135 163 };
cannam@135 164
cannam@135 165 FdObserver(UnixEventPort& eventPort, int fd, uint flags);
cannam@135 166 // Begin watching the given file descriptor for readability. Only one ReadObserver may exist
cannam@135 167 // for a given file descriptor at a time.
cannam@135 168
cannam@135 169 ~FdObserver() noexcept(false);
cannam@135 170
cannam@135 171 KJ_DISALLOW_COPY(FdObserver);
cannam@135 172
cannam@135 173 Promise<void> whenBecomesReadable();
cannam@135 174 // Resolves the next time the file descriptor transitions from having no data to read to having
cannam@135 175 // some data to read.
cannam@135 176 //
cannam@135 177 // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error
cannam@135 178 // to call this method when there is already data in the read buffer which has been there since
cannam@135 179 // prior to the last turn of the event loop or prior to creation FdWatcher. In this case, it is
cannam@135 180 // unspecified whether the promise will ever resolve -- it depends on the underlying event
cannam@135 181 // mechanism being used.
cannam@135 182 //
cannam@135 183 // In order to avoid this problem, make sure that you only call `whenBecomesReadable()`
cannam@135 184 // only at times when you know the buffer is empty. You know this for sure when one of the
cannam@135 185 // following happens:
cannam@135 186 // * read() or recv() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode
cannam@135 187 // enabled on the fd!)
cannam@135 188 // * The file descriptor is a regular byte-oriented object (like a socket or pipe),
cannam@135 189 // read() or recv() returns fewer than the number of bytes requested, and `atEndHint()`
cannam@135 190 // returns false. This can only happen if the buffer is empty but EOF is not reached. (Note,
cannam@135 191 // though, that for record-oriented file descriptors like Linux's inotify interface, this
cannam@135 192 // rule does not hold, because it could simply be that the next record did not fit into the
cannam@135 193 // space available.)
cannam@135 194 //
cannam@135 195 // It is an error to call `whenBecomesReadable()` again when the promise returned previously
cannam@135 196 // has not yet resolved. If you do this, the previous promise may throw an exception.
cannam@135 197
cannam@135 198 inline Maybe<bool> atEndHint() { return atEnd; }
cannam@135 199 // Returns true if the event system has indicated that EOF has been received. There may still
cannam@135 200 // be data in the read buffer, but once that is gone, there's nothing left.
cannam@135 201 //
cannam@135 202 // Returns false if the event system has indicated that EOF had NOT been received as of the
cannam@135 203 // last turn of the event loop.
cannam@135 204 //
cannam@135 205 // Returns nullptr if the event system does not know whether EOF has been reached. In this
cannam@135 206 // case, the only way to know for sure is to call read() or recv() and check if it returns
cannam@135 207 // zero.
cannam@135 208 //
cannam@135 209 // This hint may be useful as an optimization to avoid an unnecessary system call.
cannam@135 210
cannam@135 211 Promise<void> whenBecomesWritable();
cannam@135 212 // Resolves the next time the file descriptor transitions from having no space available in the
cannam@135 213 // write buffer to having some space available.
cannam@135 214 //
cannam@135 215 // KJ uses "edge-triggered" event notification whenever possible. As a result, it is an error
cannam@135 216 // to call this method when there is already space in the write buffer which has been there
cannam@135 217 // since prior to the last turn of the event loop or prior to creation FdWatcher. In this case,
cannam@135 218 // it is unspecified whether the promise will ever resolve -- it depends on the underlying
cannam@135 219 // event mechanism being used.
cannam@135 220 //
cannam@135 221 // In order to avoid this problem, make sure that you only call `whenBecomesWritable()`
cannam@135 222 // only at times when you know the buffer is full. You know this for sure when one of the
cannam@135 223 // following happens:
cannam@135 224 // * write() or send() fails with EAGAIN or EWOULDBLOCK. (You MUST have non-blocking mode
cannam@135 225 // enabled on the fd!)
cannam@135 226 // * write() or send() succeeds but accepts fewer than the number of bytes provided. This can
cannam@135 227 // only happen if the buffer is full.
cannam@135 228 //
cannam@135 229 // It is an error to call `whenBecomesWritable()` again when the promise returned previously
cannam@135 230 // has not yet resolved. If you do this, the previous promise may throw an exception.
cannam@135 231
cannam@135 232 Promise<void> whenUrgentDataAvailable();
cannam@135 233 // Resolves the next time the file descriptor's read buffer contains "urgent" data.
cannam@135 234 //
cannam@135 235 // The conditions for availability of urgent data are specific to the file descriptor's
cannam@135 236 // underlying implementation.
cannam@135 237 //
cannam@135 238 // It is an error to call `whenUrgentDataAvailable()` again when the promise returned previously
cannam@135 239 // has not yet resolved. If you do this, the previous promise may throw an exception.
cannam@135 240 //
cannam@135 241 // WARNING: This has some known weird behavior on macOS. See
cannam@135 242 // https://github.com/sandstorm-io/capnproto/issues/374.
cannam@135 243
cannam@135 244 private:
cannam@135 245 UnixEventPort& eventPort;
cannam@135 246 int fd;
cannam@135 247 uint flags;
cannam@135 248
cannam@135 249 kj::Maybe<Own<PromiseFulfiller<void>>> readFulfiller;
cannam@135 250 kj::Maybe<Own<PromiseFulfiller<void>>> writeFulfiller;
cannam@135 251 kj::Maybe<Own<PromiseFulfiller<void>>> urgentFulfiller;
cannam@135 252 // Replaced each time `whenBecomesReadable()` or `whenBecomesWritable()` is called. Reverted to
cannam@135 253 // null every time an event is fired.
cannam@135 254
cannam@135 255 Maybe<bool> atEnd;
cannam@135 256
cannam@135 257 void fire(short events);
cannam@135 258
cannam@135 259 #if !KJ_USE_EPOLL
cannam@135 260 FdObserver* next;
cannam@135 261 FdObserver** prev;
cannam@135 262 // Linked list of observers which currently have a non-null readFulfiller or writeFulfiller.
cannam@135 263 // If `prev` is null then the observer is not currently in the list.
cannam@135 264
cannam@135 265 short getEventMask();
cannam@135 266 #endif
cannam@135 267
cannam@135 268 friend class UnixEventPort;
cannam@135 269 };
cannam@135 270
cannam@135 271 } // namespace kj
cannam@135 272
cannam@135 273 #endif // KJ_ASYNC_UNIX_H_