-
-
Notifications
You must be signed in to change notification settings - Fork 31k
/
Copy pathselectmodule.c
2672 lines (2259 loc) · 70.3 KB
/
selectmodule.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* select - Module containing unix select(2) call.
Under Unix, the file descriptors are small integers.
Under Win32, select only exists for sockets, and sockets may
have any value except INVALID_SOCKET.
*/
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#if defined(HAVE_POLL_H) && !defined(_GNU_SOURCE)
# define _GNU_SOURCE
#endif
#include "Python.h"
#include "pycore_fileutils.h" // _Py_set_inheritable()
#include "structmember.h" // PyMemberDef
#ifdef HAVE_SYS_DEVPOLL_H
#include <sys/resource.h>
#include <sys/devpoll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
#ifdef __APPLE__
/* Perform runtime testing for a broken poll on OSX to make it easier
* to use the same binary on multiple releases of the OS.
*/
#undef HAVE_BROKEN_POLL
#endif
/* Windows #defines FD_SETSIZE to 64 if FD_SETSIZE isn't already defined.
64 is too small (too many people have bumped into that limit).
Here we boost it.
Users who want even more than the boosted limit should #define
FD_SETSIZE higher before this; e.g., via compiler /D switch.
*/
#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
#define FD_SETSIZE 512
#endif
#if defined(HAVE_POLL_H)
#include <poll.h>
#elif defined(HAVE_SYS_POLL_H)
#include <sys/poll.h>
#endif
#ifdef __sgi
/* This is missing from unistd.h */
extern void bzero(void *, int);
#endif
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef MS_WINDOWS
# define WIN32_LEAN_AND_MEAN
# include <winsock.h>
#else
# define SOCKET int
#endif
// WASI SDK 16 does not have POLLPRIO, define as no-op
#if defined(__wasi__) && !defined(POLLPRI)
# define POLLPRI 0
#endif
typedef struct {
PyObject *close;
PyTypeObject *poll_Type;
PyTypeObject *devpoll_Type;
PyTypeObject *pyEpoll_Type;
PyTypeObject *kqueue_event_Type;
PyTypeObject *kqueue_queue_Type;
} _selectstate;
static struct PyModuleDef selectmodule;
static inline _selectstate*
get_select_state(PyObject *module)
{
void *state = PyModule_GetState(module);
assert(state != NULL);
return (_selectstate *)state;
}
#define _selectstate_by_type(type) get_select_state(PyType_GetModule(type))
/*[clinic input]
module select
class select.poll "pollObject *" "_selectstate_by_type(type)->poll_Type"
class select.devpoll "devpollObject *" "_selectstate_by_type(type)->devpoll_Type"
class select.epoll "pyEpoll_Object *" "_selectstate_by_type(type)->pyEpoll_Type"
class select.kqueue "kqueue_queue_Object *" "_selectstate_by_type(type)->kqueue_queue_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=8072de35824aa327]*/
/* list of Python objects and their file descriptor */
typedef struct {
PyObject *obj; /* owned reference */
SOCKET fd;
int sentinel; /* -1 == sentinel */
} pylist;
static void
reap_obj(pylist fd2obj[FD_SETSIZE + 1])
{
unsigned int i;
for (i = 0; i < (unsigned int)FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
Py_CLEAR(fd2obj[i].obj);
}
fd2obj[0].sentinel = -1;
}
/* returns -1 and sets the Python exception if an error occurred, otherwise
returns a number >= 0
*/
static int
seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
int max = -1;
unsigned int index = 0;
Py_ssize_t i;
PyObject* fast_seq = NULL;
PyObject* o = NULL;
fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
FD_ZERO(set);
fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
if (!fast_seq)
return -1;
for (i = 0; i < PySequence_Fast_GET_SIZE(fast_seq); i++) {
SOCKET v;
/* any intervening fileno() calls could decr this refcnt */
if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
goto finally;
Py_INCREF(o);
v = PyObject_AsFileDescriptor( o );
if (v == -1) goto finally;
#if defined(_MSC_VER)
max = 0; /* not used for Win32 */
#else /* !_MSC_VER */
if (!_PyIsSelectable_fd(v)) {
PyErr_SetString(PyExc_ValueError,
"filedescriptor out of range in select()");
goto finally;
}
if (v > max)
max = v;
#endif /* _MSC_VER */
FD_SET(v, set);
/* add object and its file descriptor to the list */
if (index >= (unsigned int)FD_SETSIZE) {
PyErr_SetString(PyExc_ValueError,
"too many file descriptors in select()");
goto finally;
}
fd2obj[index].obj = o;
fd2obj[index].fd = v;
fd2obj[index].sentinel = 0;
fd2obj[++index].sentinel = -1;
}
Py_DECREF(fast_seq);
return max+1;
finally:
Py_XDECREF(o);
Py_DECREF(fast_seq);
return -1;
}
/* returns NULL and sets the Python exception if an error occurred */
static PyObject *
set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
int i, j, count=0;
PyObject *list, *o;
SOCKET fd;
for (j = 0; fd2obj[j].sentinel >= 0; j++) {
if (FD_ISSET(fd2obj[j].fd, set))
count++;
}
list = PyList_New(count);
if (!list)
return NULL;
i = 0;
for (j = 0; fd2obj[j].sentinel >= 0; j++) {
fd = fd2obj[j].fd;
if (FD_ISSET(fd, set)) {
o = fd2obj[j].obj;
fd2obj[j].obj = NULL;
/* transfer ownership */
if (PyList_SetItem(list, i, o) < 0)
goto finally;
i++;
}
}
return list;
finally:
Py_DECREF(list);
return NULL;
}
#undef SELECT_USES_HEAP
#if FD_SETSIZE > 1024
#define SELECT_USES_HEAP
#endif /* FD_SETSIZE > 1024 */
/*[clinic input]
select.select
rlist: object
wlist: object
xlist: object
timeout as timeout_obj: object = None
/
Wait until one or more file descriptors are ready for some kind of I/O.
The first three arguments are iterables of file descriptors to be waited for:
rlist -- wait until ready for reading
wlist -- wait until ready for writing
xlist -- wait for an "exceptional condition"
If only one kind of condition is required, pass [] for the other lists.
A file descriptor is either a socket or file object, or a small integer
gotten from a fileno() method call on one of those.
The optional 4th argument specifies a timeout in seconds; it may be
a floating point number to specify fractions of seconds. If it is absent
or None, the call will never time out.
The return value is a tuple of three lists corresponding to the first three
arguments; each contains the subset of the corresponding file descriptors
that are ready.
*** IMPORTANT NOTICE ***
On Windows, only sockets are supported; on Unix, all file
descriptors can be used.
[clinic start generated code]*/
static PyObject *
select_select_impl(PyObject *module, PyObject *rlist, PyObject *wlist,
PyObject *xlist, PyObject *timeout_obj)
/*[clinic end generated code: output=2b3cfa824f7ae4cf input=e467f5d68033de00]*/
{
#ifdef SELECT_USES_HEAP
pylist *rfd2obj, *wfd2obj, *efd2obj;
#else /* !SELECT_USES_HEAP */
/* XXX: All this should probably be implemented as follows:
* - find the highest descriptor we're interested in
* - add one
* - that's the size
* See: Stevens, APitUE, $12.5.1
*/
pylist rfd2obj[FD_SETSIZE + 1];
pylist wfd2obj[FD_SETSIZE + 1];
pylist efd2obj[FD_SETSIZE + 1];
#endif /* SELECT_USES_HEAP */
PyObject *ret = NULL;
fd_set ifdset, ofdset, efdset;
struct timeval tv, *tvp;
int imax, omax, emax, max;
int n;
_PyTime_t timeout, deadline = 0;
if (timeout_obj == Py_None)
tvp = (struct timeval *)NULL;
else {
if (_PyTime_FromSecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be a float or None");
}
return NULL;
}
if (_PyTime_AsTimeval(timeout, &tv, _PyTime_ROUND_TIMEOUT) == -1)
return NULL;
if (tv.tv_sec < 0) {
PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
return NULL;
}
tvp = &tv;
}
#ifdef SELECT_USES_HEAP
/* Allocate memory for the lists */
rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
if (rfd2obj) PyMem_Free(rfd2obj);
if (wfd2obj) PyMem_Free(wfd2obj);
if (efd2obj) PyMem_Free(efd2obj);
return PyErr_NoMemory();
}
#endif /* SELECT_USES_HEAP */
/* Convert iterables to fd_sets, and get maximum fd number
* propagates the Python exception set in seq2set()
*/
rfd2obj[0].sentinel = -1;
wfd2obj[0].sentinel = -1;
efd2obj[0].sentinel = -1;
if ((imax = seq2set(rlist, &ifdset, rfd2obj)) < 0)
goto finally;
if ((omax = seq2set(wlist, &ofdset, wfd2obj)) < 0)
goto finally;
if ((emax = seq2set(xlist, &efdset, efd2obj)) < 0)
goto finally;
max = imax;
if (omax > max) max = omax;
if (emax > max) max = emax;
if (tvp) {
deadline = _PyDeadline_Init(timeout);
}
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
n = select(
max,
imax ? &ifdset : NULL,
omax ? &ofdset : NULL,
emax ? &efdset : NULL,
tvp);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* select() was interrupted by a signal */
if (PyErr_CheckSignals())
goto finally;
if (tvp) {
timeout = _PyDeadline_Get(deadline);
if (timeout < 0) {
/* bpo-35310: lists were unmodified -- clear them explicitly */
FD_ZERO(&ifdset);
FD_ZERO(&ofdset);
FD_ZERO(&efdset);
n = 0;
break;
}
_PyTime_AsTimeval_clamp(timeout, &tv, _PyTime_ROUND_CEILING);
/* retry select() with the recomputed timeout */
}
} while (1);
#ifdef MS_WINDOWS
if (n == SOCKET_ERROR) {
PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError());
}
#else
if (n < 0) {
PyErr_SetFromErrno(PyExc_OSError);
}
#endif
else {
/* any of these three calls can raise an exception. it's more
convenient to test for this after all three calls... but
is that acceptable?
*/
rlist = set2list(&ifdset, rfd2obj);
wlist = set2list(&ofdset, wfd2obj);
xlist = set2list(&efdset, efd2obj);
if (PyErr_Occurred())
ret = NULL;
else
ret = PyTuple_Pack(3, rlist, wlist, xlist);
Py_XDECREF(rlist);
Py_XDECREF(wlist);
Py_XDECREF(xlist);
}
finally:
reap_obj(rfd2obj);
reap_obj(wfd2obj);
reap_obj(efd2obj);
#ifdef SELECT_USES_HEAP
PyMem_Free(rfd2obj);
PyMem_Free(wfd2obj);
PyMem_Free(efd2obj);
#endif /* SELECT_USES_HEAP */
return ret;
}
#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
/*
* poll() support
*/
typedef struct {
PyObject_HEAD
PyObject *dict;
int ufd_uptodate;
int ufd_len;
struct pollfd *ufds;
int poll_running;
} pollObject;
/* Update the malloc'ed array of pollfds to match the dictionary
contained within a pollObject. Return 1 on success, 0 on an error.
*/
static int
update_ufd_array(pollObject *self)
{
Py_ssize_t i, pos;
PyObject *key, *value;
struct pollfd *old_ufds = self->ufds;
self->ufd_len = PyDict_GET_SIZE(self->dict);
PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
if (self->ufds == NULL) {
self->ufds = old_ufds;
PyErr_NoMemory();
return 0;
}
i = pos = 0;
while (PyDict_Next(self->dict, &pos, &key, &value)) {
assert(i < self->ufd_len);
/* Never overflow */
self->ufds[i].fd = (int)PyLong_AsLong(key);
self->ufds[i].events = (short)(unsigned short)PyLong_AsLong(value);
i++;
}
assert(i == self->ufd_len);
self->ufd_uptodate = 1;
return 1;
}
/*[clinic input]
select.poll.register
fd: fildes
either an integer, or an object with a fileno() method returning an int
eventmask: unsigned_short(c_default="POLLIN | POLLPRI | POLLOUT") = select.POLLIN | select.POLLPRI | select.POLLOUT
an optional bitmask describing the type of events to check for
/
Register a file descriptor with the polling object.
[clinic start generated code]*/
static PyObject *
select_poll_register_impl(pollObject *self, int fd, unsigned short eventmask)
/*[clinic end generated code: output=0dc7173c800a4a65 input=34e16cfb28d3c900]*/
{
PyObject *key, *value;
int err;
/* Add entry to the internal dictionary: the key is the
file descriptor, and the value is the event mask. */
key = PyLong_FromLong(fd);
if (key == NULL)
return NULL;
value = PyLong_FromLong(eventmask);
if (value == NULL) {
Py_DECREF(key);
return NULL;
}
err = PyDict_SetItem(self->dict, key, value);
Py_DECREF(key);
Py_DECREF(value);
if (err < 0)
return NULL;
self->ufd_uptodate = 0;
Py_RETURN_NONE;
}
/*[clinic input]
select.poll.modify
fd: fildes
either an integer, or an object with a fileno() method returning
an int
eventmask: unsigned_short
a bitmask describing the type of events to check for
/
Modify an already registered file descriptor.
[clinic start generated code]*/
static PyObject *
select_poll_modify_impl(pollObject *self, int fd, unsigned short eventmask)
/*[clinic end generated code: output=1a7b88bf079eff17 input=a8e383df075c32cf]*/
{
PyObject *key, *value;
int err;
/* Modify registered fd */
key = PyLong_FromLong(fd);
if (key == NULL)
return NULL;
err = PyDict_Contains(self->dict, key);
if (err < 0) {
Py_DECREF(key);
return NULL;
}
if (err == 0) {
errno = ENOENT;
PyErr_SetFromErrno(PyExc_OSError);
Py_DECREF(key);
return NULL;
}
value = PyLong_FromLong(eventmask);
if (value == NULL) {
Py_DECREF(key);
return NULL;
}
err = PyDict_SetItem(self->dict, key, value);
Py_DECREF(key);
Py_DECREF(value);
if (err < 0)
return NULL;
self->ufd_uptodate = 0;
Py_RETURN_NONE;
}
/*[clinic input]
select.poll.unregister
fd: fildes
/
Remove a file descriptor being tracked by the polling object.
[clinic start generated code]*/
static PyObject *
select_poll_unregister_impl(pollObject *self, int fd)
/*[clinic end generated code: output=8c9f42e75e7d291b input=4b4fccc1040e79cb]*/
{
PyObject *key;
/* Check whether the fd is already in the array */
key = PyLong_FromLong(fd);
if (key == NULL)
return NULL;
if (PyDict_DelItem(self->dict, key) == -1) {
Py_DECREF(key);
/* This will simply raise the KeyError set by PyDict_DelItem
if the file descriptor isn't registered. */
return NULL;
}
Py_DECREF(key);
self->ufd_uptodate = 0;
Py_RETURN_NONE;
}
/*[clinic input]
select.poll.poll
timeout as timeout_obj: object = None
The maximum time to wait in milliseconds, or else None (or a negative
value) to wait indefinitely.
/
Polls the set of registered file descriptors.
Returns a list containing any descriptors that have events or errors to
report, as a list of (fd, event) 2-tuples.
[clinic start generated code]*/
static PyObject *
select_poll_poll_impl(pollObject *self, PyObject *timeout_obj)
/*[clinic end generated code: output=876e837d193ed7e4 input=c2f6953ec45e5622]*/
{
PyObject *result_list = NULL;
int poll_result, i, j;
PyObject *value = NULL, *num = NULL;
_PyTime_t timeout = -1, ms = -1, deadline = 0;
int async_err = 0;
if (timeout_obj != Py_None) {
if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be an integer or None");
}
return NULL;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
if (ms < INT_MIN || ms > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "timeout is too large");
return NULL;
}
if (timeout >= 0) {
deadline = _PyDeadline_Init(timeout);
}
}
/* On some OSes, typically BSD-based ones, the timeout parameter of the
poll() syscall, when negative, must be exactly INFTIM, where defined,
or -1. See issue 31334. */
if (ms < 0) {
#ifdef INFTIM
ms = INFTIM;
#else
ms = -1;
#endif
}
/* Avoid concurrent poll() invocation, issue 8865 */
if (self->poll_running) {
PyErr_SetString(PyExc_RuntimeError,
"concurrent poll() invocation");
return NULL;
}
/* Ensure the ufd array is up to date */
if (!self->ufd_uptodate)
if (update_ufd_array(self) == 0)
return NULL;
self->poll_running = 1;
/* call poll() */
async_err = 0;
do {
Py_BEGIN_ALLOW_THREADS
errno = 0;
poll_result = poll(self->ufds, self->ufd_len, (int)ms);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* poll() was interrupted by a signal */
if (PyErr_CheckSignals()) {
async_err = 1;
break;
}
if (timeout >= 0) {
timeout = _PyDeadline_Get(deadline);
if (timeout < 0) {
poll_result = 0;
break;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
/* retry poll() with the recomputed timeout */
}
} while (1);
self->poll_running = 0;
if (poll_result < 0) {
if (!async_err)
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* build the result list */
result_list = PyList_New(poll_result);
if (!result_list)
return NULL;
for (i = 0, j = 0; j < poll_result; j++) {
/* skip to the next fired descriptor */
while (!self->ufds[i].revents) {
i++;
}
/* if we hit a NULL return, set value to NULL
and break out of loop; code at end will
clean up result_list */
value = PyTuple_New(2);
if (value == NULL)
goto error;
num = PyLong_FromLong(self->ufds[i].fd);
if (num == NULL) {
Py_DECREF(value);
goto error;
}
PyTuple_SET_ITEM(value, 0, num);
/* The &0xffff is a workaround for AIX. 'revents'
is a 16-bit short, and IBM assigned POLLNVAL
to be 0x8000, so the conversion to int results
in a negative number. See SF bug #923315. */
num = PyLong_FromLong(self->ufds[i].revents & 0xffff);
if (num == NULL) {
Py_DECREF(value);
goto error;
}
PyTuple_SET_ITEM(value, 1, num);
PyList_SET_ITEM(result_list, j, value);
i++;
}
return result_list;
error:
Py_DECREF(result_list);
return NULL;
}
static pollObject *
newPollObject(PyObject *module)
{
pollObject *self;
self = PyObject_New(pollObject, get_select_state(module)->poll_Type);
if (self == NULL)
return NULL;
/* ufd_uptodate is a Boolean, denoting whether the
array pointed to by ufds matches the contents of the dictionary. */
self->ufd_uptodate = 0;
self->ufds = NULL;
self->poll_running = 0;
self->dict = PyDict_New();
if (self->dict == NULL) {
Py_DECREF(self);
return NULL;
}
return self;
}
static void
poll_dealloc(pollObject *self)
{
PyObject* type = (PyObject *)Py_TYPE(self);
if (self->ufds != NULL)
PyMem_Free(self->ufds);
Py_XDECREF(self->dict);
PyObject_Free(self);
Py_DECREF(type);
}
#ifdef HAVE_SYS_DEVPOLL_H
static PyMethodDef devpoll_methods[];
typedef struct {
PyObject_HEAD
int fd_devpoll;
int max_n_fds;
int n_fds;
struct pollfd *fds;
} devpollObject;
static PyObject *
devpoll_err_closed(void)
{
PyErr_SetString(PyExc_ValueError, "I/O operation on closed devpoll object");
return NULL;
}
static int devpoll_flush(devpollObject *self)
{
int size, n;
if (!self->n_fds) return 0;
size = sizeof(struct pollfd)*self->n_fds;
self->n_fds = 0;
n = _Py_write(self->fd_devpoll, self->fds, size);
if (n == -1)
return -1;
if (n < size) {
/*
** Data writed to /dev/poll is a binary data structure. It is not
** clear what to do if a partial write occurred. For now, raise
** an exception and see if we actually found this problem in
** the wild.
** See http://bugs.python.org/issue6397.
*/
PyErr_Format(PyExc_OSError, "failed to write all pollfds. "
"Please, report at http://bugs.python.org/. "
"Data to report: Size tried: %d, actual size written: %d.",
size, n);
return -1;
}
return 0;
}
static PyObject *
internal_devpoll_register(devpollObject *self, int fd,
unsigned short events, int remove)
{
if (self->fd_devpoll < 0)
return devpoll_err_closed();
if (remove) {
self->fds[self->n_fds].fd = fd;
self->fds[self->n_fds].events = POLLREMOVE;
if (++self->n_fds == self->max_n_fds) {
if (devpoll_flush(self))
return NULL;
}
}
self->fds[self->n_fds].fd = fd;
self->fds[self->n_fds].events = (signed short)events;
if (++self->n_fds == self->max_n_fds) {
if (devpoll_flush(self))
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
select.devpoll.register
fd: fildes
either an integer, or an object with a fileno() method returning
an int
eventmask: unsigned_short(c_default="POLLIN | POLLPRI | POLLOUT") = select.POLLIN | select.POLLPRI | select.POLLOUT
an optional bitmask describing the type of events to check for
/
Register a file descriptor with the polling object.
[clinic start generated code]*/
static PyObject *
select_devpoll_register_impl(devpollObject *self, int fd,
unsigned short eventmask)
/*[clinic end generated code: output=6e07fe8b74abba0c input=22006fabe9567522]*/
{
return internal_devpoll_register(self, fd, eventmask, 0);
}
/*[clinic input]
select.devpoll.modify
fd: fildes
either an integer, or an object with a fileno() method returning
an int
eventmask: unsigned_short(c_default="POLLIN | POLLPRI | POLLOUT") = select.POLLIN | select.POLLPRI | select.POLLOUT
an optional bitmask describing the type of events to check for
/
Modify a possible already registered file descriptor.
[clinic start generated code]*/
static PyObject *
select_devpoll_modify_impl(devpollObject *self, int fd,
unsigned short eventmask)
/*[clinic end generated code: output=bc2e6d23aaff98b4 input=09fa335db7cdc09e]*/
{
return internal_devpoll_register(self, fd, eventmask, 1);
}
/*[clinic input]
select.devpoll.unregister
fd: fildes
/
Remove a file descriptor being tracked by the polling object.
[clinic start generated code]*/
static PyObject *
select_devpoll_unregister_impl(devpollObject *self, int fd)
/*[clinic end generated code: output=95519ffa0c7d43fe input=b4ea42a4442fd467]*/
{
if (self->fd_devpoll < 0)
return devpoll_err_closed();
self->fds[self->n_fds].fd = fd;
self->fds[self->n_fds].events = POLLREMOVE;
if (++self->n_fds == self->max_n_fds) {
if (devpoll_flush(self))
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
select.devpoll.poll
timeout as timeout_obj: object = None
The maximum time to wait in milliseconds, or else None (or a negative
value) to wait indefinitely.
/
Polls the set of registered file descriptors.
Returns a list containing any descriptors that have events or errors to
report, as a list of (fd, event) 2-tuples.
[clinic start generated code]*/
static PyObject *
select_devpoll_poll_impl(devpollObject *self, PyObject *timeout_obj)
/*[clinic end generated code: output=2654e5457cca0b3c input=3c3f0a355ec2bedb]*/
{
struct dvpoll dvp;
PyObject *result_list = NULL;
int poll_result, i;
PyObject *value, *num1, *num2;
_PyTime_t timeout, ms, deadline = 0;
if (self->fd_devpoll < 0)
return devpoll_err_closed();
/* Check values for timeout */
if (timeout_obj == Py_None) {
timeout = -1;
ms = -1;
}
else {
if (_PyTime_FromMillisecondsObject(&timeout, timeout_obj,
_PyTime_ROUND_TIMEOUT) < 0) {
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_SetString(PyExc_TypeError,
"timeout must be an integer or None");
}
return NULL;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_TIMEOUT);
if (ms < -1 || ms > INT_MAX) {
PyErr_SetString(PyExc_OverflowError, "timeout is too large");
return NULL;
}
}
if (devpoll_flush(self))
return NULL;
dvp.dp_fds = self->fds;
dvp.dp_nfds = self->max_n_fds;
dvp.dp_timeout = (int)ms;
if (timeout >= 0) {
deadline = _PyDeadline_Init(timeout);
}
do {
/* call devpoll() */
Py_BEGIN_ALLOW_THREADS
errno = 0;
poll_result = ioctl(self->fd_devpoll, DP_POLL, &dvp);
Py_END_ALLOW_THREADS
if (errno != EINTR)
break;
/* devpoll() was interrupted by a signal */
if (PyErr_CheckSignals())
return NULL;
if (timeout >= 0) {
timeout = _PyDeadline_Get(deadline);
if (timeout < 0) {
poll_result = 0;
break;
}
ms = _PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
dvp.dp_timeout = (int)ms;
/* retry devpoll() with the recomputed timeout */
}
} while (1);
if (poll_result < 0) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
/* build the result list */
result_list = PyList_New(poll_result);
if (!result_list)
return NULL;