faulthandler.c 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415
  1. /*
  2. * faulthandler module
  3. *
  4. * Written by Victor Stinner.
  5. */
  6. #include "Python.h"
  7. #include "pythread.h"
  8. #include <signal.h>
  9. #ifdef MS_WINDOWS
  10. # include <windows.h>
  11. #endif
  12. #ifdef HAVE_SYS_RESOURCE_H
  13. # include <sys/resource.h>
  14. #endif
  15. #define VERSION 0x302
  16. /* Allocate at maximum 100 MB of the stack to raise the stack overflow */
  17. #define STACK_OVERFLOW_MAX_SIZE (100*1024*1024)
  18. #ifdef SIGALRM
  19. # define FAULTHANDLER_LATER
  20. #endif
  21. #ifndef MS_WINDOWS
  22. /* sigaltstack() is not available on Windows */
  23. # define HAVE_SIGALTSTACK
  24. /* register() is useless on Windows, because only SIGSEGV, SIGABRT and
  25. SIGILL can be handled by the process, and these signals can only be used
  26. with enable(), not using register() */
  27. # define FAULTHANDLER_USER
  28. #endif
  29. #if PY_MAJOR_VERSION >= 3
  30. # define PYINT_CHECK PyLong_Check
  31. # define PYINT_ASLONG PyLong_AsLong
  32. #else
  33. # define PYINT_CHECK PyInt_Check
  34. # define PYINT_ASLONG PyInt_AsLong
  35. #endif
  36. /* defined in traceback.c */
  37. extern Py_ssize_t _Py_write_noraise(int fd, const char *buf, size_t count);
  38. extern void dump_decimal(int fd, int value);
  39. extern void reverse_string(char *text, const size_t len);
  40. /* cast size_t to int because write() takes an int on Windows
  41. (anyway, the length is smaller than 30 characters) */
  42. #define PUTS(fd, str) _Py_write_noraise(fd, str, (int)strlen(str))
  43. #ifdef HAVE_SIGACTION
  44. typedef struct sigaction _Py_sighandler_t;
  45. #else
  46. typedef PyOS_sighandler_t _Py_sighandler_t;
  47. #endif
  48. typedef struct {
  49. int signum;
  50. int enabled;
  51. const char* name;
  52. _Py_sighandler_t previous;
  53. int all_threads;
  54. } fault_handler_t;
  55. static struct {
  56. int enabled;
  57. PyObject *file;
  58. int fd;
  59. int all_threads;
  60. PyInterpreterState *interp;
  61. } fatal_error = {0, NULL, -1, 0};
  62. #ifdef FAULTHANDLER_LATER
  63. static struct {
  64. PyObject *file;
  65. int fd;
  66. int timeout;
  67. int repeat;
  68. PyInterpreterState *interp;
  69. int exit;
  70. char *header;
  71. size_t header_len;
  72. } fault_alarm;
  73. #endif
  74. #ifdef FAULTHANDLER_USER
  75. typedef struct {
  76. int enabled;
  77. PyObject *file;
  78. int fd;
  79. int all_threads;
  80. int chain;
  81. _Py_sighandler_t previous;
  82. PyInterpreterState *interp;
  83. } user_signal_t;
  84. static user_signal_t *user_signals;
  85. /* the following macros come from Python: Modules/signalmodule.c of Python 3.3 */
  86. #if defined(PYOS_OS2) && !defined(PYCC_GCC)
  87. #define NSIG 12
  88. #endif
  89. #ifndef NSIG
  90. # if defined(_NSIG)
  91. # define NSIG _NSIG /* For BSD/SysV */
  92. # elif defined(_SIGMAX)
  93. # define NSIG (_SIGMAX + 1) /* For QNX */
  94. # elif defined(SIGMAX)
  95. # define NSIG (SIGMAX + 1) /* For djgpp */
  96. # else
  97. # define NSIG 64 /* Use a reasonable default value */
  98. # endif
  99. #endif
  100. static void faulthandler_user(int signum);
  101. #endif /* FAULTHANDLER_USER */
  102. #ifndef SI_KERNEL
  103. #define SI_KERNEL 0x80
  104. #endif
  105. #ifndef SI_TKILL
  106. #define SI_TKILL -6
  107. #endif
  108. static fault_handler_t faulthandler_handlers[] = {
  109. #ifdef SIGBUS
  110. {SIGBUS, 0, "Bus error", },
  111. #endif
  112. #ifdef SIGILL
  113. {SIGILL, 0, "Illegal instruction", },
  114. #endif
  115. {SIGFPE, 0, "Floating point exception", },
  116. {SIGABRT, 0, "Aborted", },
  117. /* define SIGSEGV at the end to make it the default choice if searching the
  118. handler fails in faulthandler_fatal_error() */
  119. {SIGSEGV, 0, "Segmentation fault", }
  120. };
  121. static const size_t faulthandler_nsignals = \
  122. sizeof(faulthandler_handlers) / sizeof(faulthandler_handlers[0]);
  123. #ifdef HAVE_SIGALTSTACK
  124. static stack_t stack;
  125. #endif
  126. /* Forward */
  127. static void faulthandler_unload(void);
  128. /* from traceback.c */
  129. extern void _Py_DumpTraceback(int fd, PyThreadState *tstate);
  130. extern const char* _Py_DumpTracebackThreads(
  131. int fd,
  132. PyInterpreterState *interp,
  133. PyThreadState *current_thread);
  134. /* Get the file descriptor of a file by calling its fileno() method and then
  135. call its flush() method.
  136. If file is NULL or Py_None, use sys.stderr as the new file.
  137. If file is an integer, it will be treated as file descriptor.
  138. On success, return the file descriptor and write the new file into *file_ptr.
  139. On error, return -1. */
  140. static int
  141. faulthandler_get_fileno(PyObject **file_ptr)
  142. {
  143. PyObject *result;
  144. long fd_long;
  145. long fd;
  146. PyObject *file = *file_ptr;
  147. if (file == NULL || file == Py_None) {
  148. file = PySys_GetObject("stderr");
  149. if (file == NULL) {
  150. PyErr_SetString(PyExc_RuntimeError, "unable to get sys.stderr");
  151. return -1;
  152. }
  153. if (file == Py_None) {
  154. PyErr_SetString(PyExc_RuntimeError, "sys.stderr is None");
  155. return -1;
  156. }
  157. }
  158. else if (PYINT_CHECK(file)) {
  159. fd = PYINT_ASLONG(file);
  160. if (fd == -1 && PyErr_Occurred())
  161. return -1;
  162. if (fd < 0 || fd > INT_MAX) {
  163. PyErr_SetString(PyExc_ValueError,
  164. "file is not a valid file descripter");
  165. return -1;
  166. }
  167. *file_ptr = NULL;
  168. return (int)fd;
  169. }
  170. result = PyObject_CallMethod(file, "fileno", "");
  171. if (result == NULL)
  172. return -1;
  173. fd = -1;
  174. if (PYINT_CHECK(result)) {
  175. fd_long = PYINT_ASLONG(result);
  176. if (0 < fd_long && fd_long < INT_MAX)
  177. fd = (int)fd_long;
  178. }
  179. Py_DECREF(result);
  180. if (fd == -1) {
  181. PyErr_SetString(PyExc_RuntimeError,
  182. "file.fileno() is not a valid file descriptor");
  183. return -1;
  184. }
  185. result = PyObject_CallMethod(file, "flush", "");
  186. if (result != NULL)
  187. Py_DECREF(result);
  188. else {
  189. /* ignore flush() error */
  190. PyErr_Clear();
  191. }
  192. *file_ptr = file;
  193. return fd;
  194. }
  195. /* Get the state of the current thread: only call this function if the current
  196. thread holds the GIL. Raise an exception on error. */
  197. static PyThreadState*
  198. get_thread_state(void)
  199. {
  200. PyThreadState *tstate = PyThreadState_Get();
  201. if (tstate == NULL) {
  202. PyErr_SetString(PyExc_RuntimeError,
  203. "unable to get the current thread state");
  204. return NULL;
  205. }
  206. return tstate;
  207. }
  208. static void
  209. faulthandler_dump_traceback(int fd, int all_threads,
  210. PyInterpreterState *interp)
  211. {
  212. static volatile int reentrant = 0;
  213. PyThreadState *tstate;
  214. if (reentrant)
  215. return;
  216. reentrant = 1;
  217. #ifdef WITH_THREAD
  218. /* SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL are synchronous signals and
  219. are thus delivered to the thread that caused the fault. Get the Python
  220. thread state of the current thread.
  221. PyThreadState_Get() doesn't give the state of the thread that caused the
  222. fault if the thread released the GIL, and so this function cannot be
  223. used. Read the thread local storage (TLS) instead: call
  224. PyGILState_GetThisThreadState(). */
  225. tstate = PyGILState_GetThisThreadState();
  226. #else
  227. tstate = PyThreadState_Get();
  228. #endif
  229. if (all_threads)
  230. _Py_DumpTracebackThreads(fd, interp, tstate);
  231. else {
  232. if (tstate != NULL)
  233. _Py_DumpTraceback(fd, tstate);
  234. }
  235. reentrant = 0;
  236. }
  237. static PyObject*
  238. faulthandler_dump_traceback_py(PyObject *self,
  239. PyObject *args, PyObject *kwargs)
  240. {
  241. static char *kwlist[] = {"file", "all_threads", NULL};
  242. PyObject *file = NULL;
  243. int all_threads = 1;
  244. PyThreadState *tstate;
  245. const char *errmsg;
  246. int fd;
  247. if (!PyArg_ParseTupleAndKeywords(args, kwargs,
  248. "|Oi:dump_traceback", kwlist,
  249. &file, &all_threads))
  250. return NULL;
  251. fd = faulthandler_get_fileno(&file);
  252. if (fd < 0)
  253. return NULL;
  254. tstate = get_thread_state();
  255. if (tstate == NULL)
  256. return NULL;
  257. if (all_threads) {
  258. errmsg = _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
  259. if (errmsg != NULL) {
  260. PyErr_SetString(PyExc_RuntimeError, errmsg);
  261. return NULL;
  262. }
  263. }
  264. else {
  265. _Py_DumpTraceback(fd, tstate);
  266. }
  267. if (PyErr_CheckSignals())
  268. return NULL;
  269. Py_RETURN_NONE;
  270. }
  271. static void
  272. faulthandler_disable_fatal_handler(fault_handler_t *handler)
  273. {
  274. if (!handler->enabled)
  275. return;
  276. handler->enabled = 0;
  277. #ifdef HAVE_SIGACTION
  278. (void)sigaction(handler->signum, &handler->previous, NULL);
  279. #else
  280. (void)signal(handler->signum, handler->previous);
  281. #endif
  282. }
  283. /* Handler for SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals.
  284. Display the current Python traceback, restore the previous handler and call
  285. the previous handler.
  286. On Windows, don't explicitly call the previous handler, because the Windows
  287. signal handler would not be called (for an unknown reason). The execution of
  288. the program continues at faulthandler_fatal_error() exit, but the same
  289. instruction will raise the same fault (signal), and so the previous handler
  290. will be called.
  291. This function is signal-safe and should only call signal-safe functions. */
  292. static void
  293. faulthandler_fatal_error(int signum)
  294. {
  295. const int fd = fatal_error.fd;
  296. size_t i;
  297. fault_handler_t *handler = NULL;
  298. int save_errno = errno;
  299. if (!fatal_error.enabled)
  300. return;
  301. for (i=0; i < faulthandler_nsignals; i++) {
  302. handler = &faulthandler_handlers[i];
  303. if (handler->signum == signum)
  304. break;
  305. }
  306. if (handler == NULL) {
  307. /* faulthandler_nsignals == 0 (unlikely) */
  308. return;
  309. }
  310. /* restore the previous handler */
  311. faulthandler_disable_fatal_handler(handler);
  312. PUTS(fd, "Fatal Python error: ");
  313. PUTS(fd, handler->name);
  314. PUTS(fd, "\n\n");
  315. faulthandler_dump_traceback(fd, fatal_error.all_threads,
  316. fatal_error.interp);
  317. errno = save_errno;
  318. #ifdef MS_WINDOWS
  319. if (signum == SIGSEGV) {
  320. /* don't explicitly call the previous handler for SIGSEGV in this signal
  321. handler, because the Windows signal handler would not be called */
  322. return;
  323. }
  324. #endif
  325. /* call the previous signal handler: it is called immediately if we use
  326. sigaction() thanks to SA_NODEFER flag, otherwise it is deferred */
  327. raise(signum);
  328. }
  329. static size_t
  330. uitoa(size_t val, char* ss) {
  331. char* start = ss;
  332. size_t len = 0;
  333. do {
  334. *ss = '0' + (val % 10);
  335. val /= 10;
  336. ss++; len++;
  337. } while (val);
  338. reverse_string(start, len);
  339. return len;
  340. }
  341. static void
  342. read_proc_exe(pid_t pid, char* buff, size_t len) {
  343. char pathname[32] = {0};
  344. strcpy(pathname, "/proc/");
  345. size_t pos = uitoa(pid, &pathname[6]) + 6;
  346. strcpy(&pathname[pos], "/exe");
  347. ssize_t l = readlink(pathname, buff, len);
  348. if (l > 0) {
  349. // readlink() does not append a null byte to buf
  350. buff[l] = '\0';
  351. } else {
  352. strncpy(buff, "unknown_program", len);
  353. }
  354. }
  355. #ifdef HAVE_SIGACTION
  356. static void
  357. faulthandler_fatal_error_siginfo(int signum, siginfo_t* siginfo, void* ctx)
  358. {
  359. const int fd = fatal_error.fd;
  360. int save_errno = errno;
  361. if (!fatal_error.enabled)
  362. return;
  363. PUTS(fd, "\n*** Signal {si_signo=");
  364. dump_decimal(fd, siginfo->si_signo);
  365. PUTS(fd, ", si_code=");
  366. dump_decimal(fd, siginfo->si_code);
  367. switch (siginfo->si_code) {
  368. case SEGV_ACCERR: PUTS(fd, " SEGV_ACCERR"); break;
  369. case SEGV_MAPERR: PUTS(fd, " SEGV_MAPERR"); break;
  370. case SI_KERNEL: PUTS(fd, " SI_KERNEL"); break;
  371. case SI_TIMER: PUTS(fd, " SI_TIMER"); break;
  372. case SI_TKILL: PUTS(fd, " SI_TKILL"); break;
  373. case SI_USER: PUTS(fd, " SI_USER"); break;
  374. }
  375. if (siginfo->si_pid > 0) {
  376. PUTS(fd, ", si_pid=");
  377. dump_decimal(fd, siginfo->si_pid);
  378. PUTS(fd, " ");
  379. char buffer[PATH_MAX] = {0};
  380. read_proc_exe(siginfo->si_pid, &buffer[0], PATH_MAX - 1);
  381. PUTS(fd, &buffer[0]);
  382. }
  383. PUTS(fd, ", si_uid=");
  384. dump_decimal(fd, siginfo->si_uid);
  385. PUTS(fd, "} received by proc {pid=");
  386. dump_decimal(fd, getpid());
  387. PUTS(fd, ", uid=");
  388. dump_decimal(fd, getuid());
  389. PUTS(fd, "} ***\n");
  390. faulthandler_fatal_error(signum);
  391. errno = save_errno;
  392. }
  393. #endif
  394. #ifdef MS_WINDOWS
  395. extern void _Py_dump_hexadecimal(int fd, unsigned long value, size_t bytes);
  396. static int
  397. faulthandler_ignore_exception(DWORD code)
  398. {
  399. /* bpo-30557: ignore exceptions which are not errors */
  400. if (!(code & 0x80000000)) {
  401. return 1;
  402. }
  403. /* bpo-31701: ignore MSC and COM exceptions
  404. E0000000 + code */
  405. if (code == 0xE06D7363 /* MSC exception ("Emsc") */
  406. || code == 0xE0434352 /* COM Callable Runtime exception ("ECCR") */) {
  407. return 1;
  408. }
  409. /* Interesting exception: log it with the Python traceback */
  410. return 0;
  411. }
  412. static LONG WINAPI
  413. faulthandler_exc_handler(struct _EXCEPTION_POINTERS *exc_info)
  414. {
  415. const int fd = fatal_error.fd;
  416. DWORD code = exc_info->ExceptionRecord->ExceptionCode;
  417. if (faulthandler_ignore_exception(code)) {
  418. /* ignore the exception: call the next exception handler */
  419. return EXCEPTION_CONTINUE_SEARCH;
  420. }
  421. PUTS(fd, "Windows exception: ");
  422. switch (code)
  423. {
  424. /* only format most common errors */
  425. case EXCEPTION_ACCESS_VIOLATION: PUTS(fd, "access violation"); break;
  426. case EXCEPTION_FLT_DIVIDE_BY_ZERO: PUTS(fd, "float divide by zero"); break;
  427. case EXCEPTION_FLT_OVERFLOW: PUTS(fd, "float overflow"); break;
  428. case EXCEPTION_INT_DIVIDE_BY_ZERO: PUTS(fd, "int divide by zero"); break;
  429. case EXCEPTION_INT_OVERFLOW: PUTS(fd, "integer overflow"); break;
  430. case EXCEPTION_IN_PAGE_ERROR: PUTS(fd, "page error"); break;
  431. case EXCEPTION_STACK_OVERFLOW: PUTS(fd, "stack overflow"); break;
  432. default:
  433. PUTS(fd, "code 0x");
  434. _Py_dump_hexadecimal(fd, code, sizeof(DWORD));
  435. }
  436. PUTS(fd, "\n\n");
  437. if (code == EXCEPTION_ACCESS_VIOLATION) {
  438. /* disable signal handler for SIGSEGV */
  439. fault_handler_t *handler;
  440. size_t i;
  441. for (i=0; i < faulthandler_nsignals; i++) {
  442. handler = &faulthandler_handlers[i];
  443. if (handler->signum == SIGSEGV) {
  444. faulthandler_disable_fatal_handler(handler);
  445. break;
  446. }
  447. }
  448. }
  449. faulthandler_dump_traceback(fd, fatal_error.all_threads,
  450. fatal_error.interp);
  451. /* call the next exception handler */
  452. return EXCEPTION_CONTINUE_SEARCH;
  453. }
  454. #endif
  455. /* Install the handler for fatal signals, faulthandler_fatal_error(). */
  456. static PyObject*
  457. faulthandler_enable(PyObject *self, PyObject *args, PyObject *kwargs)
  458. {
  459. static char *kwlist[] = {"file", "all_threads", NULL};
  460. PyObject *file = NULL;
  461. int all_threads = 1;
  462. unsigned int i;
  463. fault_handler_t *handler;
  464. #ifdef HAVE_SIGACTION
  465. struct sigaction action;
  466. #endif
  467. int err;
  468. int fd;
  469. PyThreadState *tstate;
  470. if (!PyArg_ParseTupleAndKeywords(args, kwargs,
  471. "|Oi:enable", kwlist, &file, &all_threads))
  472. return NULL;
  473. fd = faulthandler_get_fileno(&file);
  474. if (fd < 0)
  475. return NULL;
  476. tstate = get_thread_state();
  477. if (tstate == NULL)
  478. return NULL;
  479. Py_XDECREF(fatal_error.file);
  480. Py_XINCREF(file);
  481. fatal_error.file = file;
  482. fatal_error.fd = fd;
  483. fatal_error.all_threads = all_threads;
  484. fatal_error.interp = tstate->interp;
  485. if (!fatal_error.enabled) {
  486. fatal_error.enabled = 1;
  487. for (i=0; i < faulthandler_nsignals; i++) {
  488. handler = &faulthandler_handlers[i];
  489. #ifdef HAVE_SIGACTION
  490. action.sa_flags = 0;
  491. #ifdef USE_SIGINFO
  492. action.sa_handler = faulthandler_fatal_error_siginfo;
  493. action.sa_flags |= SA_SIGINFO;
  494. #else
  495. action.sa_handler = faulthandler_fatal_error;
  496. #endif
  497. sigemptyset(&action.sa_mask);
  498. /* Do not prevent the signal from being received from within
  499. its own signal handler */
  500. action.sa_flags |= SA_NODEFER;
  501. #ifdef HAVE_SIGALTSTACK
  502. if (stack.ss_sp != NULL) {
  503. /* Call the signal handler on an alternate signal stack
  504. provided by sigaltstack() */
  505. action.sa_flags |= SA_ONSTACK;
  506. }
  507. #endif
  508. err = sigaction(handler->signum, &action, &handler->previous);
  509. #else
  510. handler->previous = signal(handler->signum,
  511. faulthandler_fatal_error);
  512. err = (handler->previous == SIG_ERR);
  513. #endif
  514. if (err) {
  515. PyErr_SetFromErrno(PyExc_RuntimeError);
  516. return NULL;
  517. }
  518. handler->enabled = 1;
  519. }
  520. #ifdef MS_WINDOWS
  521. AddVectoredExceptionHandler(1, faulthandler_exc_handler);
  522. #endif
  523. }
  524. Py_RETURN_NONE;
  525. }
  526. static void
  527. faulthandler_disable(void)
  528. {
  529. unsigned int i;
  530. fault_handler_t *handler;
  531. if (fatal_error.enabled) {
  532. fatal_error.enabled = 0;
  533. for (i=0; i < faulthandler_nsignals; i++) {
  534. handler = &faulthandler_handlers[i];
  535. faulthandler_disable_fatal_handler(handler);
  536. }
  537. }
  538. Py_CLEAR(fatal_error.file);
  539. }
  540. static PyObject*
  541. faulthandler_disable_py(PyObject *self)
  542. {
  543. if (!fatal_error.enabled) {
  544. Py_INCREF(Py_False);
  545. return Py_False;
  546. }
  547. faulthandler_disable();
  548. Py_INCREF(Py_True);
  549. return Py_True;
  550. }
  551. static PyObject*
  552. faulthandler_is_enabled(PyObject *self)
  553. {
  554. return PyBool_FromLong(fatal_error.enabled);
  555. }
  556. #ifdef FAULTHANDLER_LATER
  557. /* Handler of the SIGALRM signal.
  558. Dump the traceback of the current thread, or of all threads if
  559. fault_alarm.all_threads is true. On success, register itself again if
  560. fault_alarm.repeat is true.
  561. This function is signal safe and should only call signal safe functions. */
  562. static void
  563. faulthandler_alarm(int signum)
  564. {
  565. PyThreadState *tstate;
  566. const char* errmsg;
  567. int ok;
  568. _Py_write_noraise(fault_alarm.fd,
  569. fault_alarm.header, fault_alarm.header_len);
  570. /* PyThreadState_Get() doesn't give the state of the current thread if
  571. the thread doesn't hold the GIL. Read the thread local storage (TLS)
  572. instead: call PyGILState_GetThisThreadState(). */
  573. tstate = PyGILState_GetThisThreadState();
  574. errmsg = _Py_DumpTracebackThreads(fault_alarm.fd, fault_alarm.interp, tstate);
  575. ok = (errmsg == NULL);
  576. if (ok && fault_alarm.repeat)
  577. alarm(fault_alarm.timeout);
  578. else
  579. /* don't call Py_CLEAR() here because it may call _Py_Dealloc() which
  580. is not signal safe */
  581. alarm(0);
  582. if (fault_alarm.exit)
  583. _exit(1);
  584. }
  585. static char*
  586. format_timeout(double timeout)
  587. {
  588. unsigned long us, sec, min, hour;
  589. double intpart, fracpart;
  590. char buffer[100];
  591. fracpart = modf(timeout, &intpart);
  592. sec = (unsigned long)intpart;
  593. us = (unsigned long)(fracpart * 1e6);
  594. min = sec / 60;
  595. sec %= 60;
  596. hour = min / 60;
  597. min %= 60;
  598. if (us != 0)
  599. PyOS_snprintf(buffer, sizeof(buffer),
  600. "Timeout (%lu:%02lu:%02lu.%06lu)!\n",
  601. hour, min, sec, us);
  602. else
  603. PyOS_snprintf(buffer, sizeof(buffer),
  604. "Timeout (%lu:%02lu:%02lu)!\n",
  605. hour, min, sec);
  606. return strdup(buffer);
  607. }
  608. static PyObject*
  609. faulthandler_dump_traceback_later(PyObject *self,
  610. PyObject *args, PyObject *kwargs)
  611. {
  612. static char *kwlist[] = {"timeout", "repeat", "file", "exit", NULL};
  613. int timeout;
  614. PyOS_sighandler_t previous;
  615. int repeat = 0;
  616. PyObject *file = NULL;
  617. int exit = 0;
  618. PyThreadState *tstate;
  619. int fd;
  620. char *header;
  621. size_t header_len;
  622. if (!PyArg_ParseTupleAndKeywords(args, kwargs,
  623. "i|iOi:dump_traceback_later", kwlist,
  624. &timeout, &repeat, &file, &exit))
  625. return NULL;
  626. if (timeout <= 0) {
  627. PyErr_SetString(PyExc_ValueError, "timeout must be greater than 0");
  628. return NULL;
  629. }
  630. tstate = get_thread_state();
  631. if (tstate == NULL)
  632. return NULL;
  633. fd = faulthandler_get_fileno(&file);
  634. if (fd < 0)
  635. return NULL;
  636. /* format the timeout */
  637. header = format_timeout(timeout);
  638. if (header == NULL)
  639. return PyErr_NoMemory();
  640. header_len = strlen(header);
  641. previous = signal(SIGALRM, faulthandler_alarm);
  642. if (previous == SIG_ERR) {
  643. PyErr_SetString(PyExc_RuntimeError, "unable to set SIGALRM handler");
  644. free(header);
  645. return NULL;
  646. }
  647. Py_XDECREF(fault_alarm.file);
  648. Py_XINCREF(file);
  649. fault_alarm.file = file;
  650. fault_alarm.fd = fd;
  651. fault_alarm.timeout = timeout;
  652. fault_alarm.repeat = repeat;
  653. fault_alarm.interp = tstate->interp;
  654. fault_alarm.exit = exit;
  655. fault_alarm.header = header;
  656. fault_alarm.header_len = header_len;
  657. alarm(timeout);
  658. Py_RETURN_NONE;
  659. }
  660. static PyObject*
  661. faulthandler_cancel_dump_traceback_later_py(PyObject *self)
  662. {
  663. alarm(0);
  664. Py_CLEAR(fault_alarm.file);
  665. free(fault_alarm.header);
  666. fault_alarm.header = NULL;
  667. Py_RETURN_NONE;
  668. }
  669. #endif /* FAULTHANDLER_LATER */
  670. #ifdef FAULTHANDLER_USER
  671. static int
  672. faulthandler_register(int signum, int chain, _Py_sighandler_t *p_previous)
  673. {
  674. #ifdef HAVE_SIGACTION
  675. struct sigaction action;
  676. action.sa_handler = faulthandler_user;
  677. sigemptyset(&action.sa_mask);
  678. /* if the signal is received while the kernel is executing a system
  679. call, try to restart the system call instead of interrupting it and
  680. return EINTR. */
  681. action.sa_flags = SA_RESTART;
  682. if (chain) {
  683. /* do not prevent the signal from being received from within its
  684. own signal handler */
  685. action.sa_flags = SA_NODEFER;
  686. }
  687. #ifdef HAVE_SIGALTSTACK
  688. if (stack.ss_sp != NULL) {
  689. /* Call the signal handler on an alternate signal stack
  690. provided by sigaltstack() */
  691. action.sa_flags |= SA_ONSTACK;
  692. }
  693. #endif
  694. return sigaction(signum, &action, p_previous);
  695. #else
  696. _Py_sighandler_t previous;
  697. previous = signal(signum, faulthandler_user);
  698. if (p_previous != NULL)
  699. *p_previous = previous;
  700. return (previous == SIG_ERR);
  701. #endif
  702. }
  703. /* Handler of user signals (e.g. SIGUSR1).
  704. Dump the traceback of the current thread, or of all threads if
  705. thread.all_threads is true.
  706. This function is signal safe and should only call signal safe functions. */
  707. static void
  708. faulthandler_user(int signum)
  709. {
  710. user_signal_t *user;
  711. int save_errno = errno;
  712. user = &user_signals[signum];
  713. if (!user->enabled)
  714. return;
  715. faulthandler_dump_traceback(user->fd, user->all_threads, user->interp);
  716. #ifdef HAVE_SIGACTION
  717. if (user->chain) {
  718. (void)sigaction(signum, &user->previous, NULL);
  719. errno = save_errno;
  720. /* call the previous signal handler */
  721. raise(signum);
  722. save_errno = errno;
  723. (void)faulthandler_register(signum, user->chain, NULL);
  724. errno = save_errno;
  725. }
  726. #else
  727. if (user->chain) {
  728. errno = save_errno;
  729. /* call the previous signal handler */
  730. user->previous(signum);
  731. }
  732. #endif
  733. }
  734. static int
  735. check_signum(int signum)
  736. {
  737. unsigned int i;
  738. for (i=0; i < faulthandler_nsignals; i++) {
  739. if (faulthandler_handlers[i].signum == signum) {
  740. PyErr_Format(PyExc_RuntimeError,
  741. "signal %i cannot be registered, "
  742. "use enable() instead",
  743. signum);
  744. return 0;
  745. }
  746. }
  747. if (signum < 1 || NSIG <= signum) {
  748. PyErr_SetString(PyExc_ValueError, "signal number out of range");
  749. return 0;
  750. }
  751. return 1;
  752. }
  753. static PyObject*
  754. faulthandler_register_py(PyObject *self,
  755. PyObject *args, PyObject *kwargs)
  756. {
  757. static char *kwlist[] = {"signum", "file", "all_threads", "chain", NULL};
  758. int signum;
  759. PyObject *file = NULL;
  760. int all_threads = 1;
  761. int chain = 0;
  762. int fd;
  763. user_signal_t *user;
  764. _Py_sighandler_t previous;
  765. PyThreadState *tstate;
  766. int err;
  767. if (!PyArg_ParseTupleAndKeywords(args, kwargs,
  768. "i|Oii:register", kwlist,
  769. &signum, &file, &all_threads, &chain))
  770. return NULL;
  771. if (!check_signum(signum))
  772. return NULL;
  773. tstate = get_thread_state();
  774. if (tstate == NULL)
  775. return NULL;
  776. fd = faulthandler_get_fileno(&file);
  777. if (fd < 0)
  778. return NULL;
  779. if (user_signals == NULL) {
  780. user_signals = PyMem_Malloc(NSIG * sizeof(user_signal_t));
  781. if (user_signals == NULL)
  782. return PyErr_NoMemory();
  783. memset(user_signals, 0, NSIG * sizeof(user_signal_t));
  784. }
  785. user = &user_signals[signum];
  786. if (!user->enabled) {
  787. err = faulthandler_register(signum, chain, &previous);
  788. if (err) {
  789. PyErr_SetFromErrno(PyExc_OSError);
  790. return NULL;
  791. }
  792. user->previous = previous;
  793. }
  794. Py_XDECREF(user->file);
  795. Py_XINCREF(file);
  796. user->file = file;
  797. user->fd = fd;
  798. user->all_threads = all_threads;
  799. user->chain = chain;
  800. user->interp = tstate->interp;
  801. user->enabled = 1;
  802. Py_RETURN_NONE;
  803. }
  804. static int
  805. faulthandler_unregister(user_signal_t *user, int signum)
  806. {
  807. if (!user->enabled)
  808. return 0;
  809. user->enabled = 0;
  810. #ifdef HAVE_SIGACTION
  811. (void)sigaction(signum, &user->previous, NULL);
  812. #else
  813. (void)signal(signum, user->previous);
  814. #endif
  815. user->fd = -1;
  816. return 1;
  817. }
  818. static PyObject*
  819. faulthandler_unregister_py(PyObject *self, PyObject *args)
  820. {
  821. int signum;
  822. user_signal_t *user;
  823. int change;
  824. if (!PyArg_ParseTuple(args, "i:unregister", &signum))
  825. return NULL;
  826. if (!check_signum(signum))
  827. return NULL;
  828. if (user_signals == NULL)
  829. Py_RETURN_FALSE;
  830. user = &user_signals[signum];
  831. change = faulthandler_unregister(user, signum);
  832. Py_CLEAR(user->file);
  833. return PyBool_FromLong(change);
  834. }
  835. #endif /* FAULTHANDLER_USER */
  836. static void
  837. faulthandler_suppress_crash_report(void)
  838. {
  839. #ifdef MS_WINDOWS
  840. UINT mode;
  841. /* Configure Windows to not display the Windows Error Reporting dialog */
  842. mode = SetErrorMode(SEM_NOGPFAULTERRORBOX);
  843. SetErrorMode(mode | SEM_NOGPFAULTERRORBOX);
  844. #endif
  845. #ifdef HAVE_SYS_RESOURCE_H
  846. struct rlimit rl;
  847. /* Disable creation of core dump */
  848. if (getrlimit(RLIMIT_CORE, &rl) != 0) {
  849. rl.rlim_cur = 0;
  850. setrlimit(RLIMIT_CORE, &rl);
  851. }
  852. #endif
  853. #ifdef _MSC_VER
  854. /* Visual Studio: configure abort() to not display an error message nor
  855. open a popup asking to report the fault. */
  856. _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
  857. #endif
  858. }
  859. static PyObject *
  860. faulthandler_read_null(PyObject *self, PyObject *args)
  861. {
  862. volatile int *x;
  863. volatile int y;
  864. faulthandler_suppress_crash_report();
  865. x = NULL;
  866. y = *x;
  867. return PyLong_FromLong(y);
  868. }
  869. static void
  870. faulthandler_raise_sigsegv(void)
  871. {
  872. faulthandler_suppress_crash_report();
  873. #if defined(MS_WINDOWS)
  874. /* For SIGSEGV, faulthandler_fatal_error() restores the previous signal
  875. handler and then gives back the execution flow to the program (without
  876. explicitly calling the previous error handler). In a normal case, the
  877. SIGSEGV was raised by the kernel because of a fault, and so if the
  878. program retries to execute the same instruction, the fault will be
  879. raised again.
  880. Here the fault is simulated by a fake SIGSEGV signal raised by the
  881. application. We have to raise SIGSEGV at lease twice: once for
  882. faulthandler_fatal_error(), and one more time for the previous signal
  883. handler. */
  884. while(1)
  885. raise(SIGSEGV);
  886. #else
  887. raise(SIGSEGV);
  888. #endif
  889. }
  890. static PyObject *
  891. faulthandler_sigsegv(PyObject *self, PyObject *args)
  892. {
  893. int release_gil = 0;
  894. if (!PyArg_ParseTuple(args, "|i:_read_null", &release_gil))
  895. return NULL;
  896. if (release_gil) {
  897. Py_BEGIN_ALLOW_THREADS
  898. faulthandler_raise_sigsegv();
  899. Py_END_ALLOW_THREADS
  900. } else {
  901. faulthandler_raise_sigsegv();
  902. }
  903. Py_RETURN_NONE;
  904. }
  905. static PyObject *
  906. faulthandler_sigfpe(PyObject *self, PyObject *args)
  907. {
  908. /* Do an integer division by zero: raise a SIGFPE on Intel CPU, but not on
  909. PowerPC. Use volatile to disable compile-time optimizations. */
  910. volatile int x = 1, y = 0, z;
  911. faulthandler_suppress_crash_report();
  912. z = x / y;
  913. /* If the division by zero didn't raise a SIGFPE (e.g. on PowerPC),
  914. raise it manually. */
  915. raise(SIGFPE);
  916. /* This line is never reached, but we pretend to make something with z
  917. to silence a compiler warning. */
  918. return PyLong_FromLong(z);
  919. }
  920. static PyObject *
  921. faulthandler_sigabrt(PyObject *self, PyObject *args)
  922. {
  923. faulthandler_suppress_crash_report();
  924. abort();
  925. Py_RETURN_NONE;
  926. }
  927. static PyObject *
  928. faulthandler_raise_signal(PyObject *self, PyObject *args)
  929. {
  930. int signum, err;
  931. if (PyArg_ParseTuple(args, "i:raise_signal", &signum) < 0)
  932. return NULL;
  933. faulthandler_suppress_crash_report();
  934. err = raise(signum);
  935. if (err)
  936. return PyErr_SetFromErrno(PyExc_OSError);
  937. if (PyErr_CheckSignals() < 0)
  938. return NULL;
  939. Py_RETURN_NONE;
  940. }
  941. static PyObject *
  942. faulthandler_fatal_error_py(PyObject *self, PyObject *args)
  943. {
  944. char *message;
  945. #if PY_MAJOR_VERSION >= 3
  946. if (!PyArg_ParseTuple(args, "y:_fatal_error", &message))
  947. return NULL;
  948. #else
  949. if (!PyArg_ParseTuple(args, "s:fatal_error", &message))
  950. return NULL;
  951. #endif
  952. faulthandler_suppress_crash_report();
  953. Py_FatalError(message);
  954. Py_RETURN_NONE;
  955. }
  956. #ifdef __INTEL_COMPILER
  957. /* Issue #23654: Turn off ICC's tail call optimization for the
  958. * stack_overflow generator. ICC turns the recursive tail call into
  959. * a loop. */
  960. # pragma intel optimization_level 0
  961. #endif
  962. static
  963. Py_uintptr_t
  964. stack_overflow(Py_uintptr_t min_sp, Py_uintptr_t max_sp, size_t *depth)
  965. {
  966. /* allocate 4096 bytes on the stack at each call */
  967. unsigned char buffer[1024*1024];
  968. Py_uintptr_t sp = (Py_uintptr_t)&buffer;
  969. *depth += 1;
  970. if (sp < min_sp || max_sp < sp) {
  971. return sp;
  972. }
  973. memset(buffer, (unsigned char)*depth, sizeof(buffer));
  974. return stack_overflow(min_sp, max_sp, depth) + buffer[0];
  975. }
  976. static PyObject *
  977. faulthandler_stack_overflow(PyObject *self)
  978. {
  979. size_t depth, size;
  980. Py_uintptr_t sp = (Py_uintptr_t)&depth;
  981. Py_uintptr_t min_sp;
  982. Py_uintptr_t max_sp;
  983. Py_uintptr_t stop;
  984. faulthandler_suppress_crash_report();
  985. depth = 0;
  986. if (sp > STACK_OVERFLOW_MAX_SIZE)
  987. min_sp = sp - STACK_OVERFLOW_MAX_SIZE;
  988. else
  989. min_sp = 0;
  990. max_sp = sp + STACK_OVERFLOW_MAX_SIZE;
  991. stop = stack_overflow(min_sp, max_sp, &depth);
  992. if (sp < stop)
  993. size = stop - sp;
  994. else
  995. size = sp - stop;
  996. PyErr_Format(PyExc_RuntimeError,
  997. "unable to raise a stack overflow (allocated %zu bytes "
  998. "on the stack, %zu recursive calls)",
  999. size, depth);
  1000. return NULL;
  1001. }
  1002. #if PY_MAJOR_VERSION >= 3
  1003. static int
  1004. faulthandler_traverse(PyObject *module, visitproc visit, void *arg)
  1005. {
  1006. #ifdef FAULTHANDLER_USER
  1007. unsigned int signum;
  1008. #endif
  1009. #ifdef FAULTHANDLER_LATER
  1010. Py_VISIT(fault_alarm.file);
  1011. #endif
  1012. #ifdef FAULTHANDLER_USER
  1013. if (user_signals != NULL) {
  1014. for (signum=0; signum < NSIG; signum++)
  1015. Py_VISIT(user_signals[signum].file);
  1016. }
  1017. #endif
  1018. Py_VISIT(fatal_error.file);
  1019. return 0;
  1020. }
  1021. #endif
  1022. #ifdef MS_WINDOWS
  1023. static PyObject *
  1024. faulthandler_raise_exception(PyObject *self, PyObject *args)
  1025. {
  1026. unsigned int code, flags = 0;
  1027. if (!PyArg_ParseTuple(args, "I|I:_raise_exception", &code, &flags))
  1028. return NULL;
  1029. RaiseException(code, flags, 0, NULL);
  1030. Py_RETURN_NONE;
  1031. }
  1032. #endif
  1033. PyDoc_STRVAR(module_doc,
  1034. "faulthandler module.");
  1035. static PyMethodDef module_methods[] = {
  1036. {"enable",
  1037. (PyCFunction)faulthandler_enable, METH_VARARGS|METH_KEYWORDS,
  1038. PyDoc_STR("enable(file=sys.stderr, all_threads=True): "
  1039. "enable the fault handler")},
  1040. {"disable", (PyCFunction)faulthandler_disable_py, METH_NOARGS,
  1041. PyDoc_STR("disable(): disable the fault handler")},
  1042. {"is_enabled", (PyCFunction)faulthandler_is_enabled, METH_NOARGS,
  1043. PyDoc_STR("is_enabled()->bool: check if the handler is enabled")},
  1044. {"dump_traceback",
  1045. (PyCFunction)faulthandler_dump_traceback_py, METH_VARARGS|METH_KEYWORDS,
  1046. PyDoc_STR("dump_traceback(file=sys.stderr, all_threads=True): "
  1047. "dump the traceback of the current thread, or of all threads "
  1048. "if all_threads is True, into file")},
  1049. #ifdef FAULTHANDLER_LATER
  1050. {"dump_traceback_later",
  1051. (PyCFunction)faulthandler_dump_traceback_later, METH_VARARGS|METH_KEYWORDS,
  1052. PyDoc_STR("dump_traceback_later(timeout, repeat=False, file=sys.stderrn, exit=False):\n"
  1053. "dump the traceback of all threads in timeout seconds,\n"
  1054. "or each timeout seconds if repeat is True. If exit is True, "
  1055. "call _exit(1) which is not safe.")},
  1056. {"cancel_dump_traceback_later",
  1057. (PyCFunction)faulthandler_cancel_dump_traceback_later_py, METH_NOARGS,
  1058. PyDoc_STR("cancel_dump_traceback_later():\ncancel the previous call "
  1059. "to dump_traceback_later().")},
  1060. #endif
  1061. #ifdef FAULTHANDLER_USER
  1062. {"register",
  1063. (PyCFunction)faulthandler_register_py, METH_VARARGS|METH_KEYWORDS,
  1064. PyDoc_STR("register(signum, file=sys.stderr, all_threads=True, chain=False): "
  1065. "register an handler for the signal 'signum': dump the "
  1066. "traceback of the current thread, or of all threads if "
  1067. "all_threads is True, into file")},
  1068. {"unregister",
  1069. faulthandler_unregister_py, METH_VARARGS|METH_KEYWORDS,
  1070. PyDoc_STR("unregister(signum): unregister the handler of the signal "
  1071. "'signum' registered by register()")},
  1072. #endif
  1073. {"_read_null", faulthandler_read_null, METH_NOARGS,
  1074. PyDoc_STR("_read_null(): read from NULL, raise "
  1075. "a SIGSEGV or SIGBUS signal depending on the platform")},
  1076. {"_sigsegv", faulthandler_sigsegv, METH_VARARGS,
  1077. PyDoc_STR("_sigsegv(release_gil=False): raise a SIGSEGV signal")},
  1078. {"_sigabrt", faulthandler_sigabrt, METH_NOARGS,
  1079. PyDoc_STR("_sigabrt(): raise a SIGABRT signal")},
  1080. {"_sigfpe", (PyCFunction)faulthandler_sigfpe, METH_NOARGS,
  1081. PyDoc_STR("_sigfpe(): raise a SIGFPE signal")},
  1082. {"_raise_signal", (PyCFunction)faulthandler_raise_signal, METH_VARARGS,
  1083. PyDoc_STR("raise_signal(signum): raise a signal")},
  1084. {"_fatal_error", faulthandler_fatal_error_py, METH_VARARGS,
  1085. PyDoc_STR("_fatal_error(message): call Py_FatalError(message)")},
  1086. {"_stack_overflow", (PyCFunction)faulthandler_stack_overflow, METH_NOARGS,
  1087. PyDoc_STR("_stack_overflow(): recursive call to raise a stack overflow")},
  1088. #ifdef MS_WINDOWS
  1089. {"_raise_exception", faulthandler_raise_exception, METH_VARARGS,
  1090. PyDoc_STR("raise_exception(code, flags=0): Call RaiseException(code, flags).")},
  1091. #endif
  1092. {NULL, NULL} /* sentinel */
  1093. };
  1094. #if PY_MAJOR_VERSION >= 3
  1095. static struct PyModuleDef module_def = {
  1096. PyModuleDef_HEAD_INIT,
  1097. "faulthandler",
  1098. module_doc,
  1099. 0, /* non negative size to be able to unload the module */
  1100. module_methods,
  1101. NULL,
  1102. faulthandler_traverse,
  1103. NULL,
  1104. NULL
  1105. };
  1106. #endif
  1107. PyMODINIT_FUNC
  1108. #if PY_MAJOR_VERSION >= 3
  1109. PyInit_faulthandler(void)
  1110. #else
  1111. initfaulthandler(void)
  1112. #endif
  1113. {
  1114. PyObject *m, *version;
  1115. #ifdef HAVE_SIGALTSTACK
  1116. int err;
  1117. #endif
  1118. #if PY_MAJOR_VERSION >= 3
  1119. m = PyModule_Create(&module_def);
  1120. #else
  1121. m = Py_InitModule3("faulthandler", module_methods, module_doc);
  1122. #endif
  1123. if (m == NULL) {
  1124. #if PY_MAJOR_VERSION >= 3
  1125. return NULL;
  1126. #else
  1127. return;
  1128. #endif
  1129. }
  1130. #ifdef MS_WINDOWS
  1131. /* RaiseException() flags */
  1132. if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE",
  1133. EXCEPTION_NONCONTINUABLE))
  1134. goto error;
  1135. if (PyModule_AddIntConstant(m, "_EXCEPTION_NONCONTINUABLE_EXCEPTION",
  1136. EXCEPTION_NONCONTINUABLE_EXCEPTION))
  1137. goto error;
  1138. #endif
  1139. #ifdef HAVE_SIGALTSTACK
  1140. /* Try to allocate an alternate stack for faulthandler() signal handler to
  1141. * be able to allocate memory on the stack, even on a stack overflow. If it
  1142. * fails, ignore the error. */
  1143. stack.ss_flags = 0;
  1144. /* bpo-21131: allocate dedicated stack of SIGSTKSZ*2 bytes, instead of just
  1145. SIGSTKSZ bytes. Calling the previous signal handler in faulthandler
  1146. signal handler uses more than SIGSTKSZ bytes of stack memory on some
  1147. platforms. */
  1148. stack.ss_size = SIGSTKSZ * 2;
  1149. stack.ss_sp = PyMem_Malloc(stack.ss_size);
  1150. if (stack.ss_sp != NULL) {
  1151. err = sigaltstack(&stack, NULL);
  1152. if (err) {
  1153. PyMem_Free(stack.ss_sp);
  1154. stack.ss_sp = NULL;
  1155. }
  1156. }
  1157. #endif
  1158. (void)Py_AtExit(faulthandler_unload);
  1159. version = Py_BuildValue("(ii)", VERSION >> 8, VERSION & 0xFF);
  1160. if (version == NULL)
  1161. goto error;
  1162. PyModule_AddObject(m, "version", version);
  1163. #if PY_MAJOR_VERSION >= 3
  1164. version = PyUnicode_FromFormat("%i.%i", VERSION >> 8, VERSION & 0xFF);
  1165. #else
  1166. version = PyString_FromFormat("%i.%i", VERSION >> 8, VERSION & 0xFF);
  1167. #endif
  1168. if (version == NULL)
  1169. goto error;
  1170. PyModule_AddObject(m, "__version__", version);
  1171. #if PY_MAJOR_VERSION >= 3
  1172. return m;
  1173. #else
  1174. return;
  1175. #endif
  1176. error:
  1177. #if PY_MAJOR_VERSION >= 3
  1178. Py_DECREF(m);
  1179. return NULL;
  1180. #else
  1181. return;
  1182. #endif
  1183. }
  1184. static void
  1185. faulthandler_unload(void)
  1186. {
  1187. #ifdef FAULTHANDLER_USER
  1188. unsigned int signum;
  1189. #endif
  1190. #ifdef FAULTHANDLER_LATER
  1191. /* later */
  1192. alarm(0);
  1193. if (fault_alarm.header != NULL) {
  1194. free(fault_alarm.header);
  1195. fault_alarm.header = NULL;
  1196. }
  1197. /* Don't call Py_CLEAR(fault_alarm.file): this function is called too late,
  1198. by Py_AtExit(). Destroy a Python object here raise strange errors. */
  1199. #endif
  1200. #ifdef FAULTHANDLER_USER
  1201. /* user */
  1202. if (user_signals != NULL) {
  1203. for (signum=0; signum < NSIG; signum++) {
  1204. faulthandler_unregister(&user_signals[signum], signum);
  1205. /* Don't call Py_CLEAR(user->file): this function is called too late,
  1206. by Py_AtExit(). Destroy a Python object here raise strange
  1207. errors. */
  1208. }
  1209. PyMem_Free(user_signals);
  1210. user_signals = NULL;
  1211. }
  1212. #endif
  1213. /* don't release file: faulthandler_unload_fatal_error()
  1214. is called too late */
  1215. fatal_error.file = NULL;
  1216. faulthandler_disable();
  1217. #ifdef HAVE_SIGALTSTACK
  1218. if (stack.ss_sp != NULL) {
  1219. PyMem_Free(stack.ss_sp);
  1220. stack.ss_sp = NULL;
  1221. }
  1222. #endif
  1223. }