xref: /third_party/python/Modules/selectmodule.c (revision 7db96d56)
1/* select - Module containing unix select(2) call.
2   Under Unix, the file descriptors are small integers.
3   Under Win32, select only exists for sockets, and sockets may
4   have any value except INVALID_SOCKET.
5*/
6
7#ifndef Py_BUILD_CORE_BUILTIN
8#  define Py_BUILD_CORE_MODULE 1
9#endif
10
11#if defined(HAVE_POLL_H) && !defined(_GNU_SOURCE)
12#  define _GNU_SOURCE
13#endif
14
15#include "Python.h"
16#include "pycore_fileutils.h"     // _Py_set_inheritable()
17#include "structmember.h"         // PyMemberDef
18
19#ifdef HAVE_SYS_DEVPOLL_H
20#include <sys/resource.h>
21#include <sys/devpoll.h>
22#include <sys/types.h>
23#include <sys/stat.h>
24#include <fcntl.h>
25#endif
26
27#ifdef __APPLE__
28    /* Perform runtime testing for a broken poll on OSX to make it easier
29     * to use the same binary on multiple releases of the OS.
30     */
31#undef HAVE_BROKEN_POLL
32#endif
33
34/* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
35   64 is too small (too many people have bumped into that limit).
36   Here we boost it.
37   Users who want even more than the boosted limit should #define
38   FD_SETSIZE higher before this; e.g., via compiler /D switch.
39*/
40#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
41#define FD_SETSIZE 512
42#endif
43
44#if defined(HAVE_POLL_H)
45#include <poll.h>
46#elif defined(HAVE_SYS_POLL_H)
47#include <sys/poll.h>
48#endif
49
50#ifdef __sgi
51/* This is missing from unistd.h */
52extern void bzero(void *, int);
53#endif
54
55#ifdef HAVE_SYS_TYPES_H
56#include <sys/types.h>
57#endif
58
59#ifdef MS_WINDOWS
60#  define WIN32_LEAN_AND_MEAN
61#  include <winsock.h>
62#else
63#  define SOCKET int
64#endif
65
66// WASI SDK 16 does not have POLLPRIO, define as no-op
67#if defined(__wasi__) && !defined(POLLPRI)
68#  define POLLPRI 0
69#endif
70
71typedef struct {
72    PyObject *close;
73    PyTypeObject *poll_Type;
74    PyTypeObject *devpoll_Type;
75    PyTypeObject *pyEpoll_Type;
76    PyTypeObject *kqueue_event_Type;
77    PyTypeObject *kqueue_queue_Type;
78} _selectstate;
79
80static struct PyModuleDef selectmodule;
81
82static inline _selectstate*
83get_select_state(PyObject *module)
84{
85    void *state = PyModule_GetState(module);
86    assert(state != NULL);
87    return (_selectstate *)state;
88}
89
90#define _selectstate_by_type(type) get_select_state(PyType_GetModule(type))
91
92/*[clinic input]
93module select
94class select.poll "pollObject *" "_selectstate_by_type(type)->poll_Type"
95class select.devpoll "devpollObject *" "_selectstate_by_type(type)->devpoll_Type"
96class select.epoll "pyEpoll_Object *" "_selectstate_by_type(type)->pyEpoll_Type"
97class select.kqueue "kqueue_queue_Object *" "_selectstate_by_type(type)->kqueue_queue_Type"
98[clinic start generated code]*/
99/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8072de35824aa327]*/
100
101/* list of Python objects and their file descriptor */
102typedef struct {
103    PyObject *obj;                           /* owned reference */
104    SOCKET fd;
105    int sentinel;                            /* -1 == sentinel */
106} pylist;
107
108static void
109reap_obj(pylist fd2obj[FD_SETSIZE + 1])
110{
111    unsigned int i;
112    for (i = 0; i < (unsigned int)FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
113        Py_CLEAR(fd2obj[i].obj);
114    }
115    fd2obj[0].sentinel = -1;
116}
117
118
119/* returns -1 and sets the Python exception if an error occurred, otherwise
120   returns a number >= 0
121*/
122static int
123seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
124{
125    int max = -1;
126    unsigned int index = 0;
127    Py_ssize_t i;
128    PyObject* fast_seq = NULL;
129    PyObject* o = NULL;
130
131    fd2obj[0].obj = (PyObject*)0;            /* set list to zero size */
132    FD_ZERO(set);
133
134    fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
135    if (!fast_seq)
136        return -1;
137
138    for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++)  {
139        SOCKET v;
140
141        /* any intervening fileno() calls could decr this refcnt */
142        if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
143            goto finally;
144
145        Py_INCREF(o);
146        v = PyObject_AsFileDescriptor( o );
147        if (v == -1) goto finally;
148
149#if defined(_MSC_VER)
150        max = 0;                             /* not used for Win32 */
151#else  /* !_MSC_VER */
152        if (!_PyIsSelectable_fd(v)) {
153            PyErr_SetString(PyExc_ValueError,
154                        "filedescriptor out of range in select()");
155            goto finally;
156        }
157        if (v > max)
158            max = v;
159#endif /* _MSC_VER */
160        FD_SET(v, set);
161
162        /* add object and its file descriptor to the list */
163        if (index >= (unsigned int)FD_SETSIZE) {
164            PyErr_SetString(PyExc_ValueError,
165                          "too many file descriptors in select()");
166            goto finally;
167        }
168        fd2obj[index].obj = o;
169        fd2obj[index].fd = v;
170        fd2obj[index].sentinel = 0;
171        fd2obj[++index].sentinel = -1;
172    }
173    Py_DECREF(fast_seq);
174    return max+1;
175
176  finally:
177    Py_XDECREF(o);
178    Py_DECREF(fast_seq);
179    return -1;
180}
181
182/* returns NULL and sets the Python exception if an error occurred */
183static PyObject *
184set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
185{
186    int i, j, count=0;
187    PyObject *list, *o;
188    SOCKET fd;
189
190    for (j = 0; fd2obj[j].sentinel >= 0; j++) {
191        if (FD_ISSET(fd2obj[j].fd, set))
192            count++;
193    }
194    list = PyList_New(count);
195    if (!list)
196        return NULL;
197
198    i = 0;
199    for (j = 0; fd2obj[j].sentinel >= 0; j++) {
200        fd = fd2obj[j].fd;
201        if (FD_ISSET(fd, set)) {
202            o = fd2obj[j].obj;
203            fd2obj[j].obj = NULL;
204            /* transfer ownership */
205            if (PyList_SetItem(list, i, o) < 0)
206                goto finally;
207
208            i++;
209        }
210    }
211    return list;
212  finally:
213    Py_DECREF(list);
214    return NULL;
215}
216
217#undef SELECT_USES_HEAP
218#if FD_SETSIZE > 1024
219#define SELECT_USES_HEAP
220#endif /* FD_SETSIZE > 1024 */
221
222/*[clinic input]
223select.select
224
225    rlist: object
226    wlist: object
227    xlist: object
228    timeout as timeout_obj: object = None
229    /
230
231Wait until one or more file descriptors are ready for some kind of I/O.
232
233The first three arguments are iterables of file descriptors to be waited for:
234rlist -- wait until ready for reading
235wlist -- wait until ready for writing
236xlist -- wait for an "exceptional condition"
237If only one kind of condition is required, pass [] for the other lists.
238
239A file descriptor is either a socket or file object, or a small integer
240gotten from a fileno() method call on one of those.
241
242The optional 4th argument specifies a timeout in seconds; it may be
243a floating point number to specify fractions of seconds.  If it is absent
244or None, the call will never time out.
245
246The return value is a tuple of three lists corresponding to the first three
247arguments; each contains the subset of the corresponding file descriptors
248that are ready.
249
250*** IMPORTANT NOTICE ***
251On Windows, only sockets are supported; on Unix, all file
252descriptors can be used.
253[clinic start generated code]*/
254
255static PyObject *
256select_select_impl(PyObject *module, PyObject *rlist, PyObject *wlist,
257                   PyObject *xlist, PyObject *timeout_obj)
258/*[clinic end generated code: output=2b3cfa824f7ae4cf input=e467f5d68033de00]*/
259{
260#ifdef SELECT_USES_HEAP
261    pylist *rfd2obj, *wfd2obj, *efd2obj;
262#else  /* !SELECT_USES_HEAP */
263    /* XXX: All this should probably be implemented as follows:
264     * - find the highest descriptor we're interested in
265     * - add one
266     * - that's the size
267     * See: Stevens, APitUE, $12.5.1
268     */
269    pylist rfd2obj[FD_SETSIZE + 1];
270    pylist wfd2obj[FD_SETSIZE + 1];
271    pylist efd2obj[FD_SETSIZE + 1];
272#endif /* SELECT_USES_HEAP */
273    PyObject *ret = NULL;
274    fd_set ifdset, ofdset, efdset;
275    struct timeval tv, *tvp;
276    int imax, omax, emax, max;
277    int n;
278    _PyTime_t timeout, deadline = 0;
279
280    if (timeout_obj == Py_None)
281        tvp = (struct timeval *)NULL;
282    else {
283        if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
284                                      _PyTime_ROUND_TIMEOUT) < 0) {
285            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
286                PyErr_SetString(PyExc_TypeError,
287                                "timeout must be a float or None");
288            }
289            return NULL;
290        }
291
292        if (_PyTime_AsTimeval(timeout, &tv, _PyTime_ROUND_TIMEOUT) == -1)
293            return NULL;
294        if (tv.tv_sec < 0) {
295            PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
296            return NULL;
297        }
298        tvp = &tv;
299    }
300
301#ifdef SELECT_USES_HEAP
302    /* Allocate memory for the lists */
303    rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
304    wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
305    efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
306    if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
307        if (rfd2obj) PyMem_Free(rfd2obj);
308        if (wfd2obj) PyMem_Free(wfd2obj);
309        if (efd2obj) PyMem_Free(efd2obj);
310        return PyErr_NoMemory();
311    }
312#endif /* SELECT_USES_HEAP */
313
314    /* Convert iterables to fd_sets, and get maximum fd number
315     * propagates the Python exception set in seq2set()
316     */
317    rfd2obj[0].sentinel = -1;
318    wfd2obj[0].sentinel = -1;
319    efd2obj[0].sentinel = -1;
320    if ((imax = seq2set(rlist, &ifdset, rfd2obj)) < 0)
321        goto finally;
322    if ((omax = seq2set(wlist, &ofdset, wfd2obj)) < 0)
323        goto finally;
324    if ((emax = seq2set(xlist, &efdset, efd2obj)) < 0)
325        goto finally;
326
327    max = imax;
328    if (omax > max) max = omax;
329    if (emax > max) max = emax;
330
331    if (tvp) {
332        deadline = _PyDeadline_Init(timeout);
333    }
334
335    do {
336        Py_BEGIN_ALLOW_THREADS
337        errno = 0;
338        n = select(
339            max,
340            imax ? &ifdset : NULL,
341            omax ? &ofdset : NULL,
342            emax ? &efdset : NULL,
343            tvp);
344        Py_END_ALLOW_THREADS
345
346        if (errno != EINTR)
347            break;
348
349        /* select() was interrupted by a signal */
350        if (PyErr_CheckSignals())
351            goto finally;
352
353        if (tvp) {
354            timeout = _PyDeadline_Get(deadline);
355            if (timeout < 0) {
356                /* bpo-35310: lists were unmodified -- clear them explicitly */
357                FD_ZERO(&ifdset);
358                FD_ZERO(&ofdset);
359                FD_ZERO(&efdset);
360                n = 0;
361                break;
362            }
363            _PyTime_AsTimeval_clamp(timeout, &tv, _PyTime_ROUND_CEILING);
364            /* retry select() with the recomputed timeout */
365        }
366    } while (1);
367
368#ifdef MS_WINDOWS
369    if (n == SOCKET_ERROR) {
370        PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
371    }
372#else
373    if (n < 0) {
374        PyErr_SetFromErrno(PyExc_OSError);
375    }
376#endif
377    else {
378        /* any of these three calls can raise an exception.  it's more
379           convenient to test for this after all three calls... but
380           is that acceptable?
381        */
382        rlist = set2list(&ifdset, rfd2obj);
383        wlist = set2list(&ofdset, wfd2obj);
384        xlist = set2list(&efdset, efd2obj);
385        if (PyErr_Occurred())
386            ret = NULL;
387        else
388            ret = PyTuple_Pack(3, rlist, wlist, xlist);
389
390        Py_XDECREF(rlist);
391        Py_XDECREF(wlist);
392        Py_XDECREF(xlist);
393    }
394
395  finally:
396    reap_obj(rfd2obj);
397    reap_obj(wfd2obj);
398    reap_obj(efd2obj);
399#ifdef SELECT_USES_HEAP
400    PyMem_Free(rfd2obj);
401    PyMem_Free(wfd2obj);
402    PyMem_Free(efd2obj);
403#endif /* SELECT_USES_HEAP */
404    return ret;
405}
406
407#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
408/*
409 * poll() support
410 */
411
412typedef struct {
413    PyObject_HEAD
414    PyObject *dict;
415    int ufd_uptodate;
416    int ufd_len;
417    struct pollfd *ufds;
418    int poll_running;
419} pollObject;
420
421/* Update the malloc'ed array of pollfds to match the dictionary
422   contained within a pollObject.  Return 1 on success, 0 on an error.
423*/
424
425static int
426update_ufd_array(pollObject *self)
427{
428    Py_ssize_t i, pos;
429    PyObject *key, *value;
430    struct pollfd *old_ufds = self->ufds;
431
432    self->ufd_len = PyDict_GET_SIZE(self->dict);
433    PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
434    if (self->ufds == NULL) {
435        self->ufds = old_ufds;
436        PyErr_NoMemory();
437        return 0;
438    }
439
440    i = pos = 0;
441    while (PyDict_Next(self->dict, &pos, &key, &value)) {
442        assert(i < self->ufd_len);
443        /* Never overflow */
444        self->ufds[i].fd = (int)PyLong_AsLong(key);
445        self->ufds[i].events = (short)(unsigned short)PyLong_AsLong(value);
446        i++;
447    }
448    assert(i == self->ufd_len);
449    self->ufd_uptodate = 1;
450    return 1;
451}
452
453/*[clinic input]
454select.poll.register
455
456    fd: fildes
457      either an integer, or an object with a fileno() method returning an int
458    eventmask: unsigned_short(c_default="POLLIN | POLLPRI | POLLOUT") = select.POLLIN | select.POLLPRI | select.POLLOUT
459      an optional bitmask describing the type of events to check for
460    /
461
462Register a file descriptor with the polling object.
463[clinic start generated code]*/
464
465static PyObject *
466select_poll_register_impl(pollObject *self, int fd, unsigned short eventmask)
467/*[clinic end generated code: output=0dc7173c800a4a65 input=34e16cfb28d3c900]*/
468{
469    PyObject *key, *value;
470    int err;
471
472    /* Add entry to the internal dictionary: the key is the
473       file descriptor, and the value is the event mask. */
474    key = PyLong_FromLong(fd);
475    if (key == NULL)
476        return NULL;
477    value = PyLong_FromLong(eventmask);
478    if (value == NULL) {
479        Py_DECREF(key);
480        return NULL;
481    }
482    err = PyDict_SetItem(self->dict, key, value);
483    Py_DECREF(key);
484    Py_DECREF(value);
485    if (err < 0)
486        return NULL;
487
488    self->ufd_uptodate = 0;
489
490    Py_RETURN_NONE;
491}
492
493
494/*[clinic input]
495select.poll.modify
496
497    fd: fildes
498      either an integer, or an object with a fileno() method returning
499      an int
500    eventmask: unsigned_short
501      a bitmask describing the type of events to check for
502    /
503
504Modify an already registered file descriptor.
505[clinic start generated code]*/
506
507static PyObject *
508select_poll_modify_impl(pollObject *self, int fd, unsigned short eventmask)
509/*[clinic end generated code: output=1a7b88bf079eff17 input=a8e383df075c32cf]*/
510{
511    PyObject *key, *value;
512    int err;
513
514    /* Modify registered fd */
515    key = PyLong_FromLong(fd);
516    if (key == NULL)
517        return NULL;
518    err = PyDict_Contains(self->dict, key);
519    if (err < 0) {
520        Py_DECREF(key);
521        return NULL;
522    }
523    if (err == 0) {
524        errno = ENOENT;
525        PyErr_SetFromErrno(PyExc_OSError);
526        Py_DECREF(key);
527        return NULL;
528    }
529    value = PyLong_FromLong(eventmask);
530    if (value == NULL) {
531        Py_DECREF(key);
532        return NULL;
533    }
534    err = PyDict_SetItem(self->dict, key, value);
535    Py_DECREF(key);
536    Py_DECREF(value);
537    if (err < 0)
538        return NULL;
539
540    self->ufd_uptodate = 0;
541
542    Py_RETURN_NONE;
543}
544
545
546/*[clinic input]
547select.poll.unregister
548
549    fd: fildes
550    /
551
552Remove a file descriptor being tracked by the polling object.
553[clinic start generated code]*/
554
555static PyObject *
556select_poll_unregister_impl(pollObject *self, int fd)
557/*[clinic end generated code: output=8c9f42e75e7d291b input=4b4fccc1040e79cb]*/
558{
559    PyObject *key;
560
561    /* Check whether the fd is already in the array */
562    key = PyLong_FromLong(fd);
563    if (key == NULL)
564        return NULL;
565
566    if (PyDict_DelItem(self->dict, key) == -1) {
567        Py_DECREF(key);
568        /* This will simply raise the KeyError set by PyDict_DelItem
569           if the file descriptor isn't registered. */
570        return NULL;
571    }
572
573    Py_DECREF(key);
574    self->ufd_uptodate = 0;
575
576    Py_RETURN_NONE;
577}
578
579/*[clinic input]
580select.poll.poll
581
582    timeout as timeout_obj: object = None
583      The maximum time to wait in milliseconds, or else None (or a negative
584      value) to wait indefinitely.
585    /
586
587Polls the set of registered file descriptors.
588
589Returns a list containing any descriptors that have events or errors to
590report, as a list of (fd, event) 2-tuples.
591[clinic start generated code]*/
592
593static PyObject *
594select_poll_poll_impl(pollObject *self, PyObject *timeout_obj)
595/*[clinic end generated code: output=876e837d193ed7e4 input=c2f6953ec45e5622]*/
596{
597    PyObject *result_list = NULL;
598    int poll_result, i, j;
599    PyObject *value = NULL, *num = NULL;
600    _PyTime_t timeout = -1, ms = -1, deadline = 0;
601    int async_err = 0;
602
603    if (timeout_obj != Py_None) {
604        if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
605                                           _PyTime_ROUND_TIMEOUT) < 0) {
606            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
607                PyErr_SetString(PyExc_TypeError,
608                                "timeout must be an integer or None");
609            }
610            return NULL;
611        }
612
613        ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
614        if (ms < INT_MIN || ms > INT_MAX) {
615            PyErr_SetString(PyExc_OverflowError, "timeout is too large");
616            return NULL;
617        }
618
619        if (timeout >= 0) {
620            deadline = _PyDeadline_Init(timeout);
621        }
622    }
623
624    /* On some OSes, typically BSD-based ones, the timeout parameter of the
625       poll() syscall, when negative, must be exactly INFTIM, where defined,
626       or -1. See issue 31334. */
627    if (ms < 0) {
628#ifdef INFTIM
629        ms = INFTIM;
630#else
631        ms = -1;
632#endif
633    }
634
635    /* Avoid concurrent poll() invocation, issue 8865 */
636    if (self->poll_running) {
637        PyErr_SetString(PyExc_RuntimeError,
638                        "concurrent poll() invocation");
639        return NULL;
640    }
641
642    /* Ensure the ufd array is up to date */
643    if (!self->ufd_uptodate)
644        if (update_ufd_array(self) == 0)
645            return NULL;
646
647    self->poll_running = 1;
648
649    /* call poll() */
650    async_err = 0;
651    do {
652        Py_BEGIN_ALLOW_THREADS
653        errno = 0;
654        poll_result = poll(self->ufds, self->ufd_len, (int)ms);
655        Py_END_ALLOW_THREADS
656
657        if (errno != EINTR)
658            break;
659
660        /* poll() was interrupted by a signal */
661        if (PyErr_CheckSignals()) {
662            async_err = 1;
663            break;
664        }
665
666        if (timeout >= 0) {
667            timeout = _PyDeadline_Get(deadline);
668            if (timeout < 0) {
669                poll_result = 0;
670                break;
671            }
672            ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
673            /* retry poll() with the recomputed timeout */
674        }
675    } while (1);
676
677    self->poll_running = 0;
678
679    if (poll_result < 0) {
680        if (!async_err)
681            PyErr_SetFromErrno(PyExc_OSError);
682        return NULL;
683    }
684
685    /* build the result list */
686
687    result_list = PyList_New(poll_result);
688    if (!result_list)
689        return NULL;
690
691    for (i = 0, j = 0; j < poll_result; j++) {
692        /* skip to the next fired descriptor */
693        while (!self->ufds[i].revents) {
694            i++;
695        }
696        /* if we hit a NULL return, set value to NULL
697           and break out of loop; code at end will
698           clean up result_list */
699        value = PyTuple_New(2);
700        if (value == NULL)
701            goto error;
702        num = PyLong_FromLong(self->ufds[i].fd);
703        if (num == NULL) {
704            Py_DECREF(value);
705            goto error;
706        }
707        PyTuple_SET_ITEM(value, 0, num);
708
709        /* The &0xffff is a workaround for AIX.  'revents'
710           is a 16-bit short, and IBM assigned POLLNVAL
711           to be 0x8000, so the conversion to int results
712           in a negative number. See SF bug #923315. */
713        num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
714        if (num == NULL) {
715            Py_DECREF(value);
716            goto error;
717        }
718        PyTuple_SET_ITEM(value, 1, num);
719        PyList_SET_ITEM(result_list, j, value);
720        i++;
721    }
722    return result_list;
723
724  error:
725    Py_DECREF(result_list);
726    return NULL;
727}
728
729static pollObject *
730newPollObject(PyObject *module)
731{
732    pollObject *self;
733    self = PyObject_New(pollObject, get_select_state(module)->poll_Type);
734    if (self == NULL)
735        return NULL;
736    /* ufd_uptodate is a Boolean, denoting whether the
737       array pointed to by ufds matches the contents of the dictionary. */
738    self->ufd_uptodate = 0;
739    self->ufds = NULL;
740    self->poll_running = 0;
741    self->dict = PyDict_New();
742    if (self->dict == NULL) {
743        Py_DECREF(self);
744        return NULL;
745    }
746    return self;
747}
748
749static void
750poll_dealloc(pollObject *self)
751{
752    PyObject* type = (PyObject *)Py_TYPE(self);
753    if (self->ufds != NULL)
754        PyMem_Free(self->ufds);
755    Py_XDECREF(self->dict);
756    PyObject_Free(self);
757    Py_DECREF(type);
758}
759
760
761#ifdef HAVE_SYS_DEVPOLL_H
762static PyMethodDef devpoll_methods[];
763
764typedef struct {
765    PyObject_HEAD
766    int fd_devpoll;
767    int max_n_fds;
768    int n_fds;
769    struct pollfd *fds;
770} devpollObject;
771
772static PyObject *
773devpoll_err_closed(void)
774{
775    PyErr_SetString(PyExc_ValueError, "I/O operation on closed devpoll object");
776    return NULL;
777}
778
779static int devpoll_flush(devpollObject *self)
780{
781    int size, n;
782
783    if (!self->n_fds) return 0;
784
785    size = sizeof(struct pollfd)*self->n_fds;
786    self->n_fds = 0;
787
788    n = _Py_write(self->fd_devpoll, self->fds, size);
789    if (n == -1)
790        return -1;
791
792    if (n < size) {
793        /*
794        ** Data writed to /dev/poll is a binary data structure. It is not
795        ** clear what to do if a partial write occurred. For now, raise
796        ** an exception and see if we actually found this problem in
797        ** the wild.
798        ** See http://bugs.python.org/issue6397.
799        */
800        PyErr_Format(PyExc_OSError, "failed to write all pollfds. "
801                "Please, report at http://bugs.python.org/. "
802                "Data to report: Size tried: %d, actual size written: %d.",
803                size, n);
804        return -1;
805    }
806    return 0;
807}
808
809static PyObject *
810internal_devpoll_register(devpollObject *self, int fd,
811                          unsigned short events, int remove)
812{
813    if (self->fd_devpoll < 0)
814        return devpoll_err_closed();
815
816    if (remove) {
817        self->fds[self->n_fds].fd = fd;
818        self->fds[self->n_fds].events = POLLREMOVE;
819
820        if (++self->n_fds == self->max_n_fds) {
821            if (devpoll_flush(self))
822                return NULL;
823        }
824    }
825
826    self->fds[self->n_fds].fd = fd;
827    self->fds[self->n_fds].events = (signed short)events;
828
829    if (++self->n_fds == self->max_n_fds) {
830        if (devpoll_flush(self))
831            return NULL;
832    }
833
834    Py_RETURN_NONE;
835}
836
837/*[clinic input]
838select.devpoll.register
839
840    fd: fildes
841        either an integer, or an object with a fileno() method returning
842        an int
843    eventmask: unsigned_short(c_default="POLLIN | POLLPRI | POLLOUT") = select.POLLIN | select.POLLPRI | select.POLLOUT
844        an optional bitmask describing the type of events to check for
845    /
846
847Register a file descriptor with the polling object.
848[clinic start generated code]*/
849
850static PyObject *
851select_devpoll_register_impl(devpollObject *self, int fd,
852                             unsigned short eventmask)
853/*[clinic end generated code: output=6e07fe8b74abba0c input=22006fabe9567522]*/
854{
855    return internal_devpoll_register(self, fd, eventmask, 0);
856}
857
858/*[clinic input]
859select.devpoll.modify
860
861    fd: fildes
862        either an integer, or an object with a fileno() method returning
863        an int
864    eventmask: unsigned_short(c_default="POLLIN | POLLPRI | POLLOUT") = select.POLLIN | select.POLLPRI | select.POLLOUT
865        an optional bitmask describing the type of events to check for
866    /
867
868Modify a possible already registered file descriptor.
869[clinic start generated code]*/
870
871static PyObject *
872select_devpoll_modify_impl(devpollObject *self, int fd,
873                           unsigned short eventmask)
874/*[clinic end generated code: output=bc2e6d23aaff98b4 input=09fa335db7cdc09e]*/
875{
876    return internal_devpoll_register(self, fd, eventmask, 1);
877}
878
879/*[clinic input]
880select.devpoll.unregister
881
882    fd: fildes
883    /
884
885Remove a file descriptor being tracked by the polling object.
886[clinic start generated code]*/
887
888static PyObject *
889select_devpoll_unregister_impl(devpollObject *self, int fd)
890/*[clinic end generated code: output=95519ffa0c7d43fe input=b4ea42a4442fd467]*/
891{
892    if (self->fd_devpoll < 0)
893        return devpoll_err_closed();
894
895    self->fds[self->n_fds].fd = fd;
896    self->fds[self->n_fds].events = POLLREMOVE;
897
898    if (++self->n_fds == self->max_n_fds) {
899        if (devpoll_flush(self))
900            return NULL;
901    }
902
903    Py_RETURN_NONE;
904}
905
906/*[clinic input]
907select.devpoll.poll
908    timeout as timeout_obj: object = None
909      The maximum time to wait in milliseconds, or else None (or a negative
910      value) to wait indefinitely.
911    /
912
913Polls the set of registered file descriptors.
914
915Returns a list containing any descriptors that have events or errors to
916report, as a list of (fd, event) 2-tuples.
917[clinic start generated code]*/
918
919static PyObject *
920select_devpoll_poll_impl(devpollObject *self, PyObject *timeout_obj)
921/*[clinic end generated code: output=2654e5457cca0b3c input=3c3f0a355ec2bedb]*/
922{
923    struct dvpoll dvp;
924    PyObject *result_list = NULL;
925    int poll_result, i;
926    PyObject *value, *num1, *num2;
927    _PyTime_t timeout, ms, deadline = 0;
928
929    if (self->fd_devpoll < 0)
930        return devpoll_err_closed();
931
932    /* Check values for timeout */
933    if (timeout_obj == Py_None) {
934        timeout = -1;
935        ms = -1;
936    }
937    else {
938        if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
939                                           _PyTime_ROUND_TIMEOUT) < 0) {
940            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
941                PyErr_SetString(PyExc_TypeError,
942                                "timeout must be an integer or None");
943            }
944            return NULL;
945        }
946
947        ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
948        if (ms < -1 || ms > INT_MAX) {
949            PyErr_SetString(PyExc_OverflowError, "timeout is too large");
950            return NULL;
951        }
952    }
953
954    if (devpoll_flush(self))
955        return NULL;
956
957    dvp.dp_fds = self->fds;
958    dvp.dp_nfds = self->max_n_fds;
959    dvp.dp_timeout = (int)ms;
960
961    if (timeout >= 0) {
962        deadline = _PyDeadline_Init(timeout);
963    }
964
965    do {
966        /* call devpoll() */
967        Py_BEGIN_ALLOW_THREADS
968        errno = 0;
969        poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
970        Py_END_ALLOW_THREADS
971
972        if (errno != EINTR)
973            break;
974
975        /* devpoll() was interrupted by a signal */
976        if (PyErr_CheckSignals())
977            return NULL;
978
979        if (timeout >= 0) {
980            timeout = _PyDeadline_Get(deadline);
981            if (timeout < 0) {
982                poll_result = 0;
983                break;
984            }
985            ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
986            dvp.dp_timeout = (int)ms;
987            /* retry devpoll() with the recomputed timeout */
988        }
989    } while (1);
990
991    if (poll_result < 0) {
992        PyErr_SetFromErrno(PyExc_OSError);
993        return NULL;
994    }
995
996    /* build the result list */
997    result_list = PyList_New(poll_result);
998    if (!result_list)
999        return NULL;
1000
1001    for (i = 0; i < poll_result; i++) {
1002        num1 = PyLong_FromLong(self->fds[i].fd);
1003        num2 = PyLong_FromLong(self->fds[i].revents);
1004        if ((num1 == NULL) || (num2 == NULL)) {
1005            Py_XDECREF(num1);
1006            Py_XDECREF(num2);
1007            goto error;
1008        }
1009        value = PyTuple_Pack(2, num1, num2);
1010        Py_DECREF(num1);
1011        Py_DECREF(num2);
1012        if (value == NULL)
1013            goto error;
1014        PyList_SET_ITEM(result_list, i, value);
1015    }
1016
1017    return result_list;
1018
1019  error:
1020    Py_DECREF(result_list);
1021    return NULL;
1022}
1023
1024static int
1025devpoll_internal_close(devpollObject *self)
1026{
1027    int save_errno = 0;
1028    if (self->fd_devpoll >= 0) {
1029        int fd = self->fd_devpoll;
1030        self->fd_devpoll = -1;
1031        Py_BEGIN_ALLOW_THREADS
1032        if (close(fd) < 0)
1033            save_errno = errno;
1034        Py_END_ALLOW_THREADS
1035    }
1036    return save_errno;
1037}
1038
1039/*[clinic input]
1040select.devpoll.close
1041
1042Close the devpoll file descriptor.
1043
1044Further operations on the devpoll object will raise an exception.
1045[clinic start generated code]*/
1046
1047static PyObject *
1048select_devpoll_close_impl(devpollObject *self)
1049/*[clinic end generated code: output=26b355bd6429f21b input=6273c30f5560a99b]*/
1050{
1051    errno = devpoll_internal_close(self);
1052    if (errno < 0) {
1053        PyErr_SetFromErrno(PyExc_OSError);
1054        return NULL;
1055    }
1056    Py_RETURN_NONE;
1057}
1058
1059static PyObject*
1060devpoll_get_closed(devpollObject *self, void *Py_UNUSED(ignored))
1061{
1062    if (self->fd_devpoll < 0)
1063        Py_RETURN_TRUE;
1064    else
1065        Py_RETURN_FALSE;
1066}
1067
1068/*[clinic input]
1069select.devpoll.fileno
1070
1071Return the file descriptor.
1072[clinic start generated code]*/
1073
1074static PyObject *
1075select_devpoll_fileno_impl(devpollObject *self)
1076/*[clinic end generated code: output=26920929f8d292f4 input=ef15331ebde6c368]*/
1077{
1078    if (self->fd_devpoll < 0)
1079        return devpoll_err_closed();
1080    return PyLong_FromLong(self->fd_devpoll);
1081}
1082
1083static PyGetSetDef devpoll_getsetlist[] = {
1084    {"closed", (getter)devpoll_get_closed, NULL,
1085     "True if the devpoll object is closed"},
1086    {0},
1087};
1088
1089static devpollObject *
1090newDevPollObject(PyObject *module)
1091{
1092    devpollObject *self;
1093    int fd_devpoll, limit_result;
1094    struct pollfd *fds;
1095    struct rlimit limit;
1096
1097    /*
1098    ** If we try to process more that getrlimit()
1099    ** fds, the kernel will give an error, so
1100    ** we set the limit here. It is a dynamic
1101    ** value, because we can change rlimit() anytime.
1102    */
1103    limit_result = getrlimit(RLIMIT_NOFILE, &limit);
1104    if (limit_result == -1) {
1105        PyErr_SetFromErrno(PyExc_OSError);
1106        return NULL;
1107    }
1108
1109    fd_devpoll = _Py_open("/dev/poll", O_RDWR);
1110    if (fd_devpoll == -1)
1111        return NULL;
1112
1113    fds = PyMem_NEW(struct pollfd, limit.rlim_cur);
1114    if (fds == NULL) {
1115        close(fd_devpoll);
1116        PyErr_NoMemory();
1117        return NULL;
1118    }
1119
1120    self = PyObject_New(devpollObject, get_select_state(module)->devpoll_Type);
1121    if (self == NULL) {
1122        close(fd_devpoll);
1123        PyMem_Free(fds);
1124        return NULL;
1125    }
1126    self->fd_devpoll = fd_devpoll;
1127    self->max_n_fds = limit.rlim_cur;
1128    self->n_fds = 0;
1129    self->fds = fds;
1130
1131    return self;
1132}
1133
1134static void
1135devpoll_dealloc(devpollObject *self)
1136{
1137    PyObject *type = (PyObject *)Py_TYPE(self);
1138    (void)devpoll_internal_close(self);
1139    PyMem_Free(self->fds);
1140    PyObject_Free(self);
1141    Py_DECREF(type);
1142}
1143
1144static PyType_Slot devpoll_Type_slots[] = {
1145    {Py_tp_dealloc, devpoll_dealloc},
1146    {Py_tp_getset, devpoll_getsetlist},
1147    {Py_tp_methods, devpoll_methods},
1148    {0, 0},
1149};
1150
1151static PyType_Spec devpoll_Type_spec = {
1152    "select.devpoll",
1153    sizeof(devpollObject),
1154    0,
1155    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
1156    devpoll_Type_slots
1157};
1158
1159#endif  /* HAVE_SYS_DEVPOLL_H */
1160
1161
1162/*[clinic input]
1163select.poll
1164
1165Returns a polling object.
1166
1167This object supports registering and unregistering file descriptors, and then
1168polling them for I/O events.
1169[clinic start generated code]*/
1170
1171static PyObject *
1172select_poll_impl(PyObject *module)
1173/*[clinic end generated code: output=16a665a4e1d228c5 input=3f877909d5696bbf]*/
1174{
1175    return (PyObject *)newPollObject(module);
1176}
1177
1178#ifdef HAVE_SYS_DEVPOLL_H
1179
1180/*[clinic input]
1181select.devpoll
1182
1183Returns a polling object.
1184
1185This object supports registering and unregistering file descriptors, and then
1186polling them for I/O events.
1187[clinic start generated code]*/
1188
1189static PyObject *
1190select_devpoll_impl(PyObject *module)
1191/*[clinic end generated code: output=ea9213cc87fd9581 input=53a1af94564f00a3]*/
1192{
1193    return (PyObject *)newDevPollObject(module);
1194}
1195#endif
1196
1197
1198#ifdef __APPLE__
1199/*
1200 * On some systems poll() sets errno on invalid file descriptors. We test
1201 * for this at runtime because this bug may be fixed or introduced between
1202 * OS releases.
1203 */
1204static int select_have_broken_poll(void)
1205{
1206    int poll_test;
1207    int filedes[2];
1208
1209    struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
1210
1211    /* Create a file descriptor to make invalid */
1212    if (pipe(filedes) < 0) {
1213        return 1;
1214    }
1215    poll_struct.fd = filedes[0];
1216    close(filedes[0]);
1217    close(filedes[1]);
1218    poll_test = poll(&poll_struct, 1, 0);
1219    if (poll_test < 0) {
1220        return 1;
1221    } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
1222        return 1;
1223    }
1224    return 0;
1225}
1226#endif /* __APPLE__ */
1227
1228#endif /* HAVE_POLL */
1229
1230#ifdef HAVE_EPOLL
1231/* **************************************************************************
1232 *                      epoll interface for Linux 2.6
1233 *
1234 * Written by Christian Heimes
1235 * Inspired by Twisted's _epoll.pyx and select.poll()
1236 */
1237
1238#ifdef HAVE_SYS_EPOLL_H
1239#include <sys/epoll.h>
1240#endif
1241
1242typedef struct {
1243    PyObject_HEAD
1244    SOCKET epfd;                        /* epoll control file descriptor */
1245} pyEpoll_Object;
1246
1247static PyObject *
1248pyepoll_err_closed(void)
1249{
1250    PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll object");
1251    return NULL;
1252}
1253
1254static int
1255pyepoll_internal_close(pyEpoll_Object *self)
1256{
1257    int save_errno = 0;
1258    if (self->epfd >= 0) {
1259        int epfd = self->epfd;
1260        self->epfd = -1;
1261        Py_BEGIN_ALLOW_THREADS
1262        if (close(epfd) < 0)
1263            save_errno = errno;
1264        Py_END_ALLOW_THREADS
1265    }
1266    return save_errno;
1267}
1268
1269static PyObject *
1270newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd)
1271{
1272    pyEpoll_Object *self;
1273    assert(type != NULL);
1274    allocfunc epoll_alloc = PyType_GetSlot(type, Py_tp_alloc);
1275    assert(epoll_alloc != NULL);
1276    self = (pyEpoll_Object *) epoll_alloc(type, 0);
1277    if (self == NULL)
1278        return NULL;
1279
1280    if (fd == -1) {
1281        Py_BEGIN_ALLOW_THREADS
1282#ifdef HAVE_EPOLL_CREATE1
1283        self->epfd = epoll_create1(EPOLL_CLOEXEC);
1284#else
1285        self->epfd = epoll_create(sizehint);
1286#endif
1287        Py_END_ALLOW_THREADS
1288    }
1289    else {
1290        self->epfd = fd;
1291    }
1292    if (self->epfd < 0) {
1293        Py_DECREF(self);
1294        PyErr_SetFromErrno(PyExc_OSError);
1295        return NULL;
1296    }
1297
1298#ifndef HAVE_EPOLL_CREATE1
1299    if (fd == -1 && _Py_set_inheritable(self->epfd, 0, NULL) < 0) {
1300        Py_DECREF(self);
1301        return NULL;
1302    }
1303#endif
1304
1305    return (PyObject *)self;
1306}
1307
1308
1309/*[clinic input]
1310@classmethod
1311select.epoll.__new__
1312
1313    sizehint: int = -1
1314      The expected number of events to be registered.  It must be positive,
1315      or -1 to use the default.  It is only used on older systems where
1316      epoll_create1() is not available; otherwise it has no effect (though its
1317      value is still checked).
1318    flags: int = 0
1319      Deprecated and completely ignored.  However, when supplied, its value
1320      must be 0 or select.EPOLL_CLOEXEC, otherwise OSError is raised.
1321
1322Returns an epolling object.
1323[clinic start generated code]*/
1324
1325static PyObject *
1326select_epoll_impl(PyTypeObject *type, int sizehint, int flags)
1327/*[clinic end generated code: output=c87404e705013bb5 input=303e3295e7975e43]*/
1328{
1329    if (sizehint == -1) {
1330        sizehint = FD_SETSIZE - 1;
1331    }
1332    else if (sizehint <= 0) {
1333        PyErr_SetString(PyExc_ValueError, "negative sizehint");
1334        return NULL;
1335    }
1336
1337#ifdef HAVE_EPOLL_CREATE1
1338    if (flags && flags != EPOLL_CLOEXEC) {
1339        PyErr_SetString(PyExc_OSError, "invalid flags");
1340        return NULL;
1341    }
1342#endif
1343
1344    return newPyEpoll_Object(type, sizehint, -1);
1345}
1346
1347
1348static void
1349pyepoll_dealloc(pyEpoll_Object *self)
1350{
1351    PyTypeObject* type = Py_TYPE(self);
1352    (void)pyepoll_internal_close(self);
1353    freefunc epoll_free = PyType_GetSlot(type, Py_tp_free);
1354    epoll_free((PyObject *)self);
1355    Py_DECREF((PyObject *)type);
1356}
1357
1358/*[clinic input]
1359select.epoll.close
1360
1361Close the epoll control file descriptor.
1362
1363Further operations on the epoll object will raise an exception.
1364[clinic start generated code]*/
1365
1366static PyObject *
1367select_epoll_close_impl(pyEpoll_Object *self)
1368/*[clinic end generated code: output=ee2144c446a1a435 input=ca6c66ba5a736bfd]*/
1369{
1370    errno = pyepoll_internal_close(self);
1371    if (errno < 0) {
1372        PyErr_SetFromErrno(PyExc_OSError);
1373        return NULL;
1374    }
1375    Py_RETURN_NONE;
1376}
1377
1378
1379static PyObject*
1380pyepoll_get_closed(pyEpoll_Object *self, void *Py_UNUSED(ignored))
1381{
1382    if (self->epfd < 0)
1383        Py_RETURN_TRUE;
1384    else
1385        Py_RETURN_FALSE;
1386}
1387
1388/*[clinic input]
1389select.epoll.fileno
1390
1391Return the epoll control file descriptor.
1392[clinic start generated code]*/
1393
1394static PyObject *
1395select_epoll_fileno_impl(pyEpoll_Object *self)
1396/*[clinic end generated code: output=e171375fdc619ba3 input=c11091a6aee60b5c]*/
1397{
1398    if (self->epfd < 0)
1399        return pyepoll_err_closed();
1400    return PyLong_FromLong(self->epfd);
1401}
1402
1403
1404/*[clinic input]
1405@classmethod
1406select.epoll.fromfd
1407
1408    fd: int
1409    /
1410
1411Create an epoll object from a given control fd.
1412[clinic start generated code]*/
1413
1414static PyObject *
1415select_epoll_fromfd_impl(PyTypeObject *type, int fd)
1416/*[clinic end generated code: output=c15de2a083524e8e input=faecefdb55e3046e]*/
1417{
1418    SOCKET s_fd = (SOCKET)fd;
1419    return newPyEpoll_Object(type, FD_SETSIZE - 1, s_fd);
1420}
1421
1422
1423static PyObject *
1424pyepoll_internal_ctl(int epfd, int op, int fd, unsigned int events)
1425{
1426    struct epoll_event ev;
1427    int result;
1428
1429    if (epfd < 0)
1430        return pyepoll_err_closed();
1431
1432    switch (op) {
1433    case EPOLL_CTL_ADD:
1434    case EPOLL_CTL_MOD:
1435        ev.events = events;
1436        ev.data.fd = fd;
1437        Py_BEGIN_ALLOW_THREADS
1438        result = epoll_ctl(epfd, op, fd, &ev);
1439        Py_END_ALLOW_THREADS
1440        break;
1441    case EPOLL_CTL_DEL:
1442        /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
1443         * operation required a non-NULL pointer in event, even
1444         * though this argument is ignored. */
1445        Py_BEGIN_ALLOW_THREADS
1446        result = epoll_ctl(epfd, op, fd, &ev);
1447        Py_END_ALLOW_THREADS
1448        break;
1449    default:
1450        result = -1;
1451        errno = EINVAL;
1452    }
1453
1454    if (result < 0) {
1455        PyErr_SetFromErrno(PyExc_OSError);
1456        return NULL;
1457    }
1458    Py_RETURN_NONE;
1459}
1460
1461/*[clinic input]
1462select.epoll.register
1463
1464    fd: fildes
1465      the target file descriptor of the operation
1466    eventmask: unsigned_int(c_default="EPOLLIN | EPOLLPRI | EPOLLOUT", bitwise=True) = select.EPOLLIN | select.EPOLLPRI | select.EPOLLOUT
1467      a bit set composed of the various EPOLL constants
1468
1469Registers a new fd or raises an OSError if the fd is already registered.
1470
1471The epoll interface supports all file descriptors that support poll.
1472[clinic start generated code]*/
1473
1474static PyObject *
1475select_epoll_register_impl(pyEpoll_Object *self, int fd,
1476                           unsigned int eventmask)
1477/*[clinic end generated code: output=318e5e6386520599 input=a5071b71edfe3578]*/
1478{
1479    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, fd, eventmask);
1480}
1481
1482/*[clinic input]
1483select.epoll.modify
1484
1485    fd: fildes
1486      the target file descriptor of the operation
1487    eventmask: unsigned_int(bitwise=True)
1488      a bit set composed of the various EPOLL constants
1489
1490Modify event mask for a registered file descriptor.
1491[clinic start generated code]*/
1492
1493static PyObject *
1494select_epoll_modify_impl(pyEpoll_Object *self, int fd,
1495                         unsigned int eventmask)
1496/*[clinic end generated code: output=7e3447307cff6f65 input=88a83dac53a8c3da]*/
1497{
1498    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, fd, eventmask);
1499}
1500
1501/*[clinic input]
1502select.epoll.unregister
1503
1504    fd: fildes
1505      the target file descriptor of the operation
1506
1507Remove a registered file descriptor from the epoll object.
1508[clinic start generated code]*/
1509
1510static PyObject *
1511select_epoll_unregister_impl(pyEpoll_Object *self, int fd)
1512/*[clinic end generated code: output=07c5dbd612a512d4 input=3093f68d3644743d]*/
1513{
1514    return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, fd, 0);
1515}
1516
1517/*[clinic input]
1518select.epoll.poll
1519
1520    timeout as timeout_obj: object = None
1521      the maximum time to wait in seconds (as float);
1522      a timeout of None or -1 makes poll wait indefinitely
1523    maxevents: int = -1
1524      the maximum number of events returned; -1 means no limit
1525
1526Wait for events on the epoll file descriptor.
1527
1528Returns a list containing any descriptors that have events to report,
1529as a list of (fd, events) 2-tuples.
1530[clinic start generated code]*/
1531
1532static PyObject *
1533select_epoll_poll_impl(pyEpoll_Object *self, PyObject *timeout_obj,
1534                       int maxevents)
1535/*[clinic end generated code: output=e02d121a20246c6c input=33d34a5ea430fd5b]*/
1536{
1537    int nfds, i;
1538    PyObject *elist = NULL, *etuple = NULL;
1539    struct epoll_event *evs = NULL;
1540    _PyTime_t timeout = -1, ms = -1, deadline = 0;
1541
1542    if (self->epfd < 0)
1543        return pyepoll_err_closed();
1544
1545    if (timeout_obj != Py_None) {
1546        /* epoll_wait() has a resolution of 1 millisecond, round towards
1547           infinity to wait at least timeout seconds. */
1548        if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
1549                                      _PyTime_ROUND_TIMEOUT) < 0) {
1550            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
1551                PyErr_SetString(PyExc_TypeError,
1552                                "timeout must be an integer or None");
1553            }
1554            return NULL;
1555        }
1556
1557        ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
1558        if (ms < INT_MIN || ms > INT_MAX) {
1559            PyErr_SetString(PyExc_OverflowError, "timeout is too large");
1560            return NULL;
1561        }
1562        /* epoll_wait(2) treats all arbitrary negative numbers the same
1563           for the timeout argument, but -1 is the documented way to block
1564           indefinitely in the epoll_wait(2) documentation, so we set ms
1565           to -1 if the value of ms is a negative number.
1566
1567           Note that we didn't use INFTIM here since it's non-standard and
1568           isn't available under Linux. */
1569        if (ms < 0) {
1570            ms = -1;
1571        }
1572
1573        if (timeout >= 0) {
1574            deadline = _PyDeadline_Init(timeout);
1575        }
1576    }
1577
1578    if (maxevents == -1) {
1579        maxevents = FD_SETSIZE-1;
1580    }
1581    else if (maxevents < 1) {
1582        PyErr_Format(PyExc_ValueError,
1583                     "maxevents must be greater than 0, got %d",
1584                     maxevents);
1585        return NULL;
1586    }
1587
1588    evs = PyMem_New(struct epoll_event, maxevents);
1589    if (evs == NULL) {
1590        PyErr_NoMemory();
1591        return NULL;
1592    }
1593
1594    do {
1595        Py_BEGIN_ALLOW_THREADS
1596        errno = 0;
1597        nfds = epoll_wait(self->epfd, evs, maxevents, (int)ms);
1598        Py_END_ALLOW_THREADS
1599
1600        if (errno != EINTR)
1601            break;
1602
1603        /* poll() was interrupted by a signal */
1604        if (PyErr_CheckSignals())
1605            goto error;
1606
1607        if (timeout >= 0) {
1608            timeout = _PyDeadline_Get(deadline);
1609            if (timeout < 0) {
1610                nfds = 0;
1611                break;
1612            }
1613            ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
1614            /* retry epoll_wait() with the recomputed timeout */
1615        }
1616    } while(1);
1617
1618    if (nfds < 0) {
1619        PyErr_SetFromErrno(PyExc_OSError);
1620        goto error;
1621    }
1622
1623    elist = PyList_New(nfds);
1624    if (elist == NULL) {
1625        goto error;
1626    }
1627
1628    for (i = 0; i < nfds; i++) {
1629        etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
1630        if (etuple == NULL) {
1631            Py_CLEAR(elist);
1632            goto error;
1633        }
1634        PyList_SET_ITEM(elist, i, etuple);
1635    }
1636
1637    error:
1638    PyMem_Free(evs);
1639    return elist;
1640}
1641
1642
1643/*[clinic input]
1644select.epoll.__enter__
1645
1646[clinic start generated code]*/
1647
1648static PyObject *
1649select_epoll___enter___impl(pyEpoll_Object *self)
1650/*[clinic end generated code: output=ab45d433504db2a0 input=3c22568587efeadb]*/
1651{
1652    if (self->epfd < 0)
1653        return pyepoll_err_closed();
1654
1655    Py_INCREF(self);
1656    return (PyObject *)self;
1657}
1658
1659/*[clinic input]
1660select.epoll.__exit__
1661
1662    exc_type:  object = None
1663    exc_value: object = None
1664    exc_tb:    object = None
1665    /
1666
1667[clinic start generated code]*/
1668
1669static PyObject *
1670select_epoll___exit___impl(pyEpoll_Object *self, PyObject *exc_type,
1671                           PyObject *exc_value, PyObject *exc_tb)
1672/*[clinic end generated code: output=c480f38ce361748e input=7ae81a5a4c1a98d8]*/
1673{
1674    _selectstate *state = _selectstate_by_type(Py_TYPE(self));
1675    return PyObject_CallMethodObjArgs((PyObject *)self, state->close, NULL);
1676}
1677
1678static PyGetSetDef pyepoll_getsetlist[] = {
1679    {"closed", (getter)pyepoll_get_closed, NULL,
1680     "True if the epoll handler is closed"},
1681    {0},
1682};
1683
1684PyDoc_STRVAR(pyepoll_doc,
1685"select.epoll(sizehint=-1, flags=0)\n\
1686\n\
1687Returns an epolling object\n\
1688\n\
1689sizehint must be a positive integer or -1 for the default size. The\n\
1690sizehint is used to optimize internal data structures. It doesn't limit\n\
1691the maximum number of monitored events.");
1692
1693#endif /* HAVE_EPOLL */
1694
1695#ifdef HAVE_KQUEUE
1696/* **************************************************************************
1697 *                      kqueue interface for BSD
1698 *
1699 * Copyright (c) 2000 Doug White, 2006 James Knight, 2007 Christian Heimes
1700 * All rights reserved.
1701 *
1702 * Redistribution and use in source and binary forms, with or without
1703 * modification, are permitted provided that the following conditions
1704 * are met:
1705 * 1. Redistributions of source code must retain the above copyright
1706 *    notice, this list of conditions and the following disclaimer.
1707 * 2. Redistributions in binary form must reproduce the above copyright
1708 *    notice, this list of conditions and the following disclaimer in the
1709 *    documentation and/or other materials provided with the distribution.
1710 *
1711 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1712 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1713 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1714 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1715 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1716 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1717 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
1718 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
1719 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
1720 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
1721 * SUCH DAMAGE.
1722 */
1723
1724#ifdef HAVE_SYS_EVENT_H
1725#include <sys/event.h>
1726#endif
1727
1728PyDoc_STRVAR(kqueue_event_doc,
1729"kevent(ident, filter=KQ_FILTER_READ, flags=KQ_EV_ADD, fflags=0, data=0, udata=0)\n\
1730\n\
1731This object is the equivalent of the struct kevent for the C API.\n\
1732\n\
1733See the kqueue manpage for more detailed information about the meaning\n\
1734of the arguments.\n\
1735\n\
1736One minor note: while you might hope that udata could store a\n\
1737reference to a python object, it cannot, because it is impossible to\n\
1738keep a proper reference count of the object once it's passed into the\n\
1739kernel. Therefore, I have restricted it to only storing an integer.  I\n\
1740recommend ignoring it and simply using the 'ident' field to key off\n\
1741of. You could also set up a dictionary on the python side to store a\n\
1742udata->object mapping.");
1743
1744typedef struct {
1745    PyObject_HEAD
1746    struct kevent e;
1747} kqueue_event_Object;
1748
1749#define kqueue_event_Check(op, state) (PyObject_TypeCheck((op), state->kqueue_event_Type))
1750
1751typedef struct {
1752    PyObject_HEAD
1753    SOCKET kqfd;                /* kqueue control fd */
1754} kqueue_queue_Object;
1755
1756#if (SIZEOF_UINTPTR_T != SIZEOF_VOID_P)
1757#   error uintptr_t does not match void *!
1758#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG_LONG)
1759#   define T_UINTPTRT         T_ULONGLONG
1760#   define T_INTPTRT          T_LONGLONG
1761#   define UINTPTRT_FMT_UNIT  "K"
1762#   define INTPTRT_FMT_UNIT   "L"
1763#elif (SIZEOF_UINTPTR_T == SIZEOF_LONG)
1764#   define T_UINTPTRT         T_ULONG
1765#   define T_INTPTRT          T_LONG
1766#   define UINTPTRT_FMT_UNIT  "k"
1767#   define INTPTRT_FMT_UNIT   "l"
1768#elif (SIZEOF_UINTPTR_T == SIZEOF_INT)
1769#   define T_UINTPTRT         T_UINT
1770#   define T_INTPTRT          T_INT
1771#   define UINTPTRT_FMT_UNIT  "I"
1772#   define INTPTRT_FMT_UNIT   "i"
1773#else
1774#   error uintptr_t does not match int, long, or long long!
1775#endif
1776
1777#if SIZEOF_LONG_LONG == 8
1778#   define T_INT64          T_LONGLONG
1779#   define INT64_FMT_UNIT   "L"
1780#elif SIZEOF_LONG == 8
1781#   define T_INT64          T_LONG
1782#   define INT64_FMT_UNIT   "l"
1783#elif SIZEOF_INT == 8
1784#   define T_INT64          T_INT
1785#   define INT64_FMT_UNIT   "i"
1786#else
1787#   define INT64_FMT_UNIT   "_"
1788#endif
1789
1790#if SIZEOF_LONG_LONG == 4
1791#   define T_UINT32         T_ULONGLONG
1792#   define UINT32_FMT_UNIT  "K"
1793#elif SIZEOF_LONG == 4
1794#   define T_UINT32         T_ULONG
1795#   define UINT32_FMT_UNIT  "k"
1796#elif SIZEOF_INT == 4
1797#   define T_UINT32         T_UINT
1798#   define UINT32_FMT_UNIT  "I"
1799#else
1800#   define UINT32_FMT_UNIT  "_"
1801#endif
1802
1803/*
1804 * kevent is not standard and its members vary across BSDs.
1805 */
1806#ifdef __NetBSD__
1807#   define FILTER_TYPE      T_UINT32
1808#   define FILTER_FMT_UNIT  UINT32_FMT_UNIT
1809#   define FLAGS_TYPE       T_UINT32
1810#   define FLAGS_FMT_UNIT   UINT32_FMT_UNIT
1811#   define FFLAGS_TYPE      T_UINT32
1812#   define FFLAGS_FMT_UNIT  UINT32_FMT_UNIT
1813#else
1814#   define FILTER_TYPE      T_SHORT
1815#   define FILTER_FMT_UNIT  "h"
1816#   define FLAGS_TYPE       T_USHORT
1817#   define FLAGS_FMT_UNIT   "H"
1818#   define FFLAGS_TYPE      T_UINT
1819#   define FFLAGS_FMT_UNIT  "I"
1820#endif
1821
1822#if defined(__NetBSD__) || defined(__OpenBSD__)
1823#   define DATA_TYPE        T_INT64
1824#   define DATA_FMT_UNIT    INT64_FMT_UNIT
1825#else
1826#   define DATA_TYPE        T_INTPTRT
1827#   define DATA_FMT_UNIT    INTPTRT_FMT_UNIT
1828#endif
1829
1830/* Unfortunately, we can't store python objects in udata, because
1831 * kevents in the kernel can be removed without warning, which would
1832 * forever lose the refcount on the object stored with it.
1833 */
1834
1835#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
1836static struct PyMemberDef kqueue_event_members[] = {
1837    {"ident",           T_UINTPTRT,     KQ_OFF(e.ident)},
1838    {"filter",          FILTER_TYPE,    KQ_OFF(e.filter)},
1839    {"flags",           FLAGS_TYPE,     KQ_OFF(e.flags)},
1840    {"fflags",          T_UINT,         KQ_OFF(e.fflags)},
1841    {"data",            DATA_TYPE,      KQ_OFF(e.data)},
1842    {"udata",           T_UINTPTRT,     KQ_OFF(e.udata)},
1843    {NULL} /* Sentinel */
1844};
1845#undef KQ_OFF
1846
1847static PyObject *
1848
1849kqueue_event_repr(kqueue_event_Object *s)
1850{
1851    char buf[1024];
1852    PyOS_snprintf(
1853        buf, sizeof(buf),
1854        "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
1855        "data=0x%llx udata=%p>",
1856        (size_t)(s->e.ident), (int)s->e.filter, (unsigned int)s->e.flags,
1857        (unsigned int)s->e.fflags, (long long)(s->e.data), (void *)s->e.udata);
1858    return PyUnicode_FromString(buf);
1859}
1860
1861static int
1862kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
1863{
1864    PyObject *pfd;
1865    static char *kwlist[] = {"ident", "filter", "flags", "fflags",
1866                             "data", "udata", NULL};
1867    static const char fmt[] = "O|"
1868                FILTER_FMT_UNIT FLAGS_FMT_UNIT FFLAGS_FMT_UNIT DATA_FMT_UNIT
1869                UINTPTRT_FMT_UNIT ":kevent";
1870
1871    EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
1872
1873    if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
1874        &pfd, &(self->e.filter), &(self->e.flags),
1875        &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
1876        return -1;
1877    }
1878
1879    if (PyLong_Check(pfd)) {
1880        self->e.ident = PyLong_AsSize_t(pfd);
1881    }
1882    else {
1883        self->e.ident = PyObject_AsFileDescriptor(pfd);
1884    }
1885    if (PyErr_Occurred()) {
1886        return -1;
1887    }
1888    return 0;
1889}
1890
1891static PyObject *
1892kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
1893                         int op)
1894{
1895    int result;
1896    _selectstate *state = _selectstate_by_type(Py_TYPE(s));
1897
1898    if (!kqueue_event_Check(o, state)) {
1899        Py_RETURN_NOTIMPLEMENTED;
1900    }
1901
1902#define CMP(a, b) ((a) != (b)) ? ((a) < (b) ? -1 : 1)
1903    result = CMP(s->e.ident, o->e.ident)
1904           : CMP(s->e.filter, o->e.filter)
1905           : CMP(s->e.flags, o->e.flags)
1906           : CMP(s->e.fflags, o->e.fflags)
1907           : CMP(s->e.data, o->e.data)
1908           : CMP((intptr_t)s->e.udata, (intptr_t)o->e.udata)
1909           : 0;
1910#undef CMP
1911
1912    Py_RETURN_RICHCOMPARE(result, 0, op);
1913}
1914
1915static PyType_Slot kqueue_event_Type_slots[] = {
1916    {Py_tp_doc, (void*)kqueue_event_doc},
1917    {Py_tp_init, kqueue_event_init},
1918    {Py_tp_members, kqueue_event_members},
1919    {Py_tp_new, PyType_GenericNew},
1920    {Py_tp_repr, kqueue_event_repr},
1921    {Py_tp_richcompare, kqueue_event_richcompare},
1922    {0, 0},
1923};
1924
1925static PyType_Spec kqueue_event_Type_spec = {
1926    "select.kevent",
1927    sizeof(kqueue_event_Object),
1928    0,
1929    Py_TPFLAGS_DEFAULT,
1930    kqueue_event_Type_slots
1931};
1932
1933static PyObject *
1934kqueue_queue_err_closed(void)
1935{
1936    PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue object");
1937    return NULL;
1938}
1939
1940static int
1941kqueue_queue_internal_close(kqueue_queue_Object *self)
1942{
1943    int save_errno = 0;
1944    if (self->kqfd >= 0) {
1945        int kqfd = self->kqfd;
1946        self->kqfd = -1;
1947        Py_BEGIN_ALLOW_THREADS
1948        if (close(kqfd) < 0)
1949            save_errno = errno;
1950        Py_END_ALLOW_THREADS
1951    }
1952    return save_errno;
1953}
1954
1955static PyObject *
1956newKqueue_Object(PyTypeObject *type, SOCKET fd)
1957{
1958    kqueue_queue_Object *self;
1959    assert(type != NULL);
1960    allocfunc queue_alloc = PyType_GetSlot(type, Py_tp_alloc);
1961    assert(queue_alloc != NULL);
1962    self = (kqueue_queue_Object *) queue_alloc(type, 0);
1963    if (self == NULL) {
1964        return NULL;
1965    }
1966
1967    if (fd == -1) {
1968        Py_BEGIN_ALLOW_THREADS
1969        self->kqfd = kqueue();
1970        Py_END_ALLOW_THREADS
1971    }
1972    else {
1973        self->kqfd = fd;
1974    }
1975    if (self->kqfd < 0) {
1976        Py_DECREF(self);
1977        PyErr_SetFromErrno(PyExc_OSError);
1978        return NULL;
1979    }
1980
1981    if (fd == -1) {
1982        if (_Py_set_inheritable(self->kqfd, 0, NULL) < 0) {
1983            Py_DECREF(self);
1984            return NULL;
1985        }
1986    }
1987    return (PyObject *)self;
1988}
1989
1990/*[clinic input]
1991@classmethod
1992select.kqueue.__new__
1993
1994Kqueue syscall wrapper.
1995
1996For example, to start watching a socket for input:
1997>>> kq = kqueue()
1998>>> sock = socket()
1999>>> sock.connect((host, port))
2000>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_ADD)], 0)
2001
2002To wait one second for it to become writeable:
2003>>> kq.control(None, 1, 1000)
2004
2005To stop listening:
2006>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)
2007[clinic start generated code]*/
2008
2009static PyObject *
2010select_kqueue_impl(PyTypeObject *type)
2011/*[clinic end generated code: output=e0ff89f154d56236 input=cf625e49218366e8]*/
2012{
2013    return newKqueue_Object(type, -1);
2014}
2015
2016static void
2017kqueue_queue_dealloc(kqueue_queue_Object *self)
2018{
2019    PyTypeObject* type = Py_TYPE(self);
2020    kqueue_queue_internal_close(self);
2021    freefunc kqueue_free = PyType_GetSlot(type, Py_tp_free);
2022    kqueue_free((PyObject *)self);
2023    Py_DECREF((PyObject *)type);
2024}
2025
2026/*[clinic input]
2027select.kqueue.close
2028
2029Close the kqueue control file descriptor.
2030
2031Further operations on the kqueue object will raise an exception.
2032[clinic start generated code]*/
2033
2034static PyObject *
2035select_kqueue_close_impl(kqueue_queue_Object *self)
2036/*[clinic end generated code: output=d1c7df0b407a4bc1 input=0b12d95430e0634c]*/
2037{
2038    errno = kqueue_queue_internal_close(self);
2039    if (errno < 0) {
2040        PyErr_SetFromErrno(PyExc_OSError);
2041        return NULL;
2042    }
2043    Py_RETURN_NONE;
2044}
2045
2046static PyObject*
2047kqueue_queue_get_closed(kqueue_queue_Object *self, void *Py_UNUSED(ignored))
2048{
2049    if (self->kqfd < 0)
2050        Py_RETURN_TRUE;
2051    else
2052        Py_RETURN_FALSE;
2053}
2054
2055/*[clinic input]
2056select.kqueue.fileno
2057
2058Return the kqueue control file descriptor.
2059[clinic start generated code]*/
2060
2061static PyObject *
2062select_kqueue_fileno_impl(kqueue_queue_Object *self)
2063/*[clinic end generated code: output=716f46112a4f6e5c input=41911c539ca2b0ca]*/
2064{
2065    if (self->kqfd < 0)
2066        return kqueue_queue_err_closed();
2067    return PyLong_FromLong(self->kqfd);
2068}
2069
2070/*[clinic input]
2071@classmethod
2072select.kqueue.fromfd
2073
2074    fd: int
2075    /
2076
2077Create a kqueue object from a given control fd.
2078[clinic start generated code]*/
2079
2080static PyObject *
2081select_kqueue_fromfd_impl(PyTypeObject *type, int fd)
2082/*[clinic end generated code: output=d02c3c7dc538a653 input=f6172a48ca4ecdd0]*/
2083{
2084    SOCKET s_fd = (SOCKET)fd;
2085
2086    return newKqueue_Object(type, s_fd);
2087}
2088
2089/*[clinic input]
2090select.kqueue.control
2091
2092    changelist: object
2093        Must be an iterable of kevent objects describing the changes to be made
2094        to the kernel's watch list or None.
2095    maxevents: int
2096        The maximum number of events that the kernel will return.
2097    timeout as otimeout: object = None
2098        The maximum time to wait in seconds, or else None to wait forever.
2099        This accepts floats for smaller timeouts, too.
2100    /
2101
2102Calls the kernel kevent function.
2103[clinic start generated code]*/
2104
2105static PyObject *
2106select_kqueue_control_impl(kqueue_queue_Object *self, PyObject *changelist,
2107                           int maxevents, PyObject *otimeout)
2108/*[clinic end generated code: output=81324ff5130db7ae input=59c4e30811209c47]*/
2109{
2110    int gotevents = 0;
2111    int nchanges = 0;
2112    int i = 0;
2113    PyObject *seq = NULL, *ei = NULL;
2114    PyObject *result = NULL;
2115    struct kevent *evl = NULL;
2116    struct kevent *chl = NULL;
2117    struct timespec timeoutspec;
2118    struct timespec *ptimeoutspec;
2119    _PyTime_t timeout, deadline = 0;
2120    _selectstate *state = _selectstate_by_type(Py_TYPE(self));
2121
2122    if (self->kqfd < 0)
2123        return kqueue_queue_err_closed();
2124
2125    if (maxevents < 0) {
2126        PyErr_Format(PyExc_ValueError,
2127            "Length of eventlist must be 0 or positive, got %d",
2128            maxevents);
2129        return NULL;
2130    }
2131
2132    if (otimeout == Py_None) {
2133        ptimeoutspec = NULL;
2134    }
2135    else {
2136        if (_PyTime_FromSecondsObject(&timeout,
2137                                      otimeout, _PyTime_ROUND_TIMEOUT) < 0) {
2138            PyErr_Format(PyExc_TypeError,
2139                "timeout argument must be a number "
2140                "or None, got %.200s",
2141                _PyType_Name(Py_TYPE(otimeout)));
2142            return NULL;
2143        }
2144
2145        if (_PyTime_AsTimespec(timeout, &timeoutspec) == -1)
2146            return NULL;
2147
2148        if (timeoutspec.tv_sec < 0) {
2149            PyErr_SetString(PyExc_ValueError,
2150                            "timeout must be positive or None");
2151            return NULL;
2152        }
2153        ptimeoutspec = &timeoutspec;
2154    }
2155
2156    if (changelist != Py_None) {
2157        seq = PySequence_Fast(changelist, "changelist is not iterable");
2158        if (seq == NULL) {
2159            return NULL;
2160        }
2161        if (PySequence_Fast_GET_SIZE(seq) > INT_MAX) {
2162            PyErr_SetString(PyExc_OverflowError,
2163                            "changelist is too long");
2164            goto error;
2165        }
2166        nchanges = (int)PySequence_Fast_GET_SIZE(seq);
2167
2168        chl = PyMem_New(struct kevent, nchanges);
2169        if (chl == NULL) {
2170            PyErr_NoMemory();
2171            goto error;
2172        }
2173        _selectstate *state = _selectstate_by_type(Py_TYPE(self));
2174        for (i = 0; i < nchanges; ++i) {
2175            ei = PySequence_Fast_GET_ITEM(seq, i);
2176            if (!kqueue_event_Check(ei, state)) {
2177                PyErr_SetString(PyExc_TypeError,
2178                    "changelist must be an iterable of "
2179                    "select.kevent objects");
2180                goto error;
2181            }
2182            chl[i] = ((kqueue_event_Object *)ei)->e;
2183        }
2184        Py_CLEAR(seq);
2185    }
2186
2187    /* event list */
2188    if (maxevents) {
2189        evl = PyMem_New(struct kevent, maxevents);
2190        if (evl == NULL) {
2191            PyErr_NoMemory();
2192            goto error;
2193        }
2194    }
2195
2196    if (ptimeoutspec) {
2197        deadline = _PyDeadline_Init(timeout);
2198    }
2199
2200    do {
2201        Py_BEGIN_ALLOW_THREADS
2202        errno = 0;
2203        gotevents = kevent(self->kqfd, chl, nchanges,
2204                           evl, maxevents, ptimeoutspec);
2205        Py_END_ALLOW_THREADS
2206
2207        if (errno != EINTR)
2208            break;
2209
2210        /* kevent() was interrupted by a signal */
2211        if (PyErr_CheckSignals())
2212            goto error;
2213
2214        if (ptimeoutspec) {
2215            timeout = _PyDeadline_Get(deadline);
2216            if (timeout < 0) {
2217                gotevents = 0;
2218                break;
2219            }
2220            if (_PyTime_AsTimespec(timeout, &timeoutspec) == -1)
2221                goto error;
2222            /* retry kevent() with the recomputed timeout */
2223        }
2224    } while (1);
2225
2226    if (gotevents == -1) {
2227        PyErr_SetFromErrno(PyExc_OSError);
2228        goto error;
2229    }
2230
2231    result = PyList_New(gotevents);
2232    if (result == NULL) {
2233        goto error;
2234    }
2235
2236    for (i = 0; i < gotevents; i++) {
2237        kqueue_event_Object *ch;
2238
2239        ch = PyObject_New(kqueue_event_Object, state->kqueue_event_Type);
2240        if (ch == NULL) {
2241            goto error;
2242        }
2243        ch->e = evl[i];
2244        PyList_SET_ITEM(result, i, (PyObject *)ch);
2245    }
2246    PyMem_Free(chl);
2247    PyMem_Free(evl);
2248    return result;
2249
2250    error:
2251    PyMem_Free(chl);
2252    PyMem_Free(evl);
2253    Py_XDECREF(result);
2254    Py_XDECREF(seq);
2255    return NULL;
2256}
2257
2258static PyGetSetDef kqueue_queue_getsetlist[] = {
2259    {"closed", (getter)kqueue_queue_get_closed, NULL,
2260     "True if the kqueue handler is closed"},
2261    {0},
2262};
2263
2264#endif /* HAVE_KQUEUE */
2265
2266
2267/* ************************************************************************ */
2268
2269#include "clinic/selectmodule.c.h"
2270
2271#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
2272
2273static PyMethodDef poll_methods[] = {
2274    SELECT_POLL_REGISTER_METHODDEF
2275    SELECT_POLL_MODIFY_METHODDEF
2276    SELECT_POLL_UNREGISTER_METHODDEF
2277    SELECT_POLL_POLL_METHODDEF
2278    {NULL, NULL}           /* sentinel */
2279};
2280
2281
2282static PyType_Slot poll_Type_slots[] = {
2283    {Py_tp_dealloc, poll_dealloc},
2284    {Py_tp_methods, poll_methods},
2285    {0, 0},
2286};
2287
2288static PyType_Spec poll_Type_spec = {
2289    .name = "select.poll",
2290    .basicsize = sizeof(pollObject),
2291    .flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION,
2292    .slots = poll_Type_slots,
2293};
2294
2295#ifdef HAVE_SYS_DEVPOLL_H
2296
2297static PyMethodDef devpoll_methods[] = {
2298    SELECT_DEVPOLL_REGISTER_METHODDEF
2299    SELECT_DEVPOLL_MODIFY_METHODDEF
2300    SELECT_DEVPOLL_UNREGISTER_METHODDEF
2301    SELECT_DEVPOLL_POLL_METHODDEF
2302    SELECT_DEVPOLL_CLOSE_METHODDEF
2303    SELECT_DEVPOLL_FILENO_METHODDEF
2304    {NULL,              NULL}           /* sentinel */
2305};
2306
2307#endif  /* HAVE_SYS_DEVPOLL_H */
2308
2309#endif /* HAVE_POLL */
2310
2311#ifdef HAVE_EPOLL
2312
2313static PyMethodDef pyepoll_methods[] = {
2314    SELECT_EPOLL_FROMFD_METHODDEF
2315    SELECT_EPOLL_CLOSE_METHODDEF
2316    SELECT_EPOLL_FILENO_METHODDEF
2317    SELECT_EPOLL_MODIFY_METHODDEF
2318    SELECT_EPOLL_REGISTER_METHODDEF
2319    SELECT_EPOLL_UNREGISTER_METHODDEF
2320    SELECT_EPOLL_POLL_METHODDEF
2321    SELECT_EPOLL___ENTER___METHODDEF
2322    SELECT_EPOLL___EXIT___METHODDEF
2323    {NULL,      NULL},
2324};
2325
2326static PyType_Slot pyEpoll_Type_slots[] = {
2327    {Py_tp_dealloc, pyepoll_dealloc},
2328    {Py_tp_doc, (void*)pyepoll_doc},
2329    {Py_tp_getattro, PyObject_GenericGetAttr},
2330    {Py_tp_getset, pyepoll_getsetlist},
2331    {Py_tp_methods, pyepoll_methods},
2332    {Py_tp_new, select_epoll},
2333    {0, 0},
2334};
2335
2336static PyType_Spec pyEpoll_Type_spec = {
2337    "select.epoll",
2338    sizeof(pyEpoll_Object),
2339    0,
2340    Py_TPFLAGS_DEFAULT,
2341    pyEpoll_Type_slots
2342};
2343
2344#endif /* HAVE_EPOLL */
2345
2346#ifdef HAVE_KQUEUE
2347
2348static PyMethodDef kqueue_queue_methods[] = {
2349    SELECT_KQUEUE_FROMFD_METHODDEF
2350    SELECT_KQUEUE_CLOSE_METHODDEF
2351    SELECT_KQUEUE_FILENO_METHODDEF
2352    SELECT_KQUEUE_CONTROL_METHODDEF
2353    {NULL,      NULL},
2354};
2355
2356static PyType_Slot kqueue_queue_Type_slots[] = {
2357    {Py_tp_dealloc, kqueue_queue_dealloc},
2358    {Py_tp_doc, (void*)select_kqueue__doc__},
2359    {Py_tp_getset, kqueue_queue_getsetlist},
2360    {Py_tp_methods, kqueue_queue_methods},
2361    {Py_tp_new, select_kqueue},
2362    {0, 0},
2363};
2364
2365static PyType_Spec kqueue_queue_Type_spec = {
2366    "select.kqueue",
2367    sizeof(kqueue_queue_Object),
2368    0,
2369    Py_TPFLAGS_DEFAULT,
2370    kqueue_queue_Type_slots
2371};
2372
2373#endif /* HAVE_KQUEUE */
2374
2375
2376
2377
2378
2379/* ************************************************************************ */
2380
2381
2382static PyMethodDef select_methods[] = {
2383    SELECT_SELECT_METHODDEF
2384    SELECT_POLL_METHODDEF
2385    SELECT_DEVPOLL_METHODDEF
2386    {0,         0},     /* sentinel */
2387};
2388
2389PyDoc_STRVAR(module_doc,
2390"This module supports asynchronous I/O on multiple file descriptors.\n\
2391\n\
2392*** IMPORTANT NOTICE ***\n\
2393On Windows, only sockets are supported; on Unix, all file descriptors.");
2394
2395
2396
2397static int
2398_select_traverse(PyObject *module, visitproc visit, void *arg)
2399{
2400    _selectstate *state = get_select_state(module);
2401
2402    Py_VISIT(state->close);
2403    Py_VISIT(state->poll_Type);
2404    Py_VISIT(state->devpoll_Type);
2405    Py_VISIT(state->pyEpoll_Type);
2406    Py_VISIT(state->kqueue_event_Type);
2407    Py_VISIT(state->kqueue_queue_Type);
2408    return 0;
2409}
2410
2411static int
2412_select_clear(PyObject *module)
2413{
2414    _selectstate *state = get_select_state(module);
2415
2416    Py_CLEAR(state->close);
2417    Py_CLEAR(state->poll_Type);
2418    Py_CLEAR(state->devpoll_Type);
2419    Py_CLEAR(state->pyEpoll_Type);
2420    Py_CLEAR(state->kqueue_event_Type);
2421    Py_CLEAR(state->kqueue_queue_Type);
2422    return 0;
2423}
2424
2425static void
2426_select_free(void *module)
2427{
2428    _select_clear((PyObject *)module);
2429}
2430
2431int
2432_select_exec(PyObject *m)
2433{
2434    _selectstate *state = get_select_state(m);
2435
2436    state->close = PyUnicode_InternFromString("close");
2437    if (state->close == NULL) {
2438        return -1;
2439    }
2440    if (PyModule_AddObjectRef(m, "error", PyExc_OSError) < 0) {
2441        return -1;
2442    }
2443
2444#ifdef PIPE_BUF
2445#ifdef HAVE_BROKEN_PIPE_BUF
2446#undef PIPE_BUF
2447#define PIPE_BUF 512
2448#endif
2449    PyModule_AddIntMacro(m, PIPE_BUF);
2450#endif
2451
2452#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
2453#ifdef __APPLE__
2454    if (select_have_broken_poll()) {
2455        if (PyObject_DelAttrString(m, "poll") == -1) {
2456            PyErr_Clear();
2457        }
2458    } else {
2459#else
2460    {
2461#endif
2462        state->poll_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
2463            m, &poll_Type_spec, NULL);
2464        if (state->poll_Type == NULL) {
2465            return -1;
2466        }
2467
2468        PyModule_AddIntMacro(m, POLLIN);
2469        PyModule_AddIntMacro(m, POLLPRI);
2470        PyModule_AddIntMacro(m, POLLOUT);
2471        PyModule_AddIntMacro(m, POLLERR);
2472        PyModule_AddIntMacro(m, POLLHUP);
2473        PyModule_AddIntMacro(m, POLLNVAL);
2474
2475#ifdef POLLRDNORM
2476        PyModule_AddIntMacro(m, POLLRDNORM);
2477#endif
2478#ifdef POLLRDBAND
2479        PyModule_AddIntMacro(m, POLLRDBAND);
2480#endif
2481#ifdef POLLWRNORM
2482        PyModule_AddIntMacro(m, POLLWRNORM);
2483#endif
2484#ifdef POLLWRBAND
2485        PyModule_AddIntMacro(m, POLLWRBAND);
2486#endif
2487#ifdef POLLMSG
2488        PyModule_AddIntMacro(m, POLLMSG);
2489#endif
2490#ifdef POLLRDHUP
2491        /* Kernel 2.6.17+ */
2492        PyModule_AddIntMacro(m, POLLRDHUP);
2493#endif
2494    }
2495#endif /* HAVE_POLL */
2496
2497#ifdef HAVE_SYS_DEVPOLL_H
2498    state->devpoll_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
2499        m, &devpoll_Type_spec, NULL);
2500    if (state->devpoll_Type == NULL) {
2501        return -1;
2502    }
2503#endif
2504
2505#ifdef HAVE_EPOLL
2506    state->pyEpoll_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
2507        m, &pyEpoll_Type_spec, NULL);
2508    if (state->pyEpoll_Type == NULL) {
2509        return -1;
2510    }
2511    if (PyModule_AddType(m, state->pyEpoll_Type) < 0) {
2512        return -1;
2513    }
2514
2515    PyModule_AddIntMacro(m, EPOLLIN);
2516    PyModule_AddIntMacro(m, EPOLLOUT);
2517    PyModule_AddIntMacro(m, EPOLLPRI);
2518    PyModule_AddIntMacro(m, EPOLLERR);
2519    PyModule_AddIntMacro(m, EPOLLHUP);
2520#ifdef EPOLLRDHUP
2521    /* Kernel 2.6.17 */
2522    PyModule_AddIntMacro(m, EPOLLRDHUP);
2523#endif
2524    PyModule_AddIntMacro(m, EPOLLET);
2525#ifdef EPOLLONESHOT
2526    /* Kernel 2.6.2+ */
2527    PyModule_AddIntMacro(m, EPOLLONESHOT);
2528#endif
2529#ifdef EPOLLEXCLUSIVE
2530    PyModule_AddIntMacro(m, EPOLLEXCLUSIVE);
2531#endif
2532
2533#ifdef EPOLLRDNORM
2534    PyModule_AddIntMacro(m, EPOLLRDNORM);
2535#endif
2536#ifdef EPOLLRDBAND
2537    PyModule_AddIntMacro(m, EPOLLRDBAND);
2538#endif
2539#ifdef EPOLLWRNORM
2540    PyModule_AddIntMacro(m, EPOLLWRNORM);
2541#endif
2542#ifdef EPOLLWRBAND
2543    PyModule_AddIntMacro(m, EPOLLWRBAND);
2544#endif
2545#ifdef EPOLLMSG
2546    PyModule_AddIntMacro(m, EPOLLMSG);
2547#endif
2548
2549#ifdef EPOLL_CLOEXEC
2550    PyModule_AddIntMacro(m, EPOLL_CLOEXEC);
2551#endif
2552#endif /* HAVE_EPOLL */
2553
2554#ifdef HAVE_KQUEUE
2555    state->kqueue_event_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
2556        m, &kqueue_event_Type_spec, NULL);
2557    if (state->kqueue_event_Type == NULL) {
2558        return -1;
2559    }
2560    if (PyModule_AddType(m, state->kqueue_event_Type) < 0) {
2561        return -1;
2562    }
2563
2564    state->kqueue_queue_Type = (PyTypeObject *)PyType_FromModuleAndSpec(
2565        m, &kqueue_queue_Type_spec, NULL);
2566    if (state->kqueue_queue_Type == NULL) {
2567        return -1;
2568    }
2569    if (PyModule_AddType(m, state->kqueue_queue_Type) < 0) {
2570        return -1;
2571    }
2572
2573    /* event filters */
2574    PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
2575    PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
2576#ifdef EVFILT_AIO
2577    PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
2578#endif
2579#ifdef EVFILT_VNODE
2580    PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
2581#endif
2582#ifdef EVFILT_PROC
2583    PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
2584#endif
2585#ifdef EVFILT_NETDEV
2586    PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
2587#endif
2588#ifdef EVFILT_SIGNAL
2589    PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
2590#endif
2591    PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
2592
2593    /* event flags */
2594    PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
2595    PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
2596    PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
2597    PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
2598    PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
2599    PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
2600
2601#ifdef EV_SYSFLAGS
2602    PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
2603#endif
2604#ifdef EV_FLAG1
2605    PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
2606#endif
2607
2608    PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
2609    PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
2610
2611    /* READ WRITE filter flag */
2612#ifdef NOTE_LOWAT
2613    PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
2614#endif
2615
2616    /* VNODE filter flags  */
2617#ifdef EVFILT_VNODE
2618    PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
2619    PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
2620    PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
2621    PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
2622    PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
2623    PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
2624    PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
2625#endif
2626
2627    /* PROC filter flags  */
2628#ifdef EVFILT_PROC
2629    PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
2630    PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
2631    PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
2632    PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
2633    PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
2634
2635    PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
2636    PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
2637    PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
2638#endif
2639
2640    /* NETDEV filter flags */
2641#ifdef EVFILT_NETDEV
2642    PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
2643    PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
2644    PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
2645#endif
2646
2647#endif /* HAVE_KQUEUE */
2648    return 0;
2649}
2650
2651static PyModuleDef_Slot _select_slots[] = {
2652    {Py_mod_exec, _select_exec},
2653    {0, NULL}
2654};
2655
2656static struct PyModuleDef selectmodule = {
2657    PyModuleDef_HEAD_INIT,
2658    .m_name = "select",
2659    .m_doc = module_doc,
2660    .m_size = sizeof(_selectstate),
2661    .m_methods = select_methods,
2662    .m_slots = _select_slots,
2663    .m_traverse = _select_traverse,
2664    .m_clear = _select_clear,
2665    .m_free = _select_free,
2666};
2667
2668PyMODINIT_FUNC
2669PyInit_select(void)
2670{
2671    return PyModuleDef_Init(&selectmodule);
2672}
2673