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.

1598 lines
44 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. #endif
  29. _Py_IDENTIFIER(flush);
  30. _Py_IDENTIFIER(name);
  31. _Py_IDENTIFIER(stdin);
  32. _Py_IDENTIFIER(stdout);
  33. _Py_IDENTIFIER(stderr);
  34. #ifdef __cplusplus
  35. extern "C" {
  36. #endif
  37. extern wchar_t *Py_GetPath(void);
  38. extern grammar _PyParser_Grammar; /* From graminit.c */
  39. /* Forward */
  40. static void initmain(PyInterpreterState *interp);
  41. static int initfsencoding(PyInterpreterState *interp);
  42. static void initsite(void);
  43. static int initstdio(void);
  44. static void initsigs(void);
  45. static void call_py_exitfuncs(void);
  46. static void wait_for_thread_shutdown(void);
  47. static void call_ll_exitfuncs(void);
  48. extern int _PyUnicode_Init(void);
  49. extern int _PyStructSequence_Init(void);
  50. extern void _PyUnicode_Fini(void);
  51. extern int _PyLong_Init(void);
  52. extern void PyLong_Fini(void);
  53. extern int _PyFaulthandler_Init(void);
  54. extern void _PyFaulthandler_Fini(void);
  55. extern void _PyHash_Fini(void);
  56. extern int _PyTraceMalloc_Init(void);
  57. extern int _PyTraceMalloc_Fini(void);
  58. #ifdef WITH_THREAD
  59. extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
  60. extern void _PyGILState_Fini(void);
  61. #endif /* WITH_THREAD */
  62. /* Global configuration variable declarations are in pydebug.h */
  63. /* XXX (ncoghlan): move those declarations to pylifecycle.h? */
  64. int Py_DebugFlag; /* Needed by parser.c */
  65. int Py_VerboseFlag; /* Needed by import.c */
  66. int Py_QuietFlag; /* Needed by sysmodule.c */
  67. int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
  68. int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
  69. int Py_OptimizeFlag = 0; /* Needed by compile.c */
  70. int Py_NoSiteFlag; /* Suppress 'import site' */
  71. int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
  72. int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
  73. int Py_FrozenFlag; /* Needed by getpath.c */
  74. int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
  75. int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.py[co]) */
  76. int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
  77. int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
  78. int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
  79. int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
  80. PyThreadState *_Py_Finalizing = NULL;
  81. /* Hack to force loading of object files */
  82. int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
  83. PyOS_mystrnicmp; /* Python/pystrcmp.o */
  84. /* PyModule_GetWarningsModule is no longer necessary as of 2.6
  85. since _warnings is builtin. This API should not be used. */
  86. PyObject *
  87. PyModule_GetWarningsModule(void)
  88. {
  89. return PyImport_ImportModule("warnings");
  90. }
  91. static int initialized = 0;
  92. /* API to access the initialized flag -- useful for esoteric use */
  93. int
  94. Py_IsInitialized(void)
  95. {
  96. return initialized;
  97. }
  98. /* Helper to allow an embedding application to override the normal
  99. * mechanism that attempts to figure out an appropriate IO encoding
  100. */
  101. static char *_Py_StandardStreamEncoding = NULL;
  102. static char *_Py_StandardStreamErrors = NULL;
  103. int
  104. Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
  105. {
  106. if (Py_IsInitialized()) {
  107. /* This is too late to have any effect */
  108. return -1;
  109. }
  110. /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
  111. * initialised yet.
  112. *
  113. * However, the raw memory allocators are initialised appropriately
  114. * as C static variables, so _PyMem_RawStrdup is OK even though
  115. * Py_Initialize hasn't been called yet.
  116. */
  117. if (encoding) {
  118. _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
  119. if (!_Py_StandardStreamEncoding) {
  120. return -2;
  121. }
  122. }
  123. if (errors) {
  124. _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
  125. if (!_Py_StandardStreamErrors) {
  126. if (_Py_StandardStreamEncoding) {
  127. PyMem_RawFree(_Py_StandardStreamEncoding);
  128. }
  129. return -3;
  130. }
  131. }
  132. return 0;
  133. }
  134. /* Global initializations. Can be undone by Py_Finalize(). Don't
  135. call this twice without an intervening Py_Finalize() call. When
  136. initializations fail, a fatal error is issued and the function does
  137. not return. On return, the first thread and interpreter state have
  138. been created.
  139. Locking: you must hold the interpreter lock while calling this.
  140. (If the lock has not yet been initialized, that's equivalent to
  141. having the lock, but you cannot use multiple threads.)
  142. */
  143. static int
  144. add_flag(int flag, const char *envs)
  145. {
  146. int env = atoi(envs);
  147. if (flag < env)
  148. flag = env;
  149. if (flag < 1)
  150. flag = 1;
  151. return flag;
  152. }
  153. static char*
  154. get_codec_name(const char *encoding)
  155. {
  156. char *name_utf8, *name_str;
  157. PyObject *codec, *name = NULL;
  158. codec = _PyCodec_Lookup(encoding);
  159. if (!codec)
  160. goto error;
  161. name = _PyObject_GetAttrId(codec, &PyId_name);
  162. Py_CLEAR(codec);
  163. if (!name)
  164. goto error;
  165. name_utf8 = _PyUnicode_AsString(name);
  166. if (name_utf8 == NULL)
  167. goto error;
  168. name_str = _PyMem_RawStrdup(name_utf8);
  169. Py_DECREF(name);
  170. if (name_str == NULL) {
  171. PyErr_NoMemory();
  172. return NULL;
  173. }
  174. return name_str;
  175. error:
  176. Py_XDECREF(codec);
  177. Py_XDECREF(name);
  178. return NULL;
  179. }
  180. static char*
  181. get_locale_encoding(void)
  182. {
  183. #ifdef MS_WINDOWS
  184. char codepage[100];
  185. PyOS_snprintf(codepage, sizeof(codepage), "cp%d", GetACP());
  186. return get_codec_name(codepage);
  187. #elif defined(HAVE_LANGINFO_H) && defined(CODESET)
  188. char* codeset = nl_langinfo(CODESET);
  189. if (!codeset || codeset[0] == '\0') {
  190. PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
  191. return NULL;
  192. }
  193. return get_codec_name(codeset);
  194. #else
  195. PyErr_SetNone(PyExc_NotImplementedError);
  196. return NULL;
  197. #endif
  198. }
  199. static void
  200. import_init(PyInterpreterState *interp, PyObject *sysmod)
  201. {
  202. PyObject *importlib;
  203. PyObject *impmod;
  204. PyObject *sys_modules;
  205. PyObject *value;
  206. /* Import _importlib through its frozen version, _frozen_importlib. */
  207. if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
  208. Py_FatalError("Py_Initialize: can't import _frozen_importlib");
  209. }
  210. else if (Py_VerboseFlag) {
  211. PySys_FormatStderr("import _frozen_importlib # frozen\n");
  212. }
  213. importlib = PyImport_AddModule("_frozen_importlib");
  214. if (importlib == NULL) {
  215. Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
  216. "sys.modules");
  217. }
  218. interp->importlib = importlib;
  219. Py_INCREF(interp->importlib);
  220. /* Import the _imp module */
  221. impmod = PyInit_imp();
  222. if (impmod == NULL) {
  223. Py_FatalError("Py_Initialize: can't import _imp");
  224. }
  225. else if (Py_VerboseFlag) {
  226. PySys_FormatStderr("import _imp # builtin\n");
  227. }
  228. sys_modules = PyImport_GetModuleDict();
  229. if (Py_VerboseFlag) {
  230. PySys_FormatStderr("import sys # builtin\n");
  231. }
  232. if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
  233. Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
  234. }
  235. /* Install importlib as the implementation of import */
  236. value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
  237. if (value == NULL) {
  238. PyErr_Print();
  239. Py_FatalError("Py_Initialize: importlib install failed");
  240. }
  241. Py_DECREF(value);
  242. Py_DECREF(impmod);
  243. _PyImportZip_Init();
  244. }
  245. void
  246. _Py_InitializeEx_Private(int install_sigs, int install_importlib)
  247. {
  248. PyInterpreterState *interp;
  249. PyThreadState *tstate;
  250. PyObject *bimod, *sysmod, *pstderr;
  251. char *p;
  252. extern void _Py_ReadyTypes(void);
  253. if (initialized)
  254. return;
  255. initialized = 1;
  256. _Py_Finalizing = NULL;
  257. #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE)
  258. /* Set up the LC_CTYPE locale, so we can obtain
  259. the locale's charset without having to switch
  260. locales. */
  261. setlocale(LC_CTYPE, "");
  262. #endif
  263. if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
  264. Py_DebugFlag = add_flag(Py_DebugFlag, p);
  265. if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
  266. Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
  267. if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
  268. Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
  269. if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
  270. Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
  271. /* The variable is only tested for existence here; _PyRandom_Init will
  272. check its value further. */
  273. if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
  274. Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
  275. _PyRandom_Init();
  276. interp = PyInterpreterState_New();
  277. if (interp == NULL)
  278. Py_FatalError("Py_Initialize: can't make first interpreter");
  279. tstate = PyThreadState_New(interp);
  280. if (tstate == NULL)
  281. Py_FatalError("Py_Initialize: can't make first thread");
  282. (void) PyThreadState_Swap(tstate);
  283. #ifdef WITH_THREAD
  284. /* We can't call _PyEval_FiniThreads() in Py_Finalize because
  285. destroying the GIL might fail when it is being referenced from
  286. another running thread (see issue #9901).
  287. Instead we destroy the previously created GIL here, which ensures
  288. that we can call Py_Initialize / Py_Finalize multiple times. */
  289. _PyEval_FiniThreads();
  290. /* Auto-thread-state API */
  291. _PyGILState_Init(interp, tstate);
  292. #endif /* WITH_THREAD */
  293. _Py_ReadyTypes();
  294. if (!_PyFrame_Init())
  295. Py_FatalError("Py_Initialize: can't init frames");
  296. if (!_PyLong_Init())
  297. Py_FatalError("Py_Initialize: can't init longs");
  298. if (!PyByteArray_Init())
  299. Py_FatalError("Py_Initialize: can't init bytearray");
  300. if (!_PyFloat_Init())
  301. Py_FatalError("Py_Initialize: can't init float");
  302. interp->modules = PyDict_New();
  303. if (interp->modules == NULL)
  304. Py_FatalError("Py_Initialize: can't make modules dictionary");
  305. /* Init Unicode implementation; relies on the codec registry */
  306. if (_PyUnicode_Init() < 0)
  307. Py_FatalError("Py_Initialize: can't initialize unicode");
  308. if (_PyStructSequence_Init() < 0)
  309. Py_FatalError("Py_Initialize: can't initialize structseq");
  310. bimod = _PyBuiltin_Init();
  311. if (bimod == NULL)
  312. Py_FatalError("Py_Initialize: can't initialize builtins modules");
  313. _PyImport_FixupBuiltin(bimod, "builtins");
  314. interp->builtins = PyModule_GetDict(bimod);
  315. if (interp->builtins == NULL)
  316. Py_FatalError("Py_Initialize: can't initialize builtins dict");
  317. Py_INCREF(interp->builtins);
  318. /* initialize builtin exceptions */
  319. _PyExc_Init(bimod);
  320. sysmod = _PySys_Init();
  321. if (sysmod == NULL)
  322. Py_FatalError("Py_Initialize: can't initialize sys");
  323. interp->sysdict = PyModule_GetDict(sysmod);
  324. if (interp->sysdict == NULL)
  325. Py_FatalError("Py_Initialize: can't initialize sys dict");
  326. Py_INCREF(interp->sysdict);
  327. _PyImport_FixupBuiltin(sysmod, "sys");
  328. PySys_SetPath(Py_GetPath());
  329. PyDict_SetItemString(interp->sysdict, "modules",
  330. interp->modules);
  331. /* Set up a preliminary stderr printer until we have enough
  332. infrastructure for the io module in place. */
  333. pstderr = PyFile_NewStdPrinter(fileno(stderr));
  334. if (pstderr == NULL)
  335. Py_FatalError("Py_Initialize: can't set preliminary stderr");
  336. _PySys_SetObjectId(&PyId_stderr, pstderr);
  337. PySys_SetObject("__stderr__", pstderr);
  338. Py_DECREF(pstderr);
  339. _PyImport_Init();
  340. _PyImportHooks_Init();
  341. /* Initialize _warnings. */
  342. _PyWarnings_Init();
  343. if (!install_importlib)
  344. return;
  345. if (_PyTime_Init() < 0)
  346. Py_FatalError("Py_Initialize: can't initialize time");
  347. import_init(interp, sysmod);
  348. /* initialize the faulthandler module */
  349. if (_PyFaulthandler_Init())
  350. Py_FatalError("Py_Initialize: can't initialize faulthandler");
  351. if (initfsencoding(interp) < 0)
  352. Py_FatalError("Py_Initialize: unable to load the file system codec");
  353. if (install_sigs)
  354. initsigs(); /* Signal handling stuff, including initintr() */
  355. if (_PyTraceMalloc_Init() < 0)
  356. Py_FatalError("Py_Initialize: can't initialize tracemalloc");
  357. initmain(interp); /* Module __main__ */
  358. if (initstdio() < 0)
  359. Py_FatalError(
  360. "Py_Initialize: can't initialize sys standard streams");
  361. /* Initialize warnings. */
  362. if (PySys_HasWarnOptions()) {
  363. PyObject *warnings_module = PyImport_ImportModule("warnings");
  364. if (warnings_module == NULL) {
  365. fprintf(stderr, "'import warnings' failed; traceback:\n");
  366. PyErr_Print();
  367. }
  368. Py_XDECREF(warnings_module);
  369. }
  370. if (!Py_NoSiteFlag)
  371. initsite(); /* Module site */
  372. }
  373. void
  374. Py_InitializeEx(int install_sigs)
  375. {
  376. _Py_InitializeEx_Private(install_sigs, 1);
  377. }
  378. void
  379. Py_Initialize(void)
  380. {
  381. Py_InitializeEx(1);
  382. }
  383. #ifdef COUNT_ALLOCS
  384. extern void dump_counts(FILE*);
  385. #endif
  386. /* Flush stdout and stderr */
  387. static int
  388. file_is_closed(PyObject *fobj)
  389. {
  390. int r;
  391. PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
  392. if (tmp == NULL) {
  393. PyErr_Clear();
  394. return 0;
  395. }
  396. r = PyObject_IsTrue(tmp);
  397. Py_DECREF(tmp);
  398. if (r < 0)
  399. PyErr_Clear();
  400. return r > 0;
  401. }
  402. static void
  403. flush_std_files(void)
  404. {
  405. PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
  406. PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
  407. PyObject *tmp;
  408. if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
  409. tmp = _PyObject_CallMethodId(fout, &PyId_flush, "");
  410. if (tmp == NULL)
  411. PyErr_WriteUnraisable(fout);
  412. else
  413. Py_DECREF(tmp);
  414. }
  415. if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
  416. tmp = _PyObject_CallMethodId(ferr, &PyId_flush, "");
  417. if (tmp == NULL)
  418. PyErr_Clear();
  419. else
  420. Py_DECREF(tmp);
  421. }
  422. }
  423. /* Undo the effect of Py_Initialize().
  424. Beware: if multiple interpreter and/or thread states exist, these
  425. are not wiped out; only the current thread and interpreter state
  426. are deleted. But since everything else is deleted, those other
  427. interpreter and thread states should no longer be used.
  428. (XXX We should do better, e.g. wipe out all interpreters and
  429. threads.)
  430. Locking: as above.
  431. */
  432. void
  433. Py_Finalize(void)
  434. {
  435. PyInterpreterState *interp;
  436. PyThreadState *tstate;
  437. if (!initialized)
  438. return;
  439. wait_for_thread_shutdown();
  440. /* The interpreter is still entirely intact at this point, and the
  441. * exit funcs may be relying on that. In particular, if some thread
  442. * or exit func is still waiting to do an import, the import machinery
  443. * expects Py_IsInitialized() to return true. So don't say the
  444. * interpreter is uninitialized until after the exit funcs have run.
  445. * Note that Threading.py uses an exit func to do a join on all the
  446. * threads created thru it, so this also protects pending imports in
  447. * the threads created via Threading.
  448. */
  449. call_py_exitfuncs();
  450. /* Get current thread state and interpreter pointer */
  451. tstate = PyThreadState_GET();
  452. interp = tstate->interp;
  453. /* Remaining threads (e.g. daemon threads) will automatically exit
  454. after taking the GIL (in PyEval_RestoreThread()). */
  455. _Py_Finalizing = tstate;
  456. initialized = 0;
  457. /* Flush sys.stdout and sys.stderr */
  458. flush_std_files();
  459. /* Disable signal handling */
  460. PyOS_FiniInterrupts();
  461. /* Collect garbage. This may call finalizers; it's nice to call these
  462. * before all modules are destroyed.
  463. * XXX If a __del__ or weakref callback is triggered here, and tries to
  464. * XXX import a module, bad things can happen, because Python no
  465. * XXX longer believes it's initialized.
  466. * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
  467. * XXX is easy to provoke that way. I've also seen, e.g.,
  468. * XXX Exception exceptions.ImportError: 'No module named sha'
  469. * XXX in <function callback at 0x008F5718> ignored
  470. * XXX but I'm unclear on exactly how that one happens. In any case,
  471. * XXX I haven't seen a real-life report of either of these.
  472. */
  473. PyGC_Collect();
  474. #ifdef COUNT_ALLOCS
  475. /* With COUNT_ALLOCS, it helps to run GC multiple times:
  476. each collection might release some types from the type
  477. list, so they become garbage. */
  478. while (PyGC_Collect() > 0)
  479. /* nothing */;
  480. #endif
  481. /* Destroy all modules */
  482. PyImport_Cleanup();
  483. /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
  484. flush_std_files();
  485. /* Collect final garbage. This disposes of cycles created by
  486. * class definitions, for example.
  487. * XXX This is disabled because it caused too many problems. If
  488. * XXX a __del__ or weakref callback triggers here, Python code has
  489. * XXX a hard time running, because even the sys module has been
  490. * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
  491. * XXX One symptom is a sequence of information-free messages
  492. * XXX coming from threads (if a __del__ or callback is invoked,
  493. * XXX other threads can execute too, and any exception they encounter
  494. * XXX triggers a comedy of errors as subsystem after subsystem
  495. * XXX fails to find what it *expects* to find in sys to help report
  496. * XXX the exception and consequent unexpected failures). I've also
  497. * XXX seen segfaults then, after adding print statements to the
  498. * XXX Python code getting called.
  499. */
  500. #if 0
  501. PyGC_Collect();
  502. #endif
  503. /* Disable tracemalloc after all Python objects have been destroyed,
  504. so it is possible to use tracemalloc in objects destructor. */
  505. _PyTraceMalloc_Fini();
  506. /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
  507. _PyImport_Fini();
  508. /* Cleanup typeobject.c's internal caches. */
  509. _PyType_Fini();
  510. /* unload faulthandler module */
  511. _PyFaulthandler_Fini();
  512. /* Debugging stuff */
  513. #ifdef COUNT_ALLOCS
  514. dump_counts(stdout);
  515. #endif
  516. /* dump hash stats */
  517. _PyHash_Fini();
  518. _PY_DEBUG_PRINT_TOTAL_REFS();
  519. #ifdef Py_TRACE_REFS
  520. /* Display all objects still alive -- this can invoke arbitrary
  521. * __repr__ overrides, so requires a mostly-intact interpreter.
  522. * Alas, a lot of stuff may still be alive now that will be cleaned
  523. * up later.
  524. */
  525. if (Py_GETENV("PYTHONDUMPREFS"))
  526. _Py_PrintReferences(stderr);
  527. #endif /* Py_TRACE_REFS */
  528. /* Clear interpreter state and all thread states. */
  529. PyInterpreterState_Clear(interp);
  530. /* Now we decref the exception classes. After this point nothing
  531. can raise an exception. That's okay, because each Fini() method
  532. below has been checked to make sure no exceptions are ever
  533. raised.
  534. */
  535. _PyExc_Fini();
  536. /* Sundry finalizers */
  537. PyMethod_Fini();
  538. PyFrame_Fini();
  539. PyCFunction_Fini();
  540. PyTuple_Fini();
  541. PyList_Fini();
  542. PySet_Fini();
  543. PyBytes_Fini();
  544. PyByteArray_Fini();
  545. PyLong_Fini();
  546. PyFloat_Fini();
  547. PyDict_Fini();
  548. PySlice_Fini();
  549. _PyGC_Fini();
  550. _PyRandom_Fini();
  551. /* Cleanup Unicode implementation */
  552. _PyUnicode_Fini();
  553. /* reset file system default encoding */
  554. if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
  555. PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
  556. Py_FileSystemDefaultEncoding = NULL;
  557. }
  558. /* XXX Still allocated:
  559. - various static ad-hoc pointers to interned strings
  560. - int and float free list blocks
  561. - whatever various modules and libraries allocate
  562. */
  563. PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
  564. /* Cleanup auto-thread-state */
  565. #ifdef WITH_THREAD
  566. _PyGILState_Fini();
  567. #endif /* WITH_THREAD */
  568. /* Delete current thread. After this, many C API calls become crashy. */
  569. PyThreadState_Swap(NULL);
  570. PyInterpreterState_Delete(interp);
  571. #ifdef Py_TRACE_REFS
  572. /* Display addresses (& refcnts) of all objects still alive.
  573. * An address can be used to find the repr of the object, printed
  574. * above by _Py_PrintReferences.
  575. */
  576. if (Py_GETENV("PYTHONDUMPREFS"))
  577. _Py_PrintReferenceAddresses(stderr);
  578. #endif /* Py_TRACE_REFS */
  579. #ifdef PYMALLOC_DEBUG
  580. if (Py_GETENV("PYTHONMALLOCSTATS"))
  581. _PyObject_DebugMallocStats(stderr);
  582. #endif
  583. call_ll_exitfuncs();
  584. }
  585. /* Create and initialize a new interpreter and thread, and return the
  586. new thread. This requires that Py_Initialize() has been called
  587. first.
  588. Unsuccessful initialization yields a NULL pointer. Note that *no*
  589. exception information is available even in this case -- the
  590. exception information is held in the thread, and there is no
  591. thread.
  592. Locking: as above.
  593. */
  594. PyThreadState *
  595. Py_NewInterpreter(void)
  596. {
  597. PyInterpreterState *interp;
  598. PyThreadState *tstate, *save_tstate;
  599. PyObject *bimod, *sysmod;
  600. if (!initialized)
  601. Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
  602. interp = PyInterpreterState_New();
  603. if (interp == NULL)
  604. return NULL;
  605. tstate = PyThreadState_New(interp);
  606. if (tstate == NULL) {
  607. PyInterpreterState_Delete(interp);
  608. return NULL;
  609. }
  610. save_tstate = PyThreadState_Swap(tstate);
  611. /* XXX The following is lax in error checking */
  612. interp->modules = PyDict_New();
  613. bimod = _PyImport_FindBuiltin("builtins");
  614. if (bimod != NULL) {
  615. interp->builtins = PyModule_GetDict(bimod);
  616. if (interp->builtins == NULL)
  617. goto handle_error;
  618. Py_INCREF(interp->builtins);
  619. }
  620. /* initialize builtin exceptions */
  621. _PyExc_Init(bimod);
  622. sysmod = _PyImport_FindBuiltin("sys");
  623. if (bimod != NULL && sysmod != NULL) {
  624. PyObject *pstderr;
  625. interp->sysdict = PyModule_GetDict(sysmod);
  626. if (interp->sysdict == NULL)
  627. goto handle_error;
  628. Py_INCREF(interp->sysdict);
  629. PySys_SetPath(Py_GetPath());
  630. PyDict_SetItemString(interp->sysdict, "modules",
  631. interp->modules);
  632. /* Set up a preliminary stderr printer until we have enough
  633. infrastructure for the io module in place. */
  634. pstderr = PyFile_NewStdPrinter(fileno(stderr));
  635. if (pstderr == NULL)
  636. Py_FatalError("Py_Initialize: can't set preliminary stderr");
  637. _PySys_SetObjectId(&PyId_stderr, pstderr);
  638. PySys_SetObject("__stderr__", pstderr);
  639. Py_DECREF(pstderr);
  640. _PyImportHooks_Init();
  641. import_init(interp, sysmod);
  642. if (initfsencoding(interp) < 0)
  643. goto handle_error;
  644. if (initstdio() < 0)
  645. Py_FatalError(
  646. "Py_Initialize: can't initialize sys standard streams");
  647. initmain(interp);
  648. if (!Py_NoSiteFlag)
  649. initsite();
  650. }
  651. if (!PyErr_Occurred())
  652. return tstate;
  653. handle_error:
  654. /* Oops, it didn't work. Undo it all. */
  655. PyErr_PrintEx(0);
  656. PyThreadState_Clear(tstate);
  657. PyThreadState_Swap(save_tstate);
  658. PyThreadState_Delete(tstate);
  659. PyInterpreterState_Delete(interp);
  660. return NULL;
  661. }
  662. /* Delete an interpreter and its last thread. This requires that the
  663. given thread state is current, that the thread has no remaining
  664. frames, and that it is its interpreter's only remaining thread.
  665. It is a fatal error to violate these constraints.
  666. (Py_Finalize() doesn't have these constraints -- it zaps
  667. everything, regardless.)
  668. Locking: as above.
  669. */
  670. void
  671. Py_EndInterpreter(PyThreadState *tstate)
  672. {
  673. PyInterpreterState *interp = tstate->interp;
  674. if (tstate != PyThreadState_GET())
  675. Py_FatalError("Py_EndInterpreter: thread is not current");
  676. if (tstate->frame != NULL)
  677. Py_FatalError("Py_EndInterpreter: thread still has a frame");
  678. wait_for_thread_shutdown();
  679. if (tstate != interp->tstate_head || tstate->next != NULL)
  680. Py_FatalError("Py_EndInterpreter: not the last thread");
  681. PyImport_Cleanup();
  682. PyInterpreterState_Clear(interp);
  683. PyThreadState_Swap(NULL);
  684. PyInterpreterState_Delete(interp);
  685. }
  686. #ifdef MS_WINDOWS
  687. static wchar_t *progname = L"python";
  688. #else
  689. static wchar_t *progname = L"python3";
  690. #endif
  691. void
  692. Py_SetProgramName(wchar_t *pn)
  693. {
  694. if (pn && *pn)
  695. progname = pn;
  696. }
  697. wchar_t *
  698. Py_GetProgramName(void)
  699. {
  700. return progname;
  701. }
  702. static wchar_t *default_home = NULL;
  703. static wchar_t env_home[MAXPATHLEN+1];
  704. void
  705. Py_SetPythonHome(wchar_t *home)
  706. {
  707. default_home = home;
  708. }
  709. wchar_t *
  710. Py_GetPythonHome(void)
  711. {
  712. wchar_t *home = default_home;
  713. if (home == NULL && !Py_IgnoreEnvironmentFlag) {
  714. char* chome = Py_GETENV("PYTHONHOME");
  715. if (chome) {
  716. size_t size = Py_ARRAY_LENGTH(env_home);
  717. size_t r = mbstowcs(env_home, chome, size);
  718. if (r != (size_t)-1 && r < size)
  719. home = env_home;
  720. }
  721. }
  722. return home;
  723. }
  724. /* Create __main__ module */
  725. static void
  726. initmain(PyInterpreterState *interp)
  727. {
  728. PyObject *m, *d, *loader;
  729. m = PyImport_AddModule("__main__");
  730. if (m == NULL)
  731. Py_FatalError("can't create __main__ module");
  732. d = PyModule_GetDict(m);
  733. if (PyDict_GetItemString(d, "__builtins__") == NULL) {
  734. PyObject *bimod = PyImport_ImportModule("builtins");
  735. if (bimod == NULL) {
  736. Py_FatalError("Failed to retrieve builtins module");
  737. }
  738. if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
  739. Py_FatalError("Failed to initialize __main__.__builtins__");
  740. }
  741. Py_DECREF(bimod);
  742. }
  743. /* Main is a little special - imp.is_builtin("__main__") will return
  744. * False, but BuiltinImporter is still the most appropriate initial
  745. * setting for its __loader__ attribute. A more suitable value will
  746. * be set if __main__ gets further initialized later in the startup
  747. * process.
  748. */
  749. loader = PyDict_GetItemString(d, "__loader__");
  750. if (loader == NULL || loader == Py_None) {
  751. PyObject *loader = PyObject_GetAttrString(interp->importlib,
  752. "BuiltinImporter");
  753. if (loader == NULL) {
  754. Py_FatalError("Failed to retrieve BuiltinImporter");
  755. }
  756. if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
  757. Py_FatalError("Failed to initialize __main__.__loader__");
  758. }
  759. Py_DECREF(loader);
  760. }
  761. }
  762. static int
  763. initfsencoding(PyInterpreterState *interp)
  764. {
  765. PyObject *codec;
  766. if (Py_FileSystemDefaultEncoding == NULL)
  767. {
  768. Py_FileSystemDefaultEncoding = get_locale_encoding();
  769. if (Py_FileSystemDefaultEncoding == NULL)
  770. Py_FatalError("Py_Initialize: Unable to get the locale encoding");
  771. Py_HasFileSystemDefaultEncoding = 0;
  772. interp->fscodec_initialized = 1;
  773. return 0;
  774. }
  775. /* the encoding is mbcs, utf-8 or ascii */
  776. codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
  777. if (!codec) {
  778. /* Such error can only occurs in critical situations: no more
  779. * memory, import a module of the standard library failed,
  780. * etc. */
  781. return -1;
  782. }
  783. Py_DECREF(codec);
  784. interp->fscodec_initialized = 1;
  785. return 0;
  786. }
  787. /* Import the site module (not into __main__ though) */
  788. static void
  789. initsite(void)
  790. {
  791. PyObject *m;
  792. m = PyImport_ImportModule("site");
  793. if (m == NULL) {
  794. fprintf(stderr, "Failed to import the site module\n");
  795. PyErr_Print();
  796. Py_Finalize();
  797. exit(1);
  798. }
  799. else {
  800. Py_DECREF(m);
  801. }
  802. }
  803. /* Check if a file descriptor is valid or not.
  804. Return 0 if the file descriptor is invalid, return non-zero otherwise. */
  805. static int
  806. is_valid_fd(int fd)
  807. {
  808. int fd2;
  809. if (fd < 0 || !_PyVerify_fd(fd))
  810. return 0;
  811. _Py_BEGIN_SUPPRESS_IPH
  812. fd2 = dup(fd);
  813. if (fd2 >= 0)
  814. close(fd2);
  815. _Py_END_SUPPRESS_IPH
  816. return fd2 >= 0;
  817. }
  818. /* returns Py_None if the fd is not valid */
  819. static PyObject*
  820. create_stdio(PyObject* io,
  821. int fd, int write_mode, char* name,
  822. char* encoding, char* errors)
  823. {
  824. PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
  825. const char* mode;
  826. const char* newline;
  827. PyObject *line_buffering;
  828. int buffering, isatty;
  829. _Py_IDENTIFIER(open);
  830. _Py_IDENTIFIER(isatty);
  831. _Py_IDENTIFIER(TextIOWrapper);
  832. _Py_IDENTIFIER(mode);
  833. if (!is_valid_fd(fd))
  834. Py_RETURN_NONE;
  835. /* stdin is always opened in buffered mode, first because it shouldn't
  836. make a difference in common use cases, second because TextIOWrapper
  837. depends on the presence of a read1() method which only exists on
  838. buffered streams.
  839. */
  840. if (Py_UnbufferedStdioFlag && write_mode)
  841. buffering = 0;
  842. else
  843. buffering = -1;
  844. if (write_mode)
  845. mode = "wb";
  846. else
  847. mode = "rb";
  848. buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
  849. fd, mode, buffering,
  850. Py_None, Py_None, Py_None, 0);
  851. if (buf == NULL)
  852. goto error;
  853. if (buffering) {
  854. _Py_IDENTIFIER(raw);
  855. raw = _PyObject_GetAttrId(buf, &PyId_raw);
  856. if (raw == NULL)
  857. goto error;
  858. }
  859. else {
  860. raw = buf;
  861. Py_INCREF(raw);
  862. }
  863. text = PyUnicode_FromString(name);
  864. if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
  865. goto error;
  866. res = _PyObject_CallMethodId(raw, &PyId_isatty, "");
  867. if (res == NULL)
  868. goto error;
  869. isatty = PyObject_IsTrue(res);
  870. Py_DECREF(res);
  871. if (isatty == -1)
  872. goto error;
  873. if (isatty || Py_UnbufferedStdioFlag)
  874. line_buffering = Py_True;
  875. else
  876. line_buffering = Py_False;
  877. Py_CLEAR(raw);
  878. Py_CLEAR(text);
  879. #ifdef MS_WINDOWS
  880. /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
  881. newlines to "\n".
  882. sys.stdout and sys.stderr: translate "\n" to "\r\n". */
  883. newline = NULL;
  884. #else
  885. /* sys.stdin: split lines at "\n".
  886. sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
  887. newline = "\n";
  888. #endif
  889. stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
  890. buf, encoding, errors,
  891. newline, line_buffering);
  892. Py_CLEAR(buf);
  893. if (stream == NULL)
  894. goto error;
  895. if (write_mode)
  896. mode = "w";
  897. else
  898. mode = "r";
  899. text = PyUnicode_FromString(mode);
  900. if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
  901. goto error;
  902. Py_CLEAR(text);
  903. return stream;
  904. error:
  905. Py_XDECREF(buf);
  906. Py_XDECREF(stream);
  907. Py_XDECREF(text);
  908. Py_XDECREF(raw);
  909. if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
  910. /* Issue #24891: the file descriptor was closed after the first
  911. is_valid_fd() check was called. Ignore the OSError and set the
  912. stream to None. */
  913. PyErr_Clear();
  914. Py_RETURN_NONE;
  915. }
  916. return NULL;
  917. }
  918. /* Initialize sys.stdin, stdout, stderr and builtins.open */
  919. static int
  920. initstdio(void)
  921. {
  922. PyObject *iomod = NULL, *wrapper;
  923. PyObject *bimod = NULL;
  924. PyObject *m;
  925. PyObject *std = NULL;
  926. int status = 0, fd;
  927. PyObject * encoding_attr;
  928. char *pythonioencoding = NULL, *encoding, *errors;
  929. /* Hack to avoid a nasty recursion issue when Python is invoked
  930. in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
  931. if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
  932. goto error;
  933. }
  934. Py_DECREF(m);
  935. if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
  936. goto error;
  937. }
  938. Py_DECREF(m);
  939. if (!(bimod = PyImport_ImportModule("builtins"))) {
  940. goto error;
  941. }
  942. if (!(iomod = PyImport_ImportModule("io"))) {
  943. goto error;
  944. }
  945. if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
  946. goto error;
  947. }
  948. /* Set builtins.open */
  949. if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
  950. Py_DECREF(wrapper);
  951. goto error;
  952. }
  953. Py_DECREF(wrapper);
  954. encoding = _Py_StandardStreamEncoding;
  955. errors = _Py_StandardStreamErrors;
  956. if (!encoding || !errors) {
  957. if (!errors) {
  958. /* When the LC_CTYPE locale is the POSIX locale ("C locale"),
  959. stdin and stdout use the surrogateescape error handler by
  960. default, instead of the strict error handler. */
  961. char *loc = setlocale(LC_CTYPE, NULL);
  962. if (loc != NULL && strcmp(loc, "C") == 0)
  963. errors = "surrogateescape";
  964. }
  965. pythonioencoding = Py_GETENV("PYTHONIOENCODING");
  966. if (pythonioencoding) {
  967. char *err;
  968. pythonioencoding = _PyMem_Strdup(pythonioencoding);
  969. if (pythonioencoding == NULL) {
  970. PyErr_NoMemory();
  971. goto error;
  972. }
  973. err = strchr(pythonioencoding, ':');
  974. if (err) {
  975. *err = '\0';
  976. err++;
  977. if (*err && !_Py_StandardStreamErrors) {
  978. errors = err;
  979. }
  980. }
  981. if (*pythonioencoding && !encoding) {
  982. encoding = pythonioencoding;
  983. }
  984. }
  985. }
  986. /* Set sys.stdin */
  987. fd = fileno(stdin);
  988. /* Under some conditions stdin, stdout and stderr may not be connected
  989. * and fileno() may point to an invalid file descriptor. For example
  990. * GUI apps don't have valid standard streams by default.
  991. */
  992. std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
  993. if (std == NULL)
  994. goto error;
  995. PySys_SetObject("__stdin__", std);
  996. _PySys_SetObjectId(&PyId_stdin, std);
  997. Py_DECREF(std);
  998. /* Set sys.stdout */
  999. fd = fileno(stdout);
  1000. std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
  1001. if (std == NULL)
  1002. goto error;
  1003. PySys_SetObject("__stdout__", std);
  1004. _PySys_SetObjectId(&PyId_stdout, std);
  1005. Py_DECREF(std);
  1006. #if 1 /* Disable this if you have trouble debugging bootstrap stuff */
  1007. /* Set sys.stderr, replaces the preliminary stderr */
  1008. fd = fileno(stderr);
  1009. std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
  1010. if (std == NULL)
  1011. goto error;
  1012. /* Same as hack above, pre-import stderr's codec to avoid recursion
  1013. when import.c tries to write to stderr in verbose mode. */
  1014. encoding_attr = PyObject_GetAttrString(std, "encoding");
  1015. if (encoding_attr != NULL) {
  1016. const char * std_encoding;
  1017. std_encoding = _PyUnicode_AsString(encoding_attr);
  1018. if (std_encoding != NULL) {
  1019. PyObject *codec_info = _PyCodec_Lookup(std_encoding);
  1020. Py_XDECREF(codec_info);
  1021. }
  1022. Py_DECREF(encoding_attr);
  1023. }
  1024. PyErr_Clear(); /* Not a fatal error if codec isn't available */
  1025. if (PySys_SetObject("__stderr__", std) < 0) {
  1026. Py_DECREF(std);
  1027. goto error;
  1028. }
  1029. if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
  1030. Py_DECREF(std);
  1031. goto error;
  1032. }
  1033. Py_DECREF(std);
  1034. #endif
  1035. if (0) {
  1036. error:
  1037. status = -1;
  1038. }
  1039. /* We won't need them anymore. */
  1040. if (_Py_StandardStreamEncoding) {
  1041. PyMem_RawFree(_Py_StandardStreamEncoding);
  1042. _Py_StandardStreamEncoding = NULL;
  1043. }
  1044. if (_Py_StandardStreamErrors) {
  1045. PyMem_RawFree(_Py_StandardStreamErrors);
  1046. _Py_StandardStreamErrors = NULL;
  1047. }
  1048. PyMem_Free(pythonioencoding);
  1049. Py_XDECREF(bimod);
  1050. Py_XDECREF(iomod);
  1051. return status;
  1052. }
  1053. static void
  1054. _Py_FatalError_DumpTracebacks(int fd)
  1055. {
  1056. PyThreadState *tstate;
  1057. #ifdef WITH_THREAD
  1058. /* PyGILState_GetThisThreadState() works even if the GIL was released */
  1059. tstate = PyGILState_GetThisThreadState();
  1060. #else
  1061. tstate = PyThreadState_GET();
  1062. #endif
  1063. if (tstate == NULL) {
  1064. /* _Py_DumpTracebackThreads() requires the thread state to display
  1065. * frames */
  1066. return;
  1067. }
  1068. fputc('\n', stderr);
  1069. fflush(stderr);
  1070. /* display the current Python stack */
  1071. _Py_DumpTracebackThreads(fd, tstate->interp, tstate);
  1072. }
  1073. /* Print the current exception (if an exception is set) with its traceback,
  1074. or display the current Python stack.
  1075. Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
  1076. called on catastrophic cases.
  1077. Return 1 if the traceback was displayed, 0 otherwise. */
  1078. static int
  1079. _Py_FatalError_PrintExc(int fd)
  1080. {
  1081. PyObject *ferr, *res;
  1082. PyObject *exception, *v, *tb;
  1083. int has_tb;
  1084. if (PyThreadState_GET() == NULL) {
  1085. /* The GIL is released: trying to acquire it is likely to deadlock,
  1086. just give up. */
  1087. return 0;
  1088. }
  1089. PyErr_Fetch(&exception, &v, &tb);
  1090. if (exception == NULL) {
  1091. /* No current exception */
  1092. return 0;
  1093. }
  1094. ferr = _PySys_GetObjectId(&PyId_stderr);
  1095. if (ferr == NULL || ferr == Py_None) {
  1096. /* sys.stderr is not set yet or set to None,
  1097. no need to try to display the exception */
  1098. return 0;
  1099. }
  1100. PyErr_NormalizeException(&exception, &v, &tb);
  1101. if (tb == NULL) {
  1102. tb = Py_None;
  1103. Py_INCREF(tb);
  1104. }
  1105. PyException_SetTraceback(v, tb);
  1106. if (exception == NULL) {
  1107. /* PyErr_NormalizeException() failed */
  1108. return 0;
  1109. }
  1110. has_tb = (tb != Py_None);
  1111. PyErr_Display(exception, v, tb);
  1112. Py_XDECREF(exception);
  1113. Py_XDECREF(v);
  1114. Py_XDECREF(tb);
  1115. /* sys.stderr may be buffered: call sys.stderr.flush() */
  1116. res = _PyObject_CallMethodId(ferr, &PyId_flush, "");
  1117. if (res == NULL)
  1118. PyErr_Clear();
  1119. else
  1120. Py_DECREF(res);
  1121. return has_tb;
  1122. }
  1123. /* Print fatal error message and abort */
  1124. void
  1125. Py_FatalError(const char *msg)
  1126. {
  1127. const int fd = fileno(stderr);
  1128. static int reentrant = 0;
  1129. #ifdef MS_WINDOWS
  1130. size_t len;
  1131. WCHAR* buffer;
  1132. size_t i;
  1133. #endif
  1134. if (reentrant) {
  1135. /* Py_FatalError() caused a second fatal error.
  1136. Example: flush_std_files() raises a recursion error. */
  1137. goto exit;
  1138. }
  1139. reentrant = 1;
  1140. fprintf(stderr, "Fatal Python error: %s\n", msg);
  1141. fflush(stderr); /* it helps in Windows debug build */
  1142. /* Print the exception (if an exception is set) with its traceback,
  1143. * or display the current Python stack. */
  1144. if (!_Py_FatalError_PrintExc(fd))
  1145. _Py_FatalError_DumpTracebacks(fd);
  1146. /* The main purpose of faulthandler is to display the traceback. We already
  1147. * did our best to display it. So faulthandler can now be disabled.
  1148. * (Don't trigger it on abort().) */
  1149. _PyFaulthandler_Fini();
  1150. /* Check if the current Python thread hold the GIL */
  1151. if (PyThreadState_GET() != NULL) {
  1152. /* Flush sys.stdout and sys.stderr */
  1153. flush_std_files();
  1154. }
  1155. #ifdef MS_WINDOWS
  1156. len = strlen(msg);
  1157. /* Convert the message to wchar_t. This uses a simple one-to-one
  1158. conversion, assuming that the this error message actually uses ASCII
  1159. only. If this ceases to be true, we will have to convert. */
  1160. buffer = alloca( (len+1) * (sizeof *buffer));
  1161. for( i=0; i<=len; ++i)
  1162. buffer[i] = msg[i];
  1163. OutputDebugStringW(L"Fatal Python error: ");
  1164. OutputDebugStringW(buffer);
  1165. OutputDebugStringW(L"\n");
  1166. #endif /* MS_WINDOWS */
  1167. exit:
  1168. #if defined(MS_WINDOWS) && defined(_DEBUG)
  1169. DebugBreak();
  1170. #endif
  1171. abort();
  1172. }
  1173. /* Clean up and exit */
  1174. #ifdef WITH_THREAD
  1175. #include "pythread.h"
  1176. #endif
  1177. static void (*pyexitfunc)(void) = NULL;
  1178. /* For the atexit module. */
  1179. void _Py_PyAtExit(void (*func)(void))
  1180. {
  1181. pyexitfunc = func;
  1182. }
  1183. static void
  1184. call_py_exitfuncs(void)
  1185. {
  1186. if (pyexitfunc == NULL)
  1187. return;
  1188. (*pyexitfunc)();
  1189. PyErr_Clear();
  1190. }
  1191. /* Wait until threading._shutdown completes, provided
  1192. the threading module was imported in the first place.
  1193. The shutdown routine will wait until all non-daemon
  1194. "threading" threads have completed. */
  1195. static void
  1196. wait_for_thread_shutdown(void)
  1197. {
  1198. #ifdef WITH_THREAD
  1199. _Py_IDENTIFIER(_shutdown);
  1200. PyObject *result;
  1201. PyThreadState *tstate = PyThreadState_GET();
  1202. PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
  1203. "threading");
  1204. if (threading == NULL) {
  1205. /* threading not imported */
  1206. PyErr_Clear();
  1207. return;
  1208. }
  1209. result = _PyObject_CallMethodId(threading, &PyId__shutdown, "");
  1210. if (result == NULL) {
  1211. PyErr_WriteUnraisable(threading);
  1212. }
  1213. else {
  1214. Py_DECREF(result);
  1215. }
  1216. Py_DECREF(threading);
  1217. #endif
  1218. }
  1219. #define NEXITFUNCS 32
  1220. static void (*exitfuncs[NEXITFUNCS])(void);
  1221. static int nexitfuncs = 0;
  1222. int Py_AtExit(void (*func)(void))
  1223. {
  1224. if (nexitfuncs >= NEXITFUNCS)
  1225. return -1;
  1226. exitfuncs[nexitfuncs++] = func;
  1227. return 0;
  1228. }
  1229. static void
  1230. call_ll_exitfuncs(void)
  1231. {
  1232. while (nexitfuncs > 0)
  1233. (*exitfuncs[--nexitfuncs])();
  1234. fflush(stdout);
  1235. fflush(stderr);
  1236. }
  1237. void
  1238. Py_Exit(int sts)
  1239. {
  1240. Py_Finalize();
  1241. exit(sts);
  1242. }
  1243. static void
  1244. initsigs(void)
  1245. {
  1246. #ifdef SIGPIPE
  1247. PyOS_setsig(SIGPIPE, SIG_IGN);
  1248. #endif
  1249. #ifdef SIGXFZ
  1250. PyOS_setsig(SIGXFZ, SIG_IGN);
  1251. #endif
  1252. #ifdef SIGXFSZ
  1253. PyOS_setsig(SIGXFSZ, SIG_IGN);
  1254. #endif
  1255. PyOS_InitInterrupts(); /* May imply initsignal() */
  1256. if (PyErr_Occurred()) {
  1257. Py_FatalError("Py_Initialize: can't import signal");
  1258. }
  1259. }
  1260. /* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
  1261. *
  1262. * All of the code in this function must only use async-signal-safe functions,
  1263. * listed at `man 7 signal` or
  1264. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  1265. */
  1266. void
  1267. _Py_RestoreSignals(void)
  1268. {
  1269. #ifdef SIGPIPE
  1270. PyOS_setsig(SIGPIPE, SIG_DFL);
  1271. #endif
  1272. #ifdef SIGXFZ
  1273. PyOS_setsig(SIGXFZ, SIG_DFL);
  1274. #endif
  1275. #ifdef SIGXFSZ
  1276. PyOS_setsig(SIGXFSZ, SIG_DFL);
  1277. #endif
  1278. }
  1279. /*
  1280. * The file descriptor fd is considered ``interactive'' if either
  1281. * a) isatty(fd) is TRUE, or
  1282. * b) the -i flag was given, and the filename associated with
  1283. * the descriptor is NULL or "<stdin>" or "???".
  1284. */
  1285. int
  1286. Py_FdIsInteractive(FILE *fp, const char *filename)
  1287. {
  1288. if (isatty((int)fileno(fp)))
  1289. return 1;
  1290. if (!Py_InteractiveFlag)
  1291. return 0;
  1292. return (filename == NULL) ||
  1293. (strcmp(filename, "<stdin>") == 0) ||
  1294. (strcmp(filename, "???") == 0);
  1295. }
  1296. /* Wrappers around sigaction() or signal(). */
  1297. PyOS_sighandler_t
  1298. PyOS_getsig(int sig)
  1299. {
  1300. #ifdef HAVE_SIGACTION
  1301. struct sigaction context;
  1302. if (sigaction(sig, NULL, &context) == -1)
  1303. return SIG_ERR;
  1304. return context.sa_handler;
  1305. #else
  1306. PyOS_sighandler_t handler;
  1307. /* Special signal handling for the secure CRT in Visual Studio 2005 */
  1308. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1309. switch (sig) {
  1310. /* Only these signals are valid */
  1311. case SIGINT:
  1312. case SIGILL:
  1313. case SIGFPE:
  1314. case SIGSEGV:
  1315. case SIGTERM:
  1316. case SIGBREAK:
  1317. case SIGABRT:
  1318. break;
  1319. /* Don't call signal() with other values or it will assert */
  1320. default:
  1321. return SIG_ERR;
  1322. }
  1323. #endif /* _MSC_VER && _MSC_VER >= 1400 */
  1324. handler = signal(sig, SIG_IGN);
  1325. if (handler != SIG_ERR)
  1326. signal(sig, handler);
  1327. return handler;
  1328. #endif
  1329. }
  1330. /*
  1331. * All of the code in this function must only use async-signal-safe functions,
  1332. * listed at `man 7 signal` or
  1333. * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
  1334. */
  1335. PyOS_sighandler_t
  1336. PyOS_setsig(int sig, PyOS_sighandler_t handler)
  1337. {
  1338. #ifdef HAVE_SIGACTION
  1339. /* Some code in Modules/signalmodule.c depends on sigaction() being
  1340. * used here if HAVE_SIGACTION is defined. Fix that if this code
  1341. * changes to invalidate that assumption.
  1342. */
  1343. struct sigaction context, ocontext;
  1344. context.sa_handler = handler;
  1345. sigemptyset(&context.sa_mask);
  1346. context.sa_flags = 0;
  1347. if (sigaction(sig, &context, &ocontext) == -1)
  1348. return SIG_ERR;
  1349. return ocontext.sa_handler;
  1350. #else
  1351. PyOS_sighandler_t oldhandler;
  1352. oldhandler = signal(sig, handler);
  1353. #ifdef HAVE_SIGINTERRUPT
  1354. siginterrupt(sig, 1);
  1355. #endif
  1356. return oldhandler;
  1357. #endif
  1358. }
  1359. #ifdef __cplusplus
  1360. }
  1361. #endif