blob: f75b8604a33061662cfca3c630c263f784d42327 [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/* Global configuration variable declarations are in pydebug.h */
112/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
Benjamin Peterson0a37a302017-12-31 10:04:13 -0800113int Py_DebugFlag = 0; /* Needed by parser.c */
114int Py_VerboseFlag = 0; /* Needed by import.c */
115int Py_QuietFlag = 0; /* Needed by sysmodule.c */
116int Py_InteractiveFlag = 0; /* Needed by Py_FdIsInteractive() below */
117int Py_InspectFlag = 0; /* Needed to determine whether to exit at SystemExit */
Nick Coghland6009512014-11-20 21:39:37 +1000118int Py_OptimizeFlag = 0; /* Needed by compile.c */
Benjamin Peterson0a37a302017-12-31 10:04:13 -0800119int Py_NoSiteFlag = 0; /* Suppress 'import site' */
120int Py_BytesWarningFlag = 0; /* Warn on str(bytes) and str(buffer) */
121int Py_FrozenFlag = 0; /* Needed by getpath.c */
122int Py_IgnoreEnvironmentFlag = 0; /* e.g. PYTHONPATH, PYTHONHOME */
123int Py_DontWriteBytecodeFlag = 0; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000124int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
125int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
126int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
127int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700128#ifdef MS_WINDOWS
129int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700130int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700131#endif
Nick Coghland6009512014-11-20 21:39:37 +1000132
Nick Coghland6009512014-11-20 21:39:37 +1000133/* Hack to force loading of object files */
134int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
135 PyOS_mystrnicmp; /* Python/pystrcmp.o */
136
137/* PyModule_GetWarningsModule is no longer necessary as of 2.6
138since _warnings is builtin. This API should not be used. */
139PyObject *
140PyModule_GetWarningsModule(void)
141{
142 return PyImport_ImportModule("warnings");
143}
144
Eric Snowc7ec9982017-05-23 23:00:52 -0700145
Eric Snow1abcf672017-05-23 21:46:51 -0700146/* APIs to access the initialization flags
147 *
148 * Can be called prior to Py_Initialize.
149 */
Nick Coghland6009512014-11-20 21:39:37 +1000150
Eric Snow1abcf672017-05-23 21:46:51 -0700151int
152_Py_IsCoreInitialized(void)
153{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600154 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700155}
Nick Coghland6009512014-11-20 21:39:37 +1000156
157int
158Py_IsInitialized(void)
159{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600160 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000161}
162
163/* Helper to allow an embedding application to override the normal
164 * mechanism that attempts to figure out an appropriate IO encoding
165 */
166
167static char *_Py_StandardStreamEncoding = NULL;
168static char *_Py_StandardStreamErrors = NULL;
169
170int
171Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
172{
173 if (Py_IsInitialized()) {
174 /* This is too late to have any effect */
175 return -1;
176 }
Victor Stinner31e99082017-12-20 23:41:38 +0100177
178 int res = 0;
179
180 /* Py_SetStandardStreamEncoding() can be called before Py_Initialize(),
181 but Py_Initialize() can change the allocator. Use a known allocator
182 to be able to release the memory later. */
183 PyMemAllocatorEx old_alloc;
184 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
185
Nick Coghland6009512014-11-20 21:39:37 +1000186 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
187 * initialised yet.
188 *
189 * However, the raw memory allocators are initialised appropriately
190 * as C static variables, so _PyMem_RawStrdup is OK even though
191 * Py_Initialize hasn't been called yet.
192 */
193 if (encoding) {
194 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
195 if (!_Py_StandardStreamEncoding) {
Victor Stinner31e99082017-12-20 23:41:38 +0100196 res = -2;
197 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000198 }
199 }
200 if (errors) {
201 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
202 if (!_Py_StandardStreamErrors) {
203 if (_Py_StandardStreamEncoding) {
204 PyMem_RawFree(_Py_StandardStreamEncoding);
205 }
Victor Stinner31e99082017-12-20 23:41:38 +0100206 res = -3;
207 goto done;
Nick Coghland6009512014-11-20 21:39:37 +1000208 }
209 }
Steve Dower39294992016-08-30 21:22:36 -0700210#ifdef MS_WINDOWS
211 if (_Py_StandardStreamEncoding) {
212 /* Overriding the stream encoding implies legacy streams */
213 Py_LegacyWindowsStdioFlag = 1;
214 }
215#endif
Victor Stinner31e99082017-12-20 23:41:38 +0100216
217done:
218 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
219
220 return res;
Nick Coghland6009512014-11-20 21:39:37 +1000221}
222
Nick Coghlan6ea41862017-06-11 13:16:15 +1000223
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000224/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
225 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000226 initializations fail, a fatal error is issued and the function does
227 not return. On return, the first thread and interpreter state have
228 been created.
229
230 Locking: you must hold the interpreter lock while calling this.
231 (If the lock has not yet been initialized, that's equivalent to
232 having the lock, but you cannot use multiple threads.)
233
234*/
235
Nick Coghland6009512014-11-20 21:39:37 +1000236static char*
237get_codec_name(const char *encoding)
238{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200239 const char *name_utf8;
240 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000241 PyObject *codec, *name = NULL;
242
243 codec = _PyCodec_Lookup(encoding);
244 if (!codec)
245 goto error;
246
247 name = _PyObject_GetAttrId(codec, &PyId_name);
248 Py_CLEAR(codec);
249 if (!name)
250 goto error;
251
Serhiy Storchaka06515832016-11-20 09:13:07 +0200252 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000253 if (name_utf8 == NULL)
254 goto error;
255 name_str = _PyMem_RawStrdup(name_utf8);
256 Py_DECREF(name);
257 if (name_str == NULL) {
258 PyErr_NoMemory();
259 return NULL;
260 }
261 return name_str;
262
263error:
264 Py_XDECREF(codec);
265 Py_XDECREF(name);
266 return NULL;
267}
268
269static char*
270get_locale_encoding(void)
271{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700272#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000273 char* codeset = nl_langinfo(CODESET);
274 if (!codeset || codeset[0] == '\0') {
275 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
276 return NULL;
277 }
278 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200279#elif defined(__ANDROID__)
280 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000281#else
282 PyErr_SetNone(PyExc_NotImplementedError);
283 return NULL;
284#endif
285}
286
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800287static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700288initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000289{
290 PyObject *importlib;
291 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000292 PyObject *value;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800293 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000294
295 /* Import _importlib through its frozen version, _frozen_importlib. */
296 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800297 return _Py_INIT_ERR("can't import _frozen_importlib");
Nick Coghland6009512014-11-20 21:39:37 +1000298 }
299 else if (Py_VerboseFlag) {
300 PySys_FormatStderr("import _frozen_importlib # frozen\n");
301 }
302 importlib = PyImport_AddModule("_frozen_importlib");
303 if (importlib == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800304 return _Py_INIT_ERR("couldn't get _frozen_importlib from sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000305 }
306 interp->importlib = importlib;
307 Py_INCREF(interp->importlib);
308
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300309 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
310 if (interp->import_func == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800311 return _Py_INIT_ERR("__import__ not found");
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300312 Py_INCREF(interp->import_func);
313
Victor Stinnercd6e6942015-09-18 09:11:57 +0200314 /* Import the _imp module */
Benjamin Petersonc65ef772018-01-29 11:33:57 -0800315 impmod = PyInit__imp();
Nick Coghland6009512014-11-20 21:39:37 +1000316 if (impmod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800317 return _Py_INIT_ERR("can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000318 }
319 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200320 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000321 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600322 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800323 return _Py_INIT_ERR("can't save _imp to sys.modules");
Nick Coghland6009512014-11-20 21:39:37 +1000324 }
325
Victor Stinnercd6e6942015-09-18 09:11:57 +0200326 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000327 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
328 if (value == NULL) {
329 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800330 return _Py_INIT_ERR("importlib install failed");
Nick Coghland6009512014-11-20 21:39:37 +1000331 }
332 Py_DECREF(value);
333 Py_DECREF(impmod);
334
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800335 err = _PyImportZip_Init();
336 if (_Py_INIT_FAILED(err)) {
337 return err;
338 }
339
340 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000341}
342
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800343static _PyInitError
Eric Snow1abcf672017-05-23 21:46:51 -0700344initexternalimport(PyInterpreterState *interp)
345{
346 PyObject *value;
347 value = PyObject_CallMethod(interp->importlib,
348 "_install_external_importers", "");
349 if (value == NULL) {
350 PyErr_Print();
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800351 return _Py_INIT_ERR("external importer setup failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700352 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200353 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800354 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700355}
Nick Coghland6009512014-11-20 21:39:37 +1000356
Nick Coghlan6ea41862017-06-11 13:16:15 +1000357/* Helper functions to better handle the legacy C locale
358 *
359 * The legacy C locale assumes ASCII as the default text encoding, which
360 * causes problems not only for the CPython runtime, but also other
361 * components like GNU readline.
362 *
363 * Accordingly, when the CLI detects it, it attempts to coerce it to a
364 * more capable UTF-8 based alternative as follows:
365 *
366 * if (_Py_LegacyLocaleDetected()) {
367 * _Py_CoerceLegacyLocale();
368 * }
369 *
370 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
371 *
372 * Locale coercion also impacts the default error handler for the standard
373 * streams: while the usual default is "strict", the default for the legacy
374 * C locale and for any of the coercion target locales is "surrogateescape".
375 */
376
377int
378_Py_LegacyLocaleDetected(void)
379{
380#ifndef MS_WINDOWS
381 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000382 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
383 * the POSIX locale as a simple alias for the C locale, so
384 * we may also want to check for that explicitly.
385 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000386 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
387 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
388#else
389 /* Windows uses code pages instead of locales, so no locale is legacy */
390 return 0;
391#endif
392}
393
Nick Coghlaneb817952017-06-18 12:29:42 +1000394static const char *_C_LOCALE_WARNING =
395 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
396 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
397 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
398 "locales is recommended.\n";
399
Nick Coghlaneb817952017-06-18 12:29:42 +1000400static void
Victor Stinner94540602017-12-16 04:54:22 +0100401_emit_stderr_warning_for_legacy_locale(const _PyCoreConfig *core_config)
Nick Coghlaneb817952017-06-18 12:29:42 +1000402{
Victor Stinner94540602017-12-16 04:54:22 +0100403 if (core_config->coerce_c_locale_warn) {
Nick Coghlaneb817952017-06-18 12:29:42 +1000404 if (_Py_LegacyLocaleDetected()) {
405 fprintf(stderr, "%s", _C_LOCALE_WARNING);
406 }
407 }
408}
409
Nick Coghlan6ea41862017-06-11 13:16:15 +1000410typedef struct _CandidateLocale {
411 const char *locale_name; /* The locale to try as a coercion target */
412} _LocaleCoercionTarget;
413
414static _LocaleCoercionTarget _TARGET_LOCALES[] = {
415 {"C.UTF-8"},
416 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000417 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000418 {NULL}
419};
420
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200421static const char *
Nick Coghlan6ea41862017-06-11 13:16:15 +1000422get_default_standard_stream_error_handler(void)
423{
424 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
425 if (ctype_loc != NULL) {
426 /* "surrogateescape" is the default in the legacy C locale */
427 if (strcmp(ctype_loc, "C") == 0) {
428 return "surrogateescape";
429 }
430
431#ifdef PY_COERCE_C_LOCALE
432 /* "surrogateescape" is the default in locale coercion target locales */
433 const _LocaleCoercionTarget *target = NULL;
434 for (target = _TARGET_LOCALES; target->locale_name; target++) {
435 if (strcmp(ctype_loc, target->locale_name) == 0) {
436 return "surrogateescape";
437 }
438 }
439#endif
440 }
441
442 /* Otherwise return NULL to request the typical default error handler */
443 return NULL;
444}
445
446#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100447static const char C_LOCALE_COERCION_WARNING[] =
Nick Coghlan6ea41862017-06-11 13:16:15 +1000448 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
449 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
450
451static void
Victor Stinner94540602017-12-16 04:54:22 +0100452_coerce_default_locale_settings(const _PyCoreConfig *config, const _LocaleCoercionTarget *target)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000453{
454 const char *newloc = target->locale_name;
455
456 /* Reset locale back to currently configured defaults */
xdegaye1588be62017-11-12 12:45:59 +0100457 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000458
459 /* Set the relevant locale environment variable */
460 if (setenv("LC_CTYPE", newloc, 1)) {
461 fprintf(stderr,
462 "Error setting LC_CTYPE, skipping C locale coercion\n");
463 return;
464 }
Victor Stinner94540602017-12-16 04:54:22 +0100465 if (config->coerce_c_locale_warn) {
466 fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
Nick Coghlaneb817952017-06-18 12:29:42 +1000467 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000468
469 /* Reconfigure with the overridden environment variables */
xdegaye1588be62017-11-12 12:45:59 +0100470 _Py_SetLocaleFromEnv(LC_ALL);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000471}
472#endif
473
474void
Victor Stinner94540602017-12-16 04:54:22 +0100475_Py_CoerceLegacyLocale(const _PyCoreConfig *config)
Nick Coghlan6ea41862017-06-11 13:16:15 +1000476{
477#ifdef PY_COERCE_C_LOCALE
Victor Stinner94540602017-12-16 04:54:22 +0100478 const char *locale_override = getenv("LC_ALL");
479 if (locale_override == NULL || *locale_override == '\0') {
480 /* LC_ALL is also not set (or is set to an empty string) */
481 const _LocaleCoercionTarget *target = NULL;
482 for (target = _TARGET_LOCALES; target->locale_name; target++) {
483 const char *new_locale = setlocale(LC_CTYPE,
484 target->locale_name);
485 if (new_locale != NULL) {
xdegaye1588be62017-11-12 12:45:59 +0100486#if !defined(__APPLE__) && !defined(__ANDROID__) && \
Victor Stinner94540602017-12-16 04:54:22 +0100487defined(HAVE_LANGINFO_H) && defined(CODESET)
488 /* Also ensure that nl_langinfo works in this locale */
489 char *codeset = nl_langinfo(CODESET);
490 if (!codeset || *codeset == '\0') {
491 /* CODESET is not set or empty, so skip coercion */
492 new_locale = NULL;
493 _Py_SetLocaleFromEnv(LC_CTYPE);
494 continue;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000495 }
Victor Stinner94540602017-12-16 04:54:22 +0100496#endif
497 /* Successfully configured locale, so make it the default */
498 _coerce_default_locale_settings(config, target);
499 return;
Nick Coghlan6ea41862017-06-11 13:16:15 +1000500 }
501 }
502 }
503 /* No C locale warning here, as Py_Initialize will emit one later */
504#endif
505}
506
xdegaye1588be62017-11-12 12:45:59 +0100507/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
508 * isolate the idiosyncrasies of different libc implementations. It reads the
509 * appropriate environment variable and uses its value to select the locale for
510 * 'category'. */
511char *
512_Py_SetLocaleFromEnv(int category)
513{
514#ifdef __ANDROID__
515 const char *locale;
516 const char **pvar;
517#ifdef PY_COERCE_C_LOCALE
518 const char *coerce_c_locale;
519#endif
520 const char *utf8_locale = "C.UTF-8";
521 const char *env_var_set[] = {
522 "LC_ALL",
523 "LC_CTYPE",
524 "LANG",
525 NULL,
526 };
527
528 /* Android setlocale(category, "") doesn't check the environment variables
529 * and incorrectly sets the "C" locale at API 24 and older APIs. We only
530 * check the environment variables listed in env_var_set. */
531 for (pvar=env_var_set; *pvar; pvar++) {
532 locale = getenv(*pvar);
533 if (locale != NULL && *locale != '\0') {
534 if (strcmp(locale, utf8_locale) == 0 ||
535 strcmp(locale, "en_US.UTF-8") == 0) {
536 return setlocale(category, utf8_locale);
537 }
538 return setlocale(category, "C");
539 }
540 }
541
542 /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
543 * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
544 * Quote from POSIX section "8.2 Internationalization Variables":
545 * "4. If the LANG environment variable is not set or is set to the empty
546 * string, the implementation-defined default locale shall be used." */
547
548#ifdef PY_COERCE_C_LOCALE
549 coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
550 if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
551 /* Some other ported code may check the environment variables (e.g. in
552 * extension modules), so we make sure that they match the locale
553 * configuration */
554 if (setenv("LC_CTYPE", utf8_locale, 1)) {
555 fprintf(stderr, "Warning: failed setting the LC_CTYPE "
556 "environment variable to %s\n", utf8_locale);
557 }
558 }
559#endif
560 return setlocale(category, utf8_locale);
561#else /* __ANDROID__ */
562 return setlocale(category, "");
563#endif /* __ANDROID__ */
564}
565
Nick Coghlan6ea41862017-06-11 13:16:15 +1000566
Eric Snow1abcf672017-05-23 21:46:51 -0700567/* Global initializations. Can be undone by Py_Finalize(). Don't
568 call this twice without an intervening Py_Finalize() call.
569
570 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
571 must have a corresponding call to Py_Finalize.
572
573 Locking: you must hold the interpreter lock while calling these APIs.
574 (If the lock has not yet been initialized, that's equivalent to
575 having the lock, but you cannot use multiple threads.)
576
577*/
578
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200579static _PyInitError
580_Py_Initialize_ReconfigureCore(PyInterpreterState *interp,
581 const _PyCoreConfig *core_config)
582{
583 if (core_config->allocator != NULL) {
584 const char *allocator = _PyMem_GetAllocatorsName();
585 if (allocator == NULL || strcmp(core_config->allocator, allocator) != 0) {
586 return _Py_INIT_USER_ERR("cannot modify memory allocator "
587 "after first Py_Initialize()");
588 }
589 }
590
591 _PyCoreConfig_SetGlobalConfig(core_config);
592
593 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
594 return _Py_INIT_ERR("failed to copy core config");
595 }
596 return _Py_INIT_OK();
597}
598
599
Eric Snow1abcf672017-05-23 21:46:51 -0700600/* Begin interpreter initialization
601 *
602 * On return, the first thread and interpreter state have been created,
603 * but the compiler, signal handling, multithreading and
604 * multiple interpreter support, and codec infrastructure are not yet
605 * available.
606 *
607 * The import system will support builtin and frozen modules only.
608 * The only supported io is writing to sys.stderr
609 *
610 * If any operation invoked by this function fails, a fatal error is
611 * issued and the function does not return.
612 *
613 * Any code invoked from this function should *not* assume it has access
614 * to the Python C API (unless the API is explicitly listed as being
615 * safe to call without calling Py_Initialize first)
616 */
617
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800618_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200619_Py_InitializeCore_impl(PyInterpreterState **interp_p,
620 const _PyCoreConfig *core_config)
Nick Coghland6009512014-11-20 21:39:37 +1000621{
622 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800623 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +1000624
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200625 /* bpo-34008: For backward compatibility reasons, calling Py_Main() after
626 Py_Initialize() ignores the new configuration. */
627 if (_PyRuntime.core_initialized) {
628 PyThreadState *tstate = PyThreadState_GET();
629 if (!tstate) {
630 return _Py_INIT_ERR("no thread state found");
631 }
632
633 interp = tstate->interp;
634 if (interp == NULL) {
635 return _Py_INIT_ERR("no main interpreter found");
636 }
637 *interp_p = interp;
638
639 return _Py_Initialize_ReconfigureCore(interp, core_config);
640 }
641
642
643 _PyCoreConfig_SetGlobalConfig(core_config);
644
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800645 err = _PyRuntime_Initialize();
646 if (_Py_INIT_FAILED(err)) {
647 return err;
648 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600649
Victor Stinner31e99082017-12-20 23:41:38 +0100650 if (core_config->allocator != NULL) {
651 if (_PyMem_SetupAllocators(core_config->allocator) < 0) {
652 return _Py_INIT_USER_ERR("Unknown PYTHONMALLOC allocator");
653 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800654 }
655
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 if (_PyRuntime.initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800657 return _Py_INIT_ERR("main interpreter already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700658 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600659 if (_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800660 return _Py_INIT_ERR("runtime core already initialized");
Eric Snow1abcf672017-05-23 21:46:51 -0700661 }
662
663 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
664 * threads behave a little more gracefully at interpreter shutdown.
665 * We clobber it here so the new interpreter can start with a clean
666 * slate.
667 *
668 * However, this may still lead to misbehaviour if there are daemon
669 * threads still hanging around from a previous Py_Initialize/Finalize
670 * pair :(
671 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600672 _PyRuntime.finalizing = NULL;
673
Nick Coghlan6ea41862017-06-11 13:16:15 +1000674#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000675 /* Set up the LC_CTYPE locale, so we can obtain
676 the locale's charset without having to switch
677 locales. */
xdegaye1588be62017-11-12 12:45:59 +0100678 _Py_SetLocaleFromEnv(LC_CTYPE);
Victor Stinner94540602017-12-16 04:54:22 +0100679 _emit_stderr_warning_for_legacy_locale(core_config);
Nick Coghlan6ea41862017-06-11 13:16:15 +1000680#endif
Nick Coghland6009512014-11-20 21:39:37 +1000681
Victor Stinnerda273412017-12-15 01:46:02 +0100682 err = _Py_HashRandomization_Init(core_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800683 if (_Py_INIT_FAILED(err)) {
684 return err;
685 }
686
Victor Stinnerda273412017-12-15 01:46:02 +0100687 if (!core_config->use_hash_seed || core_config->hash_seed) {
Eric Snow1abcf672017-05-23 21:46:51 -0700688 /* Random or non-zero hash seed */
689 Py_HashRandomizationFlag = 1;
690 }
Nick Coghland6009512014-11-20 21:39:37 +1000691
Victor Stinnera7368ac2017-11-15 18:11:45 -0800692 err = _PyInterpreterState_Enable(&_PyRuntime);
693 if (_Py_INIT_FAILED(err)) {
694 return err;
695 }
696
Nick Coghland6009512014-11-20 21:39:37 +1000697 interp = PyInterpreterState_New();
Victor Stinnerda273412017-12-15 01:46:02 +0100698 if (interp == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800699 return _Py_INIT_ERR("can't make main interpreter");
Victor Stinnerda273412017-12-15 01:46:02 +0100700 }
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200701 *interp_p = interp;
Victor Stinnerda273412017-12-15 01:46:02 +0100702
703 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
704 return _Py_INIT_ERR("failed to copy core config");
705 }
Nick Coghland6009512014-11-20 21:39:37 +1000706
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200707 PyThreadState *tstate = PyThreadState_New(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000708 if (tstate == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800709 return _Py_INIT_ERR("can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000710 (void) PyThreadState_Swap(tstate);
711
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000712 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000713 destroying the GIL might fail when it is being referenced from
714 another running thread (see issue #9901).
715 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000716 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000717 _PyEval_FiniThreads();
Victor Stinner2914bb32018-01-29 11:57:45 +0100718
Nick Coghland6009512014-11-20 21:39:37 +1000719 /* Auto-thread-state API */
720 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000721
Victor Stinner2914bb32018-01-29 11:57:45 +0100722 /* Create the GIL */
723 PyEval_InitThreads();
724
Nick Coghland6009512014-11-20 21:39:37 +1000725 _Py_ReadyTypes();
726
727 if (!_PyFrame_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800728 return _Py_INIT_ERR("can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000729
730 if (!_PyLong_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800731 return _Py_INIT_ERR("can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000732
733 if (!PyByteArray_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800734 return _Py_INIT_ERR("can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000735
736 if (!_PyFloat_Init())
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800737 return _Py_INIT_ERR("can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000738
Eric Snowd393c1b2017-09-14 12:18:12 -0600739 PyObject *modules = PyDict_New();
740 if (modules == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800741 return _Py_INIT_ERR("can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600742 interp->modules = modules;
743
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200744 PyObject *sysmod;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800745 err = _PySys_BeginInit(&sysmod);
746 if (_Py_INIT_FAILED(err)) {
747 return err;
748 }
749
Eric Snowd393c1b2017-09-14 12:18:12 -0600750 interp->sysdict = PyModule_GetDict(sysmod);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800751 if (interp->sysdict == NULL) {
752 return _Py_INIT_ERR("can't initialize sys dict");
753 }
754
Eric Snowd393c1b2017-09-14 12:18:12 -0600755 Py_INCREF(interp->sysdict);
756 PyDict_SetItemString(interp->sysdict, "modules", modules);
757 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000758
759 /* Init Unicode implementation; relies on the codec registry */
760 if (_PyUnicode_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800761 return _Py_INIT_ERR("can't initialize unicode");
Eric Snow1abcf672017-05-23 21:46:51 -0700762
Nick Coghland6009512014-11-20 21:39:37 +1000763 if (_PyStructSequence_Init() < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800764 return _Py_INIT_ERR("can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000765
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200766 PyObject *bimod = _PyBuiltin_Init();
Nick Coghland6009512014-11-20 21:39:37 +1000767 if (bimod == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800768 return _Py_INIT_ERR("can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600769 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000770 interp->builtins = PyModule_GetDict(bimod);
771 if (interp->builtins == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800772 return _Py_INIT_ERR("can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000773 Py_INCREF(interp->builtins);
774
775 /* initialize builtin exceptions */
776 _PyExc_Init(bimod);
777
Nick Coghland6009512014-11-20 21:39:37 +1000778 /* Set up a preliminary stderr printer until we have enough
779 infrastructure for the io module in place. */
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200780 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
Nick Coghland6009512014-11-20 21:39:37 +1000781 if (pstderr == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800782 return _Py_INIT_ERR("can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000783 _PySys_SetObjectId(&PyId_stderr, pstderr);
784 PySys_SetObject("__stderr__", pstderr);
785 Py_DECREF(pstderr);
786
Victor Stinner672b6ba2017-12-06 17:25:50 +0100787 err = _PyImport_Init(interp);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800788 if (_Py_INIT_FAILED(err)) {
789 return err;
790 }
Nick Coghland6009512014-11-20 21:39:37 +1000791
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800792 err = _PyImportHooks_Init();
793 if (_Py_INIT_FAILED(err)) {
794 return err;
795 }
Nick Coghland6009512014-11-20 21:39:37 +1000796
797 /* Initialize _warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100798 if (_PyWarnings_Init() == NULL) {
Victor Stinner1f151112017-11-23 10:43:14 +0100799 return _Py_INIT_ERR("can't initialize warnings");
800 }
Nick Coghland6009512014-11-20 21:39:37 +1000801
Yury Selivanovf23746a2018-01-22 19:11:18 -0500802 if (!_PyContext_Init())
803 return _Py_INIT_ERR("can't init context");
804
Eric Snow1abcf672017-05-23 21:46:51 -0700805 /* This call sets up builtin and frozen import support */
806 if (!interp->core_config._disable_importlib) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800807 err = initimport(interp, sysmod);
808 if (_Py_INIT_FAILED(err)) {
809 return err;
810 }
Eric Snow1abcf672017-05-23 21:46:51 -0700811 }
812
813 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600814 _PyRuntime.core_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800815 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700816}
817
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200818
819_PyInitError
820_Py_InitializeCore(PyInterpreterState **interp_p,
821 const _PyCoreConfig *src_config)
822{
823 assert(src_config != NULL);
824
825 PyMemAllocatorEx old_alloc;
826 _PyInitError err;
827
828 /* Copy the configuration, since _PyCoreConfig_Read() modifies it
829 (and the input configuration is read only). */
830 _PyCoreConfig config = _PyCoreConfig_INIT;
831
832 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
833 if (_PyCoreConfig_Copy(&config, src_config) >= 0) {
834 err = _PyCoreConfig_Read(&config);
835 }
836 else {
837 err = _Py_INIT_ERR("failed to copy core config");
838 }
839 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
840
841 if (_Py_INIT_FAILED(err)) {
842 goto done;
843 }
844
845 err = _Py_InitializeCore_impl(interp_p, &config);
846
847done:
848 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
849 _PyCoreConfig_Clear(&config);
850 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
851
852 return err;
853}
854
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700855/* Py_Initialize() has already been called: update the main interpreter
856 configuration. Example of bpo-34008: Py_Main() called after
857 Py_Initialize(). */
858static _PyInitError
859_Py_ReconfigureMainInterpreter(PyInterpreterState *interp,
860 const _PyMainInterpreterConfig *config)
861{
862 if (config->argv != NULL) {
863 int res = PyDict_SetItemString(interp->sysdict, "argv", config->argv);
864 if (res < 0) {
865 return _Py_INIT_ERR("fail to set sys.argv");
866 }
867 }
868 return _Py_INIT_OK();
869}
870
Eric Snowc7ec9982017-05-23 23:00:52 -0700871/* Update interpreter state based on supplied configuration settings
872 *
873 * After calling this function, most of the restrictions on the interpreter
874 * are lifted. The only remaining incomplete settings are those related
875 * to the main module (sys.argv[0], __main__ metadata)
876 *
877 * Calling this when the interpreter is not initializing, is already
878 * initialized or without a valid current thread state is a fatal error.
879 * Other errors should be reported as normal Python exceptions with a
880 * non-zero return code.
881 */
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800882_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200883_Py_InitializeMainInterpreter(PyInterpreterState *interp,
884 const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700885{
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800886 _PyInitError err;
Eric Snow1abcf672017-05-23 21:46:51 -0700887
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600888 if (!_PyRuntime.core_initialized) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800889 return _Py_INIT_ERR("runtime core not initialized");
Eric Snowc7ec9982017-05-23 23:00:52 -0700890 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700891
Eric Snow1abcf672017-05-23 21:46:51 -0700892 /* Now finish configuring the main interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +0100893 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
894 return _Py_INIT_ERR("failed to copy main interpreter config");
895 }
Eric Snowc7ec9982017-05-23 23:00:52 -0700896
Miss Islington (bot)03ec4df2018-07-20 17:16:22 -0700897 if (_PyRuntime.initialized) {
898 return _Py_ReconfigureMainInterpreter(interp, config);
899 }
900
Eric Snow1abcf672017-05-23 21:46:51 -0700901 if (interp->core_config._disable_importlib) {
902 /* Special mode for freeze_importlib: run with no import system
903 *
904 * This means anything which needs support from extension modules
905 * or pure Python code in the standard library won't work.
906 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600907 _PyRuntime.initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800908 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -0700909 }
Victor Stinner9316ee42017-11-25 03:17:57 +0100910
Victor Stinner33c377e2017-12-05 15:12:41 +0100911 if (_PyTime_Init() < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800912 return _Py_INIT_ERR("can't initialize time");
Victor Stinner33c377e2017-12-05 15:12:41 +0100913 }
Victor Stinner13019fd2015-04-03 13:10:54 +0200914
Victor Stinner41264f12017-12-15 02:05:29 +0100915 if (_PySys_EndInit(interp->sysdict, &interp->config) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800916 return _Py_INIT_ERR("can't finish initializing sys");
Victor Stinnerda273412017-12-15 01:46:02 +0100917 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800918
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800919 err = initexternalimport(interp);
920 if (_Py_INIT_FAILED(err)) {
921 return err;
922 }
Nick Coghland6009512014-11-20 21:39:37 +1000923
924 /* initialize the faulthandler module */
Victor Stinnera7368ac2017-11-15 18:11:45 -0800925 err = _PyFaulthandler_Init(interp->core_config.faulthandler);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800926 if (_Py_INIT_FAILED(err)) {
927 return err;
928 }
Nick Coghland6009512014-11-20 21:39:37 +1000929
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800930 err = initfsencoding(interp);
931 if (_Py_INIT_FAILED(err)) {
932 return err;
933 }
Nick Coghland6009512014-11-20 21:39:37 +1000934
Victor Stinner1f151112017-11-23 10:43:14 +0100935 if (interp->config.install_signal_handlers) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800936 err = initsigs(); /* Signal handling stuff, including initintr() */
937 if (_Py_INIT_FAILED(err)) {
938 return err;
939 }
940 }
Nick Coghland6009512014-11-20 21:39:37 +1000941
Victor Stinnera7368ac2017-11-15 18:11:45 -0800942 if (_PyTraceMalloc_Init(interp->core_config.tracemalloc) < 0)
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800943 return _Py_INIT_ERR("can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000944
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800945 err = add_main_module(interp);
946 if (_Py_INIT_FAILED(err)) {
947 return err;
948 }
Victor Stinnera7368ac2017-11-15 18:11:45 -0800949
Victor Stinner91106cd2017-12-13 12:29:09 +0100950 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -0800951 if (_Py_INIT_FAILED(err)) {
952 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800953 }
Nick Coghland6009512014-11-20 21:39:37 +1000954
955 /* Initialize warnings. */
Victor Stinner5d862462017-12-19 11:35:58 +0100956 if (interp->config.warnoptions != NULL &&
957 PyList_Size(interp->config.warnoptions) > 0)
958 {
Nick Coghland6009512014-11-20 21:39:37 +1000959 PyObject *warnings_module = PyImport_ImportModule("warnings");
960 if (warnings_module == NULL) {
961 fprintf(stderr, "'import warnings' failed; traceback:\n");
962 PyErr_Print();
963 }
964 Py_XDECREF(warnings_module);
965 }
966
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600967 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700968
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800969 if (!Py_NoSiteFlag) {
970 err = initsite(); /* Module site */
971 if (_Py_INIT_FAILED(err)) {
972 return err;
973 }
974 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800975 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +1000976}
977
Eric Snowc7ec9982017-05-23 23:00:52 -0700978#undef _INIT_DEBUG_PRINT
979
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200980
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800981_PyInitError
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200982_Py_InitializeFromConfig(const _PyCoreConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700983{
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200984 _Py_Initialize_ReadEnvVarsNoAlloc();
Miss Islington (bot)3747dd12018-06-22 10:33:48 -0700985
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200986 PyInterpreterState *interp;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800987 _PyInitError err;
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200988 err = _Py_InitializeCore(&interp, config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800989 if (_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200990 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800991 }
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200992 config = &interp->core_config;
Victor Stinnerbc8ac6b2017-11-30 18:03:55 +0100993
Victor Stinner9cfc0022017-12-20 19:36:46 +0100994 _PyMainInterpreterConfig main_config = _PyMainInterpreterConfig_INIT;
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200995 err = _PyMainInterpreterConfig_Read(&main_config, config);
Victor Stinner9cfc0022017-12-20 19:36:46 +0100996 if (!_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +0200997 err = _Py_InitializeMainInterpreter(interp, &main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -0800998 }
Victor Stinner9cfc0022017-12-20 19:36:46 +0100999 _PyMainInterpreterConfig_Clear(&main_config);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001000 if (_Py_INIT_FAILED(err)) {
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001001 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001002 }
1003
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001004 return _Py_INIT_OK();
Eric Snow1abcf672017-05-23 21:46:51 -07001005}
1006
1007
1008void
Nick Coghland6009512014-11-20 21:39:37 +10001009Py_InitializeEx(int install_sigs)
1010{
Victor Stinner0c90d6f2018-08-05 12:31:59 +02001011 if (_PyRuntime.initialized) {
1012 /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1013 return;
1014 }
1015
1016 _PyInitError err;
1017 _PyCoreConfig config = _PyCoreConfig_INIT;
1018 config.install_signal_handlers = install_sigs;
1019
1020 err = _Py_InitializeFromConfig(&config);
1021 _PyCoreConfig_Clear(&config);
1022
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001023 if (_Py_INIT_FAILED(err)) {
1024 _Py_FatalInitError(err);
1025 }
Nick Coghland6009512014-11-20 21:39:37 +10001026}
1027
1028void
1029Py_Initialize(void)
1030{
1031 Py_InitializeEx(1);
1032}
1033
1034
1035#ifdef COUNT_ALLOCS
1036extern void dump_counts(FILE*);
1037#endif
1038
1039/* Flush stdout and stderr */
1040
1041static int
1042file_is_closed(PyObject *fobj)
1043{
1044 int r;
1045 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1046 if (tmp == NULL) {
1047 PyErr_Clear();
1048 return 0;
1049 }
1050 r = PyObject_IsTrue(tmp);
1051 Py_DECREF(tmp);
1052 if (r < 0)
1053 PyErr_Clear();
1054 return r > 0;
1055}
1056
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001057static int
Nick Coghland6009512014-11-20 21:39:37 +10001058flush_std_files(void)
1059{
1060 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1061 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1062 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001063 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001064
1065 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001066 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001067 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001068 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001069 status = -1;
1070 }
Nick Coghland6009512014-11-20 21:39:37 +10001071 else
1072 Py_DECREF(tmp);
1073 }
1074
1075 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -07001076 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001077 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001078 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001079 status = -1;
1080 }
Nick Coghland6009512014-11-20 21:39:37 +10001081 else
1082 Py_DECREF(tmp);
1083 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001084
1085 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001086}
1087
1088/* Undo the effect of Py_Initialize().
1089
1090 Beware: if multiple interpreter and/or thread states exist, these
1091 are not wiped out; only the current thread and interpreter state
1092 are deleted. But since everything else is deleted, those other
1093 interpreter and thread states should no longer be used.
1094
1095 (XXX We should do better, e.g. wipe out all interpreters and
1096 threads.)
1097
1098 Locking: as above.
1099
1100*/
1101
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001102int
1103Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +10001104{
1105 PyInterpreterState *interp;
1106 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001107 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001108
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001109 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001110 return status;
Nick Coghland6009512014-11-20 21:39:37 +10001111
1112 wait_for_thread_shutdown();
1113
Marcel Plch776407f2017-12-20 11:17:58 +01001114 /* Get current thread state and interpreter pointer */
1115 tstate = PyThreadState_GET();
1116 interp = tstate->interp;
1117
Nick Coghland6009512014-11-20 21:39:37 +10001118 /* The interpreter is still entirely intact at this point, and the
1119 * exit funcs may be relying on that. In particular, if some thread
1120 * or exit func is still waiting to do an import, the import machinery
1121 * expects Py_IsInitialized() to return true. So don't say the
1122 * interpreter is uninitialized until after the exit funcs have run.
1123 * Note that Threading.py uses an exit func to do a join on all the
1124 * threads created thru it, so this also protects pending imports in
1125 * the threads created via Threading.
1126 */
Nick Coghland6009512014-11-20 21:39:37 +10001127
Marcel Plch776407f2017-12-20 11:17:58 +01001128 call_py_exitfuncs(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001129
Victor Stinnerda273412017-12-15 01:46:02 +01001130 /* Copy the core config, PyInterpreterState_Delete() free
1131 the core config memory */
Victor Stinner5d862462017-12-19 11:35:58 +01001132#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001133 int show_ref_count = interp->core_config.show_ref_count;
Victor Stinner5d862462017-12-19 11:35:58 +01001134#endif
1135#ifdef Py_TRACE_REFS
Victor Stinnerda273412017-12-15 01:46:02 +01001136 int dump_refs = interp->core_config.dump_refs;
Victor Stinner5d862462017-12-19 11:35:58 +01001137#endif
1138#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001139 int malloc_stats = interp->core_config.malloc_stats;
Victor Stinner5d862462017-12-19 11:35:58 +01001140#endif
Victor Stinner6bf992a2017-12-06 17:26:10 +01001141
Nick Coghland6009512014-11-20 21:39:37 +10001142 /* Remaining threads (e.g. daemon threads) will automatically exit
1143 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001144 _PyRuntime.finalizing = tstate;
1145 _PyRuntime.initialized = 0;
1146 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +10001147
Victor Stinnere0deff32015-03-24 13:46:18 +01001148 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001149 if (flush_std_files() < 0) {
1150 status = -1;
1151 }
Nick Coghland6009512014-11-20 21:39:37 +10001152
1153 /* Disable signal handling */
1154 PyOS_FiniInterrupts();
1155
1156 /* Collect garbage. This may call finalizers; it's nice to call these
1157 * before all modules are destroyed.
1158 * XXX If a __del__ or weakref callback is triggered here, and tries to
1159 * XXX import a module, bad things can happen, because Python no
1160 * XXX longer believes it's initialized.
1161 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1162 * XXX is easy to provoke that way. I've also seen, e.g.,
1163 * XXX Exception exceptions.ImportError: 'No module named sha'
1164 * XXX in <function callback at 0x008F5718> ignored
1165 * XXX but I'm unclear on exactly how that one happens. In any case,
1166 * XXX I haven't seen a real-life report of either of these.
1167 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001168 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001169#ifdef COUNT_ALLOCS
1170 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1171 each collection might release some types from the type
1172 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001173 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001174 /* nothing */;
1175#endif
Eric Snowdae02762017-09-14 00:35:58 -07001176
Nick Coghland6009512014-11-20 21:39:37 +10001177 /* Destroy all modules */
1178 PyImport_Cleanup();
1179
Victor Stinnere0deff32015-03-24 13:46:18 +01001180 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001181 if (flush_std_files() < 0) {
1182 status = -1;
1183 }
Nick Coghland6009512014-11-20 21:39:37 +10001184
1185 /* Collect final garbage. This disposes of cycles created by
1186 * class definitions, for example.
1187 * XXX This is disabled because it caused too many problems. If
1188 * XXX a __del__ or weakref callback triggers here, Python code has
1189 * XXX a hard time running, because even the sys module has been
1190 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1191 * XXX One symptom is a sequence of information-free messages
1192 * XXX coming from threads (if a __del__ or callback is invoked,
1193 * XXX other threads can execute too, and any exception they encounter
1194 * XXX triggers a comedy of errors as subsystem after subsystem
1195 * XXX fails to find what it *expects* to find in sys to help report
1196 * XXX the exception and consequent unexpected failures). I've also
1197 * XXX seen segfaults then, after adding print statements to the
1198 * XXX Python code getting called.
1199 */
1200#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001201 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001202#endif
1203
1204 /* Disable tracemalloc after all Python objects have been destroyed,
1205 so it is possible to use tracemalloc in objects destructor. */
1206 _PyTraceMalloc_Fini();
1207
1208 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1209 _PyImport_Fini();
1210
1211 /* Cleanup typeobject.c's internal caches. */
1212 _PyType_Fini();
1213
1214 /* unload faulthandler module */
1215 _PyFaulthandler_Fini();
1216
1217 /* Debugging stuff */
1218#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001219 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001220#endif
1221 /* dump hash stats */
1222 _PyHash_Fini();
1223
Eric Snowdae02762017-09-14 00:35:58 -07001224#ifdef Py_REF_DEBUG
Victor Stinnerda273412017-12-15 01:46:02 +01001225 if (show_ref_count) {
Victor Stinner25420fe2017-11-20 18:12:22 -08001226 _PyDebug_PrintTotalRefs();
1227 }
Eric Snowdae02762017-09-14 00:35:58 -07001228#endif
Nick Coghland6009512014-11-20 21:39:37 +10001229
1230#ifdef Py_TRACE_REFS
1231 /* Display all objects still alive -- this can invoke arbitrary
1232 * __repr__ overrides, so requires a mostly-intact interpreter.
1233 * Alas, a lot of stuff may still be alive now that will be cleaned
1234 * up later.
1235 */
Victor Stinnerda273412017-12-15 01:46:02 +01001236 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001237 _Py_PrintReferences(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001238 }
Nick Coghland6009512014-11-20 21:39:37 +10001239#endif /* Py_TRACE_REFS */
1240
1241 /* Clear interpreter state and all thread states. */
1242 PyInterpreterState_Clear(interp);
1243
1244 /* Now we decref the exception classes. After this point nothing
1245 can raise an exception. That's okay, because each Fini() method
1246 below has been checked to make sure no exceptions are ever
1247 raised.
1248 */
1249
1250 _PyExc_Fini();
1251
1252 /* Sundry finalizers */
1253 PyMethod_Fini();
1254 PyFrame_Fini();
1255 PyCFunction_Fini();
1256 PyTuple_Fini();
1257 PyList_Fini();
1258 PySet_Fini();
1259 PyBytes_Fini();
1260 PyByteArray_Fini();
1261 PyLong_Fini();
1262 PyFloat_Fini();
1263 PyDict_Fini();
1264 PySlice_Fini();
1265 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001266 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001267 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001268 PyAsyncGen_Fini();
Yury Selivanovf23746a2018-01-22 19:11:18 -05001269 _PyContext_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001270
1271 /* Cleanup Unicode implementation */
1272 _PyUnicode_Fini();
1273
1274 /* reset file system default encoding */
1275 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1276 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1277 Py_FileSystemDefaultEncoding = NULL;
1278 }
1279
1280 /* XXX Still allocated:
1281 - various static ad-hoc pointers to interned strings
1282 - int and float free list blocks
1283 - whatever various modules and libraries allocate
1284 */
1285
1286 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1287
1288 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001289 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001290
1291 /* Delete current thread. After this, many C API calls become crashy. */
1292 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001293
Nick Coghland6009512014-11-20 21:39:37 +10001294 PyInterpreterState_Delete(interp);
1295
1296#ifdef Py_TRACE_REFS
1297 /* Display addresses (& refcnts) of all objects still alive.
1298 * An address can be used to find the repr of the object, printed
1299 * above by _Py_PrintReferences.
1300 */
Victor Stinnerda273412017-12-15 01:46:02 +01001301 if (dump_refs) {
Nick Coghland6009512014-11-20 21:39:37 +10001302 _Py_PrintReferenceAddresses(stderr);
Victor Stinner6bf992a2017-12-06 17:26:10 +01001303 }
Nick Coghland6009512014-11-20 21:39:37 +10001304#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001305#ifdef WITH_PYMALLOC
Victor Stinnerda273412017-12-15 01:46:02 +01001306 if (malloc_stats) {
Victor Stinner6bf992a2017-12-06 17:26:10 +01001307 _PyObject_DebugMallocStats(stderr);
Victor Stinner34be8072016-03-14 12:04:26 +01001308 }
Nick Coghland6009512014-11-20 21:39:37 +10001309#endif
1310
1311 call_ll_exitfuncs();
Victor Stinner9316ee42017-11-25 03:17:57 +01001312
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001313 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001314 return status;
1315}
1316
1317void
1318Py_Finalize(void)
1319{
1320 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001321}
1322
1323/* Create and initialize a new interpreter and thread, and return the
1324 new thread. This requires that Py_Initialize() has been called
1325 first.
1326
1327 Unsuccessful initialization yields a NULL pointer. Note that *no*
1328 exception information is available even in this case -- the
1329 exception information is held in the thread, and there is no
1330 thread.
1331
1332 Locking: as above.
1333
1334*/
1335
Victor Stinnera7368ac2017-11-15 18:11:45 -08001336static _PyInitError
1337new_interpreter(PyThreadState **tstate_p)
Nick Coghland6009512014-11-20 21:39:37 +10001338{
1339 PyInterpreterState *interp;
1340 PyThreadState *tstate, *save_tstate;
1341 PyObject *bimod, *sysmod;
Victor Stinner9316ee42017-11-25 03:17:57 +01001342 _PyInitError err;
Nick Coghland6009512014-11-20 21:39:37 +10001343
Victor Stinnera7368ac2017-11-15 18:11:45 -08001344 if (!_PyRuntime.initialized) {
1345 return _Py_INIT_ERR("Py_Initialize must be called first");
1346 }
Nick Coghland6009512014-11-20 21:39:37 +10001347
Victor Stinner8a1be612016-03-14 22:07:55 +01001348 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1349 interpreters: disable PyGILState_Check(). */
1350 _PyGILState_check_enabled = 0;
1351
Nick Coghland6009512014-11-20 21:39:37 +10001352 interp = PyInterpreterState_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001353 if (interp == NULL) {
1354 *tstate_p = NULL;
1355 return _Py_INIT_OK();
1356 }
Nick Coghland6009512014-11-20 21:39:37 +10001357
1358 tstate = PyThreadState_New(interp);
1359 if (tstate == NULL) {
1360 PyInterpreterState_Delete(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001361 *tstate_p = NULL;
1362 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001363 }
1364
1365 save_tstate = PyThreadState_Swap(tstate);
1366
Eric Snow1abcf672017-05-23 21:46:51 -07001367 /* Copy the current interpreter config into the new interpreter */
Victor Stinnerda273412017-12-15 01:46:02 +01001368 _PyCoreConfig *core_config;
1369 _PyMainInterpreterConfig *config;
Eric Snow1abcf672017-05-23 21:46:51 -07001370 if (save_tstate != NULL) {
Victor Stinnerda273412017-12-15 01:46:02 +01001371 core_config = &save_tstate->interp->core_config;
1372 config = &save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001373 } else {
1374 /* No current thread state, copy from the main interpreter */
1375 PyInterpreterState *main_interp = PyInterpreterState_Main();
Victor Stinnerda273412017-12-15 01:46:02 +01001376 core_config = &main_interp->core_config;
1377 config = &main_interp->config;
1378 }
1379
1380 if (_PyCoreConfig_Copy(&interp->core_config, core_config) < 0) {
1381 return _Py_INIT_ERR("failed to copy core config");
1382 }
1383 if (_PyMainInterpreterConfig_Copy(&interp->config, config) < 0) {
1384 return _Py_INIT_ERR("failed to copy main interpreter config");
Eric Snow1abcf672017-05-23 21:46:51 -07001385 }
1386
Nick Coghland6009512014-11-20 21:39:37 +10001387 /* XXX The following is lax in error checking */
Eric Snowd393c1b2017-09-14 12:18:12 -06001388 PyObject *modules = PyDict_New();
Victor Stinnera7368ac2017-11-15 18:11:45 -08001389 if (modules == NULL) {
1390 return _Py_INIT_ERR("can't make modules dictionary");
1391 }
Eric Snowd393c1b2017-09-14 12:18:12 -06001392 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001393
Eric Snowd393c1b2017-09-14 12:18:12 -06001394 sysmod = _PyImport_FindBuiltin("sys", modules);
1395 if (sysmod != NULL) {
1396 interp->sysdict = PyModule_GetDict(sysmod);
1397 if (interp->sysdict == NULL)
1398 goto handle_error;
1399 Py_INCREF(interp->sysdict);
1400 PyDict_SetItemString(interp->sysdict, "modules", modules);
Victor Stinner41264f12017-12-15 02:05:29 +01001401 _PySys_EndInit(interp->sysdict, &interp->config);
Eric Snowd393c1b2017-09-14 12:18:12 -06001402 }
1403
1404 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001405 if (bimod != NULL) {
1406 interp->builtins = PyModule_GetDict(bimod);
1407 if (interp->builtins == NULL)
1408 goto handle_error;
1409 Py_INCREF(interp->builtins);
1410 }
1411
1412 /* initialize builtin exceptions */
1413 _PyExc_Init(bimod);
1414
Nick Coghland6009512014-11-20 21:39:37 +10001415 if (bimod != NULL && sysmod != NULL) {
1416 PyObject *pstderr;
1417
Nick Coghland6009512014-11-20 21:39:37 +10001418 /* Set up a preliminary stderr printer until we have enough
1419 infrastructure for the io module in place. */
1420 pstderr = PyFile_NewStdPrinter(fileno(stderr));
Victor Stinnera7368ac2017-11-15 18:11:45 -08001421 if (pstderr == NULL) {
1422 return _Py_INIT_ERR("can't set preliminary stderr");
1423 }
Nick Coghland6009512014-11-20 21:39:37 +10001424 _PySys_SetObjectId(&PyId_stderr, pstderr);
1425 PySys_SetObject("__stderr__", pstderr);
1426 Py_DECREF(pstderr);
1427
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001428 err = _PyImportHooks_Init();
1429 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001430 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001431 }
Nick Coghland6009512014-11-20 21:39:37 +10001432
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001433 err = initimport(interp, sysmod);
1434 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001435 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001436 }
Nick Coghland6009512014-11-20 21:39:37 +10001437
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001438 err = initexternalimport(interp);
1439 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001440 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001441 }
Nick Coghland6009512014-11-20 21:39:37 +10001442
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001443 err = initfsencoding(interp);
1444 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001445 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001446 }
1447
Victor Stinner91106cd2017-12-13 12:29:09 +01001448 err = init_sys_streams(interp);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001449 if (_Py_INIT_FAILED(err)) {
1450 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001451 }
1452
1453 err = add_main_module(interp);
1454 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001455 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001456 }
1457
1458 if (!Py_NoSiteFlag) {
1459 err = initsite();
1460 if (_Py_INIT_FAILED(err)) {
Victor Stinnera7368ac2017-11-15 18:11:45 -08001461 return err;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001462 }
1463 }
Nick Coghland6009512014-11-20 21:39:37 +10001464 }
1465
Victor Stinnera7368ac2017-11-15 18:11:45 -08001466 if (PyErr_Occurred()) {
1467 goto handle_error;
1468 }
Nick Coghland6009512014-11-20 21:39:37 +10001469
Victor Stinnera7368ac2017-11-15 18:11:45 -08001470 *tstate_p = tstate;
1471 return _Py_INIT_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001472
Nick Coghland6009512014-11-20 21:39:37 +10001473handle_error:
1474 /* Oops, it didn't work. Undo it all. */
1475
1476 PyErr_PrintEx(0);
1477 PyThreadState_Clear(tstate);
1478 PyThreadState_Swap(save_tstate);
1479 PyThreadState_Delete(tstate);
1480 PyInterpreterState_Delete(interp);
1481
Victor Stinnera7368ac2017-11-15 18:11:45 -08001482 *tstate_p = NULL;
1483 return _Py_INIT_OK();
1484}
1485
1486PyThreadState *
1487Py_NewInterpreter(void)
1488{
1489 PyThreadState *tstate;
1490 _PyInitError err = new_interpreter(&tstate);
1491 if (_Py_INIT_FAILED(err)) {
1492 _Py_FatalInitError(err);
1493 }
1494 return tstate;
1495
Nick Coghland6009512014-11-20 21:39:37 +10001496}
1497
1498/* Delete an interpreter and its last thread. This requires that the
1499 given thread state is current, that the thread has no remaining
1500 frames, and that it is its interpreter's only remaining thread.
1501 It is a fatal error to violate these constraints.
1502
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001503 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001504 everything, regardless.)
1505
1506 Locking: as above.
1507
1508*/
1509
1510void
1511Py_EndInterpreter(PyThreadState *tstate)
1512{
1513 PyInterpreterState *interp = tstate->interp;
1514
1515 if (tstate != PyThreadState_GET())
1516 Py_FatalError("Py_EndInterpreter: thread is not current");
1517 if (tstate->frame != NULL)
1518 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1519
1520 wait_for_thread_shutdown();
1521
Marcel Plch776407f2017-12-20 11:17:58 +01001522 call_py_exitfuncs(interp);
1523
Nick Coghland6009512014-11-20 21:39:37 +10001524 if (tstate != interp->tstate_head || tstate->next != NULL)
1525 Py_FatalError("Py_EndInterpreter: not the last thread");
1526
1527 PyImport_Cleanup();
1528 PyInterpreterState_Clear(interp);
1529 PyThreadState_Swap(NULL);
1530 PyInterpreterState_Delete(interp);
1531}
1532
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001533/* Add the __main__ module */
Nick Coghland6009512014-11-20 21:39:37 +10001534
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001535static _PyInitError
1536add_main_module(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001537{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001538 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001539 m = PyImport_AddModule("__main__");
1540 if (m == NULL)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001541 return _Py_INIT_ERR("can't create __main__ module");
1542
Nick Coghland6009512014-11-20 21:39:37 +10001543 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001544 ann_dict = PyDict_New();
1545 if ((ann_dict == NULL) ||
1546 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001547 return _Py_INIT_ERR("Failed to initialize __main__.__annotations__");
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001548 }
1549 Py_DECREF(ann_dict);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001550
Nick Coghland6009512014-11-20 21:39:37 +10001551 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1552 PyObject *bimod = PyImport_ImportModule("builtins");
1553 if (bimod == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001554 return _Py_INIT_ERR("Failed to retrieve builtins module");
Nick Coghland6009512014-11-20 21:39:37 +10001555 }
1556 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001557 return _Py_INIT_ERR("Failed to initialize __main__.__builtins__");
Nick Coghland6009512014-11-20 21:39:37 +10001558 }
1559 Py_DECREF(bimod);
1560 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001561
Nick Coghland6009512014-11-20 21:39:37 +10001562 /* Main is a little special - imp.is_builtin("__main__") will return
1563 * False, but BuiltinImporter is still the most appropriate initial
1564 * setting for its __loader__ attribute. A more suitable value will
1565 * be set if __main__ gets further initialized later in the startup
1566 * process.
1567 */
1568 loader = PyDict_GetItemString(d, "__loader__");
1569 if (loader == NULL || loader == Py_None) {
1570 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1571 "BuiltinImporter");
1572 if (loader == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001573 return _Py_INIT_ERR("Failed to retrieve BuiltinImporter");
Nick Coghland6009512014-11-20 21:39:37 +10001574 }
1575 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001576 return _Py_INIT_ERR("Failed to initialize __main__.__loader__");
Nick Coghland6009512014-11-20 21:39:37 +10001577 }
1578 Py_DECREF(loader);
1579 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001580 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001581}
1582
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001583static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001584initfsencoding(PyInterpreterState *interp)
1585{
1586 PyObject *codec;
1587
Steve Dowercc16be82016-09-08 10:35:16 -07001588#ifdef MS_WINDOWS
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001589 if (Py_LegacyWindowsFSEncodingFlag) {
Steve Dowercc16be82016-09-08 10:35:16 -07001590 Py_FileSystemDefaultEncoding = "mbcs";
1591 Py_FileSystemDefaultEncodeErrors = "replace";
1592 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001593 else {
Steve Dowercc16be82016-09-08 10:35:16 -07001594 Py_FileSystemDefaultEncoding = "utf-8";
1595 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1596 }
1597#else
Victor Stinner91106cd2017-12-13 12:29:09 +01001598 if (Py_FileSystemDefaultEncoding == NULL &&
1599 interp->core_config.utf8_mode)
1600 {
1601 Py_FileSystemDefaultEncoding = "utf-8";
1602 Py_HasFileSystemDefaultEncoding = 1;
1603 }
1604 else if (Py_FileSystemDefaultEncoding == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +10001605 Py_FileSystemDefaultEncoding = get_locale_encoding();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001606 if (Py_FileSystemDefaultEncoding == NULL) {
1607 return _Py_INIT_ERR("Unable to get the locale encoding");
1608 }
Nick Coghland6009512014-11-20 21:39:37 +10001609
1610 Py_HasFileSystemDefaultEncoding = 0;
1611 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001612 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001613 }
Steve Dowercc16be82016-09-08 10:35:16 -07001614#endif
Nick Coghland6009512014-11-20 21:39:37 +10001615
1616 /* the encoding is mbcs, utf-8 or ascii */
1617 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1618 if (!codec) {
1619 /* Such error can only occurs in critical situations: no more
1620 * memory, import a module of the standard library failed,
1621 * etc. */
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001622 return _Py_INIT_ERR("unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +10001623 }
1624 Py_DECREF(codec);
1625 interp->fscodec_initialized = 1;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001626 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001627}
1628
1629/* Import the site module (not into __main__ though) */
1630
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001631static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10001632initsite(void)
1633{
1634 PyObject *m;
1635 m = PyImport_ImportModule("site");
1636 if (m == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001637 return _Py_INIT_USER_ERR("Failed to import the site module");
Nick Coghland6009512014-11-20 21:39:37 +10001638 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001639 Py_DECREF(m);
1640 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001641}
1642
Victor Stinner874dbe82015-09-04 17:29:57 +02001643/* Check if a file descriptor is valid or not.
1644 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1645static int
1646is_valid_fd(int fd)
1647{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001648#ifdef __APPLE__
1649 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1650 and the other side of the pipe is closed, dup(1) succeed, whereas
1651 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1652 such error. */
1653 struct stat st;
1654 return (fstat(fd, &st) == 0);
1655#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001656 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001657 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001658 return 0;
1659 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001660 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1661 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1662 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001663 fd2 = dup(fd);
1664 if (fd2 >= 0)
1665 close(fd2);
1666 _Py_END_SUPPRESS_IPH
1667 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001668#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001669}
1670
1671/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001672static PyObject*
1673create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001674 int fd, int write_mode, const char* name,
1675 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001676{
1677 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1678 const char* mode;
1679 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001680 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001681 int buffering, isatty;
1682 _Py_IDENTIFIER(open);
1683 _Py_IDENTIFIER(isatty);
1684 _Py_IDENTIFIER(TextIOWrapper);
1685 _Py_IDENTIFIER(mode);
1686
Victor Stinner874dbe82015-09-04 17:29:57 +02001687 if (!is_valid_fd(fd))
1688 Py_RETURN_NONE;
1689
Nick Coghland6009512014-11-20 21:39:37 +10001690 /* stdin is always opened in buffered mode, first because it shouldn't
1691 make a difference in common use cases, second because TextIOWrapper
1692 depends on the presence of a read1() method which only exists on
1693 buffered streams.
1694 */
1695 if (Py_UnbufferedStdioFlag && write_mode)
1696 buffering = 0;
1697 else
1698 buffering = -1;
1699 if (write_mode)
1700 mode = "wb";
1701 else
1702 mode = "rb";
1703 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1704 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001705 Py_None, Py_None, /* encoding, errors */
1706 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001707 if (buf == NULL)
1708 goto error;
1709
1710 if (buffering) {
1711 _Py_IDENTIFIER(raw);
1712 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1713 if (raw == NULL)
1714 goto error;
1715 }
1716 else {
1717 raw = buf;
1718 Py_INCREF(raw);
1719 }
1720
Steve Dower39294992016-08-30 21:22:36 -07001721#ifdef MS_WINDOWS
1722 /* Windows console IO is always UTF-8 encoded */
1723 if (PyWindowsConsoleIO_Check(raw))
1724 encoding = "utf-8";
1725#endif
1726
Nick Coghland6009512014-11-20 21:39:37 +10001727 text = PyUnicode_FromString(name);
1728 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1729 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001730 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001731 if (res == NULL)
1732 goto error;
1733 isatty = PyObject_IsTrue(res);
1734 Py_DECREF(res);
1735 if (isatty == -1)
1736 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001737 if (Py_UnbufferedStdioFlag)
1738 write_through = Py_True;
1739 else
1740 write_through = Py_False;
1741 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001742 line_buffering = Py_True;
1743 else
1744 line_buffering = Py_False;
1745
1746 Py_CLEAR(raw);
1747 Py_CLEAR(text);
1748
1749#ifdef MS_WINDOWS
1750 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1751 newlines to "\n".
1752 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1753 newline = NULL;
1754#else
1755 /* sys.stdin: split lines at "\n".
1756 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1757 newline = "\n";
1758#endif
1759
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001760 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001761 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001762 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001763 Py_CLEAR(buf);
1764 if (stream == NULL)
1765 goto error;
1766
1767 if (write_mode)
1768 mode = "w";
1769 else
1770 mode = "r";
1771 text = PyUnicode_FromString(mode);
1772 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1773 goto error;
1774 Py_CLEAR(text);
1775 return stream;
1776
1777error:
1778 Py_XDECREF(buf);
1779 Py_XDECREF(stream);
1780 Py_XDECREF(text);
1781 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001782
Victor Stinner874dbe82015-09-04 17:29:57 +02001783 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1784 /* Issue #24891: the file descriptor was closed after the first
1785 is_valid_fd() check was called. Ignore the OSError and set the
1786 stream to None. */
1787 PyErr_Clear();
1788 Py_RETURN_NONE;
1789 }
1790 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001791}
1792
1793/* Initialize sys.stdin, stdout, stderr and builtins.open */
Victor Stinnera7368ac2017-11-15 18:11:45 -08001794static _PyInitError
Victor Stinner91106cd2017-12-13 12:29:09 +01001795init_sys_streams(PyInterpreterState *interp)
Nick Coghland6009512014-11-20 21:39:37 +10001796{
1797 PyObject *iomod = NULL, *wrapper;
1798 PyObject *bimod = NULL;
1799 PyObject *m;
1800 PyObject *std = NULL;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001801 int fd;
Nick Coghland6009512014-11-20 21:39:37 +10001802 PyObject * encoding_attr;
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +02001803 char *pythonioencoding = NULL;
1804 const char *encoding, *errors;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001805 _PyInitError res = _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10001806
1807 /* Hack to avoid a nasty recursion issue when Python is invoked
1808 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1809 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1810 goto error;
1811 }
1812 Py_DECREF(m);
1813
1814 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1815 goto error;
1816 }
1817 Py_DECREF(m);
1818
1819 if (!(bimod = PyImport_ImportModule("builtins"))) {
1820 goto error;
1821 }
1822
1823 if (!(iomod = PyImport_ImportModule("io"))) {
1824 goto error;
1825 }
1826 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1827 goto error;
1828 }
1829
1830 /* Set builtins.open */
1831 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1832 Py_DECREF(wrapper);
1833 goto error;
1834 }
1835 Py_DECREF(wrapper);
1836
1837 encoding = _Py_StandardStreamEncoding;
1838 errors = _Py_StandardStreamErrors;
1839 if (!encoding || !errors) {
Victor Stinner91106cd2017-12-13 12:29:09 +01001840 char *opt = Py_GETENV("PYTHONIOENCODING");
1841 if (opt && opt[0] != '\0') {
Nick Coghland6009512014-11-20 21:39:37 +10001842 char *err;
Victor Stinner91106cd2017-12-13 12:29:09 +01001843 pythonioencoding = _PyMem_Strdup(opt);
Nick Coghland6009512014-11-20 21:39:37 +10001844 if (pythonioencoding == NULL) {
1845 PyErr_NoMemory();
1846 goto error;
1847 }
1848 err = strchr(pythonioencoding, ':');
1849 if (err) {
1850 *err = '\0';
1851 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001852 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001853 errors = err;
1854 }
1855 }
1856 if (*pythonioencoding && !encoding) {
1857 encoding = pythonioencoding;
1858 }
1859 }
Victor Stinner91106cd2017-12-13 12:29:09 +01001860 else if (interp->core_config.utf8_mode) {
1861 encoding = "utf-8";
1862 errors = "surrogateescape";
1863 }
1864
1865 if (!errors && !pythonioencoding) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001866 /* Choose the default error handler based on the current locale */
1867 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001868 }
Nick Coghland6009512014-11-20 21:39:37 +10001869 }
1870
1871 /* Set sys.stdin */
1872 fd = fileno(stdin);
1873 /* Under some conditions stdin, stdout and stderr may not be connected
1874 * and fileno() may point to an invalid file descriptor. For example
1875 * GUI apps don't have valid standard streams by default.
1876 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001877 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1878 if (std == NULL)
1879 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001880 PySys_SetObject("__stdin__", std);
1881 _PySys_SetObjectId(&PyId_stdin, std);
1882 Py_DECREF(std);
1883
1884 /* Set sys.stdout */
1885 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001886 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1887 if (std == NULL)
1888 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001889 PySys_SetObject("__stdout__", std);
1890 _PySys_SetObjectId(&PyId_stdout, std);
1891 Py_DECREF(std);
1892
1893#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1894 /* Set sys.stderr, replaces the preliminary stderr */
1895 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001896 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1897 if (std == NULL)
1898 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001899
1900 /* Same as hack above, pre-import stderr's codec to avoid recursion
1901 when import.c tries to write to stderr in verbose mode. */
1902 encoding_attr = PyObject_GetAttrString(std, "encoding");
1903 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001904 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001905 if (std_encoding != NULL) {
1906 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1907 Py_XDECREF(codec_info);
1908 }
1909 Py_DECREF(encoding_attr);
1910 }
1911 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1912
1913 if (PySys_SetObject("__stderr__", std) < 0) {
1914 Py_DECREF(std);
1915 goto error;
1916 }
1917 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1918 Py_DECREF(std);
1919 goto error;
1920 }
1921 Py_DECREF(std);
1922#endif
1923
Victor Stinnera7368ac2017-11-15 18:11:45 -08001924 goto done;
Nick Coghland6009512014-11-20 21:39:37 +10001925
Victor Stinnera7368ac2017-11-15 18:11:45 -08001926error:
1927 res = _Py_INIT_ERR("can't initialize sys standard streams");
1928
Victor Stinner31e99082017-12-20 23:41:38 +01001929 /* Use the same allocator than Py_SetStandardStreamEncoding() */
1930 PyMemAllocatorEx old_alloc;
Victor Stinnera7368ac2017-11-15 18:11:45 -08001931done:
Victor Stinner31e99082017-12-20 23:41:38 +01001932 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1933
Nick Coghland6009512014-11-20 21:39:37 +10001934 /* We won't need them anymore. */
1935 if (_Py_StandardStreamEncoding) {
1936 PyMem_RawFree(_Py_StandardStreamEncoding);
1937 _Py_StandardStreamEncoding = NULL;
1938 }
1939 if (_Py_StandardStreamErrors) {
1940 PyMem_RawFree(_Py_StandardStreamErrors);
1941 _Py_StandardStreamErrors = NULL;
1942 }
Victor Stinner31e99082017-12-20 23:41:38 +01001943
1944 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1945
Nick Coghland6009512014-11-20 21:39:37 +10001946 PyMem_Free(pythonioencoding);
1947 Py_XDECREF(bimod);
1948 Py_XDECREF(iomod);
Victor Stinnera7368ac2017-11-15 18:11:45 -08001949 return res;
Nick Coghland6009512014-11-20 21:39:37 +10001950}
1951
1952
Victor Stinner10dc4842015-03-24 12:01:30 +01001953static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001954_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001955{
Victor Stinner10dc4842015-03-24 12:01:30 +01001956 fputc('\n', stderr);
1957 fflush(stderr);
1958
1959 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001960 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001961}
Victor Stinner791da1c2016-03-14 16:53:12 +01001962
1963/* Print the current exception (if an exception is set) with its traceback,
1964 or display the current Python stack.
1965
1966 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1967 called on catastrophic cases.
1968
1969 Return 1 if the traceback was displayed, 0 otherwise. */
1970
1971static int
1972_Py_FatalError_PrintExc(int fd)
1973{
1974 PyObject *ferr, *res;
1975 PyObject *exception, *v, *tb;
1976 int has_tb;
1977
1978 if (PyThreadState_GET() == NULL) {
1979 /* The GIL is released: trying to acquire it is likely to deadlock,
1980 just give up. */
1981 return 0;
1982 }
1983
1984 PyErr_Fetch(&exception, &v, &tb);
1985 if (exception == NULL) {
1986 /* No current exception */
1987 return 0;
1988 }
1989
1990 ferr = _PySys_GetObjectId(&PyId_stderr);
1991 if (ferr == NULL || ferr == Py_None) {
1992 /* sys.stderr is not set yet or set to None,
1993 no need to try to display the exception */
1994 return 0;
1995 }
1996
1997 PyErr_NormalizeException(&exception, &v, &tb);
1998 if (tb == NULL) {
1999 tb = Py_None;
2000 Py_INCREF(tb);
2001 }
2002 PyException_SetTraceback(v, tb);
2003 if (exception == NULL) {
2004 /* PyErr_NormalizeException() failed */
2005 return 0;
2006 }
2007
2008 has_tb = (tb != Py_None);
2009 PyErr_Display(exception, v, tb);
2010 Py_XDECREF(exception);
2011 Py_XDECREF(v);
2012 Py_XDECREF(tb);
2013
2014 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07002015 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01002016 if (res == NULL)
2017 PyErr_Clear();
2018 else
2019 Py_DECREF(res);
2020
2021 return has_tb;
2022}
2023
Nick Coghland6009512014-11-20 21:39:37 +10002024/* Print fatal error message and abort */
2025
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002026#ifdef MS_WINDOWS
2027static void
2028fatal_output_debug(const char *msg)
2029{
2030 /* buffer of 256 bytes allocated on the stack */
2031 WCHAR buffer[256 / sizeof(WCHAR)];
2032 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2033 size_t msglen;
2034
2035 OutputDebugStringW(L"Fatal Python error: ");
2036
2037 msglen = strlen(msg);
2038 while (msglen) {
2039 size_t i;
2040
2041 if (buflen > msglen) {
2042 buflen = msglen;
2043 }
2044
2045 /* Convert the message to wchar_t. This uses a simple one-to-one
2046 conversion, assuming that the this error message actually uses
2047 ASCII only. If this ceases to be true, we will have to convert. */
2048 for (i=0; i < buflen; ++i) {
2049 buffer[i] = msg[i];
2050 }
2051 buffer[i] = L'\0';
2052 OutputDebugStringW(buffer);
2053
2054 msg += buflen;
2055 msglen -= buflen;
2056 }
2057 OutputDebugStringW(L"\n");
2058}
2059#endif
2060
Benjamin Petersoncef88b92017-11-25 13:02:55 -08002061static void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002062fatal_error(const char *prefix, const char *msg, int status)
Nick Coghland6009512014-11-20 21:39:37 +10002063{
2064 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01002065 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01002066
2067 if (reentrant) {
2068 /* Py_FatalError() caused a second fatal error.
2069 Example: flush_std_files() raises a recursion error. */
2070 goto exit;
2071 }
2072 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10002073
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002074 fprintf(stderr, "Fatal Python error: ");
2075 if (prefix) {
2076 fputs(prefix, stderr);
2077 fputs(": ", stderr);
2078 }
2079 if (msg) {
2080 fputs(msg, stderr);
2081 }
2082 else {
2083 fprintf(stderr, "<message not set>");
2084 }
2085 fputs("\n", stderr);
Nick Coghland6009512014-11-20 21:39:37 +10002086 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01002087
Victor Stinnere0deff32015-03-24 13:46:18 +01002088 /* Print the exception (if an exception is set) with its traceback,
2089 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002090 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01002091 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002092 }
Victor Stinner10dc4842015-03-24 12:01:30 +01002093
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002094 /* The main purpose of faulthandler is to display the traceback.
2095 This function already did its best to display a traceback.
2096 Disable faulthandler to prevent writing a second traceback
2097 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01002098 _PyFaulthandler_Fini();
2099
Victor Stinner791da1c2016-03-14 16:53:12 +01002100 /* Check if the current Python thread hold the GIL */
2101 if (PyThreadState_GET() != NULL) {
2102 /* Flush sys.stdout and sys.stderr */
2103 flush_std_files();
2104 }
Victor Stinnere0deff32015-03-24 13:46:18 +01002105
Nick Coghland6009512014-11-20 21:39:37 +10002106#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07002107 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01002108#endif /* MS_WINDOWS */
2109
2110exit:
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002111 if (status < 0) {
Victor Stinner53345a42015-03-25 01:55:14 +01002112#if defined(MS_WINDOWS) && defined(_DEBUG)
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002113 DebugBreak();
Nick Coghland6009512014-11-20 21:39:37 +10002114#endif
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002115 abort();
2116 }
2117 else {
2118 exit(status);
2119 }
2120}
2121
Victor Stinner19760862017-12-20 01:41:59 +01002122void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002123Py_FatalError(const char *msg)
2124{
2125 fatal_error(NULL, msg, -1);
2126}
2127
Victor Stinner19760862017-12-20 01:41:59 +01002128void _Py_NO_RETURN
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002129_Py_FatalInitError(_PyInitError err)
2130{
2131 /* On "user" error: exit with status 1.
2132 For all other errors, call abort(). */
2133 int status = err.user_err ? 1 : -1;
2134 fatal_error(err.prefix, err.msg, status);
Nick Coghland6009512014-11-20 21:39:37 +10002135}
2136
2137/* Clean up and exit */
2138
Victor Stinnerd7292b52016-06-17 12:29:00 +02002139# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10002140
Nick Coghland6009512014-11-20 21:39:37 +10002141/* For the atexit module. */
Marcel Plch776407f2017-12-20 11:17:58 +01002142void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
Nick Coghland6009512014-11-20 21:39:37 +10002143{
Marcel Plch776407f2017-12-20 11:17:58 +01002144 PyThreadState *ts;
2145 PyInterpreterState *is;
Victor Stinnerca719ac2017-12-20 18:00:19 +01002146
Marcel Plch776407f2017-12-20 11:17:58 +01002147 ts = PyThreadState_GET();
2148 is = ts->interp;
2149
Antoine Pitroufc5db952017-12-13 02:29:07 +01002150 /* Guard against API misuse (see bpo-17852) */
Marcel Plch776407f2017-12-20 11:17:58 +01002151 assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2152
2153 is->pyexitfunc = func;
2154 is->pyexitmodule = module;
Nick Coghland6009512014-11-20 21:39:37 +10002155}
2156
2157static void
Marcel Plch776407f2017-12-20 11:17:58 +01002158call_py_exitfuncs(PyInterpreterState *istate)
Nick Coghland6009512014-11-20 21:39:37 +10002159{
Marcel Plch776407f2017-12-20 11:17:58 +01002160 if (istate->pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10002161 return;
2162
Marcel Plch776407f2017-12-20 11:17:58 +01002163 (*istate->pyexitfunc)(istate->pyexitmodule);
Nick Coghland6009512014-11-20 21:39:37 +10002164 PyErr_Clear();
2165}
2166
2167/* Wait until threading._shutdown completes, provided
2168 the threading module was imported in the first place.
2169 The shutdown routine will wait until all non-daemon
2170 "threading" threads have completed. */
2171static void
2172wait_for_thread_shutdown(void)
2173{
Nick Coghland6009512014-11-20 21:39:37 +10002174 _Py_IDENTIFIER(_shutdown);
2175 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06002176 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10002177 if (threading == NULL) {
2178 /* threading not imported */
2179 PyErr_Clear();
2180 return;
2181 }
Victor Stinner3466bde2016-09-05 18:16:01 -07002182 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10002183 if (result == NULL) {
2184 PyErr_WriteUnraisable(threading);
2185 }
2186 else {
2187 Py_DECREF(result);
2188 }
2189 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10002190}
2191
2192#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10002193int Py_AtExit(void (*func)(void))
2194{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002195 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10002196 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002197 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10002198 return 0;
2199}
2200
2201static void
2202call_ll_exitfuncs(void)
2203{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002204 while (_PyRuntime.nexitfuncs > 0)
2205 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10002206
2207 fflush(stdout);
2208 fflush(stderr);
2209}
2210
2211void
2212Py_Exit(int sts)
2213{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00002214 if (Py_FinalizeEx() < 0) {
2215 sts = 120;
2216 }
Nick Coghland6009512014-11-20 21:39:37 +10002217
2218 exit(sts);
2219}
2220
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002221static _PyInitError
Nick Coghland6009512014-11-20 21:39:37 +10002222initsigs(void)
2223{
2224#ifdef SIGPIPE
2225 PyOS_setsig(SIGPIPE, SIG_IGN);
2226#endif
2227#ifdef SIGXFZ
2228 PyOS_setsig(SIGXFZ, SIG_IGN);
2229#endif
2230#ifdef SIGXFSZ
2231 PyOS_setsig(SIGXFSZ, SIG_IGN);
2232#endif
2233 PyOS_InitInterrupts(); /* May imply initsignal() */
2234 if (PyErr_Occurred()) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002235 return _Py_INIT_ERR("can't import signal");
Nick Coghland6009512014-11-20 21:39:37 +10002236 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002237 return _Py_INIT_OK();
Nick Coghland6009512014-11-20 21:39:37 +10002238}
2239
2240
2241/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2242 *
2243 * All of the code in this function must only use async-signal-safe functions,
2244 * listed at `man 7 signal` or
2245 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2246 */
2247void
2248_Py_RestoreSignals(void)
2249{
2250#ifdef SIGPIPE
2251 PyOS_setsig(SIGPIPE, SIG_DFL);
2252#endif
2253#ifdef SIGXFZ
2254 PyOS_setsig(SIGXFZ, SIG_DFL);
2255#endif
2256#ifdef SIGXFSZ
2257 PyOS_setsig(SIGXFSZ, SIG_DFL);
2258#endif
2259}
2260
2261
2262/*
2263 * The file descriptor fd is considered ``interactive'' if either
2264 * a) isatty(fd) is TRUE, or
2265 * b) the -i flag was given, and the filename associated with
2266 * the descriptor is NULL or "<stdin>" or "???".
2267 */
2268int
2269Py_FdIsInteractive(FILE *fp, const char *filename)
2270{
2271 if (isatty((int)fileno(fp)))
2272 return 1;
2273 if (!Py_InteractiveFlag)
2274 return 0;
2275 return (filename == NULL) ||
2276 (strcmp(filename, "<stdin>") == 0) ||
2277 (strcmp(filename, "???") == 0);
2278}
2279
2280
Nick Coghland6009512014-11-20 21:39:37 +10002281/* Wrappers around sigaction() or signal(). */
2282
2283PyOS_sighandler_t
2284PyOS_getsig(int sig)
2285{
2286#ifdef HAVE_SIGACTION
2287 struct sigaction context;
2288 if (sigaction(sig, NULL, &context) == -1)
2289 return SIG_ERR;
2290 return context.sa_handler;
2291#else
2292 PyOS_sighandler_t handler;
2293/* Special signal handling for the secure CRT in Visual Studio 2005 */
2294#if defined(_MSC_VER) && _MSC_VER >= 1400
2295 switch (sig) {
2296 /* Only these signals are valid */
2297 case SIGINT:
2298 case SIGILL:
2299 case SIGFPE:
2300 case SIGSEGV:
2301 case SIGTERM:
2302 case SIGBREAK:
2303 case SIGABRT:
2304 break;
2305 /* Don't call signal() with other values or it will assert */
2306 default:
2307 return SIG_ERR;
2308 }
2309#endif /* _MSC_VER && _MSC_VER >= 1400 */
2310 handler = signal(sig, SIG_IGN);
2311 if (handler != SIG_ERR)
2312 signal(sig, handler);
2313 return handler;
2314#endif
2315}
2316
2317/*
2318 * All of the code in this function must only use async-signal-safe functions,
2319 * listed at `man 7 signal` or
2320 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2321 */
2322PyOS_sighandler_t
2323PyOS_setsig(int sig, PyOS_sighandler_t handler)
2324{
2325#ifdef HAVE_SIGACTION
2326 /* Some code in Modules/signalmodule.c depends on sigaction() being
2327 * used here if HAVE_SIGACTION is defined. Fix that if this code
2328 * changes to invalidate that assumption.
2329 */
2330 struct sigaction context, ocontext;
2331 context.sa_handler = handler;
2332 sigemptyset(&context.sa_mask);
2333 context.sa_flags = 0;
2334 if (sigaction(sig, &context, &ocontext) == -1)
2335 return SIG_ERR;
2336 return ocontext.sa_handler;
2337#else
2338 PyOS_sighandler_t oldhandler;
2339 oldhandler = signal(sig, handler);
2340#ifdef HAVE_SIGINTERRUPT
2341 siginterrupt(sig, 1);
2342#endif
2343 return oldhandler;
2344#endif
2345}
2346
2347#ifdef __cplusplus
2348}
2349#endif