selectmodule.c 75 KB

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