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