blob: c2ee4ffc4681ba62613daffe926fc5814ad3378b [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 */
Yury Selivanovf23746a2018-01-22 19:11:18 -05007#include "internal/context.h"
8#include "internal/hamt.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -06009#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +100010#include "grammar.h"
11#include "node.h"
12#include "token.h"
13#include "parsetok.h"
14#include "errcode.h"
15#include "code.h"
16#include "symtable.h"
17#include "ast.h"
18#include "marshal.h"
19#include "osdefs.h"
20#include <locale.h>
21
22#ifdef HAVE_SIGNAL_H
23#include <signal.h>
24#endif
25
26#ifdef MS_WINDOWS
27#include "malloc.h" /* for alloca */
28#endif
29
30#ifdef HAVE_LANGINFO_H
31#include <langinfo.h>
32#endif
33
34#ifdef MS_WINDOWS
35#undef BYTE
36#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070037
38extern PyTypeObject PyWindowsConsoleIO_Type;
39#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100040#endif
41
42_Py_IDENTIFIER(flush);
43_Py_IDENTIFIER(name);
44_Py_IDENTIFIER(stdin);
45_Py_IDENTIFIER(stdout);
46_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060047_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100048
49#ifdef __cplusplus
50extern "C" {
51#endif
52
Nick Coghland6009512014-11-20 21:39:37 +100053extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
Victor Stinnerf7e5b562017-11-15 15:48:08 -080056static _PyInitError add_main_module(PyInterpreterState *interp);
57static _PyInitError initfsencoding(PyInterpreterState *interp);
58static _PyInitError initsite(void);
Victor Stinner91106cd2017-12-13 12:29:09 +010059static _PyInitError init_sys_streams(PyInterpreterState *interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -080060static _PyInitError initsigs(void);
Marcel Plch776407f2017-12-20 11:17:58 +010061static void call_py_exitfuncs(PyInterpreterState *);
Nick Coghland6009512014-11-20 21:39:37 +100062static void wait_for_thread_shutdown(void);
63static void call_ll_exitfuncs(void);
64extern int _PyUnicode_Init(void);
65extern int _PyStructSequence_Init(void);
66extern void _PyUnicode_Fini(void);
67extern int _PyLong_Init(void);
68extern void PyLong_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080069extern _PyInitError _PyFaulthandler_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100070extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
Victor Stinnera7368ac2017-11-15 18:11:45 -080072extern int _PyTraceMalloc_Init(int enable);
Nick Coghland6009512014-11-20 21:39:37 +100073extern int _PyTraceMalloc_Fini(void);
Eric Snowc7ec9982017-05-23 23:00:52 -070074extern void _Py_ReadyTypes(void);
Nick Coghland6009512014-11-20 21:39:37 +100075
Nick Coghland6009512014-11-20 21:39:37 +100076extern void _PyGILState_Init(PyInterpreterState *, PyThreadState *);
77extern void _PyGILState_Fini(void);
Nick Coghland6009512014-11-20 21:39:37 +100078
Victor Stinnerf7e5b562017-11-15 15:48:08 -080079_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
Eric Snow2ebc5ce2017-09-07 23:51:28 -060080
Victor Stinnerf7e5b562017-11-15 15:48:08 -080081_PyInitError
Eric Snow2ebc5ce2017-09-07 23:51:28 -060082_PyRuntime_Initialize(void)
83{
84 /* XXX We only initialize once in the process, which aligns with
85 the static initialization of the former globals now found in
86 _PyRuntime. However, _PyRuntime *should* be initialized with
87 every Py_Initialize() call, but doing so breaks the runtime.
88 This is because the runtime state is not properly finalized
89 currently. */
90 static int initialized = 0;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080091 if (initialized) {
92 return _Py_INIT_OK();
93 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -060094 initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -080095
96 return _PyRuntimeState_Init(&_PyRuntime);
Eric Snow2ebc5ce2017-09-07 23:51:28 -060097}
98
99void
100_PyRuntime_Finalize(void)
101{
102 _PyRuntimeState_Fini(&_PyRuntime);
103}
104
105int
106_Py_IsFinalizing(void)
107{
108 return _PyRuntime.finalizing != NULL;
109}
110
Nick Coghland6009512014-11-20 21:39:37 +1000111/* Hack to force loading of object files */
112int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
113 PyOS_mystrnicmp; /* Python/pystrcmp.o */
114
115/* PyModule_GetWarningsModule is no longer necessary as of 2.6
116since _warnings is builtin. This API should not be used. */
117PyObject *
118PyModule_GetWarningsModule(void)
119{
120 return PyImport_ImportModule("warnings");
121}
122
Eric Snowc7ec9982017-05-23 23:00:52 -0700123
Eric Snow1abcf672017-05-23 21:46:51 -0700124/* APIs to access the initialization flags
125 *
126 * Can be called prior to Py_Initialize.
127 */
Nick Coghland6009512014-11-20 21:39:37 +1000128
Eric Snow1abcf672017-05-23 21:46:51 -0700129int
130_Py_IsCoreInitialized(void)
131{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600132 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700133}
Nick Coghland6009512014-11-20 21:39:37 +1000134
135int
136Py_IsInitialized(void)
137{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600138 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000139}
140
141/* Helper to allow an embedding application to override the normal
142 * mechanism that attempts to figure out an appropriate IO encoding
143 */
144
145static char *_Py_StandardStreamEncoding = NULL;
146static char *_Py_StandardStreamErrors = NULL;
147
148int
149Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
150{
151 if (Py_IsInitialized()) {
152 /* This is too late to have any effect */
153 return -1;
154 }
Victor Stinner31e99082017-12-20 23:41:38 +0100155
156 int res = 0;
157
158 /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
159 but Py_Initialize() can change the allocator. Use a known allocator
160 to be able to release the memory later. */
161 PyMemAllocatorEx old_alloc;
162 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
163
Nick Coghland6009512014-11-20 21:39:37 +1000164 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
165 * initialised yet.
166 *
167 * However, the raw memory allocators are initialised appropriately
168 * as C static variables, so _PyMem_RawStrdup is OK even though
169 * Py_Initialize hasn't been called yet.
170 */
171 if (encoding) {
172 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
173 if (!_Py_StandardStreamEncoding) {
Victor Stinner31e99082017-12-20 23:41:38 +0100174 res = -2;
175 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000176 }
177 }
178 if (errors) {
179 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
180 if (!_Py_StandardStreamErrors) {
181 if (_Py_StandardStreamEncoding) {
182 PyMem_RawFree(_Py_StandardStreamEncoding);
183 }
Victor Stinner31e99082017-12-20 23:41:38 +0100184 res = -3;
185 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000186 }
187 }
Steve Dower39294992016-08-30 21:22:36 -0700188#ifdef MS_WINDOWS
189 if (_Py_StandardStreamEncoding) {
190 /* Overriding the stream encoding implies legacy streams */
191 Py_LegacyWindowsStdioFlag = 1;
192 }
193#endif
Victor Stinner31e99082017-12-20 23:41:38 +0100194
195done:
196 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
197
198 return res;
Nick Coghland6009512014-11-20 21:39:37 +1000199}
200
Nick Coghlan6ea41862017-06-11 13:16:15 +1000201
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000202/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
203 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000204 initializations fail, a fatal error is issued and the function does
205 not return. On return, the first thread and interpreter state have
206 been created.
207
208 Locking: you must hold the interpreter lock while calling this.
209 (If the lock has not yet been initialized, that's equivalent to
210 having the lock, but you cannot use multiple threads.)
211
212*/
213
Nick Coghland6009512014-11-20 21:39:37 +1000214static char*
215get_codec_name(const char *encoding)
216{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200217 const char *name_utf8;
218 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000219 PyObject *codec, *name = NULL;
220
221 codec = _PyCodec_Lookup(encoding);
222 if (!codec)
223 goto error;
224
225 name = _PyObject_GetAttrId(codec, &PyId_name);
226 Py_CLEAR(codec);
227 if (!name)
228 goto error;
229
Serhiy Storchaka06515832016-11-20 09:13:07 +0200230 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000231 if (name_utf8 == NULL)
232 goto error;
233 name_str = _PyMem_RawStrdup(name_utf8);
234 Py_DECREF(name);
235 if (name_str == NULL) {
236 PyErr_NoMemory();
237 return NULL;
238 }
239 return name_str;
240
241error:
242 Py_XDECREF(codec);
243 Py_XDECREF(name);
244 return NULL;
245}
246
247static char*
248get_locale_encoding(void)
249{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700250#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000251 char* codeset = nl_langinfo(CODESET);
252 if (!codeset || codeset[0] == '\0') {
253 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
254 return NULL;
255 }
256 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200257#elif defined(__ANDROID__)
258 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000259#else
260 PyErr_SetNone(PyExc_NotImplementedError);
261 return NULL;
262#endif
263}
264
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800265static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700266initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000267{
268 PyObject *importlib;
269 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000270 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800271 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000272
273 /* Import _importlib through its frozen version, _frozen_importlib. */
274 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800275 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000276 }
277 else if (Py_VerboseFlag) {
278 PySys_FormatStderr("import _frozen_importlib # frozen\n");
279 }
280 importlib = PyImport_AddModule("_frozen_importlib");
281 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800282 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000283 }
284 interp->importlib = importlib;
285 Py_INCREF(interp->importlib);
286
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300287 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
288 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800289 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300290 Py_INCREF(interp->import_func);
291
Victor Stinnercd6e6942015-09-18 09:11:57 +0200292 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800293 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000294 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800295 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000296 }
297 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200298 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000299 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600300 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800301 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000302 }
303
Victor Stinnercd6e6942015-09-18 09:11:57 +0200304 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000305 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
306 if (value == NULL) {
307 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800308 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000309 }
310 Py_DECREF(value);
311 Py_DECREF(impmod);
312
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800313 err = _PyImportZip_Init();
314 if (_Py_INIT_FAILED(err)) {
315 return err;
316 }
317
318 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000319}
320
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800321static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700322initexternalimport(PyInterpreterState *interp)
323{
324 PyObject *value;
325 value = PyObject_CallMethod(interp->importlib,
326 "_install_external_importers", "");
327 if (value == NULL) {
328 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800329 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700330 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200331 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800332 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700333}
Nick Coghland6009512014-11-20 21:39:37 +1000334
Nick Coghlan6ea41862017-06-11 13:16:15 +1000335/* Helper functions to better handle the legacy C locale
336 *
337 * The legacy C locale assumes ASCII as the default text encoding, which
338 * causes problems not only for the CPython runtime, but also other
339 * components like GNU readline.
340 *
341 * Accordingly, when the CLI detects it, it attempts to coerce it to a
342 * more capable UTF-8 based alternative as follows:
343 *
344 * if (_Py_LegacyLocaleDetected()) {
345 * _Py_CoerceLegacyLocale();
346 * }
347 *
348 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
349 *
350 * Locale coercion also impacts the default error handler for the standard
351 * streams: while the usual default is "strict", the default for the legacy
352 * C locale and for any of the coercion target locales is "surrogateescape".
353 */
354
355int
356_Py_LegacyLocaleDetected(void)
357{
358#ifndef MS_WINDOWS
359 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000360 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
361 * the POSIX locale as a simple alias for the C locale, so
362 * we may also want to check for that explicitly.
363 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000364 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
365 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
366#else
367 /* Windows uses code pages instead of locales, so no locale is legacy */
368 return 0;
369#endif
370}
371
Nick Coghlaneb817952017-06-18 12:29:42 +1000372static const char *_C_LOCALE_WARNING =
373 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
374 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
375 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
376 "locales is recommended.\n";
377
Nick Coghlaneb817952017-06-18 12:29:42 +1000378static void
Victor Stinner94540602017-12-16 04:54:22 +0100379_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000380{
Victor Stinner94540602017-12-16 04:54:22 +0100381 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000382 if (_Py_LegacyLocaleDetected()) {
383 fprintf(stderr, "%s", _C_LOCALE_WARNING);
384 }
385 }
386}
387
Nick Coghlan6ea41862017-06-11 13:16:15 +1000388typedef struct _CandidateLocale {
389 const char *locale_name; /* The locale to try as a coercion target */
390} _LocaleCoercionTarget;
391
392static _LocaleCoercionTarget _TARGET_LOCALES[] = {
393 {"C.UTF-8"},
394 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000395 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000396 {NULL}
397};
398
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200399static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000400get_default_standard_stream_error_handler(void)
401{
402 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
403 if (ctype_loc != NULL) {
404 /* "surrogateescape" is the default in the legacy C locale */
405 if (strcmp(ctype_loc, "C") == 0) {
406 return "surrogateescape";
407 }
408
409#ifdef PY_COERCE_C_LOCALE
410 /* "surrogateescape" is the default in locale coercion target locales */
411 const _LocaleCoercionTarget *target = NULL;
412 for (target = _TARGET_LOCALES; target->locale_name; target++) {
413 if (strcmp(ctype_loc, target->locale_name) == 0) {
414 return "surrogateescape";
415 }
416 }
417#endif
418 }
419
420 /* Otherwise return NULL to request the typical default error handler */
421 return NULL;
422}
423
424#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100425static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000426 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
427 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
428
429static void
Victor Stinner94540602017-12-16 04:54:22 +0100430_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000431{
432 const char *newloc = target->locale_name;
433
434 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100435 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000436
437 /* Set the relevant locale environment variable */
438 if (setenv("LC_CTYPE", newloc, 1)) {
439 fprintf(stderr,
440 "Error setting LC_CTYPE, skipping C locale coercion\n");
441 return;
442 }
Victor Stinner94540602017-12-16 04:54:22 +0100443 if (config->coerce_c_locale_warn) {
444 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000445 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000446
447 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100448 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000449}
450#endif
451
452void
Victor Stinner94540602017-12-16 04:54:22 +0100453_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000454{
455#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100456 const char *locale_override = getenv("LC_ALL");
457 if (locale_override == NULL || *locale_override == '\0') {
458 /* LC_ALL is also not set (or is set to an empty string) */
459 const _LocaleCoercionTarget *target = NULL;
460 for (target = _TARGET_LOCALES; target->locale_name; target++) {
461 const char *new_locale = setlocale(LC_CTYPE,
462 target->locale_name);
463 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100464#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100465defined(HAVE_LANGINFO_H) && defined(CODESET)
466 /* Also ensure that nl_langinfo works in this locale */
467 char *codeset = nl_langinfo(CODESET);
468 if (!codeset || *codeset == '\0') {
469 /* CODESET is not set or empty, so skip coercion */
470 new_locale = NULL;
471 _Py_SetLocaleFromEnv(LC_CTYPE);
472 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000473 }
Victor Stinner94540602017-12-16 04:54:22 +0100474#endif
475 /* Successfully configured locale, so make it the default */
476 _coerce_default_locale_settings(config, target);
477 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000478 }
479 }
480 }
481 /* No C locale warning here, as Py_Initialize will emit one later */
482#endif
483}
484
xdegaye1588be62017-11-12 12:45:59 +0100485/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
486 * isolate the idiosyncrasies of different libc implementations. It reads the
487 * appropriate environment variable and uses its value to select the locale for
488 * 'category'. */
489char *
490_Py_SetLocaleFromEnv(int category)
491{
492#ifdef __ANDROID__
493 const char *locale;
494 const char **pvar;
495#ifdef PY_COERCE_C_LOCALE
496 const char *coerce_c_locale;
497#endif
498 const char *utf8_locale = "C.UTF-8";
499 const char *env_var_set[] = {
500 "LC_ALL",
501 "LC_CTYPE",
502 "LANG",
503 NULL,
504 };
505
506 /* Android setlocale(category, "") doesn't check the environment variables
507 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
508 * check the environment variables listed in env_var_set. */
509 for (pvar=env_var_set; *pvar; pvar++) {
510 locale = getenv(*pvar);
511 if (locale != NULL && *locale != '\0') {
512 if (strcmp(locale, utf8_locale) == 0 ||
513 strcmp(locale, "en_US.UTF-8") == 0) {
514 return setlocale(category, utf8_locale);
515 }
516 return setlocale(category, "C");
517 }
518 }
519
520 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
521 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
522 * Quote from POSIX section "8.2 Internationalization Variables":
523 * "4. If the LANG environment variable is not set or is set to the empty
524 * string, the implementation-defined default locale shall be used." */
525
526#ifdef PY_COERCE_C_LOCALE
527 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
528 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
529 /* Some other ported code may check the environment variables (e.g. in
530 * extension modules), so we make sure that they match the locale
531 * configuration */
532 if (setenv("LC_CTYPE", utf8_locale, 1)) {
533 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
534 "environment variable to %s\n", utf8_locale);
535 }
536 }
537#endif
538 return setlocale(category, utf8_locale);
539#else /* __ANDROID__ */
540 return setlocale(category, "");
541#endif /* __ANDROID__ */
542}
543
Nick Coghlan6ea41862017-06-11 13:16:15 +1000544
Eric Snow1abcf672017-05-23 21:46:51 -0700545/* Global initializations. Can be undone by Py_Finalize(). Don't
546 call this twice without an intervening Py_Finalize() call.
547
Victor Stinner1dc6e392018-07-25 02:49:17 +0200548 Every call to _Py_InitializeCore, Py_Initialize or Py_InitializeEx
Eric Snow1abcf672017-05-23 21:46:51 -0700549 must have a corresponding call to Py_Finalize.
550
551 Locking: you must hold the interpreter lock while calling these APIs.
552 (If the lock has not yet been initialized, that's equivalent to
553 having the lock, but you cannot use multiple threads.)
554
555*/
556
Victor Stinner1dc6e392018-07-25 02:49:17 +0200557static _PyInitError
558_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
559 const _PyCoreConfig *core_config)
560{
561 if (core_config->allocator != NULL) {
562 const char *allocator = _PyMem_GetAllocatorsName();
563 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
564 return _Py_INIT_USER_ERR("cannot modify memory allocator "
565 "after first Py_Initialize()");
566 }
567 }
568
569 _PyCoreConfig_SetGlobalConfig(core_config);
570
571 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
572 return _Py_INIT_ERR("failed to copy core config");
573 }
574 core_config = &interp->core_config;
575
576 if (core_config->_install_importlib) {
577 _PyInitError err = _PyCoreConfig_SetPathConfig(core_config);
578 if (_Py_INIT_FAILED(err)) {
579 return err;
580 }
581 }
582 return _Py_INIT_OK();
583}
584
585
Eric Snow1abcf672017-05-23 21:46:51 -0700586/* Begin interpreter initialization
587 *
588 * On return, the first thread and interpreter state have been created,
589 * but the compiler, signal handling, multithreading and
590 * multiple interpreter support, and codec infrastructure are not yet
591 * available.
592 *
593 * The import system will support builtin and frozen modules only.
594 * The only supported io is writing to sys.stderr
595 *
596 * If any operation invoked by this function fails, a fatal error is
597 * issued and the function does not return.
598 *
599 * Any code invoked from this function should *not* assume it has access
600 * to the Python C API (unless the API is explicitly listed as being
601 * safe to call without calling Py_Initialize first)
Victor Stinner1dc6e392018-07-25 02:49:17 +0200602 *
603 * The caller is responsible to call _PyCoreConfig_Read().
Eric Snow1abcf672017-05-23 21:46:51 -0700604 */
605
Victor Stinner1dc6e392018-07-25 02:49:17 +0200606static _PyInitError
607_Py_InitializeCore_impl(PyInterpreterState **interp_p,
608 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000609{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200610 PyInterpreterState *interp;
611 _PyInitError err;
612
613 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
614 Py_Initialize() ignores the new configuration. */
615 if (_PyRuntime.core_initialized) {
616 PyThreadState *tstate = PyThreadState_GET();
617 if (!tstate) {
618 return _Py_INIT_ERR("failed to read thread state");
619 }
620
621 interp = tstate->interp;
622 if (interp == NULL) {
623 return _Py_INIT_ERR("can't make main interpreter");
624 }
625 *interp_p = interp;
626
627 return _Py_Initialize_ReconfigureCore(interp, core_config);
628 }
629
630 if (_PyRuntime.initialized) {
631 return _Py_INIT_ERR("main interpreter already initialized");
632 }
Victor Stinnerda273412017-12-15 01:46:02 +0100633
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200634 _PyCoreConfig_SetGlobalConfig(core_config);
Nick Coghland6009512014-11-20 21:39:37 +1000635
Victor Stinner1dc6e392018-07-25 02:49:17 +0200636 err = _PyRuntime_Initialize();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800637 if (_Py_INIT_FAILED(err)) {
638 return err;
639 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600640
Victor Stinner31e99082017-12-20 23:41:38 +0100641 if (core_config->allocator != NULL) {
642 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
643 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
644 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800645 }
646
Eric Snow1abcf672017-05-23 21:46:51 -0700647 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
648 * threads behave a little more gracefully at interpreter shutdown.
649 * We clobber it here so the new interpreter can start with a clean
650 * slate.
651 *
652 * However, this may still lead to misbehaviour if there are daemon
653 * threads still hanging around from a previous Py_Initialize/Finalize
654 * pair :(
655 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 _PyRuntime.finalizing = NULL;
657
Nick Coghlan6ea41862017-06-11 13:16:15 +1000658#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000659 /* Set up the LC_CTYPE locale, so we can obtain
660 the locale's charset without having to switch
661 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100662 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner94540602017-12-16 04:54:22 +0100663 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000664#endif
Nick Coghland6009512014-11-20 21:39:37 +1000665
Victor Stinnerda273412017-12-15 01:46:02 +0100666 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800667 if (_Py_INIT_FAILED(err)) {
668 return err;
669 }
670
Victor Stinnera7368ac2017-11-15 18:11:45 -0800671 err = _PyInterpreterState_Enable(&_PyRuntime);
672 if (_Py_INIT_FAILED(err)) {
673 return err;
674 }
675
Victor Stinner1dc6e392018-07-25 02:49:17 +0200676 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100677 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800678 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100679 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200680 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100681
682 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
683 return _Py_INIT_ERR("failed to copy core config");
684 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200685 core_config = &interp->core_config;
Nick Coghland6009512014-11-20 21:39:37 +1000686
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200687 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000688 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800689 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000690 (void) PyThreadState_Swap(tstate);
691
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000692 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000693 destroying the GIL might fail when it is being referenced from
694 another running thread (see issue #9901).
695 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000696 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000697 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100698
Nick Coghland6009512014-11-20 21:39:37 +1000699 /* Auto-thread-state API */
700 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000701
Victor Stinner2914bb32018-01-29 11:57:45 +0100702 /* Create the GIL */
703 PyEval_InitThreads();
704
Nick Coghland6009512014-11-20 21:39:37 +1000705 _Py_ReadyTypes();
706
Nick Coghland6009512014-11-20 21:39:37 +1000707 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800708 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000709
710 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800711 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000712
713 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800714 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000715
Eric Snowd393c1b2017-09-14 12:18:12 -0600716 PyObject *modules = PyDict_New();
717 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800718 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600719 interp->modules = modules;
720
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200721 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800722 err = _PySys_BeginInit(&sysmod);
723 if (_Py_INIT_FAILED(err)) {
724 return err;
725 }
726
Eric Snowd393c1b2017-09-14 12:18:12 -0600727 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800728 if (interp->sysdict == NULL) {
729 return _Py_INIT_ERR("can't initialize sys dict");
730 }
731
Eric Snowd393c1b2017-09-14 12:18:12 -0600732 Py_INCREF(interp->sysdict);
733 PyDict_SetItemString(interp->sysdict, "modules", modules);
734 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000735
736 /* Init Unicode implementation; relies on the codec registry */
737 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800738 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700739
Nick Coghland6009512014-11-20 21:39:37 +1000740 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800741 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000742
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200743 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000744 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800745 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600746 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000747 interp->builtins = PyModule_GetDict(bimod);
748 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800749 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000750 Py_INCREF(interp->builtins);
751
752 /* initialize builtin exceptions */
753 _PyExc_Init(bimod);
754
Nick Coghland6009512014-11-20 21:39:37 +1000755 /* Set up a preliminary stderr printer until we have enough
756 infrastructure for the io module in place. */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200757 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000758 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800759 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000760 _PySys_SetObjectId(&PyId_stderr, pstderr);
761 PySys_SetObject("__stderr__", pstderr);
762 Py_DECREF(pstderr);
763
Victor Stinner672b6ba2017-12-06 17:25:50 +0100764 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800765 if (_Py_INIT_FAILED(err)) {
766 return err;
767 }
Nick Coghland6009512014-11-20 21:39:37 +1000768
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800769 err = _PyImportHooks_Init();
770 if (_Py_INIT_FAILED(err)) {
771 return err;
772 }
Nick Coghland6009512014-11-20 21:39:37 +1000773
774 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100775 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100776 return _Py_INIT_ERR("can't initialize warnings");
777 }
Nick Coghland6009512014-11-20 21:39:37 +1000778
Yury Selivanovf23746a2018-01-22 19:11:18 -0500779 if (!_PyContext_Init())
780 return _Py_INIT_ERR("can't init context");
781
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200782 if (core_config->_install_importlib) {
Victor Stinnerb1147e42018-07-21 02:06:16 +0200783 err = _PyCoreConfig_SetPathConfig(core_config);
784 if (_Py_INIT_FAILED(err)) {
785 return err;
786 }
787 }
788
Eric Snow1abcf672017-05-23 21:46:51 -0700789 /* This call sets up builtin and frozen import support */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200790 if (core_config->_install_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800791 err = initimport(interp, sysmod);
792 if (_Py_INIT_FAILED(err)) {
793 return err;
794 }
Eric Snow1abcf672017-05-23 21:46:51 -0700795 }
796
797 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600798 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800799 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700800}
801
Victor Stinner1dc6e392018-07-25 02:49:17 +0200802_PyInitError
803_Py_InitializeCore(PyInterpreterState **interp_p,
804 const _PyCoreConfig *src_config)
805{
806 assert(src_config != NULL);
807
808
809 PyMemAllocatorEx old_alloc;
810 _PyInitError err;
811
812 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
813 (and the input configuration is read only). */
814 _PyCoreConfig config = _PyCoreConfig_INIT;
815
816 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
817 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
818 err = _PyCoreConfig_Read(&config);
819 }
820 else {
821 err = _Py_INIT_ERR("failed to copy core config");
822 }
823 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
824
825 if (_Py_INIT_FAILED(err)) {
826 goto done;
827 }
828
829 err = _Py_InitializeCore_impl(interp_p, &config);
830
831done:
832 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
833 _PyCoreConfig_Clear(&config);
834 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
835
836 return err;
837}
838
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200839/* Py_Initialize() has already been called: update the main interpreter
840 configuration. Example of bpo-34008: Py_Main() called after
841 Py_Initialize(). */
842static _PyInitError
843_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
844 const _PyMainInterpreterConfig *config)
845{
846 if (config->argv != NULL) {
847 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
848 if (res < 0) {
849 return _Py_INIT_ERR("fail to set sys.argv");
850 }
851 }
852 return _Py_INIT_OK();
853}
854
Eric Snowc7ec9982017-05-23 23:00:52 -0700855/* Update interpreter state based on supplied configuration settings
856 *
857 * After calling this function, most of the restrictions on the interpreter
858 * are lifted. The only remaining incomplete settings are those related
859 * to the main module (sys.argv[0], __main__ metadata)
860 *
861 * Calling this when the interpreter is not initializing, is already
862 * initialized or without a valid current thread state is a fatal error.
863 * Other errors should be reported as normal Python exceptions with a
864 * non-zero return code.
865 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800866_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200867_Py_InitializeMainInterpreter(PyInterpreterState *interp,
868 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700869{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600870 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800871 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700872 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700873
Victor Stinner1dc6e392018-07-25 02:49:17 +0200874 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100875 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
876 return _Py_INIT_ERR("failed to copy main interpreter config");
877 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200878 config = &interp->config;
879 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700880
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200881 if (_PyRuntime.initialized) {
882 return _Py_ReconfigureMainInterpreter(interp, config);
883 }
884
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200885 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700886 /* Special mode for freeze_importlib: run with no import system
887 *
888 * This means anything which needs support from extension modules
889 * or pure Python code in the standard library won't work.
890 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600891 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800892 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700893 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100894
Victor Stinner33c377e2017-12-05 15:12:41 +0100895 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800896 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100897 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200898
Victor Stinner41264f12017-12-15 02:05:29 +0100899 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800900 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100901 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800902
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200903 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800904 if (_Py_INIT_FAILED(err)) {
905 return err;
906 }
Nick Coghland6009512014-11-20 21:39:37 +1000907
908 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200909 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800910 if (_Py_INIT_FAILED(err)) {
911 return err;
912 }
Nick Coghland6009512014-11-20 21:39:37 +1000913
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800914 err = initfsencoding(interp);
915 if (_Py_INIT_FAILED(err)) {
916 return err;
917 }
Nick Coghland6009512014-11-20 21:39:37 +1000918
Victor Stinner1f151112017-11-23 10:43:14 +0100919 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800920 err = initsigs(); /* Signal handling stuff, including initintr() */
921 if (_Py_INIT_FAILED(err)) {
922 return err;
923 }
924 }
Nick Coghland6009512014-11-20 21:39:37 +1000925
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200926 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800927 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200928 }
Nick Coghland6009512014-11-20 21:39:37 +1000929
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 err = add_main_module(interp);
931 if (_Py_INIT_FAILED(err)) {
932 return err;
933 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800934
Victor Stinner91106cd2017-12-13 12:29:09 +0100935 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800936 if (_Py_INIT_FAILED(err)) {
937 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800938 }
Nick Coghland6009512014-11-20 21:39:37 +1000939
940 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100941 if (interp->config.warnoptions != NULL &&
942 PyList_Size(interp->config.warnoptions) > 0)
943 {
Nick Coghland6009512014-11-20 21:39:37 +1000944 PyObject *warnings_module = PyImport_ImportModule("warnings");
945 if (warnings_module == NULL) {
946 fprintf(stderr, "'import warnings' failed; traceback:\n");
947 PyErr_Print();
948 }
949 Py_XDECREF(warnings_module);
950 }
951
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600952 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700953
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200954 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800955 err = initsite(); /* Module site */
956 if (_Py_INIT_FAILED(err)) {
957 return err;
958 }
959 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800960 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000961}
962
Eric Snowc7ec9982017-05-23 23:00:52 -0700963#undef _INIT_DEBUG_PRINT
964
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800965_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200966_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700967{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200968 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200970 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800971 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200972 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800973 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200974 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100975
Victor Stinner9cfc0022017-12-20 19:36:46 +0100976 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200977 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100978 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200979 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800980 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100981 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800982 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200983 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800984 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200985 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700986}
987
988
989void
Nick Coghland6009512014-11-20 21:39:37 +1000990Py_InitializeEx(int install_sigs)
991{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200992 if (_PyRuntime.initialized) {
993 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
994 return;
995 }
996
997 _PyInitError err;
998 _PyCoreConfig config = _PyCoreConfig_INIT;
999 config.install_signal_handlers = install_sigs;
1000
1001 err = _Py_InitializeFromConfig(&config);
1002 _PyCoreConfig_Clear(&config);
1003
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001004 if (_Py_INIT_FAILED(err)) {
1005 _Py_FatalInitError(err);
1006 }
Nick Coghland6009512014-11-20 21:39:37 +10001007}
1008
1009void
1010Py_Initialize(void)
1011{
1012 Py_InitializeEx(1);
1013}
1014
1015
1016#ifdef COUNT_ALLOCS
1017extern void dump_counts(FILE*);
1018#endif
1019
1020/* Flush stdout and stderr */
1021
1022static int
1023file_is_closed(PyObject *fobj)
1024{
1025 int r;
1026 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1027 if (tmp == NULL) {
1028 PyErr_Clear();
1029 return 0;
1030 }
1031 r = PyObject_IsTrue(tmp);
1032 Py_DECREF(tmp);
1033 if (r < 0)
1034 PyErr_Clear();
1035 return r > 0;
1036}
1037
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001038static int
Nick Coghland6009512014-11-20 21:39:37 +10001039flush_std_files(void)
1040{
1041 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1042 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1043 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001044 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001045
1046 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001047 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001048 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001049 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001050 status = -1;
1051 }
Nick Coghland6009512014-11-20 21:39:37 +10001052 else
1053 Py_DECREF(tmp);
1054 }
1055
1056 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001057 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001058 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001059 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001060 status = -1;
1061 }
Nick Coghland6009512014-11-20 21:39:37 +10001062 else
1063 Py_DECREF(tmp);
1064 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001065
1066 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001067}
1068
1069/* Undo the effect of Py_Initialize().
1070
1071 Beware: if multiple interpreter and/or thread states exist, these
1072 are not wiped out; only the current thread and interpreter state
1073 are deleted. But since everything else is deleted, those other
1074 interpreter and thread states should no longer be used.
1075
1076 (XXX We should do better, e.g. wipe out all interpreters and
1077 threads.)
1078
1079 Locking: as above.
1080
1081*/
1082
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001083int
1084Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001085{
1086 PyInterpreterState *interp;
1087 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001088 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001089
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001090 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001091 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001092
1093 wait_for_thread_shutdown();
1094
Marcel Plch776407f2017-12-20 11:17:58 +01001095 /* Get current thread state and interpreter pointer */
1096 tstate = PyThreadState_GET();
1097 interp = tstate->interp;
1098
Nick Coghland6009512014-11-20 21:39:37 +10001099 /* The interpreter is still entirely intact at this point, and the
1100 * exit funcs may be relying on that. In particular, if some thread
1101 * or exit func is still waiting to do an import, the import machinery
1102 * expects Py_IsInitialized() to return true. So don't say the
1103 * interpreter is uninitialized until after the exit funcs have run.
1104 * Note that Threading.py uses an exit func to do a join on all the
1105 * threads created thru it, so this also protects pending imports in
1106 * the threads created via Threading.
1107 */
Nick Coghland6009512014-11-20 21:39:37 +10001108
Marcel Plch776407f2017-12-20 11:17:58 +01001109 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001110
Victor Stinnerda273412017-12-15 01:46:02 +01001111 /* Copy the core config, PyInterpreterState_Delete() free
1112 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001113#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001114 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001115#endif
1116#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001117 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001118#endif
1119#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001120 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001121#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001122
Nick Coghland6009512014-11-20 21:39:37 +10001123 /* Remaining threads (e.g. daemon threads) will automatically exit
1124 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001125 _PyRuntime.finalizing = tstate;
1126 _PyRuntime.initialized = 0;
1127 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001128
Victor Stinnere0deff32015-03-24 13:46:18 +01001129 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001130 if (flush_std_files() < 0) {
1131 status = -1;
1132 }
Nick Coghland6009512014-11-20 21:39:37 +10001133
1134 /* Disable signal handling */
1135 PyOS_FiniInterrupts();
1136
1137 /* Collect garbage. This may call finalizers; it's nice to call these
1138 * before all modules are destroyed.
1139 * XXX If a __del__ or weakref callback is triggered here, and tries to
1140 * XXX import a module, bad things can happen, because Python no
1141 * XXX longer believes it's initialized.
1142 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1143 * XXX is easy to provoke that way. I've also seen, e.g.,
1144 * XXX Exception exceptions.ImportError: 'No module named sha'
1145 * XXX in <function callback at 0x008F5718> ignored
1146 * XXX but I'm unclear on exactly how that one happens. In any case,
1147 * XXX I haven't seen a real-life report of either of these.
1148 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001149 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001150#ifdef COUNT_ALLOCS
1151 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1152 each collection might release some types from the type
1153 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001154 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001155 /* nothing */;
1156#endif
Eric Snowdae02762017-09-14 00:35:58 -07001157
Nick Coghland6009512014-11-20 21:39:37 +10001158 /* Destroy all modules */
1159 PyImport_Cleanup();
1160
Victor Stinnere0deff32015-03-24 13:46:18 +01001161 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001162 if (flush_std_files() < 0) {
1163 status = -1;
1164 }
Nick Coghland6009512014-11-20 21:39:37 +10001165
1166 /* Collect final garbage. This disposes of cycles created by
1167 * class definitions, for example.
1168 * XXX This is disabled because it caused too many problems. If
1169 * XXX a __del__ or weakref callback triggers here, Python code has
1170 * XXX a hard time running, because even the sys module has been
1171 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1172 * XXX One symptom is a sequence of information-free messages
1173 * XXX coming from threads (if a __del__ or callback is invoked,
1174 * XXX other threads can execute too, and any exception they encounter
1175 * XXX triggers a comedy of errors as subsystem after subsystem
1176 * XXX fails to find what it *expects* to find in sys to help report
1177 * XXX the exception and consequent unexpected failures). I've also
1178 * XXX seen segfaults then, after adding print statements to the
1179 * XXX Python code getting called.
1180 */
1181#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001182 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001183#endif
1184
1185 /* Disable tracemalloc after all Python objects have been destroyed,
1186 so it is possible to use tracemalloc in objects destructor. */
1187 _PyTraceMalloc_Fini();
1188
1189 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1190 _PyImport_Fini();
1191
1192 /* Cleanup typeobject.c's internal caches. */
1193 _PyType_Fini();
1194
1195 /* unload faulthandler module */
1196 _PyFaulthandler_Fini();
1197
1198 /* Debugging stuff */
1199#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001200 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001201#endif
1202 /* dump hash stats */
1203 _PyHash_Fini();
1204
Eric Snowdae02762017-09-14 00:35:58 -07001205#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001206 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001207 _PyDebug_PrintTotalRefs();
1208 }
Eric Snowdae02762017-09-14 00:35:58 -07001209#endif
Nick Coghland6009512014-11-20 21:39:37 +10001210
1211#ifdef Py_TRACE_REFS
1212 /* Display all objects still alive -- this can invoke arbitrary
1213 * __repr__ overrides, so requires a mostly-intact interpreter.
1214 * Alas, a lot of stuff may still be alive now that will be cleaned
1215 * up later.
1216 */
Victor Stinnerda273412017-12-15 01:46:02 +01001217 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001218 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001219 }
Nick Coghland6009512014-11-20 21:39:37 +10001220#endif /* Py_TRACE_REFS */
1221
1222 /* Clear interpreter state and all thread states. */
1223 PyInterpreterState_Clear(interp);
1224
1225 /* Now we decref the exception classes. After this point nothing
1226 can raise an exception. That's okay, because each Fini() method
1227 below has been checked to make sure no exceptions are ever
1228 raised.
1229 */
1230
1231 _PyExc_Fini();
1232
1233 /* Sundry finalizers */
1234 PyMethod_Fini();
1235 PyFrame_Fini();
1236 PyCFunction_Fini();
1237 PyTuple_Fini();
1238 PyList_Fini();
1239 PySet_Fini();
1240 PyBytes_Fini();
1241 PyByteArray_Fini();
1242 PyLong_Fini();
1243 PyFloat_Fini();
1244 PyDict_Fini();
1245 PySlice_Fini();
1246 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001247 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001248 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001249 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001250 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001251
1252 /* Cleanup Unicode implementation */
1253 _PyUnicode_Fini();
1254
1255 /* reset file system default encoding */
1256 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1257 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1258 Py_FileSystemDefaultEncoding = NULL;
1259 }
1260
1261 /* XXX Still allocated:
1262 - various static ad-hoc pointers to interned strings
1263 - int and float free list blocks
1264 - whatever various modules and libraries allocate
1265 */
1266
1267 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1268
1269 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001270 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001271
1272 /* Delete current thread. After this, many C API calls become crashy. */
1273 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001274
Nick Coghland6009512014-11-20 21:39:37 +10001275 PyInterpreterState_Delete(interp);
1276
1277#ifdef Py_TRACE_REFS
1278 /* Display addresses (& refcnts) of all objects still alive.
1279 * An address can be used to find the repr of the object, printed
1280 * above by _Py_PrintReferences.
1281 */
Victor Stinnerda273412017-12-15 01:46:02 +01001282 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001283 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001284 }
Nick Coghland6009512014-11-20 21:39:37 +10001285#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001286#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001287 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001288 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001289 }
Nick Coghland6009512014-11-20 21:39:37 +10001290#endif
1291
1292 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001293
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001294 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001295 return status;
1296}
1297
1298void
1299Py_Finalize(void)
1300{
1301 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001302}
1303
1304/* Create and initialize a new interpreter and thread, and return the
1305 new thread. This requires that Py_Initialize() has been called
1306 first.
1307
1308 Unsuccessful initialization yields a NULL pointer. Note that *no*
1309 exception information is available even in this case -- the
1310 exception information is held in the thread, and there is no
1311 thread.
1312
1313 Locking: as above.
1314
1315*/
1316
Victor Stinnera7368ac2017-11-15 18:11:45 -08001317static _PyInitError
1318new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001319{
1320 PyInterpreterState *interp;
1321 PyThreadState *tstate, *save_tstate;
1322 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001323 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001324
Victor Stinnera7368ac2017-11-15 18:11:45 -08001325 if (!_PyRuntime.initialized) {
1326 return _Py_INIT_ERR("Py_Initialize must be called first");
1327 }
Nick Coghland6009512014-11-20 21:39:37 +10001328
Victor Stinner8a1be612016-03-14 22:07:55 +01001329 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1330 interpreters: disable PyGILState_Check(). */
1331 _PyGILState_check_enabled = 0;
1332
Nick Coghland6009512014-11-20 21:39:37 +10001333 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001334 if (interp == NULL) {
1335 *tstate_p = NULL;
1336 return _Py_INIT_OK();
1337 }
Nick Coghland6009512014-11-20 21:39:37 +10001338
1339 tstate = PyThreadState_New(interp);
1340 if (tstate == NULL) {
1341 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001342 *tstate_p = NULL;
1343 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001344 }
1345
1346 save_tstate = PyThreadState_Swap(tstate);
1347
Eric Snow1abcf672017-05-23 21:46:51 -07001348 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001349 _PyCoreConfig *core_config;
1350 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001351 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001352 core_config = &save_tstate->interp->core_config;
1353 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001354 } else {
1355 /* No current thread state, copy from the main interpreter */
1356 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001357 core_config = &main_interp->core_config;
1358 config = &main_interp->config;
1359 }
1360
1361 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1362 return _Py_INIT_ERR("failed to copy core config");
1363 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001364 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001365 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1366 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001367 }
1368
Nick Coghland6009512014-11-20 21:39:37 +10001369 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001370 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001371 if (modules == NULL) {
1372 return _Py_INIT_ERR("can't make modules dictionary");
1373 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001374 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001375
Eric Snowd393c1b2017-09-14 12:18:12 -06001376 sysmod = _PyImport_FindBuiltin("sys", modules);
1377 if (sysmod != NULL) {
1378 interp->sysdict = PyModule_GetDict(sysmod);
1379 if (interp->sysdict == NULL)
1380 goto handle_error;
1381 Py_INCREF(interp->sysdict);
1382 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001383 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001384 }
1385
1386 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001387 if (bimod != NULL) {
1388 interp->builtins = PyModule_GetDict(bimod);
1389 if (interp->builtins == NULL)
1390 goto handle_error;
1391 Py_INCREF(interp->builtins);
1392 }
1393
1394 /* initialize builtin exceptions */
1395 _PyExc_Init(bimod);
1396
Nick Coghland6009512014-11-20 21:39:37 +10001397 if (bimod != NULL && sysmod != NULL) {
1398 PyObject *pstderr;
1399
Nick Coghland6009512014-11-20 21:39:37 +10001400 /* Set up a preliminary stderr printer until we have enough
1401 infrastructure for the io module in place. */
1402 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001403 if (pstderr == NULL) {
1404 return _Py_INIT_ERR("can't set preliminary stderr");
1405 }
Nick Coghland6009512014-11-20 21:39:37 +10001406 _PySys_SetObjectId(&PyId_stderr, pstderr);
1407 PySys_SetObject("__stderr__", pstderr);
1408 Py_DECREF(pstderr);
1409
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001410 err = _PyImportHooks_Init();
1411 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001412 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001413 }
Nick Coghland6009512014-11-20 21:39:37 +10001414
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001415 err = initimport(interp, sysmod);
1416 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001417 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001418 }
Nick Coghland6009512014-11-20 21:39:37 +10001419
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001420 err = initexternalimport(interp);
1421 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001422 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001423 }
Nick Coghland6009512014-11-20 21:39:37 +10001424
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001425 err = initfsencoding(interp);
1426 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001427 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001428 }
1429
Victor Stinner91106cd2017-12-13 12:29:09 +01001430 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001431 if (_Py_INIT_FAILED(err)) {
1432 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001433 }
1434
1435 err = add_main_module(interp);
1436 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001437 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001438 }
1439
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001440 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001441 err = initsite();
1442 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001443 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001444 }
1445 }
Nick Coghland6009512014-11-20 21:39:37 +10001446 }
1447
Victor Stinnera7368ac2017-11-15 18:11:45 -08001448 if (PyErr_Occurred()) {
1449 goto handle_error;
1450 }
Nick Coghland6009512014-11-20 21:39:37 +10001451
Victor Stinnera7368ac2017-11-15 18:11:45 -08001452 *tstate_p = tstate;
1453 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001454
Nick Coghland6009512014-11-20 21:39:37 +10001455handle_error:
1456 /* Oops, it didn't work. Undo it all. */
1457
1458 PyErr_PrintEx(0);
1459 PyThreadState_Clear(tstate);
1460 PyThreadState_Swap(save_tstate);
1461 PyThreadState_Delete(tstate);
1462 PyInterpreterState_Delete(interp);
1463
Victor Stinnera7368ac2017-11-15 18:11:45 -08001464 *tstate_p = NULL;
1465 return _Py_INIT_OK();
1466}
1467
1468PyThreadState *
1469Py_NewInterpreter(void)
1470{
1471 PyThreadState *tstate;
1472 _PyInitError err = new_interpreter(&tstate);
1473 if (_Py_INIT_FAILED(err)) {
1474 _Py_FatalInitError(err);
1475 }
1476 return tstate;
1477
Nick Coghland6009512014-11-20 21:39:37 +10001478}
1479
1480/* Delete an interpreter and its last thread. This requires that the
1481 given thread state is current, that the thread has no remaining
1482 frames, and that it is its interpreter's only remaining thread.
1483 It is a fatal error to violate these constraints.
1484
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001485 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001486 everything, regardless.)
1487
1488 Locking: as above.
1489
1490*/
1491
1492void
1493Py_EndInterpreter(PyThreadState *tstate)
1494{
1495 PyInterpreterState *interp = tstate->interp;
1496
1497 if (tstate != PyThreadState_GET())
1498 Py_FatalError("Py_EndInterpreter: thread is not current");
1499 if (tstate->frame != NULL)
1500 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1501
1502 wait_for_thread_shutdown();
1503
Marcel Plch776407f2017-12-20 11:17:58 +01001504 call_py_exitfuncs(interp);
1505
Nick Coghland6009512014-11-20 21:39:37 +10001506 if (tstate != interp->tstate_head || tstate->next != NULL)
1507 Py_FatalError("Py_EndInterpreter: not the last thread");
1508
1509 PyImport_Cleanup();
1510 PyInterpreterState_Clear(interp);
1511 PyThreadState_Swap(NULL);
1512 PyInterpreterState_Delete(interp);
1513}
1514
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001515/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001516
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001517static _PyInitError
1518add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001519{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001520 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001521 m = PyImport_AddModule("__main__");
1522 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001523 return _Py_INIT_ERR("can't create __main__ module");
1524
Nick Coghland6009512014-11-20 21:39:37 +10001525 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001526 ann_dict = PyDict_New();
1527 if ((ann_dict == NULL) ||
1528 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001529 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001530 }
1531 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001532
Nick Coghland6009512014-11-20 21:39:37 +10001533 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1534 PyObject *bimod = PyImport_ImportModule("builtins");
1535 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001536 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001537 }
1538 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001539 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001540 }
1541 Py_DECREF(bimod);
1542 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001543
Nick Coghland6009512014-11-20 21:39:37 +10001544 /* Main is a little special - imp.is_builtin("__main__") will return
1545 * False, but BuiltinImporter is still the most appropriate initial
1546 * setting for its __loader__ attribute. A more suitable value will
1547 * be set if __main__ gets further initialized later in the startup
1548 * process.
1549 */
1550 loader = PyDict_GetItemString(d, "__loader__");
1551 if (loader == NULL || loader == Py_None) {
1552 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1553 "BuiltinImporter");
1554 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001555 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001556 }
1557 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001558 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001559 }
1560 Py_DECREF(loader);
1561 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001562 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001563}
1564
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001565static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001566initfsencoding(PyInterpreterState *interp)
1567{
1568 PyObject *codec;
1569
Steve Dowercc16be82016-09-08 10:35:16 -07001570#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001571 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001572 Py_FileSystemDefaultEncoding = "mbcs";
1573 Py_FileSystemDefaultEncodeErrors = "replace";
1574 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001575 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001576 Py_FileSystemDefaultEncoding = "utf-8";
1577 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1578 }
1579#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001580 if (Py_FileSystemDefaultEncoding == NULL &&
1581 interp->core_config.utf8_mode)
1582 {
1583 Py_FileSystemDefaultEncoding = "utf-8";
1584 Py_HasFileSystemDefaultEncoding = 1;
1585 }
1586 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001587 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001588 if (Py_FileSystemDefaultEncoding == NULL) {
1589 return _Py_INIT_ERR("Unable to get the locale encoding");
1590 }
Nick Coghland6009512014-11-20 21:39:37 +10001591
1592 Py_HasFileSystemDefaultEncoding = 0;
1593 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001594 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001595 }
Steve Dowercc16be82016-09-08 10:35:16 -07001596#endif
Nick Coghland6009512014-11-20 21:39:37 +10001597
1598 /* the encoding is mbcs, utf-8 or ascii */
1599 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1600 if (!codec) {
1601 /* Such error can only occurs in critical situations: no more
1602 * memory, import a module of the standard library failed,
1603 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001604 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001605 }
1606 Py_DECREF(codec);
1607 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001608 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001609}
1610
1611/* Import the site module (not into __main__ though) */
1612
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001613static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001614initsite(void)
1615{
1616 PyObject *m;
1617 m = PyImport_ImportModule("site");
1618 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001619 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001620 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001621 Py_DECREF(m);
1622 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001623}
1624
Victor Stinner874dbe82015-09-04 17:29:57 +02001625/* Check if a file descriptor is valid or not.
1626 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1627static int
1628is_valid_fd(int fd)
1629{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001630#ifdef __APPLE__
1631 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1632 and the other side of the pipe is closed, dup(1) succeed, whereas
1633 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1634 such error. */
1635 struct stat st;
1636 return (fstat(fd, &st) == 0);
1637#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001638 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001639 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001640 return 0;
1641 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001642 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1643 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1644 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001645 fd2 = dup(fd);
1646 if (fd2 >= 0)
1647 close(fd2);
1648 _Py_END_SUPPRESS_IPH
1649 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001650#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001651}
1652
1653/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001654static PyObject*
1655create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001656 int fd, int write_mode, const char* name,
1657 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001658{
1659 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1660 const char* mode;
1661 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001662 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001663 int buffering, isatty;
1664 _Py_IDENTIFIER(open);
1665 _Py_IDENTIFIER(isatty);
1666 _Py_IDENTIFIER(TextIOWrapper);
1667 _Py_IDENTIFIER(mode);
1668
Victor Stinner874dbe82015-09-04 17:29:57 +02001669 if (!is_valid_fd(fd))
1670 Py_RETURN_NONE;
1671
Nick Coghland6009512014-11-20 21:39:37 +10001672 /* stdin is always opened in buffered mode, first because it shouldn't
1673 make a difference in common use cases, second because TextIOWrapper
1674 depends on the presence of a read1() method which only exists on
1675 buffered streams.
1676 */
1677 if (Py_UnbufferedStdioFlag && write_mode)
1678 buffering = 0;
1679 else
1680 buffering = -1;
1681 if (write_mode)
1682 mode = "wb";
1683 else
1684 mode = "rb";
1685 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1686 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001687 Py_None, Py_None, /* encoding, errors */
1688 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001689 if (buf == NULL)
1690 goto error;
1691
1692 if (buffering) {
1693 _Py_IDENTIFIER(raw);
1694 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1695 if (raw == NULL)
1696 goto error;
1697 }
1698 else {
1699 raw = buf;
1700 Py_INCREF(raw);
1701 }
1702
Steve Dower39294992016-08-30 21:22:36 -07001703#ifdef MS_WINDOWS
1704 /* Windows console IO is always UTF-8 encoded */
1705 if (PyWindowsConsoleIO_Check(raw))
1706 encoding = "utf-8";
1707#endif
1708
Nick Coghland6009512014-11-20 21:39:37 +10001709 text = PyUnicode_FromString(name);
1710 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1711 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001712 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001713 if (res == NULL)
1714 goto error;
1715 isatty = PyObject_IsTrue(res);
1716 Py_DECREF(res);
1717 if (isatty == -1)
1718 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001719 if (Py_UnbufferedStdioFlag)
1720 write_through = Py_True;
1721 else
1722 write_through = Py_False;
1723 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001724 line_buffering = Py_True;
1725 else
1726 line_buffering = Py_False;
1727
1728 Py_CLEAR(raw);
1729 Py_CLEAR(text);
1730
1731#ifdef MS_WINDOWS
1732 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1733 newlines to "\n".
1734 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1735 newline = NULL;
1736#else
1737 /* sys.stdin: split lines at "\n".
1738 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1739 newline = "\n";
1740#endif
1741
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001742 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001743 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001744 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001745 Py_CLEAR(buf);
1746 if (stream == NULL)
1747 goto error;
1748
1749 if (write_mode)
1750 mode = "w";
1751 else
1752 mode = "r";
1753 text = PyUnicode_FromString(mode);
1754 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1755 goto error;
1756 Py_CLEAR(text);
1757 return stream;
1758
1759error:
1760 Py_XDECREF(buf);
1761 Py_XDECREF(stream);
1762 Py_XDECREF(text);
1763 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001764
Victor Stinner874dbe82015-09-04 17:29:57 +02001765 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1766 /* Issue #24891: the file descriptor was closed after the first
1767 is_valid_fd() check was called. Ignore the OSError and set the
1768 stream to None. */
1769 PyErr_Clear();
1770 Py_RETURN_NONE;
1771 }
1772 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001773}
1774
1775/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001776static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001777init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001778{
1779 PyObject *iomod = NULL, *wrapper;
1780 PyObject *bimod = NULL;
1781 PyObject *m;
1782 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001783 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001784 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001785 char *pythonioencoding = NULL;
1786 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001787 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001788
1789 /* Hack to avoid a nasty recursion issue when Python is invoked
1790 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1791 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1792 goto error;
1793 }
1794 Py_DECREF(m);
1795
1796 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1797 goto error;
1798 }
1799 Py_DECREF(m);
1800
1801 if (!(bimod = PyImport_ImportModule("builtins"))) {
1802 goto error;
1803 }
1804
1805 if (!(iomod = PyImport_ImportModule("io"))) {
1806 goto error;
1807 }
1808 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1809 goto error;
1810 }
1811
1812 /* Set builtins.open */
1813 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1814 Py_DECREF(wrapper);
1815 goto error;
1816 }
1817 Py_DECREF(wrapper);
1818
1819 encoding = _Py_StandardStreamEncoding;
1820 errors = _Py_StandardStreamErrors;
1821 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001822 char *opt = Py_GETENV("PYTHONIOENCODING");
1823 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001824 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001825 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001826 if (pythonioencoding == NULL) {
1827 PyErr_NoMemory();
1828 goto error;
1829 }
1830 err = strchr(pythonioencoding, ':');
1831 if (err) {
1832 *err = '\0';
1833 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001834 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001835 errors = err;
1836 }
1837 }
1838 if (*pythonioencoding && !encoding) {
1839 encoding = pythonioencoding;
1840 }
1841 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001842 else if (interp->core_config.utf8_mode) {
1843 encoding = "utf-8";
1844 errors = "surrogateescape";
1845 }
1846
1847 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001848 /* Choose the default error handler based on the current locale */
1849 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001850 }
Nick Coghland6009512014-11-20 21:39:37 +10001851 }
1852
1853 /* Set sys.stdin */
1854 fd = fileno(stdin);
1855 /* Under some conditions stdin, stdout and stderr may not be connected
1856 * and fileno() may point to an invalid file descriptor. For example
1857 * GUI apps don't have valid standard streams by default.
1858 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001859 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1860 if (std == NULL)
1861 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001862 PySys_SetObject("__stdin__", std);
1863 _PySys_SetObjectId(&PyId_stdin, std);
1864 Py_DECREF(std);
1865
1866 /* Set sys.stdout */
1867 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001868 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1869 if (std == NULL)
1870 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001871 PySys_SetObject("__stdout__", std);
1872 _PySys_SetObjectId(&PyId_stdout, std);
1873 Py_DECREF(std);
1874
1875#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1876 /* Set sys.stderr, replaces the preliminary stderr */
1877 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001878 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1879 if (std == NULL)
1880 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001881
1882 /* Same as hack above, pre-import stderr's codec to avoid recursion
1883 when import.c tries to write to stderr in verbose mode. */
1884 encoding_attr = PyObject_GetAttrString(std, "encoding");
1885 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001886 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001887 if (std_encoding != NULL) {
1888 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1889 Py_XDECREF(codec_info);
1890 }
1891 Py_DECREF(encoding_attr);
1892 }
1893 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1894
1895 if (PySys_SetObject("__stderr__", std) < 0) {
1896 Py_DECREF(std);
1897 goto error;
1898 }
1899 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1900 Py_DECREF(std);
1901 goto error;
1902 }
1903 Py_DECREF(std);
1904#endif
1905
Victor Stinnera7368ac2017-11-15 18:11:45 -08001906 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001907
Victor Stinnera7368ac2017-11-15 18:11:45 -08001908error:
1909 res = _Py_INIT_ERR("can't initialize sys standard streams");
1910
Victor Stinner31e99082017-12-20 23:41:38 +01001911 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1912 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001913done:
Victor Stinner31e99082017-12-20 23:41:38 +01001914 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1915
Nick Coghland6009512014-11-20 21:39:37 +10001916 /* We won't need them anymore. */
1917 if (_Py_StandardStreamEncoding) {
1918 PyMem_RawFree(_Py_StandardStreamEncoding);
1919 _Py_StandardStreamEncoding = NULL;
1920 }
1921 if (_Py_StandardStreamErrors) {
1922 PyMem_RawFree(_Py_StandardStreamErrors);
1923 _Py_StandardStreamErrors = NULL;
1924 }
Victor Stinner31e99082017-12-20 23:41:38 +01001925
1926 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1927
Nick Coghland6009512014-11-20 21:39:37 +10001928 PyMem_Free(pythonioencoding);
1929 Py_XDECREF(bimod);
1930 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001931 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001932}
1933
1934
Victor Stinner10dc4842015-03-24 12:01:30 +01001935static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001936_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001937{
Victor Stinner10dc4842015-03-24 12:01:30 +01001938 fputc('\n', stderr);
1939 fflush(stderr);
1940
1941 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001942 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001943}
Victor Stinner791da1c2016-03-14 16:53:12 +01001944
1945/* Print the current exception (if an exception is set) with its traceback,
1946 or display the current Python stack.
1947
1948 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1949 called on catastrophic cases.
1950
1951 Return 1 if the traceback was displayed, 0 otherwise. */
1952
1953static int
1954_Py_FatalError_PrintExc(int fd)
1955{
1956 PyObject *ferr, *res;
1957 PyObject *exception, *v, *tb;
1958 int has_tb;
1959
1960 if (PyThreadState_GET() == NULL) {
1961 /* The GIL is released: trying to acquire it is likely to deadlock,
1962 just give up. */
1963 return 0;
1964 }
1965
1966 PyErr_Fetch(&exception, &v, &tb);
1967 if (exception == NULL) {
1968 /* No current exception */
1969 return 0;
1970 }
1971
1972 ferr = _PySys_GetObjectId(&PyId_stderr);
1973 if (ferr == NULL || ferr == Py_None) {
1974 /* sys.stderr is not set yet or set to None,
1975 no need to try to display the exception */
1976 return 0;
1977 }
1978
1979 PyErr_NormalizeException(&exception, &v, &tb);
1980 if (tb == NULL) {
1981 tb = Py_None;
1982 Py_INCREF(tb);
1983 }
1984 PyException_SetTraceback(v, tb);
1985 if (exception == NULL) {
1986 /* PyErr_NormalizeException() failed */
1987 return 0;
1988 }
1989
1990 has_tb = (tb != Py_None);
1991 PyErr_Display(exception, v, tb);
1992 Py_XDECREF(exception);
1993 Py_XDECREF(v);
1994 Py_XDECREF(tb);
1995
1996 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001997 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001998 if (res == NULL)
1999 PyErr_Clear();
2000 else
2001 Py_DECREF(res);
2002
2003 return has_tb;
2004}
2005
Nick Coghland6009512014-11-20 21:39:37 +10002006/* Print fatal error message and abort */
2007
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002008#ifdef MS_WINDOWS
2009static void
2010fatal_output_debug(const char *msg)
2011{
2012 /* buffer of 256 bytes allocated on the stack */
2013 WCHAR buffer[256 / sizeof(WCHAR)];
2014 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2015 size_t msglen;
2016
2017 OutputDebugStringW(L"Fatal Python error: ");
2018
2019 msglen = strlen(msg);
2020 while (msglen) {
2021 size_t i;
2022
2023 if (buflen > msglen) {
2024 buflen = msglen;
2025 }
2026
2027 /* Convert the message to wchar_t. This uses a simple one-to-one
2028 conversion, assuming that the this error message actually uses
2029 ASCII only. If this ceases to be true, we will have to convert. */
2030 for (i=0; i < buflen; ++i) {
2031 buffer[i] = msg[i];
2032 }
2033 buffer[i] = L'\0';
2034 OutputDebugStringW(buffer);
2035
2036 msg += buflen;
2037 msglen -= buflen;
2038 }
2039 OutputDebugStringW(L"\n");
2040}
2041#endif
2042
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002043static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002044fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002045{
2046 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002047 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002048
2049 if (reentrant) {
2050 /* Py_FatalError() caused a second fatal error.
2051 Example: flush_std_files() raises a recursion error. */
2052 goto exit;
2053 }
2054 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002055
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002056 fprintf(stderr, "Fatal Python error: ");
2057 if (prefix) {
2058 fputs(prefix, stderr);
2059 fputs(": ", stderr);
2060 }
2061 if (msg) {
2062 fputs(msg, stderr);
2063 }
2064 else {
2065 fprintf(stderr, "<message not set>");
2066 }
2067 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002068 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002069
Victor Stinnere0deff32015-03-24 13:46:18 +01002070 /* Print the exception (if an exception is set) with its traceback,
2071 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002072 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002073 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002074 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002075
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002076 /* The main purpose of faulthandler is to display the traceback.
2077 This function already did its best to display a traceback.
2078 Disable faulthandler to prevent writing a second traceback
2079 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002080 _PyFaulthandler_Fini();
2081
Victor Stinner791da1c2016-03-14 16:53:12 +01002082 /* Check if the current Python thread hold the GIL */
2083 if (PyThreadState_GET() != NULL) {
2084 /* Flush sys.stdout and sys.stderr */
2085 flush_std_files();
2086 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002087
Nick Coghland6009512014-11-20 21:39:37 +10002088#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002089 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002090#endif /* MS_WINDOWS */
2091
2092exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002093 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002094#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002095 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002096#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002097 abort();
2098 }
2099 else {
2100 exit(status);
2101 }
2102}
2103
Victor Stinner19760862017-12-20 01:41:59 +01002104void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002105Py_FatalError(const char *msg)
2106{
2107 fatal_error(NULL, msg, -1);
2108}
2109
Victor Stinner19760862017-12-20 01:41:59 +01002110void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002111_Py_FatalInitError(_PyInitError err)
2112{
2113 /* On "user" error: exit with status 1.
2114 For all other errors, call abort(). */
2115 int status = err.user_err ? 1 : -1;
2116 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002117}
2118
2119/* Clean up and exit */
2120
Victor Stinnerd7292b52016-06-17 12:29:00 +02002121# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002122
Nick Coghland6009512014-11-20 21:39:37 +10002123/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002124void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002125{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002126 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002127
Antoine Pitroufc5db952017-12-13 02:29:07 +01002128 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002129 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2130
2131 is->pyexitfunc = func;
2132 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002133}
2134
2135static void
Marcel Plch776407f2017-12-20 11:17:58 +01002136call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002137{
Marcel Plch776407f2017-12-20 11:17:58 +01002138 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002139 return;
2140
Marcel Plch776407f2017-12-20 11:17:58 +01002141 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002142 PyErr_Clear();
2143}
2144
2145/* Wait until threading._shutdown completes, provided
2146 the threading module was imported in the first place.
2147 The shutdown routine will wait until all non-daemon
2148 "threading" threads have completed. */
2149static void
2150wait_for_thread_shutdown(void)
2151{
Nick Coghland6009512014-11-20 21:39:37 +10002152 _Py_IDENTIFIER(_shutdown);
2153 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002154 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002155 if (threading == NULL) {
2156 /* threading not imported */
2157 PyErr_Clear();
2158 return;
2159 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002160 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002161 if (result == NULL) {
2162 PyErr_WriteUnraisable(threading);
2163 }
2164 else {
2165 Py_DECREF(result);
2166 }
2167 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002168}
2169
2170#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002171int Py_AtExit(void (*func)(void))
2172{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002173 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002174 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002175 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002176 return 0;
2177}
2178
2179static void
2180call_ll_exitfuncs(void)
2181{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002182 while (_PyRuntime.nexitfuncs > 0)
2183 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002184
2185 fflush(stdout);
2186 fflush(stderr);
2187}
2188
Victor Stinnercfc88312018-08-01 16:41:25 +02002189void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002190Py_Exit(int sts)
2191{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002192 if (Py_FinalizeEx() < 0) {
2193 sts = 120;
2194 }
Nick Coghland6009512014-11-20 21:39:37 +10002195
2196 exit(sts);
2197}
2198
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002199static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002200initsigs(void)
2201{
2202#ifdef SIGPIPE
2203 PyOS_setsig(SIGPIPE, SIG_IGN);
2204#endif
2205#ifdef SIGXFZ
2206 PyOS_setsig(SIGXFZ, SIG_IGN);
2207#endif
2208#ifdef SIGXFSZ
2209 PyOS_setsig(SIGXFSZ, SIG_IGN);
2210#endif
2211 PyOS_InitInterrupts(); /* May imply initsignal() */
2212 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002213 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002214 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002215 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002216}
2217
2218
2219/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2220 *
2221 * All of the code in this function must only use async-signal-safe functions,
2222 * listed at `man 7 signal` or
2223 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2224 */
2225void
2226_Py_RestoreSignals(void)
2227{
2228#ifdef SIGPIPE
2229 PyOS_setsig(SIGPIPE, SIG_DFL);
2230#endif
2231#ifdef SIGXFZ
2232 PyOS_setsig(SIGXFZ, SIG_DFL);
2233#endif
2234#ifdef SIGXFSZ
2235 PyOS_setsig(SIGXFSZ, SIG_DFL);
2236#endif
2237}
2238
2239
2240/*
2241 * The file descriptor fd is considered ``interactive'' if either
2242 * a) isatty(fd) is TRUE, or
2243 * b) the -i flag was given, and the filename associated with
2244 * the descriptor is NULL or "<stdin>" or "???".
2245 */
2246int
2247Py_FdIsInteractive(FILE *fp, const char *filename)
2248{
2249 if (isatty((int)fileno(fp)))
2250 return 1;
2251 if (!Py_InteractiveFlag)
2252 return 0;
2253 return (filename == NULL) ||
2254 (strcmp(filename, "<stdin>") == 0) ||
2255 (strcmp(filename, "???") == 0);
2256}
2257
2258
Nick Coghland6009512014-11-20 21:39:37 +10002259/* Wrappers around sigaction() or signal(). */
2260
2261PyOS_sighandler_t
2262PyOS_getsig(int sig)
2263{
2264#ifdef HAVE_SIGACTION
2265 struct sigaction context;
2266 if (sigaction(sig, NULL, &context) == -1)
2267 return SIG_ERR;
2268 return context.sa_handler;
2269#else
2270 PyOS_sighandler_t handler;
2271/* Special signal handling for the secure CRT in Visual Studio 2005 */
2272#if defined(_MSC_VER) && _MSC_VER >= 1400
2273 switch (sig) {
2274 /* Only these signals are valid */
2275 case SIGINT:
2276 case SIGILL:
2277 case SIGFPE:
2278 case SIGSEGV:
2279 case SIGTERM:
2280 case SIGBREAK:
2281 case SIGABRT:
2282 break;
2283 /* Don't call signal() with other values or it will assert */
2284 default:
2285 return SIG_ERR;
2286 }
2287#endif /* _MSC_VER && _MSC_VER >= 1400 */
2288 handler = signal(sig, SIG_IGN);
2289 if (handler != SIG_ERR)
2290 signal(sig, handler);
2291 return handler;
2292#endif
2293}
2294
2295/*
2296 * All of the code in this function must only use async-signal-safe functions,
2297 * listed at `man 7 signal` or
2298 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2299 */
2300PyOS_sighandler_t
2301PyOS_setsig(int sig, PyOS_sighandler_t handler)
2302{
2303#ifdef HAVE_SIGACTION
2304 /* Some code in Modules/signalmodule.c depends on sigaction() being
2305 * used here if HAVE_SIGACTION is defined. Fix that if this code
2306 * changes to invalidate that assumption.
2307 */
2308 struct sigaction context, ocontext;
2309 context.sa_handler = handler;
2310 sigemptyset(&context.sa_mask);
2311 context.sa_flags = 0;
2312 if (sigaction(sig, &context, &ocontext) == -1)
2313 return SIG_ERR;
2314 return ocontext.sa_handler;
2315#else
2316 PyOS_sighandler_t oldhandler;
2317 oldhandler = signal(sig, handler);
2318#ifdef HAVE_SIGINTERRUPT
2319 siginterrupt(sig, 1);
2320#endif
2321 return oldhandler;
2322#endif
2323}
2324
2325#ifdef __cplusplus
2326}
2327#endif