blob: 4e8bbb662e971e39c2015e340d9501617acb2ba9 [file] [log] [blame]
Nick Coghland6009512014-11-20 21:39:37 +10001/* Python interpreter top-level routines, including init/exit */
2
3#include "Python.h"
4
5#include "Python-ast.h"
6#undef Yield /* undefine macro conflicting with winbase.h */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06007#include "internal/pystate.h"
Nick Coghland6009512014-11-20 21:39:37 +10008#include "grammar.h"
9#include "node.h"
10#include "token.h"
11#include "parsetok.h"
12#include "errcode.h"
13#include "code.h"
14#include "symtable.h"
15#include "ast.h"
16#include "marshal.h"
17#include "osdefs.h"
18#include <locale.h>
19
20#ifdef HAVE_SIGNAL_H
21#include <signal.h>
22#endif
23
24#ifdef MS_WINDOWS
25#include "malloc.h" /* for alloca */
26#endif
27
28#ifdef HAVE_LANGINFO_H
29#include <langinfo.h>
30#endif
31
32#ifdef MS_WINDOWS
33#undef BYTE
34#include "windows.h"
Steve Dower39294992016-08-30 21:22:36 -070035
36extern PyTypeObject PyWindowsConsoleIO_Type;
37#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
Nick Coghland6009512014-11-20 21:39:37 +100038#endif
39
40_Py_IDENTIFIER(flush);
41_Py_IDENTIFIER(name);
42_Py_IDENTIFIER(stdin);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
Eric Snow3f9eee62017-09-15 16:35:20 -060045_Py_IDENTIFIER(threading);
Nick Coghland6009512014-11-20 21:39:37 +100046
47#ifdef __cplusplus
48extern "C" {
49#endif
50
51extern wchar_t *Py_GetPath(void);
52
53extern grammar _PyParser_Grammar; /* From graminit.c */
54
55/* Forward */
56static void initmain(PyInterpreterState *interp);
57static int initfsencoding(PyInterpreterState *interp);
58static void initsite(void);
59static int initstdio(void);
60static void initsigs(void);
61static void call_py_exitfuncs(void);
62static 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);
69extern int _PyFaulthandler_Init(void);
70extern void _PyFaulthandler_Fini(void);
71extern void _PyHash_Fini(void);
72extern int _PyTraceMalloc_Init(void);
73extern 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
Eric Snow2ebc5ce2017-09-07 23:51:28 -060079_PyRuntimeState _PyRuntime = {0, 0};
80
81void
82_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;
91 if (initialized)
92 return;
93 initialized = 1;
94 _PyRuntimeState_Init(&_PyRuntime);
95}
96
97void
98_PyRuntime_Finalize(void)
99{
100 _PyRuntimeState_Fini(&_PyRuntime);
101}
102
103int
104_Py_IsFinalizing(void)
105{
106 return _PyRuntime.finalizing != NULL;
107}
108
Nick Coghland6009512014-11-20 21:39:37 +1000109/* Global configuration variable declarations are in pydebug.h */
110/* XXX (ncoghlan): move those declarations to pylifecycle.h? */
111int Py_DebugFlag; /* Needed by parser.c */
112int Py_VerboseFlag; /* Needed by import.c */
113int Py_QuietFlag; /* Needed by sysmodule.c */
114int Py_InteractiveFlag; /* Needed by Py_FdIsInteractive() below */
115int Py_InspectFlag; /* Needed to determine whether to exit at SystemExit */
116int Py_OptimizeFlag = 0; /* Needed by compile.c */
117int Py_NoSiteFlag; /* Suppress 'import site' */
118int Py_BytesWarningFlag; /* Warn on str(bytes) and str(buffer) */
119int Py_UseClassExceptionsFlag = 1; /* Needed by bltinmodule.c: deprecated */
120int Py_FrozenFlag; /* Needed by getpath.c */
121int Py_IgnoreEnvironmentFlag; /* e.g. PYTHONPATH, PYTHONHOME */
Xiang Zhang0710d752017-03-11 13:02:52 +0800122int Py_DontWriteBytecodeFlag; /* Suppress writing bytecode files (*.pyc) */
Nick Coghland6009512014-11-20 21:39:37 +1000123int Py_NoUserSiteDirectory = 0; /* for -s and site.py */
124int Py_UnbufferedStdioFlag = 0; /* Unbuffered binary std{in,out,err} */
125int Py_HashRandomizationFlag = 0; /* for -R and PYTHONHASHSEED */
126int Py_IsolatedFlag = 0; /* for -I, isolate from user's env */
Steve Dowercc16be82016-09-08 10:35:16 -0700127#ifdef MS_WINDOWS
128int Py_LegacyWindowsFSEncodingFlag = 0; /* Uses mbcs instead of utf-8 */
Steve Dower39294992016-08-30 21:22:36 -0700129int Py_LegacyWindowsStdioFlag = 0; /* Uses FileIO instead of WindowsConsoleIO */
Steve Dowercc16be82016-09-08 10:35:16 -0700130#endif
Nick Coghland6009512014-11-20 21:39:37 +1000131
Nick Coghland6009512014-11-20 21:39:37 +1000132/* Hack to force loading of object files */
133int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
134 PyOS_mystrnicmp; /* Python/pystrcmp.o */
135
136/* PyModule_GetWarningsModule is no longer necessary as of 2.6
137since _warnings is builtin. This API should not be used. */
138PyObject *
139PyModule_GetWarningsModule(void)
140{
141 return PyImport_ImportModule("warnings");
142}
143
Eric Snowc7ec9982017-05-23 23:00:52 -0700144
Eric Snow1abcf672017-05-23 21:46:51 -0700145/* APIs to access the initialization flags
146 *
147 * Can be called prior to Py_Initialize.
148 */
Nick Coghland6009512014-11-20 21:39:37 +1000149
Eric Snow1abcf672017-05-23 21:46:51 -0700150int
151_Py_IsCoreInitialized(void)
152{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600153 return _PyRuntime.core_initialized;
Eric Snow1abcf672017-05-23 21:46:51 -0700154}
Nick Coghland6009512014-11-20 21:39:37 +1000155
156int
157Py_IsInitialized(void)
158{
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600159 return _PyRuntime.initialized;
Nick Coghland6009512014-11-20 21:39:37 +1000160}
161
162/* Helper to allow an embedding application to override the normal
163 * mechanism that attempts to figure out an appropriate IO encoding
164 */
165
166static char *_Py_StandardStreamEncoding = NULL;
167static char *_Py_StandardStreamErrors = NULL;
168
169int
170Py_SetStandardStreamEncoding(const char *encoding, const char *errors)
171{
172 if (Py_IsInitialized()) {
173 /* This is too late to have any effect */
174 return -1;
175 }
176 /* Can't call PyErr_NoMemory() on errors, as Python hasn't been
177 * initialised yet.
178 *
179 * However, the raw memory allocators are initialised appropriately
180 * as C static variables, so _PyMem_RawStrdup is OK even though
181 * Py_Initialize hasn't been called yet.
182 */
183 if (encoding) {
184 _Py_StandardStreamEncoding = _PyMem_RawStrdup(encoding);
185 if (!_Py_StandardStreamEncoding) {
186 return -2;
187 }
188 }
189 if (errors) {
190 _Py_StandardStreamErrors = _PyMem_RawStrdup(errors);
191 if (!_Py_StandardStreamErrors) {
192 if (_Py_StandardStreamEncoding) {
193 PyMem_RawFree(_Py_StandardStreamEncoding);
194 }
195 return -3;
196 }
197 }
Steve Dower39294992016-08-30 21:22:36 -0700198#ifdef MS_WINDOWS
199 if (_Py_StandardStreamEncoding) {
200 /* Overriding the stream encoding implies legacy streams */
201 Py_LegacyWindowsStdioFlag = 1;
202 }
203#endif
Nick Coghland6009512014-11-20 21:39:37 +1000204 return 0;
205}
206
Nick Coghlan6ea41862017-06-11 13:16:15 +1000207
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000208/* Global initializations. Can be undone by Py_FinalizeEx(). Don't
209 call this twice without an intervening Py_FinalizeEx() call. When
Nick Coghland6009512014-11-20 21:39:37 +1000210 initializations fail, a fatal error is issued and the function does
211 not return. On return, the first thread and interpreter state have
212 been created.
213
214 Locking: you must hold the interpreter lock while calling this.
215 (If the lock has not yet been initialized, that's equivalent to
216 having the lock, but you cannot use multiple threads.)
217
218*/
219
Nick Coghland7ac0612017-10-25 12:11:26 +1000220static void
221set_flag(int *flag, const char *envs)
Nick Coghland6009512014-11-20 21:39:37 +1000222{
Nick Coghland7ac0612017-10-25 12:11:26 +1000223 /* Helper to set flag variables from environment variables:
224 * - uses the higher of the two values if they're both set
225 * - otherwise sets the flag to 1
226 */
Nick Coghland6009512014-11-20 21:39:37 +1000227 int env = atoi(envs);
Nick Coghland7ac0612017-10-25 12:11:26 +1000228 if (*flag < env)
229 *flag = env;
230 if (*flag < 1)
231 *flag = 1;
Nick Coghland6009512014-11-20 21:39:37 +1000232}
233
234static char*
235get_codec_name(const char *encoding)
236{
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200237 const char *name_utf8;
238 char *name_str;
Nick Coghland6009512014-11-20 21:39:37 +1000239 PyObject *codec, *name = NULL;
240
241 codec = _PyCodec_Lookup(encoding);
242 if (!codec)
243 goto error;
244
245 name = _PyObject_GetAttrId(codec, &PyId_name);
246 Py_CLEAR(codec);
247 if (!name)
248 goto error;
249
Serhiy Storchaka06515832016-11-20 09:13:07 +0200250 name_utf8 = PyUnicode_AsUTF8(name);
Nick Coghland6009512014-11-20 21:39:37 +1000251 if (name_utf8 == NULL)
252 goto error;
253 name_str = _PyMem_RawStrdup(name_utf8);
254 Py_DECREF(name);
255 if (name_str == NULL) {
256 PyErr_NoMemory();
257 return NULL;
258 }
259 return name_str;
260
261error:
262 Py_XDECREF(codec);
263 Py_XDECREF(name);
264 return NULL;
265}
266
267static char*
268get_locale_encoding(void)
269{
Benjamin Petersondb610e92017-09-08 14:30:07 -0700270#if defined(HAVE_LANGINFO_H) && defined(CODESET)
Nick Coghland6009512014-11-20 21:39:37 +1000271 char* codeset = nl_langinfo(CODESET);
272 if (!codeset || codeset[0] == '\0') {
273 PyErr_SetString(PyExc_ValueError, "CODESET is not set or empty");
274 return NULL;
275 }
276 return get_codec_name(codeset);
Stefan Krah144da4e2016-04-26 01:56:50 +0200277#elif defined(__ANDROID__)
278 return get_codec_name("UTF-8");
Nick Coghland6009512014-11-20 21:39:37 +1000279#else
280 PyErr_SetNone(PyExc_NotImplementedError);
281 return NULL;
282#endif
283}
284
285static void
Eric Snow1abcf672017-05-23 21:46:51 -0700286initimport(PyInterpreterState *interp, PyObject *sysmod)
Nick Coghland6009512014-11-20 21:39:37 +1000287{
288 PyObject *importlib;
289 PyObject *impmod;
Nick Coghland6009512014-11-20 21:39:37 +1000290 PyObject *value;
291
292 /* Import _importlib through its frozen version, _frozen_importlib. */
293 if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
294 Py_FatalError("Py_Initialize: can't import _frozen_importlib");
295 }
296 else if (Py_VerboseFlag) {
297 PySys_FormatStderr("import _frozen_importlib # frozen\n");
298 }
299 importlib = PyImport_AddModule("_frozen_importlib");
300 if (importlib == NULL) {
301 Py_FatalError("Py_Initialize: couldn't get _frozen_importlib from "
302 "sys.modules");
303 }
304 interp->importlib = importlib;
305 Py_INCREF(interp->importlib);
306
Serhiy Storchaka133138a2016-08-02 22:51:21 +0300307 interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
308 if (interp->import_func == NULL)
309 Py_FatalError("Py_Initialize: __import__ not found");
310 Py_INCREF(interp->import_func);
311
Victor Stinnercd6e6942015-09-18 09:11:57 +0200312 /* Import the _imp module */
Nick Coghland6009512014-11-20 21:39:37 +1000313 impmod = PyInit_imp();
314 if (impmod == NULL) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200315 Py_FatalError("Py_Initialize: can't import _imp");
Nick Coghland6009512014-11-20 21:39:37 +1000316 }
317 else if (Py_VerboseFlag) {
Victor Stinnercd6e6942015-09-18 09:11:57 +0200318 PySys_FormatStderr("import _imp # builtin\n");
Nick Coghland6009512014-11-20 21:39:37 +1000319 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600320 if (_PyImport_SetModuleString("_imp", impmod) < 0) {
Nick Coghland6009512014-11-20 21:39:37 +1000321 Py_FatalError("Py_Initialize: can't save _imp to sys.modules");
322 }
323
Victor Stinnercd6e6942015-09-18 09:11:57 +0200324 /* Install importlib as the implementation of import */
Nick Coghland6009512014-11-20 21:39:37 +1000325 value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200326 if (value != NULL) {
327 Py_DECREF(value);
Eric Snow6b4be192017-05-22 21:36:03 -0700328 value = PyObject_CallMethod(importlib,
329 "_install_external_importers", "");
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200330 }
Nick Coghland6009512014-11-20 21:39:37 +1000331 if (value == NULL) {
332 PyErr_Print();
333 Py_FatalError("Py_Initialize: importlib install failed");
334 }
335 Py_DECREF(value);
336 Py_DECREF(impmod);
337
338 _PyImportZip_Init();
339}
340
Eric Snow1abcf672017-05-23 21:46:51 -0700341static void
342initexternalimport(PyInterpreterState *interp)
343{
344 PyObject *value;
345 value = PyObject_CallMethod(interp->importlib,
346 "_install_external_importers", "");
347 if (value == NULL) {
348 PyErr_Print();
349 Py_FatalError("Py_EndInitialization: external importer setup failed");
350 }
Stéphane Wirtelab1cb802017-06-08 13:13:20 +0200351 Py_DECREF(value);
Eric Snow1abcf672017-05-23 21:46:51 -0700352}
Nick Coghland6009512014-11-20 21:39:37 +1000353
Nick Coghlan6ea41862017-06-11 13:16:15 +1000354/* Helper functions to better handle the legacy C locale
355 *
356 * The legacy C locale assumes ASCII as the default text encoding, which
357 * causes problems not only for the CPython runtime, but also other
358 * components like GNU readline.
359 *
360 * Accordingly, when the CLI detects it, it attempts to coerce it to a
361 * more capable UTF-8 based alternative as follows:
362 *
363 * if (_Py_LegacyLocaleDetected()) {
364 * _Py_CoerceLegacyLocale();
365 * }
366 *
367 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
368 *
369 * Locale coercion also impacts the default error handler for the standard
370 * streams: while the usual default is "strict", the default for the legacy
371 * C locale and for any of the coercion target locales is "surrogateescape".
372 */
373
374int
375_Py_LegacyLocaleDetected(void)
376{
377#ifndef MS_WINDOWS
378 /* On non-Windows systems, the C locale is considered a legacy locale */
Nick Coghlaneb817952017-06-18 12:29:42 +1000379 /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
380 * the POSIX locale as a simple alias for the C locale, so
381 * we may also want to check for that explicitly.
382 */
Nick Coghlan6ea41862017-06-11 13:16:15 +1000383 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
384 return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
385#else
386 /* Windows uses code pages instead of locales, so no locale is legacy */
387 return 0;
388#endif
389}
390
Nick Coghlaneb817952017-06-18 12:29:42 +1000391static const char *_C_LOCALE_WARNING =
392 "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
393 "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
394 "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
395 "locales is recommended.\n";
396
397static int
398_legacy_locale_warnings_enabled(void)
399{
400 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
401 return (coerce_c_locale != NULL &&
402 strncmp(coerce_c_locale, "warn", 5) == 0);
403}
404
405static void
406_emit_stderr_warning_for_legacy_locale(void)
407{
408 if (_legacy_locale_warnings_enabled()) {
409 if (_Py_LegacyLocaleDetected()) {
410 fprintf(stderr, "%s", _C_LOCALE_WARNING);
411 }
412 }
413}
414
Nick Coghlan6ea41862017-06-11 13:16:15 +1000415typedef struct _CandidateLocale {
416 const char *locale_name; /* The locale to try as a coercion target */
417} _LocaleCoercionTarget;
418
419static _LocaleCoercionTarget _TARGET_LOCALES[] = {
420 {"C.UTF-8"},
421 {"C.utf8"},
Nick Coghlan18974c32017-06-30 00:48:14 +1000422 {"UTF-8"},
Nick Coghlan6ea41862017-06-11 13:16:15 +1000423 {NULL}
424};
425
426static char *
427get_default_standard_stream_error_handler(void)
428{
429 const char *ctype_loc = setlocale(LC_CTYPE, NULL);
430 if (ctype_loc != NULL) {
431 /* "surrogateescape" is the default in the legacy C locale */
432 if (strcmp(ctype_loc, "C") == 0) {
433 return "surrogateescape";
434 }
435
436#ifdef PY_COERCE_C_LOCALE
437 /* "surrogateescape" is the default in locale coercion target locales */
438 const _LocaleCoercionTarget *target = NULL;
439 for (target = _TARGET_LOCALES; target->locale_name; target++) {
440 if (strcmp(ctype_loc, target->locale_name) == 0) {
441 return "surrogateescape";
442 }
443 }
444#endif
445 }
446
447 /* Otherwise return NULL to request the typical default error handler */
448 return NULL;
449}
450
451#ifdef PY_COERCE_C_LOCALE
452static const char *_C_LOCALE_COERCION_WARNING =
453 "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
454 "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
455
456static void
457_coerce_default_locale_settings(const _LocaleCoercionTarget *target)
458{
459 const char *newloc = target->locale_name;
460
461 /* Reset locale back to currently configured defaults */
462 setlocale(LC_ALL, "");
463
464 /* Set the relevant locale environment variable */
465 if (setenv("LC_CTYPE", newloc, 1)) {
466 fprintf(stderr,
467 "Error setting LC_CTYPE, skipping C locale coercion\n");
468 return;
469 }
Nick Coghlaneb817952017-06-18 12:29:42 +1000470 if (_legacy_locale_warnings_enabled()) {
471 fprintf(stderr, _C_LOCALE_COERCION_WARNING, newloc);
472 }
Nick Coghlan6ea41862017-06-11 13:16:15 +1000473
474 /* Reconfigure with the overridden environment variables */
475 setlocale(LC_ALL, "");
476}
477#endif
478
479void
480_Py_CoerceLegacyLocale(void)
481{
482#ifdef PY_COERCE_C_LOCALE
483 /* We ignore the Python -E and -I flags here, as the CLI needs to sort out
484 * the locale settings *before* we try to do anything with the command
485 * line arguments. For cross-platform debugging purposes, we also need
486 * to give end users a way to force even scripts that are otherwise
487 * isolated from their environment to use the legacy ASCII-centric C
488 * locale.
489 *
490 * Ignoring -E and -I is safe from a security perspective, as we only use
491 * the setting to turn *off* the implicit locale coercion, and anyone with
492 * access to the process environment already has the ability to set
493 * `LC_ALL=C` to override the C level locale settings anyway.
494 */
495 const char *coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
496 if (coerce_c_locale == NULL || strncmp(coerce_c_locale, "0", 2) != 0) {
497 /* PYTHONCOERCECLOCALE is not set, or is set to something other than "0" */
498 const char *locale_override = getenv("LC_ALL");
499 if (locale_override == NULL || *locale_override == '\0') {
500 /* LC_ALL is also not set (or is set to an empty string) */
501 const _LocaleCoercionTarget *target = NULL;
502 for (target = _TARGET_LOCALES; target->locale_name; target++) {
503 const char *new_locale = setlocale(LC_CTYPE,
504 target->locale_name);
505 if (new_locale != NULL) {
Nick Coghlan18974c32017-06-30 00:48:14 +1000506#if !defined(__APPLE__) && defined(HAVE_LANGINFO_H) && defined(CODESET)
507 /* Also ensure that nl_langinfo works in this locale */
508 char *codeset = nl_langinfo(CODESET);
509 if (!codeset || *codeset == '\0') {
510 /* CODESET is not set or empty, so skip coercion */
511 new_locale = NULL;
512 setlocale(LC_CTYPE, "");
513 continue;
514 }
515#endif
Nick Coghlan6ea41862017-06-11 13:16:15 +1000516 /* Successfully configured locale, so make it the default */
517 _coerce_default_locale_settings(target);
518 return;
519 }
520 }
521 }
522 }
523 /* No C locale warning here, as Py_Initialize will emit one later */
524#endif
525}
526
527
Eric Snow1abcf672017-05-23 21:46:51 -0700528/* Global initializations. Can be undone by Py_Finalize(). Don't
529 call this twice without an intervening Py_Finalize() call.
530
531 Every call to Py_InitializeCore, Py_Initialize or Py_InitializeEx
532 must have a corresponding call to Py_Finalize.
533
534 Locking: you must hold the interpreter lock while calling these APIs.
535 (If the lock has not yet been initialized, that's equivalent to
536 having the lock, but you cannot use multiple threads.)
537
538*/
539
540/* Begin interpreter initialization
541 *
542 * On return, the first thread and interpreter state have been created,
543 * but the compiler, signal handling, multithreading and
544 * multiple interpreter support, and codec infrastructure are not yet
545 * available.
546 *
547 * The import system will support builtin and frozen modules only.
548 * The only supported io is writing to sys.stderr
549 *
550 * If any operation invoked by this function fails, a fatal error is
551 * issued and the function does not return.
552 *
553 * Any code invoked from this function should *not* assume it has access
554 * to the Python C API (unless the API is explicitly listed as being
555 * safe to call without calling Py_Initialize first)
556 */
557
Stéphane Wirtelccfdb602017-07-25 14:32:08 +0200558/* TODO: Progressively move functionality from Py_BeginInitialization to
Eric Snow1abcf672017-05-23 21:46:51 -0700559 * Py_ReadConfig and Py_EndInitialization
560 */
561
562void _Py_InitializeCore(const _PyCoreConfig *config)
Nick Coghland6009512014-11-20 21:39:37 +1000563{
564 PyInterpreterState *interp;
565 PyThreadState *tstate;
566 PyObject *bimod, *sysmod, *pstderr;
567 char *p;
Eric Snow1abcf672017-05-23 21:46:51 -0700568 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700569 _PyMainInterpreterConfig preinit_config = _PyMainInterpreterConfig_INIT;
Nick Coghland6009512014-11-20 21:39:37 +1000570
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600571 _PyRuntime_Initialize();
572
Eric Snow1abcf672017-05-23 21:46:51 -0700573 if (config != NULL) {
574 core_config = *config;
575 }
576
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600577 if (_PyRuntime.initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700578 Py_FatalError("Py_InitializeCore: main interpreter already initialized");
579 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600580 if (_PyRuntime.core_initialized) {
Eric Snow1abcf672017-05-23 21:46:51 -0700581 Py_FatalError("Py_InitializeCore: runtime core already initialized");
582 }
583
584 /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
585 * threads behave a little more gracefully at interpreter shutdown.
586 * We clobber it here so the new interpreter can start with a clean
587 * slate.
588 *
589 * However, this may still lead to misbehaviour if there are daemon
590 * threads still hanging around from a previous Py_Initialize/Finalize
591 * pair :(
592 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600593 _PyRuntime.finalizing = NULL;
594
595 if (_PyMem_SetupAllocators(core_config.allocator) < 0) {
596 fprintf(stderr,
597 "Error in PYTHONMALLOC: unknown allocator \"%s\"!\n",
598 core_config.allocator);
599 exit(1);
600 }
Nick Coghland6009512014-11-20 21:39:37 +1000601
Nick Coghlan6ea41862017-06-11 13:16:15 +1000602#ifdef __ANDROID__
603 /* Passing "" to setlocale() on Android requests the C locale rather
604 * than checking environment variables, so request C.UTF-8 explicitly
605 */
606 setlocale(LC_CTYPE, "C.UTF-8");
607#else
608#ifndef MS_WINDOWS
Nick Coghland6009512014-11-20 21:39:37 +1000609 /* Set up the LC_CTYPE locale, so we can obtain
610 the locale's charset without having to switch
611 locales. */
612 setlocale(LC_CTYPE, "");
Nick Coghlaneb817952017-06-18 12:29:42 +1000613 _emit_stderr_warning_for_legacy_locale();
Nick Coghlan6ea41862017-06-11 13:16:15 +1000614#endif
Nick Coghland6009512014-11-20 21:39:37 +1000615#endif
616
617 if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000618 set_flag(&Py_DebugFlag, p);
Nick Coghland6009512014-11-20 21:39:37 +1000619 if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000620 set_flag(&Py_VerboseFlag, p);
Nick Coghland6009512014-11-20 21:39:37 +1000621 if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000622 set_flag(&Py_OptimizeFlag, p);
623 if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
624 set_flag(&Py_InspectFlag, p);
Nick Coghland6009512014-11-20 21:39:37 +1000625 if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000626 set_flag(&Py_DontWriteBytecodeFlag, p);
627 if ((p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
628 set_flag(&Py_NoUserSiteDirectory, p);
629 if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
630 set_flag(&Py_UnbufferedStdioFlag, p);
Eric Snow6b4be192017-05-22 21:36:03 -0700631 /* The variable is only tested for existence here;
632 _Py_HashRandomization_Init will check its value further. */
Nick Coghland6009512014-11-20 21:39:37 +1000633 if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000634 set_flag(&Py_HashRandomizationFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700635#ifdef MS_WINDOWS
636 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSFSENCODING")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000637 set_flag(&Py_LegacyWindowsFSEncodingFlag, p);
Steve Dower39294992016-08-30 21:22:36 -0700638 if ((p = Py_GETENV("PYTHONLEGACYWINDOWSSTDIO")) && *p != '\0')
Nick Coghland7ac0612017-10-25 12:11:26 +1000639 set_flag(&Py_LegacyWindowsStdioFlag, p);
Steve Dowercc16be82016-09-08 10:35:16 -0700640#endif
Nick Coghland6009512014-11-20 21:39:37 +1000641
Eric Snow1abcf672017-05-23 21:46:51 -0700642 _Py_HashRandomization_Init(&core_config);
643 if (!core_config.use_hash_seed || core_config.hash_seed) {
644 /* Random or non-zero hash seed */
645 Py_HashRandomizationFlag = 1;
646 }
Nick Coghland6009512014-11-20 21:39:37 +1000647
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600648 _PyInterpreterState_Enable(&_PyRuntime);
Nick Coghland6009512014-11-20 21:39:37 +1000649 interp = PyInterpreterState_New();
650 if (interp == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700651 Py_FatalError("Py_InitializeCore: can't make main interpreter");
652 interp->core_config = core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -0700653 interp->config = preinit_config;
Nick Coghland6009512014-11-20 21:39:37 +1000654
655 tstate = PyThreadState_New(interp);
656 if (tstate == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700657 Py_FatalError("Py_InitializeCore: can't make first thread");
Nick Coghland6009512014-11-20 21:39:37 +1000658 (void) PyThreadState_Swap(tstate);
659
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000660 /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
Nick Coghland6009512014-11-20 21:39:37 +1000661 destroying the GIL might fail when it is being referenced from
662 another running thread (see issue #9901).
663 Instead we destroy the previously created GIL here, which ensures
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000664 that we can call Py_Initialize / Py_FinalizeEx multiple times. */
Nick Coghland6009512014-11-20 21:39:37 +1000665 _PyEval_FiniThreads();
Nick Coghland6009512014-11-20 21:39:37 +1000666 /* Auto-thread-state API */
667 _PyGILState_Init(interp, tstate);
Nick Coghland6009512014-11-20 21:39:37 +1000668
669 _Py_ReadyTypes();
670
671 if (!_PyFrame_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700672 Py_FatalError("Py_InitializeCore: can't init frames");
Nick Coghland6009512014-11-20 21:39:37 +1000673
674 if (!_PyLong_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700675 Py_FatalError("Py_InitializeCore: can't init longs");
Nick Coghland6009512014-11-20 21:39:37 +1000676
677 if (!PyByteArray_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700678 Py_FatalError("Py_InitializeCore: can't init bytearray");
Nick Coghland6009512014-11-20 21:39:37 +1000679
680 if (!_PyFloat_Init())
Eric Snow1abcf672017-05-23 21:46:51 -0700681 Py_FatalError("Py_InitializeCore: can't init float");
Nick Coghland6009512014-11-20 21:39:37 +1000682
Eric Snowd393c1b2017-09-14 12:18:12 -0600683 PyObject *modules = PyDict_New();
684 if (modules == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700685 Py_FatalError("Py_InitializeCore: can't make modules dictionary");
Eric Snowd393c1b2017-09-14 12:18:12 -0600686 interp->modules = modules;
687
688 sysmod = _PySys_BeginInit();
689 if (sysmod == NULL)
690 Py_FatalError("Py_InitializeCore: can't initialize sys");
691 interp->sysdict = PyModule_GetDict(sysmod);
692 if (interp->sysdict == NULL)
693 Py_FatalError("Py_InitializeCore: can't initialize sys dict");
694 Py_INCREF(interp->sysdict);
695 PyDict_SetItemString(interp->sysdict, "modules", modules);
696 _PyImport_FixupBuiltin(sysmod, "sys", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000697
698 /* Init Unicode implementation; relies on the codec registry */
699 if (_PyUnicode_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700700 Py_FatalError("Py_InitializeCore: can't initialize unicode");
701
Nick Coghland6009512014-11-20 21:39:37 +1000702 if (_PyStructSequence_Init() < 0)
Eric Snow1abcf672017-05-23 21:46:51 -0700703 Py_FatalError("Py_InitializeCore: can't initialize structseq");
Nick Coghland6009512014-11-20 21:39:37 +1000704
705 bimod = _PyBuiltin_Init();
706 if (bimod == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700707 Py_FatalError("Py_InitializeCore: can't initialize builtins modules");
Eric Snowd393c1b2017-09-14 12:18:12 -0600708 _PyImport_FixupBuiltin(bimod, "builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +1000709 interp->builtins = PyModule_GetDict(bimod);
710 if (interp->builtins == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700711 Py_FatalError("Py_InitializeCore: can't initialize builtins dict");
Nick Coghland6009512014-11-20 21:39:37 +1000712 Py_INCREF(interp->builtins);
713
714 /* initialize builtin exceptions */
715 _PyExc_Init(bimod);
716
Nick Coghland6009512014-11-20 21:39:37 +1000717 /* Set up a preliminary stderr printer until we have enough
718 infrastructure for the io module in place. */
719 pstderr = PyFile_NewStdPrinter(fileno(stderr));
720 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -0700721 Py_FatalError("Py_InitializeCore: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +1000722 _PySys_SetObjectId(&PyId_stderr, pstderr);
723 PySys_SetObject("__stderr__", pstderr);
724 Py_DECREF(pstderr);
725
726 _PyImport_Init();
727
728 _PyImportHooks_Init();
729
730 /* Initialize _warnings. */
731 _PyWarnings_Init();
732
Eric Snow1abcf672017-05-23 21:46:51 -0700733 /* This call sets up builtin and frozen import support */
734 if (!interp->core_config._disable_importlib) {
735 initimport(interp, sysmod);
736 }
737
738 /* Only when we get here is the runtime core fully initialized */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600739 _PyRuntime.core_initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700740}
741
Eric Snowc7ec9982017-05-23 23:00:52 -0700742/* Read configuration settings from standard locations
743 *
744 * This function doesn't make any changes to the interpreter state - it
745 * merely populates any missing configuration settings. This allows an
746 * embedding application to completely override a config option by
747 * setting it before calling this function, or else modify the default
748 * setting before passing the fully populated config to Py_EndInitialization.
749 *
750 * More advanced selective initialization tricks are possible by calling
751 * this function multiple times with various preconfigured settings.
752 */
753
754int _Py_ReadMainInterpreterConfig(_PyMainInterpreterConfig *config)
755{
756 /* Signal handlers are installed by default */
757 if (config->install_signal_handlers < 0) {
758 config->install_signal_handlers = 1;
759 }
760
761 return 0;
762}
763
764/* Update interpreter state based on supplied configuration settings
765 *
766 * After calling this function, most of the restrictions on the interpreter
767 * are lifted. The only remaining incomplete settings are those related
768 * to the main module (sys.argv[0], __main__ metadata)
769 *
770 * Calling this when the interpreter is not initializing, is already
771 * initialized or without a valid current thread state is a fatal error.
772 * Other errors should be reported as normal Python exceptions with a
773 * non-zero return code.
774 */
775int _Py_InitializeMainInterpreter(const _PyMainInterpreterConfig *config)
Eric Snow1abcf672017-05-23 21:46:51 -0700776{
777 PyInterpreterState *interp;
778 PyThreadState *tstate;
779
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600780 if (!_PyRuntime.core_initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700781 Py_FatalError("Py_InitializeMainInterpreter: runtime core not initialized");
782 }
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600783 if (_PyRuntime.initialized) {
Eric Snowc7ec9982017-05-23 23:00:52 -0700784 Py_FatalError("Py_InitializeMainInterpreter: main interpreter already initialized");
785 }
786
Eric Snow1abcf672017-05-23 21:46:51 -0700787 /* Get current thread state and interpreter pointer */
788 tstate = PyThreadState_GET();
789 if (!tstate)
Eric Snowc7ec9982017-05-23 23:00:52 -0700790 Py_FatalError("Py_InitializeMainInterpreter: failed to read thread state");
Eric Snow1abcf672017-05-23 21:46:51 -0700791 interp = tstate->interp;
792 if (!interp)
Eric Snowc7ec9982017-05-23 23:00:52 -0700793 Py_FatalError("Py_InitializeMainInterpreter: failed to get interpreter");
Eric Snow1abcf672017-05-23 21:46:51 -0700794
795 /* Now finish configuring the main interpreter */
Eric Snowc7ec9982017-05-23 23:00:52 -0700796 interp->config = *config;
797
Eric Snow1abcf672017-05-23 21:46:51 -0700798 if (interp->core_config._disable_importlib) {
799 /* Special mode for freeze_importlib: run with no import system
800 *
801 * This means anything which needs support from extension modules
802 * or pure Python code in the standard library won't work.
803 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600804 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700805 return 0;
806 }
807 /* TODO: Report exceptions rather than fatal errors below here */
Nick Coghland6009512014-11-20 21:39:37 +1000808
Victor Stinner13019fd2015-04-03 13:10:54 +0200809 if (_PyTime_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700810 Py_FatalError("Py_InitializeMainInterpreter: can't initialize time");
Victor Stinner13019fd2015-04-03 13:10:54 +0200811
Eric Snow1abcf672017-05-23 21:46:51 -0700812 /* Finish setting up the sys module and import system */
813 /* GetPath may initialize state that _PySys_EndInit locks
814 in, and so has to be called first. */
Eric Snow18c13562017-05-25 10:05:50 -0700815 /* TODO: Call Py_GetPath() in Py_ReadConfig, rather than here */
Eric Snow1abcf672017-05-23 21:46:51 -0700816 PySys_SetPath(Py_GetPath());
817 if (_PySys_EndInit(interp->sysdict) < 0)
818 Py_FatalError("Py_InitializeMainInterpreter: can't finish initializing sys");
Eric Snow1abcf672017-05-23 21:46:51 -0700819 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +1000820
821 /* initialize the faulthandler module */
822 if (_PyFaulthandler_Init())
Eric Snowc7ec9982017-05-23 23:00:52 -0700823 Py_FatalError("Py_InitializeMainInterpreter: can't initialize faulthandler");
Nick Coghland6009512014-11-20 21:39:37 +1000824
Nick Coghland6009512014-11-20 21:39:37 +1000825 if (initfsencoding(interp) < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700826 Py_FatalError("Py_InitializeMainInterpreter: unable to load the file system codec");
Nick Coghland6009512014-11-20 21:39:37 +1000827
Eric Snowc7ec9982017-05-23 23:00:52 -0700828 if (config->install_signal_handlers)
Nick Coghland6009512014-11-20 21:39:37 +1000829 initsigs(); /* Signal handling stuff, including initintr() */
830
831 if (_PyTraceMalloc_Init() < 0)
Eric Snowc7ec9982017-05-23 23:00:52 -0700832 Py_FatalError("Py_InitializeMainInterpreter: can't initialize tracemalloc");
Nick Coghland6009512014-11-20 21:39:37 +1000833
834 initmain(interp); /* Module __main__ */
835 if (initstdio() < 0)
836 Py_FatalError(
Eric Snowc7ec9982017-05-23 23:00:52 -0700837 "Py_InitializeMainInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +1000838
839 /* Initialize warnings. */
840 if (PySys_HasWarnOptions()) {
841 PyObject *warnings_module = PyImport_ImportModule("warnings");
842 if (warnings_module == NULL) {
843 fprintf(stderr, "'import warnings' failed; traceback:\n");
844 PyErr_Print();
845 }
846 Py_XDECREF(warnings_module);
847 }
848
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600849 _PyRuntime.initialized = 1;
Eric Snow1abcf672017-05-23 21:46:51 -0700850
Nick Coghland6009512014-11-20 21:39:37 +1000851 if (!Py_NoSiteFlag)
852 initsite(); /* Module site */
Eric Snow1abcf672017-05-23 21:46:51 -0700853
Eric Snowc7ec9982017-05-23 23:00:52 -0700854 return 0;
Nick Coghland6009512014-11-20 21:39:37 +1000855}
856
Eric Snowc7ec9982017-05-23 23:00:52 -0700857#undef _INIT_DEBUG_PRINT
858
Nick Coghland6009512014-11-20 21:39:37 +1000859void
Eric Snow1abcf672017-05-23 21:46:51 -0700860_Py_InitializeEx_Private(int install_sigs, int install_importlib)
861{
862 _PyCoreConfig core_config = _PyCoreConfig_INIT;
Eric Snowc7ec9982017-05-23 23:00:52 -0700863 _PyMainInterpreterConfig config = _PyMainInterpreterConfig_INIT;
Eric Snow1abcf672017-05-23 21:46:51 -0700864
865 /* TODO: Moar config options! */
866 core_config.ignore_environment = Py_IgnoreEnvironmentFlag;
867 core_config._disable_importlib = !install_importlib;
Eric Snowc7ec9982017-05-23 23:00:52 -0700868 config.install_signal_handlers = install_sigs;
Eric Snow1abcf672017-05-23 21:46:51 -0700869 _Py_InitializeCore(&core_config);
Eric Snowc7ec9982017-05-23 23:00:52 -0700870 /* TODO: Print any exceptions raised by these operations */
871 if (_Py_ReadMainInterpreterConfig(&config))
872 Py_FatalError("Py_Initialize: Py_ReadMainInterpreterConfig failed");
873 if (_Py_InitializeMainInterpreter(&config))
874 Py_FatalError("Py_Initialize: Py_InitializeMainInterpreter failed");
Eric Snow1abcf672017-05-23 21:46:51 -0700875}
876
877
878void
Nick Coghland6009512014-11-20 21:39:37 +1000879Py_InitializeEx(int install_sigs)
880{
881 _Py_InitializeEx_Private(install_sigs, 1);
882}
883
884void
885Py_Initialize(void)
886{
887 Py_InitializeEx(1);
888}
889
890
891#ifdef COUNT_ALLOCS
892extern void dump_counts(FILE*);
893#endif
894
895/* Flush stdout and stderr */
896
897static int
898file_is_closed(PyObject *fobj)
899{
900 int r;
901 PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
902 if (tmp == NULL) {
903 PyErr_Clear();
904 return 0;
905 }
906 r = PyObject_IsTrue(tmp);
907 Py_DECREF(tmp);
908 if (r < 0)
909 PyErr_Clear();
910 return r > 0;
911}
912
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000913static int
Nick Coghland6009512014-11-20 21:39:37 +1000914flush_std_files(void)
915{
916 PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
917 PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
918 PyObject *tmp;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000919 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000920
921 if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700922 tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000923 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000924 PyErr_WriteUnraisable(fout);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000925 status = -1;
926 }
Nick Coghland6009512014-11-20 21:39:37 +1000927 else
928 Py_DECREF(tmp);
929 }
930
931 if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
Victor Stinner3466bde2016-09-05 18:16:01 -0700932 tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000933 if (tmp == NULL) {
Nick Coghland6009512014-11-20 21:39:37 +1000934 PyErr_Clear();
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000935 status = -1;
936 }
Nick Coghland6009512014-11-20 21:39:37 +1000937 else
938 Py_DECREF(tmp);
939 }
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000940
941 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000942}
943
944/* Undo the effect of Py_Initialize().
945
946 Beware: if multiple interpreter and/or thread states exist, these
947 are not wiped out; only the current thread and interpreter state
948 are deleted. But since everything else is deleted, those other
949 interpreter and thread states should no longer be used.
950
951 (XXX We should do better, e.g. wipe out all interpreters and
952 threads.)
953
954 Locking: as above.
955
956*/
957
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000958int
959Py_FinalizeEx(void)
Nick Coghland6009512014-11-20 21:39:37 +1000960{
961 PyInterpreterState *interp;
962 PyThreadState *tstate;
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000963 int status = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000964
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600965 if (!_PyRuntime.initialized)
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000966 return status;
Nick Coghland6009512014-11-20 21:39:37 +1000967
968 wait_for_thread_shutdown();
969
970 /* The interpreter is still entirely intact at this point, and the
971 * exit funcs may be relying on that. In particular, if some thread
972 * or exit func is still waiting to do an import, the import machinery
973 * expects Py_IsInitialized() to return true. So don't say the
974 * interpreter is uninitialized until after the exit funcs have run.
975 * Note that Threading.py uses an exit func to do a join on all the
976 * threads created thru it, so this also protects pending imports in
977 * the threads created via Threading.
978 */
979 call_py_exitfuncs();
980
981 /* Get current thread state and interpreter pointer */
982 tstate = PyThreadState_GET();
983 interp = tstate->interp;
984
985 /* Remaining threads (e.g. daemon threads) will automatically exit
986 after taking the GIL (in PyEval_RestoreThread()). */
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600987 _PyRuntime.finalizing = tstate;
988 _PyRuntime.initialized = 0;
989 _PyRuntime.core_initialized = 0;
Nick Coghland6009512014-11-20 21:39:37 +1000990
Victor Stinnere0deff32015-03-24 13:46:18 +0100991 /* Flush sys.stdout and sys.stderr */
Martin Panterb4ce1fc2015-11-30 03:18:29 +0000992 if (flush_std_files() < 0) {
993 status = -1;
994 }
Nick Coghland6009512014-11-20 21:39:37 +1000995
996 /* Disable signal handling */
997 PyOS_FiniInterrupts();
998
999 /* Collect garbage. This may call finalizers; it's nice to call these
1000 * before all modules are destroyed.
1001 * XXX If a __del__ or weakref callback is triggered here, and tries to
1002 * XXX import a module, bad things can happen, because Python no
1003 * XXX longer believes it's initialized.
1004 * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
1005 * XXX is easy to provoke that way. I've also seen, e.g.,
1006 * XXX Exception exceptions.ImportError: 'No module named sha'
1007 * XXX in <function callback at 0x008F5718> ignored
1008 * XXX but I'm unclear on exactly how that one happens. In any case,
1009 * XXX I haven't seen a real-life report of either of these.
1010 */
Łukasz Langafef7e942016-09-09 21:47:46 -07001011 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001012#ifdef COUNT_ALLOCS
1013 /* With COUNT_ALLOCS, it helps to run GC multiple times:
1014 each collection might release some types from the type
1015 list, so they become garbage. */
Łukasz Langafef7e942016-09-09 21:47:46 -07001016 while (_PyGC_CollectIfEnabled() > 0)
Nick Coghland6009512014-11-20 21:39:37 +10001017 /* nothing */;
1018#endif
Eric Snowdae02762017-09-14 00:35:58 -07001019
1020#ifdef Py_REF_DEBUG
1021 PyObject *showrefcount = _PyDebug_XOptionShowRefCount();
1022#endif
1023
Nick Coghland6009512014-11-20 21:39:37 +10001024 /* Destroy all modules */
1025 PyImport_Cleanup();
1026
Victor Stinnere0deff32015-03-24 13:46:18 +01001027 /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001028 if (flush_std_files() < 0) {
1029 status = -1;
1030 }
Nick Coghland6009512014-11-20 21:39:37 +10001031
1032 /* Collect final garbage. This disposes of cycles created by
1033 * class definitions, for example.
1034 * XXX This is disabled because it caused too many problems. If
1035 * XXX a __del__ or weakref callback triggers here, Python code has
1036 * XXX a hard time running, because even the sys module has been
1037 * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1038 * XXX One symptom is a sequence of information-free messages
1039 * XXX coming from threads (if a __del__ or callback is invoked,
1040 * XXX other threads can execute too, and any exception they encounter
1041 * XXX triggers a comedy of errors as subsystem after subsystem
1042 * XXX fails to find what it *expects* to find in sys to help report
1043 * XXX the exception and consequent unexpected failures). I've also
1044 * XXX seen segfaults then, after adding print statements to the
1045 * XXX Python code getting called.
1046 */
1047#if 0
Łukasz Langafef7e942016-09-09 21:47:46 -07001048 _PyGC_CollectIfEnabled();
Nick Coghland6009512014-11-20 21:39:37 +10001049#endif
1050
1051 /* Disable tracemalloc after all Python objects have been destroyed,
1052 so it is possible to use tracemalloc in objects destructor. */
1053 _PyTraceMalloc_Fini();
1054
1055 /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1056 _PyImport_Fini();
1057
1058 /* Cleanup typeobject.c's internal caches. */
1059 _PyType_Fini();
1060
1061 /* unload faulthandler module */
1062 _PyFaulthandler_Fini();
1063
1064 /* Debugging stuff */
1065#ifdef COUNT_ALLOCS
Serhiy Storchaka7e160ce2016-07-03 21:03:53 +03001066 dump_counts(stderr);
Nick Coghland6009512014-11-20 21:39:37 +10001067#endif
1068 /* dump hash stats */
1069 _PyHash_Fini();
1070
Eric Snowdae02762017-09-14 00:35:58 -07001071#ifdef Py_REF_DEBUG
1072 if (showrefcount == Py_True)
1073 _PyDebug_PrintTotalRefs();
1074#endif
Nick Coghland6009512014-11-20 21:39:37 +10001075
1076#ifdef Py_TRACE_REFS
1077 /* Display all objects still alive -- this can invoke arbitrary
1078 * __repr__ overrides, so requires a mostly-intact interpreter.
1079 * Alas, a lot of stuff may still be alive now that will be cleaned
1080 * up later.
1081 */
1082 if (Py_GETENV("PYTHONDUMPREFS"))
1083 _Py_PrintReferences(stderr);
1084#endif /* Py_TRACE_REFS */
1085
1086 /* Clear interpreter state and all thread states. */
1087 PyInterpreterState_Clear(interp);
1088
1089 /* Now we decref the exception classes. After this point nothing
1090 can raise an exception. That's okay, because each Fini() method
1091 below has been checked to make sure no exceptions are ever
1092 raised.
1093 */
1094
1095 _PyExc_Fini();
1096
1097 /* Sundry finalizers */
1098 PyMethod_Fini();
1099 PyFrame_Fini();
1100 PyCFunction_Fini();
1101 PyTuple_Fini();
1102 PyList_Fini();
1103 PySet_Fini();
1104 PyBytes_Fini();
1105 PyByteArray_Fini();
1106 PyLong_Fini();
1107 PyFloat_Fini();
1108 PyDict_Fini();
1109 PySlice_Fini();
1110 _PyGC_Fini();
Eric Snow6b4be192017-05-22 21:36:03 -07001111 _Py_HashRandomization_Fini();
Serhiy Storchaka9171a8b2016-08-14 10:52:18 +03001112 _PyArg_Fini();
Yury Selivanoveb636452016-09-08 22:01:51 -07001113 PyAsyncGen_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001114
1115 /* Cleanup Unicode implementation */
1116 _PyUnicode_Fini();
1117
1118 /* reset file system default encoding */
1119 if (!Py_HasFileSystemDefaultEncoding && Py_FileSystemDefaultEncoding) {
1120 PyMem_RawFree((char*)Py_FileSystemDefaultEncoding);
1121 Py_FileSystemDefaultEncoding = NULL;
1122 }
1123
1124 /* XXX Still allocated:
1125 - various static ad-hoc pointers to interned strings
1126 - int and float free list blocks
1127 - whatever various modules and libraries allocate
1128 */
1129
1130 PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1131
1132 /* Cleanup auto-thread-state */
Nick Coghland6009512014-11-20 21:39:37 +10001133 _PyGILState_Fini();
Nick Coghland6009512014-11-20 21:39:37 +10001134
1135 /* Delete current thread. After this, many C API calls become crashy. */
1136 PyThreadState_Swap(NULL);
Victor Stinner8a1be612016-03-14 22:07:55 +01001137
Nick Coghland6009512014-11-20 21:39:37 +10001138 PyInterpreterState_Delete(interp);
1139
1140#ifdef Py_TRACE_REFS
1141 /* Display addresses (& refcnts) of all objects still alive.
1142 * An address can be used to find the repr of the object, printed
1143 * above by _Py_PrintReferences.
1144 */
1145 if (Py_GETENV("PYTHONDUMPREFS"))
1146 _Py_PrintReferenceAddresses(stderr);
1147#endif /* Py_TRACE_REFS */
Victor Stinner34be8072016-03-14 12:04:26 +01001148#ifdef WITH_PYMALLOC
1149 if (_PyMem_PymallocEnabled()) {
1150 char *opt = Py_GETENV("PYTHONMALLOCSTATS");
1151 if (opt != NULL && *opt != '\0')
1152 _PyObject_DebugMallocStats(stderr);
1153 }
Nick Coghland6009512014-11-20 21:39:37 +10001154#endif
1155
1156 call_ll_exitfuncs();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001157 _PyRuntime_Finalize();
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001158 return status;
1159}
1160
1161void
1162Py_Finalize(void)
1163{
1164 Py_FinalizeEx();
Nick Coghland6009512014-11-20 21:39:37 +10001165}
1166
1167/* Create and initialize a new interpreter and thread, and return the
1168 new thread. This requires that Py_Initialize() has been called
1169 first.
1170
1171 Unsuccessful initialization yields a NULL pointer. Note that *no*
1172 exception information is available even in this case -- the
1173 exception information is held in the thread, and there is no
1174 thread.
1175
1176 Locking: as above.
1177
1178*/
1179
1180PyThreadState *
1181Py_NewInterpreter(void)
1182{
1183 PyInterpreterState *interp;
1184 PyThreadState *tstate, *save_tstate;
1185 PyObject *bimod, *sysmod;
1186
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001187 if (!_PyRuntime.initialized)
Nick Coghland6009512014-11-20 21:39:37 +10001188 Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
1189
Victor Stinner8a1be612016-03-14 22:07:55 +01001190 /* Issue #10915, #15751: The GIL API doesn't work with multiple
1191 interpreters: disable PyGILState_Check(). */
1192 _PyGILState_check_enabled = 0;
1193
Nick Coghland6009512014-11-20 21:39:37 +10001194 interp = PyInterpreterState_New();
1195 if (interp == NULL)
1196 return NULL;
1197
1198 tstate = PyThreadState_New(interp);
1199 if (tstate == NULL) {
1200 PyInterpreterState_Delete(interp);
1201 return NULL;
1202 }
1203
1204 save_tstate = PyThreadState_Swap(tstate);
1205
Eric Snow1abcf672017-05-23 21:46:51 -07001206 /* Copy the current interpreter config into the new interpreter */
1207 if (save_tstate != NULL) {
1208 interp->core_config = save_tstate->interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001209 interp->config = save_tstate->interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001210 } else {
1211 /* No current thread state, copy from the main interpreter */
1212 PyInterpreterState *main_interp = PyInterpreterState_Main();
1213 interp->core_config = main_interp->core_config;
Eric Snowc7ec9982017-05-23 23:00:52 -07001214 interp->config = main_interp->config;
Eric Snow1abcf672017-05-23 21:46:51 -07001215 }
1216
Nick Coghland6009512014-11-20 21:39:37 +10001217 /* XXX The following is lax in error checking */
1218
Eric Snowd393c1b2017-09-14 12:18:12 -06001219 PyObject *modules = PyDict_New();
1220 if (modules == NULL)
1221 Py_FatalError("Py_NewInterpreter: can't make modules dictionary");
1222 interp->modules = modules;
Nick Coghland6009512014-11-20 21:39:37 +10001223
Eric Snowd393c1b2017-09-14 12:18:12 -06001224 sysmod = _PyImport_FindBuiltin("sys", modules);
1225 if (sysmod != NULL) {
1226 interp->sysdict = PyModule_GetDict(sysmod);
1227 if (interp->sysdict == NULL)
1228 goto handle_error;
1229 Py_INCREF(interp->sysdict);
1230 PyDict_SetItemString(interp->sysdict, "modules", modules);
1231 PySys_SetPath(Py_GetPath());
1232 _PySys_EndInit(interp->sysdict);
1233 }
1234
1235 bimod = _PyImport_FindBuiltin("builtins", modules);
Nick Coghland6009512014-11-20 21:39:37 +10001236 if (bimod != NULL) {
1237 interp->builtins = PyModule_GetDict(bimod);
1238 if (interp->builtins == NULL)
1239 goto handle_error;
1240 Py_INCREF(interp->builtins);
1241 }
1242
1243 /* initialize builtin exceptions */
1244 _PyExc_Init(bimod);
1245
Nick Coghland6009512014-11-20 21:39:37 +10001246 if (bimod != NULL && sysmod != NULL) {
1247 PyObject *pstderr;
1248
Nick Coghland6009512014-11-20 21:39:37 +10001249 /* Set up a preliminary stderr printer until we have enough
1250 infrastructure for the io module in place. */
1251 pstderr = PyFile_NewStdPrinter(fileno(stderr));
1252 if (pstderr == NULL)
Eric Snow1abcf672017-05-23 21:46:51 -07001253 Py_FatalError("Py_NewInterpreter: can't set preliminary stderr");
Nick Coghland6009512014-11-20 21:39:37 +10001254 _PySys_SetObjectId(&PyId_stderr, pstderr);
1255 PySys_SetObject("__stderr__", pstderr);
1256 Py_DECREF(pstderr);
1257
1258 _PyImportHooks_Init();
1259
Eric Snow1abcf672017-05-23 21:46:51 -07001260 initimport(interp, sysmod);
1261 initexternalimport(interp);
Nick Coghland6009512014-11-20 21:39:37 +10001262
1263 if (initfsencoding(interp) < 0)
1264 goto handle_error;
1265
1266 if (initstdio() < 0)
1267 Py_FatalError(
Eric Snow1abcf672017-05-23 21:46:51 -07001268 "Py_NewInterpreter: can't initialize sys standard streams");
Nick Coghland6009512014-11-20 21:39:37 +10001269 initmain(interp);
1270 if (!Py_NoSiteFlag)
1271 initsite();
1272 }
1273
1274 if (!PyErr_Occurred())
1275 return tstate;
1276
1277handle_error:
1278 /* Oops, it didn't work. Undo it all. */
1279
1280 PyErr_PrintEx(0);
1281 PyThreadState_Clear(tstate);
1282 PyThreadState_Swap(save_tstate);
1283 PyThreadState_Delete(tstate);
1284 PyInterpreterState_Delete(interp);
1285
1286 return NULL;
1287}
1288
1289/* Delete an interpreter and its last thread. This requires that the
1290 given thread state is current, that the thread has no remaining
1291 frames, and that it is its interpreter's only remaining thread.
1292 It is a fatal error to violate these constraints.
1293
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001294 (Py_FinalizeEx() doesn't have these constraints -- it zaps
Nick Coghland6009512014-11-20 21:39:37 +10001295 everything, regardless.)
1296
1297 Locking: as above.
1298
1299*/
1300
1301void
1302Py_EndInterpreter(PyThreadState *tstate)
1303{
1304 PyInterpreterState *interp = tstate->interp;
1305
1306 if (tstate != PyThreadState_GET())
1307 Py_FatalError("Py_EndInterpreter: thread is not current");
1308 if (tstate->frame != NULL)
1309 Py_FatalError("Py_EndInterpreter: thread still has a frame");
1310
1311 wait_for_thread_shutdown();
1312
1313 if (tstate != interp->tstate_head || tstate->next != NULL)
1314 Py_FatalError("Py_EndInterpreter: not the last thread");
1315
1316 PyImport_Cleanup();
1317 PyInterpreterState_Clear(interp);
1318 PyThreadState_Swap(NULL);
1319 PyInterpreterState_Delete(interp);
1320}
1321
1322#ifdef MS_WINDOWS
1323static wchar_t *progname = L"python";
1324#else
1325static wchar_t *progname = L"python3";
1326#endif
1327
1328void
1329Py_SetProgramName(wchar_t *pn)
1330{
1331 if (pn && *pn)
1332 progname = pn;
1333}
1334
1335wchar_t *
1336Py_GetProgramName(void)
1337{
1338 return progname;
1339}
1340
1341static wchar_t *default_home = NULL;
1342static wchar_t env_home[MAXPATHLEN+1];
1343
1344void
1345Py_SetPythonHome(wchar_t *home)
1346{
1347 default_home = home;
1348}
1349
1350wchar_t *
1351Py_GetPythonHome(void)
1352{
1353 wchar_t *home = default_home;
1354 if (home == NULL && !Py_IgnoreEnvironmentFlag) {
1355 char* chome = Py_GETENV("PYTHONHOME");
1356 if (chome) {
1357 size_t size = Py_ARRAY_LENGTH(env_home);
1358 size_t r = mbstowcs(env_home, chome, size);
1359 if (r != (size_t)-1 && r < size)
1360 home = env_home;
1361 }
1362
1363 }
1364 return home;
1365}
1366
1367/* Create __main__ module */
1368
1369static void
1370initmain(PyInterpreterState *interp)
1371{
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001372 PyObject *m, *d, *loader, *ann_dict;
Nick Coghland6009512014-11-20 21:39:37 +10001373 m = PyImport_AddModule("__main__");
1374 if (m == NULL)
1375 Py_FatalError("can't create __main__ module");
1376 d = PyModule_GetDict(m);
Yury Selivanovf8cb8a12016-09-08 20:50:03 -07001377 ann_dict = PyDict_New();
1378 if ((ann_dict == NULL) ||
1379 (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1380 Py_FatalError("Failed to initialize __main__.__annotations__");
1381 }
1382 Py_DECREF(ann_dict);
Nick Coghland6009512014-11-20 21:39:37 +10001383 if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1384 PyObject *bimod = PyImport_ImportModule("builtins");
1385 if (bimod == NULL) {
1386 Py_FatalError("Failed to retrieve builtins module");
1387 }
1388 if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1389 Py_FatalError("Failed to initialize __main__.__builtins__");
1390 }
1391 Py_DECREF(bimod);
1392 }
1393 /* Main is a little special - imp.is_builtin("__main__") will return
1394 * False, but BuiltinImporter is still the most appropriate initial
1395 * setting for its __loader__ attribute. A more suitable value will
1396 * be set if __main__ gets further initialized later in the startup
1397 * process.
1398 */
1399 loader = PyDict_GetItemString(d, "__loader__");
1400 if (loader == NULL || loader == Py_None) {
1401 PyObject *loader = PyObject_GetAttrString(interp->importlib,
1402 "BuiltinImporter");
1403 if (loader == NULL) {
1404 Py_FatalError("Failed to retrieve BuiltinImporter");
1405 }
1406 if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1407 Py_FatalError("Failed to initialize __main__.__loader__");
1408 }
1409 Py_DECREF(loader);
1410 }
1411}
1412
1413static int
1414initfsencoding(PyInterpreterState *interp)
1415{
1416 PyObject *codec;
1417
Steve Dowercc16be82016-09-08 10:35:16 -07001418#ifdef MS_WINDOWS
1419 if (Py_LegacyWindowsFSEncodingFlag)
1420 {
1421 Py_FileSystemDefaultEncoding = "mbcs";
1422 Py_FileSystemDefaultEncodeErrors = "replace";
1423 }
1424 else
1425 {
1426 Py_FileSystemDefaultEncoding = "utf-8";
1427 Py_FileSystemDefaultEncodeErrors = "surrogatepass";
1428 }
1429#else
Nick Coghland6009512014-11-20 21:39:37 +10001430 if (Py_FileSystemDefaultEncoding == NULL)
1431 {
1432 Py_FileSystemDefaultEncoding = get_locale_encoding();
1433 if (Py_FileSystemDefaultEncoding == NULL)
1434 Py_FatalError("Py_Initialize: Unable to get the locale encoding");
1435
1436 Py_HasFileSystemDefaultEncoding = 0;
1437 interp->fscodec_initialized = 1;
1438 return 0;
1439 }
Steve Dowercc16be82016-09-08 10:35:16 -07001440#endif
Nick Coghland6009512014-11-20 21:39:37 +10001441
1442 /* the encoding is mbcs, utf-8 or ascii */
1443 codec = _PyCodec_Lookup(Py_FileSystemDefaultEncoding);
1444 if (!codec) {
1445 /* Such error can only occurs in critical situations: no more
1446 * memory, import a module of the standard library failed,
1447 * etc. */
1448 return -1;
1449 }
1450 Py_DECREF(codec);
1451 interp->fscodec_initialized = 1;
1452 return 0;
1453}
1454
1455/* Import the site module (not into __main__ though) */
1456
1457static void
1458initsite(void)
1459{
1460 PyObject *m;
1461 m = PyImport_ImportModule("site");
1462 if (m == NULL) {
1463 fprintf(stderr, "Failed to import the site module\n");
1464 PyErr_Print();
1465 Py_Finalize();
1466 exit(1);
1467 }
1468 else {
1469 Py_DECREF(m);
1470 }
1471}
1472
Victor Stinner874dbe82015-09-04 17:29:57 +02001473/* Check if a file descriptor is valid or not.
1474 Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1475static int
1476is_valid_fd(int fd)
1477{
Victor Stinner1c4670e2017-05-04 00:45:56 +02001478#ifdef __APPLE__
1479 /* bpo-30225: On macOS Tiger, when stdout is redirected to a pipe
1480 and the other side of the pipe is closed, dup(1) succeed, whereas
1481 fstat(1, &st) fails with EBADF. Prefer fstat() over dup() to detect
1482 such error. */
1483 struct stat st;
1484 return (fstat(fd, &st) == 0);
1485#else
Victor Stinner874dbe82015-09-04 17:29:57 +02001486 int fd2;
Steve Dower940f33a2016-09-08 11:21:54 -07001487 if (fd < 0)
Victor Stinner874dbe82015-09-04 17:29:57 +02001488 return 0;
1489 _Py_BEGIN_SUPPRESS_IPH
Victor Stinner449b2712015-09-29 13:59:50 +02001490 /* Prefer dup() over fstat(). fstat() can require input/output whereas
1491 dup() doesn't, there is a low risk of EMFILE/ENFILE at Python
1492 startup. */
Victor Stinner874dbe82015-09-04 17:29:57 +02001493 fd2 = dup(fd);
1494 if (fd2 >= 0)
1495 close(fd2);
1496 _Py_END_SUPPRESS_IPH
1497 return fd2 >= 0;
Victor Stinner1c4670e2017-05-04 00:45:56 +02001498#endif
Victor Stinner874dbe82015-09-04 17:29:57 +02001499}
1500
1501/* returns Py_None if the fd is not valid */
Nick Coghland6009512014-11-20 21:39:37 +10001502static PyObject*
1503create_stdio(PyObject* io,
Serhiy Storchakaef1585e2015-12-25 20:01:53 +02001504 int fd, int write_mode, const char* name,
1505 const char* encoding, const char* errors)
Nick Coghland6009512014-11-20 21:39:37 +10001506{
1507 PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1508 const char* mode;
1509 const char* newline;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001510 PyObject *line_buffering, *write_through;
Nick Coghland6009512014-11-20 21:39:37 +10001511 int buffering, isatty;
1512 _Py_IDENTIFIER(open);
1513 _Py_IDENTIFIER(isatty);
1514 _Py_IDENTIFIER(TextIOWrapper);
1515 _Py_IDENTIFIER(mode);
1516
Victor Stinner874dbe82015-09-04 17:29:57 +02001517 if (!is_valid_fd(fd))
1518 Py_RETURN_NONE;
1519
Nick Coghland6009512014-11-20 21:39:37 +10001520 /* stdin is always opened in buffered mode, first because it shouldn't
1521 make a difference in common use cases, second because TextIOWrapper
1522 depends on the presence of a read1() method which only exists on
1523 buffered streams.
1524 */
1525 if (Py_UnbufferedStdioFlag && write_mode)
1526 buffering = 0;
1527 else
1528 buffering = -1;
1529 if (write_mode)
1530 mode = "wb";
1531 else
1532 mode = "rb";
1533 buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1534 fd, mode, buffering,
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001535 Py_None, Py_None, /* encoding, errors */
1536 Py_None, 0); /* newline, closefd */
Nick Coghland6009512014-11-20 21:39:37 +10001537 if (buf == NULL)
1538 goto error;
1539
1540 if (buffering) {
1541 _Py_IDENTIFIER(raw);
1542 raw = _PyObject_GetAttrId(buf, &PyId_raw);
1543 if (raw == NULL)
1544 goto error;
1545 }
1546 else {
1547 raw = buf;
1548 Py_INCREF(raw);
1549 }
1550
Steve Dower39294992016-08-30 21:22:36 -07001551#ifdef MS_WINDOWS
1552 /* Windows console IO is always UTF-8 encoded */
1553 if (PyWindowsConsoleIO_Check(raw))
1554 encoding = "utf-8";
1555#endif
1556
Nick Coghland6009512014-11-20 21:39:37 +10001557 text = PyUnicode_FromString(name);
1558 if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1559 goto error;
Victor Stinner3466bde2016-09-05 18:16:01 -07001560 res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001561 if (res == NULL)
1562 goto error;
1563 isatty = PyObject_IsTrue(res);
1564 Py_DECREF(res);
1565 if (isatty == -1)
1566 goto error;
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001567 if (Py_UnbufferedStdioFlag)
1568 write_through = Py_True;
1569 else
1570 write_through = Py_False;
1571 if (isatty && !Py_UnbufferedStdioFlag)
Nick Coghland6009512014-11-20 21:39:37 +10001572 line_buffering = Py_True;
1573 else
1574 line_buffering = Py_False;
1575
1576 Py_CLEAR(raw);
1577 Py_CLEAR(text);
1578
1579#ifdef MS_WINDOWS
1580 /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1581 newlines to "\n".
1582 sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1583 newline = NULL;
1584#else
1585 /* sys.stdin: split lines at "\n".
1586 sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1587 newline = "\n";
1588#endif
1589
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001590 stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OsssOO",
Nick Coghland6009512014-11-20 21:39:37 +10001591 buf, encoding, errors,
Serhiy Storchaka77732be2017-10-04 20:25:40 +03001592 newline, line_buffering, write_through);
Nick Coghland6009512014-11-20 21:39:37 +10001593 Py_CLEAR(buf);
1594 if (stream == NULL)
1595 goto error;
1596
1597 if (write_mode)
1598 mode = "w";
1599 else
1600 mode = "r";
1601 text = PyUnicode_FromString(mode);
1602 if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1603 goto error;
1604 Py_CLEAR(text);
1605 return stream;
1606
1607error:
1608 Py_XDECREF(buf);
1609 Py_XDECREF(stream);
1610 Py_XDECREF(text);
1611 Py_XDECREF(raw);
Nick Coghland6009512014-11-20 21:39:37 +10001612
Victor Stinner874dbe82015-09-04 17:29:57 +02001613 if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1614 /* Issue #24891: the file descriptor was closed after the first
1615 is_valid_fd() check was called. Ignore the OSError and set the
1616 stream to None. */
1617 PyErr_Clear();
1618 Py_RETURN_NONE;
1619 }
1620 return NULL;
Nick Coghland6009512014-11-20 21:39:37 +10001621}
1622
1623/* Initialize sys.stdin, stdout, stderr and builtins.open */
1624static int
1625initstdio(void)
1626{
1627 PyObject *iomod = NULL, *wrapper;
1628 PyObject *bimod = NULL;
1629 PyObject *m;
1630 PyObject *std = NULL;
1631 int status = 0, fd;
1632 PyObject * encoding_attr;
1633 char *pythonioencoding = NULL, *encoding, *errors;
1634
1635 /* Hack to avoid a nasty recursion issue when Python is invoked
1636 in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1637 if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1638 goto error;
1639 }
1640 Py_DECREF(m);
1641
1642 if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1643 goto error;
1644 }
1645 Py_DECREF(m);
1646
1647 if (!(bimod = PyImport_ImportModule("builtins"))) {
1648 goto error;
1649 }
1650
1651 if (!(iomod = PyImport_ImportModule("io"))) {
1652 goto error;
1653 }
1654 if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1655 goto error;
1656 }
1657
1658 /* Set builtins.open */
1659 if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1660 Py_DECREF(wrapper);
1661 goto error;
1662 }
1663 Py_DECREF(wrapper);
1664
1665 encoding = _Py_StandardStreamEncoding;
1666 errors = _Py_StandardStreamErrors;
1667 if (!encoding || !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001668 pythonioencoding = Py_GETENV("PYTHONIOENCODING");
1669 if (pythonioencoding) {
1670 char *err;
1671 pythonioencoding = _PyMem_Strdup(pythonioencoding);
1672 if (pythonioencoding == NULL) {
1673 PyErr_NoMemory();
1674 goto error;
1675 }
1676 err = strchr(pythonioencoding, ':');
1677 if (err) {
1678 *err = '\0';
1679 err++;
Serhiy Storchakafc435112016-04-10 14:34:13 +03001680 if (*err && !errors) {
Nick Coghland6009512014-11-20 21:39:37 +10001681 errors = err;
1682 }
1683 }
1684 if (*pythonioencoding && !encoding) {
1685 encoding = pythonioencoding;
1686 }
1687 }
Serhiy Storchakafc435112016-04-10 14:34:13 +03001688 if (!errors && !(pythonioencoding && *pythonioencoding)) {
Nick Coghlan6ea41862017-06-11 13:16:15 +10001689 /* Choose the default error handler based on the current locale */
1690 errors = get_default_standard_stream_error_handler();
Serhiy Storchakafc435112016-04-10 14:34:13 +03001691 }
Nick Coghland6009512014-11-20 21:39:37 +10001692 }
1693
1694 /* Set sys.stdin */
1695 fd = fileno(stdin);
1696 /* Under some conditions stdin, stdout and stderr may not be connected
1697 * and fileno() may point to an invalid file descriptor. For example
1698 * GUI apps don't have valid standard streams by default.
1699 */
Victor Stinner874dbe82015-09-04 17:29:57 +02001700 std = create_stdio(iomod, fd, 0, "<stdin>", encoding, errors);
1701 if (std == NULL)
1702 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001703 PySys_SetObject("__stdin__", std);
1704 _PySys_SetObjectId(&PyId_stdin, std);
1705 Py_DECREF(std);
1706
1707 /* Set sys.stdout */
1708 fd = fileno(stdout);
Victor Stinner874dbe82015-09-04 17:29:57 +02001709 std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
1710 if (std == NULL)
1711 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001712 PySys_SetObject("__stdout__", std);
1713 _PySys_SetObjectId(&PyId_stdout, std);
1714 Py_DECREF(std);
1715
1716#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1717 /* Set sys.stderr, replaces the preliminary stderr */
1718 fd = fileno(stderr);
Victor Stinner874dbe82015-09-04 17:29:57 +02001719 std = create_stdio(iomod, fd, 1, "<stderr>", encoding, "backslashreplace");
1720 if (std == NULL)
1721 goto error;
Nick Coghland6009512014-11-20 21:39:37 +10001722
1723 /* Same as hack above, pre-import stderr's codec to avoid recursion
1724 when import.c tries to write to stderr in verbose mode. */
1725 encoding_attr = PyObject_GetAttrString(std, "encoding");
1726 if (encoding_attr != NULL) {
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02001727 const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
Nick Coghland6009512014-11-20 21:39:37 +10001728 if (std_encoding != NULL) {
1729 PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1730 Py_XDECREF(codec_info);
1731 }
1732 Py_DECREF(encoding_attr);
1733 }
1734 PyErr_Clear(); /* Not a fatal error if codec isn't available */
1735
1736 if (PySys_SetObject("__stderr__", std) < 0) {
1737 Py_DECREF(std);
1738 goto error;
1739 }
1740 if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1741 Py_DECREF(std);
1742 goto error;
1743 }
1744 Py_DECREF(std);
1745#endif
1746
1747 if (0) {
1748 error:
1749 status = -1;
1750 }
1751
1752 /* We won't need them anymore. */
1753 if (_Py_StandardStreamEncoding) {
1754 PyMem_RawFree(_Py_StandardStreamEncoding);
1755 _Py_StandardStreamEncoding = NULL;
1756 }
1757 if (_Py_StandardStreamErrors) {
1758 PyMem_RawFree(_Py_StandardStreamErrors);
1759 _Py_StandardStreamErrors = NULL;
1760 }
1761 PyMem_Free(pythonioencoding);
1762 Py_XDECREF(bimod);
1763 Py_XDECREF(iomod);
1764 return status;
1765}
1766
1767
Victor Stinner10dc4842015-03-24 12:01:30 +01001768static void
Victor Stinner791da1c2016-03-14 16:53:12 +01001769_Py_FatalError_DumpTracebacks(int fd)
Victor Stinner10dc4842015-03-24 12:01:30 +01001770{
Victor Stinner10dc4842015-03-24 12:01:30 +01001771 fputc('\n', stderr);
1772 fflush(stderr);
1773
1774 /* display the current Python stack */
Victor Stinner861d9ab2016-03-16 22:45:24 +01001775 _Py_DumpTracebackThreads(fd, NULL, NULL);
Victor Stinner10dc4842015-03-24 12:01:30 +01001776}
Victor Stinner791da1c2016-03-14 16:53:12 +01001777
1778/* Print the current exception (if an exception is set) with its traceback,
1779 or display the current Python stack.
1780
1781 Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1782 called on catastrophic cases.
1783
1784 Return 1 if the traceback was displayed, 0 otherwise. */
1785
1786static int
1787_Py_FatalError_PrintExc(int fd)
1788{
1789 PyObject *ferr, *res;
1790 PyObject *exception, *v, *tb;
1791 int has_tb;
1792
1793 if (PyThreadState_GET() == NULL) {
1794 /* The GIL is released: trying to acquire it is likely to deadlock,
1795 just give up. */
1796 return 0;
1797 }
1798
1799 PyErr_Fetch(&exception, &v, &tb);
1800 if (exception == NULL) {
1801 /* No current exception */
1802 return 0;
1803 }
1804
1805 ferr = _PySys_GetObjectId(&PyId_stderr);
1806 if (ferr == NULL || ferr == Py_None) {
1807 /* sys.stderr is not set yet or set to None,
1808 no need to try to display the exception */
1809 return 0;
1810 }
1811
1812 PyErr_NormalizeException(&exception, &v, &tb);
1813 if (tb == NULL) {
1814 tb = Py_None;
1815 Py_INCREF(tb);
1816 }
1817 PyException_SetTraceback(v, tb);
1818 if (exception == NULL) {
1819 /* PyErr_NormalizeException() failed */
1820 return 0;
1821 }
1822
1823 has_tb = (tb != Py_None);
1824 PyErr_Display(exception, v, tb);
1825 Py_XDECREF(exception);
1826 Py_XDECREF(v);
1827 Py_XDECREF(tb);
1828
1829 /* sys.stderr may be buffered: call sys.stderr.flush() */
Victor Stinner3466bde2016-09-05 18:16:01 -07001830 res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
Victor Stinner791da1c2016-03-14 16:53:12 +01001831 if (res == NULL)
1832 PyErr_Clear();
1833 else
1834 Py_DECREF(res);
1835
1836 return has_tb;
1837}
1838
Nick Coghland6009512014-11-20 21:39:37 +10001839/* Print fatal error message and abort */
1840
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001841#ifdef MS_WINDOWS
1842static void
1843fatal_output_debug(const char *msg)
1844{
1845 /* buffer of 256 bytes allocated on the stack */
1846 WCHAR buffer[256 / sizeof(WCHAR)];
1847 size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
1848 size_t msglen;
1849
1850 OutputDebugStringW(L"Fatal Python error: ");
1851
1852 msglen = strlen(msg);
1853 while (msglen) {
1854 size_t i;
1855
1856 if (buflen > msglen) {
1857 buflen = msglen;
1858 }
1859
1860 /* Convert the message to wchar_t. This uses a simple one-to-one
1861 conversion, assuming that the this error message actually uses
1862 ASCII only. If this ceases to be true, we will have to convert. */
1863 for (i=0; i < buflen; ++i) {
1864 buffer[i] = msg[i];
1865 }
1866 buffer[i] = L'\0';
1867 OutputDebugStringW(buffer);
1868
1869 msg += buflen;
1870 msglen -= buflen;
1871 }
1872 OutputDebugStringW(L"\n");
1873}
1874#endif
1875
Nick Coghland6009512014-11-20 21:39:37 +10001876void
1877Py_FatalError(const char *msg)
1878{
1879 const int fd = fileno(stderr);
Victor Stinner53345a42015-03-25 01:55:14 +01001880 static int reentrant = 0;
Victor Stinner53345a42015-03-25 01:55:14 +01001881
1882 if (reentrant) {
1883 /* Py_FatalError() caused a second fatal error.
1884 Example: flush_std_files() raises a recursion error. */
1885 goto exit;
1886 }
1887 reentrant = 1;
Nick Coghland6009512014-11-20 21:39:37 +10001888
1889 fprintf(stderr, "Fatal Python error: %s\n", msg);
1890 fflush(stderr); /* it helps in Windows debug build */
Victor Stinner10dc4842015-03-24 12:01:30 +01001891
Victor Stinnere0deff32015-03-24 13:46:18 +01001892 /* Print the exception (if an exception is set) with its traceback,
1893 * or display the current Python stack. */
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001894 if (!_Py_FatalError_PrintExc(fd)) {
Victor Stinner791da1c2016-03-14 16:53:12 +01001895 _Py_FatalError_DumpTracebacks(fd);
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001896 }
Victor Stinner10dc4842015-03-24 12:01:30 +01001897
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001898 /* The main purpose of faulthandler is to display the traceback.
1899 This function already did its best to display a traceback.
1900 Disable faulthandler to prevent writing a second traceback
1901 on abort(). */
Victor Stinner2025d782016-03-16 23:19:15 +01001902 _PyFaulthandler_Fini();
1903
Victor Stinner791da1c2016-03-14 16:53:12 +01001904 /* Check if the current Python thread hold the GIL */
1905 if (PyThreadState_GET() != NULL) {
1906 /* Flush sys.stdout and sys.stderr */
1907 flush_std_files();
1908 }
Victor Stinnere0deff32015-03-24 13:46:18 +01001909
Nick Coghland6009512014-11-20 21:39:37 +10001910#ifdef MS_WINDOWS
Victor Stinner8d5a3aa2017-10-04 09:50:12 -07001911 fatal_output_debug(msg);
Victor Stinner53345a42015-03-25 01:55:14 +01001912#endif /* MS_WINDOWS */
1913
1914exit:
1915#if defined(MS_WINDOWS) && defined(_DEBUG)
Nick Coghland6009512014-11-20 21:39:37 +10001916 DebugBreak();
1917#endif
Nick Coghland6009512014-11-20 21:39:37 +10001918 abort();
1919}
1920
1921/* Clean up and exit */
1922
Victor Stinnerd7292b52016-06-17 12:29:00 +02001923# include "pythread.h"
Nick Coghland6009512014-11-20 21:39:37 +10001924
Nick Coghland6009512014-11-20 21:39:37 +10001925/* For the atexit module. */
1926void _Py_PyAtExit(void (*func)(void))
1927{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001928 _PyRuntime.pyexitfunc = func;
Nick Coghland6009512014-11-20 21:39:37 +10001929}
1930
1931static void
1932call_py_exitfuncs(void)
1933{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001934 if (_PyRuntime.pyexitfunc == NULL)
Nick Coghland6009512014-11-20 21:39:37 +10001935 return;
1936
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001937 (*_PyRuntime.pyexitfunc)();
Nick Coghland6009512014-11-20 21:39:37 +10001938 PyErr_Clear();
1939}
1940
1941/* Wait until threading._shutdown completes, provided
1942 the threading module was imported in the first place.
1943 The shutdown routine will wait until all non-daemon
1944 "threading" threads have completed. */
1945static void
1946wait_for_thread_shutdown(void)
1947{
Nick Coghland6009512014-11-20 21:39:37 +10001948 _Py_IDENTIFIER(_shutdown);
1949 PyObject *result;
Eric Snow3f9eee62017-09-15 16:35:20 -06001950 PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
Nick Coghland6009512014-11-20 21:39:37 +10001951 if (threading == NULL) {
1952 /* threading not imported */
1953 PyErr_Clear();
1954 return;
1955 }
Victor Stinner3466bde2016-09-05 18:16:01 -07001956 result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
Nick Coghland6009512014-11-20 21:39:37 +10001957 if (result == NULL) {
1958 PyErr_WriteUnraisable(threading);
1959 }
1960 else {
1961 Py_DECREF(result);
1962 }
1963 Py_DECREF(threading);
Nick Coghland6009512014-11-20 21:39:37 +10001964}
1965
1966#define NEXITFUNCS 32
Nick Coghland6009512014-11-20 21:39:37 +10001967int Py_AtExit(void (*func)(void))
1968{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001969 if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
Nick Coghland6009512014-11-20 21:39:37 +10001970 return -1;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001971 _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
Nick Coghland6009512014-11-20 21:39:37 +10001972 return 0;
1973}
1974
1975static void
1976call_ll_exitfuncs(void)
1977{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001978 while (_PyRuntime.nexitfuncs > 0)
1979 (*_PyRuntime.exitfuncs[--_PyRuntime.nexitfuncs])();
Nick Coghland6009512014-11-20 21:39:37 +10001980
1981 fflush(stdout);
1982 fflush(stderr);
1983}
1984
1985void
1986Py_Exit(int sts)
1987{
Martin Panterb4ce1fc2015-11-30 03:18:29 +00001988 if (Py_FinalizeEx() < 0) {
1989 sts = 120;
1990 }
Nick Coghland6009512014-11-20 21:39:37 +10001991
1992 exit(sts);
1993}
1994
1995static void
1996initsigs(void)
1997{
1998#ifdef SIGPIPE
1999 PyOS_setsig(SIGPIPE, SIG_IGN);
2000#endif
2001#ifdef SIGXFZ
2002 PyOS_setsig(SIGXFZ, SIG_IGN);
2003#endif
2004#ifdef SIGXFSZ
2005 PyOS_setsig(SIGXFSZ, SIG_IGN);
2006#endif
2007 PyOS_InitInterrupts(); /* May imply initsignal() */
2008 if (PyErr_Occurred()) {
2009 Py_FatalError("Py_Initialize: can't import signal");
2010 }
2011}
2012
2013
2014/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2015 *
2016 * All of the code in this function must only use async-signal-safe functions,
2017 * listed at `man 7 signal` or
2018 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2019 */
2020void
2021_Py_RestoreSignals(void)
2022{
2023#ifdef SIGPIPE
2024 PyOS_setsig(SIGPIPE, SIG_DFL);
2025#endif
2026#ifdef SIGXFZ
2027 PyOS_setsig(SIGXFZ, SIG_DFL);
2028#endif
2029#ifdef SIGXFSZ
2030 PyOS_setsig(SIGXFSZ, SIG_DFL);
2031#endif
2032}
2033
2034
2035/*
2036 * The file descriptor fd is considered ``interactive'' if either
2037 * a) isatty(fd) is TRUE, or
2038 * b) the -i flag was given, and the filename associated with
2039 * the descriptor is NULL or "<stdin>" or "???".
2040 */
2041int
2042Py_FdIsInteractive(FILE *fp, const char *filename)
2043{
2044 if (isatty((int)fileno(fp)))
2045 return 1;
2046 if (!Py_InteractiveFlag)
2047 return 0;
2048 return (filename == NULL) ||
2049 (strcmp(filename, "<stdin>") == 0) ||
2050 (strcmp(filename, "???") == 0);
2051}
2052
2053
Nick Coghland6009512014-11-20 21:39:37 +10002054/* Wrappers around sigaction() or signal(). */
2055
2056PyOS_sighandler_t
2057PyOS_getsig(int sig)
2058{
2059#ifdef HAVE_SIGACTION
2060 struct sigaction context;
2061 if (sigaction(sig, NULL, &context) == -1)
2062 return SIG_ERR;
2063 return context.sa_handler;
2064#else
2065 PyOS_sighandler_t handler;
2066/* Special signal handling for the secure CRT in Visual Studio 2005 */
2067#if defined(_MSC_VER) && _MSC_VER >= 1400
2068 switch (sig) {
2069 /* Only these signals are valid */
2070 case SIGINT:
2071 case SIGILL:
2072 case SIGFPE:
2073 case SIGSEGV:
2074 case SIGTERM:
2075 case SIGBREAK:
2076 case SIGABRT:
2077 break;
2078 /* Don't call signal() with other values or it will assert */
2079 default:
2080 return SIG_ERR;
2081 }
2082#endif /* _MSC_VER && _MSC_VER >= 1400 */
2083 handler = signal(sig, SIG_IGN);
2084 if (handler != SIG_ERR)
2085 signal(sig, handler);
2086 return handler;
2087#endif
2088}
2089
2090/*
2091 * All of the code in this function must only use async-signal-safe functions,
2092 * listed at `man 7 signal` or
2093 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2094 */
2095PyOS_sighandler_t
2096PyOS_setsig(int sig, PyOS_sighandler_t handler)
2097{
2098#ifdef HAVE_SIGACTION
2099 /* Some code in Modules/signalmodule.c depends on sigaction() being
2100 * used here if HAVE_SIGACTION is defined. Fix that if this code
2101 * changes to invalidate that assumption.
2102 */
2103 struct sigaction context, ocontext;
2104 context.sa_handler = handler;
2105 sigemptyset(&context.sa_mask);
2106 context.sa_flags = 0;
2107 if (sigaction(sig, &context, &ocontext) == -1)
2108 return SIG_ERR;
2109 return ocontext.sa_handler;
2110#else
2111 PyOS_sighandler_t oldhandler;
2112 oldhandler = signal(sig, handler);
2113#ifdef HAVE_SIGINTERRUPT
2114 siginterrupt(sig, 1);
2115#endif
2116 return oldhandler;
2117#endif
2118}
2119
2120#ifdef __cplusplus
2121}
2122#endif