You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2063 lines
60 KiB

  1. /* Python interpreter top-level routines, including init/exit */
  2. #include "Python.h"
  3. #include "Python-ast.h"
  4. #undef Yield /* undefine macro conflicting with winbase.h */
  5. #include "grammar.h"
  6. #include "node.h"
  7. #include "token.h"
  8. #include "parsetok.h"
  9. #include "errcode.h"
  10. #include "code.h"
  11. #include "symtable.h"
  12. #include "ast.h"
  13. #include "marshal.h"
  14. #include "osdefs.h"
  15. #include <locale.h>
  16. #ifdef HAVE_SIGNAL_H
  17. #include <signal.h>
  18. #endif
  19. #ifdef MS_WINDOWS
  20. #include "malloc.h" /* for alloca */
  21. #endif
  22. #ifdef HAVE_LANGINFO_H
  23. #include <langinfo.h>
  24. #endif
  25. #ifdef MS_WINDOWS
  26. #undef BYTE
  27. #include "windows.h"
  28. extern PyTypeObject PyWindowsConsoleIO_Type;
  29. #define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
  30. #endif
  31. _Py_IDENTIFIER(flush);
  32. _Py_IDENTIFIER(name);
  33. _Py_IDENTIFIER(stdin);
  34. _Py_IDENTIFIER(stdout);
  35. _Py_IDENTIFIER(stderr);
  36. #ifdef __cplusplus
  37. extern "C" {
  38. #endif
  39. extern wchar_t *Py_GetPath(void);
  40. extern grammar _PyParser_Grammar; /* From graminit.c */
  41. /* Forward */
  42. static void initmain(PyInterpreterState *interp);
  43. static int initfsencoding(PyInterpreterState *interp);
  44. static void initsite(void);
  45. static int initstdio(void);
  46. static void initsigs(void);
  47. static void call_py_exitfuncs(void);
  48. static void wait_for_thread_shutdown(void);
  49. static void call_ll_exitfuncs(void);
  50. extern int _PyUnicode_Init(void);
  51. extern int _PyStructSequence_Init(void);
  52. extern void _PyUnicode_Fini(void);
  53. extern int _PyLong_Init(void);
  54. extern void PyLong_Fini(void);
  55. extern int _PyFaulthandler_Init(void);
  56. extern void _PyFaulthandler_Fini(void);
  57. extern void _PyHash_Fini(void);
  58. extern int _PyTraceMalloc_Init(void);
  59. extern int _PyTraceMalloc_Fini(void);
  60. extern void _Py_ReadyTypes(void);
  61. #ifdef WITH_THREAD
  62. extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
  63. extern void _PyGILState_Fini(void);
  64. #endif /* WITH_THREAD */
  65. /* Global configuration variable declarations are in pydebug.h */
  66. /* XXX (ncoghlan): move those declarations to pylifecycle.h? */
  67. int Py_DebugFlag; /* Needed by parser.c */
  68. int Py_VerboseFlag; /* Needed by import.c */
  69. int Py_QuietFlag; /* Needed by sysmodule.c */
  70. int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
  71. int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
  72. int Py_OptimizeFlag = 0; /* Needed by compile.c */
  73. int Py_NoSiteFlag; /* Suppress 'import site' */
  74. int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
  75. int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
  76. int Py_FrozenFlag; /* Needed by getpath.c */
  77. int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
  78. int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
  79. int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
  80. int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
  81. int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
  82. int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
  83. #ifdef MS_WINDOWS
  84. int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
  85. int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
  86. #endif
  87. PyThreadState *_Py_Finalizing = NULL;
  88. /* Hack to force loading of object files */
  89. int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
  90. PyOS_mystrnicmp; /* Python/pystrcmp.o */
  91. /* PyModule_GetWarningsModule is no longer necessary as of 2.6
  92. since _warnings is builtin. This API should not be used. */
  93. PyObject *
  94. PyModule_GetWarningsModule(void)
  95. {
  96. return PyImport_ImportModule("warnings");
  97. }
  98. /* APIs to access the initialization flags
  99. *
  100. * Can be called prior to Py_Initialize.
  101. */
  102. int _Py_CoreInitialized = 0;
  103. int _Py_Initialized = 0;
  104. int
  105. _Py_IsCoreInitialized(void)
  106. {
  107. return _Py_CoreInitialized;
  108. }
  109. int
  110. Py_IsInitialized(void)
  111. {
  112. return _Py_Initialized;
  113. }
  114. /* Helper to allow an embedding application to override the normal
  115. * mechanism that attempts to figure out an appropriate IO encoding
  116. */
  117. static char *_Py_StandardStreamEncoding = NULL;
  118. static char *_Py_StandardStreamErrors = NULL;
  119. int
  120. Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
  121. {
  122. if (Py_IsInitialized()) {
  123. /* This is too late to have any effect */
  124. return -1;
  125. }
  126. /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
  127. * initialised yet.
  128. *
  129. * However, the raw memory allocators are initialised appropriately
  130. * as C static variables, so _PyMem_RawStrdup is OK even though
  131. * Py_Initialize hasn't been called yet.
  132. */
  133. if (encoding) {
  134. _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
  135. if (!_Py_StandardStreamEncoding) {
  136. return -2;
  137. }
  138. }
  139. if (errors) {
  140. _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
  141. if (!_Py_StandardStreamErrors) {
  142. if (_Py_StandardStreamEncoding) {
  143. PyMem_RawFree(_Py_StandardStreamEncoding);
  144. }
  145. return -3;
  146. }
  147. }
  148. #ifdef MS_WINDOWS
  149. if (_Py_StandardStreamEncoding) {
  150. /* Overriding the stream encoding implies legacy streams */
  151. Py_LegacyWindowsStdioFlag = 1;
  152. }
  153. #endif
  154. return 0;
  155. }
  156. /* Global initializations. Can be undone by Py_FinalizeEx(). Don't
  157. call this twice without an intervening Py_FinalizeEx() call. When
  158. initializations fail, a fatal error is issued and the function does
  159. not return. On return, the first thread and interpreter state have
  160. been created.
  161. Locking: you must hold the interpreter lock while calling this.
  162. (If the lock has not yet been initialized, that's equivalent to
  163. having the lock, but you cannot use multiple threads.)
  164. */
  165. static int
  166. add_flag(int flag, const char *envs)
  167. {
  168. int env = atoi(envs);
  169. if (flag < env)
  170. flag = env;
  171. if (flag < 1)
  172. flag = 1;
  173. return flag;
  174. }
  175. static char*
  176. get_codec_name(const char *encoding)
  177. {
  178. const char *name_utf8;
  179. char *name_str;
  180. PyObject *codec, *name = NULL;
  181. codec = _PyCodec_Lookup(encoding);
  182. if (!codec)
  183. goto error;
  184. name = _PyObject_GetAttrId(codec, &PyId_name);
  185. Py_CLEAR(codec);
  186. if (!name)
  187. goto error;
  188. name_utf8 = PyUnicode_AsUTF8(name);
  189. if (name_utf8 == NULL)
  190. goto error;
  191. name_str = _PyMem_RawStrdup(name_utf8);
  192. Py_DECREF(name);
  193. if (name_str == NULL) {
  194. PyErr_NoMemory();
  195. return NULL;
  196. }
  197. return name_str;
  198. error:
  199. Py_XDECREF(codec);
  200. Py_XDECREF(name);
  201. return NULL;
  202. }
  203. static char*
  204. get_locale_encoding(void)
  205. {
  206. #ifdef MS_WINDOWS
  207. char codepage[100];
  208. PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
  209. return get_codec_name(codepage);
  210. #elif defined(HAVE_LANGINFO_H) && defined(CODESET)
  211. char* codeset = nl_langinfo(CODESET);
  212. if (!codeset || codeset[0] == '\0') {
  213. PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
  214. return NULL;
  215. }
  216. return get_codec_name(codeset);
  217. #elif defined(__ANDROID__)
  218. return get_codec_name("UTF-8");
  219. #else
  220. PyErr_SetNone(PyExc_NotImplementedError);
  221. return NULL;
  222. #endif
  223. }
  224. static void
  225. initimport(PyInterpreterState *interp, PyObject *sysmod)
  226. {
  227. PyObject *importlib;
  228. PyObject *impmod;
  229. PyObject *sys_modules;
  230. PyObject *value;
  231. /* Import _importlib through its frozen version, _frozen_importlib. */
  232. if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
  233. Py_FatalError("Py_Initialize: can't import _frozen_importlib");
  234. }
  235. else if (Py_VerboseFlag) {
  236. PySys_FormatStderr("import _frozen_importlib # frozen\n");
  237. }
  238. importlib = PyImport_AddModule("_frozen_importlib");
  239. if (importlib == NULL) {
  240. Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
  241. "sys.modules");
  242. }
  243. interp->importlib = importlib;
  244. Py_INCREF(interp->importlib);
  245. interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
  246. if (interp->import_func == NULL)
  247. Py_FatalError("Py_Initialize: __import__ not found");
  248. Py_INCREF(interp->import_func);
  249. /* Import the _imp module */
  250. impmod = PyInit_imp();
  251. if (impmod == NULL) {
  252. Py_FatalError("Py_Initialize: can't import _imp");
  253. }
  254. else if (Py_VerboseFlag) {
  255. PySys_FormatStderr("import _imp # builtin\n");
  256. }
  257. sys_modules = PyImport_GetModuleDict();
  258. if (Py_VerboseFlag) {
  259. PySys_FormatStderr("import sys # builtin\n");
  260. }
  261. if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
  262. Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
  263. }
  264. /* Install importlib as the implementation of import */
  265. value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
  266. if (value != NULL) {
  267. Py_DECREF(value);
  268. value = PyObject_CallMethod(importlib,
  269. "_install_external_importers", "");
  270. }
  271. if (value == NULL) {
  272. PyErr_Print();
  273. Py_FatalError("Py_Initialize: importlib install failed");
  274. }
  275. Py_DECREF(value);
  276. Py_DECREF(impmod);
  277. _PyImportZip_Init();
  278. }
  279. static void
  280. initexternalimport(PyInterpreterState *interp)
  281. {
  282. PyObject *value;
  283. value = PyObject_CallMethod(interp->importlib,
  284. "_install_external_importers", "");
  285. if (value == NULL) {
  286. PyErr_Print();
  287. Py_FatalError("Py_EndInitialization: external importer setup failed");
  288. }
  289. Py_DECREF(value);
  290. }
  291. /* Helper functions to better handle the legacy C locale
  292. *
  293. * The legacy C locale assumes ASCII as the default text encoding, which
  294. * causes problems not only for the CPython runtime, but also other
  295. * components like GNU readline.
  296. *
  297. * Accordingly, when the CLI detects it, it attempts to coerce it to a
  298. * more capable UTF-8 based alternative as follows:
  299. *
  300. * if (_Py_LegacyLocaleDetected()) {
  301. * _Py_CoerceLegacyLocale();
  302. * }
  303. *
  304. * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
  305. *
  306. * Locale coercion also impacts the default error handler for the standard
  307. * streams: while the usual default is "strict", the default for the legacy
  308. * C locale and for any of the coercion target locales is "surrogateescape".
  309. */
  310. int
  311. _Py_LegacyLocaleDetected(void)
  312. {
  313. #ifndef MS_WINDOWS
  314. /* On non-Windows systems, the C locale is considered a legacy locale */
  315. /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
  316. * the POSIX locale as a simple alias for the C locale, so
  317. * we may also want to check for that explicitly.
  318. */
  319. const char *ctype_loc = setlocale(LC_CTYPE, NULL);
  320. return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
  321. #else
  322. /* Windows uses code pages instead of locales, so no locale is legacy */
  323. return 0;
  324. #endif
  325. }
  326. static const char *_C_LOCALE_WARNING =
  327. "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
  328. "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
  329. "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
  330. "locales is recommended.\n";
  331. static int
  332. _legacy_locale_warnings_enabled(void)
  333. {
  334. const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
  335. return (coerce_c_locale != NULL &&
  336. strncmp(coerce_c_locale, "warn", 5) == 0);
  337. }
  338. static void
  339. _emit_stderr_warning_for_legacy_locale(void)
  340. {
  341. if (_legacy_locale_warnings_enabled()) {
  342. if (_Py_LegacyLocaleDetected()) {
  343. fprintf(stderr, "%s", _C_LOCALE_WARNING);
  344. }
  345. }
  346. }
  347. typedef struct _CandidateLocale {
  348. const char *locale_name; /* The locale to try as a coercion target */
  349. } _LocaleCoercionTarget;
  350. static _LocaleCoercionTarget _TARGET_LOCALES[] = {
  351. {"C.UTF-8"},
  352. {"C.utf8"},
  353. {"UTF-8"},
  354. {NULL}
  355. };
  356. static char *
  357. get_default_standard_stream_error_handler(void)
  358. {
  359. const char *ctype_loc = setlocale(LC_CTYPE, NULL);
  360. if (ctype_loc != NULL) {
  361. /* "surrogateescape" is the default in the legacy C locale */
  362. if (strcmp(ctype_loc, "C") == 0) {
  363. return "surrogateescape";
  364. }
  365. #ifdef PY_COERCE_C_LOCALE
  366. /* "surrogateescape" is the default in locale coercion target locales */
  367. const _LocaleCoercionTarget *target = NULL;
  368. for (target = _TARGET_LOCALES; target->locale_name; target++) {
  369. if (strcmp(ctype_loc, target->locale_name) == 0) {
  370. return "surrogateescape";
  371. }
  372. }
  373. #endif
  374. }
  375. /* Otherwise return NULL to request the typical default error handler */
  376. return NULL;
  377. }
  378. #ifdef PY_COERCE_C_LOCALE
  379. static const char *_C_LOCALE_COERCION_WARNING =
  380. "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
  381. "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
  382. static void
  383. _coerce_default_locale_settings(const _LocaleCoercionTarget *target)
  384. {
  385. const char *newloc = target->locale_name;
  386. /* Reset locale back to currently configured defaults */
  387. setlocale(LC_ALL, "");
  388. /* Set the relevant locale environment variable */
  389. if (setenv("LC_CTYPE", newloc, 1)) {
  390. fprintf(stderr,
  391. "Error setting LC_CTYPE, skipping C locale coercion\n");
  392. return;
  393. }
  394. if (_legacy_locale_warnings_enabled()) {
  395. fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
  396. }
  397. /* Reconfigure with the overridden environment variables */
  398. setlocale(LC_ALL, "");
  399. }
  400. #endif
  401. void
  402. _Py_CoerceLegacyLocale(void)
  403. {
  404. #ifdef PY_COERCE_C_LOCALE
  405. /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
  406. * the locale settings *before* we try to do anything with the command
  407. * line arguments. For cross-platform debugging purposes, we also need
  408. * to give end users a way to force even scripts that are otherwise
  409. * isolated from their environment to use the legacy ASCII-centric C
  410. * locale.
  411. *
  412. * Ignoring -E and -I is safe from a security perspective, as we only use
  413. * the setting to turn *off* the implicit locale coercion, and anyone with
  414. * access to the process environment already has the ability to set
  415. * `LC_ALL=C` to override the C level locale settings anyway.
  416. */
  417. const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
  418. if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
  419. /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
  420. const char *locale_override = getenv("LC_ALL");
  421. if (locale_override == NULL || *locale_override == '\0') {
  422. /* LC_ALL is also not set (or is set to an empty string) */
  423. const _LocaleCoercionTarget *target = NULL;
  424. for (target = _TARGET_LOCALES; target->locale_name; target++) {
  425. const char *new_locale = setlocale(LC_CTYPE,
  426. target->locale_name);
  427. if (new_locale != NULL) {
  428. #if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
  429. /* Also ensure that nl_langinfo works in this locale */
  430. char *codeset = nl_langinfo(CODESET);
  431. if (!codeset || *codeset == '\0') {
  432. /* CODESET is not set or empty, so skip coercion */
  433. new_locale = NULL;
  434. setlocale(LC_CTYPE, "");
  435. continue;
  436. }
  437. #endif
  438. /* Successfully configured locale, so make it the default */
  439. _coerce_default_locale_settings(target);
  440. return;
  441. }
  442. }
  443. }
  444. }
  445. /* No C locale warning here, as Py_Initialize will emit one later */
  446. #endif
  447. }
  448. /* Global initializations. Can be undone by Py_Finalize(). Don't
  449. call this twice without an intervening Py_Finalize() call.
  450. Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
  451. must have a corresponding call to Py_Finalize.
  452. Locking: you must hold the interpreter lock while calling these APIs.
  453. (If the lock has not yet been initialized, that's equivalent to
  454. having the lock, but you cannot use multiple threads.)
  455. */
  456. /* Begin interpreter initialization
  457. *
  458. * On return, the first thread and interpreter state have been created,
  459. * but the compiler, signal handling, multithreading and
  460. * multiple interpreter support, and codec infrastructure are not yet
  461. * available.
  462. *
  463. * The import system will support builtin and frozen modules only.
  464. * The only supported io is writing to sys.stderr
  465. *
  466. * If any operation invoked by this function fails, a fatal error is
  467. * issued and the function does not return.
  468. *
  469. * Any code invoked from this function should *not* assume it has access
  470. * to the Python C API (unless the API is explicitly listed as being
  471. * safe to call without calling Py_Initialize first)
  472. */
  473. /* TODO: Progressively move functionality from Py_BeginInitialization to
  474. * Py_ReadConfig and Py_EndInitialization
  475. */
  476. void _Py_InitializeCore(const _PyCoreConfig *config)
  477. {
  478. PyInterpreterState *interp;
  479. PyThreadState *tstate;
  480. PyObject *bimod, *sysmod, *pstderr;
  481. char *p;
  482. _PyCoreConfig core_config = _PyCoreConfig_INIT;
  483. _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
  484. if (config != NULL) {
  485. core_config = *config;
  486. }
  487. if (_Py_Initialized) {
  488. Py_FatalError("Py_InitializeCore: main interpreter already initialized");
  489. }
  490. if (_Py_CoreInitialized) {
  491. Py_FatalError("Py_InitializeCore: runtime core already initialized");
  492. }
  493. /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
  494. * threads behave a little more gracefully at interpreter shutdown.
  495. * We clobber it here so the new interpreter can start with a clean
  496. * slate.
  497. *
  498. * However, this may still lead to misbehaviour if there are daemon
  499. * threads still hanging around from a previous Py_Initialize/Finalize
  500. * pair :(
  501. */
  502. _Py_Finalizing = NULL;
  503. #ifdef __ANDROID__
  504. /* Passing "" to setlocale() on Android requests the C locale rather
  505. * than checking environment variables, so request C.UTF-8 explicitly
  506. */
  507. setlocale(LC_CTYPE, "C.UTF-8");
  508. #else
  509. #ifndef MS_WINDOWS
  510. /* Set up the LC_CTYPE locale, so we can obtain
  511. the locale's charset without having to switch
  512. locales. */
  513. setlocale(LC_CTYPE, "");
  514. _emit_stderr_warning_for_legacy_locale();
  515. #endif
  516. #endif
  517. if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
  518. Py_DebugFlag = add_flag(Py_DebugFlag, p);
  519. if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
  520. Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
  521. if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
  522. Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
  523. if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
  524. Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
  525. /* The variable is only tested for existence here;
  526. _Py_HashRandomization_Init will check its value further. */
  527. if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
  528. Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
  529. #ifdef MS_WINDOWS
  530. if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
  531. Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
  532. if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
  533. Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
  534. #endif
  535. _Py_HashRandomization_Init(&core_config);
  536. if (!core_config.use_hash_seed || core_config.hash_seed) {
  537. /* Random or non-zero hash seed */
  538. Py_HashRandomizationFlag = 1;
  539. }
  540. _PyInterpreterState_Init();
  541. interp = PyInterpreterState_New();
  542. if (interp == NULL)
  543. Py_FatalError("Py_InitializeCore: can't make main interpreter");
  544. interp->core_config = core_config;
  545. interp->config = preinit_config;
  546. tstate = PyThreadState_New(interp);
  547. if (tstate == NULL)
  548. Py_FatalError("Py_InitializeCore: can't make first thread");
  549. (void) PyThreadState_Swap(tstate);
  550. #ifdef WITH_THREAD
  551. /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
  552. destroying the GIL might fail when it is being referenced from
  553. another running thread (see issue #9901).
  554. Instead we destroy the previously created GIL here, which ensures
  555. that we can call Py_Initialize / Py_FinalizeEx multiple times. */
  556. _PyEval_FiniThreads();
  557. /* Auto-thread-state API */
  558. _PyGILState_Init(interp, tstate);
  559. #endif /* WITH_THREAD */
  560. _Py_ReadyTypes();
  561. if (!_PyFrame_Init())
  562. Py_FatalError("Py_InitializeCore: can't init frames");
  563. if (!_PyLong_Init())
  564. Py_FatalError("Py_InitializeCore: can't init longs");
  565. if (!PyByteArray_Init())
  566. Py_FatalError("Py_InitializeCore: can't init bytearray");
  567. if (!_PyFloat_Init())
  568. Py_FatalError("Py_InitializeCore: can't init float");
  569. interp->modules = PyDict_New();
  570. if (interp->modules == NULL)
  571. Py_FatalError("Py_InitializeCore: can't make modules dictionary");
  572. /* Init Unicode implementation; relies on the codec registry */
  573. if (_PyUnicode_Init() < 0)
  574. Py_FatalError("Py_InitializeCore: can't initialize unicode");
  575. if (_PyStructSequence_Init() < 0)
  576. Py_FatalError("Py_InitializeCore: can't initialize structseq");
  577. bimod = _PyBuiltin_Init();
  578. if (bimod == NULL)
  579. Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
  580. _PyImport_FixupBuiltin(bimod, "builtins");
  581. interp->builtins = PyModule_GetDict(bimod);
  582. if (interp->builtins == NULL)
  583. Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
  584. Py_INCREF(interp->builtins);
  585. /* initialize builtin exceptions */
  586. _PyExc_Init(bimod);
  587. sysmod = _PySys_BeginInit();
  588. if (sysmod == NULL)
  589. Py_FatalError("Py_InitializeCore: can't initialize sys");
  590. interp->sysdict = PyModule_GetDict(sysmod);
  591. if (interp->sysdict == NULL)
  592. Py_FatalError("Py_InitializeCore: can't initialize sys dict");
  593. Py_INCREF(interp->sysdict);
  594. _PyImport_FixupBuiltin(sysmod, "sys");
  595. PyDict_SetItemString(interp->sysdict, "modules",
  596. interp->modules);
  597. /* Set up a preliminary stderr printer until we have enough
  598. infrastructure for the io module in place. */
  599. pstderr = PyFile_NewStdPrinter(fileno(stderr));
  600. if (pstderr == NULL)
  601. Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
  602. _PySys_SetObjectId(&PyId_stderr, pstderr);
  603. PySys_SetObject("__stderr__", pstderr);
  604. Py_DECREF(pstderr);
  605. _PyImport_Init();
  606. _PyImportHooks_Init();
  607. /* Initialize _warnings. */
  608. _PyWarnings_Init();
  609. /* This call sets up builtin and frozen import support */
  610. if (!interp->core_config._disable_importlib) {
  611. initimport(interp, sysmod);
  612. }
  613. /* Only when we get here is the runtime core fully initialized */
  614. _Py_CoreInitialized = 1;
  615. }
  616. /* Read configuration settings from standard locations
  617. *
  618. * This function doesn't make any changes to the interpreter state - it
  619. * merely populates any missing configuration settings. This allows an
  620. * embedding application to completely override a config option by
  621. * setting it before calling this function, or else modify the default
  622. * setting before passing the fully populated config to Py_EndInitialization.
  623. *
  624. * More advanced selective initialization tricks are possible by calling
  625. * this function multiple times with various preconfigured settings.
  626. */
  627. int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
  628. {
  629. /* Signal handlers are installed by default */
  630. if (config->install_signal_handlers < 0) {
  631. config->install_signal_handlers = 1;
  632. }
  633. return 0;
  634. }
  635. /* Update interpreter state based on supplied configuration settings
  636. *
  637. * After calling this function, most of the restrictions on the interpreter
  638. * are lifted. The only remaining incomplete settings are those related
  639. * to the main module (sys.argv[0], __main__ metadata)
  640. *
  641. * Calling this when the interpreter is not initializing, is already
  642. * initialized or without a valid current thread state is a fatal error.
  643. * Other errors should be reported as normal Python exceptions with a
  644. * non-zero return code.
  645. */
  646. int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
  647. {
  648. PyInterpreterState *interp;
  649. PyThreadState *tstate;
  650. if (!_Py_CoreInitialized) {
  651. Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
  652. }
  653. if (_Py_Initialized) {
  654. Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
  655. }
  656. /* Get current thread state and interpreter pointer */
  657. tstate = PyThreadState_GET();
  658. if (!tstate)
  659. Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
  660. interp = tstate->interp;
  661. if (!interp)
  662. Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
  663. /* Now finish configuring the main interpreter */
  664. interp->config = *config;
  665. if (interp->core_config._disable_importlib) {
  666. /* Special mode for freeze_importlib: run with no import system
  667. *
  668. * This means anything which needs support from extension modules
  669. * or pure Python code in the standard library won't work.
  670. */
  671. _Py_Initialized = 1;
  672. return 0;
  673. }
  674. /* TODO: Report exceptions rather than fatal errors below here */
  675. if (_PyTime_Init() < 0)
  676. Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
  677. /* Finish setting up the sys module and import system */
  678. /* GetPath may initialize state that _PySys_EndInit locks
  679. in, and so has to be called first. */
  680. /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
  681. PySys_SetPath(Py_GetPath());
  682. if (_PySys_EndInit(interp->sysdict) < 0)
  683. Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
  684. initexternalimport(interp);
  685. /* initialize the faulthandler module */
  686. if (_PyFaulthandler_Init())
  687. Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
  688. if (initfsencoding(interp) < 0)
  689. Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
  690. if (config->install_signal_handlers)
  691. initsigs(); /* Signal handling stuff, including initintr() */
  692. if (_PyTraceMalloc_Init() < 0)
  693. Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
  694. initmain(interp); /* Module __main__ */
  695. if (initstdio() < 0)
  696. Py_FatalError(
  697. "Py_InitializeMainInterpreter: can't initialize sys standard streams");
  698. /* Initialize warnings. */
  699. if (PySys_HasWarnOptions()) {
  700. PyObject *warnings_module = PyImport_ImportModule("warnings");
  701. if (warnings_module == NULL) {
  702. fprintf(stderr, "'import warnings' failed; traceback:\n");
  703. PyErr_Print();
  704. }
  705. Py_XDECREF(warnings_module);
  706. }
  707. _Py_Initialized = 1;
  708. if (!Py_NoSiteFlag)
  709. initsite(); /* Module site */
  710. return 0;
  711. }
  712. #undef _INIT_DEBUG_PRINT
  713. void
  714. _Py_InitializeEx_Private(int install_sigs, int install_importlib)
  715. {
  716. _PyCoreConfig core_config = _PyCoreConfig_INIT;
  717. _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
  718. /* TODO: Moar config options! */
  719. core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
  720. core_config._disable_importlib = !install_importlib;
  721. config.install_signal_handlers = install_sigs;
  722. _Py_InitializeCore(&core_config);
  723. /* TODO: Print any exceptions raised by these operations */
  724. if (_Py_ReadMainInterpreterConfig(&config))
  725. Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
  726. if (_Py_InitializeMainInterpreter(&config))
  727. Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
  728. }
  729. void
  730. Py_InitializeEx(int install_sigs)
  731. {
  732. _Py_InitializeEx_Private(install_sigs, 1);
  733. }
  734. void
  735. Py_Initialize(void)
  736. {
  737. Py_InitializeEx(1);
  738. }
  739. #ifdef COUNT_ALLOCS
  740. extern void dump_counts(FILE*);
  741. #endif
  742. /* Flush stdout and stderr */
  743. static int
  744. file_is_closed(PyObject *fobj)
  745. {
  746. int r;
  747. PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
  748. if (tmp == NULL) {
  749. PyErr_Clear();
  750. return 0;
  751. }
  752. r = PyObject_IsTrue(tmp);
  753. Py_DECREF(tmp);
  754. if (r < 0)
  755. PyErr_Clear();
  756. return r > 0;
  757. }
  758. static int
  759. flush_std_files(void)
  760. {
  761. PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
  762. PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
  763. PyObject *tmp;
  764. int status = 0;
  765. if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
  766. tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
  767. if (tmp == NULL) {
  768. PyErr_WriteUnraisable(fout);
  769. status = -1;
  770. }
  771. else
  772. Py_DECREF(tmp);
  773. }
  774. if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
  775. tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
  776. if (tmp == NULL) {
  777. PyErr_Clear();
  778. status = -1;
  779. }
  780. else
  781. Py_DECREF(tmp);
  782. }
  783. return status;
  784. }
  785. /* Undo the effect of Py_Initialize().
  786. Beware: if multiple interpreter and/or thread states exist, these
  787. are not wiped out; only the current thread and interpreter state
  788. are deleted. But since everything else is deleted, those other
  789. interpreter and thread states should no longer be used.
  790. (XXX We should do better, e.g. wipe out all interpreters and
  791. threads.)
  792. Locking: as above.
  793. */
  794. int
  795. Py_FinalizeEx(void)
  796. {
  797. PyInterpreterState *interp;
  798. PyThreadState *tstate;
  799. int status = 0;
  800. if (!_Py_Initialized)
  801. return status;
  802. wait_for_thread_shutdown();
  803. /* The interpreter is still entirely intact at this point, and the
  804. * exit funcs may be relying on that. In particular, if some thread
  805. * or exit func is still waiting to do an import, the import machinery
  806. * expects Py_IsInitialized() to return true. So don't say the
  807. * interpreter is uninitialized until after the exit funcs have run.
  808. * Note that Threading.py uses an exit func to do a join on all the
  809. * threads created thru it, so this also protects pending imports in
  810. * the threads created via Threading.
  811. */
  812. call_py_exitfuncs();
  813. /* Get current thread state and interpreter pointer */
  814. tstate = PyThreadState_GET();
  815. interp = tstate->interp;
  816. /* Remaining threads (e.g. daemon threads) will automatically exit
  817. after taking the GIL (in PyEval_RestoreThread()). */
  818. _Py_Finalizing = tstate;
  819. _Py_Initialized = 0;
  820. _Py_CoreInitialized = 0;
  821. /* Flush sys.stdout and sys.stderr */
  822. if (flush_std_files() < 0) {
  823. status = -1;
  824. }
  825. /* Disable signal handling */
  826. PyOS_FiniInterrupts();
  827. /* Collect garbage. This may call finalizers; it's nice to call these
  828. * before all modules are destroyed.
  829. * XXX If a __del__ or weakref callback is triggered here, and tries to
  830. * XXX import a module, bad things can happen, because Python no
  831. * XXX longer believes it's initialized.
  832. * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
  833. * XXX is easy to provoke that way. I've also seen, e.g.,
  834. * XXX Exception exceptions.ImportError: 'No module named sha'
  835. * XXX in <function callback at 0x008F5718> ignored
  836. * XXX but I'm unclear on exactly how that one happens. In any case,
  837. * XXX I haven't seen a real-life report of either of these.
  838. */
  839. _PyGC_CollectIfEnabled();
  840. #ifdef COUNT_ALLOCS
  841. /* With COUNT_ALLOCS, it helps to run GC multiple times:
  842. each collection might release some types from the type
  843. list, so they become garbage. */
  844. while (_PyGC_CollectIfEnabled() > 0)
  845. /* nothing */;
  846. #endif
  847. /* Destroy all modules */
  848. PyImport_Cleanup();
  849. /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
  850. if (flush_std_files() < 0) {
  851. status = -1;
  852. }
  853. /* Collect final garbage. This disposes of cycles created by
  854. * class definitions, for example.
  855. * XXX This is disabled because it caused too many problems. If
  856. * XXX a __del__ or weakref callback triggers here, Python code has
  857. * XXX a hard time running, because even the sys module has been
  858. * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
  859. * XXX One symptom is a sequence of information-free messages
  860. * XXX coming from threads (if a __del__ or callback is invoked,
  861. * XXX other threads can execute too, and any exception they encounter
  862. * XXX triggers a comedy of errors as subsystem after subsystem
  863. * XXX fails to find what it *expects* to find in sys to help report
  864. * XXX the exception and consequent unexpected failures). I've also
  865. * XXX seen segfaults then, after adding print statements to the
  866. * XXX Python code getting called.
  867. */
  868. #if 0
  869. _PyGC_CollectIfEnabled();
  870. #endif
  871. /* Disable tracemalloc after all Python objects have been destroyed,
  872. so it is possible to use tracemalloc in objects destructor. */
  873. _PyTraceMalloc_Fini();
  874. /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  875. _PyImport_Fini();
  876. /* Cleanup typeobject.c's internal caches. */
  877. _PyType_Fini();
  878. /* unload faulthandler module */
  879. _PyFaulthandler_Fini();
  880. /* Debugging stuff */
  881. #ifdef COUNT_ALLOCS
  882. dump_counts(stderr);
  883. #endif
  884. /* dump hash stats */
  885. _PyHash_Fini();
  886. _PY_DEBUG_PRINT_TOTAL_REFS();
  887. #ifdef Py_TRACE_REFS
  888. /* Display all objects still alive -- this can invoke arbitrary
  889. * __repr__ overrides, so requires a mostly-intact interpreter.
  890. * Alas, a lot of stuff may still be alive now that will be cleaned
  891. * up later.
  892. */
  893. if (Py_GETENV("PYTHONDUMPREFS"))
  894. _Py_PrintReferences(stderr);
  895. #endif /* Py_TRACE_REFS */
  896. /* Clear interpreter state and all thread states. */
  897. PyInterpreterState_Clear(interp);
  898. /* Now we decref the exception classes. After this point nothing
  899. can raise an exception. That's okay, because each Fini() method
  900. below has been checked to make sure no exceptions are ever
  901. raised.
  902. */
  903. _PyExc_Fini();
  904. /* Sundry finalizers */
  905. PyMethod_Fini();
  906. PyFrame_Fini();
  907. PyCFunction_Fini();
  908. PyTuple_Fini();
  909. PyList_Fini();
  910. PySet_Fini();
  911. PyBytes_Fini();
  912. PyByteArray_Fini();
  913. PyLong_Fini();
  914. PyFloat_Fini();
  915. PyDict_Fini();
  916. PySlice_Fini();
  917. _PyGC_Fini();
  918. _Py_HashRandomization_Fini();
  919. _PyArg_Fini();
  920. PyAsyncGen_Fini();
  921. /* Cleanup Unicode implementation */
  922. _PyUnicode_Fini();
  923. /* reset file system default encoding */
  924. if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
  925. PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
  926. Py_FileSystemDefaultEncoding = NULL;
  927. }
  928. /* XXX Still allocated:
  929. - various static ad-hoc pointers to interned strings
  930. - int and float free list blocks
  931. - whatever various modules and libraries allocate
  932. */
  933. PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  934. /* Cleanup auto-thread-state */
  935. #ifdef WITH_THREAD
  936. _PyGILState_Fini();
  937. #endif /* WITH_THREAD */
  938. /* Delete current thread. After this, many C API calls become crashy. */
  939. PyThreadState_Swap(NULL);
  940. PyInterpreterState_Delete(interp);
  941. #ifdef Py_TRACE_REFS
  942. /* Display addresses (& refcnts) of all objects still alive.
  943. * An address can be used to find the repr of the object, printed
  944. * above by _Py_PrintReferences.
  945. */
  946. if (Py_GETENV("PYTHONDUMPREFS"))
  947. _Py_PrintReferenceAddresses(stderr);
  948. #endif /* Py_TRACE_REFS */
  949. #ifdef WITH_PYMALLOC
  950. if (_PyMem_PymallocEnabled()) {
  951. char *opt = Py_GETENV("PYTHONMALLOCSTATS");
  952. if (opt != NULL && *opt != '\0')
  953. _PyObject_DebugMallocStats(stderr);
  954. }
  955. #endif
  956. call_ll_exitfuncs();
  957. return status;
  958. }
  959. void
  960. Py_Finalize(void)
  961. {
  962. Py_FinalizeEx();
  963. }
  964. /* Create and initialize a new interpreter and thread, and return the
  965. new thread. This requires that Py_Initialize() has been called
  966. first.
  967. Unsuccessful initialization yields a NULL pointer. Note that *no*
  968. exception information is available even in this case -- the
  969. exception information is held in the thread, and there is no
  970. thread.
  971. Locking: as above.
  972. */
  973. PyThreadState *
  974. Py_NewInterpreter(void)
  975. {
  976. PyInterpreterState *interp;
  977. PyThreadState *tstate, *save_tstate;
  978. PyObject *bimod, *sysmod;
  979. if (!_Py_Initialized)
  980. Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  981. #ifdef WITH_THREAD
  982. /* Issue #10915, #15751: The GIL API doesn't work with multiple
  983. interpreters: disable PyGILState_Check(). */
  984. _PyGILState_check_enabled = 0;
  985. #endif
  986. interp = PyInterpreterState_New();
  987. if (interp == NULL)
  988. return NULL;
  989. tstate = PyThreadState_New(interp);
  990. if (tstate == NULL) {
  991. PyInterpreterState_Delete(interp);
  992. return NULL;
  993. }
  994. save_tstate = PyThreadState_Swap(tstate);
  995. /* Copy the current interpreter config into the new interpreter */
  996. if (save_tstate != NULL) {
  997. interp->core_config = save_tstate->interp->core_config;
  998. interp->config = save_tstate->interp->config;
  999. } else {
  1000. /* No current thread state, copy from the main interpreter */
  1001. PyInterpreterState *main_interp = PyInterpreterState_Main();
  1002. interp->core_config = main_interp->core_config;
  1003. interp->config = main_interp->config;
  1004. }
  1005. /* XXX The following is lax in error checking */
  1006. interp->modules = PyDict_New();
  1007. bimod = _PyImport_FindBuiltin("builtins");
  1008. if (bimod != NULL) {
  1009. interp->builtins = PyModule_GetDict(bimod);
  1010. if (interp->builtins == NULL)
  1011. goto handle_error;
  1012. Py_INCREF(interp->builtins);
  1013. }
  1014. /* initialize builtin exceptions */
  1015. _PyExc_Init(bimod);
  1016. sysmod = _PyImport_FindBuiltin("sys");
  1017. if (bimod != NULL && sysmod != NULL) {
  1018. PyObject *pstderr;
  1019. interp->sysdict = PyModule_GetDict(sysmod);
  1020. if (interp->sysdict == NULL)
  1021. goto handle_error;
  1022. Py_INCREF(interp->sysdict);
  1023. _PySys_EndInit(interp->sysdict);
  1024. PySys_SetPath(Py_GetPath());
  1025. PyDict_SetItemString(interp->sysdict, "modules",
  1026. interp->modules);
  1027. /* Set up a preliminary stderr printer until we have enough
  1028. infrastructure for the io module in place. */
  1029. pstderr = PyFile_NewStdPrinter(fileno(stderr));
  1030. if (pstderr == NULL)
  1031. Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
  1032. _PySys_SetObjectId(&PyId_stderr, pstderr);
  1033. PySys_SetObject("__stderr__", pstderr);
  1034. Py_DECREF(pstderr);
  1035. _PyImportHooks_Init();
  1036. initimport(interp, sysmod);
  1037. initexternalimport(interp);
  1038. if (initfsencoding(interp) < 0)
  1039. goto handle_error;
  1040. if (initstdio() < 0)
  1041. Py_FatalError(
  1042. "Py_NewInterpreter: can't initialize sys standard streams");
  1043. initmain(interp);
  1044. if (!Py_NoSiteFlag)
  1045. initsite();
  1046. }
  1047. if (!PyErr_Occurred())
  1048. return tstate;
  1049. handle_error:
  1050. /* Oops, it didn't work. Undo it all. */
  1051. PyErr_PrintEx(0);
  1052. PyThreadState_Clear(tstate);
  1053. PyThreadState_Swap(save_tstate);
  1054. PyThreadState_Delete(tstate);
  1055. PyInterpreterState_Delete(interp);
  1056. return NULL;
  1057. }
  1058. /* Delete an interpreter and its last thread. This requires that the
  1059. given thread state is current, that the thread has no remaining
  1060. frames, and that it is its interpreter's only remaining thread.
  1061. It is a fatal error to violate these constraints.
  1062. (Py_FinalizeEx() doesn't have these constraints -- it zaps
  1063. everything, regardless.)
  1064. Locking: as above.
  1065. */
  1066. void
  1067. Py_EndInterpreter(PyThreadState *tstate)
  1068. {
  1069. PyInterpreterState *interp = tstate->interp;
  1070. if (tstate != PyThreadState_GET())
  1071. Py_FatalError("Py_EndInterpreter: thread is not current");
  1072. if (tstate->frame != NULL)
  1073. Py_FatalError("Py_EndInterpreter: thread still has a frame");
  1074. wait_for_thread_shutdown();
  1075. if (tstate != interp->tstate_head || tstate->next != NULL)
  1076. Py_FatalError("Py_EndInterpreter: not the last thread");
  1077. PyImport_Cleanup();
  1078. PyInterpreterState_Clear(interp);
  1079. PyThreadState_Swap(NULL);
  1080. PyInterpreterState_Delete(interp);
  1081. }
  1082. #ifdef MS_WINDOWS
  1083. static wchar_t *progname = L"python";
  1084. #else
  1085. static wchar_t *progname = L"python3";
  1086. #endif
  1087. void
  1088. Py_SetProgramName(wchar_t *pn)
  1089. {
  1090. if (pn && *pn)
  1091. progname = pn;
  1092. }
  1093. wchar_t *
  1094. Py_GetProgramName(void)
  1095. {
  1096. return progname;
  1097. }
  1098. static wchar_t *default_home = NULL;
  1099. static wchar_t env_home[MAXPATHLEN+1];
  1100. void
  1101. Py_SetPythonHome(wchar_t *home)
  1102. {
  1103. default_home = home;
  1104. }
  1105. wchar_t *
  1106. Py_GetPythonHome(void)
  1107. {
  1108. wchar_t *home = default_home;
  1109. if (home == NULL && !Py_IgnoreEnvironmentFlag) {
  1110. char* chome = Py_GETENV("PYTHONHOME");
  1111. if (chome) {
  1112. size_t size = Py_ARRAY_LENGTH(env_home);
  1113. size_t r = mbstowcs(env_home, chome, size);
  1114. if (r != (size_t)-1 && r < size)
  1115. home = env_home;
  1116. }
  1117. }
  1118. return home;
  1119. }
  1120. /* Create __main__ module */
  1121. static void
  1122. initmain(PyInterpreterState *interp)
  1123. {
  1124. PyObject *m, *d, *loader, *ann_dict;
  1125. m = PyImport_AddModule("__main__");
  1126. if (m == NULL)
  1127. Py_FatalError("can't create __main__ module");
  1128. d = PyModule_GetDict(m);
  1129. ann_dict = PyDict_New();
  1130. if ((ann_dict == NULL) ||
  1131. (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
  1132. Py_FatalError("Failed to initialize __main__.__annotations__");
  1133. }
  1134. Py_DECREF(ann_dict);
  1135. if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  1136. PyObject *bimod = PyImport_ImportModule("builtins");
  1137. if (bimod == NULL) {
  1138. Py_FatalError("Failed to retrieve builtins module");
  1139. }
  1140. if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
  1141. Py_FatalError("Failed to initialize __main__.__builtins__");
  1142. }
  1143. Py_DECREF(bimod);
  1144. }
  1145. /* Main is a little special - imp.is_builtin("__main__") will return
  1146. * False, but BuiltinImporter is still the most appropriate initial
  1147. * setting for its __loader__ attribute. A more suitable value will
  1148. * be set if __main__ gets further initialized later in the startup
  1149. * process.
  1150. */
  1151. loader = PyDict_GetItemString(d, "__loader__");
  1152. if (loader == NULL || loader == Py_None) {
  1153. PyObject *loader = PyObject_GetAttrString(interp->importlib,
  1154. "BuiltinImporter");
  1155. if (loader == NULL) {
  1156. Py_FatalError("Failed to retrieve BuiltinImporter");
  1157. }
  1158. if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
  1159. Py_FatalError("Failed to initialize __main__.__loader__");
  1160. }
  1161. Py_DECREF(loader);
  1162. }
  1163. }
  1164. static int
  1165. initfsencoding(PyInterpreterState *interp)
  1166. {
  1167. PyObject *codec;
  1168. #ifdef MS_WINDOWS
  1169. if (Py_LegacyWindowsFSEncodingFlag)
  1170. {
  1171. Py_FileSystemDefaultEncoding = "mbcs";
  1172. Py_FileSystemDefaultEncodeErrors = "replace";
  1173. }
  1174. else
  1175. {
  1176. Py_FileSystemDefaultEncoding = "utf-8";
  1177. Py_FileSystemDefaultEncodeErrors = "surrogatepass";
  1178. }
  1179. #else
  1180. if (Py_FileSystemDefaultEncoding == NULL)
  1181. {
  1182. Py_FileSystemDefaultEncoding = get_locale_encoding();
  1183. if (Py_FileSystemDefaultEncoding == NULL)
  1184. Py_FatalError("Py_Initialize: Unable to get the locale encoding");
  1185. Py_HasFileSystemDefaultEncoding = 0;
  1186. interp->fscodec_initialized = 1;
  1187. return 0;
  1188. }
  1189. #endif
  1190. /* the encoding is mbcs, utf-8 or ascii */
  1191. codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
  1192. if (!codec) {
  1193. /* Such error can only occurs in critical situations: no more
  1194. * memory, import a module of the standard library failed,
  1195. * etc. */
  1196. return -1;
  1197. }
  1198. Py_DECREF(codec);
  1199. interp->fscodec_initialized = 1;
  1200. return 0;
  1201. }
  1202. /* Import the site module (not into __main__ though) */
  1203. static void
  1204. initsite(void)
  1205. {
  1206. PyObject *m;
  1207. m = PyImport_ImportModule("site");
  1208. if (m == NULL) {
  1209. fprintf(stderr, "Failed to import the site module\n");
  1210. PyErr_Print();
  1211. Py_Finalize();
  1212. exit(1);
  1213. }
  1214. else {
  1215. Py_DECREF(m);
  1216. }
  1217. }
  1218. /* Check if a file descriptor is valid or not.
  1219. Return 0 if the file descriptor is invalid, return non-zero otherwise. */
  1220. static int
  1221. is_valid_fd(int fd)
  1222. {
  1223. #ifdef __APPLE__
  1224. /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
  1225. and the other side of the pipe is closed, dup(1) succeed, whereas
  1226. fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
  1227. such error. */
  1228. struct stat st;
  1229. return (fstat(fd, &st) == 0);
  1230. #else
  1231. int fd2;
  1232. if (fd < 0)
  1233. return 0;
  1234. _Py_BEGIN_SUPPRESS_IPH
  1235. /* Prefer dup() over fstat(). fstat() can require input/output whereas
  1236. dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
  1237. startup. */
  1238. fd2 = dup(fd);
  1239. if (fd2 >= 0)
  1240. close(fd2);
  1241. _Py_END_SUPPRESS_IPH
  1242. return fd2 >= 0;
  1243. #endif
  1244. }
  1245. /* returns Py_None if the fd is not valid */
  1246. static PyObject*
  1247. create_stdio(PyObject* io,
  1248. int fd, int write_mode, const char* name,
  1249. const char* encoding, const char* errors)
  1250. {
  1251. PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
  1252. const char* mode;
  1253. const char* newline;
  1254. PyObject *line_buffering;
  1255. int buffering, isatty;
  1256. _Py_IDENTIFIER(open);
  1257. _Py_IDENTIFIER(isatty);
  1258. _Py_IDENTIFIER(TextIOWrapper);
  1259. _Py_IDENTIFIER(mode);
  1260. if (!is_valid_fd(fd))
  1261. Py_RETURN_NONE;
  1262. /* stdin is always opened in buffered mode, first because it shouldn't
  1263. make a difference in common use cases, second because TextIOWrapper
  1264. depends on the presence of a read1() method which only exists on
  1265. buffered streams.
  1266. */
  1267. if (Py_UnbufferedStdioFlag && write_mode)
  1268. buffering = 0;
  1269. else
  1270. buffering = -1;
  1271. if (write_mode)
  1272. mode = "wb";
  1273. else
  1274. mode = "rb";
  1275. buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
  1276. fd, mode, buffering,
  1277. Py_None, Py_None, /* encoding, errors */
  1278. Py_None, 0); /* newline, closefd */
  1279. if (buf == NULL)
  1280. goto error;
  1281. if (buffering) {
  1282. _Py_IDENTIFIER(raw);
  1283. raw = _PyObject_GetAttrId(buf, &PyId_raw);
  1284. if (raw == NULL)
  1285. goto error;
  1286. }
  1287. else {
  1288. raw = buf;
  1289. Py_INCREF(raw);
  1290. }
  1291. #ifdef MS_WINDOWS
  1292. /* Windows console IO is always UTF-8 encoded */
  1293. if (PyWindowsConsoleIO_Check(raw))
  1294. encoding = "utf-8";
  1295. #endif
  1296. text = PyUnicode_FromString(name);
  1297. if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
  1298. goto error;
  1299. res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
  1300. if (res == NULL)
  1301. goto error;
  1302. isatty = PyObject_IsTrue(res);
  1303. Py_DECREF(res);
  1304. if (isatty == -1)
  1305. goto error;
  1306. if (isatty || Py_UnbufferedStdioFlag)
  1307. line_buffering = Py_True;
  1308. else
  1309. line_buffering = Py_False;
  1310. Py_CLEAR(raw);
  1311. Py_CLEAR(text);
  1312. #ifdef MS_WINDOWS
  1313. /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
  1314. newlines to "\n".
  1315. sys.stdout and sys.stderr: translate "\n" to "\r\n". */
  1316. newline = NULL;
  1317. #else
  1318. /* sys.stdin: split lines at "\n".
  1319. sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
  1320. newline = "\n";
  1321. #endif
  1322. stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
  1323. buf, encoding, errors,
  1324. newline, line_buffering);
  1325. Py_CLEAR(buf);
  1326. if (stream == NULL)
  1327. goto error;
  1328. if (write_mode)
  1329. mode = "w";
  1330. else
  1331. mode = "r";
  1332. text = PyUnicode_FromString(mode);
  1333. if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
  1334. goto error;
  1335. Py_CLEAR(text);
  1336. return stream;
  1337. error:
  1338. Py_XDECREF(buf);
  1339. Py_XDECREF(stream);
  1340. Py_XDECREF(text);
  1341. Py_XDECREF(raw);
  1342. if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
  1343. /* Issue #24891: the file descriptor was closed after the first
  1344. is_valid_fd() check was called. Ignore the OSError and set the
  1345. stream to None. */
  1346. PyErr_Clear();
  1347. Py_RETURN_NONE;
  1348. }
  1349. return NULL;
  1350. }
  1351. /* Initialize sys.stdin, stdout, stderr and builtins.open */
  1352. static int
  1353. initstdio(void)
  1354. {
  1355. PyObject *iomod = NULL, *wrapper;
  1356. PyObject *bimod = NULL;
  1357. PyObject *m;
  1358. PyObject *std = NULL;
  1359. int status = 0, fd;
  1360. PyObject * encoding_attr;
  1361. char *pythonioencoding = NULL, *encoding, *errors;
  1362. /* Hack to avoid a nasty recursion issue when Python is invoked
  1363. in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
  1364. if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
  1365. goto error;
  1366. }
  1367. Py_DECREF(m);
  1368. if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
  1369. goto error;
  1370. }
  1371. Py_DECREF(m);
  1372. if (!(bimod = PyImport_ImportModule("builtins"))) {
  1373. goto error;
  1374. }
  1375. if (!(iomod = PyImport_ImportModule("io"))) {
  1376. goto error;
  1377. }
  1378. if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
  1379. goto error;
  1380. }
  1381. /* Set builtins.open */
  1382. if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
  1383. Py_DECREF(wrapper);
  1384. goto error;
  1385. }
  1386. Py_DECREF(wrapper);
  1387. encoding = _Py_StandardStreamEncoding;
  1388. errors = _Py_StandardStreamErrors;
  1389. if (!encoding || !errors) {
  1390. pythonioencoding = Py_GETENV("PYTHONIOENCODING");
  1391. if (pythonioencoding) {
  1392. char *err;
  1393. pythonioencoding = _PyMem_Strdup(pythonioencoding);
  1394. if (pythonioencoding == NULL) {
  1395. PyErr_NoMemory();
  1396. goto error;
  1397. }
  1398. err = strchr(pythonioencoding, ':');
  1399. if (err) {
  1400. *err = '\0';
  1401. err++;
  1402. if (*err && !errors) {
  1403. errors = err;
  1404. }
  1405. }
  1406. if (*pythonioencoding && !encoding) {
  1407. encoding = pythonioencoding;
  1408. }
  1409. }
  1410. if (!errors && !(pythonioencoding && *pythonioencoding)) {
  1411. /* Choose the default error handler based on the current locale */
  1412. errors = get_default_standard_stream_error_handler();
  1413. }
  1414. }
  1415. /* Set sys.stdin */
  1416. fd = fileno(stdin);
  1417. /* Under some conditions stdin, stdout and stderr may not be connected
  1418. * and fileno() may point to an invalid file descriptor. For example
  1419. * GUI apps don't have valid standard streams by default.
  1420. */
  1421. std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
  1422. if (std == NULL)
  1423. goto error;
  1424. PySys_SetObject("__stdin__", std);
  1425. _PySys_SetObjectId(&PyId_stdin, std);
  1426. Py_DECREF(std);
  1427. /* Set sys.stdout */
  1428. fd = fileno(stdout);
  1429. std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
  1430. if (std == NULL)
  1431. goto error;
  1432. PySys_SetObject("__stdout__", std);
  1433. _PySys_SetObjectId(&PyId_stdout, std);
  1434. Py_DECREF(std);
  1435. #if 1 /* Disable this if you have trouble debugging bootstrap stuff */
  1436. /* Set sys.stderr, replaces the preliminary stderr */
  1437. fd = fileno(stderr);
  1438. std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
  1439. if (std == NULL)
  1440. goto error;
  1441. /* Same as hack above, pre-import stderr's codec to avoid recursion
  1442. when import.c tries to write to stderr in verbose mode. */
  1443. encoding_attr = PyObject_GetAttrString(std, "encoding");
  1444. if (encoding_attr != NULL) {
  1445. const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
  1446. if (std_encoding != NULL) {
  1447. PyObject *codec_info = _PyCodec_Lookup(std_encoding);
  1448. Py_XDECREF(codec_info);
  1449. }
  1450. Py_DECREF(encoding_attr);
  1451. }
  1452. PyErr_Clear(); /* Not a fatal error if codec isn't available */
  1453. if (PySys_SetObject("__stderr__", std) < 0) {
  1454. Py_DECREF(std);
  1455. goto error;
  1456. }
  1457. if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
  1458. Py_DECREF(std);
  1459. goto error;
  1460. }
  1461. Py_DECREF(std);
  1462. #endif
  1463. if (0) {
  1464. error:
  1465. status = -1;
  1466. }
  1467. /* We won't need them anymore. */
  1468. if (_Py_StandardStreamEncoding) {
  1469. PyMem_RawFree(_Py_StandardStreamEncoding);
  1470. _Py_StandardStreamEncoding = NULL;
  1471. }
  1472. if (_Py_StandardStreamErrors) {
  1473. PyMem_RawFree(_Py_StandardStreamErrors);
  1474. _Py_StandardStreamErrors = NULL;
  1475. }
  1476. PyMem_Free(pythonioencoding);
  1477. Py_XDECREF(bimod);
  1478. Py_XDECREF(iomod);
  1479. return status;
  1480. }
  1481. static void
  1482. _Py_FatalError_DumpTracebacks(int fd)
  1483. {
  1484. fputc('\n', stderr);
  1485. fflush(stderr);
  1486. /* display the current Python stack */
  1487. _Py_DumpTracebackThreads(fd, NULL, NULL);
  1488. }
  1489. /* Print the current exception (if an exception is set) with its traceback,
  1490. or display the current Python stack.
  1491. Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
  1492. called on catastrophic cases.
  1493. Return 1 if the traceback was displayed, 0 otherwise. */
  1494. static int
  1495. _Py_FatalError_PrintExc(int fd)
  1496. {
  1497. PyObject *ferr, *res;
  1498. PyObject *exception, *v, *tb;
  1499. int has_tb;
  1500. if (PyThreadState_GET() == NULL) {
  1501. /* The GIL is released: trying to acquire it is likely to deadlock,
  1502. just give up. */
  1503. return 0;
  1504. }
  1505. PyErr_Fetch(&exception, &v, &tb);
  1506. if (exception == NULL) {
  1507. /* No current exception */
  1508. return 0;
  1509. }
  1510. ferr = _PySys_GetObjectId(&PyId_stderr);
  1511. if (ferr == NULL || ferr == Py_None) {
  1512. /* sys.stderr is not set yet or set to None,
  1513. no need to try to display the exception */
  1514. return 0;
  1515. }
  1516. PyErr_NormalizeException(&exception, &v, &tb);
  1517. if (tb == NULL) {
  1518. tb = Py_None;
  1519. Py_INCREF(tb);
  1520. }
  1521. PyException_SetTraceback(v, tb);
  1522. if (exception == NULL) {
  1523. /* PyErr_NormalizeException() failed */
  1524. return 0;
  1525. }
  1526. has_tb = (tb != Py_None);
  1527. PyErr_Display(exception, v, tb);
  1528. Py_XDECREF(exception);
  1529. Py_XDECREF(v);
  1530. Py_XDECREF(tb);
  1531. /* sys.stderr may be buffered: call sys.stderr.flush() */
  1532. res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
  1533. if (res == NULL)
  1534. PyErr_Clear();
  1535. else
  1536. Py_DECREF(res);
  1537. return has_tb;
  1538. }
  1539. /* Print fatal error message and abort */
  1540. void
  1541. Py_FatalError(const char *msg)
  1542. {
  1543. const int fd = fileno(stderr);
  1544. static int reentrant = 0;
  1545. #ifdef MS_WINDOWS
  1546. size_t len;
  1547. WCHAR* buffer;
  1548. size_t i;
  1549. #endif
  1550. if (reentrant) {
  1551. /* Py_FatalError() caused a second fatal error.
  1552. Example: flush_std_files() raises a recursion error. */
  1553. goto exit;
  1554. }
  1555. reentrant = 1;
  1556. fprintf(stderr, "Fatal Python error: %s\n", msg);
  1557. fflush(stderr); /* it helps in Windows debug build */
  1558. /* Print the exception (if an exception is set) with its traceback,
  1559. * or display the current Python stack. */
  1560. if (!_Py_FatalError_PrintExc(fd))
  1561. _Py_FatalError_DumpTracebacks(fd);
  1562. /* The main purpose of faulthandler is to display the traceback. We already
  1563. * did our best to display it. So faulthandler can now be disabled.
  1564. * (Don't trigger it on abort().) */
  1565. _PyFaulthandler_Fini();
  1566. /* Check if the current Python thread hold the GIL */
  1567. if (PyThreadState_GET() != NULL) {
  1568. /* Flush sys.stdout and sys.stderr */
  1569. flush_std_files();
  1570. }
  1571. #ifdef MS_WINDOWS
  1572. len = strlen(msg);
  1573. /* Convert the message to wchar_t. This uses a simple one-to-one
  1574. conversion, assuming that the this error message actually uses ASCII
  1575. only. If this ceases to be true, we will have to convert. */
  1576. buffer = alloca( (len+1) * (sizeof *buffer));
  1577. for( i=0; i<=len; ++i)
  1578. buffer[i] = msg[i];
  1579. OutputDebugStringW(L"Fatal Python error: ");
  1580. OutputDebugStringW(buffer);
  1581. OutputDebugStringW(L"\n");
  1582. #endif /* MS_WINDOWS */
  1583. exit:
  1584. #if defined(MS_WINDOWS) && defined(_DEBUG)
  1585. DebugBreak();
  1586. #endif
  1587. abort();
  1588. }
  1589. /* Clean up and exit */
  1590. #ifdef WITH_THREAD
  1591. # include "pythread.h"
  1592. #endif
  1593. static void (*pyexitfunc)(void) = NULL;
  1594. /* For the atexit module. */
  1595. void _Py_PyAtExit(void (*func)(void))
  1596. {
  1597. pyexitfunc = func;
  1598. }
  1599. static void
  1600. call_py_exitfuncs(void)
  1601. {
  1602. if (pyexitfunc == NULL)
  1603. return;
  1604. (*pyexitfunc)();
  1605. PyErr_Clear();
  1606. }
  1607. /* Wait until threading._shutdown completes, provided
  1608. the threading module was imported in the first place.
  1609. The shutdown routine will wait until all non-daemon
  1610. "threading" threads have completed. */
  1611. static void
  1612. wait_for_thread_shutdown(void)
  1613. {
  1614. #ifdef WITH_THREAD
  1615. _Py_IDENTIFIER(_shutdown);
  1616. PyObject *result;
  1617. PyThreadState *tstate = PyThreadState_GET();
  1618. PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
  1619. "threading");
  1620. if (threading == NULL) {
  1621. /* threading not imported */
  1622. PyErr_Clear();
  1623. return;
  1624. }
  1625. result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
  1626. if (result == NULL) {
  1627. PyErr_WriteUnraisable(threading);
  1628. }
  1629. else {
  1630. Py_DECREF(result);
  1631. }
  1632. Py_DECREF(threading);
  1633. #endif
  1634. }
  1635. #define NEXITFUNCS 32
  1636. static void (*exitfuncs[NEXITFUNCS])(void);
  1637. static int nexitfuncs = 0;
  1638. int Py_AtExit(void (*func)(void))
  1639. {
  1640. if (nexitfuncs >= NEXITFUNCS)
  1641. return -1;
  1642. exitfuncs[nexitfuncs++] = func;
  1643. return 0;
  1644. }
  1645. static void
  1646. call_ll_exitfuncs(void)
  1647. {
  1648. while (nexitfuncs > 0)
  1649. (*exitfuncs[--nexitfuncs])();
  1650. fflush(stdout);
  1651. fflush(stderr);
  1652. }
  1653. void
  1654. Py_Exit(int sts)
  1655. {
  1656. if (Py_FinalizeEx() < 0) {
  1657. sts = 120;
  1658. }
  1659. exit(sts);
  1660. }
  1661. static void
  1662. initsigs(void)
  1663. {
  1664. #ifdef SIGPIPE
  1665. PyOS_setsig(SIGPIPE, SIG_IGN);
  1666. #endif
  1667. #ifdef SIGXFZ
  1668. PyOS_setsig(SIGXFZ, SIG_IGN);
  1669. #endif
  1670. #ifdef SIGXFSZ
  1671. PyOS_setsig(SIGXFSZ, SIG_IGN);
  1672. #endif
  1673. PyOS_InitInterrupts(); /* May imply initsignal() */
  1674. if (PyErr_Occurred()) {
  1675. Py_FatalError("Py_Initialize: can't import signal");
  1676. }
  1677. }
  1678. /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
  1679. *
  1680. * All of the code in this function must only use async-signal-safe functions,
  1681. * listed at `man 7 signal` or
  1682. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  1683. */
  1684. void
  1685. _Py_RestoreSignals(void)
  1686. {
  1687. #ifdef SIGPIPE
  1688. PyOS_setsig(SIGPIPE, SIG_DFL);
  1689. #endif
  1690. #ifdef SIGXFZ
  1691. PyOS_setsig(SIGXFZ, SIG_DFL);
  1692. #endif
  1693. #ifdef SIGXFSZ
  1694. PyOS_setsig(SIGXFSZ, SIG_DFL);
  1695. #endif
  1696. }
  1697. /*
  1698. * The file descriptor fd is considered ``interactive'' if either
  1699. * a) isatty(fd) is TRUE, or
  1700. * b) the -i flag was given, and the filename associated with
  1701. * the descriptor is NULL or "<stdin>" or "???".
  1702. */
  1703. int
  1704. Py_FdIsInteractive(FILE *fp, const char *filename)
  1705. {
  1706. if (isatty((int)fileno(fp)))
  1707. return 1;
  1708. if (!Py_InteractiveFlag)
  1709. return 0;
  1710. return (filename == NULL) ||
  1711. (strcmp(filename, "<stdin>") == 0) ||
  1712. (strcmp(filename, "???") == 0);
  1713. }
  1714. /* Wrappers around sigaction() or signal(). */
  1715. PyOS_sighandler_t
  1716. PyOS_getsig(int sig)
  1717. {
  1718. #ifdef HAVE_SIGACTION
  1719. struct sigaction context;
  1720. if (sigaction(sig, NULL, &context) == -1)
  1721. return SIG_ERR;
  1722. return context.sa_handler;
  1723. #else
  1724. PyOS_sighandler_t handler;
  1725. /* Special signal handling for the secure CRT in Visual Studio 2005 */
  1726. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1727. switch (sig) {
  1728. /* Only these signals are valid */
  1729. case SIGINT:
  1730. case SIGILL:
  1731. case SIGFPE:
  1732. case SIGSEGV:
  1733. case SIGTERM:
  1734. case SIGBREAK:
  1735. case SIGABRT:
  1736. break;
  1737. /* Don't call signal() with other values or it will assert */
  1738. default:
  1739. return SIG_ERR;
  1740. }
  1741. #endif /* _MSC_VER && _MSC_VER >= 1400 */
  1742. handler = signal(sig, SIG_IGN);
  1743. if (handler != SIG_ERR)
  1744. signal(sig, handler);
  1745. return handler;
  1746. #endif
  1747. }
  1748. /*
  1749. * All of the code in this function must only use async-signal-safe functions,
  1750. * listed at `man 7 signal` or
  1751. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  1752. */
  1753. PyOS_sighandler_t
  1754. PyOS_setsig(int sig, PyOS_sighandler_t handler)
  1755. {
  1756. #ifdef HAVE_SIGACTION
  1757. /* Some code in Modules/signalmodule.c depends on sigaction() being
  1758. * used here if HAVE_SIGACTION is defined. Fix that if this code
  1759. * changes to invalidate that assumption.
  1760. */
  1761. struct sigaction context, ocontext;
  1762. context.sa_handler = handler;
  1763. sigemptyset(&context.sa_mask);
  1764. context.sa_flags = 0;
  1765. if (sigaction(sig, &context, &ocontext) == -1)
  1766. return SIG_ERR;
  1767. return ocontext.sa_handler;
  1768. #else
  1769. PyOS_sighandler_t oldhandler;
  1770. oldhandler = signal(sig, handler);
  1771. #ifdef HAVE_SIGINTERRUPT
  1772. siginterrupt(sig, 1);
  1773. #endif
  1774. return oldhandler;
  1775. #endif
  1776. }
  1777. #ifdef __cplusplus
  1778. }
  1779. #endif