signalmodule.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062
  1. /* Signal module -- many thanks to Lance Ellinghaus */
  2. /* XXX Signals should be recorded per thread, now we have thread state. */
  3. #include "Python.h"
  4. #include "pycore_atomic.h" // _Py_atomic_int
  5. #include "pycore_call.h" // _PyObject_Call()
  6. #include "pycore_ceval.h" // _PyEval_SignalReceived()
  7. #include "pycore_emscripten_signal.h" // _Py_CHECK_EMSCRIPTEN_SIGNALS
  8. #include "pycore_fileutils.h" // _Py_BEGIN_SUPPRESS_IPH
  9. #include "pycore_frame.h" // _PyInterpreterFrame
  10. #include "pycore_moduleobject.h" // _PyModule_GetState()
  11. #include "pycore_pyerrors.h" // _PyErr_SetString()
  12. #include "pycore_pystate.h" // _PyThreadState_GET()
  13. #include "pycore_signal.h" // Py_NSIG
  14. #ifndef MS_WINDOWS
  15. # include "posixmodule.h"
  16. #endif
  17. #ifdef MS_WINDOWS
  18. # include "socketmodule.h" /* needed for SOCKET_T */
  19. #endif
  20. #ifdef MS_WINDOWS
  21. # ifdef HAVE_PROCESS_H
  22. # include <process.h>
  23. # endif
  24. #endif
  25. #ifdef HAVE_SIGNAL_H
  26. # include <signal.h>
  27. #endif
  28. #ifdef HAVE_SYS_SYSCALL_H
  29. # include <sys/syscall.h>
  30. #endif
  31. #ifdef HAVE_SYS_STAT_H
  32. # include <sys/stat.h>
  33. #endif
  34. #ifdef HAVE_SYS_TIME_H
  35. # include <sys/time.h>
  36. #endif
  37. #if defined(HAVE_PTHREAD_SIGMASK) && !defined(HAVE_BROKEN_PTHREAD_SIGMASK)
  38. # define PYPTHREAD_SIGMASK
  39. #endif
  40. #if defined(PYPTHREAD_SIGMASK) && defined(HAVE_PTHREAD_H)
  41. # include <pthread.h>
  42. #endif
  43. #ifndef SIG_ERR
  44. # define SIG_ERR ((PyOS_sighandler_t)(-1))
  45. #endif
  46. #include "clinic/signalmodule.c.h"
  47. /*[clinic input]
  48. module signal
  49. [clinic start generated code]*/
  50. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b0301a3bde5fe9d3]*/
  51. #ifdef HAVE_SETSIG_T
  52. /*[python input]
  53. class sigset_t_converter(CConverter):
  54. type = 'sigset_t'
  55. converter = '_Py_Sigset_Converter'
  56. [python start generated code]*/
  57. /*[python end generated code: output=da39a3ee5e6b4b0d input=b5689d14466b6823]*/
  58. #endif
  59. /*
  60. NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS
  61. We want the following semantics:
  62. - only the main thread can set a signal handler
  63. - only the main thread runs the signal handler
  64. - signals can be delivered to any thread
  65. - any thread can get a signal handler
  66. I.e. we don't support "synchronous signals" like SIGFPE (catching
  67. this doesn't make much sense in Python anyway) nor do we support
  68. signals as a means of inter-thread communication, since not all
  69. thread implementations support that (at least our thread library
  70. doesn't).
  71. We still have the problem that in some implementations signals
  72. generated by the keyboard (e.g. SIGINT) are delivered to all
  73. threads (e.g. SGI), while in others (e.g. Solaris) such signals are
  74. delivered to one random thread. On Linux, signals are delivered to
  75. the main thread (unless the main thread is blocking the signal, for
  76. example because it's already handling the same signal). Since we
  77. allow signals to be delivered to any thread, this works fine. The
  78. only oddity is that the thread executing the Python signal handler
  79. may not be the thread that received the signal.
  80. */
  81. #define Handlers _PyRuntime.signals.handlers
  82. #define wakeup _PyRuntime.signals.wakeup
  83. #define is_tripped _PyRuntime.signals.is_tripped
  84. // State shared by all Python interpreters
  85. typedef struct _signals_runtime_state signal_state_t;
  86. #define signal_global_state _PyRuntime.signals
  87. #if defined(HAVE_GETITIMER) || defined(HAVE_SETITIMER)
  88. # define PYHAVE_ITIMER_ERROR
  89. #endif
  90. typedef struct {
  91. PyObject *default_handler; // borrowed ref (signal_global_state)
  92. PyObject *ignore_handler; // borrowed ref (signal_global_state)
  93. #ifdef PYHAVE_ITIMER_ERROR
  94. PyObject *itimer_error;
  95. #endif
  96. PyTypeObject *siginfo_type;
  97. } _signal_module_state;
  98. Py_LOCAL_INLINE(PyObject *)
  99. get_handler(int i)
  100. {
  101. return (PyObject *)_Py_atomic_load(&Handlers[i].func);
  102. }
  103. Py_LOCAL_INLINE(void)
  104. set_handler(int i, PyObject* func)
  105. {
  106. _Py_atomic_store(&Handlers[i].func, (uintptr_t)func);
  107. }
  108. static inline _signal_module_state*
  109. get_signal_state(PyObject *module)
  110. {
  111. void *state = _PyModule_GetState(module);
  112. assert(state != NULL);
  113. return (_signal_module_state *)state;
  114. }
  115. static inline int
  116. compare_handler(PyObject *func, PyObject *dfl_ign_handler)
  117. {
  118. // See https://github.com/python/cpython/pull/102399
  119. if (func == NULL || dfl_ign_handler == NULL) {
  120. return 0;
  121. }
  122. assert(PyLong_CheckExact(dfl_ign_handler));
  123. if (!PyLong_CheckExact(func)) {
  124. return 0;
  125. }
  126. // Assume that comparison of two PyLong objects will never fail.
  127. return PyObject_RichCompareBool(func, dfl_ign_handler, Py_EQ) == 1;
  128. }
  129. #ifdef HAVE_SETITIMER
  130. /* auxiliary function for setitimer */
  131. static int
  132. timeval_from_double(PyObject *obj, struct timeval *tv)
  133. {
  134. if (obj == NULL) {
  135. tv->tv_sec = 0;
  136. tv->tv_usec = 0;
  137. return 0;
  138. }
  139. _PyTime_t t;
  140. if (_PyTime_FromSecondsObject(&t, obj, _PyTime_ROUND_CEILING) < 0) {
  141. return -1;
  142. }
  143. return _PyTime_AsTimeval(t, tv, _PyTime_ROUND_CEILING);
  144. }
  145. #endif
  146. #if defined(HAVE_SETITIMER) || defined(HAVE_GETITIMER)
  147. /* auxiliary functions for get/setitimer */
  148. Py_LOCAL_INLINE(double)
  149. double_from_timeval(struct timeval *tv)
  150. {
  151. return tv->tv_sec + (double)(tv->tv_usec / 1000000.0);
  152. }
  153. static PyObject *
  154. itimer_retval(struct itimerval *iv)
  155. {
  156. PyObject *r, *v;
  157. r = PyTuple_New(2);
  158. if (r == NULL)
  159. return NULL;
  160. if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
  161. Py_DECREF(r);
  162. return NULL;
  163. }
  164. PyTuple_SET_ITEM(r, 0, v);
  165. if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
  166. Py_DECREF(r);
  167. return NULL;
  168. }
  169. PyTuple_SET_ITEM(r, 1, v);
  170. return r;
  171. }
  172. #endif
  173. /*[clinic input]
  174. signal.default_int_handler
  175. signalnum: int
  176. frame: object
  177. /
  178. The default handler for SIGINT installed by Python.
  179. It raises KeyboardInterrupt.
  180. [clinic start generated code]*/
  181. static PyObject *
  182. signal_default_int_handler_impl(PyObject *module, int signalnum,
  183. PyObject *frame)
  184. /*[clinic end generated code: output=bb11c2eb115ace4e input=efcd4a56a207acfd]*/
  185. {
  186. PyErr_SetNone(PyExc_KeyboardInterrupt);
  187. return NULL;
  188. }
  189. static int
  190. report_wakeup_write_error(void *data)
  191. {
  192. int save_errno = errno;
  193. errno = (int) (intptr_t) data;
  194. PyObject *exc = PyErr_GetRaisedException();
  195. PyErr_SetFromErrno(PyExc_OSError);
  196. _PyErr_WriteUnraisableMsg("when trying to write to the signal wakeup fd",
  197. NULL);
  198. PyErr_SetRaisedException(exc);
  199. errno = save_errno;
  200. return 0;
  201. }
  202. #ifdef MS_WINDOWS
  203. static int
  204. report_wakeup_send_error(void* data)
  205. {
  206. int send_errno = (int) (intptr_t) data;
  207. PyObject *exc = PyErr_GetRaisedException();
  208. /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
  209. recognizes the error codes used by both GetLastError() and
  210. WSAGetLastError */
  211. PyErr_SetExcFromWindowsErr(PyExc_OSError, send_errno);
  212. _PyErr_WriteUnraisableMsg("when trying to send to the signal wakeup fd", NULL);
  213. PyErr_SetRaisedException(exc);
  214. return 0;
  215. }
  216. #endif /* MS_WINDOWS */
  217. static void
  218. trip_signal(int sig_num)
  219. {
  220. _Py_atomic_store_relaxed(&Handlers[sig_num].tripped, 1);
  221. /* Set is_tripped after setting .tripped, as it gets
  222. cleared in PyErr_CheckSignals() before .tripped. */
  223. _Py_atomic_store(&is_tripped, 1);
  224. /* Signals are always handled by the main interpreter */
  225. PyInterpreterState *interp = _PyInterpreterState_Main();
  226. /* Notify ceval.c */
  227. _PyEval_SignalReceived(interp);
  228. /* And then write to the wakeup fd *after* setting all the globals and
  229. doing the _PyEval_SignalReceived. We used to write to the wakeup fd
  230. and then set the flag, but this allowed the following sequence of events
  231. (especially on windows, where trip_signal may run in a new thread):
  232. - main thread blocks on select([wakeup.fd], ...)
  233. - signal arrives
  234. - trip_signal writes to the wakeup fd
  235. - the main thread wakes up
  236. - the main thread checks the signal flags, sees that they're unset
  237. - the main thread empties the wakeup fd
  238. - the main thread goes back to sleep
  239. - trip_signal sets the flags to request the Python-level signal handler
  240. be run
  241. - the main thread doesn't notice, because it's asleep
  242. See bpo-30038 for more details.
  243. */
  244. int fd = wakeup.fd;
  245. if (fd != INVALID_FD) {
  246. unsigned char byte = (unsigned char)sig_num;
  247. #ifdef MS_WINDOWS
  248. if (wakeup.use_send) {
  249. Py_ssize_t rc = send(fd, &byte, 1, 0);
  250. if (rc < 0) {
  251. int last_error = GetLastError();
  252. if (wakeup.warn_on_full_buffer ||
  253. last_error != WSAEWOULDBLOCK)
  254. {
  255. /* _PyEval_AddPendingCall() isn't signal-safe, but we
  256. still use it for this exceptional case. */
  257. _PyEval_AddPendingCall(interp,
  258. report_wakeup_send_error,
  259. (void *)(intptr_t) last_error,
  260. 1);
  261. }
  262. }
  263. }
  264. else
  265. #endif
  266. {
  267. /* _Py_write_noraise() retries write() if write() is interrupted by
  268. a signal (fails with EINTR). */
  269. Py_ssize_t rc = _Py_write_noraise(fd, &byte, 1);
  270. if (rc < 0) {
  271. if (wakeup.warn_on_full_buffer ||
  272. (errno != EWOULDBLOCK && errno != EAGAIN))
  273. {
  274. /* _PyEval_AddPendingCall() isn't signal-safe, but we
  275. still use it for this exceptional case. */
  276. _PyEval_AddPendingCall(interp,
  277. report_wakeup_write_error,
  278. (void *)(intptr_t)errno,
  279. 1);
  280. }
  281. }
  282. }
  283. }
  284. }
  285. static void
  286. signal_handler(int sig_num)
  287. {
  288. int save_errno = errno;
  289. trip_signal(sig_num);
  290. #ifndef HAVE_SIGACTION
  291. #ifdef SIGCHLD
  292. /* To avoid infinite recursion, this signal remains
  293. reset until explicit re-instated.
  294. Don't clear the 'func' field as it is our pointer
  295. to the Python handler... */
  296. if (sig_num != SIGCHLD)
  297. #endif
  298. /* If the handler was not set up with sigaction, reinstall it. See
  299. * Python/pylifecycle.c for the implementation of PyOS_setsig which
  300. * makes this true. See also issue8354. */
  301. PyOS_setsig(sig_num, signal_handler);
  302. #endif
  303. /* Issue #10311: asynchronously executing signal handlers should not
  304. mutate errno under the feet of unsuspecting C code. */
  305. errno = save_errno;
  306. #ifdef MS_WINDOWS
  307. if (sig_num == SIGINT) {
  308. signal_state_t *state = &signal_global_state;
  309. SetEvent((HANDLE)state->sigint_event);
  310. }
  311. #endif
  312. }
  313. #ifdef HAVE_ALARM
  314. /*[clinic input]
  315. signal.alarm -> long
  316. seconds: int
  317. /
  318. Arrange for SIGALRM to arrive after the given number of seconds.
  319. [clinic start generated code]*/
  320. static long
  321. signal_alarm_impl(PyObject *module, int seconds)
  322. /*[clinic end generated code: output=144232290814c298 input=0d5e97e0e6f39e86]*/
  323. {
  324. /* alarm() returns the number of seconds remaining */
  325. return (long)alarm(seconds);
  326. }
  327. #endif
  328. #ifdef HAVE_PAUSE
  329. /*[clinic input]
  330. signal.pause
  331. Wait until a signal arrives.
  332. [clinic start generated code]*/
  333. static PyObject *
  334. signal_pause_impl(PyObject *module)
  335. /*[clinic end generated code: output=391656788b3c3929 input=f03de0f875752062]*/
  336. {
  337. Py_BEGIN_ALLOW_THREADS
  338. (void)pause();
  339. Py_END_ALLOW_THREADS
  340. /* make sure that any exceptions that got raised are propagated
  341. * back into Python
  342. */
  343. if (PyErr_CheckSignals())
  344. return NULL;
  345. Py_RETURN_NONE;
  346. }
  347. #endif
  348. /*[clinic input]
  349. signal.raise_signal
  350. signalnum: int
  351. /
  352. Send a signal to the executing process.
  353. [clinic start generated code]*/
  354. static PyObject *
  355. signal_raise_signal_impl(PyObject *module, int signalnum)
  356. /*[clinic end generated code: output=e2b014220aa6111d input=e90c0f9a42358de6]*/
  357. {
  358. int err;
  359. Py_BEGIN_ALLOW_THREADS
  360. _Py_BEGIN_SUPPRESS_IPH
  361. err = raise(signalnum);
  362. _Py_END_SUPPRESS_IPH
  363. Py_END_ALLOW_THREADS
  364. if (err) {
  365. return PyErr_SetFromErrno(PyExc_OSError);
  366. }
  367. // If the current thread can handle signals, handle immediately
  368. // the raised signal.
  369. if (PyErr_CheckSignals()) {
  370. return NULL;
  371. }
  372. Py_RETURN_NONE;
  373. }
  374. /*[clinic input]
  375. signal.signal
  376. signalnum: int
  377. handler: object
  378. /
  379. Set the action for the given signal.
  380. The action can be SIG_DFL, SIG_IGN, or a callable Python object.
  381. The previous action is returned. See getsignal() for possible return values.
  382. *** IMPORTANT NOTICE ***
  383. A signal handler function is called with two arguments:
  384. the first is the signal number, the second is the interrupted stack frame.
  385. [clinic start generated code]*/
  386. static PyObject *
  387. signal_signal_impl(PyObject *module, int signalnum, PyObject *handler)
  388. /*[clinic end generated code: output=b44cfda43780f3a1 input=deee84af5fa0432c]*/
  389. {
  390. _signal_module_state *modstate = get_signal_state(module);
  391. PyObject *old_handler;
  392. void (*func)(int);
  393. #ifdef MS_WINDOWS
  394. /* Validate that signalnum is one of the allowable signals */
  395. switch (signalnum) {
  396. case SIGABRT: break;
  397. #ifdef SIGBREAK
  398. /* Issue #10003: SIGBREAK is not documented as permitted, but works
  399. and corresponds to CTRL_BREAK_EVENT. */
  400. case SIGBREAK: break;
  401. #endif
  402. case SIGFPE: break;
  403. case SIGILL: break;
  404. case SIGINT: break;
  405. case SIGSEGV: break;
  406. case SIGTERM: break;
  407. default:
  408. PyErr_SetString(PyExc_ValueError, "invalid signal value");
  409. return NULL;
  410. }
  411. #endif
  412. PyThreadState *tstate = _PyThreadState_GET();
  413. if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
  414. _PyErr_SetString(tstate, PyExc_ValueError,
  415. "signal only works in main thread "
  416. "of the main interpreter");
  417. return NULL;
  418. }
  419. if (signalnum < 1 || signalnum >= Py_NSIG) {
  420. _PyErr_SetString(tstate, PyExc_ValueError,
  421. "signal number out of range");
  422. return NULL;
  423. }
  424. if (PyCallable_Check(handler)) {
  425. func = signal_handler;
  426. } else if (compare_handler(handler, modstate->ignore_handler)) {
  427. func = SIG_IGN;
  428. } else if (compare_handler(handler, modstate->default_handler)) {
  429. func = SIG_DFL;
  430. } else {
  431. _PyErr_SetString(tstate, PyExc_TypeError,
  432. "signal handler must be signal.SIG_IGN, "
  433. "signal.SIG_DFL, or a callable object");
  434. return NULL;
  435. }
  436. /* Check for pending signals before changing signal handler */
  437. if (_PyErr_CheckSignalsTstate(tstate)) {
  438. return NULL;
  439. }
  440. if (PyOS_setsig(signalnum, func) == SIG_ERR) {
  441. PyErr_SetFromErrno(PyExc_OSError);
  442. return NULL;
  443. }
  444. old_handler = get_handler(signalnum);
  445. set_handler(signalnum, Py_NewRef(handler));
  446. if (old_handler != NULL) {
  447. return old_handler;
  448. }
  449. else {
  450. Py_RETURN_NONE;
  451. }
  452. }
  453. /*[clinic input]
  454. signal.getsignal
  455. signalnum: int
  456. /
  457. Return the current action for the given signal.
  458. The return value can be:
  459. SIG_IGN -- if the signal is being ignored
  460. SIG_DFL -- if the default action for the signal is in effect
  461. None -- if an unknown handler is in effect
  462. anything else -- the callable Python object used as a handler
  463. [clinic start generated code]*/
  464. static PyObject *
  465. signal_getsignal_impl(PyObject *module, int signalnum)
  466. /*[clinic end generated code: output=35b3e0e796fd555e input=ac23a00f19dfa509]*/
  467. {
  468. PyObject *old_handler;
  469. if (signalnum < 1 || signalnum >= Py_NSIG) {
  470. PyErr_SetString(PyExc_ValueError,
  471. "signal number out of range");
  472. return NULL;
  473. }
  474. old_handler = get_handler(signalnum);
  475. if (old_handler != NULL) {
  476. return Py_NewRef(old_handler);
  477. }
  478. else {
  479. Py_RETURN_NONE;
  480. }
  481. }
  482. /*[clinic input]
  483. signal.strsignal
  484. signalnum: int
  485. /
  486. Return the system description of the given signal.
  487. Returns the description of signal *signalnum*, such as "Interrupt"
  488. for :const:`SIGINT`. Returns :const:`None` if *signalnum* has no
  489. description. Raises :exc:`ValueError` if *signalnum* is invalid.
  490. [clinic start generated code]*/
  491. static PyObject *
  492. signal_strsignal_impl(PyObject *module, int signalnum)
  493. /*[clinic end generated code: output=44e12e1e3b666261 input=238b335847778bc0]*/
  494. {
  495. const char *res;
  496. if (signalnum < 1 || signalnum >= Py_NSIG) {
  497. PyErr_SetString(PyExc_ValueError,
  498. "signal number out of range");
  499. return NULL;
  500. }
  501. #ifndef HAVE_STRSIGNAL
  502. switch (signalnum) {
  503. /* Though being a UNIX, HP-UX does not provide strsignal(3). */
  504. #ifndef MS_WINDOWS
  505. case SIGHUP:
  506. res = "Hangup";
  507. break;
  508. case SIGALRM:
  509. res = "Alarm clock";
  510. break;
  511. case SIGPIPE:
  512. res = "Broken pipe";
  513. break;
  514. case SIGQUIT:
  515. res = "Quit";
  516. break;
  517. case SIGCHLD:
  518. res = "Child exited";
  519. break;
  520. #endif
  521. /* Custom redefinition of POSIX signals allowed on Windows. */
  522. case SIGINT:
  523. res = "Interrupt";
  524. break;
  525. case SIGILL:
  526. res = "Illegal instruction";
  527. break;
  528. case SIGABRT:
  529. res = "Aborted";
  530. break;
  531. case SIGFPE:
  532. res = "Floating-point exception";
  533. break;
  534. case SIGSEGV:
  535. res = "Segmentation fault";
  536. break;
  537. case SIGTERM:
  538. res = "Terminated";
  539. break;
  540. default:
  541. Py_RETURN_NONE;
  542. }
  543. #else
  544. errno = 0;
  545. res = strsignal(signalnum);
  546. if (errno || res == NULL || strstr(res, "Unknown signal") != NULL)
  547. Py_RETURN_NONE;
  548. #endif
  549. return Py_BuildValue("s", res);
  550. }
  551. #ifdef HAVE_SIGINTERRUPT
  552. /*[clinic input]
  553. signal.siginterrupt
  554. signalnum: int
  555. flag: int
  556. /
  557. Change system call restart behaviour.
  558. If flag is False, system calls will be restarted when interrupted by
  559. signal sig, else system calls will be interrupted.
  560. [clinic start generated code]*/
  561. static PyObject *
  562. signal_siginterrupt_impl(PyObject *module, int signalnum, int flag)
  563. /*[clinic end generated code: output=063816243d85dd19 input=4160acacca3e2099]*/
  564. {
  565. if (signalnum < 1 || signalnum >= Py_NSIG) {
  566. PyErr_SetString(PyExc_ValueError,
  567. "signal number out of range");
  568. return NULL;
  569. }
  570. #ifdef HAVE_SIGACTION
  571. struct sigaction act;
  572. (void) sigaction(signalnum, NULL, &act);
  573. if (flag) {
  574. act.sa_flags &= ~SA_RESTART;
  575. }
  576. else {
  577. act.sa_flags |= SA_RESTART;
  578. }
  579. if (sigaction(signalnum, &act, NULL) < 0) {
  580. #else
  581. if (siginterrupt(signalnum, flag) < 0) {
  582. #endif
  583. PyErr_SetFromErrno(PyExc_OSError);
  584. return NULL;
  585. }
  586. Py_RETURN_NONE;
  587. }
  588. #endif
  589. static PyObject*
  590. signal_set_wakeup_fd(PyObject *self, PyObject *args, PyObject *kwds)
  591. {
  592. struct _Py_stat_struct status;
  593. static char *kwlist[] = {
  594. "", "warn_on_full_buffer", NULL,
  595. };
  596. int warn_on_full_buffer = 1;
  597. #ifdef MS_WINDOWS
  598. PyObject *fdobj;
  599. SOCKET_T sockfd, old_sockfd;
  600. int res;
  601. int res_size = sizeof res;
  602. PyObject *mod;
  603. int is_socket;
  604. if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|$p:set_wakeup_fd", kwlist,
  605. &fdobj, &warn_on_full_buffer))
  606. return NULL;
  607. sockfd = PyLong_AsSocket_t(fdobj);
  608. if (sockfd == (SOCKET_T)(-1) && PyErr_Occurred())
  609. return NULL;
  610. #else
  611. int fd;
  612. if (!PyArg_ParseTupleAndKeywords(args, kwds, "i|$p:set_wakeup_fd", kwlist,
  613. &fd, &warn_on_full_buffer))
  614. return NULL;
  615. #endif
  616. PyThreadState *tstate = _PyThreadState_GET();
  617. if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
  618. _PyErr_SetString(tstate, PyExc_ValueError,
  619. "set_wakeup_fd only works in main thread "
  620. "of the main interpreter");
  621. return NULL;
  622. }
  623. #ifdef MS_WINDOWS
  624. is_socket = 0;
  625. if (sockfd != INVALID_FD) {
  626. /* Import the _socket module to call WSAStartup() */
  627. mod = PyImport_ImportModule("_socket");
  628. if (mod == NULL)
  629. return NULL;
  630. Py_DECREF(mod);
  631. /* test the socket */
  632. if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR,
  633. (char *)&res, &res_size) != 0) {
  634. int fd, err;
  635. err = WSAGetLastError();
  636. if (err != WSAENOTSOCK) {
  637. PyErr_SetExcFromWindowsErr(PyExc_OSError, err);
  638. return NULL;
  639. }
  640. fd = (int)sockfd;
  641. if ((SOCKET_T)fd != sockfd) {
  642. _PyErr_SetString(tstate, PyExc_ValueError, "invalid fd");
  643. return NULL;
  644. }
  645. if (_Py_fstat(fd, &status) != 0) {
  646. return NULL;
  647. }
  648. /* on Windows, a file cannot be set to non-blocking mode */
  649. }
  650. else {
  651. is_socket = 1;
  652. /* Windows does not provide a function to test if a socket
  653. is in non-blocking mode */
  654. }
  655. }
  656. old_sockfd = wakeup.fd;
  657. wakeup.fd = Py_SAFE_DOWNCAST(sockfd, SOCKET_T, int);
  658. wakeup.warn_on_full_buffer = warn_on_full_buffer;
  659. wakeup.use_send = is_socket;
  660. if (old_sockfd != INVALID_FD)
  661. return PyLong_FromSocket_t(old_sockfd);
  662. else
  663. return PyLong_FromLong(-1);
  664. #else
  665. if (fd != -1) {
  666. int blocking;
  667. if (_Py_fstat(fd, &status) != 0)
  668. return NULL;
  669. blocking = _Py_get_blocking(fd);
  670. if (blocking < 0)
  671. return NULL;
  672. if (blocking) {
  673. _PyErr_Format(tstate, PyExc_ValueError,
  674. "the fd %i must be in non-blocking mode",
  675. fd);
  676. return NULL;
  677. }
  678. }
  679. int old_fd = wakeup.fd;
  680. wakeup.fd = fd;
  681. wakeup.warn_on_full_buffer = warn_on_full_buffer;
  682. return PyLong_FromLong(old_fd);
  683. #endif
  684. }
  685. PyDoc_STRVAR(set_wakeup_fd_doc,
  686. "set_wakeup_fd(fd, *, warn_on_full_buffer=True) -> fd\n\
  687. \n\
  688. Sets the fd to be written to (with the signal number) when a signal\n\
  689. comes in. A library can use this to wakeup select or poll.\n\
  690. The previous fd or -1 is returned.\n\
  691. \n\
  692. The fd must be non-blocking.");
  693. /* C API for the same, without all the error checking */
  694. int
  695. PySignal_SetWakeupFd(int fd)
  696. {
  697. if (fd < 0) {
  698. fd = -1;
  699. }
  700. int old_fd = wakeup.fd;
  701. wakeup.fd = fd;
  702. wakeup.warn_on_full_buffer = 1;
  703. return old_fd;
  704. }
  705. #ifdef HAVE_SETITIMER
  706. /*[clinic input]
  707. signal.setitimer
  708. which: int
  709. seconds: object
  710. interval: object(c_default="NULL") = 0.0
  711. /
  712. Sets given itimer (one of ITIMER_REAL, ITIMER_VIRTUAL or ITIMER_PROF).
  713. The timer will fire after value seconds and after that every interval seconds.
  714. The itimer can be cleared by setting seconds to zero.
  715. Returns old values as a tuple: (delay, interval).
  716. [clinic start generated code]*/
  717. static PyObject *
  718. signal_setitimer_impl(PyObject *module, int which, PyObject *seconds,
  719. PyObject *interval)
  720. /*[clinic end generated code: output=65f9dcbddc35527b input=de43daf194e6f66f]*/
  721. {
  722. _signal_module_state *modstate = get_signal_state(module);
  723. struct itimerval new;
  724. if (timeval_from_double(seconds, &new.it_value) < 0) {
  725. return NULL;
  726. }
  727. if (timeval_from_double(interval, &new.it_interval) < 0) {
  728. return NULL;
  729. }
  730. /* Let OS check "which" value */
  731. struct itimerval old;
  732. if (setitimer(which, &new, &old) != 0) {
  733. PyErr_SetFromErrno(modstate->itimer_error);
  734. return NULL;
  735. }
  736. return itimer_retval(&old);
  737. }
  738. #endif // HAVE_SETITIMER
  739. #ifdef HAVE_GETITIMER
  740. /*[clinic input]
  741. signal.getitimer
  742. which: int
  743. /
  744. Returns current value of given itimer.
  745. [clinic start generated code]*/
  746. static PyObject *
  747. signal_getitimer_impl(PyObject *module, int which)
  748. /*[clinic end generated code: output=9e053175d517db40 input=f7d21d38f3490627]*/
  749. {
  750. _signal_module_state *modstate = get_signal_state(module);
  751. struct itimerval old;
  752. if (getitimer(which, &old) != 0) {
  753. PyErr_SetFromErrno(modstate->itimer_error);
  754. return NULL;
  755. }
  756. return itimer_retval(&old);
  757. }
  758. #endif // HAVE_GETITIMER
  759. #ifdef HAVE_SIGSET_T
  760. #if defined(PYPTHREAD_SIGMASK) || defined(HAVE_SIGPENDING)
  761. static PyObject*
  762. sigset_to_set(sigset_t mask)
  763. {
  764. PyObject *signum, *result;
  765. int sig;
  766. result = PySet_New(0);
  767. if (result == NULL)
  768. return NULL;
  769. for (sig = 1; sig < Py_NSIG; sig++) {
  770. if (sigismember(&mask, sig) != 1)
  771. continue;
  772. /* Handle the case where it is a member by adding the signal to
  773. the result list. Ignore the other cases because they mean the
  774. signal isn't a member of the mask or the signal was invalid,
  775. and an invalid signal must have been our fault in constructing
  776. the loop boundaries. */
  777. signum = PyLong_FromLong(sig);
  778. if (signum == NULL) {
  779. Py_DECREF(result);
  780. return NULL;
  781. }
  782. if (PySet_Add(result, signum) == -1) {
  783. Py_DECREF(signum);
  784. Py_DECREF(result);
  785. return NULL;
  786. }
  787. Py_DECREF(signum);
  788. }
  789. return result;
  790. }
  791. #endif
  792. #ifdef PYPTHREAD_SIGMASK
  793. /*[clinic input]
  794. signal.pthread_sigmask
  795. how: int
  796. mask: sigset_t
  797. /
  798. Fetch and/or change the signal mask of the calling thread.
  799. [clinic start generated code]*/
  800. static PyObject *
  801. signal_pthread_sigmask_impl(PyObject *module, int how, sigset_t mask)
  802. /*[clinic end generated code: output=0562c0fb192981a8 input=85bcebda442fa77f]*/
  803. {
  804. sigset_t previous;
  805. int err;
  806. err = pthread_sigmask(how, &mask, &previous);
  807. if (err != 0) {
  808. errno = err;
  809. PyErr_SetFromErrno(PyExc_OSError);
  810. return NULL;
  811. }
  812. /* if signals was unblocked, signal handlers have been called */
  813. if (PyErr_CheckSignals())
  814. return NULL;
  815. return sigset_to_set(previous);
  816. }
  817. #endif /* #ifdef PYPTHREAD_SIGMASK */
  818. #ifdef HAVE_SIGPENDING
  819. /*[clinic input]
  820. signal.sigpending
  821. Examine pending signals.
  822. Returns a set of signal numbers that are pending for delivery to
  823. the calling thread.
  824. [clinic start generated code]*/
  825. static PyObject *
  826. signal_sigpending_impl(PyObject *module)
  827. /*[clinic end generated code: output=53375ffe89325022 input=e0036c016f874e29]*/
  828. {
  829. int err;
  830. sigset_t mask;
  831. err = sigpending(&mask);
  832. if (err)
  833. return PyErr_SetFromErrno(PyExc_OSError);
  834. return sigset_to_set(mask);
  835. }
  836. #endif /* #ifdef HAVE_SIGPENDING */
  837. #ifdef HAVE_SIGWAIT
  838. /*[clinic input]
  839. signal.sigwait
  840. sigset: sigset_t
  841. /
  842. Wait for a signal.
  843. Suspend execution of the calling thread until the delivery of one of the
  844. signals specified in the signal set sigset. The function accepts the signal
  845. and returns the signal number.
  846. [clinic start generated code]*/
  847. static PyObject *
  848. signal_sigwait_impl(PyObject *module, sigset_t sigset)
  849. /*[clinic end generated code: output=f43770699d682f96 input=a6fbd47b1086d119]*/
  850. {
  851. int err, signum;
  852. Py_BEGIN_ALLOW_THREADS
  853. err = sigwait(&sigset, &signum);
  854. Py_END_ALLOW_THREADS
  855. if (err) {
  856. errno = err;
  857. return PyErr_SetFromErrno(PyExc_OSError);
  858. }
  859. return PyLong_FromLong(signum);
  860. }
  861. #endif /* #ifdef HAVE_SIGWAIT */
  862. #endif /* #ifdef HAVE_SIGSET_T */
  863. #if (defined(HAVE_SIGFILLSET) && defined(HAVE_SIGSET_T)) || defined(MS_WINDOWS)
  864. /*[clinic input]
  865. signal.valid_signals
  866. Return a set of valid signal numbers on this platform.
  867. The signal numbers returned by this function can be safely passed to
  868. functions like `pthread_sigmask`.
  869. [clinic start generated code]*/
  870. static PyObject *
  871. signal_valid_signals_impl(PyObject *module)
  872. /*[clinic end generated code: output=1609cffbcfcf1314 input=86a3717ff25288f2]*/
  873. {
  874. #ifdef MS_WINDOWS
  875. #ifdef SIGBREAK
  876. PyObject *tup = Py_BuildValue("(iiiiiii)", SIGABRT, SIGBREAK, SIGFPE,
  877. SIGILL, SIGINT, SIGSEGV, SIGTERM);
  878. #else
  879. PyObject *tup = Py_BuildValue("(iiiiii)", SIGABRT, SIGFPE, SIGILL,
  880. SIGINT, SIGSEGV, SIGTERM);
  881. #endif
  882. if (tup == NULL) {
  883. return NULL;
  884. }
  885. PyObject *set = PySet_New(tup);
  886. Py_DECREF(tup);
  887. return set;
  888. #else
  889. sigset_t mask;
  890. if (sigemptyset(&mask) || sigfillset(&mask)) {
  891. return PyErr_SetFromErrno(PyExc_OSError);
  892. }
  893. return sigset_to_set(mask);
  894. #endif
  895. }
  896. #endif /* #if (defined(HAVE_SIGFILLSET) && defined(HAVE_SIGSET_T)) || defined(MS_WINDOWS) */
  897. #if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
  898. static PyStructSequence_Field struct_siginfo_fields[] = {
  899. {"si_signo", "signal number"},
  900. {"si_code", "signal code"},
  901. {"si_errno", "errno associated with this signal"},
  902. {"si_pid", "sending process ID"},
  903. {"si_uid", "real user ID of sending process"},
  904. {"si_status", "exit value or signal"},
  905. {"si_band", "band event for SIGPOLL"},
  906. {0}
  907. };
  908. PyDoc_STRVAR(struct_siginfo__doc__,
  909. "struct_siginfo: Result from sigwaitinfo or sigtimedwait.\n\n\
  910. This object may be accessed either as a tuple of\n\
  911. (si_signo, si_code, si_errno, si_pid, si_uid, si_status, si_band),\n\
  912. or via the attributes si_signo, si_code, and so on.");
  913. static PyStructSequence_Desc struct_siginfo_desc = {
  914. "signal.struct_siginfo", /* name */
  915. struct_siginfo__doc__, /* doc */
  916. struct_siginfo_fields, /* fields */
  917. 7 /* n_in_sequence */
  918. };
  919. static PyObject *
  920. fill_siginfo(_signal_module_state *state, siginfo_t *si)
  921. {
  922. PyObject *result = PyStructSequence_New(state->siginfo_type);
  923. if (!result)
  924. return NULL;
  925. PyStructSequence_SET_ITEM(result, 0, PyLong_FromLong((long)(si->si_signo)));
  926. PyStructSequence_SET_ITEM(result, 1, PyLong_FromLong((long)(si->si_code)));
  927. #ifdef __VXWORKS__
  928. PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong(0L));
  929. PyStructSequence_SET_ITEM(result, 3, PyLong_FromLong(0L));
  930. PyStructSequence_SET_ITEM(result, 4, PyLong_FromLong(0L));
  931. PyStructSequence_SET_ITEM(result, 5, PyLong_FromLong(0L));
  932. #else
  933. PyStructSequence_SET_ITEM(result, 2, PyLong_FromLong((long)(si->si_errno)));
  934. PyStructSequence_SET_ITEM(result, 3, PyLong_FromPid(si->si_pid));
  935. PyStructSequence_SET_ITEM(result, 4, _PyLong_FromUid(si->si_uid));
  936. PyStructSequence_SET_ITEM(result, 5,
  937. PyLong_FromLong((long)(si->si_status)));
  938. #endif
  939. #ifdef HAVE_SIGINFO_T_SI_BAND
  940. PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(si->si_band));
  941. #else
  942. PyStructSequence_SET_ITEM(result, 6, PyLong_FromLong(0L));
  943. #endif
  944. if (PyErr_Occurred()) {
  945. Py_DECREF(result);
  946. return NULL;
  947. }
  948. return result;
  949. }
  950. #endif
  951. #ifdef HAVE_SIGSET_T
  952. #ifdef HAVE_SIGWAITINFO
  953. /*[clinic input]
  954. signal.sigwaitinfo
  955. sigset: sigset_t
  956. /
  957. Wait synchronously until one of the signals in *sigset* is delivered.
  958. Returns a struct_siginfo containing information about the signal.
  959. [clinic start generated code]*/
  960. static PyObject *
  961. signal_sigwaitinfo_impl(PyObject *module, sigset_t sigset)
  962. /*[clinic end generated code: output=1eb2f1fa236fdbca input=3d1a7e1f27fc664c]*/
  963. {
  964. siginfo_t si;
  965. int err;
  966. int async_err = 0;
  967. do {
  968. Py_BEGIN_ALLOW_THREADS
  969. err = sigwaitinfo(&sigset, &si);
  970. Py_END_ALLOW_THREADS
  971. } while (err == -1
  972. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  973. if (err == -1)
  974. return (!async_err) ? PyErr_SetFromErrno(PyExc_OSError) : NULL;
  975. _signal_module_state *state = get_signal_state(module);
  976. return fill_siginfo(state, &si);
  977. }
  978. #endif /* #ifdef HAVE_SIGWAITINFO */
  979. #ifdef HAVE_SIGTIMEDWAIT
  980. /*[clinic input]
  981. signal.sigtimedwait
  982. sigset: sigset_t
  983. timeout as timeout_obj: object
  984. /
  985. Like sigwaitinfo(), but with a timeout.
  986. The timeout is specified in seconds, with floating-point numbers allowed.
  987. [clinic start generated code]*/
  988. static PyObject *
  989. signal_sigtimedwait_impl(PyObject *module, sigset_t sigset,
  990. PyObject *timeout_obj)
  991. /*[clinic end generated code: output=59c8971e8ae18a64 input=955773219c1596cd]*/
  992. {
  993. _PyTime_t timeout;
  994. if (_PyTime_FromSecondsObject(&timeout,
  995. timeout_obj, _PyTime_ROUND_CEILING) < 0)
  996. return NULL;
  997. if (timeout < 0) {
  998. PyErr_SetString(PyExc_ValueError, "timeout must be non-negative");
  999. return NULL;
  1000. }
  1001. _PyTime_t deadline = _PyDeadline_Init(timeout);
  1002. siginfo_t si;
  1003. do {
  1004. struct timespec ts;
  1005. if (_PyTime_AsTimespec(timeout, &ts) < 0) {
  1006. return NULL;
  1007. }
  1008. int res;
  1009. Py_BEGIN_ALLOW_THREADS
  1010. res = sigtimedwait(&sigset, &si, &ts);
  1011. Py_END_ALLOW_THREADS
  1012. if (res != -1)
  1013. break;
  1014. if (errno != EINTR) {
  1015. if (errno == EAGAIN)
  1016. Py_RETURN_NONE;
  1017. else
  1018. return PyErr_SetFromErrno(PyExc_OSError);
  1019. }
  1020. /* sigtimedwait() was interrupted by a signal (EINTR) */
  1021. if (PyErr_CheckSignals())
  1022. return NULL;
  1023. timeout = _PyDeadline_Get(deadline);
  1024. if (timeout < 0) {
  1025. break;
  1026. }
  1027. } while (1);
  1028. _signal_module_state *state = get_signal_state(module);
  1029. return fill_siginfo(state, &si);
  1030. }
  1031. #endif /* #ifdef HAVE_SIGTIMEDWAIT */
  1032. #endif /* #ifdef HAVE_SIGSET_T */
  1033. #if defined(HAVE_PTHREAD_KILL)
  1034. /*[clinic input]
  1035. signal.pthread_kill
  1036. thread_id: unsigned_long(bitwise=True)
  1037. signalnum: int
  1038. /
  1039. Send a signal to a thread.
  1040. [clinic start generated code]*/
  1041. static PyObject *
  1042. signal_pthread_kill_impl(PyObject *module, unsigned long thread_id,
  1043. int signalnum)
  1044. /*[clinic end generated code: output=7629919b791bc27f input=1d901f2c7bb544ff]*/
  1045. {
  1046. int err;
  1047. if (PySys_Audit("signal.pthread_kill", "ki", thread_id, signalnum) < 0) {
  1048. return NULL;
  1049. }
  1050. err = pthread_kill((pthread_t)thread_id, signalnum);
  1051. if (err != 0) {
  1052. errno = err;
  1053. PyErr_SetFromErrno(PyExc_OSError);
  1054. return NULL;
  1055. }
  1056. /* the signal may have been send to the current thread */
  1057. if (PyErr_CheckSignals())
  1058. return NULL;
  1059. Py_RETURN_NONE;
  1060. }
  1061. #endif /* #if defined(HAVE_PTHREAD_KILL) */
  1062. #if defined(__linux__) && defined(__NR_pidfd_send_signal)
  1063. /*[clinic input]
  1064. signal.pidfd_send_signal
  1065. pidfd: int
  1066. signalnum: int
  1067. siginfo: object = None
  1068. flags: int = 0
  1069. /
  1070. Send a signal to a process referred to by a pid file descriptor.
  1071. [clinic start generated code]*/
  1072. static PyObject *
  1073. signal_pidfd_send_signal_impl(PyObject *module, int pidfd, int signalnum,
  1074. PyObject *siginfo, int flags)
  1075. /*[clinic end generated code: output=2d59f04a75d9cbdf input=2a6543a1f4ac2000]*/
  1076. {
  1077. if (siginfo != Py_None) {
  1078. PyErr_SetString(PyExc_TypeError, "siginfo must be None");
  1079. return NULL;
  1080. }
  1081. if (syscall(__NR_pidfd_send_signal, pidfd, signalnum, NULL, flags) < 0) {
  1082. PyErr_SetFromErrno(PyExc_OSError);
  1083. return NULL;
  1084. }
  1085. Py_RETURN_NONE;
  1086. }
  1087. #endif
  1088. /* List of functions defined in the module -- some of the methoddefs are
  1089. defined to nothing if the corresponding C function is not available. */
  1090. static PyMethodDef signal_methods[] = {
  1091. SIGNAL_DEFAULT_INT_HANDLER_METHODDEF
  1092. SIGNAL_ALARM_METHODDEF
  1093. SIGNAL_SETITIMER_METHODDEF
  1094. SIGNAL_GETITIMER_METHODDEF
  1095. SIGNAL_SIGNAL_METHODDEF
  1096. SIGNAL_RAISE_SIGNAL_METHODDEF
  1097. SIGNAL_STRSIGNAL_METHODDEF
  1098. SIGNAL_GETSIGNAL_METHODDEF
  1099. {"set_wakeup_fd", _PyCFunction_CAST(signal_set_wakeup_fd), METH_VARARGS | METH_KEYWORDS, set_wakeup_fd_doc},
  1100. SIGNAL_SIGINTERRUPT_METHODDEF
  1101. SIGNAL_PAUSE_METHODDEF
  1102. SIGNAL_PIDFD_SEND_SIGNAL_METHODDEF
  1103. SIGNAL_PTHREAD_KILL_METHODDEF
  1104. SIGNAL_PTHREAD_SIGMASK_METHODDEF
  1105. SIGNAL_SIGPENDING_METHODDEF
  1106. SIGNAL_SIGWAIT_METHODDEF
  1107. SIGNAL_SIGWAITINFO_METHODDEF
  1108. SIGNAL_SIGTIMEDWAIT_METHODDEF
  1109. #if defined(HAVE_SIGFILLSET) || defined(MS_WINDOWS)
  1110. SIGNAL_VALID_SIGNALS_METHODDEF
  1111. #endif
  1112. {NULL, NULL} /* sentinel */
  1113. };
  1114. PyDoc_STRVAR(module_doc,
  1115. "This module provides mechanisms to use signal handlers in Python.\n\
  1116. \n\
  1117. Functions:\n\
  1118. \n\
  1119. alarm() -- cause SIGALRM after a specified time [Unix only]\n\
  1120. setitimer() -- cause a signal (described below) after a specified\n\
  1121. float time and the timer may restart then [Unix only]\n\
  1122. getitimer() -- get current value of timer [Unix only]\n\
  1123. signal() -- set the action for a given signal\n\
  1124. getsignal() -- get the signal action for a given signal\n\
  1125. pause() -- wait until a signal arrives [Unix only]\n\
  1126. default_int_handler() -- default SIGINT handler\n\
  1127. \n\
  1128. signal constants:\n\
  1129. SIG_DFL -- used to refer to the system default handler\n\
  1130. SIG_IGN -- used to ignore the signal\n\
  1131. NSIG -- number of defined signals\n\
  1132. SIGINT, SIGTERM, etc. -- signal numbers\n\
  1133. \n\
  1134. itimer constants:\n\
  1135. ITIMER_REAL -- decrements in real time, and delivers SIGALRM upon\n\
  1136. expiration\n\
  1137. ITIMER_VIRTUAL -- decrements only when the process is executing,\n\
  1138. and delivers SIGVTALRM upon expiration\n\
  1139. ITIMER_PROF -- decrements both when the process is executing and\n\
  1140. when the system is executing on behalf of the process.\n\
  1141. Coupled with ITIMER_VIRTUAL, this timer is usually\n\
  1142. used to profile the time spent by the application\n\
  1143. in user and kernel space. SIGPROF is delivered upon\n\
  1144. expiration.\n\
  1145. \n\n\
  1146. *** IMPORTANT NOTICE ***\n\
  1147. A signal handler function is called with two arguments:\n\
  1148. the first is the signal number, the second is the interrupted stack frame.");
  1149. static int
  1150. signal_add_constants(PyObject *module)
  1151. {
  1152. if (PyModule_AddIntConstant(module, "NSIG", Py_NSIG) < 0) {
  1153. return -1;
  1154. }
  1155. #define ADD_INT_MACRO(macro) \
  1156. if (PyModule_AddIntConstant(module, #macro, macro) < 0) { \
  1157. return -1; \
  1158. }
  1159. // SIG_xxx pthread_sigmask() constants
  1160. #ifdef SIG_BLOCK
  1161. ADD_INT_MACRO(SIG_BLOCK);
  1162. #endif
  1163. #ifdef SIG_UNBLOCK
  1164. ADD_INT_MACRO(SIG_UNBLOCK);
  1165. #endif
  1166. #ifdef SIG_SETMASK
  1167. ADD_INT_MACRO(SIG_SETMASK);
  1168. #endif
  1169. // SIGxxx signal number constants
  1170. #ifdef SIGHUP
  1171. ADD_INT_MACRO(SIGHUP);
  1172. #endif
  1173. #ifdef SIGINT
  1174. ADD_INT_MACRO(SIGINT);
  1175. #endif
  1176. #ifdef SIGBREAK
  1177. ADD_INT_MACRO(SIGBREAK);
  1178. #endif
  1179. #ifdef SIGQUIT
  1180. ADD_INT_MACRO(SIGQUIT);
  1181. #endif
  1182. #ifdef SIGILL
  1183. ADD_INT_MACRO(SIGILL);
  1184. #endif
  1185. #ifdef SIGTRAP
  1186. ADD_INT_MACRO(SIGTRAP);
  1187. #endif
  1188. #ifdef SIGIOT
  1189. ADD_INT_MACRO(SIGIOT);
  1190. #endif
  1191. #ifdef SIGABRT
  1192. ADD_INT_MACRO(SIGABRT);
  1193. #endif
  1194. #ifdef SIGEMT
  1195. ADD_INT_MACRO(SIGEMT);
  1196. #endif
  1197. #ifdef SIGFPE
  1198. ADD_INT_MACRO(SIGFPE);
  1199. #endif
  1200. #ifdef SIGKILL
  1201. ADD_INT_MACRO(SIGKILL);
  1202. #endif
  1203. #ifdef SIGBUS
  1204. ADD_INT_MACRO(SIGBUS);
  1205. #endif
  1206. #ifdef SIGSEGV
  1207. ADD_INT_MACRO(SIGSEGV);
  1208. #endif
  1209. #ifdef SIGSYS
  1210. ADD_INT_MACRO(SIGSYS);
  1211. #endif
  1212. #ifdef SIGPIPE
  1213. ADD_INT_MACRO(SIGPIPE);
  1214. #endif
  1215. #ifdef SIGALRM
  1216. ADD_INT_MACRO(SIGALRM);
  1217. #endif
  1218. #ifdef SIGTERM
  1219. ADD_INT_MACRO(SIGTERM);
  1220. #endif
  1221. #ifdef SIGUSR1
  1222. ADD_INT_MACRO(SIGUSR1);
  1223. #endif
  1224. #ifdef SIGUSR2
  1225. ADD_INT_MACRO(SIGUSR2);
  1226. #endif
  1227. #ifdef SIGCLD
  1228. ADD_INT_MACRO(SIGCLD);
  1229. #endif
  1230. #ifdef SIGCHLD
  1231. ADD_INT_MACRO(SIGCHLD);
  1232. #endif
  1233. #ifdef SIGPWR
  1234. ADD_INT_MACRO(SIGPWR);
  1235. #endif
  1236. #ifdef SIGIO
  1237. ADD_INT_MACRO(SIGIO);
  1238. #endif
  1239. #ifdef SIGURG
  1240. ADD_INT_MACRO(SIGURG);
  1241. #endif
  1242. #ifdef SIGWINCH
  1243. ADD_INT_MACRO(SIGWINCH);
  1244. #endif
  1245. #ifdef SIGPOLL
  1246. ADD_INT_MACRO(SIGPOLL);
  1247. #endif
  1248. #ifdef SIGSTOP
  1249. ADD_INT_MACRO(SIGSTOP);
  1250. #endif
  1251. #ifdef SIGTSTP
  1252. ADD_INT_MACRO(SIGTSTP);
  1253. #endif
  1254. #ifdef SIGCONT
  1255. ADD_INT_MACRO(SIGCONT);
  1256. #endif
  1257. #ifdef SIGTTIN
  1258. ADD_INT_MACRO(SIGTTIN);
  1259. #endif
  1260. #ifdef SIGTTOU
  1261. ADD_INT_MACRO(SIGTTOU);
  1262. #endif
  1263. #ifdef SIGVTALRM
  1264. ADD_INT_MACRO(SIGVTALRM);
  1265. #endif
  1266. #ifdef SIGPROF
  1267. ADD_INT_MACRO(SIGPROF);
  1268. #endif
  1269. #ifdef SIGXCPU
  1270. ADD_INT_MACRO(SIGXCPU);
  1271. #endif
  1272. #ifdef SIGXFSZ
  1273. ADD_INT_MACRO(SIGXFSZ);
  1274. #endif
  1275. #ifdef SIGRTMIN
  1276. ADD_INT_MACRO(SIGRTMIN);
  1277. #endif
  1278. #ifdef SIGRTMAX
  1279. ADD_INT_MACRO(SIGRTMAX);
  1280. #endif
  1281. #ifdef SIGINFO
  1282. ADD_INT_MACRO(SIGINFO);
  1283. #endif
  1284. #ifdef SIGSTKFLT
  1285. ADD_INT_MACRO(SIGSTKFLT);
  1286. #endif
  1287. // ITIMER_xxx constants
  1288. #ifdef ITIMER_REAL
  1289. ADD_INT_MACRO(ITIMER_REAL);
  1290. #endif
  1291. #ifdef ITIMER_VIRTUAL
  1292. ADD_INT_MACRO(ITIMER_VIRTUAL);
  1293. #endif
  1294. #ifdef ITIMER_PROF
  1295. ADD_INT_MACRO(ITIMER_PROF);
  1296. #endif
  1297. // CTRL_xxx Windows signals
  1298. #ifdef CTRL_C_EVENT
  1299. ADD_INT_MACRO(CTRL_C_EVENT);
  1300. #endif
  1301. #ifdef CTRL_BREAK_EVENT
  1302. ADD_INT_MACRO(CTRL_BREAK_EVENT);
  1303. #endif
  1304. return 0;
  1305. #undef ADD_INT_MACRO
  1306. }
  1307. static int
  1308. signal_get_set_handlers(signal_state_t *state, PyObject *mod_dict)
  1309. {
  1310. // Get signal handlers
  1311. for (int signum = 1; signum < Py_NSIG; signum++) {
  1312. void (*c_handler)(int) = PyOS_getsig(signum);
  1313. PyObject *func;
  1314. if (c_handler == SIG_DFL) {
  1315. func = state->default_handler;
  1316. }
  1317. else if (c_handler == SIG_IGN) {
  1318. func = state->ignore_handler;
  1319. }
  1320. else {
  1321. func = Py_None; // None of our business
  1322. }
  1323. // If signal_module_exec() is called more than one, we must
  1324. // clear the strong reference to the previous function.
  1325. PyObject* old_func = get_handler(signum);
  1326. set_handler(signum, Py_NewRef(func));
  1327. Py_XDECREF(old_func);
  1328. }
  1329. // Install Python SIGINT handler which raises KeyboardInterrupt
  1330. PyObject* sigint_func = get_handler(SIGINT);
  1331. if (sigint_func == state->default_handler) {
  1332. PyObject *int_handler = PyMapping_GetItemString(mod_dict,
  1333. "default_int_handler");
  1334. if (!int_handler) {
  1335. return -1;
  1336. }
  1337. set_handler(SIGINT, int_handler);
  1338. Py_DECREF(sigint_func);
  1339. PyOS_setsig(SIGINT, signal_handler);
  1340. }
  1341. return 0;
  1342. }
  1343. static int
  1344. signal_module_exec(PyObject *m)
  1345. {
  1346. assert(!PyErr_Occurred());
  1347. signal_state_t *state = &signal_global_state;
  1348. _signal_module_state *modstate = get_signal_state(m);
  1349. // XXX For proper isolation, these values must be guaranteed
  1350. // to be effectively const (e.g. immortal).
  1351. modstate->default_handler = state->default_handler; // borrowed ref
  1352. modstate->ignore_handler = state->ignore_handler; // borrowed ref
  1353. #ifdef PYHAVE_ITIMER_ERROR
  1354. modstate->itimer_error = PyErr_NewException("signal.itimer_error",
  1355. PyExc_OSError, NULL);
  1356. if (modstate->itimer_error == NULL) {
  1357. return -1;
  1358. }
  1359. #endif
  1360. if (signal_add_constants(m) < 0) {
  1361. return -1;
  1362. }
  1363. /* Add some symbolic constants to the module */
  1364. PyObject *d = PyModule_GetDict(m);
  1365. if (PyDict_SetItemString(d, "SIG_DFL", state->default_handler) < 0) {
  1366. return -1;
  1367. }
  1368. if (PyDict_SetItemString(d, "SIG_IGN", state->ignore_handler) < 0) {
  1369. return -1;
  1370. }
  1371. #ifdef PYHAVE_ITIMER_ERROR
  1372. if (PyDict_SetItemString(d, "ItimerError", modstate->itimer_error) < 0) {
  1373. return -1;
  1374. }
  1375. #endif
  1376. #if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
  1377. modstate->siginfo_type = PyStructSequence_NewType(&struct_siginfo_desc);
  1378. if (modstate->siginfo_type == NULL) {
  1379. return -1;
  1380. }
  1381. #endif
  1382. #if defined(HAVE_SIGWAITINFO) || defined(HAVE_SIGTIMEDWAIT)
  1383. if (PyModule_AddType(m, modstate->siginfo_type) < 0) {
  1384. return -1;
  1385. }
  1386. #endif
  1387. PyThreadState *tstate = _PyThreadState_GET();
  1388. if (_Py_IsMainInterpreter(tstate->interp)) {
  1389. if (signal_get_set_handlers(state, d) < 0) {
  1390. return -1;
  1391. }
  1392. }
  1393. assert(!PyErr_Occurred());
  1394. return 0;
  1395. }
  1396. #ifdef PYHAVE_ITIMER_ERROR
  1397. static int
  1398. _signal_module_traverse(PyObject *module, visitproc visit, void *arg)
  1399. {
  1400. _signal_module_state *state = get_signal_state(module);
  1401. Py_VISIT(state->itimer_error);
  1402. Py_VISIT(state->siginfo_type);
  1403. return 0;
  1404. }
  1405. static int
  1406. _signal_module_clear(PyObject *module)
  1407. {
  1408. _signal_module_state *state = get_signal_state(module);
  1409. Py_CLEAR(state->itimer_error);
  1410. Py_CLEAR(state->siginfo_type);
  1411. return 0;
  1412. }
  1413. static void
  1414. _signal_module_free(void *module)
  1415. {
  1416. _signal_module_clear((PyObject *)module);
  1417. }
  1418. #endif // PYHAVE_ITIMER_ERROR
  1419. static PyModuleDef_Slot signal_slots[] = {
  1420. {Py_mod_exec, signal_module_exec},
  1421. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1422. {0, NULL}
  1423. };
  1424. static struct PyModuleDef signal_module = {
  1425. PyModuleDef_HEAD_INIT,
  1426. "_signal",
  1427. .m_doc = module_doc,
  1428. .m_size = sizeof(_signal_module_state),
  1429. .m_methods = signal_methods,
  1430. .m_slots = signal_slots,
  1431. #ifdef PYHAVE_ITIMER_ERROR
  1432. .m_traverse = _signal_module_traverse,
  1433. .m_clear = _signal_module_clear,
  1434. .m_free = _signal_module_free,
  1435. #endif
  1436. };
  1437. PyMODINIT_FUNC
  1438. PyInit__signal(void)
  1439. {
  1440. return PyModuleDef_Init(&signal_module);
  1441. }
  1442. void
  1443. _PySignal_Fini(void)
  1444. {
  1445. signal_state_t *state = &signal_global_state;
  1446. // Restore default signals and clear handlers
  1447. for (int signum = 1; signum < Py_NSIG; signum++) {
  1448. PyObject *func = get_handler(signum);
  1449. _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
  1450. set_handler(signum, NULL);
  1451. if (func != NULL
  1452. && func != Py_None
  1453. && !compare_handler(func, state->default_handler)
  1454. && !compare_handler(func, state->ignore_handler))
  1455. {
  1456. PyOS_setsig(signum, SIG_DFL);
  1457. }
  1458. Py_XDECREF(func);
  1459. }
  1460. #ifdef MS_WINDOWS
  1461. if (state->sigint_event != NULL) {
  1462. CloseHandle((HANDLE)state->sigint_event);
  1463. state->sigint_event = NULL;
  1464. }
  1465. #endif
  1466. Py_CLEAR(state->default_handler);
  1467. Py_CLEAR(state->ignore_handler);
  1468. }
  1469. /* Declared in pyerrors.h */
  1470. int
  1471. PyErr_CheckSignals(void)
  1472. {
  1473. PyThreadState *tstate = _PyThreadState_GET();
  1474. /* Opportunistically check if the GC is scheduled to run and run it
  1475. if we have a request. This is done here because native code needs
  1476. to call this API if is going to run for some time without executing
  1477. Python code to ensure signals are handled. Checking for the GC here
  1478. allows long running native code to clean cycles created using the C-API
  1479. even if it doesn't run the evaluation loop */
  1480. struct _ceval_state *interp_ceval_state = &tstate->interp->ceval;
  1481. if (_Py_atomic_load_relaxed(&interp_ceval_state->gc_scheduled)) {
  1482. _Py_atomic_store_relaxed(&interp_ceval_state->gc_scheduled, 0);
  1483. _Py_RunGC(tstate);
  1484. }
  1485. if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
  1486. return 0;
  1487. }
  1488. return _PyErr_CheckSignalsTstate(tstate);
  1489. }
  1490. /* Declared in cpython/pyerrors.h */
  1491. int
  1492. _PyErr_CheckSignalsTstate(PyThreadState *tstate)
  1493. {
  1494. _Py_CHECK_EMSCRIPTEN_SIGNALS();
  1495. if (!_Py_atomic_load(&is_tripped)) {
  1496. return 0;
  1497. }
  1498. /*
  1499. * The is_tripped variable is meant to speed up the calls to
  1500. * PyErr_CheckSignals (both directly or via pending calls) when no
  1501. * signal has arrived. This variable is set to 1 when a signal arrives
  1502. * and it is set to 0 here, when we know some signals arrived. This way
  1503. * we can run the registered handlers with no signals blocked.
  1504. *
  1505. * NOTE: with this approach we can have a situation where is_tripped is
  1506. * 1 but we have no more signals to handle (Handlers[i].tripped
  1507. * is 0 for every signal i). This won't do us any harm (except
  1508. * we're gonna spent some cycles for nothing). This happens when
  1509. * we receive a signal i after we zero is_tripped and before we
  1510. * check Handlers[i].tripped.
  1511. */
  1512. _Py_atomic_store(&is_tripped, 0);
  1513. _PyInterpreterFrame *frame = _PyThreadState_GetFrame(tstate);
  1514. signal_state_t *state = &signal_global_state;
  1515. for (int i = 1; i < Py_NSIG; i++) {
  1516. if (!_Py_atomic_load_relaxed(&Handlers[i].tripped)) {
  1517. continue;
  1518. }
  1519. _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
  1520. /* Signal handlers can be modified while a signal is received,
  1521. * and therefore the fact that trip_signal() or PyErr_SetInterrupt()
  1522. * was called doesn't guarantee that there is still a Python
  1523. * signal handler for it by the time PyErr_CheckSignals() is called
  1524. * (see bpo-43406).
  1525. */
  1526. PyObject *func = get_handler(i);
  1527. if (func == NULL || func == Py_None ||
  1528. compare_handler(func, state->ignore_handler) ||
  1529. compare_handler(func, state->default_handler)) {
  1530. /* No Python signal handler due to aforementioned race condition.
  1531. * We can't call raise() as it would break the assumption
  1532. * that PyErr_SetInterrupt() only *simulates* an incoming
  1533. * signal (i.e. it will never kill the process).
  1534. * We also don't want to interrupt user code with a cryptic
  1535. * asynchronous exception, so instead just write out an
  1536. * unraisable error.
  1537. */
  1538. PyErr_Format(PyExc_OSError,
  1539. "Signal %i ignored due to race condition",
  1540. i);
  1541. PyErr_WriteUnraisable(Py_None);
  1542. continue;
  1543. }
  1544. PyObject *arglist = NULL;
  1545. if (frame == NULL) {
  1546. arglist = Py_BuildValue("(iO)", i, Py_None);
  1547. }
  1548. else {
  1549. PyFrameObject *f = _PyFrame_GetFrameObject(frame);
  1550. if (f != NULL) {
  1551. arglist = Py_BuildValue("(iO)", i, f);
  1552. }
  1553. }
  1554. PyObject *result;
  1555. if (arglist) {
  1556. result = _PyObject_Call(tstate, func, arglist, NULL);
  1557. Py_DECREF(arglist);
  1558. }
  1559. else {
  1560. result = NULL;
  1561. }
  1562. if (!result) {
  1563. /* On error, re-schedule a call to _PyErr_CheckSignalsTstate() */
  1564. _Py_atomic_store(&is_tripped, 1);
  1565. return -1;
  1566. }
  1567. Py_DECREF(result);
  1568. }
  1569. return 0;
  1570. }
  1571. int
  1572. _PyErr_CheckSignals(void)
  1573. {
  1574. PyThreadState *tstate = _PyThreadState_GET();
  1575. return _PyErr_CheckSignalsTstate(tstate);
  1576. }
  1577. /* Simulate the effect of a signal arriving. The next time PyErr_CheckSignals
  1578. is called, the corresponding Python signal handler will be raised.
  1579. Missing signal handler for the given signal number is silently ignored. */
  1580. int
  1581. PyErr_SetInterruptEx(int signum)
  1582. {
  1583. if (signum < 1 || signum >= Py_NSIG) {
  1584. return -1;
  1585. }
  1586. signal_state_t *state = &signal_global_state;
  1587. PyObject *func = get_handler(signum);
  1588. if (!compare_handler(func, state->ignore_handler)
  1589. && !compare_handler(func, state->default_handler)) {
  1590. trip_signal(signum);
  1591. }
  1592. return 0;
  1593. }
  1594. void
  1595. PyErr_SetInterrupt(void)
  1596. {
  1597. (void) PyErr_SetInterruptEx(SIGINT);
  1598. }
  1599. static int
  1600. signal_install_handlers(void)
  1601. {
  1602. #ifdef SIGPIPE
  1603. PyOS_setsig(SIGPIPE, SIG_IGN);
  1604. #endif
  1605. #ifdef SIGXFZ
  1606. PyOS_setsig(SIGXFZ, SIG_IGN);
  1607. #endif
  1608. #ifdef SIGXFSZ
  1609. PyOS_setsig(SIGXFSZ, SIG_IGN);
  1610. #endif
  1611. // Import _signal to install the Python SIGINT handler
  1612. PyObject *module = PyImport_ImportModule("_signal");
  1613. if (!module) {
  1614. return -1;
  1615. }
  1616. Py_DECREF(module);
  1617. return 0;
  1618. }
  1619. /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
  1620. *
  1621. * All of the code in this function must only use async-signal-safe functions,
  1622. * listed at `man 7 signal` or
  1623. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  1624. *
  1625. * If this function is updated, update also _posix_spawn() of subprocess.py.
  1626. */
  1627. void
  1628. _Py_RestoreSignals(void)
  1629. {
  1630. #ifdef SIGPIPE
  1631. PyOS_setsig(SIGPIPE, SIG_DFL);
  1632. #endif
  1633. #ifdef SIGXFZ
  1634. PyOS_setsig(SIGXFZ, SIG_DFL);
  1635. #endif
  1636. #ifdef SIGXFSZ
  1637. PyOS_setsig(SIGXFSZ, SIG_DFL);
  1638. #endif
  1639. }
  1640. int
  1641. _PySignal_Init(int install_signal_handlers)
  1642. {
  1643. signal_state_t *state = &signal_global_state;
  1644. state->default_handler = PyLong_FromVoidPtr((void *)SIG_DFL);
  1645. if (state->default_handler == NULL) {
  1646. return -1;
  1647. }
  1648. state->ignore_handler = PyLong_FromVoidPtr((void *)SIG_IGN);
  1649. if (state->ignore_handler == NULL) {
  1650. return -1;
  1651. }
  1652. #ifdef MS_WINDOWS
  1653. /* Create manual-reset event, initially unset */
  1654. state->sigint_event = (void *)CreateEvent(NULL, TRUE, FALSE, FALSE);
  1655. if (state->sigint_event == NULL) {
  1656. PyErr_SetFromWindowsErr(0);
  1657. return -1;
  1658. }
  1659. #endif
  1660. for (int signum = 1; signum < Py_NSIG; signum++) {
  1661. _Py_atomic_store_relaxed(&Handlers[signum].tripped, 0);
  1662. }
  1663. if (install_signal_handlers) {
  1664. if (signal_install_handlers() < 0) {
  1665. return -1;
  1666. }
  1667. }
  1668. return 0;
  1669. }
  1670. // The caller doesn't have to hold the GIL
  1671. int
  1672. _PyOS_InterruptOccurred(PyThreadState *tstate)
  1673. {
  1674. _Py_EnsureTstateNotNULL(tstate);
  1675. if (!_Py_ThreadCanHandleSignals(tstate->interp)) {
  1676. return 0;
  1677. }
  1678. if (!_Py_atomic_load_relaxed(&Handlers[SIGINT].tripped)) {
  1679. return 0;
  1680. }
  1681. _Py_atomic_store_relaxed(&Handlers[SIGINT].tripped, 0);
  1682. return 1;
  1683. }
  1684. // The caller must to hold the GIL
  1685. int
  1686. PyOS_InterruptOccurred(void)
  1687. {
  1688. PyThreadState *tstate = _PyThreadState_GET();
  1689. return _PyOS_InterruptOccurred(tstate);
  1690. }
  1691. #ifdef HAVE_FORK
  1692. static void
  1693. _clear_pending_signals(void)
  1694. {
  1695. if (!_Py_atomic_load(&is_tripped)) {
  1696. return;
  1697. }
  1698. _Py_atomic_store(&is_tripped, 0);
  1699. for (int i = 1; i < Py_NSIG; ++i) {
  1700. _Py_atomic_store_relaxed(&Handlers[i].tripped, 0);
  1701. }
  1702. }
  1703. void
  1704. _PySignal_AfterFork(void)
  1705. {
  1706. /* Clear the signal flags after forking so that they aren't handled
  1707. * in both processes if they came in just before the fork() but before
  1708. * the interpreter had an opportunity to call the handlers. issue9535. */
  1709. _clear_pending_signals();
  1710. }
  1711. #endif /* HAVE_FORK */
  1712. int
  1713. _PyOS_IsMainThread(void)
  1714. {
  1715. PyInterpreterState *interp = _PyInterpreterState_GET();
  1716. return _Py_ThreadCanHandleSignals(interp);
  1717. }
  1718. #ifdef MS_WINDOWS
  1719. /* Returns a manual-reset event which gets tripped whenever
  1720. SIGINT is received.
  1721. Python.h does not include windows.h so we do cannot use HANDLE
  1722. as the return type of this function. We use void* instead. */
  1723. void *_PyOS_SigintEvent(void)
  1724. {
  1725. signal_state_t *state = &signal_global_state;
  1726. return state->sigint_event;
  1727. }
  1728. #endif