blob: 9eeac9d33be60171080aef1e77a6b241885f8b71 [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. */
770 _PyWarnings_Init();
771
Eric Snow1abcf672017-05-23 21:46:51 -0700772 /* This call sets up builtin and frozen import support */
773 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800774 err = initimport(interp, sysmod);
775 if (_Py_INIT_FAILED(err)) {
776 return err;
777 }
Eric Snow1abcf672017-05-23 21:46:51 -0700778 }
779
780 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600781 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800782 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700783}
784
Eric Snowc7ec9982017-05-23 23:00:52 -0700785/* Read configuration settings from standard locations
786 *
787 * This function doesn't make any changes to the interpreter state - it
788 * merely populates any missing configuration settings. This allows an
789 * embedding application to completely override a config option by
790 * setting it before calling this function, or else modify the default
791 * setting before passing the fully populated config to Py_EndInitialization.
792 *
793 * More advanced selective initialization tricks are possible by calling
794 * this function multiple times with various preconfigured settings.
795 */
796
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800797_PyInitError
798_Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
Eric Snowc7ec9982017-05-23 23:00:52 -0700799{
800 /* Signal handlers are installed by default */
801 if (config->install_signal_handlers < 0) {
802 config->install_signal_handlers = 1;
803 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800804 return _Py_INIT_OK();
Eric Snowc7ec9982017-05-23 23:00:52 -0700805}
806
807/* Update interpreter state based on supplied configuration settings
808 *
809 * After calling this function, most of the restrictions on the interpreter
810 * are lifted. The only remaining incomplete settings are those related
811 * to the main module (sys.argv[0], __main__ metadata)
812 *
813 * Calling this when the interpreter is not initializing, is already
814 * initialized or without a valid current thread state is a fatal error.
815 * Other errors should be reported as normal Python exceptions with a
816 * non-zero return code.
817 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800818_PyInitError
819_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700820{
821 PyInterpreterState *interp;
822 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800823 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700824
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600825 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800826 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700827 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600828 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800829 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700830 }
831
Eric Snow1abcf672017-05-23 21:46:51 -0700832 /* Get current thread state and interpreter pointer */
833 tstate = PyThreadState_GET();
834 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800835 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700836 interp = tstate->interp;
837 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800838 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700839
840 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700841 interp->config = *config;
842
Victor Stinnerd4341102017-11-23 00:12:09 +0100843 /* GetPath may initialize state that _PySys_EndInit locks
844 in, and so has to be called first. */
845 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
846 wchar_t *sys_path = _Py_GetPathWithConfig(&interp->core_config);
847
Eric Snow1abcf672017-05-23 21:46:51 -0700848 if (interp->core_config._disable_importlib) {
849 /* Special mode for freeze_importlib: run with no import system
850 *
851 * This means anything which needs support from extension modules
852 * or pure Python code in the standard library won't work.
853 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600854 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800855 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700856 }
857 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000858
Victor Stinner13019fd2015-04-03 13:10:54 +0200859 if (_PyTime_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800860 return _Py_INIT_ERR("can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200861
Eric Snow1abcf672017-05-23 21:46:51 -0700862 /* Finish setting up the sys module and import system */
Victor Stinnerd4341102017-11-23 00:12:09 +0100863 PySys_SetPath(sys_path);
Eric Snow1abcf672017-05-23 21:46:51 -0700864 if (_PySys_EndInit(interp->sysdict) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnera7368ac2017-11-15 18:11:45 -0800866
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800867 err = initexternalimport(interp);
868 if (_Py_INIT_FAILED(err)) {
869 return err;
870 }
Nick Coghland6009512014-11-20 21:39:37 +1000871
872 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800873 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800874 if (_Py_INIT_FAILED(err)) {
875 return err;
876 }
Nick Coghland6009512014-11-20 21:39:37 +1000877
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800878 err = initfsencoding(interp);
879 if (_Py_INIT_FAILED(err)) {
880 return err;
881 }
Nick Coghland6009512014-11-20 21:39:37 +1000882
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800883 if (config->install_signal_handlers) {
884 err = initsigs(); /* Signal handling stuff, including initintr() */
885 if (_Py_INIT_FAILED(err)) {
886 return err;
887 }
888 }
Nick Coghland6009512014-11-20 21:39:37 +1000889
Victor Stinnera7368ac2017-11-15 18:11:45 -0800890 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000892
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800893 err = add_main_module(interp);
894 if (_Py_INIT_FAILED(err)) {
895 return err;
896 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800897
898 err = init_sys_streams();
899 if (_Py_INIT_FAILED(err)) {
900 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800901 }
Nick Coghland6009512014-11-20 21:39:37 +1000902
903 /* Initialize warnings. */
904 if (PySys_HasWarnOptions()) {
905 PyObject *warnings_module = PyImport_ImportModule("warnings");
906 if (warnings_module == NULL) {
907 fprintf(stderr, "'import warnings' failed; traceback:\n");
908 PyErr_Print();
909 }
910 Py_XDECREF(warnings_module);
911 }
912
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600913 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700914
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800915 if (!Py_NoSiteFlag) {
916 err = initsite(); /* Module site */
917 if (_Py_INIT_FAILED(err)) {
918 return err;
919 }
920 }
Eric Snow1abcf672017-05-23 21:46:51 -0700921
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800922 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000923}
924
Eric Snowc7ec9982017-05-23 23:00:52 -0700925#undef _INIT_DEBUG_PRINT
926
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700928_Py_InitializeEx_Private(int install_sigs, int install_importlib)
929{
930 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700931 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800932 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700933
934 /* TODO: Moar config options! */
935 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
936 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700937 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800938
939 err = _Py_InitializeCore(&core_config);
940 if (_Py_INIT_FAILED(err)) {
941 return err;
942 }
943
Eric Snowc7ec9982017-05-23 23:00:52 -0700944 /* TODO: Print any exceptions raised by these operations */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800945 err = _Py_ReadMainInterpreterConfig(&config);
946 if (_Py_INIT_FAILED(err)) {
947 return err;
948 }
949
950 err = _Py_InitializeMainInterpreter(&config);
951 if (_Py_INIT_FAILED(err)) {
952 return err;
953 }
954
955 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700956}
957
958
959void
Nick Coghland6009512014-11-20 21:39:37 +1000960Py_InitializeEx(int install_sigs)
961{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800962 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
963 if (_Py_INIT_FAILED(err)) {
964 _Py_FatalInitError(err);
965 }
Nick Coghland6009512014-11-20 21:39:37 +1000966}
967
968void
969Py_Initialize(void)
970{
971 Py_InitializeEx(1);
972}
973
974
975#ifdef COUNT_ALLOCS
976extern void dump_counts(FILE*);
977#endif
978
979/* Flush stdout and stderr */
980
981static int
982file_is_closed(PyObject *fobj)
983{
984 int r;
985 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
986 if (tmp == NULL) {
987 PyErr_Clear();
988 return 0;
989 }
990 r = PyObject_IsTrue(tmp);
991 Py_DECREF(tmp);
992 if (r < 0)
993 PyErr_Clear();
994 return r > 0;
995}
996
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000997static int
Nick Coghland6009512014-11-20 21:39:37 +1000998flush_std_files(void)
999{
1000 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1001 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1002 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001003 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001004
1005 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001006 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001007 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001008 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001009 status = -1;
1010 }
Nick Coghland6009512014-11-20 21:39:37 +10001011 else
1012 Py_DECREF(tmp);
1013 }
1014
1015 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001016 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001017 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001018 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001019 status = -1;
1020 }
Nick Coghland6009512014-11-20 21:39:37 +10001021 else
1022 Py_DECREF(tmp);
1023 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001024
1025 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001026}
1027
1028/* Undo the effect of Py_Initialize().
1029
1030 Beware: if multiple interpreter and/or thread states exist, these
1031 are not wiped out; only the current thread and interpreter state
1032 are deleted. But since everything else is deleted, those other
1033 interpreter and thread states should no longer be used.
1034
1035 (XXX We should do better, e.g. wipe out all interpreters and
1036 threads.)
1037
1038 Locking: as above.
1039
1040*/
1041
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001042int
1043Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001044{
1045 PyInterpreterState *interp;
1046 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001047 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001048
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001049 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001050 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001051
1052 wait_for_thread_shutdown();
1053
1054 /* The interpreter is still entirely intact at this point, and the
1055 * exit funcs may be relying on that. In particular, if some thread
1056 * or exit func is still waiting to do an import, the import machinery
1057 * expects Py_IsInitialized() to return true. So don't say the
1058 * interpreter is uninitialized until after the exit funcs have run.
1059 * Note that Threading.py uses an exit func to do a join on all the
1060 * threads created thru it, so this also protects pending imports in
1061 * the threads created via Threading.
1062 */
1063 call_py_exitfuncs();
1064
1065 /* Get current thread state and interpreter pointer */
1066 tstate = PyThreadState_GET();
1067 interp = tstate->interp;
1068
1069 /* Remaining threads (e.g. daemon threads) will automatically exit
1070 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001071 _PyRuntime.finalizing = tstate;
1072 _PyRuntime.initialized = 0;
1073 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001074
Victor Stinnere0deff32015-03-24 13:46:18 +01001075 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001076 if (flush_std_files() < 0) {
1077 status = -1;
1078 }
Nick Coghland6009512014-11-20 21:39:37 +10001079
1080 /* Disable signal handling */
1081 PyOS_FiniInterrupts();
1082
1083 /* Collect garbage. This may call finalizers; it's nice to call these
1084 * before all modules are destroyed.
1085 * XXX If a __del__ or weakref callback is triggered here, and tries to
1086 * XXX import a module, bad things can happen, because Python no
1087 * XXX longer believes it's initialized.
1088 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1089 * XXX is easy to provoke that way. I've also seen, e.g.,
1090 * XXX Exception exceptions.ImportError: 'No module named sha'
1091 * XXX in <function callback at 0x008F5718> ignored
1092 * XXX but I'm unclear on exactly how that one happens. In any case,
1093 * XXX I haven't seen a real-life report of either of these.
1094 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001095 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001096#ifdef COUNT_ALLOCS
1097 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1098 each collection might release some types from the type
1099 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001100 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001101 /* nothing */;
1102#endif
Eric Snowdae02762017-09-14 00:35:58 -07001103
Nick Coghland6009512014-11-20 21:39:37 +10001104 /* Destroy all modules */
1105 PyImport_Cleanup();
1106
Victor Stinnere0deff32015-03-24 13:46:18 +01001107 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001108 if (flush_std_files() < 0) {
1109 status = -1;
1110 }
Nick Coghland6009512014-11-20 21:39:37 +10001111
1112 /* Collect final garbage. This disposes of cycles created by
1113 * class definitions, for example.
1114 * XXX This is disabled because it caused too many problems. If
1115 * XXX a __del__ or weakref callback triggers here, Python code has
1116 * XXX a hard time running, because even the sys module has been
1117 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1118 * XXX One symptom is a sequence of information-free messages
1119 * XXX coming from threads (if a __del__ or callback is invoked,
1120 * XXX other threads can execute too, and any exception they encounter
1121 * XXX triggers a comedy of errors as subsystem after subsystem
1122 * XXX fails to find what it *expects* to find in sys to help report
1123 * XXX the exception and consequent unexpected failures). I've also
1124 * XXX seen segfaults then, after adding print statements to the
1125 * XXX Python code getting called.
1126 */
1127#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001128 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001129#endif
1130
1131 /* Disable tracemalloc after all Python objects have been destroyed,
1132 so it is possible to use tracemalloc in objects destructor. */
1133 _PyTraceMalloc_Fini();
1134
1135 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1136 _PyImport_Fini();
1137
1138 /* Cleanup typeobject.c's internal caches. */
1139 _PyType_Fini();
1140
1141 /* unload faulthandler module */
1142 _PyFaulthandler_Fini();
1143
1144 /* Debugging stuff */
1145#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001146 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001147#endif
1148 /* dump hash stats */
1149 _PyHash_Fini();
1150
Eric Snowdae02762017-09-14 00:35:58 -07001151#ifdef Py_REF_DEBUG
Victor Stinner25420fe2017-11-20 18:12:22 -08001152 if (interp->core_config.show_ref_count) {
1153 _PyDebug_PrintTotalRefs();
1154 }
Eric Snowdae02762017-09-14 00:35:58 -07001155#endif
Nick Coghland6009512014-11-20 21:39:37 +10001156
1157#ifdef Py_TRACE_REFS
1158 /* Display all objects still alive -- this can invoke arbitrary
1159 * __repr__ overrides, so requires a mostly-intact interpreter.
1160 * Alas, a lot of stuff may still be alive now that will be cleaned
1161 * up later.
1162 */
1163 if (Py_GETENV("PYTHONDUMPREFS"))
1164 _Py_PrintReferences(stderr);
1165#endif /* Py_TRACE_REFS */
1166
1167 /* Clear interpreter state and all thread states. */
1168 PyInterpreterState_Clear(interp);
1169
1170 /* Now we decref the exception classes. After this point nothing
1171 can raise an exception. That's okay, because each Fini() method
1172 below has been checked to make sure no exceptions are ever
1173 raised.
1174 */
1175
1176 _PyExc_Fini();
1177
1178 /* Sundry finalizers */
1179 PyMethod_Fini();
1180 PyFrame_Fini();
1181 PyCFunction_Fini();
1182 PyTuple_Fini();
1183 PyList_Fini();
1184 PySet_Fini();
1185 PyBytes_Fini();
1186 PyByteArray_Fini();
1187 PyLong_Fini();
1188 PyFloat_Fini();
1189 PyDict_Fini();
1190 PySlice_Fini();
1191 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001192 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001193 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001194 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001195
1196 /* Cleanup Unicode implementation */
1197 _PyUnicode_Fini();
1198
1199 /* reset file system default encoding */
1200 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1201 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1202 Py_FileSystemDefaultEncoding = NULL;
1203 }
1204
1205 /* XXX Still allocated:
1206 - various static ad-hoc pointers to interned strings
1207 - int and float free list blocks
1208 - whatever various modules and libraries allocate
1209 */
1210
1211 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1212
1213 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001214 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001215
1216 /* Delete current thread. After this, many C API calls become crashy. */
1217 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001218
Nick Coghland6009512014-11-20 21:39:37 +10001219 PyInterpreterState_Delete(interp);
1220
1221#ifdef Py_TRACE_REFS
1222 /* Display addresses (& refcnts) of all objects still alive.
1223 * An address can be used to find the repr of the object, printed
1224 * above by _Py_PrintReferences.
1225 */
1226 if (Py_GETENV("PYTHONDUMPREFS"))
1227 _Py_PrintReferenceAddresses(stderr);
1228#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001229#ifdef WITH_PYMALLOC
1230 if (_PyMem_PymallocEnabled()) {
1231 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1232 if (opt != NULL && *opt != '\0')
1233 _PyObject_DebugMallocStats(stderr);
1234 }
Nick Coghland6009512014-11-20 21:39:37 +10001235#endif
1236
1237 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001238 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001239 return status;
1240}
1241
1242void
1243Py_Finalize(void)
1244{
1245 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001246}
1247
1248/* Create and initialize a new interpreter and thread, and return the
1249 new thread. This requires that Py_Initialize() has been called
1250 first.
1251
1252 Unsuccessful initialization yields a NULL pointer. Note that *no*
1253 exception information is available even in this case -- the
1254 exception information is held in the thread, and there is no
1255 thread.
1256
1257 Locking: as above.
1258
1259*/
1260
Victor Stinnera7368ac2017-11-15 18:11:45 -08001261static _PyInitError
1262new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001263{
1264 PyInterpreterState *interp;
1265 PyThreadState *tstate, *save_tstate;
1266 PyObject *bimod, *sysmod;
1267
Victor Stinnera7368ac2017-11-15 18:11:45 -08001268 if (!_PyRuntime.initialized) {
1269 return _Py_INIT_ERR("Py_Initialize must be called first");
1270 }
Nick Coghland6009512014-11-20 21:39:37 +10001271
Victor Stinner8a1be612016-03-14 22:07:55 +01001272 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1273 interpreters: disable PyGILState_Check(). */
1274 _PyGILState_check_enabled = 0;
1275
Nick Coghland6009512014-11-20 21:39:37 +10001276 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001277 if (interp == NULL) {
1278 *tstate_p = NULL;
1279 return _Py_INIT_OK();
1280 }
Nick Coghland6009512014-11-20 21:39:37 +10001281
1282 tstate = PyThreadState_New(interp);
1283 if (tstate == NULL) {
1284 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001285 *tstate_p = NULL;
1286 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001287 }
1288
1289 save_tstate = PyThreadState_Swap(tstate);
1290
Eric Snow1abcf672017-05-23 21:46:51 -07001291 /* Copy the current interpreter config into the new interpreter */
1292 if (save_tstate != NULL) {
1293 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001294 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001295 } else {
1296 /* No current thread state, copy from the main interpreter */
1297 PyInterpreterState *main_interp = PyInterpreterState_Main();
1298 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001299 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001300 }
1301
Nick Coghland6009512014-11-20 21:39:37 +10001302 /* XXX The following is lax in error checking */
1303
Victor Stinnerd4341102017-11-23 00:12:09 +01001304 wchar_t *sys_path = _Py_GetPathWithConfig(&interp->core_config);
1305
Eric Snowd393c1b2017-09-14 12:18:12 -06001306 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001307 if (modules == NULL) {
1308 return _Py_INIT_ERR("can't make modules dictionary");
1309 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001310 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001311
Eric Snowd393c1b2017-09-14 12:18:12 -06001312 sysmod = _PyImport_FindBuiltin("sys", modules);
1313 if (sysmod != NULL) {
1314 interp->sysdict = PyModule_GetDict(sysmod);
1315 if (interp->sysdict == NULL)
1316 goto handle_error;
1317 Py_INCREF(interp->sysdict);
1318 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinnerd4341102017-11-23 00:12:09 +01001319 PySys_SetPath(sys_path);
Eric Snowd393c1b2017-09-14 12:18:12 -06001320 _PySys_EndInit(interp->sysdict);
1321 }
1322
1323 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001324 if (bimod != NULL) {
1325 interp->builtins = PyModule_GetDict(bimod);
1326 if (interp->builtins == NULL)
1327 goto handle_error;
1328 Py_INCREF(interp->builtins);
1329 }
1330
1331 /* initialize builtin exceptions */
1332 _PyExc_Init(bimod);
1333
Nick Coghland6009512014-11-20 21:39:37 +10001334 if (bimod != NULL && sysmod != NULL) {
1335 PyObject *pstderr;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001336 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001337
Nick Coghland6009512014-11-20 21:39:37 +10001338 /* Set up a preliminary stderr printer until we have enough
1339 infrastructure for the io module in place. */
1340 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001341 if (pstderr == NULL) {
1342 return _Py_INIT_ERR("can't set preliminary stderr");
1343 }
Nick Coghland6009512014-11-20 21:39:37 +10001344 _PySys_SetObjectId(&PyId_stderr, pstderr);
1345 PySys_SetObject("__stderr__", pstderr);
1346 Py_DECREF(pstderr);
1347
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001348 err = _PyImportHooks_Init();
1349 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001350 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001351 }
Nick Coghland6009512014-11-20 21:39:37 +10001352
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001353 err = initimport(interp, sysmod);
1354 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001355 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001356 }
Nick Coghland6009512014-11-20 21:39:37 +10001357
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001358 err = initexternalimport(interp);
1359 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001360 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001361 }
Nick Coghland6009512014-11-20 21:39:37 +10001362
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001363 err = initfsencoding(interp);
1364 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001365 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001366 }
1367
Victor Stinnera7368ac2017-11-15 18:11:45 -08001368 err = init_sys_streams();
1369 if (_Py_INIT_FAILED(err)) {
1370 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001371 }
1372
1373 err = add_main_module(interp);
1374 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001375 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001376 }
1377
1378 if (!Py_NoSiteFlag) {
1379 err = initsite();
1380 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001381 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001382 }
1383 }
Nick Coghland6009512014-11-20 21:39:37 +10001384 }
1385
Victor Stinnera7368ac2017-11-15 18:11:45 -08001386 if (PyErr_Occurred()) {
1387 goto handle_error;
1388 }
Nick Coghland6009512014-11-20 21:39:37 +10001389
Victor Stinnera7368ac2017-11-15 18:11:45 -08001390 *tstate_p = tstate;
1391 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001392
Nick Coghland6009512014-11-20 21:39:37 +10001393handle_error:
1394 /* Oops, it didn't work. Undo it all. */
1395
1396 PyErr_PrintEx(0);
1397 PyThreadState_Clear(tstate);
1398 PyThreadState_Swap(save_tstate);
1399 PyThreadState_Delete(tstate);
1400 PyInterpreterState_Delete(interp);
1401
Victor Stinnera7368ac2017-11-15 18:11:45 -08001402 *tstate_p = NULL;
1403 return _Py_INIT_OK();
1404}
1405
1406PyThreadState *
1407Py_NewInterpreter(void)
1408{
1409 PyThreadState *tstate;
1410 _PyInitError err = new_interpreter(&tstate);
1411 if (_Py_INIT_FAILED(err)) {
1412 _Py_FatalInitError(err);
1413 }
1414 return tstate;
1415
Nick Coghland6009512014-11-20 21:39:37 +10001416}
1417
1418/* Delete an interpreter and its last thread. This requires that the
1419 given thread state is current, that the thread has no remaining
1420 frames, and that it is its interpreter's only remaining thread.
1421 It is a fatal error to violate these constraints.
1422
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001423 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001424 everything, regardless.)
1425
1426 Locking: as above.
1427
1428*/
1429
1430void
1431Py_EndInterpreter(PyThreadState *tstate)
1432{
1433 PyInterpreterState *interp = tstate->interp;
1434
1435 if (tstate != PyThreadState_GET())
1436 Py_FatalError("Py_EndInterpreter: thread is not current");
1437 if (tstate->frame != NULL)
1438 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1439
1440 wait_for_thread_shutdown();
1441
1442 if (tstate != interp->tstate_head || tstate->next != NULL)
1443 Py_FatalError("Py_EndInterpreter: not the last thread");
1444
1445 PyImport_Cleanup();
1446 PyInterpreterState_Clear(interp);
1447 PyThreadState_Swap(NULL);
1448 PyInterpreterState_Delete(interp);
1449}
1450
1451#ifdef MS_WINDOWS
1452static wchar_t *progname = L"python";
1453#else
1454static wchar_t *progname = L"python3";
1455#endif
1456
1457void
1458Py_SetProgramName(wchar_t *pn)
1459{
1460 if (pn && *pn)
1461 progname = pn;
1462}
1463
1464wchar_t *
1465Py_GetProgramName(void)
1466{
1467 return progname;
1468}
1469
1470static wchar_t *default_home = NULL;
1471static wchar_t env_home[MAXPATHLEN+1];
1472
1473void
1474Py_SetPythonHome(wchar_t *home)
1475{
1476 default_home = home;
1477}
1478
1479wchar_t *
1480Py_GetPythonHome(void)
1481{
1482 wchar_t *home = default_home;
1483 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1484 char* chome = Py_GETENV("PYTHONHOME");
1485 if (chome) {
1486 size_t size = Py_ARRAY_LENGTH(env_home);
1487 size_t r = mbstowcs(env_home, chome, size);
1488 if (r != (size_t)-1 && r < size)
1489 home = env_home;
1490 }
1491
1492 }
1493 return home;
1494}
1495
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001496/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001497
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498static _PyInitError
1499add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001500{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001501 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001502 m = PyImport_AddModule("__main__");
1503 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 return _Py_INIT_ERR("can't create __main__ module");
1505
Nick Coghland6009512014-11-20 21:39:37 +10001506 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001507 ann_dict = PyDict_New();
1508 if ((ann_dict == NULL) ||
1509 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001510 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001511 }
1512 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001513
Nick Coghland6009512014-11-20 21:39:37 +10001514 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1515 PyObject *bimod = PyImport_ImportModule("builtins");
1516 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001518 }
1519 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001520 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001521 }
1522 Py_DECREF(bimod);
1523 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001524
Nick Coghland6009512014-11-20 21:39:37 +10001525 /* Main is a little special - imp.is_builtin("__main__") will return
1526 * False, but BuiltinImporter is still the most appropriate initial
1527 * setting for its __loader__ attribute. A more suitable value will
1528 * be set if __main__ gets further initialized later in the startup
1529 * process.
1530 */
1531 loader = PyDict_GetItemString(d, "__loader__");
1532 if (loader == NULL || loader == Py_None) {
1533 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1534 "BuiltinImporter");
1535 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001536 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001537 }
1538 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001539 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001540 }
1541 Py_DECREF(loader);
1542 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001543 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001544}
1545
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001546static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001547initfsencoding(PyInterpreterState *interp)
1548{
1549 PyObject *codec;
1550
Steve Dowercc16be82016-09-08 10:35:16 -07001551#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001552 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001553 Py_FileSystemDefaultEncoding = "mbcs";
1554 Py_FileSystemDefaultEncodeErrors = "replace";
1555 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001556 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001557 Py_FileSystemDefaultEncoding = "utf-8";
1558 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1559 }
1560#else
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561 if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001562 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001563 if (Py_FileSystemDefaultEncoding == NULL) {
1564 return _Py_INIT_ERR("Unable to get the locale encoding");
1565 }
Nick Coghland6009512014-11-20 21:39:37 +10001566
1567 Py_HasFileSystemDefaultEncoding = 0;
1568 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001569 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001570 }
Steve Dowercc16be82016-09-08 10:35:16 -07001571#endif
Nick Coghland6009512014-11-20 21:39:37 +10001572
1573 /* the encoding is mbcs, utf-8 or ascii */
1574 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1575 if (!codec) {
1576 /* Such error can only occurs in critical situations: no more
1577 * memory, import a module of the standard library failed,
1578 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001579 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001580 }
1581 Py_DECREF(codec);
1582 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001584}
1585
1586/* Import the site module (not into __main__ though) */
1587
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001588static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001589initsite(void)
1590{
1591 PyObject *m;
1592 m = PyImport_ImportModule("site");
1593 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001594 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001595 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001596 Py_DECREF(m);
1597 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001598}
1599
Victor Stinner874dbe82015-09-04 17:29:57 +02001600/* Check if a file descriptor is valid or not.
1601 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1602static int
1603is_valid_fd(int fd)
1604{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001605#ifdef __APPLE__
1606 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1607 and the other side of the pipe is closed, dup(1) succeed, whereas
1608 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1609 such error. */
1610 struct stat st;
1611 return (fstat(fd, &st) == 0);
1612#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001613 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001614 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001615 return 0;
1616 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001617 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1618 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1619 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001620 fd2 = dup(fd);
1621 if (fd2 >= 0)
1622 close(fd2);
1623 _Py_END_SUPPRESS_IPH
1624 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001625#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001626}
1627
1628/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001629static PyObject*
1630create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001631 int fd, int write_mode, const char* name,
1632 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001633{
1634 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1635 const char* mode;
1636 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001637 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001638 int buffering, isatty;
1639 _Py_IDENTIFIER(open);
1640 _Py_IDENTIFIER(isatty);
1641 _Py_IDENTIFIER(TextIOWrapper);
1642 _Py_IDENTIFIER(mode);
1643
Victor Stinner874dbe82015-09-04 17:29:57 +02001644 if (!is_valid_fd(fd))
1645 Py_RETURN_NONE;
1646
Nick Coghland6009512014-11-20 21:39:37 +10001647 /* stdin is always opened in buffered mode, first because it shouldn't
1648 make a difference in common use cases, second because TextIOWrapper
1649 depends on the presence of a read1() method which only exists on
1650 buffered streams.
1651 */
1652 if (Py_UnbufferedStdioFlag && write_mode)
1653 buffering = 0;
1654 else
1655 buffering = -1;
1656 if (write_mode)
1657 mode = "wb";
1658 else
1659 mode = "rb";
1660 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1661 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001662 Py_None, Py_None, /* encoding, errors */
1663 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001664 if (buf == NULL)
1665 goto error;
1666
1667 if (buffering) {
1668 _Py_IDENTIFIER(raw);
1669 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1670 if (raw == NULL)
1671 goto error;
1672 }
1673 else {
1674 raw = buf;
1675 Py_INCREF(raw);
1676 }
1677
Steve Dower39294992016-08-30 21:22:36 -07001678#ifdef MS_WINDOWS
1679 /* Windows console IO is always UTF-8 encoded */
1680 if (PyWindowsConsoleIO_Check(raw))
1681 encoding = "utf-8";
1682#endif
1683
Nick Coghland6009512014-11-20 21:39:37 +10001684 text = PyUnicode_FromString(name);
1685 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1686 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001687 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001688 if (res == NULL)
1689 goto error;
1690 isatty = PyObject_IsTrue(res);
1691 Py_DECREF(res);
1692 if (isatty == -1)
1693 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001694 if (Py_UnbufferedStdioFlag)
1695 write_through = Py_True;
1696 else
1697 write_through = Py_False;
1698 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001699 line_buffering = Py_True;
1700 else
1701 line_buffering = Py_False;
1702
1703 Py_CLEAR(raw);
1704 Py_CLEAR(text);
1705
1706#ifdef MS_WINDOWS
1707 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1708 newlines to "\n".
1709 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1710 newline = NULL;
1711#else
1712 /* sys.stdin: split lines at "\n".
1713 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1714 newline = "\n";
1715#endif
1716
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001717 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001718 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001719 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001720 Py_CLEAR(buf);
1721 if (stream == NULL)
1722 goto error;
1723
1724 if (write_mode)
1725 mode = "w";
1726 else
1727 mode = "r";
1728 text = PyUnicode_FromString(mode);
1729 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1730 goto error;
1731 Py_CLEAR(text);
1732 return stream;
1733
1734error:
1735 Py_XDECREF(buf);
1736 Py_XDECREF(stream);
1737 Py_XDECREF(text);
1738 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001739
Victor Stinner874dbe82015-09-04 17:29:57 +02001740 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1741 /* Issue #24891: the file descriptor was closed after the first
1742 is_valid_fd() check was called. Ignore the OSError and set the
1743 stream to None. */
1744 PyErr_Clear();
1745 Py_RETURN_NONE;
1746 }
1747 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001748}
1749
1750/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001751static _PyInitError
1752init_sys_streams(void)
Nick Coghland6009512014-11-20 21:39:37 +10001753{
1754 PyObject *iomod = NULL, *wrapper;
1755 PyObject *bimod = NULL;
1756 PyObject *m;
1757 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001758 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001759 PyObject * encoding_attr;
1760 char *pythonioencoding = NULL, *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001761 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001762
1763 /* Hack to avoid a nasty recursion issue when Python is invoked
1764 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1765 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1766 goto error;
1767 }
1768 Py_DECREF(m);
1769
1770 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1771 goto error;
1772 }
1773 Py_DECREF(m);
1774
1775 if (!(bimod = PyImport_ImportModule("builtins"))) {
1776 goto error;
1777 }
1778
1779 if (!(iomod = PyImport_ImportModule("io"))) {
1780 goto error;
1781 }
1782 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1783 goto error;
1784 }
1785
1786 /* Set builtins.open */
1787 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1788 Py_DECREF(wrapper);
1789 goto error;
1790 }
1791 Py_DECREF(wrapper);
1792
1793 encoding = _Py_StandardStreamEncoding;
1794 errors = _Py_StandardStreamErrors;
1795 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001796 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1797 if (pythonioencoding) {
1798 char *err;
1799 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1800 if (pythonioencoding == NULL) {
1801 PyErr_NoMemory();
1802 goto error;
1803 }
1804 err = strchr(pythonioencoding, ':');
1805 if (err) {
1806 *err = '\0';
1807 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001808 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001809 errors = err;
1810 }
1811 }
1812 if (*pythonioencoding && !encoding) {
1813 encoding = pythonioencoding;
1814 }
1815 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001816 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001817 /* Choose the default error handler based on the current locale */
1818 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001819 }
Nick Coghland6009512014-11-20 21:39:37 +10001820 }
1821
1822 /* Set sys.stdin */
1823 fd = fileno(stdin);
1824 /* Under some conditions stdin, stdout and stderr may not be connected
1825 * and fileno() may point to an invalid file descriptor. For example
1826 * GUI apps don't have valid standard streams by default.
1827 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001828 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1829 if (std == NULL)
1830 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001831 PySys_SetObject("__stdin__", std);
1832 _PySys_SetObjectId(&PyId_stdin, std);
1833 Py_DECREF(std);
1834
1835 /* Set sys.stdout */
1836 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001837 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1838 if (std == NULL)
1839 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001840 PySys_SetObject("__stdout__", std);
1841 _PySys_SetObjectId(&PyId_stdout, std);
1842 Py_DECREF(std);
1843
1844#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1845 /* Set sys.stderr, replaces the preliminary stderr */
1846 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001847 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1848 if (std == NULL)
1849 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001850
1851 /* Same as hack above, pre-import stderr's codec to avoid recursion
1852 when import.c tries to write to stderr in verbose mode. */
1853 encoding_attr = PyObject_GetAttrString(std, "encoding");
1854 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001855 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001856 if (std_encoding != NULL) {
1857 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1858 Py_XDECREF(codec_info);
1859 }
1860 Py_DECREF(encoding_attr);
1861 }
1862 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1863
1864 if (PySys_SetObject("__stderr__", std) < 0) {
1865 Py_DECREF(std);
1866 goto error;
1867 }
1868 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1869 Py_DECREF(std);
1870 goto error;
1871 }
1872 Py_DECREF(std);
1873#endif
1874
Victor Stinnera7368ac2017-11-15 18:11:45 -08001875 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001876
Victor Stinnera7368ac2017-11-15 18:11:45 -08001877error:
1878 res = _Py_INIT_ERR("can't initialize sys standard streams");
1879
1880done:
Nick Coghland6009512014-11-20 21:39:37 +10001881 /* We won't need them anymore. */
1882 if (_Py_StandardStreamEncoding) {
1883 PyMem_RawFree(_Py_StandardStreamEncoding);
1884 _Py_StandardStreamEncoding = NULL;
1885 }
1886 if (_Py_StandardStreamErrors) {
1887 PyMem_RawFree(_Py_StandardStreamErrors);
1888 _Py_StandardStreamErrors = NULL;
1889 }
1890 PyMem_Free(pythonioencoding);
1891 Py_XDECREF(bimod);
1892 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001893 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001894}
1895
1896
Victor Stinner10dc4842015-03-24 12:01:30 +01001897static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001898_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001899{
Victor Stinner10dc4842015-03-24 12:01:30 +01001900 fputc('\n', stderr);
1901 fflush(stderr);
1902
1903 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001904 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001905}
Victor Stinner791da1c2016-03-14 16:53:12 +01001906
1907/* Print the current exception (if an exception is set) with its traceback,
1908 or display the current Python stack.
1909
1910 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1911 called on catastrophic cases.
1912
1913 Return 1 if the traceback was displayed, 0 otherwise. */
1914
1915static int
1916_Py_FatalError_PrintExc(int fd)
1917{
1918 PyObject *ferr, *res;
1919 PyObject *exception, *v, *tb;
1920 int has_tb;
1921
1922 if (PyThreadState_GET() == NULL) {
1923 /* The GIL is released: trying to acquire it is likely to deadlock,
1924 just give up. */
1925 return 0;
1926 }
1927
1928 PyErr_Fetch(&exception, &v, &tb);
1929 if (exception == NULL) {
1930 /* No current exception */
1931 return 0;
1932 }
1933
1934 ferr = _PySys_GetObjectId(&PyId_stderr);
1935 if (ferr == NULL || ferr == Py_None) {
1936 /* sys.stderr is not set yet or set to None,
1937 no need to try to display the exception */
1938 return 0;
1939 }
1940
1941 PyErr_NormalizeException(&exception, &v, &tb);
1942 if (tb == NULL) {
1943 tb = Py_None;
1944 Py_INCREF(tb);
1945 }
1946 PyException_SetTraceback(v, tb);
1947 if (exception == NULL) {
1948 /* PyErr_NormalizeException() failed */
1949 return 0;
1950 }
1951
1952 has_tb = (tb != Py_None);
1953 PyErr_Display(exception, v, tb);
1954 Py_XDECREF(exception);
1955 Py_XDECREF(v);
1956 Py_XDECREF(tb);
1957
1958 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001959 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001960 if (res == NULL)
1961 PyErr_Clear();
1962 else
1963 Py_DECREF(res);
1964
1965 return has_tb;
1966}
1967
Nick Coghland6009512014-11-20 21:39:37 +10001968/* Print fatal error message and abort */
1969
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001970#ifdef MS_WINDOWS
1971static void
1972fatal_output_debug(const char *msg)
1973{
1974 /* buffer of 256 bytes allocated on the stack */
1975 WCHAR buffer[256 / sizeof(WCHAR)];
1976 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1977 size_t msglen;
1978
1979 OutputDebugStringW(L"Fatal Python error: ");
1980
1981 msglen = strlen(msg);
1982 while (msglen) {
1983 size_t i;
1984
1985 if (buflen > msglen) {
1986 buflen = msglen;
1987 }
1988
1989 /* Convert the message to wchar_t. This uses a simple one-to-one
1990 conversion, assuming that the this error message actually uses
1991 ASCII only. If this ceases to be true, we will have to convert. */
1992 for (i=0; i < buflen; ++i) {
1993 buffer[i] = msg[i];
1994 }
1995 buffer[i] = L'\0';
1996 OutputDebugStringW(buffer);
1997
1998 msg += buflen;
1999 msglen -= buflen;
2000 }
2001 OutputDebugStringW(L"\n");
2002}
2003#endif
2004
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002005static void
2006fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002007{
2008 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002009 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002010
2011 if (reentrant) {
2012 /* Py_FatalError() caused a second fatal error.
2013 Example: flush_std_files() raises a recursion error. */
2014 goto exit;
2015 }
2016 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002017
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002018 fprintf(stderr, "Fatal Python error: ");
2019 if (prefix) {
2020 fputs(prefix, stderr);
2021 fputs(": ", stderr);
2022 }
2023 if (msg) {
2024 fputs(msg, stderr);
2025 }
2026 else {
2027 fprintf(stderr, "<message not set>");
2028 }
2029 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002030 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002031
Victor Stinnere0deff32015-03-24 13:46:18 +01002032 /* Print the exception (if an exception is set) with its traceback,
2033 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002034 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002035 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002036 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002037
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002038 /* The main purpose of faulthandler is to display the traceback.
2039 This function already did its best to display a traceback.
2040 Disable faulthandler to prevent writing a second traceback
2041 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002042 _PyFaulthandler_Fini();
2043
Victor Stinner791da1c2016-03-14 16:53:12 +01002044 /* Check if the current Python thread hold the GIL */
2045 if (PyThreadState_GET() != NULL) {
2046 /* Flush sys.stdout and sys.stderr */
2047 flush_std_files();
2048 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002049
Nick Coghland6009512014-11-20 21:39:37 +10002050#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002051 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002052#endif /* MS_WINDOWS */
2053
2054exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002055 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002056#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002057 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002058#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002059 abort();
2060 }
2061 else {
2062 exit(status);
2063 }
2064}
2065
2066void
2067Py_FatalError(const char *msg)
2068{
2069 fatal_error(NULL, msg, -1);
2070}
2071
2072void
2073_Py_FatalInitError(_PyInitError err)
2074{
2075 /* On "user" error: exit with status 1.
2076 For all other errors, call abort(). */
2077 int status = err.user_err ? 1 : -1;
2078 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002079}
2080
2081/* Clean up and exit */
2082
Victor Stinnerd7292b52016-06-17 12:29:00 +02002083# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002084
Nick Coghland6009512014-11-20 21:39:37 +10002085/* For the atexit module. */
2086void _Py_PyAtExit(void (*func)(void))
2087{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002088 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002089}
2090
2091static void
2092call_py_exitfuncs(void)
2093{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002094 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002095 return;
2096
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002097 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002098 PyErr_Clear();
2099}
2100
2101/* Wait until threading._shutdown completes, provided
2102 the threading module was imported in the first place.
2103 The shutdown routine will wait until all non-daemon
2104 "threading" threads have completed. */
2105static void
2106wait_for_thread_shutdown(void)
2107{
Nick Coghland6009512014-11-20 21:39:37 +10002108 _Py_IDENTIFIER(_shutdown);
2109 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002110 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002111 if (threading == NULL) {
2112 /* threading not imported */
2113 PyErr_Clear();
2114 return;
2115 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002116 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002117 if (result == NULL) {
2118 PyErr_WriteUnraisable(threading);
2119 }
2120 else {
2121 Py_DECREF(result);
2122 }
2123 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002124}
2125
2126#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002127int Py_AtExit(void (*func)(void))
2128{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002129 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002130 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002131 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002132 return 0;
2133}
2134
2135static void
2136call_ll_exitfuncs(void)
2137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002138 while (_PyRuntime.nexitfuncs > 0)
2139 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002140
2141 fflush(stdout);
2142 fflush(stderr);
2143}
2144
2145void
2146Py_Exit(int sts)
2147{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002148 if (Py_FinalizeEx() < 0) {
2149 sts = 120;
2150 }
Nick Coghland6009512014-11-20 21:39:37 +10002151
2152 exit(sts);
2153}
2154
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002155static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002156initsigs(void)
2157{
2158#ifdef SIGPIPE
2159 PyOS_setsig(SIGPIPE, SIG_IGN);
2160#endif
2161#ifdef SIGXFZ
2162 PyOS_setsig(SIGXFZ, SIG_IGN);
2163#endif
2164#ifdef SIGXFSZ
2165 PyOS_setsig(SIGXFSZ, SIG_IGN);
2166#endif
2167 PyOS_InitInterrupts(); /* May imply initsignal() */
2168 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002169 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002170 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002171 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002172}
2173
2174
2175/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2176 *
2177 * All of the code in this function must only use async-signal-safe functions,
2178 * listed at `man 7 signal` or
2179 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2180 */
2181void
2182_Py_RestoreSignals(void)
2183{
2184#ifdef SIGPIPE
2185 PyOS_setsig(SIGPIPE, SIG_DFL);
2186#endif
2187#ifdef SIGXFZ
2188 PyOS_setsig(SIGXFZ, SIG_DFL);
2189#endif
2190#ifdef SIGXFSZ
2191 PyOS_setsig(SIGXFSZ, SIG_DFL);
2192#endif
2193}
2194
2195
2196/*
2197 * The file descriptor fd is considered ``interactive'' if either
2198 * a) isatty(fd) is TRUE, or
2199 * b) the -i flag was given, and the filename associated with
2200 * the descriptor is NULL or "<stdin>" or "???".
2201 */
2202int
2203Py_FdIsInteractive(FILE *fp, const char *filename)
2204{
2205 if (isatty((int)fileno(fp)))
2206 return 1;
2207 if (!Py_InteractiveFlag)
2208 return 0;
2209 return (filename == NULL) ||
2210 (strcmp(filename, "<stdin>") == 0) ||
2211 (strcmp(filename, "???") == 0);
2212}
2213
2214
Nick Coghland6009512014-11-20 21:39:37 +10002215/* Wrappers around sigaction() or signal(). */
2216
2217PyOS_sighandler_t
2218PyOS_getsig(int sig)
2219{
2220#ifdef HAVE_SIGACTION
2221 struct sigaction context;
2222 if (sigaction(sig, NULL, &context) == -1)
2223 return SIG_ERR;
2224 return context.sa_handler;
2225#else
2226 PyOS_sighandler_t handler;
2227/* Special signal handling for the secure CRT in Visual Studio 2005 */
2228#if defined(_MSC_VER) && _MSC_VER >= 1400
2229 switch (sig) {
2230 /* Only these signals are valid */
2231 case SIGINT:
2232 case SIGILL:
2233 case SIGFPE:
2234 case SIGSEGV:
2235 case SIGTERM:
2236 case SIGBREAK:
2237 case SIGABRT:
2238 break;
2239 /* Don't call signal() with other values or it will assert */
2240 default:
2241 return SIG_ERR;
2242 }
2243#endif /* _MSC_VER && _MSC_VER >= 1400 */
2244 handler = signal(sig, SIG_IGN);
2245 if (handler != SIG_ERR)
2246 signal(sig, handler);
2247 return handler;
2248#endif
2249}
2250
2251/*
2252 * All of the code in this function must only use async-signal-safe functions,
2253 * listed at `man 7 signal` or
2254 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2255 */
2256PyOS_sighandler_t
2257PyOS_setsig(int sig, PyOS_sighandler_t handler)
2258{
2259#ifdef HAVE_SIGACTION
2260 /* Some code in Modules/signalmodule.c depends on sigaction() being
2261 * used here if HAVE_SIGACTION is defined. Fix that if this code
2262 * changes to invalidate that assumption.
2263 */
2264 struct sigaction context, ocontext;
2265 context.sa_handler = handler;
2266 sigemptyset(&context.sa_mask);
2267 context.sa_flags = 0;
2268 if (sigaction(sig, &context, &ocontext) == -1)
2269 return SIG_ERR;
2270 return ocontext.sa_handler;
2271#else
2272 PyOS_sighandler_t oldhandler;
2273 oldhandler = signal(sig, handler);
2274#ifdef HAVE_SIGINTERRUPT
2275 siginterrupt(sig, 1);
2276#endif
2277 return oldhandler;
2278#endif
2279}
2280
2281#ifdef __cplusplus
2282}
2283#endif