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.

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