blob: 0700569ac5affae1df2d1b99a896ea358c443782 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
45
46#ifdef __cplusplus
47extern "C" {
48#endif
49
50extern wchar_t *Py_GetPath(void);
51
52extern grammar _PyParser_Grammar; /* From graminit.c */
53
54/* Forward */
55static void initmain(PyInterpreterState *interp);
56static int initfsencoding(PyInterpreterState *interp);
57static void initsite(void);
58static int initstdio(void);
59static void initsigs(void);
60static void call_py_exitfuncs(void);
61static void wait_for_thread_shutdown(void);
62static void call_ll_exitfuncs(void);
63extern int _PyUnicode_Init(void);
64extern int _PyStructSequence_Init(void);
65extern void _PyUnicode_Fini(void);
66extern int _PyLong_Init(void);
67extern void PyLong_Fini(void);
68extern int _PyFaulthandler_Init(void);
69extern void _PyFaulthandler_Fini(void);
70extern void _PyHash_Fini(void);
71extern int _PyTraceMalloc_Init(void);
72extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070073extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100074
Nick Coghland6009512014-11-20 21:39:37 +100075extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
76extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100077
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078_PyRuntimeState _PyRuntime = {0, 0};
79
80void
81_PyRuntime_Initialize(void)
82{
83 /* XXX We only initialize once in the process, which aligns with
84 the static initialization of the former globals now found in
85 _PyRuntime. However, _PyRuntime *should* be initialized with
86 every Py_Initialize() call, but doing so breaks the runtime.
87 This is because the runtime state is not properly finalized
88 currently. */
89 static int initialized = 0;
90 if (initialized)
91 return;
92 initialized = 1;
93 _PyRuntimeState_Init(&_PyRuntime);
94}
95
96void
97_PyRuntime_Finalize(void)
98{
99 _PyRuntimeState_Fini(&_PyRuntime);
100}
101
102int
103_Py_IsFinalizing(void)
104{
105 return _PyRuntime.finalizing != NULL;
106}
107
Nick Coghland6009512014-11-20 21:39:37 +1000108/* Global configuration variable declarations are in pydebug.h */
109/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
110int Py_DebugFlag; /* Needed by parser.c */
111int Py_VerboseFlag; /* Needed by import.c */
112int Py_QuietFlag; /* Needed by sysmodule.c */
113int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
114int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
115int Py_OptimizeFlag = 0; /* Needed by compile.c */
116int Py_NoSiteFlag; /* Suppress 'import site' */
117int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
118int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
119int Py_FrozenFlag; /* Needed by getpath.c */
120int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000122int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
123int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
124int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
125int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700126#ifdef MS_WINDOWS
127int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700128int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700129#endif
Nick Coghland6009512014-11-20 21:39:37 +1000130
Nick Coghland6009512014-11-20 21:39:37 +1000131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
139{
140 return PyImport_ImportModule("warnings");
141}
142
Eric Snowc7ec9982017-05-23 23:00:52 -0700143
Eric Snow1abcf672017-05-23 21:46:51 -0700144/* APIs to access the initialization flags
145 *
146 * Can be called prior to Py_Initialize.
147 */
Nick Coghland6009512014-11-20 21:39:37 +1000148
Eric Snow1abcf672017-05-23 21:46:51 -0700149int
150_Py_IsCoreInitialized(void)
151{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600152 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700153}
Nick Coghland6009512014-11-20 21:39:37 +1000154
155int
156Py_IsInitialized(void)
157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000159}
160
161/* Helper to allow an embedding application to override the normal
162 * mechanism that attempts to figure out an appropriate IO encoding
163 */
164
165static char *_Py_StandardStreamEncoding = NULL;
166static char *_Py_StandardStreamErrors = NULL;
167
168int
169Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
170{
171 if (Py_IsInitialized()) {
172 /* This is too late to have any effect */
173 return -1;
174 }
175 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
176 * initialised yet.
177 *
178 * However, the raw memory allocators are initialised appropriately
179 * as C static variables, so _PyMem_RawStrdup is OK even though
180 * Py_Initialize hasn't been called yet.
181 */
182 if (encoding) {
183 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
184 if (!_Py_StandardStreamEncoding) {
185 return -2;
186 }
187 }
188 if (errors) {
189 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
190 if (!_Py_StandardStreamErrors) {
191 if (_Py_StandardStreamEncoding) {
192 PyMem_RawFree(_Py_StandardStreamEncoding);
193 }
194 return -3;
195 }
196 }
Steve Dower39294992016-08-30 21:22:36 -0700197#ifdef MS_WINDOWS
198 if (_Py_StandardStreamEncoding) {
199 /* Overriding the stream encoding implies legacy streams */
200 Py_LegacyWindowsStdioFlag = 1;
201 }
202#endif
Nick Coghland6009512014-11-20 21:39:37 +1000203 return 0;
204}
205
Nick Coghlan6ea41862017-06-11 13:16:15 +1000206
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000207/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
208 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000209 initializations fail, a fatal error is issued and the function does
210 not return. On return, the first thread and interpreter state have
211 been created.
212
213 Locking: you must hold the interpreter lock while calling this.
214 (If the lock has not yet been initialized, that's equivalent to
215 having the lock, but you cannot use multiple threads.)
216
217*/
218
219static int
220add_flag(int flag, const char *envs)
221{
222 int env = atoi(envs);
223 if (flag < env)
224 flag = env;
225 if (flag < 1)
226 flag = 1;
227 return flag;
228}
229
230static char*
231get_codec_name(const char *encoding)
232{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200233 const char *name_utf8;
234 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000235 PyObject *codec, *name = NULL;
236
237 codec = _PyCodec_Lookup(encoding);
238 if (!codec)
239 goto error;
240
241 name = _PyObject_GetAttrId(codec, &PyId_name);
242 Py_CLEAR(codec);
243 if (!name)
244 goto error;
245
Serhiy Storchaka06515832016-11-20 09:13:07 +0200246 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000247 if (name_utf8 == NULL)
248 goto error;
249 name_str = _PyMem_RawStrdup(name_utf8);
250 Py_DECREF(name);
251 if (name_str == NULL) {
252 PyErr_NoMemory();
253 return NULL;
254 }
255 return name_str;
256
257error:
258 Py_XDECREF(codec);
259 Py_XDECREF(name);
260 return NULL;
261}
262
263static char*
264get_locale_encoding(void)
265{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700266#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000267 char* codeset = nl_langinfo(CODESET);
268 if (!codeset || codeset[0] == '\0') {
269 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
270 return NULL;
271 }
272 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200273#elif defined(__ANDROID__)
274 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000275#else
276 PyErr_SetNone(PyExc_NotImplementedError);
277 return NULL;
278#endif
279}
280
281static void
Eric Snow1abcf672017-05-23 21:46:51 -0700282initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000283{
284 PyObject *importlib;
285 PyObject *impmod;
Eric Snow93c92f72017-09-13 23:46:04 -0700286 PyObject *sys_modules;
Nick Coghland6009512014-11-20 21:39:37 +1000287 PyObject *value;
288
289 /* Import _importlib through its frozen version, _frozen_importlib. */
290 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
291 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
292 }
293 else if (Py_VerboseFlag) {
294 PySys_FormatStderr("import _frozen_importlib # frozen\n");
295 }
296 importlib = PyImport_AddModule("_frozen_importlib");
297 if (importlib == NULL) {
298 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
299 "sys.modules");
300 }
301 interp->importlib = importlib;
302 Py_INCREF(interp->importlib);
303
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300304 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
305 if (interp->import_func == NULL)
306 Py_FatalError("Py_Initialize: __import__ not found");
307 Py_INCREF(interp->import_func);
308
Victor Stinnercd6e6942015-09-18 09:11:57 +0200309 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000310 impmod = PyInit_imp();
311 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200312 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000313 }
314 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200315 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000316 }
Eric Snow93c92f72017-09-13 23:46:04 -0700317 sys_modules = PyImport_GetModuleDict();
318 if (Py_VerboseFlag) {
319 PySys_FormatStderr("import sys # builtin\n");
320 }
321 if (PyDict_SetItemString(sys_modules, "_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000322 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
323 }
324
Victor Stinnercd6e6942015-09-18 09:11:57 +0200325 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000326 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200327 if (value != NULL) {
328 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700329 value = PyObject_CallMethod(importlib,
330 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200331 }
Nick Coghland6009512014-11-20 21:39:37 +1000332 if (value == NULL) {
333 PyErr_Print();
334 Py_FatalError("Py_Initialize: importlib install failed");
335 }
336 Py_DECREF(value);
337 Py_DECREF(impmod);
338
339 _PyImportZip_Init();
340}
341
Eric Snow1abcf672017-05-23 21:46:51 -0700342static void
343initexternalimport(PyInterpreterState *interp)
344{
345 PyObject *value;
346 value = PyObject_CallMethod(interp->importlib,
347 "_install_external_importers", "");
348 if (value == NULL) {
349 PyErr_Print();
350 Py_FatalError("Py_EndInitialization: external importer setup failed");
351 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200352 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700353}
Nick Coghland6009512014-11-20 21:39:37 +1000354
Nick Coghlan6ea41862017-06-11 13:16:15 +1000355/* Helper functions to better handle the legacy C locale
356 *
357 * The legacy C locale assumes ASCII as the default text encoding, which
358 * causes problems not only for the CPython runtime, but also other
359 * components like GNU readline.
360 *
361 * Accordingly, when the CLI detects it, it attempts to coerce it to a
362 * more capable UTF-8 based alternative as follows:
363 *
364 * if (_Py_LegacyLocaleDetected()) {
365 * _Py_CoerceLegacyLocale();
366 * }
367 *
368 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
369 *
370 * Locale coercion also impacts the default error handler for the standard
371 * streams: while the usual default is "strict", the default for the legacy
372 * C locale and for any of the coercion target locales is "surrogateescape".
373 */
374
375int
376_Py_LegacyLocaleDetected(void)
377{
378#ifndef MS_WINDOWS
379 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000380 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
381 * the POSIX locale as a simple alias for the C locale, so
382 * we may also want to check for that explicitly.
383 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000384 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
385 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
386#else
387 /* Windows uses code pages instead of locales, so no locale is legacy */
388 return 0;
389#endif
390}
391
Nick Coghlaneb817952017-06-18 12:29:42 +1000392static const char *_C_LOCALE_WARNING =
393 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
394 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
395 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
396 "locales is recommended.\n";
397
398static int
399_legacy_locale_warnings_enabled(void)
400{
401 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
402 return (coerce_c_locale != NULL &&
403 strncmp(coerce_c_locale, "warn", 5) == 0);
404}
405
406static void
407_emit_stderr_warning_for_legacy_locale(void)
408{
409 if (_legacy_locale_warnings_enabled()) {
410 if (_Py_LegacyLocaleDetected()) {
411 fprintf(stderr, "%s", _C_LOCALE_WARNING);
412 }
413 }
414}
415
Nick Coghlan6ea41862017-06-11 13:16:15 +1000416typedef struct _CandidateLocale {
417 const char *locale_name; /* The locale to try as a coercion target */
418} _LocaleCoercionTarget;
419
420static _LocaleCoercionTarget _TARGET_LOCALES[] = {
421 {"C.UTF-8"},
422 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000423 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000424 {NULL}
425};
426
427static char *
428get_default_standard_stream_error_handler(void)
429{
430 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
431 if (ctype_loc != NULL) {
432 /* "surrogateescape" is the default in the legacy C locale */
433 if (strcmp(ctype_loc, "C") == 0) {
434 return "surrogateescape";
435 }
436
437#ifdef PY_COERCE_C_LOCALE
438 /* "surrogateescape" is the default in locale coercion target locales */
439 const _LocaleCoercionTarget *target = NULL;
440 for (target = _TARGET_LOCALES; target->locale_name; target++) {
441 if (strcmp(ctype_loc, target->locale_name) == 0) {
442 return "surrogateescape";
443 }
444 }
445#endif
446 }
447
448 /* Otherwise return NULL to request the typical default error handler */
449 return NULL;
450}
451
452#ifdef PY_COERCE_C_LOCALE
453static const char *_C_LOCALE_COERCION_WARNING =
454 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
455 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
456
457static void
458_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
459{
460 const char *newloc = target->locale_name;
461
462 /* Reset locale back to currently configured defaults */
463 setlocale(LC_ALL, "");
464
465 /* Set the relevant locale environment variable */
466 if (setenv("LC_CTYPE", newloc, 1)) {
467 fprintf(stderr,
468 "Error setting LC_CTYPE, skipping C locale coercion\n");
469 return;
470 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000471 if (_legacy_locale_warnings_enabled()) {
472 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
473 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000474
475 /* Reconfigure with the overridden environment variables */
476 setlocale(LC_ALL, "");
477}
478#endif
479
480void
481_Py_CoerceLegacyLocale(void)
482{
483#ifdef PY_COERCE_C_LOCALE
484 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
485 * the locale settings *before* we try to do anything with the command
486 * line arguments. For cross-platform debugging purposes, we also need
487 * to give end users a way to force even scripts that are otherwise
488 * isolated from their environment to use the legacy ASCII-centric C
489 * locale.
490 *
491 * Ignoring -E and -I is safe from a security perspective, as we only use
492 * the setting to turn *off* the implicit locale coercion, and anyone with
493 * access to the process environment already has the ability to set
494 * `LC_ALL=C` to override the C level locale settings anyway.
495 */
496 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
497 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
498 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
499 const char *locale_override = getenv("LC_ALL");
500 if (locale_override == NULL || *locale_override == '\0') {
501 /* LC_ALL is also not set (or is set to an empty string) */
502 const _LocaleCoercionTarget *target = NULL;
503 for (target = _TARGET_LOCALES; target->locale_name; target++) {
504 const char *new_locale = setlocale(LC_CTYPE,
505 target->locale_name);
506 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000507#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
508 /* Also ensure that nl_langinfo works in this locale */
509 char *codeset = nl_langinfo(CODESET);
510 if (!codeset || *codeset == '\0') {
511 /* CODESET is not set or empty, so skip coercion */
512 new_locale = NULL;
513 setlocale(LC_CTYPE, "");
514 continue;
515 }
516#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000517 /* Successfully configured locale, so make it the default */
518 _coerce_default_locale_settings(target);
519 return;
520 }
521 }
522 }
523 }
524 /* No C locale warning here, as Py_Initialize will emit one later */
525#endif
526}
527
528
Eric Snow1abcf672017-05-23 21:46:51 -0700529/* Global initializations. Can be undone by Py_Finalize(). Don't
530 call this twice without an intervening Py_Finalize() call.
531
532 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
533 must have a corresponding call to Py_Finalize.
534
535 Locking: you must hold the interpreter lock while calling these APIs.
536 (If the lock has not yet been initialized, that's equivalent to
537 having the lock, but you cannot use multiple threads.)
538
539*/
540
541/* Begin interpreter initialization
542 *
543 * On return, the first thread and interpreter state have been created,
544 * but the compiler, signal handling, multithreading and
545 * multiple interpreter support, and codec infrastructure are not yet
546 * available.
547 *
548 * The import system will support builtin and frozen modules only.
549 * The only supported io is writing to sys.stderr
550 *
551 * If any operation invoked by this function fails, a fatal error is
552 * issued and the function does not return.
553 *
554 * Any code invoked from this function should *not* assume it has access
555 * to the Python C API (unless the API is explicitly listed as being
556 * safe to call without calling Py_Initialize first)
557 */
558
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200559/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700560 * Py_ReadConfig and Py_EndInitialization
561 */
562
563void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000564{
565 PyInterpreterState *interp;
566 PyThreadState *tstate;
567 PyObject *bimod, *sysmod, *pstderr;
568 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700569 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700570 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000571
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600572 _PyRuntime_Initialize();
573
Eric Snow1abcf672017-05-23 21:46:51 -0700574 if (config != NULL) {
575 core_config = *config;
576 }
577
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600578 if (_PyRuntime.initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700579 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
580 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600581 if (_PyRuntime.core_initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700582 Py_FatalError("Py_InitializeCore: runtime core already initialized");
583 }
584
585 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
586 * threads behave a little more gracefully at interpreter shutdown.
587 * We clobber it here so the new interpreter can start with a clean
588 * slate.
589 *
590 * However, this may still lead to misbehaviour if there are daemon
591 * threads still hanging around from a previous Py_Initialize/Finalize
592 * pair :(
593 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600594 _PyRuntime.finalizing = NULL;
595
596 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
597 fprintf(stderr,
598 "Error in PYTHONMALLOC: unknown allocator \"%s\"!\n",
599 core_config.allocator);
600 exit(1);
601 }
Nick Coghland6009512014-11-20 21:39:37 +1000602
Nick Coghlan6ea41862017-06-11 13:16:15 +1000603#ifdef __ANDROID__
604 /* Passing "" to setlocale() on Android requests the C locale rather
605 * than checking environment variables, so request C.UTF-8 explicitly
606 */
607 setlocale(LC_CTYPE, "C.UTF-8");
608#else
609#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000610 /* Set up the LC_CTYPE locale, so we can obtain
611 the locale's charset without having to switch
612 locales. */
613 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000614 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000615#endif
Nick Coghland6009512014-11-20 21:39:37 +1000616#endif
617
618 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
619 Py_DebugFlag = add_flag(Py_DebugFlag, p);
620 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
621 Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
622 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
623 Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
624 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
625 Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700626 /* The variable is only tested for existence here;
627 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000628 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
629 Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700630#ifdef MS_WINDOWS
631 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
632 Py_LegacyWindowsFSEncodingFlag = add_flag(Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700633 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
634 Py_LegacyWindowsStdioFlag = add_flag(Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700635#endif
Nick Coghland6009512014-11-20 21:39:37 +1000636
Eric Snow1abcf672017-05-23 21:46:51 -0700637 _Py_HashRandomization_Init(&core_config);
638 if (!core_config.use_hash_seed || core_config.hash_seed) {
639 /* Random or non-zero hash seed */
640 Py_HashRandomizationFlag = 1;
641 }
Nick Coghland6009512014-11-20 21:39:37 +1000642
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600643 _PyInterpreterState_Enable(&_PyRuntime);
Nick Coghland6009512014-11-20 21:39:37 +1000644 interp = PyInterpreterState_New();
645 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700646 Py_FatalError("Py_InitializeCore: can't make main interpreter");
647 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700648 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000649
650 tstate = PyThreadState_New(interp);
651 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700652 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000653 (void) PyThreadState_Swap(tstate);
654
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000655 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000656 destroying the GIL might fail when it is being referenced from
657 another running thread (see issue #9901).
658 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000659 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000660 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000661 /* Auto-thread-state API */
662 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000663
664 _Py_ReadyTypes();
665
666 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700667 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000668
669 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700670 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000671
672 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700673 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000674
675 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700676 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000677
Eric Snow93c92f72017-09-13 23:46:04 -0700678 interp->modules = PyDict_New();
679 if (interp->modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700680 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Nick Coghland6009512014-11-20 21:39:37 +1000681
682 /* Init Unicode implementation; relies on the codec registry */
683 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700684 Py_FatalError("Py_InitializeCore: can't initialize unicode");
685
Nick Coghland6009512014-11-20 21:39:37 +1000686 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700687 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000688
689 bimod = _PyBuiltin_Init();
690 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700691 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snow93c92f72017-09-13 23:46:04 -0700692 _PyImport_FixupBuiltin(bimod, "builtins");
Nick Coghland6009512014-11-20 21:39:37 +1000693 interp->builtins = PyModule_GetDict(bimod);
694 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700695 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000696 Py_INCREF(interp->builtins);
697
698 /* initialize builtin exceptions */
699 _PyExc_Init(bimod);
700
Eric Snow93c92f72017-09-13 23:46:04 -0700701 sysmod = _PySys_BeginInit();
702 if (sysmod == NULL)
703 Py_FatalError("Py_InitializeCore: can't initialize sys");
704 interp->sysdict = PyModule_GetDict(sysmod);
705 if (interp->sysdict == NULL)
706 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
707 Py_INCREF(interp->sysdict);
708 _PyImport_FixupBuiltin(sysmod, "sys");
709 PyDict_SetItemString(interp->sysdict, "modules",
710 interp->modules);
711
Nick Coghland6009512014-11-20 21:39:37 +1000712 /* Set up a preliminary stderr printer until we have enough
713 infrastructure for the io module in place. */
714 pstderr = PyFile_NewStdPrinter(fileno(stderr));
715 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700716 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000717 _PySys_SetObjectId(&PyId_stderr, pstderr);
718 PySys_SetObject("__stderr__", pstderr);
719 Py_DECREF(pstderr);
720
721 _PyImport_Init();
722
723 _PyImportHooks_Init();
724
725 /* Initialize _warnings. */
726 _PyWarnings_Init();
727
Eric Snow1abcf672017-05-23 21:46:51 -0700728 /* This call sets up builtin and frozen import support */
729 if (!interp->core_config._disable_importlib) {
730 initimport(interp, sysmod);
731 }
732
733 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600734 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700735}
736
Eric Snowc7ec9982017-05-23 23:00:52 -0700737/* Read configuration settings from standard locations
738 *
739 * This function doesn't make any changes to the interpreter state - it
740 * merely populates any missing configuration settings. This allows an
741 * embedding application to completely override a config option by
742 * setting it before calling this function, or else modify the default
743 * setting before passing the fully populated config to Py_EndInitialization.
744 *
745 * More advanced selective initialization tricks are possible by calling
746 * this function multiple times with various preconfigured settings.
747 */
748
749int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
750{
751 /* Signal handlers are installed by default */
752 if (config->install_signal_handlers < 0) {
753 config->install_signal_handlers = 1;
754 }
755
756 return 0;
757}
758
759/* Update interpreter state based on supplied configuration settings
760 *
761 * After calling this function, most of the restrictions on the interpreter
762 * are lifted. The only remaining incomplete settings are those related
763 * to the main module (sys.argv[0], __main__ metadata)
764 *
765 * Calling this when the interpreter is not initializing, is already
766 * initialized or without a valid current thread state is a fatal error.
767 * Other errors should be reported as normal Python exceptions with a
768 * non-zero return code.
769 */
770int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700771{
772 PyInterpreterState *interp;
773 PyThreadState *tstate;
774
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600775 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700776 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
777 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600778 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700779 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
780 }
781
Eric Snow1abcf672017-05-23 21:46:51 -0700782 /* Get current thread state and interpreter pointer */
783 tstate = PyThreadState_GET();
784 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700785 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700786 interp = tstate->interp;
787 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700788 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700789
790 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700791 interp->config = *config;
792
Eric Snow1abcf672017-05-23 21:46:51 -0700793 if (interp->core_config._disable_importlib) {
794 /* Special mode for freeze_importlib: run with no import system
795 *
796 * This means anything which needs support from extension modules
797 * or pure Python code in the standard library won't work.
798 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600799 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700800 return 0;
801 }
802 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000803
Victor Stinner13019fd2015-04-03 13:10:54 +0200804 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700805 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200806
Eric Snow1abcf672017-05-23 21:46:51 -0700807 /* Finish setting up the sys module and import system */
808 /* GetPath may initialize state that _PySys_EndInit locks
809 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700810 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700811 PySys_SetPath(Py_GetPath());
812 if (_PySys_EndInit(interp->sysdict) < 0)
813 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700814 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000815
816 /* initialize the faulthandler module */
817 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700818 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000819
Nick Coghland6009512014-11-20 21:39:37 +1000820 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700821 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000822
Eric Snowc7ec9982017-05-23 23:00:52 -0700823 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000824 initsigs(); /* Signal handling stuff, including initintr() */
825
826 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700827 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000828
829 initmain(interp); /* Module __main__ */
830 if (initstdio() < 0)
831 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000833
834 /* Initialize warnings. */
835 if (PySys_HasWarnOptions()) {
836 PyObject *warnings_module = PyImport_ImportModule("warnings");
837 if (warnings_module == NULL) {
838 fprintf(stderr, "'import warnings' failed; traceback:\n");
839 PyErr_Print();
840 }
841 Py_XDECREF(warnings_module);
842 }
843
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600844 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700845
Nick Coghland6009512014-11-20 21:39:37 +1000846 if (!Py_NoSiteFlag)
847 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700848
Eric Snowc7ec9982017-05-23 23:00:52 -0700849 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000850}
851
Eric Snowc7ec9982017-05-23 23:00:52 -0700852#undef _INIT_DEBUG_PRINT
853
Nick Coghland6009512014-11-20 21:39:37 +1000854void
Eric Snow1abcf672017-05-23 21:46:51 -0700855_Py_InitializeEx_Private(int install_sigs, int install_importlib)
856{
857 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700858 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700859
860 /* TODO: Moar config options! */
861 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
862 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700863 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700864 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700865 /* TODO: Print any exceptions raised by these operations */
866 if (_Py_ReadMainInterpreterConfig(&config))
867 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
868 if (_Py_InitializeMainInterpreter(&config))
869 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700870}
871
872
873void
Nick Coghland6009512014-11-20 21:39:37 +1000874Py_InitializeEx(int install_sigs)
875{
876 _Py_InitializeEx_Private(install_sigs, 1);
877}
878
879void
880Py_Initialize(void)
881{
882 Py_InitializeEx(1);
883}
884
885
886#ifdef COUNT_ALLOCS
887extern void dump_counts(FILE*);
888#endif
889
890/* Flush stdout and stderr */
891
892static int
893file_is_closed(PyObject *fobj)
894{
895 int r;
896 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
897 if (tmp == NULL) {
898 PyErr_Clear();
899 return 0;
900 }
901 r = PyObject_IsTrue(tmp);
902 Py_DECREF(tmp);
903 if (r < 0)
904 PyErr_Clear();
905 return r > 0;
906}
907
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000908static int
Nick Coghland6009512014-11-20 21:39:37 +1000909flush_std_files(void)
910{
911 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
912 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
913 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000914 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000915
916 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700917 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000918 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000919 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000920 status = -1;
921 }
Nick Coghland6009512014-11-20 21:39:37 +1000922 else
923 Py_DECREF(tmp);
924 }
925
926 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700927 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000928 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000929 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000930 status = -1;
931 }
Nick Coghland6009512014-11-20 21:39:37 +1000932 else
933 Py_DECREF(tmp);
934 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000935
936 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000937}
938
939/* Undo the effect of Py_Initialize().
940
941 Beware: if multiple interpreter and/or thread states exist, these
942 are not wiped out; only the current thread and interpreter state
943 are deleted. But since everything else is deleted, those other
944 interpreter and thread states should no longer be used.
945
946 (XXX We should do better, e.g. wipe out all interpreters and
947 threads.)
948
949 Locking: as above.
950
951*/
952
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000953int
954Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000955{
956 PyInterpreterState *interp;
957 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000958 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000959
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600960 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000961 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000962
963 wait_for_thread_shutdown();
964
965 /* The interpreter is still entirely intact at this point, and the
966 * exit funcs may be relying on that. In particular, if some thread
967 * or exit func is still waiting to do an import, the import machinery
968 * expects Py_IsInitialized() to return true. So don't say the
969 * interpreter is uninitialized until after the exit funcs have run.
970 * Note that Threading.py uses an exit func to do a join on all the
971 * threads created thru it, so this also protects pending imports in
972 * the threads created via Threading.
973 */
974 call_py_exitfuncs();
975
976 /* Get current thread state and interpreter pointer */
977 tstate = PyThreadState_GET();
978 interp = tstate->interp;
979
980 /* Remaining threads (e.g. daemon threads) will automatically exit
981 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600982 _PyRuntime.finalizing = tstate;
983 _PyRuntime.initialized = 0;
984 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000985
Victor Stinnere0deff32015-03-24 13:46:18 +0100986 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000987 if (flush_std_files() < 0) {
988 status = -1;
989 }
Nick Coghland6009512014-11-20 21:39:37 +1000990
991 /* Disable signal handling */
992 PyOS_FiniInterrupts();
993
994 /* Collect garbage. This may call finalizers; it's nice to call these
995 * before all modules are destroyed.
996 * XXX If a __del__ or weakref callback is triggered here, and tries to
997 * XXX import a module, bad things can happen, because Python no
998 * XXX longer believes it's initialized.
999 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1000 * XXX is easy to provoke that way. I've also seen, e.g.,
1001 * XXX Exception exceptions.ImportError: 'No module named sha'
1002 * XXX in <function callback at 0x008F5718> ignored
1003 * XXX but I'm unclear on exactly how that one happens. In any case,
1004 * XXX I haven't seen a real-life report of either of these.
1005 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001006 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001007#ifdef COUNT_ALLOCS
1008 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1009 each collection might release some types from the type
1010 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001011 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001012 /* nothing */;
1013#endif
1014 /* Destroy all modules */
1015 PyImport_Cleanup();
1016
Victor Stinnere0deff32015-03-24 13:46:18 +01001017 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001018 if (flush_std_files() < 0) {
1019 status = -1;
1020 }
Nick Coghland6009512014-11-20 21:39:37 +10001021
1022 /* Collect final garbage. This disposes of cycles created by
1023 * class definitions, for example.
1024 * XXX This is disabled because it caused too many problems. If
1025 * XXX a __del__ or weakref callback triggers here, Python code has
1026 * XXX a hard time running, because even the sys module has been
1027 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1028 * XXX One symptom is a sequence of information-free messages
1029 * XXX coming from threads (if a __del__ or callback is invoked,
1030 * XXX other threads can execute too, and any exception they encounter
1031 * XXX triggers a comedy of errors as subsystem after subsystem
1032 * XXX fails to find what it *expects* to find in sys to help report
1033 * XXX the exception and consequent unexpected failures). I've also
1034 * XXX seen segfaults then, after adding print statements to the
1035 * XXX Python code getting called.
1036 */
1037#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001038 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001039#endif
1040
1041 /* Disable tracemalloc after all Python objects have been destroyed,
1042 so it is possible to use tracemalloc in objects destructor. */
1043 _PyTraceMalloc_Fini();
1044
1045 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1046 _PyImport_Fini();
1047
1048 /* Cleanup typeobject.c's internal caches. */
1049 _PyType_Fini();
1050
1051 /* unload faulthandler module */
1052 _PyFaulthandler_Fini();
1053
1054 /* Debugging stuff */
1055#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001056 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001057#endif
1058 /* dump hash stats */
1059 _PyHash_Fini();
1060
Eric Snow93c92f72017-09-13 23:46:04 -07001061 _PY_DEBUG_PRINT_TOTAL_REFS();
Nick Coghland6009512014-11-20 21:39:37 +10001062
1063#ifdef Py_TRACE_REFS
1064 /* Display all objects still alive -- this can invoke arbitrary
1065 * __repr__ overrides, so requires a mostly-intact interpreter.
1066 * Alas, a lot of stuff may still be alive now that will be cleaned
1067 * up later.
1068 */
1069 if (Py_GETENV("PYTHONDUMPREFS"))
1070 _Py_PrintReferences(stderr);
1071#endif /* Py_TRACE_REFS */
1072
1073 /* Clear interpreter state and all thread states. */
1074 PyInterpreterState_Clear(interp);
1075
1076 /* Now we decref the exception classes. After this point nothing
1077 can raise an exception. That's okay, because each Fini() method
1078 below has been checked to make sure no exceptions are ever
1079 raised.
1080 */
1081
1082 _PyExc_Fini();
1083
1084 /* Sundry finalizers */
1085 PyMethod_Fini();
1086 PyFrame_Fini();
1087 PyCFunction_Fini();
1088 PyTuple_Fini();
1089 PyList_Fini();
1090 PySet_Fini();
1091 PyBytes_Fini();
1092 PyByteArray_Fini();
1093 PyLong_Fini();
1094 PyFloat_Fini();
1095 PyDict_Fini();
1096 PySlice_Fini();
1097 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001098 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001099 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001100 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001101
1102 /* Cleanup Unicode implementation */
1103 _PyUnicode_Fini();
1104
1105 /* reset file system default encoding */
1106 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1107 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1108 Py_FileSystemDefaultEncoding = NULL;
1109 }
1110
1111 /* XXX Still allocated:
1112 - various static ad-hoc pointers to interned strings
1113 - int and float free list blocks
1114 - whatever various modules and libraries allocate
1115 */
1116
1117 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1118
1119 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001120 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001121
1122 /* Delete current thread. After this, many C API calls become crashy. */
1123 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001124
Nick Coghland6009512014-11-20 21:39:37 +10001125 PyInterpreterState_Delete(interp);
1126
1127#ifdef Py_TRACE_REFS
1128 /* Display addresses (& refcnts) of all objects still alive.
1129 * An address can be used to find the repr of the object, printed
1130 * above by _Py_PrintReferences.
1131 */
1132 if (Py_GETENV("PYTHONDUMPREFS"))
1133 _Py_PrintReferenceAddresses(stderr);
1134#endif /* Py_TRACE_REFS */
Victor Stinner34be807c2016-03-14 12:04:26 +01001135#ifdef WITH_PYMALLOC
1136 if (_PyMem_PymallocEnabled()) {
1137 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1138 if (opt != NULL && *opt != '\0')
1139 _PyObject_DebugMallocStats(stderr);
1140 }
Nick Coghland6009512014-11-20 21:39:37 +10001141#endif
1142
1143 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001144 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001145 return status;
1146}
1147
1148void
1149Py_Finalize(void)
1150{
1151 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001152}
1153
1154/* Create and initialize a new interpreter and thread, and return the
1155 new thread. This requires that Py_Initialize() has been called
1156 first.
1157
1158 Unsuccessful initialization yields a NULL pointer. Note that *no*
1159 exception information is available even in this case -- the
1160 exception information is held in the thread, and there is no
1161 thread.
1162
1163 Locking: as above.
1164
1165*/
1166
1167PyThreadState *
1168Py_NewInterpreter(void)
1169{
1170 PyInterpreterState *interp;
1171 PyThreadState *tstate, *save_tstate;
1172 PyObject *bimod, *sysmod;
1173
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001174 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001175 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1176
Victor Stinner8a1be612016-03-14 22:07:55 +01001177 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1178 interpreters: disable PyGILState_Check(). */
1179 _PyGILState_check_enabled = 0;
1180
Nick Coghland6009512014-11-20 21:39:37 +10001181 interp = PyInterpreterState_New();
1182 if (interp == NULL)
1183 return NULL;
1184
1185 tstate = PyThreadState_New(interp);
1186 if (tstate == NULL) {
1187 PyInterpreterState_Delete(interp);
1188 return NULL;
1189 }
1190
1191 save_tstate = PyThreadState_Swap(tstate);
1192
Eric Snow1abcf672017-05-23 21:46:51 -07001193 /* Copy the current interpreter config into the new interpreter */
1194 if (save_tstate != NULL) {
1195 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001196 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001197 } else {
1198 /* No current thread state, copy from the main interpreter */
1199 PyInterpreterState *main_interp = PyInterpreterState_Main();
1200 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001201 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001202 }
1203
Nick Coghland6009512014-11-20 21:39:37 +10001204 /* XXX The following is lax in error checking */
1205
Eric Snow93c92f72017-09-13 23:46:04 -07001206 interp->modules = PyDict_New();
Nick Coghland6009512014-11-20 21:39:37 +10001207
Eric Snow93c92f72017-09-13 23:46:04 -07001208 bimod = _PyImport_FindBuiltin("builtins");
Nick Coghland6009512014-11-20 21:39:37 +10001209 if (bimod != NULL) {
1210 interp->builtins = PyModule_GetDict(bimod);
1211 if (interp->builtins == NULL)
1212 goto handle_error;
1213 Py_INCREF(interp->builtins);
1214 }
1215
1216 /* initialize builtin exceptions */
1217 _PyExc_Init(bimod);
1218
Eric Snow93c92f72017-09-13 23:46:04 -07001219 sysmod = _PyImport_FindBuiltin("sys");
Nick Coghland6009512014-11-20 21:39:37 +10001220 if (bimod != NULL && sysmod != NULL) {
1221 PyObject *pstderr;
1222
Eric Snow93c92f72017-09-13 23:46:04 -07001223 interp->sysdict = PyModule_GetDict(sysmod);
1224 if (interp->sysdict == NULL)
1225 goto handle_error;
1226 Py_INCREF(interp->sysdict);
1227 _PySys_EndInit(interp->sysdict);
1228 PySys_SetPath(Py_GetPath());
1229 PyDict_SetItemString(interp->sysdict, "modules",
1230 interp->modules);
Nick Coghland6009512014-11-20 21:39:37 +10001231 /* Set up a preliminary stderr printer until we have enough
1232 infrastructure for the io module in place. */
1233 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1234 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001235 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001236 _PySys_SetObjectId(&PyId_stderr, pstderr);
1237 PySys_SetObject("__stderr__", pstderr);
1238 Py_DECREF(pstderr);
1239
1240 _PyImportHooks_Init();
1241
Eric Snow1abcf672017-05-23 21:46:51 -07001242 initimport(interp, sysmod);
1243 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001244
1245 if (initfsencoding(interp) < 0)
1246 goto handle_error;
1247
1248 if (initstdio() < 0)
1249 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001250 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001251 initmain(interp);
1252 if (!Py_NoSiteFlag)
1253 initsite();
1254 }
1255
1256 if (!PyErr_Occurred())
1257 return tstate;
1258
1259handle_error:
1260 /* Oops, it didn't work. Undo it all. */
1261
1262 PyErr_PrintEx(0);
1263 PyThreadState_Clear(tstate);
1264 PyThreadState_Swap(save_tstate);
1265 PyThreadState_Delete(tstate);
1266 PyInterpreterState_Delete(interp);
1267
1268 return NULL;
1269}
1270
1271/* Delete an interpreter and its last thread. This requires that the
1272 given thread state is current, that the thread has no remaining
1273 frames, and that it is its interpreter's only remaining thread.
1274 It is a fatal error to violate these constraints.
1275
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001276 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001277 everything, regardless.)
1278
1279 Locking: as above.
1280
1281*/
1282
1283void
1284Py_EndInterpreter(PyThreadState *tstate)
1285{
1286 PyInterpreterState *interp = tstate->interp;
1287
1288 if (tstate != PyThreadState_GET())
1289 Py_FatalError("Py_EndInterpreter: thread is not current");
1290 if (tstate->frame != NULL)
1291 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1292
1293 wait_for_thread_shutdown();
1294
1295 if (tstate != interp->tstate_head || tstate->next != NULL)
1296 Py_FatalError("Py_EndInterpreter: not the last thread");
1297
1298 PyImport_Cleanup();
1299 PyInterpreterState_Clear(interp);
1300 PyThreadState_Swap(NULL);
1301 PyInterpreterState_Delete(interp);
1302}
1303
1304#ifdef MS_WINDOWS
1305static wchar_t *progname = L"python";
1306#else
1307static wchar_t *progname = L"python3";
1308#endif
1309
1310void
1311Py_SetProgramName(wchar_t *pn)
1312{
1313 if (pn && *pn)
1314 progname = pn;
1315}
1316
1317wchar_t *
1318Py_GetProgramName(void)
1319{
1320 return progname;
1321}
1322
1323static wchar_t *default_home = NULL;
1324static wchar_t env_home[MAXPATHLEN+1];
1325
1326void
1327Py_SetPythonHome(wchar_t *home)
1328{
1329 default_home = home;
1330}
1331
1332wchar_t *
1333Py_GetPythonHome(void)
1334{
1335 wchar_t *home = default_home;
1336 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1337 char* chome = Py_GETENV("PYTHONHOME");
1338 if (chome) {
1339 size_t size = Py_ARRAY_LENGTH(env_home);
1340 size_t r = mbstowcs(env_home, chome, size);
1341 if (r != (size_t)-1 && r < size)
1342 home = env_home;
1343 }
1344
1345 }
1346 return home;
1347}
1348
1349/* Create __main__ module */
1350
1351static void
1352initmain(PyInterpreterState *interp)
1353{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001354 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001355 m = PyImport_AddModule("__main__");
1356 if (m == NULL)
1357 Py_FatalError("can't create __main__ module");
1358 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001359 ann_dict = PyDict_New();
1360 if ((ann_dict == NULL) ||
1361 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1362 Py_FatalError("Failed to initialize __main__.__annotations__");
1363 }
1364 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001365 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1366 PyObject *bimod = PyImport_ImportModule("builtins");
1367 if (bimod == NULL) {
1368 Py_FatalError("Failed to retrieve builtins module");
1369 }
1370 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1371 Py_FatalError("Failed to initialize __main__.__builtins__");
1372 }
1373 Py_DECREF(bimod);
1374 }
1375 /* Main is a little special - imp.is_builtin("__main__") will return
1376 * False, but BuiltinImporter is still the most appropriate initial
1377 * setting for its __loader__ attribute. A more suitable value will
1378 * be set if __main__ gets further initialized later in the startup
1379 * process.
1380 */
1381 loader = PyDict_GetItemString(d, "__loader__");
1382 if (loader == NULL || loader == Py_None) {
1383 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1384 "BuiltinImporter");
1385 if (loader == NULL) {
1386 Py_FatalError("Failed to retrieve BuiltinImporter");
1387 }
1388 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1389 Py_FatalError("Failed to initialize __main__.__loader__");
1390 }
1391 Py_DECREF(loader);
1392 }
1393}
1394
1395static int
1396initfsencoding(PyInterpreterState *interp)
1397{
1398 PyObject *codec;
1399
Steve Dowercc16be82016-09-08 10:35:16 -07001400#ifdef MS_WINDOWS
1401 if (Py_LegacyWindowsFSEncodingFlag)
1402 {
1403 Py_FileSystemDefaultEncoding = "mbcs";
1404 Py_FileSystemDefaultEncodeErrors = "replace";
1405 }
1406 else
1407 {
1408 Py_FileSystemDefaultEncoding = "utf-8";
1409 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1410 }
1411#else
Nick Coghland6009512014-11-20 21:39:37 +10001412 if (Py_FileSystemDefaultEncoding == NULL)
1413 {
1414 Py_FileSystemDefaultEncoding = get_locale_encoding();
1415 if (Py_FileSystemDefaultEncoding == NULL)
1416 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1417
1418 Py_HasFileSystemDefaultEncoding = 0;
1419 interp->fscodec_initialized = 1;
1420 return 0;
1421 }
Steve Dowercc16be82016-09-08 10:35:16 -07001422#endif
Nick Coghland6009512014-11-20 21:39:37 +10001423
1424 /* the encoding is mbcs, utf-8 or ascii */
1425 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1426 if (!codec) {
1427 /* Such error can only occurs in critical situations: no more
1428 * memory, import a module of the standard library failed,
1429 * etc. */
1430 return -1;
1431 }
1432 Py_DECREF(codec);
1433 interp->fscodec_initialized = 1;
1434 return 0;
1435}
1436
1437/* Import the site module (not into __main__ though) */
1438
1439static void
1440initsite(void)
1441{
1442 PyObject *m;
1443 m = PyImport_ImportModule("site");
1444 if (m == NULL) {
1445 fprintf(stderr, "Failed to import the site module\n");
1446 PyErr_Print();
1447 Py_Finalize();
1448 exit(1);
1449 }
1450 else {
1451 Py_DECREF(m);
1452 }
1453}
1454
Victor Stinner874dbe82015-09-04 17:29:57 +02001455/* Check if a file descriptor is valid or not.
1456 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1457static int
1458is_valid_fd(int fd)
1459{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001460#ifdef __APPLE__
1461 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1462 and the other side of the pipe is closed, dup(1) succeed, whereas
1463 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1464 such error. */
1465 struct stat st;
1466 return (fstat(fd, &st) == 0);
1467#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001468 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001469 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001470 return 0;
1471 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001472 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1473 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1474 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001475 fd2 = dup(fd);
1476 if (fd2 >= 0)
1477 close(fd2);
1478 _Py_END_SUPPRESS_IPH
1479 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001480#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001481}
1482
1483/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001484static PyObject*
1485create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001486 int fd, int write_mode, const char* name,
1487 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001488{
1489 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1490 const char* mode;
1491 const char* newline;
1492 PyObject *line_buffering;
1493 int buffering, isatty;
1494 _Py_IDENTIFIER(open);
1495 _Py_IDENTIFIER(isatty);
1496 _Py_IDENTIFIER(TextIOWrapper);
1497 _Py_IDENTIFIER(mode);
1498
Victor Stinner874dbe82015-09-04 17:29:57 +02001499 if (!is_valid_fd(fd))
1500 Py_RETURN_NONE;
1501
Nick Coghland6009512014-11-20 21:39:37 +10001502 /* stdin is always opened in buffered mode, first because it shouldn't
1503 make a difference in common use cases, second because TextIOWrapper
1504 depends on the presence of a read1() method which only exists on
1505 buffered streams.
1506 */
1507 if (Py_UnbufferedStdioFlag && write_mode)
1508 buffering = 0;
1509 else
1510 buffering = -1;
1511 if (write_mode)
1512 mode = "wb";
1513 else
1514 mode = "rb";
1515 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1516 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001517 Py_None, Py_None, /* encoding, errors */
1518 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001519 if (buf == NULL)
1520 goto error;
1521
1522 if (buffering) {
1523 _Py_IDENTIFIER(raw);
1524 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1525 if (raw == NULL)
1526 goto error;
1527 }
1528 else {
1529 raw = buf;
1530 Py_INCREF(raw);
1531 }
1532
Steve Dower39294992016-08-30 21:22:36 -07001533#ifdef MS_WINDOWS
1534 /* Windows console IO is always UTF-8 encoded */
1535 if (PyWindowsConsoleIO_Check(raw))
1536 encoding = "utf-8";
1537#endif
1538
Nick Coghland6009512014-11-20 21:39:37 +10001539 text = PyUnicode_FromString(name);
1540 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1541 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001542 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001543 if (res == NULL)
1544 goto error;
1545 isatty = PyObject_IsTrue(res);
1546 Py_DECREF(res);
1547 if (isatty == -1)
1548 goto error;
1549 if (isatty || Py_UnbufferedStdioFlag)
1550 line_buffering = Py_True;
1551 else
1552 line_buffering = Py_False;
1553
1554 Py_CLEAR(raw);
1555 Py_CLEAR(text);
1556
1557#ifdef MS_WINDOWS
1558 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1559 newlines to "\n".
1560 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1561 newline = NULL;
1562#else
1563 /* sys.stdin: split lines at "\n".
1564 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1565 newline = "\n";
1566#endif
1567
1568 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssO",
1569 buf, encoding, errors,
1570 newline, line_buffering);
1571 Py_CLEAR(buf);
1572 if (stream == NULL)
1573 goto error;
1574
1575 if (write_mode)
1576 mode = "w";
1577 else
1578 mode = "r";
1579 text = PyUnicode_FromString(mode);
1580 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1581 goto error;
1582 Py_CLEAR(text);
1583 return stream;
1584
1585error:
1586 Py_XDECREF(buf);
1587 Py_XDECREF(stream);
1588 Py_XDECREF(text);
1589 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001590
Victor Stinner874dbe82015-09-04 17:29:57 +02001591 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1592 /* Issue #24891: the file descriptor was closed after the first
1593 is_valid_fd() check was called. Ignore the OSError and set the
1594 stream to None. */
1595 PyErr_Clear();
1596 Py_RETURN_NONE;
1597 }
1598 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001599}
1600
1601/* Initialize sys.stdin, stdout, stderr and builtins.open */
1602static int
1603initstdio(void)
1604{
1605 PyObject *iomod = NULL, *wrapper;
1606 PyObject *bimod = NULL;
1607 PyObject *m;
1608 PyObject *std = NULL;
1609 int status = 0, fd;
1610 PyObject * encoding_attr;
1611 char *pythonioencoding = NULL, *encoding, *errors;
1612
1613 /* Hack to avoid a nasty recursion issue when Python is invoked
1614 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1615 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1616 goto error;
1617 }
1618 Py_DECREF(m);
1619
1620 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1621 goto error;
1622 }
1623 Py_DECREF(m);
1624
1625 if (!(bimod = PyImport_ImportModule("builtins"))) {
1626 goto error;
1627 }
1628
1629 if (!(iomod = PyImport_ImportModule("io"))) {
1630 goto error;
1631 }
1632 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1633 goto error;
1634 }
1635
1636 /* Set builtins.open */
1637 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1638 Py_DECREF(wrapper);
1639 goto error;
1640 }
1641 Py_DECREF(wrapper);
1642
1643 encoding = _Py_StandardStreamEncoding;
1644 errors = _Py_StandardStreamErrors;
1645 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001646 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1647 if (pythonioencoding) {
1648 char *err;
1649 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1650 if (pythonioencoding == NULL) {
1651 PyErr_NoMemory();
1652 goto error;
1653 }
1654 err = strchr(pythonioencoding, ':');
1655 if (err) {
1656 *err = '\0';
1657 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001658 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001659 errors = err;
1660 }
1661 }
1662 if (*pythonioencoding && !encoding) {
1663 encoding = pythonioencoding;
1664 }
1665 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001666 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001667 /* Choose the default error handler based on the current locale */
1668 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001669 }
Nick Coghland6009512014-11-20 21:39:37 +10001670 }
1671
1672 /* Set sys.stdin */
1673 fd = fileno(stdin);
1674 /* Under some conditions stdin, stdout and stderr may not be connected
1675 * and fileno() may point to an invalid file descriptor. For example
1676 * GUI apps don't have valid standard streams by default.
1677 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001678 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1679 if (std == NULL)
1680 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001681 PySys_SetObject("__stdin__", std);
1682 _PySys_SetObjectId(&PyId_stdin, std);
1683 Py_DECREF(std);
1684
1685 /* Set sys.stdout */
1686 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001687 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1688 if (std == NULL)
1689 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001690 PySys_SetObject("__stdout__", std);
1691 _PySys_SetObjectId(&PyId_stdout, std);
1692 Py_DECREF(std);
1693
1694#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1695 /* Set sys.stderr, replaces the preliminary stderr */
1696 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001697 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1698 if (std == NULL)
1699 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001700
1701 /* Same as hack above, pre-import stderr's codec to avoid recursion
1702 when import.c tries to write to stderr in verbose mode. */
1703 encoding_attr = PyObject_GetAttrString(std, "encoding");
1704 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001705 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001706 if (std_encoding != NULL) {
1707 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1708 Py_XDECREF(codec_info);
1709 }
1710 Py_DECREF(encoding_attr);
1711 }
1712 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1713
1714 if (PySys_SetObject("__stderr__", std) < 0) {
1715 Py_DECREF(std);
1716 goto error;
1717 }
1718 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1719 Py_DECREF(std);
1720 goto error;
1721 }
1722 Py_DECREF(std);
1723#endif
1724
1725 if (0) {
1726 error:
1727 status = -1;
1728 }
1729
1730 /* We won't need them anymore. */
1731 if (_Py_StandardStreamEncoding) {
1732 PyMem_RawFree(_Py_StandardStreamEncoding);
1733 _Py_StandardStreamEncoding = NULL;
1734 }
1735 if (_Py_StandardStreamErrors) {
1736 PyMem_RawFree(_Py_StandardStreamErrors);
1737 _Py_StandardStreamErrors = NULL;
1738 }
1739 PyMem_Free(pythonioencoding);
1740 Py_XDECREF(bimod);
1741 Py_XDECREF(iomod);
1742 return status;
1743}
1744
1745
Victor Stinner10dc4842015-03-24 12:01:30 +01001746static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001747_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001748{
Victor Stinner10dc4842015-03-24 12:01:30 +01001749 fputc('\n', stderr);
1750 fflush(stderr);
1751
1752 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001753 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001754}
Victor Stinner791da1c2016-03-14 16:53:12 +01001755
1756/* Print the current exception (if an exception is set) with its traceback,
1757 or display the current Python stack.
1758
1759 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1760 called on catastrophic cases.
1761
1762 Return 1 if the traceback was displayed, 0 otherwise. */
1763
1764static int
1765_Py_FatalError_PrintExc(int fd)
1766{
1767 PyObject *ferr, *res;
1768 PyObject *exception, *v, *tb;
1769 int has_tb;
1770
1771 if (PyThreadState_GET() == NULL) {
1772 /* The GIL is released: trying to acquire it is likely to deadlock,
1773 just give up. */
1774 return 0;
1775 }
1776
1777 PyErr_Fetch(&exception, &v, &tb);
1778 if (exception == NULL) {
1779 /* No current exception */
1780 return 0;
1781 }
1782
1783 ferr = _PySys_GetObjectId(&PyId_stderr);
1784 if (ferr == NULL || ferr == Py_None) {
1785 /* sys.stderr is not set yet or set to None,
1786 no need to try to display the exception */
1787 return 0;
1788 }
1789
1790 PyErr_NormalizeException(&exception, &v, &tb);
1791 if (tb == NULL) {
1792 tb = Py_None;
1793 Py_INCREF(tb);
1794 }
1795 PyException_SetTraceback(v, tb);
1796 if (exception == NULL) {
1797 /* PyErr_NormalizeException() failed */
1798 return 0;
1799 }
1800
1801 has_tb = (tb != Py_None);
1802 PyErr_Display(exception, v, tb);
1803 Py_XDECREF(exception);
1804 Py_XDECREF(v);
1805 Py_XDECREF(tb);
1806
1807 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001808 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001809 if (res == NULL)
1810 PyErr_Clear();
1811 else
1812 Py_DECREF(res);
1813
1814 return has_tb;
1815}
1816
Nick Coghland6009512014-11-20 21:39:37 +10001817/* Print fatal error message and abort */
1818
1819void
1820Py_FatalError(const char *msg)
1821{
1822 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001823 static int reentrant = 0;
1824#ifdef MS_WINDOWS
1825 size_t len;
1826 WCHAR* buffer;
1827 size_t i;
1828#endif
1829
1830 if (reentrant) {
1831 /* Py_FatalError() caused a second fatal error.
1832 Example: flush_std_files() raises a recursion error. */
1833 goto exit;
1834 }
1835 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001836
1837 fprintf(stderr, "Fatal Python error: %s\n", msg);
1838 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001839
Victor Stinnere0deff32015-03-24 13:46:18 +01001840 /* Print the exception (if an exception is set) with its traceback,
1841 * or display the current Python stack. */
Victor Stinner791da1c2016-03-14 16:53:12 +01001842 if (!_Py_FatalError_PrintExc(fd))
1843 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner10dc4842015-03-24 12:01:30 +01001844
Victor Stinner2025d782016-03-16 23:19:15 +01001845 /* The main purpose of faulthandler is to display the traceback. We already
1846 * did our best to display it. So faulthandler can now be disabled.
1847 * (Don't trigger it on abort().) */
1848 _PyFaulthandler_Fini();
1849
Victor Stinner791da1c2016-03-14 16:53:12 +01001850 /* Check if the current Python thread hold the GIL */
1851 if (PyThreadState_GET() != NULL) {
1852 /* Flush sys.stdout and sys.stderr */
1853 flush_std_files();
1854 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001855
Nick Coghland6009512014-11-20 21:39:37 +10001856#ifdef MS_WINDOWS
Victor Stinner53345a42015-03-25 01:55:14 +01001857 len = strlen(msg);
Nick Coghland6009512014-11-20 21:39:37 +10001858
Victor Stinner53345a42015-03-25 01:55:14 +01001859 /* Convert the message to wchar_t. This uses a simple one-to-one
1860 conversion, assuming that the this error message actually uses ASCII
1861 only. If this ceases to be true, we will have to convert. */
1862 buffer = alloca( (len+1) * (sizeof *buffer));
1863 for( i=0; i<=len; ++i)
1864 buffer[i] = msg[i];
1865 OutputDebugStringW(L"Fatal Python error: ");
1866 OutputDebugStringW(buffer);
1867 OutputDebugStringW(L"\n");
1868#endif /* MS_WINDOWS */
1869
1870exit:
1871#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001872 DebugBreak();
1873#endif
Nick Coghland6009512014-11-20 21:39:37 +10001874 abort();
1875}
1876
1877/* Clean up and exit */
1878
Victor Stinnerd7292b52016-06-17 12:29:00 +02001879# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001880
Nick Coghland6009512014-11-20 21:39:37 +10001881/* For the atexit module. */
1882void _Py_PyAtExit(void (*func)(void))
1883{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001884 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001885}
1886
1887static void
1888call_py_exitfuncs(void)
1889{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001890 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001891 return;
1892
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001893 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001894 PyErr_Clear();
1895}
1896
1897/* Wait until threading._shutdown completes, provided
1898 the threading module was imported in the first place.
1899 The shutdown routine will wait until all non-daemon
1900 "threading" threads have completed. */
1901static void
1902wait_for_thread_shutdown(void)
1903{
Nick Coghland6009512014-11-20 21:39:37 +10001904 _Py_IDENTIFIER(_shutdown);
1905 PyObject *result;
Eric Snow93c92f72017-09-13 23:46:04 -07001906 PyThreadState *tstate = PyThreadState_GET();
1907 PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
1908 "threading");
Nick Coghland6009512014-11-20 21:39:37 +10001909 if (threading == NULL) {
1910 /* threading not imported */
1911 PyErr_Clear();
1912 return;
1913 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001914 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001915 if (result == NULL) {
1916 PyErr_WriteUnraisable(threading);
1917 }
1918 else {
1919 Py_DECREF(result);
1920 }
1921 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001922}
1923
1924#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001925int Py_AtExit(void (*func)(void))
1926{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001927 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001928 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001929 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001930 return 0;
1931}
1932
1933static void
1934call_ll_exitfuncs(void)
1935{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001936 while (_PyRuntime.nexitfuncs > 0)
1937 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001938
1939 fflush(stdout);
1940 fflush(stderr);
1941}
1942
1943void
1944Py_Exit(int sts)
1945{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001946 if (Py_FinalizeEx() < 0) {
1947 sts = 120;
1948 }
Nick Coghland6009512014-11-20 21:39:37 +10001949
1950 exit(sts);
1951}
1952
1953static void
1954initsigs(void)
1955{
1956#ifdef SIGPIPE
1957 PyOS_setsig(SIGPIPE, SIG_IGN);
1958#endif
1959#ifdef SIGXFZ
1960 PyOS_setsig(SIGXFZ, SIG_IGN);
1961#endif
1962#ifdef SIGXFSZ
1963 PyOS_setsig(SIGXFSZ, SIG_IGN);
1964#endif
1965 PyOS_InitInterrupts(); /* May imply initsignal() */
1966 if (PyErr_Occurred()) {
1967 Py_FatalError("Py_Initialize: can't import signal");
1968 }
1969}
1970
1971
1972/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
1973 *
1974 * All of the code in this function must only use async-signal-safe functions,
1975 * listed at `man 7 signal` or
1976 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
1977 */
1978void
1979_Py_RestoreSignals(void)
1980{
1981#ifdef SIGPIPE
1982 PyOS_setsig(SIGPIPE, SIG_DFL);
1983#endif
1984#ifdef SIGXFZ
1985 PyOS_setsig(SIGXFZ, SIG_DFL);
1986#endif
1987#ifdef SIGXFSZ
1988 PyOS_setsig(SIGXFSZ, SIG_DFL);
1989#endif
1990}
1991
1992
1993/*
1994 * The file descriptor fd is considered ``interactive'' if either
1995 * a) isatty(fd) is TRUE, or
1996 * b) the -i flag was given, and the filename associated with
1997 * the descriptor is NULL or "<stdin>" or "???".
1998 */
1999int
2000Py_FdIsInteractive(FILE *fp, const char *filename)
2001{
2002 if (isatty((int)fileno(fp)))
2003 return 1;
2004 if (!Py_InteractiveFlag)
2005 return 0;
2006 return (filename == NULL) ||
2007 (strcmp(filename, "<stdin>") == 0) ||
2008 (strcmp(filename, "???") == 0);
2009}
2010
2011
Nick Coghland6009512014-11-20 21:39:37 +10002012/* Wrappers around sigaction() or signal(). */
2013
2014PyOS_sighandler_t
2015PyOS_getsig(int sig)
2016{
2017#ifdef HAVE_SIGACTION
2018 struct sigaction context;
2019 if (sigaction(sig, NULL, &context) == -1)
2020 return SIG_ERR;
2021 return context.sa_handler;
2022#else
2023 PyOS_sighandler_t handler;
2024/* Special signal handling for the secure CRT in Visual Studio 2005 */
2025#if defined(_MSC_VER) && _MSC_VER >= 1400
2026 switch (sig) {
2027 /* Only these signals are valid */
2028 case SIGINT:
2029 case SIGILL:
2030 case SIGFPE:
2031 case SIGSEGV:
2032 case SIGTERM:
2033 case SIGBREAK:
2034 case SIGABRT:
2035 break;
2036 /* Don't call signal() with other values or it will assert */
2037 default:
2038 return SIG_ERR;
2039 }
2040#endif /* _MSC_VER && _MSC_VER >= 1400 */
2041 handler = signal(sig, SIG_IGN);
2042 if (handler != SIG_ERR)
2043 signal(sig, handler);
2044 return handler;
2045#endif
2046}
2047
2048/*
2049 * All of the code in this function must only use async-signal-safe functions,
2050 * listed at `man 7 signal` or
2051 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2052 */
2053PyOS_sighandler_t
2054PyOS_setsig(int sig, PyOS_sighandler_t handler)
2055{
2056#ifdef HAVE_SIGACTION
2057 /* Some code in Modules/signalmodule.c depends on sigaction() being
2058 * used here if HAVE_SIGACTION is defined. Fix that if this code
2059 * changes to invalidate that assumption.
2060 */
2061 struct sigaction context, ocontext;
2062 context.sa_handler = handler;
2063 sigemptyset(&context.sa_mask);
2064 context.sa_flags = 0;
2065 if (sigaction(sig, &context, &ocontext) == -1)
2066 return SIG_ERR;
2067 return ocontext.sa_handler;
2068#else
2069 PyOS_sighandler_t oldhandler;
2070 oldhandler = signal(sig, handler);
2071#ifdef HAVE_SIGINTERRUPT
2072 siginterrupt(sig, 1);
2073#endif
2074 return oldhandler;
2075#endif
2076}
2077
2078#ifdef __cplusplus
2079}
2080#endif