blob: 28704c1c228bead0a2dd4c8b9fbf8ef02fa1bdb7 [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
Victor Stinner1dc6e392018-07-25 02:49:17 +0200808 PyMemAllocatorEx old_alloc;
809 _PyInitError err;
810
811 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
812 (and the input configuration is read only). */
813 _PyCoreConfig config = _PyCoreConfig_INIT;
814
815 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
816 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
817 err = _PyCoreConfig_Read(&config);
818 }
819 else {
820 err = _Py_INIT_ERR("failed to copy core config");
821 }
822 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
823
824 if (_Py_INIT_FAILED(err)) {
825 goto done;
826 }
827
828 err = _Py_InitializeCore_impl(interp_p, &config);
829
830done:
831 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
832 _PyCoreConfig_Clear(&config);
833 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
834
835 return err;
836}
837
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200838/* Py_Initialize() has already been called: update the main interpreter
839 configuration. Example of bpo-34008: Py_Main() called after
840 Py_Initialize(). */
841static _PyInitError
842_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
843 const _PyMainInterpreterConfig *config)
844{
845 if (config->argv != NULL) {
846 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
847 if (res < 0) {
848 return _Py_INIT_ERR("fail to set sys.argv");
849 }
850 }
851 return _Py_INIT_OK();
852}
853
Eric Snowc7ec9982017-05-23 23:00:52 -0700854/* Update interpreter state based on supplied configuration settings
855 *
856 * After calling this function, most of the restrictions on the interpreter
857 * are lifted. The only remaining incomplete settings are those related
858 * to the main module (sys.argv[0], __main__ metadata)
859 *
860 * Calling this when the interpreter is not initializing, is already
861 * initialized or without a valid current thread state is a fatal error.
862 * Other errors should be reported as normal Python exceptions with a
863 * non-zero return code.
864 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800865_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200866_Py_InitializeMainInterpreter(PyInterpreterState *interp,
867 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700868{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600869 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800870 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700871 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700872
Victor Stinner1dc6e392018-07-25 02:49:17 +0200873 /* Configure the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100874 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
875 return _Py_INIT_ERR("failed to copy main interpreter config");
876 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200877 config = &interp->config;
878 _PyCoreConfig *core_config = &interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700879
Victor Stinnerfb47bca2018-07-20 17:34:23 +0200880 if (_PyRuntime.initialized) {
881 return _Py_ReconfigureMainInterpreter(interp, config);
882 }
883
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200884 if (!core_config->_install_importlib) {
Eric Snow1abcf672017-05-23 21:46:51 -0700885 /* Special mode for freeze_importlib: run with no import system
886 *
887 * This means anything which needs support from extension modules
888 * or pure Python code in the standard library won't work.
889 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600890 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800891 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700892 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100893
Victor Stinner33c377e2017-12-05 15:12:41 +0100894 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800895 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100896 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200897
Victor Stinner41264f12017-12-15 02:05:29 +0100898 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800899 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100900 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800901
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200902 _PyInitError err = initexternalimport(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800903 if (_Py_INIT_FAILED(err)) {
904 return err;
905 }
Nick Coghland6009512014-11-20 21:39:37 +1000906
907 /* initialize the faulthandler module */
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200908 err = _PyFaulthandler_Init(core_config->faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800909 if (_Py_INIT_FAILED(err)) {
910 return err;
911 }
Nick Coghland6009512014-11-20 21:39:37 +1000912
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800913 err = initfsencoding(interp);
914 if (_Py_INIT_FAILED(err)) {
915 return err;
916 }
Nick Coghland6009512014-11-20 21:39:37 +1000917
Victor Stinner1f151112017-11-23 10:43:14 +0100918 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 err = initsigs(); /* Signal handling stuff, including initintr() */
920 if (_Py_INIT_FAILED(err)) {
921 return err;
922 }
923 }
Nick Coghland6009512014-11-20 21:39:37 +1000924
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200925 if (_PyTraceMalloc_Init(core_config->tracemalloc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800926 return _Py_INIT_ERR("can't initialize tracemalloc");
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200927 }
Nick Coghland6009512014-11-20 21:39:37 +1000928
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800929 err = add_main_module(interp);
930 if (_Py_INIT_FAILED(err)) {
931 return err;
932 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800933
Victor Stinner91106cd2017-12-13 12:29:09 +0100934 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800935 if (_Py_INIT_FAILED(err)) {
936 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800937 }
Nick Coghland6009512014-11-20 21:39:37 +1000938
939 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100940 if (interp->config.warnoptions != NULL &&
941 PyList_Size(interp->config.warnoptions) > 0)
942 {
Nick Coghland6009512014-11-20 21:39:37 +1000943 PyObject *warnings_module = PyImport_ImportModule("warnings");
944 if (warnings_module == NULL) {
945 fprintf(stderr, "'import warnings' failed; traceback:\n");
946 PyErr_Print();
947 }
948 Py_XDECREF(warnings_module);
949 }
950
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600951 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700952
Victor Stinnerd19d8d52018-07-24 13:55:48 +0200953 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800954 err = initsite(); /* Module site */
955 if (_Py_INIT_FAILED(err)) {
956 return err;
957 }
958 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800959 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000960}
961
Eric Snowc7ec9982017-05-23 23:00:52 -0700962#undef _INIT_DEBUG_PRINT
963
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800964_PyInitError
Victor Stinner1dc6e392018-07-25 02:49:17 +0200965_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700966{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200967 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800968 _PyInitError err;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200969 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800970 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200971 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800972 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200973 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100974
Victor Stinner9cfc0022017-12-20 19:36:46 +0100975 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner1dc6e392018-07-25 02:49:17 +0200976 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100977 if (!_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200978 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800979 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100980 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800981 if (_Py_INIT_FAILED(err)) {
Victor Stinner1dc6e392018-07-25 02:49:17 +0200982 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800983 }
Victor Stinner1dc6e392018-07-25 02:49:17 +0200984 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700985}
986
987
988void
Nick Coghland6009512014-11-20 21:39:37 +1000989Py_InitializeEx(int install_sigs)
990{
Victor Stinner1dc6e392018-07-25 02:49:17 +0200991 if (_PyRuntime.initialized) {
992 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
993 return;
994 }
995
996 _PyInitError err;
997 _PyCoreConfig config = _PyCoreConfig_INIT;
998 config.install_signal_handlers = install_sigs;
999
1000 err = _Py_InitializeFromConfig(&config);
1001 _PyCoreConfig_Clear(&config);
1002
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001003 if (_Py_INIT_FAILED(err)) {
1004 _Py_FatalInitError(err);
1005 }
Nick Coghland6009512014-11-20 21:39:37 +10001006}
1007
1008void
1009Py_Initialize(void)
1010{
1011 Py_InitializeEx(1);
1012}
1013
1014
1015#ifdef COUNT_ALLOCS
1016extern void dump_counts(FILE*);
1017#endif
1018
1019/* Flush stdout and stderr */
1020
1021static int
1022file_is_closed(PyObject *fobj)
1023{
1024 int r;
1025 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1026 if (tmp == NULL) {
1027 PyErr_Clear();
1028 return 0;
1029 }
1030 r = PyObject_IsTrue(tmp);
1031 Py_DECREF(tmp);
1032 if (r < 0)
1033 PyErr_Clear();
1034 return r > 0;
1035}
1036
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001037static int
Nick Coghland6009512014-11-20 21:39:37 +10001038flush_std_files(void)
1039{
1040 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1041 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1042 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001043 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001044
1045 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001046 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001047 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001048 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001049 status = -1;
1050 }
Nick Coghland6009512014-11-20 21:39:37 +10001051 else
1052 Py_DECREF(tmp);
1053 }
1054
1055 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001056 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001057 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001058 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001059 status = -1;
1060 }
Nick Coghland6009512014-11-20 21:39:37 +10001061 else
1062 Py_DECREF(tmp);
1063 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001064
1065 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001066}
1067
1068/* Undo the effect of Py_Initialize().
1069
1070 Beware: if multiple interpreter and/or thread states exist, these
1071 are not wiped out; only the current thread and interpreter state
1072 are deleted. But since everything else is deleted, those other
1073 interpreter and thread states should no longer be used.
1074
1075 (XXX We should do better, e.g. wipe out all interpreters and
1076 threads.)
1077
1078 Locking: as above.
1079
1080*/
1081
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001082int
1083Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001084{
1085 PyInterpreterState *interp;
1086 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001087 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001088
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001089 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001090 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001091
1092 wait_for_thread_shutdown();
1093
Marcel Plch776407f2017-12-20 11:17:58 +01001094 /* Get current thread state and interpreter pointer */
1095 tstate = PyThreadState_GET();
1096 interp = tstate->interp;
1097
Nick Coghland6009512014-11-20 21:39:37 +10001098 /* The interpreter is still entirely intact at this point, and the
1099 * exit funcs may be relying on that. In particular, if some thread
1100 * or exit func is still waiting to do an import, the import machinery
1101 * expects Py_IsInitialized() to return true. So don't say the
1102 * interpreter is uninitialized until after the exit funcs have run.
1103 * Note that Threading.py uses an exit func to do a join on all the
1104 * threads created thru it, so this also protects pending imports in
1105 * the threads created via Threading.
1106 */
Nick Coghland6009512014-11-20 21:39:37 +10001107
Marcel Plch776407f2017-12-20 11:17:58 +01001108 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001109
Victor Stinnerda273412017-12-15 01:46:02 +01001110 /* Copy the core config, PyInterpreterState_Delete() free
1111 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001112#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001113 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001114#endif
1115#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001116 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001117#endif
1118#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001119 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001120#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001121
Nick Coghland6009512014-11-20 21:39:37 +10001122 /* Remaining threads (e.g. daemon threads) will automatically exit
1123 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001124 _PyRuntime.finalizing = tstate;
1125 _PyRuntime.initialized = 0;
1126 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001127
Victor Stinnere0deff32015-03-24 13:46:18 +01001128 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001129 if (flush_std_files() < 0) {
1130 status = -1;
1131 }
Nick Coghland6009512014-11-20 21:39:37 +10001132
1133 /* Disable signal handling */
1134 PyOS_FiniInterrupts();
1135
1136 /* Collect garbage. This may call finalizers; it's nice to call these
1137 * before all modules are destroyed.
1138 * XXX If a __del__ or weakref callback is triggered here, and tries to
1139 * XXX import a module, bad things can happen, because Python no
1140 * XXX longer believes it's initialized.
1141 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1142 * XXX is easy to provoke that way. I've also seen, e.g.,
1143 * XXX Exception exceptions.ImportError: 'No module named sha'
1144 * XXX in <function callback at 0x008F5718> ignored
1145 * XXX but I'm unclear on exactly how that one happens. In any case,
1146 * XXX I haven't seen a real-life report of either of these.
1147 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001148 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001149#ifdef COUNT_ALLOCS
1150 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1151 each collection might release some types from the type
1152 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001153 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001154 /* nothing */;
1155#endif
Eric Snowdae02762017-09-14 00:35:58 -07001156
Nick Coghland6009512014-11-20 21:39:37 +10001157 /* Destroy all modules */
1158 PyImport_Cleanup();
1159
Victor Stinnere0deff32015-03-24 13:46:18 +01001160 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001161 if (flush_std_files() < 0) {
1162 status = -1;
1163 }
Nick Coghland6009512014-11-20 21:39:37 +10001164
1165 /* Collect final garbage. This disposes of cycles created by
1166 * class definitions, for example.
1167 * XXX This is disabled because it caused too many problems. If
1168 * XXX a __del__ or weakref callback triggers here, Python code has
1169 * XXX a hard time running, because even the sys module has been
1170 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1171 * XXX One symptom is a sequence of information-free messages
1172 * XXX coming from threads (if a __del__ or callback is invoked,
1173 * XXX other threads can execute too, and any exception they encounter
1174 * XXX triggers a comedy of errors as subsystem after subsystem
1175 * XXX fails to find what it *expects* to find in sys to help report
1176 * XXX the exception and consequent unexpected failures). I've also
1177 * XXX seen segfaults then, after adding print statements to the
1178 * XXX Python code getting called.
1179 */
1180#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001181 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001182#endif
1183
1184 /* Disable tracemalloc after all Python objects have been destroyed,
1185 so it is possible to use tracemalloc in objects destructor. */
1186 _PyTraceMalloc_Fini();
1187
1188 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1189 _PyImport_Fini();
1190
1191 /* Cleanup typeobject.c's internal caches. */
1192 _PyType_Fini();
1193
1194 /* unload faulthandler module */
1195 _PyFaulthandler_Fini();
1196
1197 /* Debugging stuff */
1198#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001199 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001200#endif
1201 /* dump hash stats */
1202 _PyHash_Fini();
1203
Eric Snowdae02762017-09-14 00:35:58 -07001204#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001205 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001206 _PyDebug_PrintTotalRefs();
1207 }
Eric Snowdae02762017-09-14 00:35:58 -07001208#endif
Nick Coghland6009512014-11-20 21:39:37 +10001209
1210#ifdef Py_TRACE_REFS
1211 /* Display all objects still alive -- this can invoke arbitrary
1212 * __repr__ overrides, so requires a mostly-intact interpreter.
1213 * Alas, a lot of stuff may still be alive now that will be cleaned
1214 * up later.
1215 */
Victor Stinnerda273412017-12-15 01:46:02 +01001216 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001217 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001218 }
Nick Coghland6009512014-11-20 21:39:37 +10001219#endif /* Py_TRACE_REFS */
1220
1221 /* Clear interpreter state and all thread states. */
1222 PyInterpreterState_Clear(interp);
1223
1224 /* Now we decref the exception classes. After this point nothing
1225 can raise an exception. That's okay, because each Fini() method
1226 below has been checked to make sure no exceptions are ever
1227 raised.
1228 */
1229
1230 _PyExc_Fini();
1231
1232 /* Sundry finalizers */
1233 PyMethod_Fini();
1234 PyFrame_Fini();
1235 PyCFunction_Fini();
1236 PyTuple_Fini();
1237 PyList_Fini();
1238 PySet_Fini();
1239 PyBytes_Fini();
1240 PyByteArray_Fini();
1241 PyLong_Fini();
1242 PyFloat_Fini();
1243 PyDict_Fini();
1244 PySlice_Fini();
1245 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001246 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001247 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001248 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001249 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001250
1251 /* Cleanup Unicode implementation */
1252 _PyUnicode_Fini();
1253
1254 /* reset file system default encoding */
1255 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1256 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1257 Py_FileSystemDefaultEncoding = NULL;
1258 }
1259
1260 /* XXX Still allocated:
1261 - various static ad-hoc pointers to interned strings
1262 - int and float free list blocks
1263 - whatever various modules and libraries allocate
1264 */
1265
1266 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1267
1268 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001269 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001270
1271 /* Delete current thread. After this, many C API calls become crashy. */
1272 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001273
Nick Coghland6009512014-11-20 21:39:37 +10001274 PyInterpreterState_Delete(interp);
1275
1276#ifdef Py_TRACE_REFS
1277 /* Display addresses (& refcnts) of all objects still alive.
1278 * An address can be used to find the repr of the object, printed
1279 * above by _Py_PrintReferences.
1280 */
Victor Stinnerda273412017-12-15 01:46:02 +01001281 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001282 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001283 }
Nick Coghland6009512014-11-20 21:39:37 +10001284#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001285#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001286 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001287 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001288 }
Nick Coghland6009512014-11-20 21:39:37 +10001289#endif
1290
1291 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001292
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001293 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001294 return status;
1295}
1296
1297void
1298Py_Finalize(void)
1299{
1300 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001301}
1302
1303/* Create and initialize a new interpreter and thread, and return the
1304 new thread. This requires that Py_Initialize() has been called
1305 first.
1306
1307 Unsuccessful initialization yields a NULL pointer. Note that *no*
1308 exception information is available even in this case -- the
1309 exception information is held in the thread, and there is no
1310 thread.
1311
1312 Locking: as above.
1313
1314*/
1315
Victor Stinnera7368ac2017-11-15 18:11:45 -08001316static _PyInitError
1317new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001318{
1319 PyInterpreterState *interp;
1320 PyThreadState *tstate, *save_tstate;
1321 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001322 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001323
Victor Stinnera7368ac2017-11-15 18:11:45 -08001324 if (!_PyRuntime.initialized) {
1325 return _Py_INIT_ERR("Py_Initialize must be called first");
1326 }
Nick Coghland6009512014-11-20 21:39:37 +10001327
Victor Stinner8a1be612016-03-14 22:07:55 +01001328 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1329 interpreters: disable PyGILState_Check(). */
1330 _PyGILState_check_enabled = 0;
1331
Nick Coghland6009512014-11-20 21:39:37 +10001332 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001333 if (interp == NULL) {
1334 *tstate_p = NULL;
1335 return _Py_INIT_OK();
1336 }
Nick Coghland6009512014-11-20 21:39:37 +10001337
1338 tstate = PyThreadState_New(interp);
1339 if (tstate == NULL) {
1340 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001341 *tstate_p = NULL;
1342 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001343 }
1344
1345 save_tstate = PyThreadState_Swap(tstate);
1346
Eric Snow1abcf672017-05-23 21:46:51 -07001347 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001348 _PyCoreConfig *core_config;
1349 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001350 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001351 core_config = &save_tstate->interp->core_config;
1352 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001353 } else {
1354 /* No current thread state, copy from the main interpreter */
1355 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001356 core_config = &main_interp->core_config;
1357 config = &main_interp->config;
1358 }
1359
1360 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1361 return _Py_INIT_ERR("failed to copy core config");
1362 }
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001363 core_config = &interp->core_config;
Victor Stinnerda273412017-12-15 01:46:02 +01001364 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1365 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001366 }
1367
Nick Coghland6009512014-11-20 21:39:37 +10001368 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001369 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001370 if (modules == NULL) {
1371 return _Py_INIT_ERR("can't make modules dictionary");
1372 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001373 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001374
Eric Snowd393c1b2017-09-14 12:18:12 -06001375 sysmod = _PyImport_FindBuiltin("sys", modules);
1376 if (sysmod != NULL) {
1377 interp->sysdict = PyModule_GetDict(sysmod);
1378 if (interp->sysdict == NULL)
1379 goto handle_error;
1380 Py_INCREF(interp->sysdict);
1381 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001382 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001383 }
1384
1385 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001386 if (bimod != NULL) {
1387 interp->builtins = PyModule_GetDict(bimod);
1388 if (interp->builtins == NULL)
1389 goto handle_error;
1390 Py_INCREF(interp->builtins);
1391 }
1392
1393 /* initialize builtin exceptions */
1394 _PyExc_Init(bimod);
1395
Nick Coghland6009512014-11-20 21:39:37 +10001396 if (bimod != NULL && sysmod != NULL) {
1397 PyObject *pstderr;
1398
Nick Coghland6009512014-11-20 21:39:37 +10001399 /* Set up a preliminary stderr printer until we have enough
1400 infrastructure for the io module in place. */
1401 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001402 if (pstderr == NULL) {
1403 return _Py_INIT_ERR("can't set preliminary stderr");
1404 }
Nick Coghland6009512014-11-20 21:39:37 +10001405 _PySys_SetObjectId(&PyId_stderr, pstderr);
1406 PySys_SetObject("__stderr__", pstderr);
1407 Py_DECREF(pstderr);
1408
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001409 err = _PyImportHooks_Init();
1410 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001411 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001412 }
Nick Coghland6009512014-11-20 21:39:37 +10001413
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001414 err = initimport(interp, sysmod);
1415 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001416 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001417 }
Nick Coghland6009512014-11-20 21:39:37 +10001418
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001419 err = initexternalimport(interp);
1420 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001421 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001422 }
Nick Coghland6009512014-11-20 21:39:37 +10001423
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001424 err = initfsencoding(interp);
1425 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001426 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001427 }
1428
Victor Stinner91106cd2017-12-13 12:29:09 +01001429 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001430 if (_Py_INIT_FAILED(err)) {
1431 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001432 }
1433
1434 err = add_main_module(interp);
1435 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001436 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001437 }
1438
Victor Stinnerd19d8d52018-07-24 13:55:48 +02001439 if (core_config->site_import) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001440 err = initsite();
1441 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001442 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001443 }
1444 }
Nick Coghland6009512014-11-20 21:39:37 +10001445 }
1446
Victor Stinnera7368ac2017-11-15 18:11:45 -08001447 if (PyErr_Occurred()) {
1448 goto handle_error;
1449 }
Nick Coghland6009512014-11-20 21:39:37 +10001450
Victor Stinnera7368ac2017-11-15 18:11:45 -08001451 *tstate_p = tstate;
1452 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001453
Nick Coghland6009512014-11-20 21:39:37 +10001454handle_error:
1455 /* Oops, it didn't work. Undo it all. */
1456
1457 PyErr_PrintEx(0);
1458 PyThreadState_Clear(tstate);
1459 PyThreadState_Swap(save_tstate);
1460 PyThreadState_Delete(tstate);
1461 PyInterpreterState_Delete(interp);
1462
Victor Stinnera7368ac2017-11-15 18:11:45 -08001463 *tstate_p = NULL;
1464 return _Py_INIT_OK();
1465}
1466
1467PyThreadState *
1468Py_NewInterpreter(void)
1469{
1470 PyThreadState *tstate;
1471 _PyInitError err = new_interpreter(&tstate);
1472 if (_Py_INIT_FAILED(err)) {
1473 _Py_FatalInitError(err);
1474 }
1475 return tstate;
1476
Nick Coghland6009512014-11-20 21:39:37 +10001477}
1478
1479/* Delete an interpreter and its last thread. This requires that the
1480 given thread state is current, that the thread has no remaining
1481 frames, and that it is its interpreter's only remaining thread.
1482 It is a fatal error to violate these constraints.
1483
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001484 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001485 everything, regardless.)
1486
1487 Locking: as above.
1488
1489*/
1490
1491void
1492Py_EndInterpreter(PyThreadState *tstate)
1493{
1494 PyInterpreterState *interp = tstate->interp;
1495
1496 if (tstate != PyThreadState_GET())
1497 Py_FatalError("Py_EndInterpreter: thread is not current");
1498 if (tstate->frame != NULL)
1499 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1500
1501 wait_for_thread_shutdown();
1502
Marcel Plch776407f2017-12-20 11:17:58 +01001503 call_py_exitfuncs(interp);
1504
Nick Coghland6009512014-11-20 21:39:37 +10001505 if (tstate != interp->tstate_head || tstate->next != NULL)
1506 Py_FatalError("Py_EndInterpreter: not the last thread");
1507
1508 PyImport_Cleanup();
1509 PyInterpreterState_Clear(interp);
1510 PyThreadState_Swap(NULL);
1511 PyInterpreterState_Delete(interp);
1512}
1513
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001514/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001515
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001516static _PyInitError
1517add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001518{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001519 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001520 m = PyImport_AddModule("__main__");
1521 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001522 return _Py_INIT_ERR("can't create __main__ module");
1523
Nick Coghland6009512014-11-20 21:39:37 +10001524 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001525 ann_dict = PyDict_New();
1526 if ((ann_dict == NULL) ||
1527 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001528 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001529 }
1530 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001531
Nick Coghland6009512014-11-20 21:39:37 +10001532 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1533 PyObject *bimod = PyImport_ImportModule("builtins");
1534 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001535 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001536 }
1537 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001538 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001539 }
1540 Py_DECREF(bimod);
1541 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001542
Nick Coghland6009512014-11-20 21:39:37 +10001543 /* Main is a little special - imp.is_builtin("__main__") will return
1544 * False, but BuiltinImporter is still the most appropriate initial
1545 * setting for its __loader__ attribute. A more suitable value will
1546 * be set if __main__ gets further initialized later in the startup
1547 * process.
1548 */
1549 loader = PyDict_GetItemString(d, "__loader__");
1550 if (loader == NULL || loader == Py_None) {
1551 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1552 "BuiltinImporter");
1553 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001554 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001555 }
1556 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001557 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001558 }
1559 Py_DECREF(loader);
1560 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001562}
1563
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001564static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001565initfsencoding(PyInterpreterState *interp)
1566{
1567 PyObject *codec;
1568
Steve Dowercc16be82016-09-08 10:35:16 -07001569#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001570 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001571 Py_FileSystemDefaultEncoding = "mbcs";
1572 Py_FileSystemDefaultEncodeErrors = "replace";
1573 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001574 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001575 Py_FileSystemDefaultEncoding = "utf-8";
1576 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1577 }
1578#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001579 if (Py_FileSystemDefaultEncoding == NULL &&
1580 interp->core_config.utf8_mode)
1581 {
1582 Py_FileSystemDefaultEncoding = "utf-8";
1583 Py_HasFileSystemDefaultEncoding = 1;
1584 }
1585 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001586 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001587 if (Py_FileSystemDefaultEncoding == NULL) {
1588 return _Py_INIT_ERR("Unable to get the locale encoding");
1589 }
Nick Coghland6009512014-11-20 21:39:37 +10001590
1591 Py_HasFileSystemDefaultEncoding = 0;
1592 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001593 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001594 }
Steve Dowercc16be82016-09-08 10:35:16 -07001595#endif
Nick Coghland6009512014-11-20 21:39:37 +10001596
1597 /* the encoding is mbcs, utf-8 or ascii */
1598 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1599 if (!codec) {
1600 /* Such error can only occurs in critical situations: no more
1601 * memory, import a module of the standard library failed,
1602 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001603 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001604 }
1605 Py_DECREF(codec);
1606 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001607 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001608}
1609
1610/* Import the site module (not into __main__ though) */
1611
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001612static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001613initsite(void)
1614{
1615 PyObject *m;
1616 m = PyImport_ImportModule("site");
1617 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001618 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001619 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001620 Py_DECREF(m);
1621 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001622}
1623
Victor Stinner874dbe82015-09-04 17:29:57 +02001624/* Check if a file descriptor is valid or not.
1625 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1626static int
1627is_valid_fd(int fd)
1628{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001629#ifdef __APPLE__
1630 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1631 and the other side of the pipe is closed, dup(1) succeed, whereas
1632 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1633 such error. */
1634 struct stat st;
1635 return (fstat(fd, &st) == 0);
1636#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001637 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001638 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001639 return 0;
1640 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001641 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1642 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1643 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001644 fd2 = dup(fd);
1645 if (fd2 >= 0)
1646 close(fd2);
1647 _Py_END_SUPPRESS_IPH
1648 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001649#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001650}
1651
1652/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001653static PyObject*
1654create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001655 int fd, int write_mode, const char* name,
1656 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001657{
1658 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1659 const char* mode;
1660 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001661 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001662 int buffering, isatty;
1663 _Py_IDENTIFIER(open);
1664 _Py_IDENTIFIER(isatty);
1665 _Py_IDENTIFIER(TextIOWrapper);
1666 _Py_IDENTIFIER(mode);
1667
Victor Stinner874dbe82015-09-04 17:29:57 +02001668 if (!is_valid_fd(fd))
1669 Py_RETURN_NONE;
1670
Nick Coghland6009512014-11-20 21:39:37 +10001671 /* stdin is always opened in buffered mode, first because it shouldn't
1672 make a difference in common use cases, second because TextIOWrapper
1673 depends on the presence of a read1() method which only exists on
1674 buffered streams.
1675 */
1676 if (Py_UnbufferedStdioFlag && write_mode)
1677 buffering = 0;
1678 else
1679 buffering = -1;
1680 if (write_mode)
1681 mode = "wb";
1682 else
1683 mode = "rb";
1684 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1685 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001686 Py_None, Py_None, /* encoding, errors */
1687 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001688 if (buf == NULL)
1689 goto error;
1690
1691 if (buffering) {
1692 _Py_IDENTIFIER(raw);
1693 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1694 if (raw == NULL)
1695 goto error;
1696 }
1697 else {
1698 raw = buf;
1699 Py_INCREF(raw);
1700 }
1701
Steve Dower39294992016-08-30 21:22:36 -07001702#ifdef MS_WINDOWS
1703 /* Windows console IO is always UTF-8 encoded */
1704 if (PyWindowsConsoleIO_Check(raw))
1705 encoding = "utf-8";
1706#endif
1707
Nick Coghland6009512014-11-20 21:39:37 +10001708 text = PyUnicode_FromString(name);
1709 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1710 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001711 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001712 if (res == NULL)
1713 goto error;
1714 isatty = PyObject_IsTrue(res);
1715 Py_DECREF(res);
1716 if (isatty == -1)
1717 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001718 if (Py_UnbufferedStdioFlag)
1719 write_through = Py_True;
1720 else
1721 write_through = Py_False;
1722 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001723 line_buffering = Py_True;
1724 else
1725 line_buffering = Py_False;
1726
1727 Py_CLEAR(raw);
1728 Py_CLEAR(text);
1729
1730#ifdef MS_WINDOWS
1731 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1732 newlines to "\n".
1733 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1734 newline = NULL;
1735#else
1736 /* sys.stdin: split lines at "\n".
1737 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1738 newline = "\n";
1739#endif
1740
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001741 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001742 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001743 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001744 Py_CLEAR(buf);
1745 if (stream == NULL)
1746 goto error;
1747
1748 if (write_mode)
1749 mode = "w";
1750 else
1751 mode = "r";
1752 text = PyUnicode_FromString(mode);
1753 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1754 goto error;
1755 Py_CLEAR(text);
1756 return stream;
1757
1758error:
1759 Py_XDECREF(buf);
1760 Py_XDECREF(stream);
1761 Py_XDECREF(text);
1762 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001763
Victor Stinner874dbe82015-09-04 17:29:57 +02001764 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1765 /* Issue #24891: the file descriptor was closed after the first
1766 is_valid_fd() check was called. Ignore the OSError and set the
1767 stream to None. */
1768 PyErr_Clear();
1769 Py_RETURN_NONE;
1770 }
1771 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001772}
1773
1774/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001775static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001776init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001777{
1778 PyObject *iomod = NULL, *wrapper;
1779 PyObject *bimod = NULL;
1780 PyObject *m;
1781 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001782 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001783 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001784 char *pythonioencoding = NULL;
1785 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001786 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001787
1788 /* Hack to avoid a nasty recursion issue when Python is invoked
1789 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1790 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1791 goto error;
1792 }
1793 Py_DECREF(m);
1794
1795 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1796 goto error;
1797 }
1798 Py_DECREF(m);
1799
1800 if (!(bimod = PyImport_ImportModule("builtins"))) {
1801 goto error;
1802 }
1803
1804 if (!(iomod = PyImport_ImportModule("io"))) {
1805 goto error;
1806 }
1807 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1808 goto error;
1809 }
1810
1811 /* Set builtins.open */
1812 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1813 Py_DECREF(wrapper);
1814 goto error;
1815 }
1816 Py_DECREF(wrapper);
1817
1818 encoding = _Py_StandardStreamEncoding;
1819 errors = _Py_StandardStreamErrors;
1820 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001821 char *opt = Py_GETENV("PYTHONIOENCODING");
1822 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001823 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001824 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001825 if (pythonioencoding == NULL) {
1826 PyErr_NoMemory();
1827 goto error;
1828 }
1829 err = strchr(pythonioencoding, ':');
1830 if (err) {
1831 *err = '\0';
1832 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001833 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001834 errors = err;
1835 }
1836 }
1837 if (*pythonioencoding && !encoding) {
1838 encoding = pythonioencoding;
1839 }
1840 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001841 else if (interp->core_config.utf8_mode) {
1842 encoding = "utf-8";
1843 errors = "surrogateescape";
1844 }
1845
1846 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001847 /* Choose the default error handler based on the current locale */
1848 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001849 }
Nick Coghland6009512014-11-20 21:39:37 +10001850 }
1851
1852 /* Set sys.stdin */
1853 fd = fileno(stdin);
1854 /* Under some conditions stdin, stdout and stderr may not be connected
1855 * and fileno() may point to an invalid file descriptor. For example
1856 * GUI apps don't have valid standard streams by default.
1857 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001858 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1859 if (std == NULL)
1860 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001861 PySys_SetObject("__stdin__", std);
1862 _PySys_SetObjectId(&PyId_stdin, std);
1863 Py_DECREF(std);
1864
1865 /* Set sys.stdout */
1866 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001867 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1868 if (std == NULL)
1869 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001870 PySys_SetObject("__stdout__", std);
1871 _PySys_SetObjectId(&PyId_stdout, std);
1872 Py_DECREF(std);
1873
1874#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1875 /* Set sys.stderr, replaces the preliminary stderr */
1876 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001877 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1878 if (std == NULL)
1879 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001880
1881 /* Same as hack above, pre-import stderr's codec to avoid recursion
1882 when import.c tries to write to stderr in verbose mode. */
1883 encoding_attr = PyObject_GetAttrString(std, "encoding");
1884 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001885 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001886 if (std_encoding != NULL) {
1887 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1888 Py_XDECREF(codec_info);
1889 }
1890 Py_DECREF(encoding_attr);
1891 }
1892 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1893
1894 if (PySys_SetObject("__stderr__", std) < 0) {
1895 Py_DECREF(std);
1896 goto error;
1897 }
1898 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1899 Py_DECREF(std);
1900 goto error;
1901 }
1902 Py_DECREF(std);
1903#endif
1904
Victor Stinnera7368ac2017-11-15 18:11:45 -08001905 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001906
Victor Stinnera7368ac2017-11-15 18:11:45 -08001907error:
1908 res = _Py_INIT_ERR("can't initialize sys standard streams");
1909
Victor Stinner31e99082017-12-20 23:41:38 +01001910 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1911 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001912done:
Victor Stinner31e99082017-12-20 23:41:38 +01001913 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1914
Nick Coghland6009512014-11-20 21:39:37 +10001915 /* We won't need them anymore. */
1916 if (_Py_StandardStreamEncoding) {
1917 PyMem_RawFree(_Py_StandardStreamEncoding);
1918 _Py_StandardStreamEncoding = NULL;
1919 }
1920 if (_Py_StandardStreamErrors) {
1921 PyMem_RawFree(_Py_StandardStreamErrors);
1922 _Py_StandardStreamErrors = NULL;
1923 }
Victor Stinner31e99082017-12-20 23:41:38 +01001924
1925 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1926
Nick Coghland6009512014-11-20 21:39:37 +10001927 PyMem_Free(pythonioencoding);
1928 Py_XDECREF(bimod);
1929 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001930 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001931}
1932
1933
Victor Stinner10dc4842015-03-24 12:01:30 +01001934static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001935_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001936{
Victor Stinner10dc4842015-03-24 12:01:30 +01001937 fputc('\n', stderr);
1938 fflush(stderr);
1939
1940 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001941 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001942}
Victor Stinner791da1c2016-03-14 16:53:12 +01001943
1944/* Print the current exception (if an exception is set) with its traceback,
1945 or display the current Python stack.
1946
1947 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1948 called on catastrophic cases.
1949
1950 Return 1 if the traceback was displayed, 0 otherwise. */
1951
1952static int
1953_Py_FatalError_PrintExc(int fd)
1954{
1955 PyObject *ferr, *res;
1956 PyObject *exception, *v, *tb;
1957 int has_tb;
1958
1959 if (PyThreadState_GET() == NULL) {
1960 /* The GIL is released: trying to acquire it is likely to deadlock,
1961 just give up. */
1962 return 0;
1963 }
1964
1965 PyErr_Fetch(&exception, &v, &tb);
1966 if (exception == NULL) {
1967 /* No current exception */
1968 return 0;
1969 }
1970
1971 ferr = _PySys_GetObjectId(&PyId_stderr);
1972 if (ferr == NULL || ferr == Py_None) {
1973 /* sys.stderr is not set yet or set to None,
1974 no need to try to display the exception */
1975 return 0;
1976 }
1977
1978 PyErr_NormalizeException(&exception, &v, &tb);
1979 if (tb == NULL) {
1980 tb = Py_None;
1981 Py_INCREF(tb);
1982 }
1983 PyException_SetTraceback(v, tb);
1984 if (exception == NULL) {
1985 /* PyErr_NormalizeException() failed */
1986 return 0;
1987 }
1988
1989 has_tb = (tb != Py_None);
1990 PyErr_Display(exception, v, tb);
1991 Py_XDECREF(exception);
1992 Py_XDECREF(v);
1993 Py_XDECREF(tb);
1994
1995 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001996 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001997 if (res == NULL)
1998 PyErr_Clear();
1999 else
2000 Py_DECREF(res);
2001
2002 return has_tb;
2003}
2004
Nick Coghland6009512014-11-20 21:39:37 +10002005/* Print fatal error message and abort */
2006
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002007#ifdef MS_WINDOWS
2008static void
2009fatal_output_debug(const char *msg)
2010{
2011 /* buffer of 256 bytes allocated on the stack */
2012 WCHAR buffer[256 / sizeof(WCHAR)];
2013 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2014 size_t msglen;
2015
2016 OutputDebugStringW(L"Fatal Python error: ");
2017
2018 msglen = strlen(msg);
2019 while (msglen) {
2020 size_t i;
2021
2022 if (buflen > msglen) {
2023 buflen = msglen;
2024 }
2025
2026 /* Convert the message to wchar_t. This uses a simple one-to-one
2027 conversion, assuming that the this error message actually uses
2028 ASCII only. If this ceases to be true, we will have to convert. */
2029 for (i=0; i < buflen; ++i) {
2030 buffer[i] = msg[i];
2031 }
2032 buffer[i] = L'\0';
2033 OutputDebugStringW(buffer);
2034
2035 msg += buflen;
2036 msglen -= buflen;
2037 }
2038 OutputDebugStringW(L"\n");
2039}
2040#endif
2041
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002042static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002043fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002044{
2045 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002046 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002047
2048 if (reentrant) {
2049 /* Py_FatalError() caused a second fatal error.
2050 Example: flush_std_files() raises a recursion error. */
2051 goto exit;
2052 }
2053 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002054
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002055 fprintf(stderr, "Fatal Python error: ");
2056 if (prefix) {
2057 fputs(prefix, stderr);
2058 fputs(": ", stderr);
2059 }
2060 if (msg) {
2061 fputs(msg, stderr);
2062 }
2063 else {
2064 fprintf(stderr, "<message not set>");
2065 }
2066 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002067 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002068
Victor Stinnere0deff32015-03-24 13:46:18 +01002069 /* Print the exception (if an exception is set) with its traceback,
2070 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002071 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002072 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002073 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002074
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002075 /* The main purpose of faulthandler is to display the traceback.
2076 This function already did its best to display a traceback.
2077 Disable faulthandler to prevent writing a second traceback
2078 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002079 _PyFaulthandler_Fini();
2080
Victor Stinner791da1c2016-03-14 16:53:12 +01002081 /* Check if the current Python thread hold the GIL */
2082 if (PyThreadState_GET() != NULL) {
2083 /* Flush sys.stdout and sys.stderr */
2084 flush_std_files();
2085 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002086
Nick Coghland6009512014-11-20 21:39:37 +10002087#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002088 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002089#endif /* MS_WINDOWS */
2090
2091exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002092 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002093#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002094 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002095#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002096 abort();
2097 }
2098 else {
2099 exit(status);
2100 }
2101}
2102
Victor Stinner19760862017-12-20 01:41:59 +01002103void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002104Py_FatalError(const char *msg)
2105{
2106 fatal_error(NULL, msg, -1);
2107}
2108
Victor Stinner19760862017-12-20 01:41:59 +01002109void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002110_Py_FatalInitError(_PyInitError err)
2111{
2112 /* On "user" error: exit with status 1.
2113 For all other errors, call abort(). */
2114 int status = err.user_err ? 1 : -1;
2115 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002116}
2117
2118/* Clean up and exit */
2119
Victor Stinnerd7292b52016-06-17 12:29:00 +02002120# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002121
Nick Coghland6009512014-11-20 21:39:37 +10002122/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002123void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002124{
Victor Stinnercaba55b2018-08-03 15:33:52 +02002125 PyInterpreterState *is = _PyInterpreterState_Get();
Marcel Plch776407f2017-12-20 11:17:58 +01002126
Antoine Pitroufc5db952017-12-13 02:29:07 +01002127 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002128 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2129
2130 is->pyexitfunc = func;
2131 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002132}
2133
2134static void
Marcel Plch776407f2017-12-20 11:17:58 +01002135call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002136{
Marcel Plch776407f2017-12-20 11:17:58 +01002137 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002138 return;
2139
Marcel Plch776407f2017-12-20 11:17:58 +01002140 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002141 PyErr_Clear();
2142}
2143
2144/* Wait until threading._shutdown completes, provided
2145 the threading module was imported in the first place.
2146 The shutdown routine will wait until all non-daemon
2147 "threading" threads have completed. */
2148static void
2149wait_for_thread_shutdown(void)
2150{
Nick Coghland6009512014-11-20 21:39:37 +10002151 _Py_IDENTIFIER(_shutdown);
2152 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002153 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002154 if (threading == NULL) {
2155 /* threading not imported */
2156 PyErr_Clear();
2157 return;
2158 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002159 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002160 if (result == NULL) {
2161 PyErr_WriteUnraisable(threading);
2162 }
2163 else {
2164 Py_DECREF(result);
2165 }
2166 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002167}
2168
2169#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002170int Py_AtExit(void (*func)(void))
2171{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002172 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002173 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002174 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002175 return 0;
2176}
2177
2178static void
2179call_ll_exitfuncs(void)
2180{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002181 while (_PyRuntime.nexitfuncs > 0)
2182 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002183
2184 fflush(stdout);
2185 fflush(stderr);
2186}
2187
Victor Stinnercfc88312018-08-01 16:41:25 +02002188void _Py_NO_RETURN
Nick Coghland6009512014-11-20 21:39:37 +10002189Py_Exit(int sts)
2190{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002191 if (Py_FinalizeEx() < 0) {
2192 sts = 120;
2193 }
Nick Coghland6009512014-11-20 21:39:37 +10002194
2195 exit(sts);
2196}
2197
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002198static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002199initsigs(void)
2200{
2201#ifdef SIGPIPE
2202 PyOS_setsig(SIGPIPE, SIG_IGN);
2203#endif
2204#ifdef SIGXFZ
2205 PyOS_setsig(SIGXFZ, SIG_IGN);
2206#endif
2207#ifdef SIGXFSZ
2208 PyOS_setsig(SIGXFSZ, SIG_IGN);
2209#endif
2210 PyOS_InitInterrupts(); /* May imply initsignal() */
2211 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002212 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002213 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002214 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002215}
2216
2217
2218/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2219 *
2220 * All of the code in this function must only use async-signal-safe functions,
2221 * listed at `man 7 signal` or
2222 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2223 */
2224void
2225_Py_RestoreSignals(void)
2226{
2227#ifdef SIGPIPE
2228 PyOS_setsig(SIGPIPE, SIG_DFL);
2229#endif
2230#ifdef SIGXFZ
2231 PyOS_setsig(SIGXFZ, SIG_DFL);
2232#endif
2233#ifdef SIGXFSZ
2234 PyOS_setsig(SIGXFSZ, SIG_DFL);
2235#endif
2236}
2237
2238
2239/*
2240 * The file descriptor fd is considered ``interactive'' if either
2241 * a) isatty(fd) is TRUE, or
2242 * b) the -i flag was given, and the filename associated with
2243 * the descriptor is NULL or "<stdin>" or "???".
2244 */
2245int
2246Py_FdIsInteractive(FILE *fp, const char *filename)
2247{
2248 if (isatty((int)fileno(fp)))
2249 return 1;
2250 if (!Py_InteractiveFlag)
2251 return 0;
2252 return (filename == NULL) ||
2253 (strcmp(filename, "<stdin>") == 0) ||
2254 (strcmp(filename, "???") == 0);
2255}
2256
2257
Nick Coghland6009512014-11-20 21:39:37 +10002258/* Wrappers around sigaction() or signal(). */
2259
2260PyOS_sighandler_t
2261PyOS_getsig(int sig)
2262{
2263#ifdef HAVE_SIGACTION
2264 struct sigaction context;
2265 if (sigaction(sig, NULL, &context) == -1)
2266 return SIG_ERR;
2267 return context.sa_handler;
2268#else
2269 PyOS_sighandler_t handler;
2270/* Special signal handling for the secure CRT in Visual Studio 2005 */
2271#if defined(_MSC_VER) && _MSC_VER >= 1400
2272 switch (sig) {
2273 /* Only these signals are valid */
2274 case SIGINT:
2275 case SIGILL:
2276 case SIGFPE:
2277 case SIGSEGV:
2278 case SIGTERM:
2279 case SIGBREAK:
2280 case SIGABRT:
2281 break;
2282 /* Don't call signal() with other values or it will assert */
2283 default:
2284 return SIG_ERR;
2285 }
2286#endif /* _MSC_VER && _MSC_VER >= 1400 */
2287 handler = signal(sig, SIG_IGN);
2288 if (handler != SIG_ERR)
2289 signal(sig, handler);
2290 return handler;
2291#endif
2292}
2293
2294/*
2295 * All of the code in this function must only use async-signal-safe functions,
2296 * listed at `man 7 signal` or
2297 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2298 */
2299PyOS_sighandler_t
2300PyOS_setsig(int sig, PyOS_sighandler_t handler)
2301{
2302#ifdef HAVE_SIGACTION
2303 /* Some code in Modules/signalmodule.c depends on sigaction() being
2304 * used here if HAVE_SIGACTION is defined. Fix that if this code
2305 * changes to invalidate that assumption.
2306 */
2307 struct sigaction context, ocontext;
2308 context.sa_handler = handler;
2309 sigemptyset(&context.sa_mask);
2310 context.sa_flags = 0;
2311 if (sigaction(sig, &context, &ocontext) == -1)
2312 return SIG_ERR;
2313 return ocontext.sa_handler;
2314#else
2315 PyOS_sighandler_t oldhandler;
2316 oldhandler = signal(sig, handler);
2317#ifdef HAVE_SIGINTERRUPT
2318 siginterrupt(sig, 1);
2319#endif
2320 return oldhandler;
2321#endif
2322}
2323
2324#ifdef __cplusplus
2325}
2326#endif