blob: 8d2ec4e91c3891e645963b857db791e3b4569ef8 [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
Victor Stinner0327bde2017-11-23 17:03:20 +01001480
1481_PyInitError
1482_Py_GetPythonHomeWithConfig(const _PyMainInterpreterConfig *config, wchar_t **homep)
Victor Stinner1f151112017-11-23 10:43:14 +01001483{
1484 /* Use a static buffer to avoid heap memory allocation failure.
1485 Py_GetPythonHome() doesn't allow to report error, and the caller
1486 doesn't release memory. */
1487 static wchar_t buffer[MAXPATHLEN+1];
1488
1489 if (default_home) {
Victor Stinner0327bde2017-11-23 17:03:20 +01001490 *homep = default_home;
1491 return _Py_INIT_OK();
Victor Stinner1f151112017-11-23 10:43:14 +01001492 }
1493
1494 if (config) {
Victor Stinner0327bde2017-11-23 17:03:20 +01001495 *homep = config->pythonhome;
1496 return _Py_INIT_OK();
Victor Stinner1f151112017-11-23 10:43:14 +01001497 }
1498
1499 char *home = Py_GETENV("PYTHONHOME");
1500 if (!home) {
Victor Stinner0327bde2017-11-23 17:03:20 +01001501 *homep = NULL;
1502 return _Py_INIT_OK();
Victor Stinner1f151112017-11-23 10:43:14 +01001503 }
1504
1505 size_t size = Py_ARRAY_LENGTH(buffer);
1506 size_t r = mbstowcs(buffer, home, size);
1507 if (r == (size_t)-1 || r >= size) {
1508 /* conversion failed or the static buffer is too small */
Victor Stinner0327bde2017-11-23 17:03:20 +01001509 *homep = NULL;
1510 return _Py_INIT_ERR("failed to decode PYTHONHOME environment variable");
Victor Stinner1f151112017-11-23 10:43:14 +01001511 }
1512
Victor Stinner0327bde2017-11-23 17:03:20 +01001513 *homep = buffer;
1514 return _Py_INIT_OK();
Victor Stinner1f151112017-11-23 10:43:14 +01001515}
1516
1517wchar_t *
Nick Coghland6009512014-11-20 21:39:37 +10001518Py_GetPythonHome(void)
1519{
Victor Stinner0327bde2017-11-23 17:03:20 +01001520 wchar_t *home;
1521 /* Ignore error */
1522 (void)_Py_GetPythonHomeWithConfig(NULL, &home);
1523 return home;
Nick Coghland6009512014-11-20 21:39:37 +10001524}
1525
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001526/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001527
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001528static _PyInitError
1529add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001530{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001531 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001532 m = PyImport_AddModule("__main__");
1533 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001534 return _Py_INIT_ERR("can't create __main__ module");
1535
Nick Coghland6009512014-11-20 21:39:37 +10001536 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001537 ann_dict = PyDict_New();
1538 if ((ann_dict == NULL) ||
1539 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001540 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001541 }
1542 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001543
Nick Coghland6009512014-11-20 21:39:37 +10001544 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1545 PyObject *bimod = PyImport_ImportModule("builtins");
1546 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001547 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001548 }
1549 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001551 }
1552 Py_DECREF(bimod);
1553 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001554
Nick Coghland6009512014-11-20 21:39:37 +10001555 /* Main is a little special - imp.is_builtin("__main__") will return
1556 * False, but BuiltinImporter is still the most appropriate initial
1557 * setting for its __loader__ attribute. A more suitable value will
1558 * be set if __main__ gets further initialized later in the startup
1559 * process.
1560 */
1561 loader = PyDict_GetItemString(d, "__loader__");
1562 if (loader == NULL || loader == Py_None) {
1563 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1564 "BuiltinImporter");
1565 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001566 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001567 }
1568 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001569 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001570 }
1571 Py_DECREF(loader);
1572 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001573 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001574}
1575
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001576static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001577initfsencoding(PyInterpreterState *interp)
1578{
1579 PyObject *codec;
1580
Steve Dowercc16be82016-09-08 10:35:16 -07001581#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001582 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001583 Py_FileSystemDefaultEncoding = "mbcs";
1584 Py_FileSystemDefaultEncodeErrors = "replace";
1585 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001586 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001587 Py_FileSystemDefaultEncoding = "utf-8";
1588 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1589 }
1590#else
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001591 if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001592 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001593 if (Py_FileSystemDefaultEncoding == NULL) {
1594 return _Py_INIT_ERR("Unable to get the locale encoding");
1595 }
Nick Coghland6009512014-11-20 21:39:37 +10001596
1597 Py_HasFileSystemDefaultEncoding = 0;
1598 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001599 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001600 }
Steve Dowercc16be82016-09-08 10:35:16 -07001601#endif
Nick Coghland6009512014-11-20 21:39:37 +10001602
1603 /* the encoding is mbcs, utf-8 or ascii */
1604 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1605 if (!codec) {
1606 /* Such error can only occurs in critical situations: no more
1607 * memory, import a module of the standard library failed,
1608 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001609 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001610 }
1611 Py_DECREF(codec);
1612 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001614}
1615
1616/* Import the site module (not into __main__ though) */
1617
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001618static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001619initsite(void)
1620{
1621 PyObject *m;
1622 m = PyImport_ImportModule("site");
1623 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001624 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001625 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626 Py_DECREF(m);
1627 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001628}
1629
Victor Stinner874dbe82015-09-04 17:29:57 +02001630/* Check if a file descriptor is valid or not.
1631 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1632static int
1633is_valid_fd(int fd)
1634{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001635#ifdef __APPLE__
1636 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1637 and the other side of the pipe is closed, dup(1) succeed, whereas
1638 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1639 such error. */
1640 struct stat st;
1641 return (fstat(fd, &st) == 0);
1642#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001643 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001644 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001645 return 0;
1646 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001647 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1648 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1649 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001650 fd2 = dup(fd);
1651 if (fd2 >= 0)
1652 close(fd2);
1653 _Py_END_SUPPRESS_IPH
1654 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001655#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001656}
1657
1658/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001659static PyObject*
1660create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001661 int fd, int write_mode, const char* name,
1662 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001663{
1664 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1665 const char* mode;
1666 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001667 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001668 int buffering, isatty;
1669 _Py_IDENTIFIER(open);
1670 _Py_IDENTIFIER(isatty);
1671 _Py_IDENTIFIER(TextIOWrapper);
1672 _Py_IDENTIFIER(mode);
1673
Victor Stinner874dbe82015-09-04 17:29:57 +02001674 if (!is_valid_fd(fd))
1675 Py_RETURN_NONE;
1676
Nick Coghland6009512014-11-20 21:39:37 +10001677 /* stdin is always opened in buffered mode, first because it shouldn't
1678 make a difference in common use cases, second because TextIOWrapper
1679 depends on the presence of a read1() method which only exists on
1680 buffered streams.
1681 */
1682 if (Py_UnbufferedStdioFlag && write_mode)
1683 buffering = 0;
1684 else
1685 buffering = -1;
1686 if (write_mode)
1687 mode = "wb";
1688 else
1689 mode = "rb";
1690 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1691 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001692 Py_None, Py_None, /* encoding, errors */
1693 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001694 if (buf == NULL)
1695 goto error;
1696
1697 if (buffering) {
1698 _Py_IDENTIFIER(raw);
1699 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1700 if (raw == NULL)
1701 goto error;
1702 }
1703 else {
1704 raw = buf;
1705 Py_INCREF(raw);
1706 }
1707
Steve Dower39294992016-08-30 21:22:36 -07001708#ifdef MS_WINDOWS
1709 /* Windows console IO is always UTF-8 encoded */
1710 if (PyWindowsConsoleIO_Check(raw))
1711 encoding = "utf-8";
1712#endif
1713
Nick Coghland6009512014-11-20 21:39:37 +10001714 text = PyUnicode_FromString(name);
1715 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1716 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001717 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001718 if (res == NULL)
1719 goto error;
1720 isatty = PyObject_IsTrue(res);
1721 Py_DECREF(res);
1722 if (isatty == -1)
1723 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001724 if (Py_UnbufferedStdioFlag)
1725 write_through = Py_True;
1726 else
1727 write_through = Py_False;
1728 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001729 line_buffering = Py_True;
1730 else
1731 line_buffering = Py_False;
1732
1733 Py_CLEAR(raw);
1734 Py_CLEAR(text);
1735
1736#ifdef MS_WINDOWS
1737 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1738 newlines to "\n".
1739 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1740 newline = NULL;
1741#else
1742 /* sys.stdin: split lines at "\n".
1743 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1744 newline = "\n";
1745#endif
1746
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001747 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001748 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001749 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001750 Py_CLEAR(buf);
1751 if (stream == NULL)
1752 goto error;
1753
1754 if (write_mode)
1755 mode = "w";
1756 else
1757 mode = "r";
1758 text = PyUnicode_FromString(mode);
1759 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1760 goto error;
1761 Py_CLEAR(text);
1762 return stream;
1763
1764error:
1765 Py_XDECREF(buf);
1766 Py_XDECREF(stream);
1767 Py_XDECREF(text);
1768 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001769
Victor Stinner874dbe82015-09-04 17:29:57 +02001770 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1771 /* Issue #24891: the file descriptor was closed after the first
1772 is_valid_fd() check was called. Ignore the OSError and set the
1773 stream to None. */
1774 PyErr_Clear();
1775 Py_RETURN_NONE;
1776 }
1777 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001778}
1779
1780/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001781static _PyInitError
1782init_sys_streams(void)
Nick Coghland6009512014-11-20 21:39:37 +10001783{
1784 PyObject *iomod = NULL, *wrapper;
1785 PyObject *bimod = NULL;
1786 PyObject *m;
1787 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001788 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001789 PyObject * encoding_attr;
1790 char *pythonioencoding = NULL, *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001791 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001792
1793 /* Hack to avoid a nasty recursion issue when Python is invoked
1794 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1795 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1796 goto error;
1797 }
1798 Py_DECREF(m);
1799
1800 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1801 goto error;
1802 }
1803 Py_DECREF(m);
1804
1805 if (!(bimod = PyImport_ImportModule("builtins"))) {
1806 goto error;
1807 }
1808
1809 if (!(iomod = PyImport_ImportModule("io"))) {
1810 goto error;
1811 }
1812 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1813 goto error;
1814 }
1815
1816 /* Set builtins.open */
1817 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1818 Py_DECREF(wrapper);
1819 goto error;
1820 }
1821 Py_DECREF(wrapper);
1822
1823 encoding = _Py_StandardStreamEncoding;
1824 errors = _Py_StandardStreamErrors;
1825 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001826 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1827 if (pythonioencoding) {
1828 char *err;
1829 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1830 if (pythonioencoding == NULL) {
1831 PyErr_NoMemory();
1832 goto error;
1833 }
1834 err = strchr(pythonioencoding, ':');
1835 if (err) {
1836 *err = '\0';
1837 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001838 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001839 errors = err;
1840 }
1841 }
1842 if (*pythonioencoding && !encoding) {
1843 encoding = pythonioencoding;
1844 }
1845 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001846 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001847 /* Choose the default error handler based on the current locale */
1848 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001849 }
Nick Coghland6009512014-11-20 21:39:37 +10001850 }
1851
1852 /* Set sys.stdin */
1853 fd = fileno(stdin);
1854 /* Under some conditions stdin, stdout and stderr may not be connected
1855 * and fileno() may point to an invalid file descriptor. For example
1856 * GUI apps don't have valid standard streams by default.
1857 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001858 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1859 if (std == NULL)
1860 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001861 PySys_SetObject("__stdin__", std);
1862 _PySys_SetObjectId(&PyId_stdin, std);
1863 Py_DECREF(std);
1864
1865 /* Set sys.stdout */
1866 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001867 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1868 if (std == NULL)
1869 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001870 PySys_SetObject("__stdout__", std);
1871 _PySys_SetObjectId(&PyId_stdout, std);
1872 Py_DECREF(std);
1873
1874#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1875 /* Set sys.stderr, replaces the preliminary stderr */
1876 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001877 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1878 if (std == NULL)
1879 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001880
1881 /* Same as hack above, pre-import stderr's codec to avoid recursion
1882 when import.c tries to write to stderr in verbose mode. */
1883 encoding_attr = PyObject_GetAttrString(std, "encoding");
1884 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001885 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001886 if (std_encoding != NULL) {
1887 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1888 Py_XDECREF(codec_info);
1889 }
1890 Py_DECREF(encoding_attr);
1891 }
1892 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1893
1894 if (PySys_SetObject("__stderr__", std) < 0) {
1895 Py_DECREF(std);
1896 goto error;
1897 }
1898 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1899 Py_DECREF(std);
1900 goto error;
1901 }
1902 Py_DECREF(std);
1903#endif
1904
Victor Stinnera7368ac2017-11-15 18:11:45 -08001905 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001906
Victor Stinnera7368ac2017-11-15 18:11:45 -08001907error:
1908 res = _Py_INIT_ERR("can't initialize sys standard streams");
1909
1910done:
Nick Coghland6009512014-11-20 21:39:37 +10001911 /* We won't need them anymore. */
1912 if (_Py_StandardStreamEncoding) {
1913 PyMem_RawFree(_Py_StandardStreamEncoding);
1914 _Py_StandardStreamEncoding = NULL;
1915 }
1916 if (_Py_StandardStreamErrors) {
1917 PyMem_RawFree(_Py_StandardStreamErrors);
1918 _Py_StandardStreamErrors = NULL;
1919 }
1920 PyMem_Free(pythonioencoding);
1921 Py_XDECREF(bimod);
1922 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001923 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001924}
1925
1926
Victor Stinner10dc4842015-03-24 12:01:30 +01001927static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001928_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001929{
Victor Stinner10dc4842015-03-24 12:01:30 +01001930 fputc('\n', stderr);
1931 fflush(stderr);
1932
1933 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001934 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001935}
Victor Stinner791da1c2016-03-14 16:53:12 +01001936
1937/* Print the current exception (if an exception is set) with its traceback,
1938 or display the current Python stack.
1939
1940 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1941 called on catastrophic cases.
1942
1943 Return 1 if the traceback was displayed, 0 otherwise. */
1944
1945static int
1946_Py_FatalError_PrintExc(int fd)
1947{
1948 PyObject *ferr, *res;
1949 PyObject *exception, *v, *tb;
1950 int has_tb;
1951
1952 if (PyThreadState_GET() == NULL) {
1953 /* The GIL is released: trying to acquire it is likely to deadlock,
1954 just give up. */
1955 return 0;
1956 }
1957
1958 PyErr_Fetch(&exception, &v, &tb);
1959 if (exception == NULL) {
1960 /* No current exception */
1961 return 0;
1962 }
1963
1964 ferr = _PySys_GetObjectId(&PyId_stderr);
1965 if (ferr == NULL || ferr == Py_None) {
1966 /* sys.stderr is not set yet or set to None,
1967 no need to try to display the exception */
1968 return 0;
1969 }
1970
1971 PyErr_NormalizeException(&exception, &v, &tb);
1972 if (tb == NULL) {
1973 tb = Py_None;
1974 Py_INCREF(tb);
1975 }
1976 PyException_SetTraceback(v, tb);
1977 if (exception == NULL) {
1978 /* PyErr_NormalizeException() failed */
1979 return 0;
1980 }
1981
1982 has_tb = (tb != Py_None);
1983 PyErr_Display(exception, v, tb);
1984 Py_XDECREF(exception);
1985 Py_XDECREF(v);
1986 Py_XDECREF(tb);
1987
1988 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001989 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001990 if (res == NULL)
1991 PyErr_Clear();
1992 else
1993 Py_DECREF(res);
1994
1995 return has_tb;
1996}
1997
Nick Coghland6009512014-11-20 21:39:37 +10001998/* Print fatal error message and abort */
1999
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002000#ifdef MS_WINDOWS
2001static void
2002fatal_output_debug(const char *msg)
2003{
2004 /* buffer of 256 bytes allocated on the stack */
2005 WCHAR buffer[256 / sizeof(WCHAR)];
2006 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2007 size_t msglen;
2008
2009 OutputDebugStringW(L"Fatal Python error: ");
2010
2011 msglen = strlen(msg);
2012 while (msglen) {
2013 size_t i;
2014
2015 if (buflen > msglen) {
2016 buflen = msglen;
2017 }
2018
2019 /* Convert the message to wchar_t. This uses a simple one-to-one
2020 conversion, assuming that the this error message actually uses
2021 ASCII only. If this ceases to be true, we will have to convert. */
2022 for (i=0; i < buflen; ++i) {
2023 buffer[i] = msg[i];
2024 }
2025 buffer[i] = L'\0';
2026 OutputDebugStringW(buffer);
2027
2028 msg += buflen;
2029 msglen -= buflen;
2030 }
2031 OutputDebugStringW(L"\n");
2032}
2033#endif
2034
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002035static void
2036fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002037{
2038 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002039 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002040
2041 if (reentrant) {
2042 /* Py_FatalError() caused a second fatal error.
2043 Example: flush_std_files() raises a recursion error. */
2044 goto exit;
2045 }
2046 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002047
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002048 fprintf(stderr, "Fatal Python error: ");
2049 if (prefix) {
2050 fputs(prefix, stderr);
2051 fputs(": ", stderr);
2052 }
2053 if (msg) {
2054 fputs(msg, stderr);
2055 }
2056 else {
2057 fprintf(stderr, "<message not set>");
2058 }
2059 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002060 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002061
Victor Stinnere0deff32015-03-24 13:46:18 +01002062 /* Print the exception (if an exception is set) with its traceback,
2063 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002064 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002065 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002066 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002067
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002068 /* The main purpose of faulthandler is to display the traceback.
2069 This function already did its best to display a traceback.
2070 Disable faulthandler to prevent writing a second traceback
2071 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002072 _PyFaulthandler_Fini();
2073
Victor Stinner791da1c2016-03-14 16:53:12 +01002074 /* Check if the current Python thread hold the GIL */
2075 if (PyThreadState_GET() != NULL) {
2076 /* Flush sys.stdout and sys.stderr */
2077 flush_std_files();
2078 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002079
Nick Coghland6009512014-11-20 21:39:37 +10002080#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002081 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002082#endif /* MS_WINDOWS */
2083
2084exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002085 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002086#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002087 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002088#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002089 abort();
2090 }
2091 else {
2092 exit(status);
2093 }
2094}
2095
2096void
2097Py_FatalError(const char *msg)
2098{
2099 fatal_error(NULL, msg, -1);
2100}
2101
2102void
2103_Py_FatalInitError(_PyInitError err)
2104{
2105 /* On "user" error: exit with status 1.
2106 For all other errors, call abort(). */
2107 int status = err.user_err ? 1 : -1;
2108 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002109}
2110
2111/* Clean up and exit */
2112
Victor Stinnerd7292b52016-06-17 12:29:00 +02002113# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002114
Nick Coghland6009512014-11-20 21:39:37 +10002115/* For the atexit module. */
2116void _Py_PyAtExit(void (*func)(void))
2117{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002118 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10002119}
2120
2121static void
2122call_py_exitfuncs(void)
2123{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002124 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002125 return;
2126
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002127 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10002128 PyErr_Clear();
2129}
2130
2131/* Wait until threading._shutdown completes, provided
2132 the threading module was imported in the first place.
2133 The shutdown routine will wait until all non-daemon
2134 "threading" threads have completed. */
2135static void
2136wait_for_thread_shutdown(void)
2137{
Nick Coghland6009512014-11-20 21:39:37 +10002138 _Py_IDENTIFIER(_shutdown);
2139 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002140 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002141 if (threading == NULL) {
2142 /* threading not imported */
2143 PyErr_Clear();
2144 return;
2145 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002146 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002147 if (result == NULL) {
2148 PyErr_WriteUnraisable(threading);
2149 }
2150 else {
2151 Py_DECREF(result);
2152 }
2153 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002154}
2155
2156#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002157int Py_AtExit(void (*func)(void))
2158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002159 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002160 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002161 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002162 return 0;
2163}
2164
2165static void
2166call_ll_exitfuncs(void)
2167{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002168 while (_PyRuntime.nexitfuncs > 0)
2169 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002170
2171 fflush(stdout);
2172 fflush(stderr);
2173}
2174
2175void
2176Py_Exit(int sts)
2177{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002178 if (Py_FinalizeEx() < 0) {
2179 sts = 120;
2180 }
Nick Coghland6009512014-11-20 21:39:37 +10002181
2182 exit(sts);
2183}
2184
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002185static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002186initsigs(void)
2187{
2188#ifdef SIGPIPE
2189 PyOS_setsig(SIGPIPE, SIG_IGN);
2190#endif
2191#ifdef SIGXFZ
2192 PyOS_setsig(SIGXFZ, SIG_IGN);
2193#endif
2194#ifdef SIGXFSZ
2195 PyOS_setsig(SIGXFSZ, SIG_IGN);
2196#endif
2197 PyOS_InitInterrupts(); /* May imply initsignal() */
2198 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002199 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002200 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002201 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002202}
2203
2204
2205/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2206 *
2207 * All of the code in this function must only use async-signal-safe functions,
2208 * listed at `man 7 signal` or
2209 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2210 */
2211void
2212_Py_RestoreSignals(void)
2213{
2214#ifdef SIGPIPE
2215 PyOS_setsig(SIGPIPE, SIG_DFL);
2216#endif
2217#ifdef SIGXFZ
2218 PyOS_setsig(SIGXFZ, SIG_DFL);
2219#endif
2220#ifdef SIGXFSZ
2221 PyOS_setsig(SIGXFSZ, SIG_DFL);
2222#endif
2223}
2224
2225
2226/*
2227 * The file descriptor fd is considered ``interactive'' if either
2228 * a) isatty(fd) is TRUE, or
2229 * b) the -i flag was given, and the filename associated with
2230 * the descriptor is NULL or "<stdin>" or "???".
2231 */
2232int
2233Py_FdIsInteractive(FILE *fp, const char *filename)
2234{
2235 if (isatty((int)fileno(fp)))
2236 return 1;
2237 if (!Py_InteractiveFlag)
2238 return 0;
2239 return (filename == NULL) ||
2240 (strcmp(filename, "<stdin>") == 0) ||
2241 (strcmp(filename, "???") == 0);
2242}
2243
2244
Nick Coghland6009512014-11-20 21:39:37 +10002245/* Wrappers around sigaction() or signal(). */
2246
2247PyOS_sighandler_t
2248PyOS_getsig(int sig)
2249{
2250#ifdef HAVE_SIGACTION
2251 struct sigaction context;
2252 if (sigaction(sig, NULL, &context) == -1)
2253 return SIG_ERR;
2254 return context.sa_handler;
2255#else
2256 PyOS_sighandler_t handler;
2257/* Special signal handling for the secure CRT in Visual Studio 2005 */
2258#if defined(_MSC_VER) && _MSC_VER >= 1400
2259 switch (sig) {
2260 /* Only these signals are valid */
2261 case SIGINT:
2262 case SIGILL:
2263 case SIGFPE:
2264 case SIGSEGV:
2265 case SIGTERM:
2266 case SIGBREAK:
2267 case SIGABRT:
2268 break;
2269 /* Don't call signal() with other values or it will assert */
2270 default:
2271 return SIG_ERR;
2272 }
2273#endif /* _MSC_VER && _MSC_VER >= 1400 */
2274 handler = signal(sig, SIG_IGN);
2275 if (handler != SIG_ERR)
2276 signal(sig, handler);
2277 return handler;
2278#endif
2279}
2280
2281/*
2282 * All of the code in this function must only use async-signal-safe functions,
2283 * listed at `man 7 signal` or
2284 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2285 */
2286PyOS_sighandler_t
2287PyOS_setsig(int sig, PyOS_sighandler_t handler)
2288{
2289#ifdef HAVE_SIGACTION
2290 /* Some code in Modules/signalmodule.c depends on sigaction() being
2291 * used here if HAVE_SIGACTION is defined. Fix that if this code
2292 * changes to invalidate that assumption.
2293 */
2294 struct sigaction context, ocontext;
2295 context.sa_handler = handler;
2296 sigemptyset(&context.sa_mask);
2297 context.sa_flags = 0;
2298 if (sigaction(sig, &context, &ocontext) == -1)
2299 return SIG_ERR;
2300 return ocontext.sa_handler;
2301#else
2302 PyOS_sighandler_t oldhandler;
2303 oldhandler = signal(sig, handler);
2304#ifdef HAVE_SIGINTERRUPT
2305 siginterrupt(sig, 1);
2306#endif
2307 return oldhandler;
2308#endif
2309}
2310
2311#ifdef __cplusplus
2312}
2313#endif