annotate osx/include/kj/async-unix.h @ 49:3ab5a40c4e3b

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