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.

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