blob: 2af76d76d2b99ee34fbeee44deb1bc51fbe16378 [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 Stinner91106cd2017-12-13 12:29:09 +010057static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080058static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010059static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100060static void wait_for_thread_shutdown(void);
61static void call_ll_exitfuncs(void);
62extern int _PyUnicode_Init(void);
63extern int _PyStructSequence_Init(void);
64extern void _PyUnicode_Fini(void);
65extern int _PyLong_Init(void);
66extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080067extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100068extern void _PyFaulthandler_Fini(void);
69extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080070extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100071extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070072extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100073
Nick Coghland6009512014-11-20 21:39:37 +100074extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
75extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100076
Victor Stinnerf7e5b562017-11-15 15:48:08 -080077_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080_PyRuntime_Initialize(void)
81{
82 /* XXX We only initialize once in the process, which aligns with
83 the static initialization of the former globals now found in
84 _PyRuntime. However, _PyRuntime *should* be initialized with
85 every Py_Initialize() call, but doing so breaks the runtime.
86 This is because the runtime state is not properly finalized
87 currently. */
88 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080089 if (initialized) {
90 return _Py_INIT_OK();
91 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060092 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080093
94 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060095}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
Nick Coghland6009512014-11-20 21:39:37 +1000119int Py_FrozenFlag; /* Needed by getpath.c */
120int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800121int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000122int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
123int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
124int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
125int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700126#ifdef MS_WINDOWS
127int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700128int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700129#endif
Nick Coghland6009512014-11-20 21:39:37 +1000130
Nick Coghland6009512014-11-20 21:39:37 +1000131/* Hack to force loading of object files */
132int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
133 PyOS_mystrnicmp; /* Python/pystrcmp.o */
134
135/* PyModule_GetWarningsModule is no longer necessary as of 2.6
136since _warnings is builtin. This API should not be used. */
137PyObject *
138PyModule_GetWarningsModule(void)
139{
140 return PyImport_ImportModule("warnings");
141}
142
Eric Snowc7ec9982017-05-23 23:00:52 -0700143
Eric Snow1abcf672017-05-23 21:46:51 -0700144/* APIs to access the initialization flags
145 *
146 * Can be called prior to Py_Initialize.
147 */
Nick Coghland6009512014-11-20 21:39:37 +1000148
Eric Snow1abcf672017-05-23 21:46:51 -0700149int
150_Py_IsCoreInitialized(void)
151{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600152 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700153}
Nick Coghland6009512014-11-20 21:39:37 +1000154
155int
156Py_IsInitialized(void)
157{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600158 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000159}
160
161/* Helper to allow an embedding application to override the normal
162 * mechanism that attempts to figure out an appropriate IO encoding
163 */
164
165static char *_Py_StandardStreamEncoding = NULL;
166static char *_Py_StandardStreamErrors = NULL;
167
168int
169Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
170{
171 if (Py_IsInitialized()) {
172 /* This is too late to have any effect */
173 return -1;
174 }
175 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
176 * initialised yet.
177 *
178 * However, the raw memory allocators are initialised appropriately
179 * as C static variables, so _PyMem_RawStrdup is OK even though
180 * Py_Initialize hasn't been called yet.
181 */
182 if (encoding) {
183 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
184 if (!_Py_StandardStreamEncoding) {
185 return -2;
186 }
187 }
188 if (errors) {
189 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
190 if (!_Py_StandardStreamErrors) {
191 if (_Py_StandardStreamEncoding) {
192 PyMem_RawFree(_Py_StandardStreamEncoding);
193 }
194 return -3;
195 }
196 }
Steve Dower39294992016-08-30 21:22:36 -0700197#ifdef MS_WINDOWS
198 if (_Py_StandardStreamEncoding) {
199 /* Overriding the stream encoding implies legacy streams */
200 Py_LegacyWindowsStdioFlag = 1;
201 }
202#endif
Nick Coghland6009512014-11-20 21:39:37 +1000203 return 0;
204}
205
Nick Coghlan6ea41862017-06-11 13:16:15 +1000206
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000207/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
208 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000209 initializations fail, a fatal error is issued and the function does
210 not return. On return, the first thread and interpreter state have
211 been created.
212
213 Locking: you must hold the interpreter lock while calling this.
214 (If the lock has not yet been initialized, that's equivalent to
215 having the lock, but you cannot use multiple threads.)
216
217*/
218
Nick Coghland6009512014-11-20 21:39:37 +1000219static char*
220get_codec_name(const char *encoding)
221{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200222 const char *name_utf8;
223 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000224 PyObject *codec, *name = NULL;
225
226 codec = _PyCodec_Lookup(encoding);
227 if (!codec)
228 goto error;
229
230 name = _PyObject_GetAttrId(codec, &PyId_name);
231 Py_CLEAR(codec);
232 if (!name)
233 goto error;
234
Serhiy Storchaka06515832016-11-20 09:13:07 +0200235 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000236 if (name_utf8 == NULL)
237 goto error;
238 name_str = _PyMem_RawStrdup(name_utf8);
239 Py_DECREF(name);
240 if (name_str == NULL) {
241 PyErr_NoMemory();
242 return NULL;
243 }
244 return name_str;
245
246error:
247 Py_XDECREF(codec);
248 Py_XDECREF(name);
249 return NULL;
250}
251
252static char*
253get_locale_encoding(void)
254{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700255#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000256 char* codeset = nl_langinfo(CODESET);
257 if (!codeset || codeset[0] == '\0') {
258 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
259 return NULL;
260 }
261 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200262#elif defined(__ANDROID__)
263 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000264#else
265 PyErr_SetNone(PyExc_NotImplementedError);
266 return NULL;
267#endif
268}
269
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800270static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700271initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000272{
273 PyObject *importlib;
274 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000275 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800276 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000277
278 /* Import _importlib through its frozen version, _frozen_importlib. */
279 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800280 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000281 }
282 else if (Py_VerboseFlag) {
283 PySys_FormatStderr("import _frozen_importlib # frozen\n");
284 }
285 importlib = PyImport_AddModule("_frozen_importlib");
286 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800287 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000288 }
289 interp->importlib = importlib;
290 Py_INCREF(interp->importlib);
291
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300292 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
293 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800294 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300295 Py_INCREF(interp->import_func);
296
Victor Stinnercd6e6942015-09-18 09:11:57 +0200297 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000298 impmod = PyInit_imp();
299 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800300 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000301 }
302 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200303 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000304 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600305 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800306 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000307 }
308
Victor Stinnercd6e6942015-09-18 09:11:57 +0200309 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000310 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200311 if (value != NULL) {
312 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700313 value = PyObject_CallMethod(importlib,
314 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200315 }
Nick Coghland6009512014-11-20 21:39:37 +1000316 if (value == NULL) {
317 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800318 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000319 }
320 Py_DECREF(value);
321 Py_DECREF(impmod);
322
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800323 err = _PyImportZip_Init();
324 if (_Py_INIT_FAILED(err)) {
325 return err;
326 }
327
328 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000329}
330
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800331static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700332initexternalimport(PyInterpreterState *interp)
333{
334 PyObject *value;
335 value = PyObject_CallMethod(interp->importlib,
336 "_install_external_importers", "");
337 if (value == NULL) {
338 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800339 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700340 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200341 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800342 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700343}
Nick Coghland6009512014-11-20 21:39:37 +1000344
Nick Coghlan6ea41862017-06-11 13:16:15 +1000345/* Helper functions to better handle the legacy C locale
346 *
347 * The legacy C locale assumes ASCII as the default text encoding, which
348 * causes problems not only for the CPython runtime, but also other
349 * components like GNU readline.
350 *
351 * Accordingly, when the CLI detects it, it attempts to coerce it to a
352 * more capable UTF-8 based alternative as follows:
353 *
354 * if (_Py_LegacyLocaleDetected()) {
355 * _Py_CoerceLegacyLocale();
356 * }
357 *
358 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
359 *
360 * Locale coercion also impacts the default error handler for the standard
361 * streams: while the usual default is "strict", the default for the legacy
362 * C locale and for any of the coercion target locales is "surrogateescape".
363 */
364
365int
366_Py_LegacyLocaleDetected(void)
367{
368#ifndef MS_WINDOWS
369 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000370 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
371 * the POSIX locale as a simple alias for the C locale, so
372 * we may also want to check for that explicitly.
373 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000374 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
375 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
376#else
377 /* Windows uses code pages instead of locales, so no locale is legacy */
378 return 0;
379#endif
380}
381
Nick Coghlaneb817952017-06-18 12:29:42 +1000382static const char *_C_LOCALE_WARNING =
383 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
384 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
385 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
386 "locales is recommended.\n";
387
Nick Coghlaneb817952017-06-18 12:29:42 +1000388static void
Victor Stinner94540602017-12-16 04:54:22 +0100389_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000390{
Victor Stinner94540602017-12-16 04:54:22 +0100391 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000392 if (_Py_LegacyLocaleDetected()) {
393 fprintf(stderr, "%s", _C_LOCALE_WARNING);
394 }
395 }
396}
397
Nick Coghlan6ea41862017-06-11 13:16:15 +1000398typedef struct _CandidateLocale {
399 const char *locale_name; /* The locale to try as a coercion target */
400} _LocaleCoercionTarget;
401
402static _LocaleCoercionTarget _TARGET_LOCALES[] = {
403 {"C.UTF-8"},
404 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000405 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000406 {NULL}
407};
408
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200409static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000410get_default_standard_stream_error_handler(void)
411{
412 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
413 if (ctype_loc != NULL) {
414 /* "surrogateescape" is the default in the legacy C locale */
415 if (strcmp(ctype_loc, "C") == 0) {
416 return "surrogateescape";
417 }
418
419#ifdef PY_COERCE_C_LOCALE
420 /* "surrogateescape" is the default in locale coercion target locales */
421 const _LocaleCoercionTarget *target = NULL;
422 for (target = _TARGET_LOCALES; target->locale_name; target++) {
423 if (strcmp(ctype_loc, target->locale_name) == 0) {
424 return "surrogateescape";
425 }
426 }
427#endif
428 }
429
430 /* Otherwise return NULL to request the typical default error handler */
431 return NULL;
432}
433
434#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100435static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000436 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
437 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
438
439static void
Victor Stinner94540602017-12-16 04:54:22 +0100440_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000441{
442 const char *newloc = target->locale_name;
443
444 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100445 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000446
447 /* Set the relevant locale environment variable */
448 if (setenv("LC_CTYPE", newloc, 1)) {
449 fprintf(stderr,
450 "Error setting LC_CTYPE, skipping C locale coercion\n");
451 return;
452 }
Victor Stinner94540602017-12-16 04:54:22 +0100453 if (config->coerce_c_locale_warn) {
454 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000455 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000456
457 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100458 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000459}
460#endif
461
462void
Victor Stinner94540602017-12-16 04:54:22 +0100463_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000464{
465#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100466 const char *locale_override = getenv("LC_ALL");
467 if (locale_override == NULL || *locale_override == '\0') {
468 /* LC_ALL is also not set (or is set to an empty string) */
469 const _LocaleCoercionTarget *target = NULL;
470 for (target = _TARGET_LOCALES; target->locale_name; target++) {
471 const char *new_locale = setlocale(LC_CTYPE,
472 target->locale_name);
473 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100474#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100475defined(HAVE_LANGINFO_H) && defined(CODESET)
476 /* Also ensure that nl_langinfo works in this locale */
477 char *codeset = nl_langinfo(CODESET);
478 if (!codeset || *codeset == '\0') {
479 /* CODESET is not set or empty, so skip coercion */
480 new_locale = NULL;
481 _Py_SetLocaleFromEnv(LC_CTYPE);
482 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000483 }
Victor Stinner94540602017-12-16 04:54:22 +0100484#endif
485 /* Successfully configured locale, so make it the default */
486 _coerce_default_locale_settings(config, target);
487 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000488 }
489 }
490 }
491 /* No C locale warning here, as Py_Initialize will emit one later */
492#endif
493}
494
xdegaye1588be62017-11-12 12:45:59 +0100495/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
496 * isolate the idiosyncrasies of different libc implementations. It reads the
497 * appropriate environment variable and uses its value to select the locale for
498 * 'category'. */
499char *
500_Py_SetLocaleFromEnv(int category)
501{
502#ifdef __ANDROID__
503 const char *locale;
504 const char **pvar;
505#ifdef PY_COERCE_C_LOCALE
506 const char *coerce_c_locale;
507#endif
508 const char *utf8_locale = "C.UTF-8";
509 const char *env_var_set[] = {
510 "LC_ALL",
511 "LC_CTYPE",
512 "LANG",
513 NULL,
514 };
515
516 /* Android setlocale(category, "") doesn't check the environment variables
517 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
518 * check the environment variables listed in env_var_set. */
519 for (pvar=env_var_set; *pvar; pvar++) {
520 locale = getenv(*pvar);
521 if (locale != NULL && *locale != '\0') {
522 if (strcmp(locale, utf8_locale) == 0 ||
523 strcmp(locale, "en_US.UTF-8") == 0) {
524 return setlocale(category, utf8_locale);
525 }
526 return setlocale(category, "C");
527 }
528 }
529
530 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
531 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
532 * Quote from POSIX section "8.2 Internationalization Variables":
533 * "4. If the LANG environment variable is not set or is set to the empty
534 * string, the implementation-defined default locale shall be used." */
535
536#ifdef PY_COERCE_C_LOCALE
537 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
538 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
539 /* Some other ported code may check the environment variables (e.g. in
540 * extension modules), so we make sure that they match the locale
541 * configuration */
542 if (setenv("LC_CTYPE", utf8_locale, 1)) {
543 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
544 "environment variable to %s\n", utf8_locale);
545 }
546 }
547#endif
548 return setlocale(category, utf8_locale);
549#else /* __ANDROID__ */
550 return setlocale(category, "");
551#endif /* __ANDROID__ */
552}
553
Nick Coghlan6ea41862017-06-11 13:16:15 +1000554
Eric Snow1abcf672017-05-23 21:46:51 -0700555/* Global initializations. Can be undone by Py_Finalize(). Don't
556 call this twice without an intervening Py_Finalize() call.
557
558 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
559 must have a corresponding call to Py_Finalize.
560
561 Locking: you must hold the interpreter lock while calling these APIs.
562 (If the lock has not yet been initialized, that's equivalent to
563 having the lock, but you cannot use multiple threads.)
564
565*/
566
567/* Begin interpreter initialization
568 *
569 * On return, the first thread and interpreter state have been created,
570 * but the compiler, signal handling, multithreading and
571 * multiple interpreter support, and codec infrastructure are not yet
572 * available.
573 *
574 * The import system will support builtin and frozen modules only.
575 * The only supported io is writing to sys.stderr
576 *
577 * If any operation invoked by this function fails, a fatal error is
578 * issued and the function does not return.
579 *
580 * Any code invoked from this function should *not* assume it has access
581 * to the Python C API (unless the API is explicitly listed as being
582 * safe to call without calling Py_Initialize first)
583 */
584
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800585_PyInitError
Victor Stinnerda273412017-12-15 01:46:02 +0100586_Py_InitializeCore(const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000587{
Victor Stinnerda273412017-12-15 01:46:02 +0100588 assert(core_config != NULL);
589
Nick Coghland6009512014-11-20 21:39:37 +1000590 PyInterpreterState *interp;
591 PyThreadState *tstate;
592 PyObject *bimod, *sysmod, *pstderr;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800593 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000594
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800595 err = _PyRuntime_Initialize();
596 if (_Py_INIT_FAILED(err)) {
597 return err;
598 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600599
Victor Stinnerda273412017-12-15 01:46:02 +0100600 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
Victor Stinner5d39e042017-11-29 17:20:38 +0100601 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800602 }
603
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600604 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800605 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700606 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600607 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800608 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700609 }
610
611 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
612 * threads behave a little more gracefully at interpreter shutdown.
613 * We clobber it here so the new interpreter can start with a clean
614 * slate.
615 *
616 * However, this may still lead to misbehaviour if there are daemon
617 * threads still hanging around from a previous Py_Initialize/Finalize
618 * pair :(
619 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600620 _PyRuntime.finalizing = NULL;
621
Nick Coghlan6ea41862017-06-11 13:16:15 +1000622#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000623 /* Set up the LC_CTYPE locale, so we can obtain
624 the locale's charset without having to switch
625 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100626 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner94540602017-12-16 04:54:22 +0100627 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000628#endif
Nick Coghland6009512014-11-20 21:39:37 +1000629
Victor Stinnerda273412017-12-15 01:46:02 +0100630 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800631 if (_Py_INIT_FAILED(err)) {
632 return err;
633 }
634
Victor Stinnerda273412017-12-15 01:46:02 +0100635 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700636 /* Random or non-zero hash seed */
637 Py_HashRandomizationFlag = 1;
638 }
Nick Coghland6009512014-11-20 21:39:37 +1000639
Victor Stinnera7368ac2017-11-15 18:11:45 -0800640 err = _PyInterpreterState_Enable(&_PyRuntime);
641 if (_Py_INIT_FAILED(err)) {
642 return err;
643 }
644
Nick Coghland6009512014-11-20 21:39:37 +1000645 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100646 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800647 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100648 }
649
650 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
651 return _Py_INIT_ERR("failed to copy core config");
652 }
Nick Coghland6009512014-11-20 21:39:37 +1000653
654 tstate = PyThreadState_New(interp);
655 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800656 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000657 (void) PyThreadState_Swap(tstate);
658
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000659 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000660 destroying the GIL might fail when it is being referenced from
661 another running thread (see issue #9901).
662 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000663 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000664 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000665 /* Auto-thread-state API */
666 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000667
668 _Py_ReadyTypes();
669
670 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800671 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000672
673 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800674 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000675
676 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800677 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000678
679 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800680 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000681
Eric Snowd393c1b2017-09-14 12:18:12 -0600682 PyObject *modules = PyDict_New();
683 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800684 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600685 interp->modules = modules;
686
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800687 err = _PySys_BeginInit(&sysmod);
688 if (_Py_INIT_FAILED(err)) {
689 return err;
690 }
691
Eric Snowd393c1b2017-09-14 12:18:12 -0600692 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800693 if (interp->sysdict == NULL) {
694 return _Py_INIT_ERR("can't initialize sys dict");
695 }
696
Eric Snowd393c1b2017-09-14 12:18:12 -0600697 Py_INCREF(interp->sysdict);
698 PyDict_SetItemString(interp->sysdict, "modules", modules);
699 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000700
701 /* Init Unicode implementation; relies on the codec registry */
702 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800703 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700704
Nick Coghland6009512014-11-20 21:39:37 +1000705 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800706 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000707
708 bimod = _PyBuiltin_Init();
709 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800710 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600711 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000712 interp->builtins = PyModule_GetDict(bimod);
713 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800714 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000715 Py_INCREF(interp->builtins);
716
717 /* initialize builtin exceptions */
718 _PyExc_Init(bimod);
719
Nick Coghland6009512014-11-20 21:39:37 +1000720 /* Set up a preliminary stderr printer until we have enough
721 infrastructure for the io module in place. */
722 pstderr = PyFile_NewStdPrinter(fileno(stderr));
723 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800724 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000725 _PySys_SetObjectId(&PyId_stderr, pstderr);
726 PySys_SetObject("__stderr__", pstderr);
727 Py_DECREF(pstderr);
728
Victor Stinner672b6ba2017-12-06 17:25:50 +0100729 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800730 if (_Py_INIT_FAILED(err)) {
731 return err;
732 }
Nick Coghland6009512014-11-20 21:39:37 +1000733
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800734 err = _PyImportHooks_Init();
735 if (_Py_INIT_FAILED(err)) {
736 return err;
737 }
Nick Coghland6009512014-11-20 21:39:37 +1000738
739 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100740 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100741 return _Py_INIT_ERR("can't initialize warnings");
742 }
Nick Coghland6009512014-11-20 21:39:37 +1000743
Eric Snow1abcf672017-05-23 21:46:51 -0700744 /* This call sets up builtin and frozen import support */
745 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800746 err = initimport(interp, sysmod);
747 if (_Py_INIT_FAILED(err)) {
748 return err;
749 }
Eric Snow1abcf672017-05-23 21:46:51 -0700750 }
751
752 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600753 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800754 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700755}
756
Eric Snowc7ec9982017-05-23 23:00:52 -0700757/* Update interpreter state based on supplied configuration settings
758 *
759 * After calling this function, most of the restrictions on the interpreter
760 * are lifted. The only remaining incomplete settings are those related
761 * to the main module (sys.argv[0], __main__ metadata)
762 *
763 * Calling this when the interpreter is not initializing, is already
764 * initialized or without a valid current thread state is a fatal error.
765 * Other errors should be reported as normal Python exceptions with a
766 * non-zero return code.
767 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800768_PyInitError
769_Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700770{
771 PyInterpreterState *interp;
772 PyThreadState *tstate;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800773 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700774
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600775 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800776 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700777 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600778 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800779 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700780 }
781
Eric Snow1abcf672017-05-23 21:46:51 -0700782 /* Get current thread state and interpreter pointer */
783 tstate = PyThreadState_GET();
784 if (!tstate)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800785 return _Py_INIT_ERR("failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700786 interp = tstate->interp;
787 if (!interp)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800788 return _Py_INIT_ERR("failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700789
790 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100791 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
792 return _Py_INIT_ERR("failed to copy main interpreter config");
793 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700794
Eric Snow1abcf672017-05-23 21:46:51 -0700795 if (interp->core_config._disable_importlib) {
796 /* Special mode for freeze_importlib: run with no import system
797 *
798 * This means anything which needs support from extension modules
799 * or pure Python code in the standard library won't work.
800 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600801 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800802 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700803 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100804
Victor Stinner33c377e2017-12-05 15:12:41 +0100805 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800806 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100807 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200808
Victor Stinner41264f12017-12-15 02:05:29 +0100809 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800810 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100811 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800812
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800813 err = initexternalimport(interp);
814 if (_Py_INIT_FAILED(err)) {
815 return err;
816 }
Nick Coghland6009512014-11-20 21:39:37 +1000817
818 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800819 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800820 if (_Py_INIT_FAILED(err)) {
821 return err;
822 }
Nick Coghland6009512014-11-20 21:39:37 +1000823
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800824 err = initfsencoding(interp);
825 if (_Py_INIT_FAILED(err)) {
826 return err;
827 }
Nick Coghland6009512014-11-20 21:39:37 +1000828
Victor Stinner1f151112017-11-23 10:43:14 +0100829 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800830 err = initsigs(); /* Signal handling stuff, including initintr() */
831 if (_Py_INIT_FAILED(err)) {
832 return err;
833 }
834 }
Nick Coghland6009512014-11-20 21:39:37 +1000835
Victor Stinnera7368ac2017-11-15 18:11:45 -0800836 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800837 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000838
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800839 err = add_main_module(interp);
840 if (_Py_INIT_FAILED(err)) {
841 return err;
842 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800843
Victor Stinner91106cd2017-12-13 12:29:09 +0100844 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800845 if (_Py_INIT_FAILED(err)) {
846 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800847 }
Nick Coghland6009512014-11-20 21:39:37 +1000848
849 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100850 if (interp->config.warnoptions != NULL &&
851 PyList_Size(interp->config.warnoptions) > 0)
852 {
Nick Coghland6009512014-11-20 21:39:37 +1000853 PyObject *warnings_module = PyImport_ImportModule("warnings");
854 if (warnings_module == NULL) {
855 fprintf(stderr, "'import warnings' failed; traceback:\n");
856 PyErr_Print();
857 }
858 Py_XDECREF(warnings_module);
859 }
860
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600861 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700862
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800863 if (!Py_NoSiteFlag) {
864 err = initsite(); /* Module site */
865 if (_Py_INIT_FAILED(err)) {
866 return err;
867 }
868 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800869 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000870}
871
Eric Snowc7ec9982017-05-23 23:00:52 -0700872#undef _INIT_DEBUG_PRINT
873
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800874_PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700875_Py_InitializeEx_Private(int install_sigs, int install_importlib)
876{
Victor Stinner9cfc0022017-12-20 19:36:46 +0100877 _PyCoreConfig config = _PyCoreConfig_INIT;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800878 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700879
Victor Stinner9cfc0022017-12-20 19:36:46 +0100880 config.ignore_environment = Py_IgnoreEnvironmentFlag;
881 config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700882 config.install_signal_handlers = install_sigs;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800883
Victor Stinner9cfc0022017-12-20 19:36:46 +0100884 err = _PyCoreConfig_Read(&config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800885 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100886 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800887 }
888
Victor Stinner9cfc0022017-12-20 19:36:46 +0100889 err = _Py_InitializeCore(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100890 if (_Py_INIT_FAILED(err)) {
891 goto done;
892 }
893
Victor Stinner9cfc0022017-12-20 19:36:46 +0100894 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
895 err = _PyMainInterpreterConfig_Read(&main_config, &config);
896 if (!_Py_INIT_FAILED(err)) {
897 err = _Py_InitializeMainInterpreter(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800898 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100899 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900 if (_Py_INIT_FAILED(err)) {
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100901 goto done;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800902 }
903
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100904 err = _Py_INIT_OK();
905
906done:
Victor Stinner9cfc0022017-12-20 19:36:46 +0100907 _PyCoreConfig_Clear(&config);
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100908 return err;
Eric Snow1abcf672017-05-23 21:46:51 -0700909}
910
911
912void
Nick Coghland6009512014-11-20 21:39:37 +1000913Py_InitializeEx(int install_sigs)
914{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800915 _PyInitError err = _Py_InitializeEx_Private(install_sigs, 1);
916 if (_Py_INIT_FAILED(err)) {
917 _Py_FatalInitError(err);
918 }
Nick Coghland6009512014-11-20 21:39:37 +1000919}
920
921void
922Py_Initialize(void)
923{
924 Py_InitializeEx(1);
925}
926
927
928#ifdef COUNT_ALLOCS
929extern void dump_counts(FILE*);
930#endif
931
932/* Flush stdout and stderr */
933
934static int
935file_is_closed(PyObject *fobj)
936{
937 int r;
938 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
939 if (tmp == NULL) {
940 PyErr_Clear();
941 return 0;
942 }
943 r = PyObject_IsTrue(tmp);
944 Py_DECREF(tmp);
945 if (r < 0)
946 PyErr_Clear();
947 return r > 0;
948}
949
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000950static int
Nick Coghland6009512014-11-20 21:39:37 +1000951flush_std_files(void)
952{
953 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
954 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
955 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000956 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000957
958 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700959 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000960 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000961 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000962 status = -1;
963 }
Nick Coghland6009512014-11-20 21:39:37 +1000964 else
965 Py_DECREF(tmp);
966 }
967
968 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700969 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000970 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000971 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000972 status = -1;
973 }
Nick Coghland6009512014-11-20 21:39:37 +1000974 else
975 Py_DECREF(tmp);
976 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000977
978 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000979}
980
981/* Undo the effect of Py_Initialize().
982
983 Beware: if multiple interpreter and/or thread states exist, these
984 are not wiped out; only the current thread and interpreter state
985 are deleted. But since everything else is deleted, those other
986 interpreter and thread states should no longer be used.
987
988 (XXX We should do better, e.g. wipe out all interpreters and
989 threads.)
990
991 Locking: as above.
992
993*/
994
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000995int
996Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000997{
998 PyInterpreterState *interp;
999 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001000 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001001
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001002 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001003 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001004
1005 wait_for_thread_shutdown();
1006
Marcel Plch776407f2017-12-20 11:17:58 +01001007 /* Get current thread state and interpreter pointer */
1008 tstate = PyThreadState_GET();
1009 interp = tstate->interp;
1010
Nick Coghland6009512014-11-20 21:39:37 +10001011 /* The interpreter is still entirely intact at this point, and the
1012 * exit funcs may be relying on that. In particular, if some thread
1013 * or exit func is still waiting to do an import, the import machinery
1014 * expects Py_IsInitialized() to return true. So don't say the
1015 * interpreter is uninitialized until after the exit funcs have run.
1016 * Note that Threading.py uses an exit func to do a join on all the
1017 * threads created thru it, so this also protects pending imports in
1018 * the threads created via Threading.
1019 */
Nick Coghland6009512014-11-20 21:39:37 +10001020
Marcel Plch776407f2017-12-20 11:17:58 +01001021 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001022
Victor Stinnerda273412017-12-15 01:46:02 +01001023 /* Copy the core config, PyInterpreterState_Delete() free
1024 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001025#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001026 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001027#endif
1028#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001029 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001030#endif
1031#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001032 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001033#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001034
Nick Coghland6009512014-11-20 21:39:37 +10001035 /* Remaining threads (e.g. daemon threads) will automatically exit
1036 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001037 _PyRuntime.finalizing = tstate;
1038 _PyRuntime.initialized = 0;
1039 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001040
Victor Stinnere0deff32015-03-24 13:46:18 +01001041 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001042 if (flush_std_files() < 0) {
1043 status = -1;
1044 }
Nick Coghland6009512014-11-20 21:39:37 +10001045
1046 /* Disable signal handling */
1047 PyOS_FiniInterrupts();
1048
1049 /* Collect garbage. This may call finalizers; it's nice to call these
1050 * before all modules are destroyed.
1051 * XXX If a __del__ or weakref callback is triggered here, and tries to
1052 * XXX import a module, bad things can happen, because Python no
1053 * XXX longer believes it's initialized.
1054 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1055 * XXX is easy to provoke that way. I've also seen, e.g.,
1056 * XXX Exception exceptions.ImportError: 'No module named sha'
1057 * XXX in <function callback at 0x008F5718> ignored
1058 * XXX but I'm unclear on exactly how that one happens. In any case,
1059 * XXX I haven't seen a real-life report of either of these.
1060 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001061 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001062#ifdef COUNT_ALLOCS
1063 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1064 each collection might release some types from the type
1065 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001066 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001067 /* nothing */;
1068#endif
Eric Snowdae02762017-09-14 00:35:58 -07001069
Nick Coghland6009512014-11-20 21:39:37 +10001070 /* Destroy all modules */
1071 PyImport_Cleanup();
1072
Victor Stinnere0deff32015-03-24 13:46:18 +01001073 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001074 if (flush_std_files() < 0) {
1075 status = -1;
1076 }
Nick Coghland6009512014-11-20 21:39:37 +10001077
1078 /* Collect final garbage. This disposes of cycles created by
1079 * class definitions, for example.
1080 * XXX This is disabled because it caused too many problems. If
1081 * XXX a __del__ or weakref callback triggers here, Python code has
1082 * XXX a hard time running, because even the sys module has been
1083 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1084 * XXX One symptom is a sequence of information-free messages
1085 * XXX coming from threads (if a __del__ or callback is invoked,
1086 * XXX other threads can execute too, and any exception they encounter
1087 * XXX triggers a comedy of errors as subsystem after subsystem
1088 * XXX fails to find what it *expects* to find in sys to help report
1089 * XXX the exception and consequent unexpected failures). I've also
1090 * XXX seen segfaults then, after adding print statements to the
1091 * XXX Python code getting called.
1092 */
1093#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001094 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001095#endif
1096
1097 /* Disable tracemalloc after all Python objects have been destroyed,
1098 so it is possible to use tracemalloc in objects destructor. */
1099 _PyTraceMalloc_Fini();
1100
1101 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1102 _PyImport_Fini();
1103
1104 /* Cleanup typeobject.c's internal caches. */
1105 _PyType_Fini();
1106
1107 /* unload faulthandler module */
1108 _PyFaulthandler_Fini();
1109
1110 /* Debugging stuff */
1111#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001112 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001113#endif
1114 /* dump hash stats */
1115 _PyHash_Fini();
1116
Eric Snowdae02762017-09-14 00:35:58 -07001117#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001118 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001119 _PyDebug_PrintTotalRefs();
1120 }
Eric Snowdae02762017-09-14 00:35:58 -07001121#endif
Nick Coghland6009512014-11-20 21:39:37 +10001122
1123#ifdef Py_TRACE_REFS
1124 /* Display all objects still alive -- this can invoke arbitrary
1125 * __repr__ overrides, so requires a mostly-intact interpreter.
1126 * Alas, a lot of stuff may still be alive now that will be cleaned
1127 * up later.
1128 */
Victor Stinnerda273412017-12-15 01:46:02 +01001129 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001130 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001131 }
Nick Coghland6009512014-11-20 21:39:37 +10001132#endif /* Py_TRACE_REFS */
1133
1134 /* Clear interpreter state and all thread states. */
1135 PyInterpreterState_Clear(interp);
1136
1137 /* Now we decref the exception classes. After this point nothing
1138 can raise an exception. That's okay, because each Fini() method
1139 below has been checked to make sure no exceptions are ever
1140 raised.
1141 */
1142
1143 _PyExc_Fini();
1144
1145 /* Sundry finalizers */
1146 PyMethod_Fini();
1147 PyFrame_Fini();
1148 PyCFunction_Fini();
1149 PyTuple_Fini();
1150 PyList_Fini();
1151 PySet_Fini();
1152 PyBytes_Fini();
1153 PyByteArray_Fini();
1154 PyLong_Fini();
1155 PyFloat_Fini();
1156 PyDict_Fini();
1157 PySlice_Fini();
1158 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001159 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001160 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001161 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001162
1163 /* Cleanup Unicode implementation */
1164 _PyUnicode_Fini();
1165
1166 /* reset file system default encoding */
1167 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1168 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1169 Py_FileSystemDefaultEncoding = NULL;
1170 }
1171
1172 /* XXX Still allocated:
1173 - various static ad-hoc pointers to interned strings
1174 - int and float free list blocks
1175 - whatever various modules and libraries allocate
1176 */
1177
1178 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1179
1180 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001181 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001182
1183 /* Delete current thread. After this, many C API calls become crashy. */
1184 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001185
Nick Coghland6009512014-11-20 21:39:37 +10001186 PyInterpreterState_Delete(interp);
1187
1188#ifdef Py_TRACE_REFS
1189 /* Display addresses (& refcnts) of all objects still alive.
1190 * An address can be used to find the repr of the object, printed
1191 * above by _Py_PrintReferences.
1192 */
Victor Stinnerda273412017-12-15 01:46:02 +01001193 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001194 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001195 }
Nick Coghland6009512014-11-20 21:39:37 +10001196#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001197#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001198 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001199 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001200 }
Nick Coghland6009512014-11-20 21:39:37 +10001201#endif
1202
1203 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001204
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001205 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001206 return status;
1207}
1208
1209void
1210Py_Finalize(void)
1211{
1212 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001213}
1214
1215/* Create and initialize a new interpreter and thread, and return the
1216 new thread. This requires that Py_Initialize() has been called
1217 first.
1218
1219 Unsuccessful initialization yields a NULL pointer. Note that *no*
1220 exception information is available even in this case -- the
1221 exception information is held in the thread, and there is no
1222 thread.
1223
1224 Locking: as above.
1225
1226*/
1227
Victor Stinnera7368ac2017-11-15 18:11:45 -08001228static _PyInitError
1229new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001230{
1231 PyInterpreterState *interp;
1232 PyThreadState *tstate, *save_tstate;
1233 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001234 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001235
Victor Stinnera7368ac2017-11-15 18:11:45 -08001236 if (!_PyRuntime.initialized) {
1237 return _Py_INIT_ERR("Py_Initialize must be called first");
1238 }
Nick Coghland6009512014-11-20 21:39:37 +10001239
Victor Stinner8a1be612016-03-14 22:07:55 +01001240 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1241 interpreters: disable PyGILState_Check(). */
1242 _PyGILState_check_enabled = 0;
1243
Nick Coghland6009512014-11-20 21:39:37 +10001244 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001245 if (interp == NULL) {
1246 *tstate_p = NULL;
1247 return _Py_INIT_OK();
1248 }
Nick Coghland6009512014-11-20 21:39:37 +10001249
1250 tstate = PyThreadState_New(interp);
1251 if (tstate == NULL) {
1252 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001253 *tstate_p = NULL;
1254 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001255 }
1256
1257 save_tstate = PyThreadState_Swap(tstate);
1258
Eric Snow1abcf672017-05-23 21:46:51 -07001259 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001260 _PyCoreConfig *core_config;
1261 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001262 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001263 core_config = &save_tstate->interp->core_config;
1264 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001265 } else {
1266 /* No current thread state, copy from the main interpreter */
1267 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001268 core_config = &main_interp->core_config;
1269 config = &main_interp->config;
1270 }
1271
1272 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1273 return _Py_INIT_ERR("failed to copy core config");
1274 }
1275 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1276 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001277 }
1278
Nick Coghland6009512014-11-20 21:39:37 +10001279 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001280 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001281 if (modules == NULL) {
1282 return _Py_INIT_ERR("can't make modules dictionary");
1283 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001284 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001285
Eric Snowd393c1b2017-09-14 12:18:12 -06001286 sysmod = _PyImport_FindBuiltin("sys", modules);
1287 if (sysmod != NULL) {
1288 interp->sysdict = PyModule_GetDict(sysmod);
1289 if (interp->sysdict == NULL)
1290 goto handle_error;
1291 Py_INCREF(interp->sysdict);
1292 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001293 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001294 }
1295
1296 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001297 if (bimod != NULL) {
1298 interp->builtins = PyModule_GetDict(bimod);
1299 if (interp->builtins == NULL)
1300 goto handle_error;
1301 Py_INCREF(interp->builtins);
1302 }
1303
1304 /* initialize builtin exceptions */
1305 _PyExc_Init(bimod);
1306
Nick Coghland6009512014-11-20 21:39:37 +10001307 if (bimod != NULL && sysmod != NULL) {
1308 PyObject *pstderr;
1309
Nick Coghland6009512014-11-20 21:39:37 +10001310 /* Set up a preliminary stderr printer until we have enough
1311 infrastructure for the io module in place. */
1312 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001313 if (pstderr == NULL) {
1314 return _Py_INIT_ERR("can't set preliminary stderr");
1315 }
Nick Coghland6009512014-11-20 21:39:37 +10001316 _PySys_SetObjectId(&PyId_stderr, pstderr);
1317 PySys_SetObject("__stderr__", pstderr);
1318 Py_DECREF(pstderr);
1319
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001320 err = _PyImportHooks_Init();
1321 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001322 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001323 }
Nick Coghland6009512014-11-20 21:39:37 +10001324
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001325 err = initimport(interp, sysmod);
1326 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001327 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001328 }
Nick Coghland6009512014-11-20 21:39:37 +10001329
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001330 err = initexternalimport(interp);
1331 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001332 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001333 }
Nick Coghland6009512014-11-20 21:39:37 +10001334
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001335 err = initfsencoding(interp);
1336 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001337 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001338 }
1339
Victor Stinner91106cd2017-12-13 12:29:09 +01001340 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001341 if (_Py_INIT_FAILED(err)) {
1342 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001343 }
1344
1345 err = add_main_module(interp);
1346 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001347 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001348 }
1349
1350 if (!Py_NoSiteFlag) {
1351 err = initsite();
1352 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001353 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001354 }
1355 }
Nick Coghland6009512014-11-20 21:39:37 +10001356 }
1357
Victor Stinnera7368ac2017-11-15 18:11:45 -08001358 if (PyErr_Occurred()) {
1359 goto handle_error;
1360 }
Nick Coghland6009512014-11-20 21:39:37 +10001361
Victor Stinnera7368ac2017-11-15 18:11:45 -08001362 *tstate_p = tstate;
1363 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001364
Nick Coghland6009512014-11-20 21:39:37 +10001365handle_error:
1366 /* Oops, it didn't work. Undo it all. */
1367
1368 PyErr_PrintEx(0);
1369 PyThreadState_Clear(tstate);
1370 PyThreadState_Swap(save_tstate);
1371 PyThreadState_Delete(tstate);
1372 PyInterpreterState_Delete(interp);
1373
Victor Stinnera7368ac2017-11-15 18:11:45 -08001374 *tstate_p = NULL;
1375 return _Py_INIT_OK();
1376}
1377
1378PyThreadState *
1379Py_NewInterpreter(void)
1380{
1381 PyThreadState *tstate;
1382 _PyInitError err = new_interpreter(&tstate);
1383 if (_Py_INIT_FAILED(err)) {
1384 _Py_FatalInitError(err);
1385 }
1386 return tstate;
1387
Nick Coghland6009512014-11-20 21:39:37 +10001388}
1389
1390/* Delete an interpreter and its last thread. This requires that the
1391 given thread state is current, that the thread has no remaining
1392 frames, and that it is its interpreter's only remaining thread.
1393 It is a fatal error to violate these constraints.
1394
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001395 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001396 everything, regardless.)
1397
1398 Locking: as above.
1399
1400*/
1401
1402void
1403Py_EndInterpreter(PyThreadState *tstate)
1404{
1405 PyInterpreterState *interp = tstate->interp;
1406
1407 if (tstate != PyThreadState_GET())
1408 Py_FatalError("Py_EndInterpreter: thread is not current");
1409 if (tstate->frame != NULL)
1410 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1411
1412 wait_for_thread_shutdown();
1413
Marcel Plch776407f2017-12-20 11:17:58 +01001414 call_py_exitfuncs(interp);
1415
Nick Coghland6009512014-11-20 21:39:37 +10001416 if (tstate != interp->tstate_head || tstate->next != NULL)
1417 Py_FatalError("Py_EndInterpreter: not the last thread");
1418
1419 PyImport_Cleanup();
1420 PyInterpreterState_Clear(interp);
1421 PyThreadState_Swap(NULL);
1422 PyInterpreterState_Delete(interp);
1423}
1424
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001425/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001426
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001427static _PyInitError
1428add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001429{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001430 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001431 m = PyImport_AddModule("__main__");
1432 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001433 return _Py_INIT_ERR("can't create __main__ module");
1434
Nick Coghland6009512014-11-20 21:39:37 +10001435 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001436 ann_dict = PyDict_New();
1437 if ((ann_dict == NULL) ||
1438 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001439 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001440 }
1441 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001442
Nick Coghland6009512014-11-20 21:39:37 +10001443 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1444 PyObject *bimod = PyImport_ImportModule("builtins");
1445 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001446 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001447 }
1448 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001449 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001450 }
1451 Py_DECREF(bimod);
1452 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001453
Nick Coghland6009512014-11-20 21:39:37 +10001454 /* Main is a little special - imp.is_builtin("__main__") will return
1455 * False, but BuiltinImporter is still the most appropriate initial
1456 * setting for its __loader__ attribute. A more suitable value will
1457 * be set if __main__ gets further initialized later in the startup
1458 * process.
1459 */
1460 loader = PyDict_GetItemString(d, "__loader__");
1461 if (loader == NULL || loader == Py_None) {
1462 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1463 "BuiltinImporter");
1464 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001465 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001466 }
1467 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001468 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001469 }
1470 Py_DECREF(loader);
1471 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001472 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001473}
1474
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001475static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001476initfsencoding(PyInterpreterState *interp)
1477{
1478 PyObject *codec;
1479
Steve Dowercc16be82016-09-08 10:35:16 -07001480#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001481 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001482 Py_FileSystemDefaultEncoding = "mbcs";
1483 Py_FileSystemDefaultEncodeErrors = "replace";
1484 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001485 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001486 Py_FileSystemDefaultEncoding = "utf-8";
1487 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1488 }
1489#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001490 if (Py_FileSystemDefaultEncoding == NULL &&
1491 interp->core_config.utf8_mode)
1492 {
1493 Py_FileSystemDefaultEncoding = "utf-8";
1494 Py_HasFileSystemDefaultEncoding = 1;
1495 }
1496 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001497 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001498 if (Py_FileSystemDefaultEncoding == NULL) {
1499 return _Py_INIT_ERR("Unable to get the locale encoding");
1500 }
Nick Coghland6009512014-11-20 21:39:37 +10001501
1502 Py_HasFileSystemDefaultEncoding = 0;
1503 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001504 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001505 }
Steve Dowercc16be82016-09-08 10:35:16 -07001506#endif
Nick Coghland6009512014-11-20 21:39:37 +10001507
1508 /* the encoding is mbcs, utf-8 or ascii */
1509 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1510 if (!codec) {
1511 /* Such error can only occurs in critical situations: no more
1512 * memory, import a module of the standard library failed,
1513 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001515 }
1516 Py_DECREF(codec);
1517 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001518 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001519}
1520
1521/* Import the site module (not into __main__ though) */
1522
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001523static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001524initsite(void)
1525{
1526 PyObject *m;
1527 m = PyImport_ImportModule("site");
1528 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001529 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001530 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531 Py_DECREF(m);
1532 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001533}
1534
Victor Stinner874dbe82015-09-04 17:29:57 +02001535/* Check if a file descriptor is valid or not.
1536 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1537static int
1538is_valid_fd(int fd)
1539{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001540#ifdef __APPLE__
1541 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1542 and the other side of the pipe is closed, dup(1) succeed, whereas
1543 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1544 such error. */
1545 struct stat st;
1546 return (fstat(fd, &st) == 0);
1547#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001548 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001549 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001550 return 0;
1551 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001552 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1553 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1554 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001555 fd2 = dup(fd);
1556 if (fd2 >= 0)
1557 close(fd2);
1558 _Py_END_SUPPRESS_IPH
1559 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001560#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001561}
1562
1563/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001564static PyObject*
1565create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001566 int fd, int write_mode, const char* name,
1567 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001568{
1569 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1570 const char* mode;
1571 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001572 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001573 int buffering, isatty;
1574 _Py_IDENTIFIER(open);
1575 _Py_IDENTIFIER(isatty);
1576 _Py_IDENTIFIER(TextIOWrapper);
1577 _Py_IDENTIFIER(mode);
1578
Victor Stinner874dbe82015-09-04 17:29:57 +02001579 if (!is_valid_fd(fd))
1580 Py_RETURN_NONE;
1581
Nick Coghland6009512014-11-20 21:39:37 +10001582 /* stdin is always opened in buffered mode, first because it shouldn't
1583 make a difference in common use cases, second because TextIOWrapper
1584 depends on the presence of a read1() method which only exists on
1585 buffered streams.
1586 */
1587 if (Py_UnbufferedStdioFlag && write_mode)
1588 buffering = 0;
1589 else
1590 buffering = -1;
1591 if (write_mode)
1592 mode = "wb";
1593 else
1594 mode = "rb";
1595 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1596 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001597 Py_None, Py_None, /* encoding, errors */
1598 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001599 if (buf == NULL)
1600 goto error;
1601
1602 if (buffering) {
1603 _Py_IDENTIFIER(raw);
1604 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1605 if (raw == NULL)
1606 goto error;
1607 }
1608 else {
1609 raw = buf;
1610 Py_INCREF(raw);
1611 }
1612
Steve Dower39294992016-08-30 21:22:36 -07001613#ifdef MS_WINDOWS
1614 /* Windows console IO is always UTF-8 encoded */
1615 if (PyWindowsConsoleIO_Check(raw))
1616 encoding = "utf-8";
1617#endif
1618
Nick Coghland6009512014-11-20 21:39:37 +10001619 text = PyUnicode_FromString(name);
1620 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1621 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001622 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001623 if (res == NULL)
1624 goto error;
1625 isatty = PyObject_IsTrue(res);
1626 Py_DECREF(res);
1627 if (isatty == -1)
1628 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001629 if (Py_UnbufferedStdioFlag)
1630 write_through = Py_True;
1631 else
1632 write_through = Py_False;
1633 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001634 line_buffering = Py_True;
1635 else
1636 line_buffering = Py_False;
1637
1638 Py_CLEAR(raw);
1639 Py_CLEAR(text);
1640
1641#ifdef MS_WINDOWS
1642 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1643 newlines to "\n".
1644 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1645 newline = NULL;
1646#else
1647 /* sys.stdin: split lines at "\n".
1648 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1649 newline = "\n";
1650#endif
1651
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001652 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001653 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001654 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001655 Py_CLEAR(buf);
1656 if (stream == NULL)
1657 goto error;
1658
1659 if (write_mode)
1660 mode = "w";
1661 else
1662 mode = "r";
1663 text = PyUnicode_FromString(mode);
1664 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1665 goto error;
1666 Py_CLEAR(text);
1667 return stream;
1668
1669error:
1670 Py_XDECREF(buf);
1671 Py_XDECREF(stream);
1672 Py_XDECREF(text);
1673 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001674
Victor Stinner874dbe82015-09-04 17:29:57 +02001675 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1676 /* Issue #24891: the file descriptor was closed after the first
1677 is_valid_fd() check was called. Ignore the OSError and set the
1678 stream to None. */
1679 PyErr_Clear();
1680 Py_RETURN_NONE;
1681 }
1682 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001683}
1684
1685/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001686static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001687init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001688{
1689 PyObject *iomod = NULL, *wrapper;
1690 PyObject *bimod = NULL;
1691 PyObject *m;
1692 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001693 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001694 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001695 char *pythonioencoding = NULL;
1696 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001697 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001698
1699 /* Hack to avoid a nasty recursion issue when Python is invoked
1700 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1701 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1702 goto error;
1703 }
1704 Py_DECREF(m);
1705
1706 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1707 goto error;
1708 }
1709 Py_DECREF(m);
1710
1711 if (!(bimod = PyImport_ImportModule("builtins"))) {
1712 goto error;
1713 }
1714
1715 if (!(iomod = PyImport_ImportModule("io"))) {
1716 goto error;
1717 }
1718 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1719 goto error;
1720 }
1721
1722 /* Set builtins.open */
1723 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1724 Py_DECREF(wrapper);
1725 goto error;
1726 }
1727 Py_DECREF(wrapper);
1728
1729 encoding = _Py_StandardStreamEncoding;
1730 errors = _Py_StandardStreamErrors;
1731 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001732 char *opt = Py_GETENV("PYTHONIOENCODING");
1733 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001734 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001735 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001736 if (pythonioencoding == NULL) {
1737 PyErr_NoMemory();
1738 goto error;
1739 }
1740 err = strchr(pythonioencoding, ':');
1741 if (err) {
1742 *err = '\0';
1743 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001744 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001745 errors = err;
1746 }
1747 }
1748 if (*pythonioencoding && !encoding) {
1749 encoding = pythonioencoding;
1750 }
1751 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001752 else if (interp->core_config.utf8_mode) {
1753 encoding = "utf-8";
1754 errors = "surrogateescape";
1755 }
1756
1757 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001758 /* Choose the default error handler based on the current locale */
1759 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001760 }
Nick Coghland6009512014-11-20 21:39:37 +10001761 }
1762
1763 /* Set sys.stdin */
1764 fd = fileno(stdin);
1765 /* Under some conditions stdin, stdout and stderr may not be connected
1766 * and fileno() may point to an invalid file descriptor. For example
1767 * GUI apps don't have valid standard streams by default.
1768 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001769 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1770 if (std == NULL)
1771 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001772 PySys_SetObject("__stdin__", std);
1773 _PySys_SetObjectId(&PyId_stdin, std);
1774 Py_DECREF(std);
1775
1776 /* Set sys.stdout */
1777 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001778 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1779 if (std == NULL)
1780 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001781 PySys_SetObject("__stdout__", std);
1782 _PySys_SetObjectId(&PyId_stdout, std);
1783 Py_DECREF(std);
1784
1785#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1786 /* Set sys.stderr, replaces the preliminary stderr */
1787 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001788 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1789 if (std == NULL)
1790 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001791
1792 /* Same as hack above, pre-import stderr's codec to avoid recursion
1793 when import.c tries to write to stderr in verbose mode. */
1794 encoding_attr = PyObject_GetAttrString(std, "encoding");
1795 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001796 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001797 if (std_encoding != NULL) {
1798 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1799 Py_XDECREF(codec_info);
1800 }
1801 Py_DECREF(encoding_attr);
1802 }
1803 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1804
1805 if (PySys_SetObject("__stderr__", std) < 0) {
1806 Py_DECREF(std);
1807 goto error;
1808 }
1809 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1810 Py_DECREF(std);
1811 goto error;
1812 }
1813 Py_DECREF(std);
1814#endif
1815
Victor Stinnera7368ac2017-11-15 18:11:45 -08001816 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001817
Victor Stinnera7368ac2017-11-15 18:11:45 -08001818error:
1819 res = _Py_INIT_ERR("can't initialize sys standard streams");
1820
1821done:
Nick Coghland6009512014-11-20 21:39:37 +10001822 /* We won't need them anymore. */
1823 if (_Py_StandardStreamEncoding) {
1824 PyMem_RawFree(_Py_StandardStreamEncoding);
1825 _Py_StandardStreamEncoding = NULL;
1826 }
1827 if (_Py_StandardStreamErrors) {
1828 PyMem_RawFree(_Py_StandardStreamErrors);
1829 _Py_StandardStreamErrors = NULL;
1830 }
1831 PyMem_Free(pythonioencoding);
1832 Py_XDECREF(bimod);
1833 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001834 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001835}
1836
1837
Victor Stinner10dc4842015-03-24 12:01:30 +01001838static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001839_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001840{
Victor Stinner10dc4842015-03-24 12:01:30 +01001841 fputc('\n', stderr);
1842 fflush(stderr);
1843
1844 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001845 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001846}
Victor Stinner791da1c2016-03-14 16:53:12 +01001847
1848/* Print the current exception (if an exception is set) with its traceback,
1849 or display the current Python stack.
1850
1851 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1852 called on catastrophic cases.
1853
1854 Return 1 if the traceback was displayed, 0 otherwise. */
1855
1856static int
1857_Py_FatalError_PrintExc(int fd)
1858{
1859 PyObject *ferr, *res;
1860 PyObject *exception, *v, *tb;
1861 int has_tb;
1862
1863 if (PyThreadState_GET() == NULL) {
1864 /* The GIL is released: trying to acquire it is likely to deadlock,
1865 just give up. */
1866 return 0;
1867 }
1868
1869 PyErr_Fetch(&exception, &v, &tb);
1870 if (exception == NULL) {
1871 /* No current exception */
1872 return 0;
1873 }
1874
1875 ferr = _PySys_GetObjectId(&PyId_stderr);
1876 if (ferr == NULL || ferr == Py_None) {
1877 /* sys.stderr is not set yet or set to None,
1878 no need to try to display the exception */
1879 return 0;
1880 }
1881
1882 PyErr_NormalizeException(&exception, &v, &tb);
1883 if (tb == NULL) {
1884 tb = Py_None;
1885 Py_INCREF(tb);
1886 }
1887 PyException_SetTraceback(v, tb);
1888 if (exception == NULL) {
1889 /* PyErr_NormalizeException() failed */
1890 return 0;
1891 }
1892
1893 has_tb = (tb != Py_None);
1894 PyErr_Display(exception, v, tb);
1895 Py_XDECREF(exception);
1896 Py_XDECREF(v);
1897 Py_XDECREF(tb);
1898
1899 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001900 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001901 if (res == NULL)
1902 PyErr_Clear();
1903 else
1904 Py_DECREF(res);
1905
1906 return has_tb;
1907}
1908
Nick Coghland6009512014-11-20 21:39:37 +10001909/* Print fatal error message and abort */
1910
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001911#ifdef MS_WINDOWS
1912static void
1913fatal_output_debug(const char *msg)
1914{
1915 /* buffer of 256 bytes allocated on the stack */
1916 WCHAR buffer[256 / sizeof(WCHAR)];
1917 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1918 size_t msglen;
1919
1920 OutputDebugStringW(L"Fatal Python error: ");
1921
1922 msglen = strlen(msg);
1923 while (msglen) {
1924 size_t i;
1925
1926 if (buflen > msglen) {
1927 buflen = msglen;
1928 }
1929
1930 /* Convert the message to wchar_t. This uses a simple one-to-one
1931 conversion, assuming that the this error message actually uses
1932 ASCII only. If this ceases to be true, we will have to convert. */
1933 for (i=0; i < buflen; ++i) {
1934 buffer[i] = msg[i];
1935 }
1936 buffer[i] = L'\0';
1937 OutputDebugStringW(buffer);
1938
1939 msg += buflen;
1940 msglen -= buflen;
1941 }
1942 OutputDebugStringW(L"\n");
1943}
1944#endif
1945
Benjamin Petersoncef88b92017-11-25 13:02:55 -08001946static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001947fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10001948{
1949 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001950 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001951
1952 if (reentrant) {
1953 /* Py_FatalError() caused a second fatal error.
1954 Example: flush_std_files() raises a recursion error. */
1955 goto exit;
1956 }
1957 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001958
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959 fprintf(stderr, "Fatal Python error: ");
1960 if (prefix) {
1961 fputs(prefix, stderr);
1962 fputs(": ", stderr);
1963 }
1964 if (msg) {
1965 fputs(msg, stderr);
1966 }
1967 else {
1968 fprintf(stderr, "<message not set>");
1969 }
1970 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001971 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001972
Victor Stinnere0deff32015-03-24 13:46:18 +01001973 /* Print the exception (if an exception is set) with its traceback,
1974 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001975 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001976 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001977 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001978
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001979 /* The main purpose of faulthandler is to display the traceback.
1980 This function already did its best to display a traceback.
1981 Disable faulthandler to prevent writing a second traceback
1982 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001983 _PyFaulthandler_Fini();
1984
Victor Stinner791da1c2016-03-14 16:53:12 +01001985 /* Check if the current Python thread hold the GIL */
1986 if (PyThreadState_GET() != NULL) {
1987 /* Flush sys.stdout and sys.stderr */
1988 flush_std_files();
1989 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001990
Nick Coghland6009512014-11-20 21:39:37 +10001991#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001992 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001993#endif /* MS_WINDOWS */
1994
1995exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001996 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01001997#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001998 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10001999#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002000 abort();
2001 }
2002 else {
2003 exit(status);
2004 }
2005}
2006
Victor Stinner19760862017-12-20 01:41:59 +01002007void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002008Py_FatalError(const char *msg)
2009{
2010 fatal_error(NULL, msg, -1);
2011}
2012
Victor Stinner19760862017-12-20 01:41:59 +01002013void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002014_Py_FatalInitError(_PyInitError err)
2015{
2016 /* On "user" error: exit with status 1.
2017 For all other errors, call abort(). */
2018 int status = err.user_err ? 1 : -1;
2019 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002020}
2021
2022/* Clean up and exit */
2023
Victor Stinnerd7292b52016-06-17 12:29:00 +02002024# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002025
Nick Coghland6009512014-11-20 21:39:37 +10002026/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002027void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002028{
Marcel Plch776407f2017-12-20 11:17:58 +01002029 PyThreadState *ts;
2030 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002031
Marcel Plch776407f2017-12-20 11:17:58 +01002032 ts = PyThreadState_GET();
2033 is = ts->interp;
2034
Antoine Pitroufc5db952017-12-13 02:29:07 +01002035 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002036 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2037
2038 is->pyexitfunc = func;
2039 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002040}
2041
2042static void
Marcel Plch776407f2017-12-20 11:17:58 +01002043call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002044{
Marcel Plch776407f2017-12-20 11:17:58 +01002045 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002046 return;
2047
Marcel Plch776407f2017-12-20 11:17:58 +01002048 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002049 PyErr_Clear();
2050}
2051
2052/* Wait until threading._shutdown completes, provided
2053 the threading module was imported in the first place.
2054 The shutdown routine will wait until all non-daemon
2055 "threading" threads have completed. */
2056static void
2057wait_for_thread_shutdown(void)
2058{
Nick Coghland6009512014-11-20 21:39:37 +10002059 _Py_IDENTIFIER(_shutdown);
2060 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002061 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002062 if (threading == NULL) {
2063 /* threading not imported */
2064 PyErr_Clear();
2065 return;
2066 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002067 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002068 if (result == NULL) {
2069 PyErr_WriteUnraisable(threading);
2070 }
2071 else {
2072 Py_DECREF(result);
2073 }
2074 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002075}
2076
2077#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002078int Py_AtExit(void (*func)(void))
2079{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002080 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002081 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002082 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002083 return 0;
2084}
2085
2086static void
2087call_ll_exitfuncs(void)
2088{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002089 while (_PyRuntime.nexitfuncs > 0)
2090 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002091
2092 fflush(stdout);
2093 fflush(stderr);
2094}
2095
2096void
2097Py_Exit(int sts)
2098{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002099 if (Py_FinalizeEx() < 0) {
2100 sts = 120;
2101 }
Nick Coghland6009512014-11-20 21:39:37 +10002102
2103 exit(sts);
2104}
2105
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002106static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002107initsigs(void)
2108{
2109#ifdef SIGPIPE
2110 PyOS_setsig(SIGPIPE, SIG_IGN);
2111#endif
2112#ifdef SIGXFZ
2113 PyOS_setsig(SIGXFZ, SIG_IGN);
2114#endif
2115#ifdef SIGXFSZ
2116 PyOS_setsig(SIGXFSZ, SIG_IGN);
2117#endif
2118 PyOS_InitInterrupts(); /* May imply initsignal() */
2119 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002120 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002121 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002122 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002123}
2124
2125
2126/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2127 *
2128 * All of the code in this function must only use async-signal-safe functions,
2129 * listed at `man 7 signal` or
2130 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2131 */
2132void
2133_Py_RestoreSignals(void)
2134{
2135#ifdef SIGPIPE
2136 PyOS_setsig(SIGPIPE, SIG_DFL);
2137#endif
2138#ifdef SIGXFZ
2139 PyOS_setsig(SIGXFZ, SIG_DFL);
2140#endif
2141#ifdef SIGXFSZ
2142 PyOS_setsig(SIGXFSZ, SIG_DFL);
2143#endif
2144}
2145
2146
2147/*
2148 * The file descriptor fd is considered ``interactive'' if either
2149 * a) isatty(fd) is TRUE, or
2150 * b) the -i flag was given, and the filename associated with
2151 * the descriptor is NULL or "<stdin>" or "???".
2152 */
2153int
2154Py_FdIsInteractive(FILE *fp, const char *filename)
2155{
2156 if (isatty((int)fileno(fp)))
2157 return 1;
2158 if (!Py_InteractiveFlag)
2159 return 0;
2160 return (filename == NULL) ||
2161 (strcmp(filename, "<stdin>") == 0) ||
2162 (strcmp(filename, "???") == 0);
2163}
2164
2165
Nick Coghland6009512014-11-20 21:39:37 +10002166/* Wrappers around sigaction() or signal(). */
2167
2168PyOS_sighandler_t
2169PyOS_getsig(int sig)
2170{
2171#ifdef HAVE_SIGACTION
2172 struct sigaction context;
2173 if (sigaction(sig, NULL, &context) == -1)
2174 return SIG_ERR;
2175 return context.sa_handler;
2176#else
2177 PyOS_sighandler_t handler;
2178/* Special signal handling for the secure CRT in Visual Studio 2005 */
2179#if defined(_MSC_VER) && _MSC_VER >= 1400
2180 switch (sig) {
2181 /* Only these signals are valid */
2182 case SIGINT:
2183 case SIGILL:
2184 case SIGFPE:
2185 case SIGSEGV:
2186 case SIGTERM:
2187 case SIGBREAK:
2188 case SIGABRT:
2189 break;
2190 /* Don't call signal() with other values or it will assert */
2191 default:
2192 return SIG_ERR;
2193 }
2194#endif /* _MSC_VER && _MSC_VER >= 1400 */
2195 handler = signal(sig, SIG_IGN);
2196 if (handler != SIG_ERR)
2197 signal(sig, handler);
2198 return handler;
2199#endif
2200}
2201
2202/*
2203 * All of the code in this function must only use async-signal-safe functions,
2204 * listed at `man 7 signal` or
2205 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2206 */
2207PyOS_sighandler_t
2208PyOS_setsig(int sig, PyOS_sighandler_t handler)
2209{
2210#ifdef HAVE_SIGACTION
2211 /* Some code in Modules/signalmodule.c depends on sigaction() being
2212 * used here if HAVE_SIGACTION is defined. Fix that if this code
2213 * changes to invalidate that assumption.
2214 */
2215 struct sigaction context, ocontext;
2216 context.sa_handler = handler;
2217 sigemptyset(&context.sa_mask);
2218 context.sa_flags = 0;
2219 if (sigaction(sig, &context, &ocontext) == -1)
2220 return SIG_ERR;
2221 return ocontext.sa_handler;
2222#else
2223 PyOS_sighandler_t oldhandler;
2224 oldhandler = signal(sig, handler);
2225#ifdef HAVE_SIGINTERRUPT
2226 siginterrupt(sig, 1);
2227#endif
2228 return oldhandler;
2229#endif
2230}
2231
2232#ifdef __cplusplus
2233}
2234#endif