blob: e36b6c1b05718010a69a098bb6ac9b4358af17d5 [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);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
Nick Coghland6009512014-11-20 21:39:37 +100051extern grammar _PyParser_Grammar; /* From graminit.c */
52
53/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080054static _PyInitError add_main_module(PyInterpreterState *interp);
55static _PyInitError initfsencoding(PyInterpreterState *interp);
56static _PyInitError initsite(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080057static _PyInitError init_sys_streams(void);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080058static _PyInitError initsigs(void);
Nick Coghland6009512014-11-20 21:39:37 +100059static void call_py_exitfuncs(void);
60static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080067extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100068extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080070extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100071extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
Nick Coghland6009512014-11-20 21:39:37 +100074extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100076
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080_PyRuntime_Initialize(void)
81{
82 /* XXX We only initialize once in the process, which aligns with
83 the static initialization of the former globals now found in
84 _PyRuntime. However, _PyRuntime *should* be initialized with
85 every Py_Initialize() call, but doing so breaks the runtime.
86 This is because the runtime state is not properly finalized
87 currently. */
88 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089 if (initialized) {
90 return _Py_INIT_OK();
91 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080093
94 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Nick Coghland6009512014-11-20 21:39:37 +1000119int 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
Nick Coghland6009512014-11-20 21:39:37 +1000219static char*
220get_codec_name(const char *encoding)
221{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200222 const char *name_utf8;
223 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000224 PyObject *codec, *name = NULL;
225
226 codec = _PyCodec_Lookup(encoding);
227 if (!codec)
228 goto error;
229
230 name = _PyObject_GetAttrId(codec, &PyId_name);
231 Py_CLEAR(codec);
232 if (!name)
233 goto error;
234
Serhiy Storchaka06515832016-11-20 09:13:07 +0200235 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000236 if (name_utf8 == NULL)
237 goto error;
238 name_str = _PyMem_RawStrdup(name_utf8);
239 Py_DECREF(name);
240 if (name_str == NULL) {
241 PyErr_NoMemory();
242 return NULL;
243 }
244 return name_str;
245
246error:
247 Py_XDECREF(codec);
248 Py_XDECREF(name);
249 return NULL;
250}
251
252static char*
253get_locale_encoding(void)
254{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700255#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000256 char* codeset = nl_langinfo(CODESET);
257 if (!codeset || codeset[0] == '\0') {
258 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
259 return NULL;
260 }
261 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200262#elif defined(__ANDROID__)
263 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000264#else
265 PyErr_SetNone(PyExc_NotImplementedError);
266 return NULL;
267#endif
268}
269
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800270static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700271initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000272{
273 PyObject *importlib;
274 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000275 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800276 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000277
278 /* Import _importlib through its frozen version, _frozen_importlib. */
279 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800280 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000281 }
282 else if (Py_VerboseFlag) {
283 PySys_FormatStderr("import _frozen_importlib # frozen\n");
284 }
285 importlib = PyImport_AddModule("_frozen_importlib");
286 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800287 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000288 }
289 interp->importlib = importlib;
290 Py_INCREF(interp->importlib);
291
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300292 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
293 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800294 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300295 Py_INCREF(interp->import_func);
296
Victor Stinnercd6e6942015-09-18 09:11:57 +0200297 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000298 impmod = PyInit_imp();
299 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800300 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000301 }
302 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200303 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000304 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600305 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800306 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000307 }
308
Victor Stinnercd6e6942015-09-18 09:11:57 +0200309 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000310 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200311 if (value != NULL) {
312 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700313 value = PyObject_CallMethod(importlib,
314 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200315 }
Nick Coghland6009512014-11-20 21:39:37 +1000316 if (value == NULL) {
317 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800318 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000319 }
320 Py_DECREF(value);
321 Py_DECREF(impmod);
322
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800323 err = _PyImportZip_Init();
324 if (_Py_INIT_FAILED(err)) {
325 return err;
326 }
327
328 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000329}
330
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800331static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700332initexternalimport(PyInterpreterState *interp)
333{
334 PyObject *value;
335 value = PyObject_CallMethod(interp->importlib,
336 "_install_external_importers", "");
337 if (value == NULL) {
338 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800339 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700340 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200341 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800342 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700343}
Nick Coghland6009512014-11-20 21:39:37 +1000344
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345/* Helper functions to better handle the legacy C locale
346 *
347 * The legacy C locale assumes ASCII as the default text encoding, which
348 * causes problems not only for the CPython runtime, but also other
349 * components like GNU readline.
350 *
351 * Accordingly, when the CLI detects it, it attempts to coerce it to a
352 * more capable UTF-8 based alternative as follows:
353 *
354 * if (_Py_LegacyLocaleDetected()) {
355 * _Py_CoerceLegacyLocale();
356 * }
357 *
358 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
359 *
360 * Locale coercion also impacts the default error handler for the standard
361 * streams: while the usual default is "strict", the default for the legacy
362 * C locale and for any of the coercion target locales is "surrogateescape".
363 */
364
365int
366_Py_LegacyLocaleDetected(void)
367{
368#ifndef MS_WINDOWS
369 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000370 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
371 * the POSIX locale as a simple alias for the C locale, so
372 * we may also want to check for that explicitly.
373 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000374 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
375 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
376#else
377 /* Windows uses code pages instead of locales, so no locale is legacy */
378 return 0;
379#endif
380}
381
Nick Coghlaneb817952017-06-18 12:29:42 +1000382static const char *_C_LOCALE_WARNING =
383 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
384 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
385 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
386 "locales is recommended.\n";
387
388static int
389_legacy_locale_warnings_enabled(void)
390{
391 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
392 return (coerce_c_locale != NULL &&
393 strncmp(coerce_c_locale, "warn", 5) == 0);
394}
395
396static void
397_emit_stderr_warning_for_legacy_locale(void)
398{
399 if (_legacy_locale_warnings_enabled()) {
400 if (_Py_LegacyLocaleDetected()) {
401 fprintf(stderr, "%s", _C_LOCALE_WARNING);
402 }
403 }
404}
405
Nick Coghlan6ea41862017-06-11 13:16:15 +1000406typedef struct _CandidateLocale {
407 const char *locale_name; /* The locale to try as a coercion target */
408} _LocaleCoercionTarget;
409
410static _LocaleCoercionTarget _TARGET_LOCALES[] = {
411 {"C.UTF-8"},
412 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000413 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000414 {NULL}
415};
416
417static char *
418get_default_standard_stream_error_handler(void)
419{
420 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
421 if (ctype_loc != NULL) {
422 /* "surrogateescape" is the default in the legacy C locale */
423 if (strcmp(ctype_loc, "C") == 0) {
424 return "surrogateescape";
425 }
426
427#ifdef PY_COERCE_C_LOCALE
428 /* "surrogateescape" is the default in locale coercion target locales */
429 const _LocaleCoercionTarget *target = NULL;
430 for (target = _TARGET_LOCALES; target->locale_name; target++) {
431 if (strcmp(ctype_loc, target->locale_name) == 0) {
432 return "surrogateescape";
433 }
434 }
435#endif
436 }
437
438 /* Otherwise return NULL to request the typical default error handler */
439 return NULL;
440}
441
442#ifdef PY_COERCE_C_LOCALE
443static const char *_C_LOCALE_COERCION_WARNING =
444 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
445 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
446
447static void
448_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
449{
450 const char *newloc = target->locale_name;
451
452 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100453 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000454
455 /* Set the relevant locale environment variable */
456 if (setenv("LC_CTYPE", newloc, 1)) {
457 fprintf(stderr,
458 "Error setting LC_CTYPE, skipping C locale coercion\n");
459 return;
460 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000461 if (_legacy_locale_warnings_enabled()) {
462 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
463 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000464
465 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100466 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000467}
468#endif
469
470void
471_Py_CoerceLegacyLocale(void)
472{
473#ifdef PY_COERCE_C_LOCALE
474 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
475 * the locale settings *before* we try to do anything with the command
476 * line arguments. For cross-platform debugging purposes, we also need
477 * to give end users a way to force even scripts that are otherwise
478 * isolated from their environment to use the legacy ASCII-centric C
479 * locale.
480 *
481 * Ignoring -E and -I is safe from a security perspective, as we only use
482 * the setting to turn *off* the implicit locale coercion, and anyone with
483 * access to the process environment already has the ability to set
484 * `LC_ALL=C` to override the C level locale settings anyway.
485 */
486 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
487 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
488 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
489 const char *locale_override = getenv("LC_ALL");
490 if (locale_override == NULL || *locale_override == '\0') {
491 /* LC_ALL is also not set (or is set to an empty string) */
492 const _LocaleCoercionTarget *target = NULL;
493 for (target = _TARGET_LOCALES; target->locale_name; target++) {
494 const char *new_locale = setlocale(LC_CTYPE,
495 target->locale_name);
496 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100497#if !defined(__APPLE__) && !defined(__ANDROID__) && \
498 defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghlan18974c32017-06-30 00:48:14 +1000499 /* Also ensure that nl_langinfo works in this locale */
500 char *codeset = nl_langinfo(CODESET);
501 if (!codeset || *codeset == '\0') {
502 /* CODESET is not set or empty, so skip coercion */
503 new_locale = NULL;
xdegaye1588be62017-11-12 12:45:59 +0100504 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlan18974c32017-06-30 00:48:14 +1000505 continue;
506 }
507#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000508 /* Successfully configured locale, so make it the default */
509 _coerce_default_locale_settings(target);
510 return;
511 }
512 }
513 }
514 }
515 /* No C locale warning here, as Py_Initialize will emit one later */
516#endif
517}
518
xdegaye1588be62017-11-12 12:45:59 +0100519/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
520 * isolate the idiosyncrasies of different libc implementations. It reads the
521 * appropriate environment variable and uses its value to select the locale for
522 * 'category'. */
523char *
524_Py_SetLocaleFromEnv(int category)
525{
526#ifdef __ANDROID__
527 const char *locale;
528 const char **pvar;
529#ifdef PY_COERCE_C_LOCALE
530 const char *coerce_c_locale;
531#endif
532 const char *utf8_locale = "C.UTF-8";
533 const char *env_var_set[] = {
534 "LC_ALL",
535 "LC_CTYPE",
536 "LANG",
537 NULL,
538 };
539
540 /* Android setlocale(category, "") doesn't check the environment variables
541 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
542 * check the environment variables listed in env_var_set. */
543 for (pvar=env_var_set; *pvar; pvar++) {
544 locale = getenv(*pvar);
545 if (locale != NULL && *locale != '\0') {
546 if (strcmp(locale, utf8_locale) == 0 ||
547 strcmp(locale, "en_US.UTF-8") == 0) {
548 return setlocale(category, utf8_locale);
549 }
550 return setlocale(category, "C");
551 }
552 }
553
554 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
555 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
556 * Quote from POSIX section "8.2 Internationalization Variables":
557 * "4. If the LANG environment variable is not set or is set to the empty
558 * string, the implementation-defined default locale shall be used." */
559
560#ifdef PY_COERCE_C_LOCALE
561 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
562 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
563 /* Some other ported code may check the environment variables (e.g. in
564 * extension modules), so we make sure that they match the locale
565 * configuration */
566 if (setenv("LC_CTYPE", utf8_locale, 1)) {
567 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
568 "environment variable to %s\n", utf8_locale);
569 }
570 }
571#endif
572 return setlocale(category, utf8_locale);
573#else /* __ANDROID__ */
574 return setlocale(category, "");
575#endif /* __ANDROID__ */
576}
577
Nick Coghlan6ea41862017-06-11 13:16:15 +1000578
Eric Snow1abcf672017-05-23 21:46:51 -0700579/* Global initializations. Can be undone by Py_Finalize(). Don't
580 call this twice without an intervening Py_Finalize() call.
581
582 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
583 must have a corresponding call to Py_Finalize.
584
585 Locking: you must hold the interpreter lock while calling these APIs.
586 (If the lock has not yet been initialized, that's equivalent to
587 having the lock, but you cannot use multiple threads.)
588
589*/
590
591/* Begin interpreter initialization
592 *
593 * On return, the first thread and interpreter state have been created,
594 * but the compiler, signal handling, multithreading and
595 * multiple interpreter support, and codec infrastructure are not yet
596 * available.
597 *
598 * The import system will support builtin and frozen modules only.
599 * The only supported io is writing to sys.stderr
600 *
601 * If any operation invoked by this function fails, a fatal error is
602 * issued and the function does not return.
603 *
604 * Any code invoked from this function should *not* assume it has access
605 * to the Python C API (unless the API is explicitly listed as being
606 * safe to call without calling Py_Initialize first)
607 */
608
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200609/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700610 * Py_ReadConfig and Py_EndInitialization
611 */
612
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800613_PyInitError
614_Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000615{
616 PyInterpreterState *interp;
617 PyThreadState *tstate;
618 PyObject *bimod, *sysmod, *pstderr;
Eric Snow1abcf672017-05-23 21:46:51 -0700619 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700620 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800621 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000622
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800623 err = _PyRuntime_Initialize();
624 if (_Py_INIT_FAILED(err)) {
625 return err;
626 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600627
Eric Snow1abcf672017-05-23 21:46:51 -0700628 if (config != NULL) {
629 core_config = *config;
630 }
631
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800632 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
633 return _Py_INIT_ERR("Unknown PYTHONMALLOC allocator");
634 }
635
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600636 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800637 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700638 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600639 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800640 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700641 }
642
643 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
644 * threads behave a little more gracefully at interpreter shutdown.
645 * We clobber it here so the new interpreter can start with a clean
646 * slate.
647 *
648 * However, this may still lead to misbehaviour if there are daemon
649 * threads still hanging around from a previous Py_Initialize/Finalize
650 * pair :(
651 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600652 _PyRuntime.finalizing = NULL;
653
Nick Coghlan6ea41862017-06-11 13:16:15 +1000654#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000655 /* Set up the LC_CTYPE locale, so we can obtain
656 the locale's charset without having to switch
657 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100658 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlaneb817952017-06-18 12:29:42 +1000659 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000660#endif
Nick Coghland6009512014-11-20 21:39:37 +1000661
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800662 err = _Py_HashRandomization_Init(&core_config);
663 if (_Py_INIT_FAILED(err)) {
664 return err;
665 }
666
Eric Snow1abcf672017-05-23 21:46:51 -0700667 if (!core_config.use_hash_seed || core_config.hash_seed) {
668 /* Random or non-zero hash seed */
669 Py_HashRandomizationFlag = 1;
670 }
Nick Coghland6009512014-11-20 21:39:37 +1000671
Victor Stinnera7368ac2017-11-15 18:11:45 -0800672 err = _PyInterpreterState_Enable(&_PyRuntime);
673 if (_Py_INIT_FAILED(err)) {
674 return err;
675 }
676
Nick Coghland6009512014-11-20 21:39:37 +1000677 interp = PyInterpreterState_New();
678 if (interp == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800679 return _Py_INIT_ERR("can't make main interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700680 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700681 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000682
683 tstate = PyThreadState_New(interp);
684 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800685 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000686 (void) PyThreadState_Swap(tstate);
687
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000688 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000689 destroying the GIL might fail when it is being referenced from
690 another running thread (see issue #9901).
691 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000692 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000693 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000694 /* Auto-thread-state API */
695 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000696
697 _Py_ReadyTypes();
698
699 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800700 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000701
702 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800703 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000704
705 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800706 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000707
708 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800709 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000710
Eric Snowd393c1b2017-09-14 12:18:12 -0600711 PyObject *modules = PyDict_New();
712 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800713 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600714 interp->modules = modules;
715
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800716 err = _PySys_BeginInit(&sysmod);
717 if (_Py_INIT_FAILED(err)) {
718 return err;
719 }
720
Eric Snowd393c1b2017-09-14 12:18:12 -0600721 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800722 if (interp->sysdict == NULL) {
723 return _Py_INIT_ERR("can't initialize sys dict");
724 }
725
Eric Snowd393c1b2017-09-14 12:18:12 -0600726 Py_INCREF(interp->sysdict);
727 PyDict_SetItemString(interp->sysdict, "modules", modules);
728 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000729
730 /* Init Unicode implementation; relies on the codec registry */
731 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800732 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700733
Nick Coghland6009512014-11-20 21:39:37 +1000734 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800735 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000736
737 bimod = _PyBuiltin_Init();
738 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800739 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600740 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000741 interp->builtins = PyModule_GetDict(bimod);
742 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800743 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000744 Py_INCREF(interp->builtins);
745
746 /* initialize builtin exceptions */
747 _PyExc_Init(bimod);
748
Nick Coghland6009512014-11-20 21:39:37 +1000749 /* Set up a preliminary stderr printer until we have enough
750 infrastructure for the io module in place. */
751 pstderr = PyFile_NewStdPrinter(fileno(stderr));
752 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800753 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000754 _PySys_SetObjectId(&PyId_stderr, pstderr);
755 PySys_SetObject("__stderr__", pstderr);
756 Py_DECREF(pstderr);
757
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800758 err = _PyImport_Init();
759 if (_Py_INIT_FAILED(err)) {
760 return err;
761 }
Nick Coghland6009512014-11-20 21:39:37 +1000762
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800763 err = _PyImportHooks_Init();
764 if (_Py_INIT_FAILED(err)) {
765 return err;
766 }
Nick Coghland6009512014-11-20 21:39:37 +1000767
768 /* Initialize _warnings. */
Victor Stinner1f151112017-11-23 10:43:14 +0100769 if (_PyWarnings_InitWithConfig(&interp->core_config) == NULL) {
770 return _Py_INIT_ERR("can't initialize warnings");
771 }
Nick Coghland6009512014-11-20 21:39:37 +1000772
Eric Snow1abcf672017-05-23 21:46:51 -0700773 /* This call sets up builtin and frozen import support */
774 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800775 err = initimport(interp, sysmod);
776 if (_Py_INIT_FAILED(err)) {
777 return err;
778 }
Eric Snow1abcf672017-05-23 21:46:51 -0700779 }
780
781 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600782 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800783 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700784}
785
Eric Snowc7ec9982017-05-23 23:00:52 -0700786/* Read configuration settings from standard locations
787 *
788 * This function doesn't make any changes to the interpreter state - it
789 * merely populates any missing configuration settings. This allows an
790 * embedding application to completely override a config option by
791 * setting it before calling this function, or else modify the default
792 * setting before passing the fully populated config to Py_EndInitialization.
793 *
794 * More advanced selective initialization tricks are possible by calling
795 * this function multiple times with various preconfigured settings.
796 */
797
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800798_PyInitError
Victor Stinner46972b72017-11-24 22:55:40 +0100799_PyMainInterpreterConfig_Read(_PyMainInterpreterConfig *config)
Eric Snowc7ec9982017-05-23 23:00:52 -0700800{
801 /* Signal handlers are installed by default */
802 if (config->install_signal_handlers < 0) {
803 config->install_signal_handlers = 1;
804 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800805 return _Py_INIT_OK();
Eric Snowc7ec9982017-05-23 23:00:52 -0700806}
807
Victor Stinner46972b72017-11-24 22:55:40 +0100808
809void
810_PyMainInterpreterConfig_Clear(_PyMainInterpreterConfig *config)
811{
812 PyMem_RawFree(config->module_search_path_env);
813 config->module_search_path_env = NULL;
814 PyMem_RawFree(config->home);
815 config->home = NULL;
816}
817
818
Eric Snowc7ec9982017-05-23 23:00:52 -0700819/* Update interpreter state based on supplied configuration settings
820 *
821 * After calling this function, most of the restrictions on the interpreter
822 * are lifted. The only remaining incomplete settings are those related
823 * to the main module (sys.argv[0], __main__ metadata)
824 *
825 * Calling this when the interpreter is not initializing, is already
826 * initialized or without a valid current thread state is a fatal error.
827 * Other errors should be reported as normal Python exceptions with a
828 * non-zero return code.
829 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830_PyInitError
831_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700832{
833 PyInterpreterState *interp;
834 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800835 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700836
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600837 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800838 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700839 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600840 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800841 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700842 }
843
Eric Snow1abcf672017-05-23 21:46:51 -0700844 /* Get current thread state and interpreter pointer */
845 tstate = PyThreadState_GET();
846 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800847 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700848 interp = tstate->interp;
849 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800850 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700851
852 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700853 interp->config = *config;
854
Victor Stinnerd4341102017-11-23 00:12:09 +0100855 /* GetPath may initialize state that _PySys_EndInit locks
856 in, and so has to be called first. */
857 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Victor Stinnere32e79f2017-11-23 01:49:45 +0100858 wchar_t *sys_path = _Py_GetPathWithConfig(&interp->config);
Victor Stinnerd4341102017-11-23 00:12:09 +0100859
Eric Snow1abcf672017-05-23 21:46:51 -0700860 if (interp->core_config._disable_importlib) {
861 /* Special mode for freeze_importlib: run with no import system
862 *
863 * This means anything which needs support from extension modules
864 * or pure Python code in the standard library won't work.
865 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600866 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800867 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700868 }
869 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000870
Victor Stinner13019fd2015-04-03 13:10:54 +0200871 if (_PyTime_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800872 return _Py_INIT_ERR("can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200873
Eric Snow1abcf672017-05-23 21:46:51 -0700874 /* Finish setting up the sys module and import system */
Victor Stinnerd4341102017-11-23 00:12:09 +0100875 PySys_SetPath(sys_path);
Eric Snow1abcf672017-05-23 21:46:51 -0700876 if (_PySys_EndInit(interp->sysdict) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800877 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800878
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800879 err = initexternalimport(interp);
880 if (_Py_INIT_FAILED(err)) {
881 return err;
882 }
Nick Coghland6009512014-11-20 21:39:37 +1000883
884 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800885 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886 if (_Py_INIT_FAILED(err)) {
887 return err;
888 }
Nick Coghland6009512014-11-20 21:39:37 +1000889
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800890 err = initfsencoding(interp);
891 if (_Py_INIT_FAILED(err)) {
892 return err;
893 }
Nick Coghland6009512014-11-20 21:39:37 +1000894
Victor Stinner1f151112017-11-23 10:43:14 +0100895 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896 err = initsigs(); /* Signal handling stuff, including initintr() */
897 if (_Py_INIT_FAILED(err)) {
898 return err;
899 }
900 }
Nick Coghland6009512014-11-20 21:39:37 +1000901
Victor Stinnera7368ac2017-11-15 18:11:45 -0800902 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000904
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800905 err = add_main_module(interp);
906 if (_Py_INIT_FAILED(err)) {
907 return err;
908 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800909
910 err = init_sys_streams();
911 if (_Py_INIT_FAILED(err)) {
912 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 }
Nick Coghland6009512014-11-20 21:39:37 +1000914
915 /* Initialize warnings. */
916 if (PySys_HasWarnOptions()) {
917 PyObject *warnings_module = PyImport_ImportModule("warnings");
918 if (warnings_module == NULL) {
919 fprintf(stderr, "'import warnings' failed; traceback:\n");
920 PyErr_Print();
921 }
922 Py_XDECREF(warnings_module);
923 }
924
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600925 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700926
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927 if (!Py_NoSiteFlag) {
928 err = initsite(); /* Module site */
929 if (_Py_INIT_FAILED(err)) {
930 return err;
931 }
932 }
Eric Snow1abcf672017-05-23 21:46:51 -0700933
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800934 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000935}
936
Eric Snowc7ec9982017-05-23 23:00:52 -0700937#undef _INIT_DEBUG_PRINT
938
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800939_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700940_Py_InitializeEx_Private(int install_sigs, int install_importlib)
941{
942 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700943 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800944 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700945
946 /* TODO: Moar config options! */
947 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
948 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700949 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800950
951 err = _Py_InitializeCore(&core_config);
952 if (_Py_INIT_FAILED(err)) {
953 return err;
954 }
955
Eric Snowc7ec9982017-05-23 23:00:52 -0700956 /* TODO: Print any exceptions raised by these operations */
Victor Stinner46972b72017-11-24 22:55:40 +0100957 err = _PyMainInterpreterConfig_Read(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800958 if (_Py_INIT_FAILED(err)) {
959 return err;
960 }
961
962 err = _Py_InitializeMainInterpreter(&config);
963 if (_Py_INIT_FAILED(err)) {
964 return err;
965 }
966
967 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700968}
969
970
971void
Nick Coghland6009512014-11-20 21:39:37 +1000972Py_InitializeEx(int install_sigs)
973{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800974 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
975 if (_Py_INIT_FAILED(err)) {
976 _Py_FatalInitError(err);
977 }
Nick Coghland6009512014-11-20 21:39:37 +1000978}
979
980void
981Py_Initialize(void)
982{
983 Py_InitializeEx(1);
984}
985
986
987#ifdef COUNT_ALLOCS
988extern void dump_counts(FILE*);
989#endif
990
991/* Flush stdout and stderr */
992
993static int
994file_is_closed(PyObject *fobj)
995{
996 int r;
997 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
998 if (tmp == NULL) {
999 PyErr_Clear();
1000 return 0;
1001 }
1002 r = PyObject_IsTrue(tmp);
1003 Py_DECREF(tmp);
1004 if (r < 0)
1005 PyErr_Clear();
1006 return r > 0;
1007}
1008
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009static int
Nick Coghland6009512014-11-20 21:39:37 +10001010flush_std_files(void)
1011{
1012 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1013 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1014 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001015 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001016
1017 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001018 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001020 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001021 status = -1;
1022 }
Nick Coghland6009512014-11-20 21:39:37 +10001023 else
1024 Py_DECREF(tmp);
1025 }
1026
1027 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001028 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001029 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001030 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001031 status = -1;
1032 }
Nick Coghland6009512014-11-20 21:39:37 +10001033 else
1034 Py_DECREF(tmp);
1035 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001036
1037 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001038}
1039
1040/* Undo the effect of Py_Initialize().
1041
1042 Beware: if multiple interpreter and/or thread states exist, these
1043 are not wiped out; only the current thread and interpreter state
1044 are deleted. But since everything else is deleted, those other
1045 interpreter and thread states should no longer be used.
1046
1047 (XXX We should do better, e.g. wipe out all interpreters and
1048 threads.)
1049
1050 Locking: as above.
1051
1052*/
1053
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001054int
1055Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001056{
1057 PyInterpreterState *interp;
1058 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001059 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001060
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001061 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001062 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001063
1064 wait_for_thread_shutdown();
1065
1066 /* The interpreter is still entirely intact at this point, and the
1067 * exit funcs may be relying on that. In particular, if some thread
1068 * or exit func is still waiting to do an import, the import machinery
1069 * expects Py_IsInitialized() to return true. So don't say the
1070 * interpreter is uninitialized until after the exit funcs have run.
1071 * Note that Threading.py uses an exit func to do a join on all the
1072 * threads created thru it, so this also protects pending imports in
1073 * the threads created via Threading.
1074 */
1075 call_py_exitfuncs();
1076
1077 /* Get current thread state and interpreter pointer */
1078 tstate = PyThreadState_GET();
1079 interp = tstate->interp;
1080
1081 /* Remaining threads (e.g. daemon threads) will automatically exit
1082 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001083 _PyRuntime.finalizing = tstate;
1084 _PyRuntime.initialized = 0;
1085 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001086
Victor Stinnere0deff32015-03-24 13:46:18 +01001087 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001088 if (flush_std_files() < 0) {
1089 status = -1;
1090 }
Nick Coghland6009512014-11-20 21:39:37 +10001091
1092 /* Disable signal handling */
1093 PyOS_FiniInterrupts();
1094
1095 /* Collect garbage. This may call finalizers; it's nice to call these
1096 * before all modules are destroyed.
1097 * XXX If a __del__ or weakref callback is triggered here, and tries to
1098 * XXX import a module, bad things can happen, because Python no
1099 * XXX longer believes it's initialized.
1100 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1101 * XXX is easy to provoke that way. I've also seen, e.g.,
1102 * XXX Exception exceptions.ImportError: 'No module named sha'
1103 * XXX in <function callback at 0x008F5718> ignored
1104 * XXX but I'm unclear on exactly how that one happens. In any case,
1105 * XXX I haven't seen a real-life report of either of these.
1106 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001107 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001108#ifdef COUNT_ALLOCS
1109 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1110 each collection might release some types from the type
1111 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001112 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001113 /* nothing */;
1114#endif
Eric Snowdae02762017-09-14 00:35:58 -07001115
Nick Coghland6009512014-11-20 21:39:37 +10001116 /* Destroy all modules */
1117 PyImport_Cleanup();
1118
Victor Stinnere0deff32015-03-24 13:46:18 +01001119 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001120 if (flush_std_files() < 0) {
1121 status = -1;
1122 }
Nick Coghland6009512014-11-20 21:39:37 +10001123
1124 /* Collect final garbage. This disposes of cycles created by
1125 * class definitions, for example.
1126 * XXX This is disabled because it caused too many problems. If
1127 * XXX a __del__ or weakref callback triggers here, Python code has
1128 * XXX a hard time running, because even the sys module has been
1129 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1130 * XXX One symptom is a sequence of information-free messages
1131 * XXX coming from threads (if a __del__ or callback is invoked,
1132 * XXX other threads can execute too, and any exception they encounter
1133 * XXX triggers a comedy of errors as subsystem after subsystem
1134 * XXX fails to find what it *expects* to find in sys to help report
1135 * XXX the exception and consequent unexpected failures). I've also
1136 * XXX seen segfaults then, after adding print statements to the
1137 * XXX Python code getting called.
1138 */
1139#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001140 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001141#endif
1142
1143 /* Disable tracemalloc after all Python objects have been destroyed,
1144 so it is possible to use tracemalloc in objects destructor. */
1145 _PyTraceMalloc_Fini();
1146
1147 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1148 _PyImport_Fini();
1149
1150 /* Cleanup typeobject.c's internal caches. */
1151 _PyType_Fini();
1152
1153 /* unload faulthandler module */
1154 _PyFaulthandler_Fini();
1155
1156 /* Debugging stuff */
1157#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001158 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001159#endif
1160 /* dump hash stats */
1161 _PyHash_Fini();
1162
Eric Snowdae02762017-09-14 00:35:58 -07001163#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -08001164 if (interp->core_config.show_ref_count) {
1165 _PyDebug_PrintTotalRefs();
1166 }
Eric Snowdae02762017-09-14 00:35:58 -07001167#endif
Nick Coghland6009512014-11-20 21:39:37 +10001168
1169#ifdef Py_TRACE_REFS
1170 /* Display all objects still alive -- this can invoke arbitrary
1171 * __repr__ overrides, so requires a mostly-intact interpreter.
1172 * Alas, a lot of stuff may still be alive now that will be cleaned
1173 * up later.
1174 */
1175 if (Py_GETENV("PYTHONDUMPREFS"))
1176 _Py_PrintReferences(stderr);
1177#endif /* Py_TRACE_REFS */
1178
1179 /* Clear interpreter state and all thread states. */
1180 PyInterpreterState_Clear(interp);
1181
1182 /* Now we decref the exception classes. After this point nothing
1183 can raise an exception. That's okay, because each Fini() method
1184 below has been checked to make sure no exceptions are ever
1185 raised.
1186 */
1187
1188 _PyExc_Fini();
1189
1190 /* Sundry finalizers */
1191 PyMethod_Fini();
1192 PyFrame_Fini();
1193 PyCFunction_Fini();
1194 PyTuple_Fini();
1195 PyList_Fini();
1196 PySet_Fini();
1197 PyBytes_Fini();
1198 PyByteArray_Fini();
1199 PyLong_Fini();
1200 PyFloat_Fini();
1201 PyDict_Fini();
1202 PySlice_Fini();
1203 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001204 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001205 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001206 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001207
1208 /* Cleanup Unicode implementation */
1209 _PyUnicode_Fini();
1210
1211 /* reset file system default encoding */
1212 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1213 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1214 Py_FileSystemDefaultEncoding = NULL;
1215 }
1216
1217 /* XXX Still allocated:
1218 - various static ad-hoc pointers to interned strings
1219 - int and float free list blocks
1220 - whatever various modules and libraries allocate
1221 */
1222
1223 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1224
1225 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001226 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001227
1228 /* Delete current thread. After this, many C API calls become crashy. */
1229 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001230
Nick Coghland6009512014-11-20 21:39:37 +10001231 PyInterpreterState_Delete(interp);
1232
1233#ifdef Py_TRACE_REFS
1234 /* Display addresses (& refcnts) of all objects still alive.
1235 * An address can be used to find the repr of the object, printed
1236 * above by _Py_PrintReferences.
1237 */
1238 if (Py_GETENV("PYTHONDUMPREFS"))
1239 _Py_PrintReferenceAddresses(stderr);
1240#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001241#ifdef WITH_PYMALLOC
1242 if (_PyMem_PymallocEnabled()) {
1243 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1244 if (opt != NULL && *opt != '\0')
1245 _PyObject_DebugMallocStats(stderr);
1246 }
Nick Coghland6009512014-11-20 21:39:37 +10001247#endif
1248
1249 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001250 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001251 return status;
1252}
1253
1254void
1255Py_Finalize(void)
1256{
1257 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001258}
1259
1260/* Create and initialize a new interpreter and thread, and return the
1261 new thread. This requires that Py_Initialize() has been called
1262 first.
1263
1264 Unsuccessful initialization yields a NULL pointer. Note that *no*
1265 exception information is available even in this case -- the
1266 exception information is held in the thread, and there is no
1267 thread.
1268
1269 Locking: as above.
1270
1271*/
1272
Victor Stinnera7368ac2017-11-15 18:11:45 -08001273static _PyInitError
1274new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001275{
1276 PyInterpreterState *interp;
1277 PyThreadState *tstate, *save_tstate;
1278 PyObject *bimod, *sysmod;
1279
Victor Stinnera7368ac2017-11-15 18:11:45 -08001280 if (!_PyRuntime.initialized) {
1281 return _Py_INIT_ERR("Py_Initialize must be called first");
1282 }
Nick Coghland6009512014-11-20 21:39:37 +10001283
Victor Stinner8a1be612016-03-14 22:07:55 +01001284 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1285 interpreters: disable PyGILState_Check(). */
1286 _PyGILState_check_enabled = 0;
1287
Nick Coghland6009512014-11-20 21:39:37 +10001288 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001289 if (interp == NULL) {
1290 *tstate_p = NULL;
1291 return _Py_INIT_OK();
1292 }
Nick Coghland6009512014-11-20 21:39:37 +10001293
1294 tstate = PyThreadState_New(interp);
1295 if (tstate == NULL) {
1296 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001297 *tstate_p = NULL;
1298 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001299 }
1300
1301 save_tstate = PyThreadState_Swap(tstate);
1302
Eric Snow1abcf672017-05-23 21:46:51 -07001303 /* Copy the current interpreter config into the new interpreter */
1304 if (save_tstate != NULL) {
1305 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001306 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001307 } else {
1308 /* No current thread state, copy from the main interpreter */
1309 PyInterpreterState *main_interp = PyInterpreterState_Main();
1310 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001311 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001312 }
1313
Nick Coghland6009512014-11-20 21:39:37 +10001314 /* XXX The following is lax in error checking */
1315
Victor Stinnere32e79f2017-11-23 01:49:45 +01001316 wchar_t *sys_path = _Py_GetPathWithConfig(&interp->config);
Victor Stinnerd4341102017-11-23 00:12:09 +01001317
Eric Snowd393c1b2017-09-14 12:18:12 -06001318 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001319 if (modules == NULL) {
1320 return _Py_INIT_ERR("can't make modules dictionary");
1321 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001322 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001323
Eric Snowd393c1b2017-09-14 12:18:12 -06001324 sysmod = _PyImport_FindBuiltin("sys", modules);
1325 if (sysmod != NULL) {
1326 interp->sysdict = PyModule_GetDict(sysmod);
1327 if (interp->sysdict == NULL)
1328 goto handle_error;
1329 Py_INCREF(interp->sysdict);
1330 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerd4341102017-11-23 00:12:09 +01001331 PySys_SetPath(sys_path);
Eric Snowd393c1b2017-09-14 12:18:12 -06001332 _PySys_EndInit(interp->sysdict);
1333 }
1334
1335 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001336 if (bimod != NULL) {
1337 interp->builtins = PyModule_GetDict(bimod);
1338 if (interp->builtins == NULL)
1339 goto handle_error;
1340 Py_INCREF(interp->builtins);
1341 }
1342
1343 /* initialize builtin exceptions */
1344 _PyExc_Init(bimod);
1345
Nick Coghland6009512014-11-20 21:39:37 +10001346 if (bimod != NULL && sysmod != NULL) {
1347 PyObject *pstderr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001348 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001349
Nick Coghland6009512014-11-20 21:39:37 +10001350 /* Set up a preliminary stderr printer until we have enough
1351 infrastructure for the io module in place. */
1352 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001353 if (pstderr == NULL) {
1354 return _Py_INIT_ERR("can't set preliminary stderr");
1355 }
Nick Coghland6009512014-11-20 21:39:37 +10001356 _PySys_SetObjectId(&PyId_stderr, pstderr);
1357 PySys_SetObject("__stderr__", pstderr);
1358 Py_DECREF(pstderr);
1359
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001360 err = _PyImportHooks_Init();
1361 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001362 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001363 }
Nick Coghland6009512014-11-20 21:39:37 +10001364
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001365 err = initimport(interp, sysmod);
1366 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001367 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001368 }
Nick Coghland6009512014-11-20 21:39:37 +10001369
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001370 err = initexternalimport(interp);
1371 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001372 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001373 }
Nick Coghland6009512014-11-20 21:39:37 +10001374
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001375 err = initfsencoding(interp);
1376 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001377 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001378 }
1379
Victor Stinnera7368ac2017-11-15 18:11:45 -08001380 err = init_sys_streams();
1381 if (_Py_INIT_FAILED(err)) {
1382 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001383 }
1384
1385 err = add_main_module(interp);
1386 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001387 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001388 }
1389
1390 if (!Py_NoSiteFlag) {
1391 err = initsite();
1392 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001393 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001394 }
1395 }
Nick Coghland6009512014-11-20 21:39:37 +10001396 }
1397
Victor Stinnera7368ac2017-11-15 18:11:45 -08001398 if (PyErr_Occurred()) {
1399 goto handle_error;
1400 }
Nick Coghland6009512014-11-20 21:39:37 +10001401
Victor Stinnera7368ac2017-11-15 18:11:45 -08001402 *tstate_p = tstate;
1403 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001404
Nick Coghland6009512014-11-20 21:39:37 +10001405handle_error:
1406 /* Oops, it didn't work. Undo it all. */
1407
1408 PyErr_PrintEx(0);
1409 PyThreadState_Clear(tstate);
1410 PyThreadState_Swap(save_tstate);
1411 PyThreadState_Delete(tstate);
1412 PyInterpreterState_Delete(interp);
1413
Victor Stinnera7368ac2017-11-15 18:11:45 -08001414 *tstate_p = NULL;
1415 return _Py_INIT_OK();
1416}
1417
1418PyThreadState *
1419Py_NewInterpreter(void)
1420{
1421 PyThreadState *tstate;
1422 _PyInitError err = new_interpreter(&tstate);
1423 if (_Py_INIT_FAILED(err)) {
1424 _Py_FatalInitError(err);
1425 }
1426 return tstate;
1427
Nick Coghland6009512014-11-20 21:39:37 +10001428}
1429
1430/* Delete an interpreter and its last thread. This requires that the
1431 given thread state is current, that the thread has no remaining
1432 frames, and that it is its interpreter's only remaining thread.
1433 It is a fatal error to violate these constraints.
1434
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001435 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001436 everything, regardless.)
1437
1438 Locking: as above.
1439
1440*/
1441
1442void
1443Py_EndInterpreter(PyThreadState *tstate)
1444{
1445 PyInterpreterState *interp = tstate->interp;
1446
1447 if (tstate != PyThreadState_GET())
1448 Py_FatalError("Py_EndInterpreter: thread is not current");
1449 if (tstate->frame != NULL)
1450 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1451
1452 wait_for_thread_shutdown();
1453
1454 if (tstate != interp->tstate_head || tstate->next != NULL)
1455 Py_FatalError("Py_EndInterpreter: not the last thread");
1456
1457 PyImport_Cleanup();
1458 PyInterpreterState_Clear(interp);
1459 PyThreadState_Swap(NULL);
1460 PyInterpreterState_Delete(interp);
1461}
1462
1463#ifdef MS_WINDOWS
1464static wchar_t *progname = L"python";
1465#else
1466static wchar_t *progname = L"python3";
1467#endif
1468
1469void
1470Py_SetProgramName(wchar_t *pn)
1471{
1472 if (pn && *pn)
1473 progname = pn;
1474}
1475
1476wchar_t *
1477Py_GetProgramName(void)
1478{
1479 return progname;
1480}
1481
1482static wchar_t *default_home = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001483
1484void
1485Py_SetPythonHome(wchar_t *home)
1486{
1487 default_home = home;
1488}
1489
Victor Stinner0327bde2017-11-23 17:03:20 +01001490
Victor Stinner46972b72017-11-24 22:55:40 +01001491wchar_t*
1492Py_GetPythonHome(void)
Victor Stinner1f151112017-11-23 10:43:14 +01001493{
1494 /* Use a static buffer to avoid heap memory allocation failure.
1495 Py_GetPythonHome() doesn't allow to report error, and the caller
1496 doesn't release memory. */
1497 static wchar_t buffer[MAXPATHLEN+1];
1498
1499 if (default_home) {
Victor Stinner46972b72017-11-24 22:55:40 +01001500 return default_home;
Victor Stinner1f151112017-11-23 10:43:14 +01001501 }
1502
1503 char *home = Py_GETENV("PYTHONHOME");
1504 if (!home) {
Victor Stinner46972b72017-11-24 22:55:40 +01001505 return NULL;
Victor Stinner1f151112017-11-23 10:43:14 +01001506 }
1507
1508 size_t size = Py_ARRAY_LENGTH(buffer);
1509 size_t r = mbstowcs(buffer, home, size);
1510 if (r == (size_t)-1 || r >= size) {
1511 /* conversion failed or the static buffer is too small */
Victor Stinner46972b72017-11-24 22:55:40 +01001512 return NULL;
Victor Stinner1f151112017-11-23 10:43:14 +01001513 }
1514
Victor Stinner46972b72017-11-24 22:55:40 +01001515 return buffer;
Nick Coghland6009512014-11-20 21:39:37 +10001516}
1517
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001519
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001520static _PyInitError
1521add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001522{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001523 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001524 m = PyImport_AddModule("__main__");
1525 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001526 return _Py_INIT_ERR("can't create __main__ module");
1527
Nick Coghland6009512014-11-20 21:39:37 +10001528 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001529 ann_dict = PyDict_New();
1530 if ((ann_dict == NULL) ||
1531 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001532 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001533 }
1534 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001535
Nick Coghland6009512014-11-20 21:39:37 +10001536 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1537 PyObject *bimod = PyImport_ImportModule("builtins");
1538 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001539 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001540 }
1541 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001543 }
1544 Py_DECREF(bimod);
1545 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001546
Nick Coghland6009512014-11-20 21:39:37 +10001547 /* Main is a little special - imp.is_builtin("__main__") will return
1548 * False, but BuiltinImporter is still the most appropriate initial
1549 * setting for its __loader__ attribute. A more suitable value will
1550 * be set if __main__ gets further initialized later in the startup
1551 * process.
1552 */
1553 loader = PyDict_GetItemString(d, "__loader__");
1554 if (loader == NULL || loader == Py_None) {
1555 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1556 "BuiltinImporter");
1557 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001559 }
1560 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001562 }
1563 Py_DECREF(loader);
1564 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001565 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001566}
1567
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001568static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001569initfsencoding(PyInterpreterState *interp)
1570{
1571 PyObject *codec;
1572
Steve Dowercc16be82016-09-08 10:35:16 -07001573#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001575 Py_FileSystemDefaultEncoding = "mbcs";
1576 Py_FileSystemDefaultEncodeErrors = "replace";
1577 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001578 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001579 Py_FileSystemDefaultEncoding = "utf-8";
1580 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1581 }
1582#else
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583 if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001584 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001585 if (Py_FileSystemDefaultEncoding == NULL) {
1586 return _Py_INIT_ERR("Unable to get the locale encoding");
1587 }
Nick Coghland6009512014-11-20 21:39:37 +10001588
1589 Py_HasFileSystemDefaultEncoding = 0;
1590 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001591 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001592 }
Steve Dowercc16be82016-09-08 10:35:16 -07001593#endif
Nick Coghland6009512014-11-20 21:39:37 +10001594
1595 /* the encoding is mbcs, utf-8 or ascii */
1596 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1597 if (!codec) {
1598 /* Such error can only occurs in critical situations: no more
1599 * memory, import a module of the standard library failed,
1600 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001601 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001602 }
1603 Py_DECREF(codec);
1604 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001605 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001606}
1607
1608/* Import the site module (not into __main__ though) */
1609
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001610static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001611initsite(void)
1612{
1613 PyObject *m;
1614 m = PyImport_ImportModule("site");
1615 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001616 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001617 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001618 Py_DECREF(m);
1619 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001620}
1621
Victor Stinner874dbe82015-09-04 17:29:57 +02001622/* Check if a file descriptor is valid or not.
1623 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1624static int
1625is_valid_fd(int fd)
1626{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001627#ifdef __APPLE__
1628 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1629 and the other side of the pipe is closed, dup(1) succeed, whereas
1630 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1631 such error. */
1632 struct stat st;
1633 return (fstat(fd, &st) == 0);
1634#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001635 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001636 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001637 return 0;
1638 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001639 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1640 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1641 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001642 fd2 = dup(fd);
1643 if (fd2 >= 0)
1644 close(fd2);
1645 _Py_END_SUPPRESS_IPH
1646 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001647#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001648}
1649
1650/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001651static PyObject*
1652create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001653 int fd, int write_mode, const char* name,
1654 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001655{
1656 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1657 const char* mode;
1658 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001659 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001660 int buffering, isatty;
1661 _Py_IDENTIFIER(open);
1662 _Py_IDENTIFIER(isatty);
1663 _Py_IDENTIFIER(TextIOWrapper);
1664 _Py_IDENTIFIER(mode);
1665
Victor Stinner874dbe82015-09-04 17:29:57 +02001666 if (!is_valid_fd(fd))
1667 Py_RETURN_NONE;
1668
Nick Coghland6009512014-11-20 21:39:37 +10001669 /* stdin is always opened in buffered mode, first because it shouldn't
1670 make a difference in common use cases, second because TextIOWrapper
1671 depends on the presence of a read1() method which only exists on
1672 buffered streams.
1673 */
1674 if (Py_UnbufferedStdioFlag && write_mode)
1675 buffering = 0;
1676 else
1677 buffering = -1;
1678 if (write_mode)
1679 mode = "wb";
1680 else
1681 mode = "rb";
1682 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1683 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001684 Py_None, Py_None, /* encoding, errors */
1685 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001686 if (buf == NULL)
1687 goto error;
1688
1689 if (buffering) {
1690 _Py_IDENTIFIER(raw);
1691 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1692 if (raw == NULL)
1693 goto error;
1694 }
1695 else {
1696 raw = buf;
1697 Py_INCREF(raw);
1698 }
1699
Steve Dower39294992016-08-30 21:22:36 -07001700#ifdef MS_WINDOWS
1701 /* Windows console IO is always UTF-8 encoded */
1702 if (PyWindowsConsoleIO_Check(raw))
1703 encoding = "utf-8";
1704#endif
1705
Nick Coghland6009512014-11-20 21:39:37 +10001706 text = PyUnicode_FromString(name);
1707 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1708 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001709 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001710 if (res == NULL)
1711 goto error;
1712 isatty = PyObject_IsTrue(res);
1713 Py_DECREF(res);
1714 if (isatty == -1)
1715 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001716 if (Py_UnbufferedStdioFlag)
1717 write_through = Py_True;
1718 else
1719 write_through = Py_False;
1720 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001721 line_buffering = Py_True;
1722 else
1723 line_buffering = Py_False;
1724
1725 Py_CLEAR(raw);
1726 Py_CLEAR(text);
1727
1728#ifdef MS_WINDOWS
1729 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1730 newlines to "\n".
1731 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1732 newline = NULL;
1733#else
1734 /* sys.stdin: split lines at "\n".
1735 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1736 newline = "\n";
1737#endif
1738
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001739 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001740 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001741 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001742 Py_CLEAR(buf);
1743 if (stream == NULL)
1744 goto error;
1745
1746 if (write_mode)
1747 mode = "w";
1748 else
1749 mode = "r";
1750 text = PyUnicode_FromString(mode);
1751 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1752 goto error;
1753 Py_CLEAR(text);
1754 return stream;
1755
1756error:
1757 Py_XDECREF(buf);
1758 Py_XDECREF(stream);
1759 Py_XDECREF(text);
1760 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001761
Victor Stinner874dbe82015-09-04 17:29:57 +02001762 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1763 /* Issue #24891: the file descriptor was closed after the first
1764 is_valid_fd() check was called. Ignore the OSError and set the
1765 stream to None. */
1766 PyErr_Clear();
1767 Py_RETURN_NONE;
1768 }
1769 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001770}
1771
1772/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001773static _PyInitError
1774init_sys_streams(void)
Nick Coghland6009512014-11-20 21:39:37 +10001775{
1776 PyObject *iomod = NULL, *wrapper;
1777 PyObject *bimod = NULL;
1778 PyObject *m;
1779 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001780 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001781 PyObject * encoding_attr;
1782 char *pythonioencoding = NULL, *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001783 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001784
1785 /* Hack to avoid a nasty recursion issue when Python is invoked
1786 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1787 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1788 goto error;
1789 }
1790 Py_DECREF(m);
1791
1792 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1793 goto error;
1794 }
1795 Py_DECREF(m);
1796
1797 if (!(bimod = PyImport_ImportModule("builtins"))) {
1798 goto error;
1799 }
1800
1801 if (!(iomod = PyImport_ImportModule("io"))) {
1802 goto error;
1803 }
1804 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1805 goto error;
1806 }
1807
1808 /* Set builtins.open */
1809 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1810 Py_DECREF(wrapper);
1811 goto error;
1812 }
1813 Py_DECREF(wrapper);
1814
1815 encoding = _Py_StandardStreamEncoding;
1816 errors = _Py_StandardStreamErrors;
1817 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001818 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1819 if (pythonioencoding) {
1820 char *err;
1821 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1822 if (pythonioencoding == NULL) {
1823 PyErr_NoMemory();
1824 goto error;
1825 }
1826 err = strchr(pythonioencoding, ':');
1827 if (err) {
1828 *err = '\0';
1829 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001830 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001831 errors = err;
1832 }
1833 }
1834 if (*pythonioencoding && !encoding) {
1835 encoding = pythonioencoding;
1836 }
1837 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001838 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001839 /* Choose the default error handler based on the current locale */
1840 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001841 }
Nick Coghland6009512014-11-20 21:39:37 +10001842 }
1843
1844 /* Set sys.stdin */
1845 fd = fileno(stdin);
1846 /* Under some conditions stdin, stdout and stderr may not be connected
1847 * and fileno() may point to an invalid file descriptor. For example
1848 * GUI apps don't have valid standard streams by default.
1849 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001850 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1851 if (std == NULL)
1852 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001853 PySys_SetObject("__stdin__", std);
1854 _PySys_SetObjectId(&PyId_stdin, std);
1855 Py_DECREF(std);
1856
1857 /* Set sys.stdout */
1858 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001859 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1860 if (std == NULL)
1861 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001862 PySys_SetObject("__stdout__", std);
1863 _PySys_SetObjectId(&PyId_stdout, std);
1864 Py_DECREF(std);
1865
1866#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1867 /* Set sys.stderr, replaces the preliminary stderr */
1868 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001869 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1870 if (std == NULL)
1871 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001872
1873 /* Same as hack above, pre-import stderr's codec to avoid recursion
1874 when import.c tries to write to stderr in verbose mode. */
1875 encoding_attr = PyObject_GetAttrString(std, "encoding");
1876 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001877 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001878 if (std_encoding != NULL) {
1879 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1880 Py_XDECREF(codec_info);
1881 }
1882 Py_DECREF(encoding_attr);
1883 }
1884 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1885
1886 if (PySys_SetObject("__stderr__", std) < 0) {
1887 Py_DECREF(std);
1888 goto error;
1889 }
1890 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1891 Py_DECREF(std);
1892 goto error;
1893 }
1894 Py_DECREF(std);
1895#endif
1896
Victor Stinnera7368ac2017-11-15 18:11:45 -08001897 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001898
Victor Stinnera7368ac2017-11-15 18:11:45 -08001899error:
1900 res = _Py_INIT_ERR("can't initialize sys standard streams");
1901
1902done:
Nick Coghland6009512014-11-20 21:39:37 +10001903 /* We won't need them anymore. */
1904 if (_Py_StandardStreamEncoding) {
1905 PyMem_RawFree(_Py_StandardStreamEncoding);
1906 _Py_StandardStreamEncoding = NULL;
1907 }
1908 if (_Py_StandardStreamErrors) {
1909 PyMem_RawFree(_Py_StandardStreamErrors);
1910 _Py_StandardStreamErrors = NULL;
1911 }
1912 PyMem_Free(pythonioencoding);
1913 Py_XDECREF(bimod);
1914 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001915 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001916}
1917
1918
Victor Stinner10dc4842015-03-24 12:01:30 +01001919static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001920_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001921{
Victor Stinner10dc4842015-03-24 12:01:30 +01001922 fputc('\n', stderr);
1923 fflush(stderr);
1924
1925 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001926 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001927}
Victor Stinner791da1c2016-03-14 16:53:12 +01001928
1929/* Print the current exception (if an exception is set) with its traceback,
1930 or display the current Python stack.
1931
1932 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1933 called on catastrophic cases.
1934
1935 Return 1 if the traceback was displayed, 0 otherwise. */
1936
1937static int
1938_Py_FatalError_PrintExc(int fd)
1939{
1940 PyObject *ferr, *res;
1941 PyObject *exception, *v, *tb;
1942 int has_tb;
1943
1944 if (PyThreadState_GET() == NULL) {
1945 /* The GIL is released: trying to acquire it is likely to deadlock,
1946 just give up. */
1947 return 0;
1948 }
1949
1950 PyErr_Fetch(&exception, &v, &tb);
1951 if (exception == NULL) {
1952 /* No current exception */
1953 return 0;
1954 }
1955
1956 ferr = _PySys_GetObjectId(&PyId_stderr);
1957 if (ferr == NULL || ferr == Py_None) {
1958 /* sys.stderr is not set yet or set to None,
1959 no need to try to display the exception */
1960 return 0;
1961 }
1962
1963 PyErr_NormalizeException(&exception, &v, &tb);
1964 if (tb == NULL) {
1965 tb = Py_None;
1966 Py_INCREF(tb);
1967 }
1968 PyException_SetTraceback(v, tb);
1969 if (exception == NULL) {
1970 /* PyErr_NormalizeException() failed */
1971 return 0;
1972 }
1973
1974 has_tb = (tb != Py_None);
1975 PyErr_Display(exception, v, tb);
1976 Py_XDECREF(exception);
1977 Py_XDECREF(v);
1978 Py_XDECREF(tb);
1979
1980 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001981 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001982 if (res == NULL)
1983 PyErr_Clear();
1984 else
1985 Py_DECREF(res);
1986
1987 return has_tb;
1988}
1989
Nick Coghland6009512014-11-20 21:39:37 +10001990/* Print fatal error message and abort */
1991
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001992#ifdef MS_WINDOWS
1993static void
1994fatal_output_debug(const char *msg)
1995{
1996 /* buffer of 256 bytes allocated on the stack */
1997 WCHAR buffer[256 / sizeof(WCHAR)];
1998 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1999 size_t msglen;
2000
2001 OutputDebugStringW(L"Fatal Python error: ");
2002
2003 msglen = strlen(msg);
2004 while (msglen) {
2005 size_t i;
2006
2007 if (buflen > msglen) {
2008 buflen = msglen;
2009 }
2010
2011 /* Convert the message to wchar_t. This uses a simple one-to-one
2012 conversion, assuming that the this error message actually uses
2013 ASCII only. If this ceases to be true, we will have to convert. */
2014 for (i=0; i < buflen; ++i) {
2015 buffer[i] = msg[i];
2016 }
2017 buffer[i] = L'\0';
2018 OutputDebugStringW(buffer);
2019
2020 msg += buflen;
2021 msglen -= buflen;
2022 }
2023 OutputDebugStringW(L"\n");
2024}
2025#endif
2026
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002027static void
2028fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002029{
2030 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002031 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002032
2033 if (reentrant) {
2034 /* Py_FatalError() caused a second fatal error.
2035 Example: flush_std_files() raises a recursion error. */
2036 goto exit;
2037 }
2038 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002039
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002040 fprintf(stderr, "Fatal Python error: ");
2041 if (prefix) {
2042 fputs(prefix, stderr);
2043 fputs(": ", stderr);
2044 }
2045 if (msg) {
2046 fputs(msg, stderr);
2047 }
2048 else {
2049 fprintf(stderr, "<message not set>");
2050 }
2051 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002052 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002053
Victor Stinnere0deff32015-03-24 13:46:18 +01002054 /* Print the exception (if an exception is set) with its traceback,
2055 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002056 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002057 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002058 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002059
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002060 /* The main purpose of faulthandler is to display the traceback.
2061 This function already did its best to display a traceback.
2062 Disable faulthandler to prevent writing a second traceback
2063 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002064 _PyFaulthandler_Fini();
2065
Victor Stinner791da1c2016-03-14 16:53:12 +01002066 /* Check if the current Python thread hold the GIL */
2067 if (PyThreadState_GET() != NULL) {
2068 /* Flush sys.stdout and sys.stderr */
2069 flush_std_files();
2070 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002071
Nick Coghland6009512014-11-20 21:39:37 +10002072#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002073 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002074#endif /* MS_WINDOWS */
2075
2076exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002077 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002078#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002079 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002080#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002081 abort();
2082 }
2083 else {
2084 exit(status);
2085 }
2086}
2087
2088void
2089Py_FatalError(const char *msg)
2090{
2091 fatal_error(NULL, msg, -1);
2092}
2093
2094void
2095_Py_FatalInitError(_PyInitError err)
2096{
2097 /* On "user" error: exit with status 1.
2098 For all other errors, call abort(). */
2099 int status = err.user_err ? 1 : -1;
2100 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002101}
2102
2103/* Clean up and exit */
2104
Victor Stinnerd7292b52016-06-17 12:29:00 +02002105# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002106
Nick Coghland6009512014-11-20 21:39:37 +10002107/* For the atexit module. */
2108void _Py_PyAtExit(void (*func)(void))
2109{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002110 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002111}
2112
2113static void
2114call_py_exitfuncs(void)
2115{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002116 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002117 return;
2118
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002119 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002120 PyErr_Clear();
2121}
2122
2123/* Wait until threading._shutdown completes, provided
2124 the threading module was imported in the first place.
2125 The shutdown routine will wait until all non-daemon
2126 "threading" threads have completed. */
2127static void
2128wait_for_thread_shutdown(void)
2129{
Nick Coghland6009512014-11-20 21:39:37 +10002130 _Py_IDENTIFIER(_shutdown);
2131 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002132 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002133 if (threading == NULL) {
2134 /* threading not imported */
2135 PyErr_Clear();
2136 return;
2137 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002138 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002139 if (result == NULL) {
2140 PyErr_WriteUnraisable(threading);
2141 }
2142 else {
2143 Py_DECREF(result);
2144 }
2145 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002146}
2147
2148#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002149int Py_AtExit(void (*func)(void))
2150{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002151 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002152 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002153 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002154 return 0;
2155}
2156
2157static void
2158call_ll_exitfuncs(void)
2159{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002160 while (_PyRuntime.nexitfuncs > 0)
2161 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002162
2163 fflush(stdout);
2164 fflush(stderr);
2165}
2166
2167void
2168Py_Exit(int sts)
2169{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002170 if (Py_FinalizeEx() < 0) {
2171 sts = 120;
2172 }
Nick Coghland6009512014-11-20 21:39:37 +10002173
2174 exit(sts);
2175}
2176
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002177static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002178initsigs(void)
2179{
2180#ifdef SIGPIPE
2181 PyOS_setsig(SIGPIPE, SIG_IGN);
2182#endif
2183#ifdef SIGXFZ
2184 PyOS_setsig(SIGXFZ, SIG_IGN);
2185#endif
2186#ifdef SIGXFSZ
2187 PyOS_setsig(SIGXFSZ, SIG_IGN);
2188#endif
2189 PyOS_InitInterrupts(); /* May imply initsignal() */
2190 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002191 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002192 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002193 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002194}
2195
2196
2197/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2198 *
2199 * All of the code in this function must only use async-signal-safe functions,
2200 * listed at `man 7 signal` or
2201 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2202 */
2203void
2204_Py_RestoreSignals(void)
2205{
2206#ifdef SIGPIPE
2207 PyOS_setsig(SIGPIPE, SIG_DFL);
2208#endif
2209#ifdef SIGXFZ
2210 PyOS_setsig(SIGXFZ, SIG_DFL);
2211#endif
2212#ifdef SIGXFSZ
2213 PyOS_setsig(SIGXFSZ, SIG_DFL);
2214#endif
2215}
2216
2217
2218/*
2219 * The file descriptor fd is considered ``interactive'' if either
2220 * a) isatty(fd) is TRUE, or
2221 * b) the -i flag was given, and the filename associated with
2222 * the descriptor is NULL or "<stdin>" or "???".
2223 */
2224int
2225Py_FdIsInteractive(FILE *fp, const char *filename)
2226{
2227 if (isatty((int)fileno(fp)))
2228 return 1;
2229 if (!Py_InteractiveFlag)
2230 return 0;
2231 return (filename == NULL) ||
2232 (strcmp(filename, "<stdin>") == 0) ||
2233 (strcmp(filename, "???") == 0);
2234}
2235
2236
Nick Coghland6009512014-11-20 21:39:37 +10002237/* Wrappers around sigaction() or signal(). */
2238
2239PyOS_sighandler_t
2240PyOS_getsig(int sig)
2241{
2242#ifdef HAVE_SIGACTION
2243 struct sigaction context;
2244 if (sigaction(sig, NULL, &context) == -1)
2245 return SIG_ERR;
2246 return context.sa_handler;
2247#else
2248 PyOS_sighandler_t handler;
2249/* Special signal handling for the secure CRT in Visual Studio 2005 */
2250#if defined(_MSC_VER) && _MSC_VER >= 1400
2251 switch (sig) {
2252 /* Only these signals are valid */
2253 case SIGINT:
2254 case SIGILL:
2255 case SIGFPE:
2256 case SIGSEGV:
2257 case SIGTERM:
2258 case SIGBREAK:
2259 case SIGABRT:
2260 break;
2261 /* Don't call signal() with other values or it will assert */
2262 default:
2263 return SIG_ERR;
2264 }
2265#endif /* _MSC_VER && _MSC_VER >= 1400 */
2266 handler = signal(sig, SIG_IGN);
2267 if (handler != SIG_ERR)
2268 signal(sig, handler);
2269 return handler;
2270#endif
2271}
2272
2273/*
2274 * All of the code in this function must only use async-signal-safe functions,
2275 * listed at `man 7 signal` or
2276 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2277 */
2278PyOS_sighandler_t
2279PyOS_setsig(int sig, PyOS_sighandler_t handler)
2280{
2281#ifdef HAVE_SIGACTION
2282 /* Some code in Modules/signalmodule.c depends on sigaction() being
2283 * used here if HAVE_SIGACTION is defined. Fix that if this code
2284 * changes to invalidate that assumption.
2285 */
2286 struct sigaction context, ocontext;
2287 context.sa_handler = handler;
2288 sigemptyset(&context.sa_mask);
2289 context.sa_flags = 0;
2290 if (sigaction(sig, &context, &ocontext) == -1)
2291 return SIG_ERR;
2292 return ocontext.sa_handler;
2293#else
2294 PyOS_sighandler_t oldhandler;
2295 oldhandler = signal(sig, handler);
2296#ifdef HAVE_SIGINTERRUPT
2297 siginterrupt(sig, 1);
2298#endif
2299 return oldhandler;
2300#endif
2301}
2302
2303#ifdef __cplusplus
2304}
2305#endif