blob: 5bbbbc68f08eccda26a9bea7936ff40640398c9b [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) */
119int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
120int Py_FrozenFlag; /* Needed by getpath.c */
121int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800122int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000123int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
124int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
125int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
126int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700127#ifdef MS_WINDOWS
128int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700129int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700130#endif
Nick Coghland6009512014-11-20 21:39:37 +1000131
Nick Coghland6009512014-11-20 21:39:37 +1000132/* Hack to force loading of object files */
133int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
134 PyOS_mystrnicmp; /* Python/pystrcmp.o */
135
136/* PyModule_GetWarningsModule is no longer necessary as of 2.6
137since _warnings is builtin. This API should not be used. */
138PyObject *
139PyModule_GetWarningsModule(void)
140{
141 return PyImport_ImportModule("warnings");
142}
143
Eric Snowc7ec9982017-05-23 23:00:52 -0700144
Eric Snow1abcf672017-05-23 21:46:51 -0700145/* APIs to access the initialization flags
146 *
147 * Can be called prior to Py_Initialize.
148 */
Nick Coghland6009512014-11-20 21:39:37 +1000149
Eric Snow1abcf672017-05-23 21:46:51 -0700150int
151_Py_IsCoreInitialized(void)
152{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600153 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700154}
Nick Coghland6009512014-11-20 21:39:37 +1000155
156int
157Py_IsInitialized(void)
158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600159 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000160}
161
162/* Helper to allow an embedding application to override the normal
163 * mechanism that attempts to figure out an appropriate IO encoding
164 */
165
166static char *_Py_StandardStreamEncoding = NULL;
167static char *_Py_StandardStreamErrors = NULL;
168
169int
170Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
171{
172 if (Py_IsInitialized()) {
173 /* This is too late to have any effect */
174 return -1;
175 }
176 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
177 * initialised yet.
178 *
179 * However, the raw memory allocators are initialised appropriately
180 * as C static variables, so _PyMem_RawStrdup is OK even though
181 * Py_Initialize hasn't been called yet.
182 */
183 if (encoding) {
184 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
185 if (!_Py_StandardStreamEncoding) {
186 return -2;
187 }
188 }
189 if (errors) {
190 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
191 if (!_Py_StandardStreamErrors) {
192 if (_Py_StandardStreamEncoding) {
193 PyMem_RawFree(_Py_StandardStreamEncoding);
194 }
195 return -3;
196 }
197 }
Steve Dower39294992016-08-30 21:22:36 -0700198#ifdef MS_WINDOWS
199 if (_Py_StandardStreamEncoding) {
200 /* Overriding the stream encoding implies legacy streams */
201 Py_LegacyWindowsStdioFlag = 1;
202 }
203#endif
Nick Coghland6009512014-11-20 21:39:37 +1000204 return 0;
205}
206
Nick Coghlan6ea41862017-06-11 13:16:15 +1000207
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000208/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
209 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000210 initializations fail, a fatal error is issued and the function does
211 not return. On return, the first thread and interpreter state have
212 been created.
213
214 Locking: you must hold the interpreter lock while calling this.
215 (If the lock has not yet been initialized, that's equivalent to
216 having the lock, but you cannot use multiple threads.)
217
218*/
219
Nick Coghland6009512014-11-20 21:39:37 +1000220static char*
221get_codec_name(const char *encoding)
222{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200223 const char *name_utf8;
224 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000225 PyObject *codec, *name = NULL;
226
227 codec = _PyCodec_Lookup(encoding);
228 if (!codec)
229 goto error;
230
231 name = _PyObject_GetAttrId(codec, &PyId_name);
232 Py_CLEAR(codec);
233 if (!name)
234 goto error;
235
Serhiy Storchaka06515832016-11-20 09:13:07 +0200236 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000237 if (name_utf8 == NULL)
238 goto error;
239 name_str = _PyMem_RawStrdup(name_utf8);
240 Py_DECREF(name);
241 if (name_str == NULL) {
242 PyErr_NoMemory();
243 return NULL;
244 }
245 return name_str;
246
247error:
248 Py_XDECREF(codec);
249 Py_XDECREF(name);
250 return NULL;
251}
252
253static char*
254get_locale_encoding(void)
255{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700256#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000257 char* codeset = nl_langinfo(CODESET);
258 if (!codeset || codeset[0] == '\0') {
259 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
260 return NULL;
261 }
262 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200263#elif defined(__ANDROID__)
264 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000265#else
266 PyErr_SetNone(PyExc_NotImplementedError);
267 return NULL;
268#endif
269}
270
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800271static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700272initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000273{
274 PyObject *importlib;
275 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000276 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800277 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000278
279 /* Import _importlib through its frozen version, _frozen_importlib. */
280 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800281 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000282 }
283 else if (Py_VerboseFlag) {
284 PySys_FormatStderr("import _frozen_importlib # frozen\n");
285 }
286 importlib = PyImport_AddModule("_frozen_importlib");
287 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800288 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000289 }
290 interp->importlib = importlib;
291 Py_INCREF(interp->importlib);
292
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300293 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
294 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800295 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300296 Py_INCREF(interp->import_func);
297
Victor Stinnercd6e6942015-09-18 09:11:57 +0200298 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000299 impmod = PyInit_imp();
300 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800301 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000302 }
303 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200304 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000305 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600306 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800307 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000308 }
309
Victor Stinnercd6e6942015-09-18 09:11:57 +0200310 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000311 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200312 if (value != NULL) {
313 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700314 value = PyObject_CallMethod(importlib,
315 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200316 }
Nick Coghland6009512014-11-20 21:39:37 +1000317 if (value == NULL) {
318 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800319 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000320 }
321 Py_DECREF(value);
322 Py_DECREF(impmod);
323
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800324 err = _PyImportZip_Init();
325 if (_Py_INIT_FAILED(err)) {
326 return err;
327 }
328
329 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000330}
331
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800332static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700333initexternalimport(PyInterpreterState *interp)
334{
335 PyObject *value;
336 value = PyObject_CallMethod(interp->importlib,
337 "_install_external_importers", "");
338 if (value == NULL) {
339 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800340 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700341 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200342 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800343 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700344}
Nick Coghland6009512014-11-20 21:39:37 +1000345
Nick Coghlan6ea41862017-06-11 13:16:15 +1000346/* Helper functions to better handle the legacy C locale
347 *
348 * The legacy C locale assumes ASCII as the default text encoding, which
349 * causes problems not only for the CPython runtime, but also other
350 * components like GNU readline.
351 *
352 * Accordingly, when the CLI detects it, it attempts to coerce it to a
353 * more capable UTF-8 based alternative as follows:
354 *
355 * if (_Py_LegacyLocaleDetected()) {
356 * _Py_CoerceLegacyLocale();
357 * }
358 *
359 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
360 *
361 * Locale coercion also impacts the default error handler for the standard
362 * streams: while the usual default is "strict", the default for the legacy
363 * C locale and for any of the coercion target locales is "surrogateescape".
364 */
365
366int
367_Py_LegacyLocaleDetected(void)
368{
369#ifndef MS_WINDOWS
370 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000371 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
372 * the POSIX locale as a simple alias for the C locale, so
373 * we may also want to check for that explicitly.
374 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000375 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
376 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
377#else
378 /* Windows uses code pages instead of locales, so no locale is legacy */
379 return 0;
380#endif
381}
382
Nick Coghlaneb817952017-06-18 12:29:42 +1000383static const char *_C_LOCALE_WARNING =
384 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
385 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
386 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
387 "locales is recommended.\n";
388
389static int
390_legacy_locale_warnings_enabled(void)
391{
392 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
393 return (coerce_c_locale != NULL &&
394 strncmp(coerce_c_locale, "warn", 5) == 0);
395}
396
397static void
398_emit_stderr_warning_for_legacy_locale(void)
399{
400 if (_legacy_locale_warnings_enabled()) {
401 if (_Py_LegacyLocaleDetected()) {
402 fprintf(stderr, "%s", _C_LOCALE_WARNING);
403 }
404 }
405}
406
Nick Coghlan6ea41862017-06-11 13:16:15 +1000407typedef struct _CandidateLocale {
408 const char *locale_name; /* The locale to try as a coercion target */
409} _LocaleCoercionTarget;
410
411static _LocaleCoercionTarget _TARGET_LOCALES[] = {
412 {"C.UTF-8"},
413 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000414 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000415 {NULL}
416};
417
418static char *
419get_default_standard_stream_error_handler(void)
420{
421 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
422 if (ctype_loc != NULL) {
423 /* "surrogateescape" is the default in the legacy C locale */
424 if (strcmp(ctype_loc, "C") == 0) {
425 return "surrogateescape";
426 }
427
428#ifdef PY_COERCE_C_LOCALE
429 /* "surrogateescape" is the default in locale coercion target locales */
430 const _LocaleCoercionTarget *target = NULL;
431 for (target = _TARGET_LOCALES; target->locale_name; target++) {
432 if (strcmp(ctype_loc, target->locale_name) == 0) {
433 return "surrogateescape";
434 }
435 }
436#endif
437 }
438
439 /* Otherwise return NULL to request the typical default error handler */
440 return NULL;
441}
442
443#ifdef PY_COERCE_C_LOCALE
444static const char *_C_LOCALE_COERCION_WARNING =
445 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
446 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
447
448static void
449_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
450{
451 const char *newloc = target->locale_name;
452
453 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100454 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000455
456 /* Set the relevant locale environment variable */
457 if (setenv("LC_CTYPE", newloc, 1)) {
458 fprintf(stderr,
459 "Error setting LC_CTYPE, skipping C locale coercion\n");
460 return;
461 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000462 if (_legacy_locale_warnings_enabled()) {
463 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
464 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000465
466 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100467 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000468}
469#endif
470
471void
472_Py_CoerceLegacyLocale(void)
473{
474#ifdef PY_COERCE_C_LOCALE
475 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
476 * the locale settings *before* we try to do anything with the command
477 * line arguments. For cross-platform debugging purposes, we also need
478 * to give end users a way to force even scripts that are otherwise
479 * isolated from their environment to use the legacy ASCII-centric C
480 * locale.
481 *
482 * Ignoring -E and -I is safe from a security perspective, as we only use
483 * the setting to turn *off* the implicit locale coercion, and anyone with
484 * access to the process environment already has the ability to set
485 * `LC_ALL=C` to override the C level locale settings anyway.
486 */
487 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
488 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
489 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
490 const char *locale_override = getenv("LC_ALL");
491 if (locale_override == NULL || *locale_override == '\0') {
492 /* LC_ALL is also not set (or is set to an empty string) */
493 const _LocaleCoercionTarget *target = NULL;
494 for (target = _TARGET_LOCALES; target->locale_name; target++) {
495 const char *new_locale = setlocale(LC_CTYPE,
496 target->locale_name);
497 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100498#if !defined(__APPLE__) && !defined(__ANDROID__) && \
499 defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghlan18974c32017-06-30 00:48:14 +1000500 /* Also ensure that nl_langinfo works in this locale */
501 char *codeset = nl_langinfo(CODESET);
502 if (!codeset || *codeset == '\0') {
503 /* CODESET is not set or empty, so skip coercion */
504 new_locale = NULL;
xdegaye1588be62017-11-12 12:45:59 +0100505 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlan18974c32017-06-30 00:48:14 +1000506 continue;
507 }
508#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000509 /* Successfully configured locale, so make it the default */
510 _coerce_default_locale_settings(target);
511 return;
512 }
513 }
514 }
515 }
516 /* No C locale warning here, as Py_Initialize will emit one later */
517#endif
518}
519
xdegaye1588be62017-11-12 12:45:59 +0100520/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
521 * isolate the idiosyncrasies of different libc implementations. It reads the
522 * appropriate environment variable and uses its value to select the locale for
523 * 'category'. */
524char *
525_Py_SetLocaleFromEnv(int category)
526{
527#ifdef __ANDROID__
528 const char *locale;
529 const char **pvar;
530#ifdef PY_COERCE_C_LOCALE
531 const char *coerce_c_locale;
532#endif
533 const char *utf8_locale = "C.UTF-8";
534 const char *env_var_set[] = {
535 "LC_ALL",
536 "LC_CTYPE",
537 "LANG",
538 NULL,
539 };
540
541 /* Android setlocale(category, "") doesn't check the environment variables
542 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
543 * check the environment variables listed in env_var_set. */
544 for (pvar=env_var_set; *pvar; pvar++) {
545 locale = getenv(*pvar);
546 if (locale != NULL && *locale != '\0') {
547 if (strcmp(locale, utf8_locale) == 0 ||
548 strcmp(locale, "en_US.UTF-8") == 0) {
549 return setlocale(category, utf8_locale);
550 }
551 return setlocale(category, "C");
552 }
553 }
554
555 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
556 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
557 * Quote from POSIX section "8.2 Internationalization Variables":
558 * "4. If the LANG environment variable is not set or is set to the empty
559 * string, the implementation-defined default locale shall be used." */
560
561#ifdef PY_COERCE_C_LOCALE
562 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
563 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
564 /* Some other ported code may check the environment variables (e.g. in
565 * extension modules), so we make sure that they match the locale
566 * configuration */
567 if (setenv("LC_CTYPE", utf8_locale, 1)) {
568 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
569 "environment variable to %s\n", utf8_locale);
570 }
571 }
572#endif
573 return setlocale(category, utf8_locale);
574#else /* __ANDROID__ */
575 return setlocale(category, "");
576#endif /* __ANDROID__ */
577}
578
Nick Coghlan6ea41862017-06-11 13:16:15 +1000579
Eric Snow1abcf672017-05-23 21:46:51 -0700580/* Global initializations. Can be undone by Py_Finalize(). Don't
581 call this twice without an intervening Py_Finalize() call.
582
583 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
584 must have a corresponding call to Py_Finalize.
585
586 Locking: you must hold the interpreter lock while calling these APIs.
587 (If the lock has not yet been initialized, that's equivalent to
588 having the lock, but you cannot use multiple threads.)
589
590*/
591
592/* Begin interpreter initialization
593 *
594 * On return, the first thread and interpreter state have been created,
595 * but the compiler, signal handling, multithreading and
596 * multiple interpreter support, and codec infrastructure are not yet
597 * available.
598 *
599 * The import system will support builtin and frozen modules only.
600 * The only supported io is writing to sys.stderr
601 *
602 * If any operation invoked by this function fails, a fatal error is
603 * issued and the function does not return.
604 *
605 * Any code invoked from this function should *not* assume it has access
606 * to the Python C API (unless the API is explicitly listed as being
607 * safe to call without calling Py_Initialize first)
608 */
609
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200610/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700611 * Py_ReadConfig and Py_EndInitialization
612 */
613
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800614_PyInitError
615_Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000616{
617 PyInterpreterState *interp;
618 PyThreadState *tstate;
619 PyObject *bimod, *sysmod, *pstderr;
Eric Snow1abcf672017-05-23 21:46:51 -0700620 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700621 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800622 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000623
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800624 err = _PyRuntime_Initialize();
625 if (_Py_INIT_FAILED(err)) {
626 return err;
627 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600628
Eric Snow1abcf672017-05-23 21:46:51 -0700629 if (config != NULL) {
630 core_config = *config;
631 }
632
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800633 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
634 return _Py_INIT_ERR("Unknown PYTHONMALLOC allocator");
635 }
636
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600637 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800638 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700639 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600640 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800641 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700642 }
643
644 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
645 * threads behave a little more gracefully at interpreter shutdown.
646 * We clobber it here so the new interpreter can start with a clean
647 * slate.
648 *
649 * However, this may still lead to misbehaviour if there are daemon
650 * threads still hanging around from a previous Py_Initialize/Finalize
651 * pair :(
652 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600653 _PyRuntime.finalizing = NULL;
654
Nick Coghlan6ea41862017-06-11 13:16:15 +1000655#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000656 /* Set up the LC_CTYPE locale, so we can obtain
657 the locale's charset without having to switch
658 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100659 _Py_SetLocaleFromEnv(LC_CTYPE);
Nick Coghlaneb817952017-06-18 12:29:42 +1000660 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000661#endif
Nick Coghland6009512014-11-20 21:39:37 +1000662
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800663 err = _Py_HashRandomization_Init(&core_config);
664 if (_Py_INIT_FAILED(err)) {
665 return err;
666 }
667
Eric Snow1abcf672017-05-23 21:46:51 -0700668 if (!core_config.use_hash_seed || core_config.hash_seed) {
669 /* Random or non-zero hash seed */
670 Py_HashRandomizationFlag = 1;
671 }
Nick Coghland6009512014-11-20 21:39:37 +1000672
Victor Stinnera7368ac2017-11-15 18:11:45 -0800673 err = _PyInterpreterState_Enable(&_PyRuntime);
674 if (_Py_INIT_FAILED(err)) {
675 return err;
676 }
677
Nick Coghland6009512014-11-20 21:39:37 +1000678 interp = PyInterpreterState_New();
679 if (interp == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800680 return _Py_INIT_ERR("can't make main interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700681 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700682 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000683
684 tstate = PyThreadState_New(interp);
685 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800686 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000687 (void) PyThreadState_Swap(tstate);
688
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000689 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000690 destroying the GIL might fail when it is being referenced from
691 another running thread (see issue #9901).
692 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000693 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000694 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000695 /* Auto-thread-state API */
696 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000697
698 _Py_ReadyTypes();
699
700 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800701 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000702
703 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800704 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000705
706 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800707 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000708
709 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800710 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000711
Eric Snowd393c1b2017-09-14 12:18:12 -0600712 PyObject *modules = PyDict_New();
713 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800714 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600715 interp->modules = modules;
716
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800717 err = _PySys_BeginInit(&sysmod);
718 if (_Py_INIT_FAILED(err)) {
719 return err;
720 }
721
Eric Snowd393c1b2017-09-14 12:18:12 -0600722 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800723 if (interp->sysdict == NULL) {
724 return _Py_INIT_ERR("can't initialize sys dict");
725 }
726
Eric Snowd393c1b2017-09-14 12:18:12 -0600727 Py_INCREF(interp->sysdict);
728 PyDict_SetItemString(interp->sysdict, "modules", modules);
729 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000730
731 /* Init Unicode implementation; relies on the codec registry */
732 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800733 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700734
Nick Coghland6009512014-11-20 21:39:37 +1000735 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800736 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000737
738 bimod = _PyBuiltin_Init();
739 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800740 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600741 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000742 interp->builtins = PyModule_GetDict(bimod);
743 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800744 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000745 Py_INCREF(interp->builtins);
746
747 /* initialize builtin exceptions */
748 _PyExc_Init(bimod);
749
Nick Coghland6009512014-11-20 21:39:37 +1000750 /* Set up a preliminary stderr printer until we have enough
751 infrastructure for the io module in place. */
752 pstderr = PyFile_NewStdPrinter(fileno(stderr));
753 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800754 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000755 _PySys_SetObjectId(&PyId_stderr, pstderr);
756 PySys_SetObject("__stderr__", pstderr);
757 Py_DECREF(pstderr);
758
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800759 err = _PyImport_Init();
760 if (_Py_INIT_FAILED(err)) {
761 return err;
762 }
Nick Coghland6009512014-11-20 21:39:37 +1000763
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800764 err = _PyImportHooks_Init();
765 if (_Py_INIT_FAILED(err)) {
766 return err;
767 }
Nick Coghland6009512014-11-20 21:39:37 +1000768
769 /* Initialize _warnings. */
Victor Stinner1f151112017-11-23 10:43:14 +0100770 if (_PyWarnings_InitWithConfig(&interp->core_config) == NULL) {
771 return _Py_INIT_ERR("can't initialize warnings");
772 }
Nick Coghland6009512014-11-20 21:39:37 +1000773
Eric Snow1abcf672017-05-23 21:46:51 -0700774 /* This call sets up builtin and frozen import support */
775 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800776 err = initimport(interp, sysmod);
777 if (_Py_INIT_FAILED(err)) {
778 return err;
779 }
Eric Snow1abcf672017-05-23 21:46:51 -0700780 }
781
782 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600783 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800784 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700785}
786
Eric Snowc7ec9982017-05-23 23:00:52 -0700787/* Read configuration settings from standard locations
788 *
789 * This function doesn't make any changes to the interpreter state - it
790 * merely populates any missing configuration settings. This allows an
791 * embedding application to completely override a config option by
792 * setting it before calling this function, or else modify the default
793 * setting before passing the fully populated config to Py_EndInitialization.
794 *
795 * More advanced selective initialization tricks are possible by calling
796 * this function multiple times with various preconfigured settings.
797 */
798
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799_PyInitError
800_Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
Eric Snowc7ec9982017-05-23 23:00:52 -0700801{
802 /* Signal handlers are installed by default */
803 if (config->install_signal_handlers < 0) {
804 config->install_signal_handlers = 1;
805 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800806 return _Py_INIT_OK();
Eric Snowc7ec9982017-05-23 23:00:52 -0700807}
808
809/* Update interpreter state based on supplied configuration settings
810 *
811 * After calling this function, most of the restrictions on the interpreter
812 * are lifted. The only remaining incomplete settings are those related
813 * to the main module (sys.argv[0], __main__ metadata)
814 *
815 * Calling this when the interpreter is not initializing, is already
816 * initialized or without a valid current thread state is a fatal error.
817 * Other errors should be reported as normal Python exceptions with a
818 * non-zero return code.
819 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800820_PyInitError
821_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700822{
823 PyInterpreterState *interp;
824 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800825 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700826
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600827 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800828 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700829 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600830 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800831 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 }
833
Eric Snow1abcf672017-05-23 21:46:51 -0700834 /* Get current thread state and interpreter pointer */
835 tstate = PyThreadState_GET();
836 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700838 interp = tstate->interp;
839 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800840 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700841
842 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700843 interp->config = *config;
844
Victor Stinnerd4341102017-11-23 00:12:09 +0100845 /* GetPath may initialize state that _PySys_EndInit locks
846 in, and so has to be called first. */
847 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Victor Stinnere32e79f2017-11-23 01:49:45 +0100848 wchar_t *sys_path = _Py_GetPathWithConfig(&interp->config);
Victor Stinnerd4341102017-11-23 00:12:09 +0100849
Eric Snow1abcf672017-05-23 21:46:51 -0700850 if (interp->core_config._disable_importlib) {
851 /* Special mode for freeze_importlib: run with no import system
852 *
853 * This means anything which needs support from extension modules
854 * or pure Python code in the standard library won't work.
855 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600856 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800857 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700858 }
859 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000860
Victor Stinner13019fd2015-04-03 13:10:54 +0200861 if (_PyTime_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800862 return _Py_INIT_ERR("can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200863
Eric Snow1abcf672017-05-23 21:46:51 -0700864 /* Finish setting up the sys module and import system */
Victor Stinnerd4341102017-11-23 00:12:09 +0100865 PySys_SetPath(sys_path);
Eric Snow1abcf672017-05-23 21:46:51 -0700866 if (_PySys_EndInit(interp->sysdict) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800867 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800868
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800869 err = initexternalimport(interp);
870 if (_Py_INIT_FAILED(err)) {
871 return err;
872 }
Nick Coghland6009512014-11-20 21:39:37 +1000873
874 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800875 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800876 if (_Py_INIT_FAILED(err)) {
877 return err;
878 }
Nick Coghland6009512014-11-20 21:39:37 +1000879
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800880 err = initfsencoding(interp);
881 if (_Py_INIT_FAILED(err)) {
882 return err;
883 }
Nick Coghland6009512014-11-20 21:39:37 +1000884
Victor Stinner1f151112017-11-23 10:43:14 +0100885 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886 err = initsigs(); /* Signal handling stuff, including initintr() */
887 if (_Py_INIT_FAILED(err)) {
888 return err;
889 }
890 }
Nick Coghland6009512014-11-20 21:39:37 +1000891
Victor Stinnera7368ac2017-11-15 18:11:45 -0800892 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800893 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000894
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 err = add_main_module(interp);
896 if (_Py_INIT_FAILED(err)) {
897 return err;
898 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800899
900 err = init_sys_streams();
901 if (_Py_INIT_FAILED(err)) {
902 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 }
Nick Coghland6009512014-11-20 21:39:37 +1000904
905 /* Initialize warnings. */
906 if (PySys_HasWarnOptions()) {
907 PyObject *warnings_module = PyImport_ImportModule("warnings");
908 if (warnings_module == NULL) {
909 fprintf(stderr, "'import warnings' failed; traceback:\n");
910 PyErr_Print();
911 }
912 Py_XDECREF(warnings_module);
913 }
914
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600915 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700916
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800917 if (!Py_NoSiteFlag) {
918 err = initsite(); /* Module site */
919 if (_Py_INIT_FAILED(err)) {
920 return err;
921 }
922 }
Eric Snow1abcf672017-05-23 21:46:51 -0700923
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800924 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000925}
926
Eric Snowc7ec9982017-05-23 23:00:52 -0700927#undef _INIT_DEBUG_PRINT
928
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700930_Py_InitializeEx_Private(int install_sigs, int install_importlib)
931{
932 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700933 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800934 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700935
936 /* TODO: Moar config options! */
937 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
938 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700939 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800940
941 err = _Py_InitializeCore(&core_config);
942 if (_Py_INIT_FAILED(err)) {
943 return err;
944 }
945
Eric Snowc7ec9982017-05-23 23:00:52 -0700946 /* TODO: Print any exceptions raised by these operations */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800947 err = _Py_ReadMainInterpreterConfig(&config);
948 if (_Py_INIT_FAILED(err)) {
949 return err;
950 }
951
952 err = _Py_InitializeMainInterpreter(&config);
953 if (_Py_INIT_FAILED(err)) {
954 return err;
955 }
956
957 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700958}
959
960
961void
Nick Coghland6009512014-11-20 21:39:37 +1000962Py_InitializeEx(int install_sigs)
963{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800964 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
965 if (_Py_INIT_FAILED(err)) {
966 _Py_FatalInitError(err);
967 }
Nick Coghland6009512014-11-20 21:39:37 +1000968}
969
970void
971Py_Initialize(void)
972{
973 Py_InitializeEx(1);
974}
975
976
977#ifdef COUNT_ALLOCS
978extern void dump_counts(FILE*);
979#endif
980
981/* Flush stdout and stderr */
982
983static int
984file_is_closed(PyObject *fobj)
985{
986 int r;
987 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
988 if (tmp == NULL) {
989 PyErr_Clear();
990 return 0;
991 }
992 r = PyObject_IsTrue(tmp);
993 Py_DECREF(tmp);
994 if (r < 0)
995 PyErr_Clear();
996 return r > 0;
997}
998
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000999static int
Nick Coghland6009512014-11-20 21:39:37 +10001000flush_std_files(void)
1001{
1002 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1003 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1004 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001005 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001006
1007 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001008 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001010 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001011 status = -1;
1012 }
Nick Coghland6009512014-11-20 21:39:37 +10001013 else
1014 Py_DECREF(tmp);
1015 }
1016
1017 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001018 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001020 PyErr_Clear();
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 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001026
1027 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001028}
1029
1030/* Undo the effect of Py_Initialize().
1031
1032 Beware: if multiple interpreter and/or thread states exist, these
1033 are not wiped out; only the current thread and interpreter state
1034 are deleted. But since everything else is deleted, those other
1035 interpreter and thread states should no longer be used.
1036
1037 (XXX We should do better, e.g. wipe out all interpreters and
1038 threads.)
1039
1040 Locking: as above.
1041
1042*/
1043
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001044int
1045Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001046{
1047 PyInterpreterState *interp;
1048 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001049 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001050
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001051 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001052 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001053
1054 wait_for_thread_shutdown();
1055
1056 /* The interpreter is still entirely intact at this point, and the
1057 * exit funcs may be relying on that. In particular, if some thread
1058 * or exit func is still waiting to do an import, the import machinery
1059 * expects Py_IsInitialized() to return true. So don't say the
1060 * interpreter is uninitialized until after the exit funcs have run.
1061 * Note that Threading.py uses an exit func to do a join on all the
1062 * threads created thru it, so this also protects pending imports in
1063 * the threads created via Threading.
1064 */
1065 call_py_exitfuncs();
1066
1067 /* Get current thread state and interpreter pointer */
1068 tstate = PyThreadState_GET();
1069 interp = tstate->interp;
1070
1071 /* Remaining threads (e.g. daemon threads) will automatically exit
1072 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001073 _PyRuntime.finalizing = tstate;
1074 _PyRuntime.initialized = 0;
1075 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001076
Victor Stinnere0deff32015-03-24 13:46:18 +01001077 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001078 if (flush_std_files() < 0) {
1079 status = -1;
1080 }
Nick Coghland6009512014-11-20 21:39:37 +10001081
1082 /* Disable signal handling */
1083 PyOS_FiniInterrupts();
1084
1085 /* Collect garbage. This may call finalizers; it's nice to call these
1086 * before all modules are destroyed.
1087 * XXX If a __del__ or weakref callback is triggered here, and tries to
1088 * XXX import a module, bad things can happen, because Python no
1089 * XXX longer believes it's initialized.
1090 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1091 * XXX is easy to provoke that way. I've also seen, e.g.,
1092 * XXX Exception exceptions.ImportError: 'No module named sha'
1093 * XXX in <function callback at 0x008F5718> ignored
1094 * XXX but I'm unclear on exactly how that one happens. In any case,
1095 * XXX I haven't seen a real-life report of either of these.
1096 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001097 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001098#ifdef COUNT_ALLOCS
1099 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1100 each collection might release some types from the type
1101 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001102 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001103 /* nothing */;
1104#endif
Eric Snowdae02762017-09-14 00:35:58 -07001105
Nick Coghland6009512014-11-20 21:39:37 +10001106 /* Destroy all modules */
1107 PyImport_Cleanup();
1108
Victor Stinnere0deff32015-03-24 13:46:18 +01001109 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001110 if (flush_std_files() < 0) {
1111 status = -1;
1112 }
Nick Coghland6009512014-11-20 21:39:37 +10001113
1114 /* Collect final garbage. This disposes of cycles created by
1115 * class definitions, for example.
1116 * XXX This is disabled because it caused too many problems. If
1117 * XXX a __del__ or weakref callback triggers here, Python code has
1118 * XXX a hard time running, because even the sys module has been
1119 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1120 * XXX One symptom is a sequence of information-free messages
1121 * XXX coming from threads (if a __del__ or callback is invoked,
1122 * XXX other threads can execute too, and any exception they encounter
1123 * XXX triggers a comedy of errors as subsystem after subsystem
1124 * XXX fails to find what it *expects* to find in sys to help report
1125 * XXX the exception and consequent unexpected failures). I've also
1126 * XXX seen segfaults then, after adding print statements to the
1127 * XXX Python code getting called.
1128 */
1129#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001130 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001131#endif
1132
1133 /* Disable tracemalloc after all Python objects have been destroyed,
1134 so it is possible to use tracemalloc in objects destructor. */
1135 _PyTraceMalloc_Fini();
1136
1137 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1138 _PyImport_Fini();
1139
1140 /* Cleanup typeobject.c's internal caches. */
1141 _PyType_Fini();
1142
1143 /* unload faulthandler module */
1144 _PyFaulthandler_Fini();
1145
1146 /* Debugging stuff */
1147#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001148 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001149#endif
1150 /* dump hash stats */
1151 _PyHash_Fini();
1152
Eric Snowdae02762017-09-14 00:35:58 -07001153#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -08001154 if (interp->core_config.show_ref_count) {
1155 _PyDebug_PrintTotalRefs();
1156 }
Eric Snowdae02762017-09-14 00:35:58 -07001157#endif
Nick Coghland6009512014-11-20 21:39:37 +10001158
1159#ifdef Py_TRACE_REFS
1160 /* Display all objects still alive -- this can invoke arbitrary
1161 * __repr__ overrides, so requires a mostly-intact interpreter.
1162 * Alas, a lot of stuff may still be alive now that will be cleaned
1163 * up later.
1164 */
1165 if (Py_GETENV("PYTHONDUMPREFS"))
1166 _Py_PrintReferences(stderr);
1167#endif /* Py_TRACE_REFS */
1168
1169 /* Clear interpreter state and all thread states. */
1170 PyInterpreterState_Clear(interp);
1171
1172 /* Now we decref the exception classes. After this point nothing
1173 can raise an exception. That's okay, because each Fini() method
1174 below has been checked to make sure no exceptions are ever
1175 raised.
1176 */
1177
1178 _PyExc_Fini();
1179
1180 /* Sundry finalizers */
1181 PyMethod_Fini();
1182 PyFrame_Fini();
1183 PyCFunction_Fini();
1184 PyTuple_Fini();
1185 PyList_Fini();
1186 PySet_Fini();
1187 PyBytes_Fini();
1188 PyByteArray_Fini();
1189 PyLong_Fini();
1190 PyFloat_Fini();
1191 PyDict_Fini();
1192 PySlice_Fini();
1193 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001194 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001195 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001196 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001197
1198 /* Cleanup Unicode implementation */
1199 _PyUnicode_Fini();
1200
1201 /* reset file system default encoding */
1202 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1203 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1204 Py_FileSystemDefaultEncoding = NULL;
1205 }
1206
1207 /* XXX Still allocated:
1208 - various static ad-hoc pointers to interned strings
1209 - int and float free list blocks
1210 - whatever various modules and libraries allocate
1211 */
1212
1213 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1214
1215 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001216 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001217
1218 /* Delete current thread. After this, many C API calls become crashy. */
1219 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001220
Nick Coghland6009512014-11-20 21:39:37 +10001221 PyInterpreterState_Delete(interp);
1222
1223#ifdef Py_TRACE_REFS
1224 /* Display addresses (& refcnts) of all objects still alive.
1225 * An address can be used to find the repr of the object, printed
1226 * above by _Py_PrintReferences.
1227 */
1228 if (Py_GETENV("PYTHONDUMPREFS"))
1229 _Py_PrintReferenceAddresses(stderr);
1230#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001231#ifdef WITH_PYMALLOC
1232 if (_PyMem_PymallocEnabled()) {
1233 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1234 if (opt != NULL && *opt != '\0')
1235 _PyObject_DebugMallocStats(stderr);
1236 }
Nick Coghland6009512014-11-20 21:39:37 +10001237#endif
1238
1239 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001240 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001241 return status;
1242}
1243
1244void
1245Py_Finalize(void)
1246{
1247 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001248}
1249
1250/* Create and initialize a new interpreter and thread, and return the
1251 new thread. This requires that Py_Initialize() has been called
1252 first.
1253
1254 Unsuccessful initialization yields a NULL pointer. Note that *no*
1255 exception information is available even in this case -- the
1256 exception information is held in the thread, and there is no
1257 thread.
1258
1259 Locking: as above.
1260
1261*/
1262
Victor Stinnera7368ac2017-11-15 18:11:45 -08001263static _PyInitError
1264new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001265{
1266 PyInterpreterState *interp;
1267 PyThreadState *tstate, *save_tstate;
1268 PyObject *bimod, *sysmod;
1269
Victor Stinnera7368ac2017-11-15 18:11:45 -08001270 if (!_PyRuntime.initialized) {
1271 return _Py_INIT_ERR("Py_Initialize must be called first");
1272 }
Nick Coghland6009512014-11-20 21:39:37 +10001273
Victor Stinner8a1be612016-03-14 22:07:55 +01001274 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1275 interpreters: disable PyGILState_Check(). */
1276 _PyGILState_check_enabled = 0;
1277
Nick Coghland6009512014-11-20 21:39:37 +10001278 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001279 if (interp == NULL) {
1280 *tstate_p = NULL;
1281 return _Py_INIT_OK();
1282 }
Nick Coghland6009512014-11-20 21:39:37 +10001283
1284 tstate = PyThreadState_New(interp);
1285 if (tstate == NULL) {
1286 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001287 *tstate_p = NULL;
1288 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001289 }
1290
1291 save_tstate = PyThreadState_Swap(tstate);
1292
Eric Snow1abcf672017-05-23 21:46:51 -07001293 /* Copy the current interpreter config into the new interpreter */
1294 if (save_tstate != NULL) {
1295 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001296 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001297 } else {
1298 /* No current thread state, copy from the main interpreter */
1299 PyInterpreterState *main_interp = PyInterpreterState_Main();
1300 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001301 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001302 }
1303
Nick Coghland6009512014-11-20 21:39:37 +10001304 /* XXX The following is lax in error checking */
1305
Victor Stinnere32e79f2017-11-23 01:49:45 +01001306 wchar_t *sys_path = _Py_GetPathWithConfig(&interp->config);
Victor Stinnerd4341102017-11-23 00:12:09 +01001307
Eric Snowd393c1b2017-09-14 12:18:12 -06001308 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001309 if (modules == NULL) {
1310 return _Py_INIT_ERR("can't make modules dictionary");
1311 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001312 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001313
Eric Snowd393c1b2017-09-14 12:18:12 -06001314 sysmod = _PyImport_FindBuiltin("sys", modules);
1315 if (sysmod != NULL) {
1316 interp->sysdict = PyModule_GetDict(sysmod);
1317 if (interp->sysdict == NULL)
1318 goto handle_error;
1319 Py_INCREF(interp->sysdict);
1320 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerd4341102017-11-23 00:12:09 +01001321 PySys_SetPath(sys_path);
Eric Snowd393c1b2017-09-14 12:18:12 -06001322 _PySys_EndInit(interp->sysdict);
1323 }
1324
1325 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001326 if (bimod != NULL) {
1327 interp->builtins = PyModule_GetDict(bimod);
1328 if (interp->builtins == NULL)
1329 goto handle_error;
1330 Py_INCREF(interp->builtins);
1331 }
1332
1333 /* initialize builtin exceptions */
1334 _PyExc_Init(bimod);
1335
Nick Coghland6009512014-11-20 21:39:37 +10001336 if (bimod != NULL && sysmod != NULL) {
1337 PyObject *pstderr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001338 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001339
Nick Coghland6009512014-11-20 21:39:37 +10001340 /* Set up a preliminary stderr printer until we have enough
1341 infrastructure for the io module in place. */
1342 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001343 if (pstderr == NULL) {
1344 return _Py_INIT_ERR("can't set preliminary stderr");
1345 }
Nick Coghland6009512014-11-20 21:39:37 +10001346 _PySys_SetObjectId(&PyId_stderr, pstderr);
1347 PySys_SetObject("__stderr__", pstderr);
1348 Py_DECREF(pstderr);
1349
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001350 err = _PyImportHooks_Init();
1351 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001352 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001353 }
Nick Coghland6009512014-11-20 21:39:37 +10001354
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001355 err = initimport(interp, sysmod);
1356 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001357 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001358 }
Nick Coghland6009512014-11-20 21:39:37 +10001359
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001360 err = initexternalimport(interp);
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 = initfsencoding(interp);
1366 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001367 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001368 }
1369
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 err = init_sys_streams();
1371 if (_Py_INIT_FAILED(err)) {
1372 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001373 }
1374
1375 err = add_main_module(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
1380 if (!Py_NoSiteFlag) {
1381 err = initsite();
1382 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001383 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001384 }
1385 }
Nick Coghland6009512014-11-20 21:39:37 +10001386 }
1387
Victor Stinnera7368ac2017-11-15 18:11:45 -08001388 if (PyErr_Occurred()) {
1389 goto handle_error;
1390 }
Nick Coghland6009512014-11-20 21:39:37 +10001391
Victor Stinnera7368ac2017-11-15 18:11:45 -08001392 *tstate_p = tstate;
1393 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001394
Nick Coghland6009512014-11-20 21:39:37 +10001395handle_error:
1396 /* Oops, it didn't work. Undo it all. */
1397
1398 PyErr_PrintEx(0);
1399 PyThreadState_Clear(tstate);
1400 PyThreadState_Swap(save_tstate);
1401 PyThreadState_Delete(tstate);
1402 PyInterpreterState_Delete(interp);
1403
Victor Stinnera7368ac2017-11-15 18:11:45 -08001404 *tstate_p = NULL;
1405 return _Py_INIT_OK();
1406}
1407
1408PyThreadState *
1409Py_NewInterpreter(void)
1410{
1411 PyThreadState *tstate;
1412 _PyInitError err = new_interpreter(&tstate);
1413 if (_Py_INIT_FAILED(err)) {
1414 _Py_FatalInitError(err);
1415 }
1416 return tstate;
1417
Nick Coghland6009512014-11-20 21:39:37 +10001418}
1419
1420/* Delete an interpreter and its last thread. This requires that the
1421 given thread state is current, that the thread has no remaining
1422 frames, and that it is its interpreter's only remaining thread.
1423 It is a fatal error to violate these constraints.
1424
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001425 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001426 everything, regardless.)
1427
1428 Locking: as above.
1429
1430*/
1431
1432void
1433Py_EndInterpreter(PyThreadState *tstate)
1434{
1435 PyInterpreterState *interp = tstate->interp;
1436
1437 if (tstate != PyThreadState_GET())
1438 Py_FatalError("Py_EndInterpreter: thread is not current");
1439 if (tstate->frame != NULL)
1440 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1441
1442 wait_for_thread_shutdown();
1443
1444 if (tstate != interp->tstate_head || tstate->next != NULL)
1445 Py_FatalError("Py_EndInterpreter: not the last thread");
1446
1447 PyImport_Cleanup();
1448 PyInterpreterState_Clear(interp);
1449 PyThreadState_Swap(NULL);
1450 PyInterpreterState_Delete(interp);
1451}
1452
1453#ifdef MS_WINDOWS
1454static wchar_t *progname = L"python";
1455#else
1456static wchar_t *progname = L"python3";
1457#endif
1458
1459void
1460Py_SetProgramName(wchar_t *pn)
1461{
1462 if (pn && *pn)
1463 progname = pn;
1464}
1465
1466wchar_t *
1467Py_GetProgramName(void)
1468{
1469 return progname;
1470}
1471
1472static wchar_t *default_home = NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001473
1474void
1475Py_SetPythonHome(wchar_t *home)
1476{
1477 default_home = home;
1478}
1479
1480wchar_t *
Victor Stinner1f151112017-11-23 10:43:14 +01001481_Py_GetPythonHomeWithConfig(const _PyMainInterpreterConfig *config)
1482{
1483 /* Use a static buffer to avoid heap memory allocation failure.
1484 Py_GetPythonHome() doesn't allow to report error, and the caller
1485 doesn't release memory. */
1486 static wchar_t buffer[MAXPATHLEN+1];
1487
1488 if (default_home) {
1489 return default_home;
1490 }
1491
1492 if (config) {
1493 return config->pythonhome;
1494 }
1495
1496 char *home = Py_GETENV("PYTHONHOME");
1497 if (!home) {
1498 return NULL;
1499 }
1500
1501 size_t size = Py_ARRAY_LENGTH(buffer);
1502 size_t r = mbstowcs(buffer, home, size);
1503 if (r == (size_t)-1 || r >= size) {
1504 /* conversion failed or the static buffer is too small */
1505 return NULL;
1506 }
1507
1508 return buffer;
1509}
1510
1511wchar_t *
Nick Coghland6009512014-11-20 21:39:37 +10001512Py_GetPythonHome(void)
1513{
Victor Stinner1f151112017-11-23 10:43:14 +01001514 return _Py_GetPythonHomeWithConfig(NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001515}
1516
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001518
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001519static _PyInitError
1520add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001521{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001522 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001523 m = PyImport_AddModule("__main__");
1524 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001525 return _Py_INIT_ERR("can't create __main__ module");
1526
Nick Coghland6009512014-11-20 21:39:37 +10001527 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001528 ann_dict = PyDict_New();
1529 if ((ann_dict == NULL) ||
1530 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001532 }
1533 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534
Nick Coghland6009512014-11-20 21:39:37 +10001535 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1536 PyObject *bimod = PyImport_ImportModule("builtins");
1537 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001538 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001539 }
1540 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001542 }
1543 Py_DECREF(bimod);
1544 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001545
Nick Coghland6009512014-11-20 21:39:37 +10001546 /* Main is a little special - imp.is_builtin("__main__") will return
1547 * False, but BuiltinImporter is still the most appropriate initial
1548 * setting for its __loader__ attribute. A more suitable value will
1549 * be set if __main__ gets further initialized later in the startup
1550 * process.
1551 */
1552 loader = PyDict_GetItemString(d, "__loader__");
1553 if (loader == NULL || loader == Py_None) {
1554 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1555 "BuiltinImporter");
1556 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001557 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001558 }
1559 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001560 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001561 }
1562 Py_DECREF(loader);
1563 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001565}
1566
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001567static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001568initfsencoding(PyInterpreterState *interp)
1569{
1570 PyObject *codec;
1571
Steve Dowercc16be82016-09-08 10:35:16 -07001572#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001573 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001574 Py_FileSystemDefaultEncoding = "mbcs";
1575 Py_FileSystemDefaultEncodeErrors = "replace";
1576 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001577 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001578 Py_FileSystemDefaultEncoding = "utf-8";
1579 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1580 }
1581#else
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001582 if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001583 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001584 if (Py_FileSystemDefaultEncoding == NULL) {
1585 return _Py_INIT_ERR("Unable to get the locale encoding");
1586 }
Nick Coghland6009512014-11-20 21:39:37 +10001587
1588 Py_HasFileSystemDefaultEncoding = 0;
1589 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001590 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001591 }
Steve Dowercc16be82016-09-08 10:35:16 -07001592#endif
Nick Coghland6009512014-11-20 21:39:37 +10001593
1594 /* the encoding is mbcs, utf-8 or ascii */
1595 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1596 if (!codec) {
1597 /* Such error can only occurs in critical situations: no more
1598 * memory, import a module of the standard library failed,
1599 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001600 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001601 }
1602 Py_DECREF(codec);
1603 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001604 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001605}
1606
1607/* Import the site module (not into __main__ though) */
1608
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001609static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001610initsite(void)
1611{
1612 PyObject *m;
1613 m = PyImport_ImportModule("site");
1614 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001615 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001616 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001617 Py_DECREF(m);
1618 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001619}
1620
Victor Stinner874dbe82015-09-04 17:29:57 +02001621/* Check if a file descriptor is valid or not.
1622 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1623static int
1624is_valid_fd(int fd)
1625{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001626#ifdef __APPLE__
1627 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1628 and the other side of the pipe is closed, dup(1) succeed, whereas
1629 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1630 such error. */
1631 struct stat st;
1632 return (fstat(fd, &st) == 0);
1633#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001634 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001635 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001636 return 0;
1637 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001638 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1639 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1640 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001641 fd2 = dup(fd);
1642 if (fd2 >= 0)
1643 close(fd2);
1644 _Py_END_SUPPRESS_IPH
1645 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001646#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001647}
1648
1649/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001650static PyObject*
1651create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001652 int fd, int write_mode, const char* name,
1653 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001654{
1655 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1656 const char* mode;
1657 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001658 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001659 int buffering, isatty;
1660 _Py_IDENTIFIER(open);
1661 _Py_IDENTIFIER(isatty);
1662 _Py_IDENTIFIER(TextIOWrapper);
1663 _Py_IDENTIFIER(mode);
1664
Victor Stinner874dbe82015-09-04 17:29:57 +02001665 if (!is_valid_fd(fd))
1666 Py_RETURN_NONE;
1667
Nick Coghland6009512014-11-20 21:39:37 +10001668 /* stdin is always opened in buffered mode, first because it shouldn't
1669 make a difference in common use cases, second because TextIOWrapper
1670 depends on the presence of a read1() method which only exists on
1671 buffered streams.
1672 */
1673 if (Py_UnbufferedStdioFlag && write_mode)
1674 buffering = 0;
1675 else
1676 buffering = -1;
1677 if (write_mode)
1678 mode = "wb";
1679 else
1680 mode = "rb";
1681 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1682 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001683 Py_None, Py_None, /* encoding, errors */
1684 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001685 if (buf == NULL)
1686 goto error;
1687
1688 if (buffering) {
1689 _Py_IDENTIFIER(raw);
1690 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1691 if (raw == NULL)
1692 goto error;
1693 }
1694 else {
1695 raw = buf;
1696 Py_INCREF(raw);
1697 }
1698
Steve Dower39294992016-08-30 21:22:36 -07001699#ifdef MS_WINDOWS
1700 /* Windows console IO is always UTF-8 encoded */
1701 if (PyWindowsConsoleIO_Check(raw))
1702 encoding = "utf-8";
1703#endif
1704
Nick Coghland6009512014-11-20 21:39:37 +10001705 text = PyUnicode_FromString(name);
1706 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1707 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001708 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001709 if (res == NULL)
1710 goto error;
1711 isatty = PyObject_IsTrue(res);
1712 Py_DECREF(res);
1713 if (isatty == -1)
1714 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001715 if (Py_UnbufferedStdioFlag)
1716 write_through = Py_True;
1717 else
1718 write_through = Py_False;
1719 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001720 line_buffering = Py_True;
1721 else
1722 line_buffering = Py_False;
1723
1724 Py_CLEAR(raw);
1725 Py_CLEAR(text);
1726
1727#ifdef MS_WINDOWS
1728 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1729 newlines to "\n".
1730 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1731 newline = NULL;
1732#else
1733 /* sys.stdin: split lines at "\n".
1734 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1735 newline = "\n";
1736#endif
1737
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001738 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001739 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001740 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001741 Py_CLEAR(buf);
1742 if (stream == NULL)
1743 goto error;
1744
1745 if (write_mode)
1746 mode = "w";
1747 else
1748 mode = "r";
1749 text = PyUnicode_FromString(mode);
1750 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1751 goto error;
1752 Py_CLEAR(text);
1753 return stream;
1754
1755error:
1756 Py_XDECREF(buf);
1757 Py_XDECREF(stream);
1758 Py_XDECREF(text);
1759 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001760
Victor Stinner874dbe82015-09-04 17:29:57 +02001761 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1762 /* Issue #24891: the file descriptor was closed after the first
1763 is_valid_fd() check was called. Ignore the OSError and set the
1764 stream to None. */
1765 PyErr_Clear();
1766 Py_RETURN_NONE;
1767 }
1768 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001769}
1770
1771/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001772static _PyInitError
1773init_sys_streams(void)
Nick Coghland6009512014-11-20 21:39:37 +10001774{
1775 PyObject *iomod = NULL, *wrapper;
1776 PyObject *bimod = NULL;
1777 PyObject *m;
1778 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001779 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001780 PyObject * encoding_attr;
1781 char *pythonioencoding = NULL, *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001782 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001783
1784 /* Hack to avoid a nasty recursion issue when Python is invoked
1785 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1786 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1787 goto error;
1788 }
1789 Py_DECREF(m);
1790
1791 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1792 goto error;
1793 }
1794 Py_DECREF(m);
1795
1796 if (!(bimod = PyImport_ImportModule("builtins"))) {
1797 goto error;
1798 }
1799
1800 if (!(iomod = PyImport_ImportModule("io"))) {
1801 goto error;
1802 }
1803 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1804 goto error;
1805 }
1806
1807 /* Set builtins.open */
1808 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1809 Py_DECREF(wrapper);
1810 goto error;
1811 }
1812 Py_DECREF(wrapper);
1813
1814 encoding = _Py_StandardStreamEncoding;
1815 errors = _Py_StandardStreamErrors;
1816 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001817 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1818 if (pythonioencoding) {
1819 char *err;
1820 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1821 if (pythonioencoding == NULL) {
1822 PyErr_NoMemory();
1823 goto error;
1824 }
1825 err = strchr(pythonioencoding, ':');
1826 if (err) {
1827 *err = '\0';
1828 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001829 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001830 errors = err;
1831 }
1832 }
1833 if (*pythonioencoding && !encoding) {
1834 encoding = pythonioencoding;
1835 }
1836 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001837 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001838 /* Choose the default error handler based on the current locale */
1839 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001840 }
Nick Coghland6009512014-11-20 21:39:37 +10001841 }
1842
1843 /* Set sys.stdin */
1844 fd = fileno(stdin);
1845 /* Under some conditions stdin, stdout and stderr may not be connected
1846 * and fileno() may point to an invalid file descriptor. For example
1847 * GUI apps don't have valid standard streams by default.
1848 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001849 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1850 if (std == NULL)
1851 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001852 PySys_SetObject("__stdin__", std);
1853 _PySys_SetObjectId(&PyId_stdin, std);
1854 Py_DECREF(std);
1855
1856 /* Set sys.stdout */
1857 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001858 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1859 if (std == NULL)
1860 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001861 PySys_SetObject("__stdout__", std);
1862 _PySys_SetObjectId(&PyId_stdout, std);
1863 Py_DECREF(std);
1864
1865#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1866 /* Set sys.stderr, replaces the preliminary stderr */
1867 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001868 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1869 if (std == NULL)
1870 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001871
1872 /* Same as hack above, pre-import stderr's codec to avoid recursion
1873 when import.c tries to write to stderr in verbose mode. */
1874 encoding_attr = PyObject_GetAttrString(std, "encoding");
1875 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001876 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001877 if (std_encoding != NULL) {
1878 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1879 Py_XDECREF(codec_info);
1880 }
1881 Py_DECREF(encoding_attr);
1882 }
1883 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1884
1885 if (PySys_SetObject("__stderr__", std) < 0) {
1886 Py_DECREF(std);
1887 goto error;
1888 }
1889 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1890 Py_DECREF(std);
1891 goto error;
1892 }
1893 Py_DECREF(std);
1894#endif
1895
Victor Stinnera7368ac2017-11-15 18:11:45 -08001896 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001897
Victor Stinnera7368ac2017-11-15 18:11:45 -08001898error:
1899 res = _Py_INIT_ERR("can't initialize sys standard streams");
1900
1901done:
Nick Coghland6009512014-11-20 21:39:37 +10001902 /* We won't need them anymore. */
1903 if (_Py_StandardStreamEncoding) {
1904 PyMem_RawFree(_Py_StandardStreamEncoding);
1905 _Py_StandardStreamEncoding = NULL;
1906 }
1907 if (_Py_StandardStreamErrors) {
1908 PyMem_RawFree(_Py_StandardStreamErrors);
1909 _Py_StandardStreamErrors = NULL;
1910 }
1911 PyMem_Free(pythonioencoding);
1912 Py_XDECREF(bimod);
1913 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001914 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001915}
1916
1917
Victor Stinner10dc4842015-03-24 12:01:30 +01001918static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001919_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001920{
Victor Stinner10dc4842015-03-24 12:01:30 +01001921 fputc('\n', stderr);
1922 fflush(stderr);
1923
1924 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001925 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001926}
Victor Stinner791da1c2016-03-14 16:53:12 +01001927
1928/* Print the current exception (if an exception is set) with its traceback,
1929 or display the current Python stack.
1930
1931 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1932 called on catastrophic cases.
1933
1934 Return 1 if the traceback was displayed, 0 otherwise. */
1935
1936static int
1937_Py_FatalError_PrintExc(int fd)
1938{
1939 PyObject *ferr, *res;
1940 PyObject *exception, *v, *tb;
1941 int has_tb;
1942
1943 if (PyThreadState_GET() == NULL) {
1944 /* The GIL is released: trying to acquire it is likely to deadlock,
1945 just give up. */
1946 return 0;
1947 }
1948
1949 PyErr_Fetch(&exception, &v, &tb);
1950 if (exception == NULL) {
1951 /* No current exception */
1952 return 0;
1953 }
1954
1955 ferr = _PySys_GetObjectId(&PyId_stderr);
1956 if (ferr == NULL || ferr == Py_None) {
1957 /* sys.stderr is not set yet or set to None,
1958 no need to try to display the exception */
1959 return 0;
1960 }
1961
1962 PyErr_NormalizeException(&exception, &v, &tb);
1963 if (tb == NULL) {
1964 tb = Py_None;
1965 Py_INCREF(tb);
1966 }
1967 PyException_SetTraceback(v, tb);
1968 if (exception == NULL) {
1969 /* PyErr_NormalizeException() failed */
1970 return 0;
1971 }
1972
1973 has_tb = (tb != Py_None);
1974 PyErr_Display(exception, v, tb);
1975 Py_XDECREF(exception);
1976 Py_XDECREF(v);
1977 Py_XDECREF(tb);
1978
1979 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001980 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001981 if (res == NULL)
1982 PyErr_Clear();
1983 else
1984 Py_DECREF(res);
1985
1986 return has_tb;
1987}
1988
Nick Coghland6009512014-11-20 21:39:37 +10001989/* Print fatal error message and abort */
1990
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001991#ifdef MS_WINDOWS
1992static void
1993fatal_output_debug(const char *msg)
1994{
1995 /* buffer of 256 bytes allocated on the stack */
1996 WCHAR buffer[256 / sizeof(WCHAR)];
1997 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1998 size_t msglen;
1999
2000 OutputDebugStringW(L"Fatal Python error: ");
2001
2002 msglen = strlen(msg);
2003 while (msglen) {
2004 size_t i;
2005
2006 if (buflen > msglen) {
2007 buflen = msglen;
2008 }
2009
2010 /* Convert the message to wchar_t. This uses a simple one-to-one
2011 conversion, assuming that the this error message actually uses
2012 ASCII only. If this ceases to be true, we will have to convert. */
2013 for (i=0; i < buflen; ++i) {
2014 buffer[i] = msg[i];
2015 }
2016 buffer[i] = L'\0';
2017 OutputDebugStringW(buffer);
2018
2019 msg += buflen;
2020 msglen -= buflen;
2021 }
2022 OutputDebugStringW(L"\n");
2023}
2024#endif
2025
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002026static void
2027fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002028{
2029 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002030 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002031
2032 if (reentrant) {
2033 /* Py_FatalError() caused a second fatal error.
2034 Example: flush_std_files() raises a recursion error. */
2035 goto exit;
2036 }
2037 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002038
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002039 fprintf(stderr, "Fatal Python error: ");
2040 if (prefix) {
2041 fputs(prefix, stderr);
2042 fputs(": ", stderr);
2043 }
2044 if (msg) {
2045 fputs(msg, stderr);
2046 }
2047 else {
2048 fprintf(stderr, "<message not set>");
2049 }
2050 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002051 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002052
Victor Stinnere0deff32015-03-24 13:46:18 +01002053 /* Print the exception (if an exception is set) with its traceback,
2054 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002055 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002056 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002057 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002058
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002059 /* The main purpose of faulthandler is to display the traceback.
2060 This function already did its best to display a traceback.
2061 Disable faulthandler to prevent writing a second traceback
2062 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002063 _PyFaulthandler_Fini();
2064
Victor Stinner791da1c2016-03-14 16:53:12 +01002065 /* Check if the current Python thread hold the GIL */
2066 if (PyThreadState_GET() != NULL) {
2067 /* Flush sys.stdout and sys.stderr */
2068 flush_std_files();
2069 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002070
Nick Coghland6009512014-11-20 21:39:37 +10002071#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002072 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002073#endif /* MS_WINDOWS */
2074
2075exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002076 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002077#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002078 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002079#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002080 abort();
2081 }
2082 else {
2083 exit(status);
2084 }
2085}
2086
2087void
2088Py_FatalError(const char *msg)
2089{
2090 fatal_error(NULL, msg, -1);
2091}
2092
2093void
2094_Py_FatalInitError(_PyInitError err)
2095{
2096 /* On "user" error: exit with status 1.
2097 For all other errors, call abort(). */
2098 int status = err.user_err ? 1 : -1;
2099 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002100}
2101
2102/* Clean up and exit */
2103
Victor Stinnerd7292b52016-06-17 12:29:00 +02002104# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002105
Nick Coghland6009512014-11-20 21:39:37 +10002106/* For the atexit module. */
2107void _Py_PyAtExit(void (*func)(void))
2108{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002109 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002110}
2111
2112static void
2113call_py_exitfuncs(void)
2114{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002115 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002116 return;
2117
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002118 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002119 PyErr_Clear();
2120}
2121
2122/* Wait until threading._shutdown completes, provided
2123 the threading module was imported in the first place.
2124 The shutdown routine will wait until all non-daemon
2125 "threading" threads have completed. */
2126static void
2127wait_for_thread_shutdown(void)
2128{
Nick Coghland6009512014-11-20 21:39:37 +10002129 _Py_IDENTIFIER(_shutdown);
2130 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002131 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002132 if (threading == NULL) {
2133 /* threading not imported */
2134 PyErr_Clear();
2135 return;
2136 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002137 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002138 if (result == NULL) {
2139 PyErr_WriteUnraisable(threading);
2140 }
2141 else {
2142 Py_DECREF(result);
2143 }
2144 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002145}
2146
2147#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002148int Py_AtExit(void (*func)(void))
2149{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002150 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002151 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002152 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002153 return 0;
2154}
2155
2156static void
2157call_ll_exitfuncs(void)
2158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002159 while (_PyRuntime.nexitfuncs > 0)
2160 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002161
2162 fflush(stdout);
2163 fflush(stderr);
2164}
2165
2166void
2167Py_Exit(int sts)
2168{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002169 if (Py_FinalizeEx() < 0) {
2170 sts = 120;
2171 }
Nick Coghland6009512014-11-20 21:39:37 +10002172
2173 exit(sts);
2174}
2175
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002176static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002177initsigs(void)
2178{
2179#ifdef SIGPIPE
2180 PyOS_setsig(SIGPIPE, SIG_IGN);
2181#endif
2182#ifdef SIGXFZ
2183 PyOS_setsig(SIGXFZ, SIG_IGN);
2184#endif
2185#ifdef SIGXFSZ
2186 PyOS_setsig(SIGXFSZ, SIG_IGN);
2187#endif
2188 PyOS_InitInterrupts(); /* May imply initsignal() */
2189 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002190 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002191 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002192 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002193}
2194
2195
2196/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2197 *
2198 * All of the code in this function must only use async-signal-safe functions,
2199 * listed at `man 7 signal` or
2200 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2201 */
2202void
2203_Py_RestoreSignals(void)
2204{
2205#ifdef SIGPIPE
2206 PyOS_setsig(SIGPIPE, SIG_DFL);
2207#endif
2208#ifdef SIGXFZ
2209 PyOS_setsig(SIGXFZ, SIG_DFL);
2210#endif
2211#ifdef SIGXFSZ
2212 PyOS_setsig(SIGXFSZ, SIG_DFL);
2213#endif
2214}
2215
2216
2217/*
2218 * The file descriptor fd is considered ``interactive'' if either
2219 * a) isatty(fd) is TRUE, or
2220 * b) the -i flag was given, and the filename associated with
2221 * the descriptor is NULL or "<stdin>" or "???".
2222 */
2223int
2224Py_FdIsInteractive(FILE *fp, const char *filename)
2225{
2226 if (isatty((int)fileno(fp)))
2227 return 1;
2228 if (!Py_InteractiveFlag)
2229 return 0;
2230 return (filename == NULL) ||
2231 (strcmp(filename, "<stdin>") == 0) ||
2232 (strcmp(filename, "???") == 0);
2233}
2234
2235
Nick Coghland6009512014-11-20 21:39:37 +10002236/* Wrappers around sigaction() or signal(). */
2237
2238PyOS_sighandler_t
2239PyOS_getsig(int sig)
2240{
2241#ifdef HAVE_SIGACTION
2242 struct sigaction context;
2243 if (sigaction(sig, NULL, &context) == -1)
2244 return SIG_ERR;
2245 return context.sa_handler;
2246#else
2247 PyOS_sighandler_t handler;
2248/* Special signal handling for the secure CRT in Visual Studio 2005 */
2249#if defined(_MSC_VER) && _MSC_VER >= 1400
2250 switch (sig) {
2251 /* Only these signals are valid */
2252 case SIGINT:
2253 case SIGILL:
2254 case SIGFPE:
2255 case SIGSEGV:
2256 case SIGTERM:
2257 case SIGBREAK:
2258 case SIGABRT:
2259 break;
2260 /* Don't call signal() with other values or it will assert */
2261 default:
2262 return SIG_ERR;
2263 }
2264#endif /* _MSC_VER && _MSC_VER >= 1400 */
2265 handler = signal(sig, SIG_IGN);
2266 if (handler != SIG_ERR)
2267 signal(sig, handler);
2268 return handler;
2269#endif
2270}
2271
2272/*
2273 * All of the code in this function must only use async-signal-safe functions,
2274 * listed at `man 7 signal` or
2275 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2276 */
2277PyOS_sighandler_t
2278PyOS_setsig(int sig, PyOS_sighandler_t handler)
2279{
2280#ifdef HAVE_SIGACTION
2281 /* Some code in Modules/signalmodule.c depends on sigaction() being
2282 * used here if HAVE_SIGACTION is defined. Fix that if this code
2283 * changes to invalidate that assumption.
2284 */
2285 struct sigaction context, ocontext;
2286 context.sa_handler = handler;
2287 sigemptyset(&context.sa_mask);
2288 context.sa_flags = 0;
2289 if (sigaction(sig, &context, &ocontext) == -1)
2290 return SIG_ERR;
2291 return ocontext.sa_handler;
2292#else
2293 PyOS_sighandler_t oldhandler;
2294 oldhandler = signal(sig, handler);
2295#ifdef HAVE_SIGINTERRUPT
2296 siginterrupt(sig, 1);
2297#endif
2298 return oldhandler;
2299#endif
2300}
2301
2302#ifdef __cplusplus
2303}
2304#endif