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.

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