Coverage Report

Created: 2025-07-11 06:59

/src/Python-3.8.3/Python/pylifecycle.c
Line
Count
Source (jump to first uncovered line)
1
/* 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> */
7
#include "pycore_ceval.h"
8
#include "pycore_context.h"
9
#include "pycore_initconfig.h"
10
#include "pycore_fileutils.h"
11
#include "pycore_hamt.h"
12
#include "pycore_pathconfig.h"
13
#include "pycore_pylifecycle.h"
14
#include "pycore_pymem.h"
15
#include "pycore_pystate.h"
16
#include "pycore_traceback.h"
17
#include "grammar.h"
18
#include "node.h"
19
#include "token.h"
20
#include "parsetok.h"
21
#include "errcode.h"
22
#include "code.h"
23
#include "symtable.h"
24
#include "ast.h"
25
#include "marshal.h"
26
#include "osdefs.h"
27
#include <locale.h>
28
29
#ifdef HAVE_SIGNAL_H
30
#include <signal.h>
31
#endif
32
33
#ifdef MS_WINDOWS
34
#include "malloc.h" /* for alloca */
35
#endif
36
37
#ifdef HAVE_LANGINFO_H
38
#include <langinfo.h>
39
#endif
40
41
#ifdef MS_WINDOWS
42
#undef BYTE
43
#include "windows.h"
44
45
extern PyTypeObject PyWindowsConsoleIO_Type;
46
#define PyWindowsConsoleIO_Check(op) (PyObject_TypeCheck((op), &PyWindowsConsoleIO_Type))
47
#endif
48
49
_Py_IDENTIFIER(flush);
50
_Py_IDENTIFIER(name);
51
_Py_IDENTIFIER(stdin);
52
_Py_IDENTIFIER(stdout);
53
_Py_IDENTIFIER(stderr);
54
_Py_IDENTIFIER(threading);
55
56
#ifdef __cplusplus
57
extern "C" {
58
#endif
59
60
extern grammar _PyParser_Grammar; /* From graminit.c */
61
62
/* Forward */
63
static PyStatus add_main_module(PyInterpreterState *interp);
64
static PyStatus init_import_size(void);
65
static PyStatus init_sys_streams(PyInterpreterState *interp);
66
static PyStatus init_signals(void);
67
static void call_py_exitfuncs(PyInterpreterState *);
68
static void wait_for_thread_shutdown(void);
69
static void call_ll_exitfuncs(_PyRuntimeState *runtime);
70
71
int _Py_UnhandledKeyboardInterrupt = 0;
72
_PyRuntimeState _PyRuntime = _PyRuntimeState_INIT;
73
static int runtime_initialized = 0;
74
75
PyStatus
76
_PyRuntime_Initialize(void)
77
700
{
78
    /* XXX We only initialize once in the process, which aligns with
79
       the static initialization of the former globals now found in
80
       _PyRuntime.  However, _PyRuntime *should* be initialized with
81
       every Py_Initialize() call, but doing so breaks the runtime.
82
       This is because the runtime state is not properly finalized
83
       currently. */
84
700
    if (runtime_initialized) {
85
686
        return _PyStatus_OK();
86
686
    }
87
14
    runtime_initialized = 1;
88
89
14
    return _PyRuntimeState_Init(&_PyRuntime);
90
700
}
91
92
void
93
_PyRuntime_Finalize(void)
94
0
{
95
0
    _PyRuntimeState_Fini(&_PyRuntime);
96
0
    runtime_initialized = 0;
97
0
}
98
99
int
100
_Py_IsFinalizing(void)
101
0
{
102
0
    return _PyRuntime.finalizing != NULL;
103
0
}
104
105
/* Hack to force loading of object files */
106
int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
107
    PyOS_mystrnicmp; /* Python/pystrcmp.o */
108
109
/* PyModule_GetWarningsModule is no longer necessary as of 2.6
110
since _warnings is builtin.  This API should not be used. */
111
PyObject *
112
PyModule_GetWarningsModule(void)
113
0
{
114
0
    return PyImport_ImportModule("warnings");
115
0
}
116
117
118
/* APIs to access the initialization flags
119
 *
120
 * Can be called prior to Py_Initialize.
121
 */
122
123
int
124
_Py_IsCoreInitialized(void)
125
0
{
126
0
    return _PyRuntime.core_initialized;
127
0
}
128
129
int
130
Py_IsInitialized(void)
131
0
{
132
0
    return _PyRuntime.initialized;
133
0
}
134
135
136
/* Global initializations.  Can be undone by Py_FinalizeEx().  Don't
137
   call this twice without an intervening Py_FinalizeEx() call.  When
138
   initializations fail, a fatal error is issued and the function does
139
   not return.  On return, the first thread and interpreter state have
140
   been created.
141
142
   Locking: you must hold the interpreter lock while calling this.
143
   (If the lock has not yet been initialized, that's equivalent to
144
   having the lock, but you cannot use multiple threads.)
145
146
*/
147
148
static PyStatus
149
init_importlib(PyInterpreterState *interp, PyObject *sysmod)
150
14
{
151
14
    PyObject *importlib;
152
14
    PyObject *impmod;
153
14
    PyObject *value;
154
14
    int verbose = interp->config.verbose;
155
156
    /* Import _importlib through its frozen version, _frozen_importlib. */
157
14
    if (PyImport_ImportFrozenModule("_frozen_importlib") <= 0) {
158
0
        return _PyStatus_ERR("can't import _frozen_importlib");
159
0
    }
160
14
    else if (verbose) {
161
0
        PySys_FormatStderr("import _frozen_importlib # frozen\n");
162
0
    }
163
14
    importlib = PyImport_AddModule("_frozen_importlib");
164
14
    if (importlib == NULL) {
165
0
        return _PyStatus_ERR("couldn't get _frozen_importlib from sys.modules");
166
0
    }
167
14
    interp->importlib = importlib;
168
14
    Py_INCREF(interp->importlib);
169
170
14
    interp->import_func = PyDict_GetItemString(interp->builtins, "__import__");
171
14
    if (interp->import_func == NULL)
172
0
        return _PyStatus_ERR("__import__ not found");
173
14
    Py_INCREF(interp->import_func);
174
175
    /* Import the _imp module */
176
14
    impmod = PyInit__imp();
177
14
    if (impmod == NULL) {
178
0
        return _PyStatus_ERR("can't import _imp");
179
0
    }
180
14
    else if (verbose) {
181
0
        PySys_FormatStderr("import _imp # builtin\n");
182
0
    }
183
14
    if (_PyImport_SetModuleString("_imp", impmod) < 0) {
184
0
        return _PyStatus_ERR("can't save _imp to sys.modules");
185
0
    }
186
187
    /* Install importlib as the implementation of import */
188
14
    value = PyObject_CallMethod(importlib, "_install", "OO", sysmod, impmod);
189
14
    if (value == NULL) {
190
0
        PyErr_Print();
191
0
        return _PyStatus_ERR("importlib install failed");
192
0
    }
193
14
    Py_DECREF(value);
194
14
    Py_DECREF(impmod);
195
196
14
    return _PyStatus_OK();
197
14
}
198
199
static PyStatus
200
init_importlib_external(PyInterpreterState *interp)
201
14
{
202
14
    PyObject *value;
203
14
    value = PyObject_CallMethod(interp->importlib,
204
14
                                "_install_external_importers", "");
205
14
    if (value == NULL) {
206
0
        PyErr_Print();
207
0
        return _PyStatus_ERR("external importer setup failed");
208
0
    }
209
14
    Py_DECREF(value);
210
14
    return _PyImportZip_Init(interp);
211
14
}
212
213
/* Helper functions to better handle the legacy C locale
214
 *
215
 * The legacy C locale assumes ASCII as the default text encoding, which
216
 * causes problems not only for the CPython runtime, but also other
217
 * components like GNU readline.
218
 *
219
 * Accordingly, when the CLI detects it, it attempts to coerce it to a
220
 * more capable UTF-8 based alternative as follows:
221
 *
222
 *     if (_Py_LegacyLocaleDetected()) {
223
 *         _Py_CoerceLegacyLocale();
224
 *     }
225
 *
226
 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
227
 *
228
 * Locale coercion also impacts the default error handler for the standard
229
 * streams: while the usual default is "strict", the default for the legacy
230
 * C locale and for any of the coercion target locales is "surrogateescape".
231
 */
232
233
int
234
_Py_LegacyLocaleDetected(int warn)
235
0
{
236
0
#ifndef MS_WINDOWS
237
0
    if (!warn) {
238
0
        const char *locale_override = getenv("LC_ALL");
239
0
        if (locale_override != NULL && *locale_override != '\0') {
240
            /* Don't coerce C locale if the LC_ALL environment variable
241
               is set */
242
0
            return 0;
243
0
        }
244
0
    }
245
246
    /* On non-Windows systems, the C locale is considered a legacy locale */
247
    /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
248
     *                 the POSIX locale as a simple alias for the C locale, so
249
     *                 we may also want to check for that explicitly.
250
     */
251
0
    const char *ctype_loc = setlocale(LC_CTYPE, NULL);
252
0
    return ctype_loc != NULL && strcmp(ctype_loc, "C") == 0;
253
#else
254
    /* Windows uses code pages instead of locales, so no locale is legacy */
255
    return 0;
256
#endif
257
0
}
258
259
static const char *_C_LOCALE_WARNING =
260
    "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
261
    "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
262
    "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
263
    "locales is recommended.\n";
264
265
static void
266
emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
267
14
{
268
14
    const PyPreConfig *preconfig = &runtime->preconfig;
269
14
    if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
270
0
        PySys_FormatStderr("%s", _C_LOCALE_WARNING);
271
0
    }
272
14
}
273
274
typedef struct _CandidateLocale {
275
    const char *locale_name; /* The locale to try as a coercion target */
276
} _LocaleCoercionTarget;
277
278
static _LocaleCoercionTarget _TARGET_LOCALES[] = {
279
    {"C.UTF-8"},
280
    {"C.utf8"},
281
    {"UTF-8"},
282
    {NULL}
283
};
284
285
286
int
287
_Py_IsLocaleCoercionTarget(const char *ctype_loc)
288
0
{
289
0
    const _LocaleCoercionTarget *target = NULL;
290
0
    for (target = _TARGET_LOCALES; target->locale_name; target++) {
291
0
        if (strcmp(ctype_loc, target->locale_name) == 0) {
292
0
            return 1;
293
0
        }
294
0
    }
295
0
    return 0;
296
0
}
297
298
299
#ifdef PY_COERCE_C_LOCALE
300
static const char C_LOCALE_COERCION_WARNING[] =
301
    "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
302
    "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
303
304
static int
305
_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
306
0
{
307
0
    const char *newloc = target->locale_name;
308
309
    /* Reset locale back to currently configured defaults */
310
0
    _Py_SetLocaleFromEnv(LC_ALL);
311
312
    /* Set the relevant locale environment variable */
313
0
    if (setenv("LC_CTYPE", newloc, 1)) {
314
0
        fprintf(stderr,
315
0
                "Error setting LC_CTYPE, skipping C locale coercion\n");
316
0
        return 0;
317
0
    }
318
0
    if (warn) {
319
0
        fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
320
0
    }
321
322
    /* Reconfigure with the overridden environment variables */
323
0
    _Py_SetLocaleFromEnv(LC_ALL);
324
0
    return 1;
325
0
}
326
#endif
327
328
int
329
_Py_CoerceLegacyLocale(int warn)
330
0
{
331
0
    int coerced = 0;
332
0
#ifdef PY_COERCE_C_LOCALE
333
0
    char *oldloc = NULL;
334
335
0
    oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
336
0
    if (oldloc == NULL) {
337
0
        return coerced;
338
0
    }
339
340
0
    const char *locale_override = getenv("LC_ALL");
341
0
    if (locale_override == NULL || *locale_override == '\0') {
342
        /* LC_ALL is also not set (or is set to an empty string) */
343
0
        const _LocaleCoercionTarget *target = NULL;
344
0
        for (target = _TARGET_LOCALES; target->locale_name; target++) {
345
0
            const char *new_locale = setlocale(LC_CTYPE,
346
0
                                               target->locale_name);
347
0
            if (new_locale != NULL) {
348
0
#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
349
                /* Also ensure that nl_langinfo works in this locale */
350
0
                char *codeset = nl_langinfo(CODESET);
351
0
                if (!codeset || *codeset == '\0') {
352
                    /* CODESET is not set or empty, so skip coercion */
353
0
                    new_locale = NULL;
354
0
                    _Py_SetLocaleFromEnv(LC_CTYPE);
355
0
                    continue;
356
0
                }
357
0
#endif
358
                /* Successfully configured locale, so make it the default */
359
0
                coerced = _coerce_default_locale_settings(warn, target);
360
0
                goto done;
361
0
            }
362
0
        }
363
0
    }
364
    /* No C locale warning here, as Py_Initialize will emit one later */
365
366
0
    setlocale(LC_CTYPE, oldloc);
367
368
0
done:
369
0
    PyMem_RawFree(oldloc);
370
0
#endif
371
0
    return coerced;
372
0
}
373
374
/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
375
 * isolate the idiosyncrasies of different libc implementations. It reads the
376
 * appropriate environment variable and uses its value to select the locale for
377
 * 'category'. */
378
char *
379
_Py_SetLocaleFromEnv(int category)
380
28
{
381
28
    char *res;
382
#ifdef __ANDROID__
383
    const char *locale;
384
    const char **pvar;
385
#ifdef PY_COERCE_C_LOCALE
386
    const char *coerce_c_locale;
387
#endif
388
    const char *utf8_locale = "C.UTF-8";
389
    const char *env_var_set[] = {
390
        "LC_ALL",
391
        "LC_CTYPE",
392
        "LANG",
393
        NULL,
394
    };
395
396
    /* Android setlocale(category, "") doesn't check the environment variables
397
     * and incorrectly sets the "C" locale at API 24 and older APIs. We only
398
     * check the environment variables listed in env_var_set. */
399
    for (pvar=env_var_set; *pvar; pvar++) {
400
        locale = getenv(*pvar);
401
        if (locale != NULL && *locale != '\0') {
402
            if (strcmp(locale, utf8_locale) == 0 ||
403
                    strcmp(locale, "en_US.UTF-8") == 0) {
404
                return setlocale(category, utf8_locale);
405
            }
406
            return setlocale(category, "C");
407
        }
408
    }
409
410
    /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
411
     * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
412
     * Quote from POSIX section "8.2 Internationalization Variables":
413
     * "4. If the LANG environment variable is not set or is set to the empty
414
     * string, the implementation-defined default locale shall be used." */
415
416
#ifdef PY_COERCE_C_LOCALE
417
    coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
418
    if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
419
        /* Some other ported code may check the environment variables (e.g. in
420
         * extension modules), so we make sure that they match the locale
421
         * configuration */
422
        if (setenv("LC_CTYPE", utf8_locale, 1)) {
423
            fprintf(stderr, "Warning: failed setting the LC_CTYPE "
424
                            "environment variable to %s\n", utf8_locale);
425
        }
426
    }
427
#endif
428
    res = setlocale(category, utf8_locale);
429
#else /* !defined(__ANDROID__) */
430
28
    res = setlocale(category, "");
431
28
#endif
432
28
    _Py_ResetForceASCII();
433
28
    return res;
434
28
}
435
436
437
/* Global initializations.  Can be undone by Py_Finalize().  Don't
438
   call this twice without an intervening Py_Finalize() call.
439
440
   Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
441
   must have a corresponding call to Py_Finalize.
442
443
   Locking: you must hold the interpreter lock while calling these APIs.
444
   (If the lock has not yet been initialized, that's equivalent to
445
   having the lock, but you cannot use multiple threads.)
446
447
*/
448
449
static PyStatus
450
pyinit_core_reconfigure(_PyRuntimeState *runtime,
451
                        PyInterpreterState **interp_p,
452
                        const PyConfig *config)
453
0
{
454
0
    PyStatus status;
455
0
    PyThreadState *tstate = _PyThreadState_GET();
456
0
    if (!tstate) {
457
0
        return _PyStatus_ERR("failed to read thread state");
458
0
    }
459
460
0
    PyInterpreterState *interp = tstate->interp;
461
0
    if (interp == NULL) {
462
0
        return _PyStatus_ERR("can't make main interpreter");
463
0
    }
464
0
    *interp_p = interp;
465
466
0
    _PyConfig_Write(config, runtime);
467
468
0
    status = _PyConfig_Copy(&interp->config, config);
469
0
    if (_PyStatus_EXCEPTION(status)) {
470
0
        return status;
471
0
    }
472
0
    config = &interp->config;
473
474
0
    if (config->_install_importlib) {
475
0
        status = _PyConfig_WritePathConfig(config);
476
0
        if (_PyStatus_EXCEPTION(status)) {
477
0
            return status;
478
0
        }
479
0
    }
480
0
    return _PyStatus_OK();
481
0
}
482
483
484
static PyStatus
485
pycore_init_runtime(_PyRuntimeState *runtime,
486
                    const PyConfig *config)
487
14
{
488
14
    if (runtime->initialized) {
489
0
        return _PyStatus_ERR("main interpreter already initialized");
490
0
    }
491
492
14
    _PyConfig_Write(config, runtime);
493
494
    /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
495
     * threads behave a little more gracefully at interpreter shutdown.
496
     * We clobber it here so the new interpreter can start with a clean
497
     * slate.
498
     *
499
     * However, this may still lead to misbehaviour if there are daemon
500
     * threads still hanging around from a previous Py_Initialize/Finalize
501
     * pair :(
502
     */
503
14
    runtime->finalizing = NULL;
504
505
14
    PyStatus status = _Py_HashRandomization_Init(config);
506
14
    if (_PyStatus_EXCEPTION(status)) {
507
0
        return status;
508
0
    }
509
510
14
    status = _PyInterpreterState_Enable(runtime);
511
14
    if (_PyStatus_EXCEPTION(status)) {
512
0
        return status;
513
0
    }
514
14
    return _PyStatus_OK();
515
14
}
516
517
518
static PyStatus
519
pycore_create_interpreter(_PyRuntimeState *runtime,
520
                          const PyConfig *config,
521
                          PyInterpreterState **interp_p)
522
14
{
523
14
    PyInterpreterState *interp = PyInterpreterState_New();
524
14
    if (interp == NULL) {
525
0
        return _PyStatus_ERR("can't make main interpreter");
526
0
    }
527
14
    *interp_p = interp;
528
529
14
    PyStatus status = _PyConfig_Copy(&interp->config, config);
530
14
    if (_PyStatus_EXCEPTION(status)) {
531
0
        return status;
532
0
    }
533
14
    config = &interp->config;
534
535
14
    PyThreadState *tstate = PyThreadState_New(interp);
536
14
    if (tstate == NULL)
537
0
        return _PyStatus_ERR("can't make first thread");
538
14
    (void) PyThreadState_Swap(tstate);
539
540
    /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because
541
       destroying the GIL might fail when it is being referenced from
542
       another running thread (see issue #9901).
543
       Instead we destroy the previously created GIL here, which ensures
544
       that we can call Py_Initialize / Py_FinalizeEx multiple times. */
545
14
    _PyEval_FiniThreads(&runtime->ceval);
546
547
    /* Auto-thread-state API */
548
14
    _PyGILState_Init(runtime, interp, tstate);
549
550
    /* Create the GIL */
551
14
    PyEval_InitThreads();
552
553
14
    return _PyStatus_OK();
554
14
}
555
556
557
static PyStatus
558
pycore_init_types(void)
559
14
{
560
14
    PyStatus status = _PyTypes_Init();
561
14
    if (_PyStatus_EXCEPTION(status)) {
562
0
        return status;
563
0
    }
564
565
14
    status = _PyUnicode_Init();
566
14
    if (_PyStatus_EXCEPTION(status)) {
567
0
        return status;
568
0
    }
569
570
14
    if (_PyStructSequence_Init() < 0) {
571
0
        return _PyStatus_ERR("can't initialize structseq");
572
0
    }
573
574
14
    if (!_PyLong_Init()) {
575
0
        return _PyStatus_ERR("can't init longs");
576
0
    }
577
578
14
    status = _PyExc_Init();
579
14
    if (_PyStatus_EXCEPTION(status)) {
580
0
        return status;
581
0
    }
582
583
14
    if (!_PyFloat_Init()) {
584
0
        return _PyStatus_ERR("can't init float");
585
0
    }
586
587
14
    if (!_PyContext_Init()) {
588
0
        return _PyStatus_ERR("can't init context");
589
0
    }
590
591
14
    status = _PyErr_Init();
592
14
    if (_PyStatus_EXCEPTION(status)) {
593
0
        return status;
594
0
    }
595
596
14
    return _PyStatus_OK();
597
14
}
598
599
600
static PyStatus
601
pycore_init_builtins(PyInterpreterState *interp)
602
14
{
603
14
    PyObject *bimod = _PyBuiltin_Init();
604
14
    if (bimod == NULL) {
605
0
        return _PyStatus_ERR("can't initialize builtins modules");
606
0
    }
607
14
    _PyImport_FixupBuiltin(bimod, "builtins", interp->modules);
608
609
14
    interp->builtins = PyModule_GetDict(bimod);
610
14
    if (interp->builtins == NULL) {
611
0
        return _PyStatus_ERR("can't initialize builtins dict");
612
0
    }
613
14
    Py_INCREF(interp->builtins);
614
615
14
    PyStatus status = _PyBuiltins_AddExceptions(bimod);
616
14
    if (_PyStatus_EXCEPTION(status)) {
617
0
        return status;
618
0
    }
619
14
    return _PyStatus_OK();
620
14
}
621
622
623
static PyStatus
624
pycore_init_import_warnings(PyInterpreterState *interp, PyObject *sysmod)
625
14
{
626
14
    const PyConfig *config = &interp->config;
627
628
14
    PyStatus status = _PyImport_Init(interp);
629
14
    if (_PyStatus_EXCEPTION(status)) {
630
0
        return status;
631
0
    }
632
633
14
    status = _PyImportHooks_Init();
634
14
    if (_PyStatus_EXCEPTION(status)) {
635
0
        return status;
636
0
    }
637
638
    /* Initialize _warnings. */
639
14
    if (_PyWarnings_Init() == NULL) {
640
0
        return _PyStatus_ERR("can't initialize warnings");
641
0
    }
642
643
14
    if (config->_install_importlib) {
644
14
        status = _PyConfig_WritePathConfig(config);
645
14
        if (_PyStatus_EXCEPTION(status)) {
646
0
            return status;
647
0
        }
648
14
    }
649
650
    /* This call sets up builtin and frozen import support */
651
14
    if (config->_install_importlib) {
652
14
        status = init_importlib(interp, sysmod);
653
14
        if (_PyStatus_EXCEPTION(status)) {
654
0
            return status;
655
0
        }
656
14
    }
657
14
    return _PyStatus_OK();
658
14
}
659
660
661
static PyStatus
662
pyinit_config(_PyRuntimeState *runtime,
663
              PyInterpreterState **interp_p,
664
              const PyConfig *config)
665
14
{
666
14
    PyInterpreterState *interp;
667
668
14
    _PyConfig_Write(config, runtime);
669
670
14
    PyStatus status = pycore_init_runtime(runtime, config);
671
14
    if (_PyStatus_EXCEPTION(status)) {
672
0
        return status;
673
0
    }
674
675
14
    status = pycore_create_interpreter(runtime, config, &interp);
676
14
    if (_PyStatus_EXCEPTION(status)) {
677
0
        return status;
678
0
    }
679
14
    config = &interp->config;
680
14
    *interp_p = interp;
681
682
14
    status = pycore_init_types();
683
14
    if (_PyStatus_EXCEPTION(status)) {
684
0
        return status;
685
0
    }
686
687
14
    PyObject *sysmod;
688
14
    status = _PySys_Create(runtime, interp, &sysmod);
689
14
    if (_PyStatus_EXCEPTION(status)) {
690
0
        return status;
691
0
    }
692
693
14
    status = pycore_init_builtins(interp);
694
14
    if (_PyStatus_EXCEPTION(status)) {
695
0
        return status;
696
0
    }
697
698
14
    status = pycore_init_import_warnings(interp, sysmod);
699
14
    if (_PyStatus_EXCEPTION(status)) {
700
0
        return status;
701
0
    }
702
703
    /* Only when we get here is the runtime core fully initialized */
704
14
    runtime->core_initialized = 1;
705
14
    return _PyStatus_OK();
706
14
}
707
708
709
PyStatus
710
_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
711
14
{
712
14
    PyStatus status;
713
714
14
    if (src_config == NULL) {
715
0
        return _PyStatus_ERR("preinitialization config is NULL");
716
0
    }
717
718
14
    status = _PyRuntime_Initialize();
719
14
    if (_PyStatus_EXCEPTION(status)) {
720
0
        return status;
721
0
    }
722
14
    _PyRuntimeState *runtime = &_PyRuntime;
723
724
14
    if (runtime->preinitialized) {
725
        /* If it's already configured: ignored the new configuration */
726
0
        return _PyStatus_OK();
727
0
    }
728
729
    /* Note: preinitialized remains 1 on error, it is only set to 0
730
       at exit on success. */
731
14
    runtime->preinitializing = 1;
732
733
14
    PyPreConfig config;
734
735
14
    status = _PyPreConfig_InitFromPreConfig(&config, src_config);
736
14
    if (_PyStatus_EXCEPTION(status)) {
737
0
        return status;
738
0
    }
739
740
14
    status = _PyPreConfig_Read(&config, args);
741
14
    if (_PyStatus_EXCEPTION(status)) {
742
0
        return status;
743
0
    }
744
745
14
    status = _PyPreConfig_Write(&config);
746
14
    if (_PyStatus_EXCEPTION(status)) {
747
0
        return status;
748
0
    }
749
750
14
    runtime->preinitializing = 0;
751
14
    runtime->preinitialized = 1;
752
14
    return _PyStatus_OK();
753
14
}
754
755
756
PyStatus
757
Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
758
0
{
759
0
    _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
760
0
    return _Py_PreInitializeFromPyArgv(src_config, &args);
761
0
}
762
763
764
PyStatus
765
Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
766
0
{
767
0
    _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
768
0
    return _Py_PreInitializeFromPyArgv(src_config, &args);
769
0
}
770
771
772
PyStatus
773
Py_PreInitialize(const PyPreConfig *src_config)
774
14
{
775
14
    return _Py_PreInitializeFromPyArgv(src_config, NULL);
776
14
}
777
778
779
PyStatus
780
_Py_PreInitializeFromConfig(const PyConfig *config,
781
                            const _PyArgv *args)
782
644
{
783
644
    assert(config != NULL);
784
785
644
    PyStatus status = _PyRuntime_Initialize();
786
644
    if (_PyStatus_EXCEPTION(status)) {
787
0
        return status;
788
0
    }
789
644
    _PyRuntimeState *runtime = &_PyRuntime;
790
791
644
    if (runtime->preinitialized) {
792
        /* Already initialized: do nothing */
793
630
        return _PyStatus_OK();
794
630
    }
795
796
14
    PyPreConfig preconfig;
797
798
14
    _PyPreConfig_InitFromConfig(&preconfig, config);
799
800
14
    if (!config->parse_argv) {
801
14
        return Py_PreInitialize(&preconfig);
802
14
    }
803
0
    else if (args == NULL) {
804
0
        _PyArgv config_args = {
805
0
            .use_bytes_argv = 0,
806
0
            .argc = config->argv.length,
807
0
            .wchar_argv = config->argv.items};
808
0
        return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
809
0
    }
810
0
    else {
811
0
        return _Py_PreInitializeFromPyArgv(&preconfig, args);
812
0
    }
813
14
}
814
815
816
/* Begin interpreter initialization
817
 *
818
 * On return, the first thread and interpreter state have been created,
819
 * but the compiler, signal handling, multithreading and
820
 * multiple interpreter support, and codec infrastructure are not yet
821
 * available.
822
 *
823
 * The import system will support builtin and frozen modules only.
824
 * The only supported io is writing to sys.stderr
825
 *
826
 * If any operation invoked by this function fails, a fatal error is
827
 * issued and the function does not return.
828
 *
829
 * Any code invoked from this function should *not* assume it has access
830
 * to the Python C API (unless the API is explicitly listed as being
831
 * safe to call without calling Py_Initialize first)
832
 */
833
static PyStatus
834
pyinit_core(_PyRuntimeState *runtime,
835
            const PyConfig *src_config,
836
            PyInterpreterState **interp_p)
837
14
{
838
14
    PyStatus status;
839
840
14
    status = _Py_PreInitializeFromConfig(src_config, NULL);
841
14
    if (_PyStatus_EXCEPTION(status)) {
842
0
        return status;
843
0
    }
844
845
14
    PyConfig config;
846
14
    _PyConfig_InitCompatConfig(&config);
847
848
14
    status = _PyConfig_Copy(&config, src_config);
849
14
    if (_PyStatus_EXCEPTION(status)) {
850
0
        goto done;
851
0
    }
852
853
14
    status = PyConfig_Read(&config);
854
14
    if (_PyStatus_EXCEPTION(status)) {
855
0
        goto done;
856
0
    }
857
858
14
    if (!runtime->core_initialized) {
859
14
        status = pyinit_config(runtime, interp_p, &config);
860
14
    }
861
0
    else {
862
0
        status = pyinit_core_reconfigure(runtime, interp_p, &config);
863
0
    }
864
14
    if (_PyStatus_EXCEPTION(status)) {
865
0
        goto done;
866
0
    }
867
868
14
done:
869
14
    PyConfig_Clear(&config);
870
14
    return status;
871
14
}
872
873
874
/* Py_Initialize() has already been called: update the main interpreter
875
   configuration. Example of bpo-34008: Py_Main() called after
876
   Py_Initialize(). */
877
static PyStatus
878
_Py_ReconfigureMainInterpreter(PyInterpreterState *interp)
879
0
{
880
0
    PyConfig *config = &interp->config;
881
882
0
    PyObject *argv = _PyWideStringList_AsList(&config->argv);
883
0
    if (argv == NULL) {
884
0
        return _PyStatus_NO_MEMORY(); \
885
0
    }
886
887
0
    int res = PyDict_SetItemString(interp->sysdict, "argv", argv);
888
0
    Py_DECREF(argv);
889
0
    if (res < 0) {
890
0
        return _PyStatus_ERR("fail to set sys.argv");
891
0
    }
892
0
    return _PyStatus_OK();
893
0
}
894
895
/* Update interpreter state based on supplied configuration settings
896
 *
897
 * After calling this function, most of the restrictions on the interpreter
898
 * are lifted. The only remaining incomplete settings are those related
899
 * to the main module (sys.argv[0], __main__ metadata)
900
 *
901
 * Calling this when the interpreter is not initializing, is already
902
 * initialized or without a valid current thread state is a fatal error.
903
 * Other errors should be reported as normal Python exceptions with a
904
 * non-zero return code.
905
 */
906
static PyStatus
907
pyinit_main(_PyRuntimeState *runtime, PyInterpreterState *interp)
908
14
{
909
14
    if (!runtime->core_initialized) {
910
0
        return _PyStatus_ERR("runtime core not initialized");
911
0
    }
912
913
    /* Configure the main interpreter */
914
14
    PyConfig *config = &interp->config;
915
916
14
    if (runtime->initialized) {
917
0
        return _Py_ReconfigureMainInterpreter(interp);
918
0
    }
919
920
14
    if (!config->_install_importlib) {
921
        /* Special mode for freeze_importlib: run with no import system
922
         *
923
         * This means anything which needs support from extension modules
924
         * or pure Python code in the standard library won't work.
925
         */
926
0
        runtime->initialized = 1;
927
0
        return _PyStatus_OK();
928
0
    }
929
930
14
    if (_PyTime_Init() < 0) {
931
0
        return _PyStatus_ERR("can't initialize time");
932
0
    }
933
934
14
    if (_PySys_InitMain(runtime, interp) < 0) {
935
0
        return _PyStatus_ERR("can't finish initializing sys");
936
0
    }
937
938
14
    PyStatus status = init_importlib_external(interp);
939
14
    if (_PyStatus_EXCEPTION(status)) {
940
0
        return status;
941
0
    }
942
943
    /* initialize the faulthandler module */
944
14
    status = _PyFaulthandler_Init(config->faulthandler);
945
14
    if (_PyStatus_EXCEPTION(status)) {
946
0
        return status;
947
0
    }
948
949
14
    PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
950
14
    status = _PyUnicode_InitEncodings(tstate);
951
14
    if (_PyStatus_EXCEPTION(status)) {
952
0
        return status;
953
0
    }
954
955
14
    if (config->install_signal_handlers) {
956
0
        status = init_signals();
957
0
        if (_PyStatus_EXCEPTION(status)) {
958
0
            return status;
959
0
        }
960
0
    }
961
962
14
    if (_PyTraceMalloc_Init(config->tracemalloc) < 0) {
963
0
        return _PyStatus_ERR("can't initialize tracemalloc");
964
0
    }
965
966
14
    status = add_main_module(interp);
967
14
    if (_PyStatus_EXCEPTION(status)) {
968
0
        return status;
969
0
    }
970
971
14
    status = init_sys_streams(interp);
972
14
    if (_PyStatus_EXCEPTION(status)) {
973
0
        return status;
974
0
    }
975
976
    /* Initialize warnings. */
977
14
    PyObject *warnoptions = PySys_GetObject("warnoptions");
978
14
    if (warnoptions != NULL && PyList_Size(warnoptions) > 0)
979
0
    {
980
0
        PyObject *warnings_module = PyImport_ImportModule("warnings");
981
0
        if (warnings_module == NULL) {
982
0
            fprintf(stderr, "'import warnings' failed; traceback:\n");
983
0
            PyErr_Print();
984
0
        }
985
0
        Py_XDECREF(warnings_module);
986
0
    }
987
988
14
    runtime->initialized = 1;
989
990
14
    if (config->site_import) {
991
14
        status = init_import_size(); /* Module site */
992
14
        if (_PyStatus_EXCEPTION(status)) {
993
0
            return status;
994
0
        }
995
14
    }
996
997
14
#ifndef MS_WINDOWS
998
14
    emit_stderr_warning_for_legacy_locale(runtime);
999
14
#endif
1000
1001
14
    return _PyStatus_OK();
1002
14
}
1003
1004
1005
PyStatus
1006
_Py_InitializeMain(void)
1007
0
{
1008
0
    PyStatus status = _PyRuntime_Initialize();
1009
0
    if (_PyStatus_EXCEPTION(status)) {
1010
0
        return status;
1011
0
    }
1012
0
    _PyRuntimeState *runtime = &_PyRuntime;
1013
0
    PyInterpreterState *interp = _PyRuntimeState_GetThreadState(runtime)->interp;
1014
1015
0
    return pyinit_main(runtime, interp);
1016
0
}
1017
1018
1019
PyStatus
1020
Py_InitializeFromConfig(const PyConfig *config)
1021
14
{
1022
14
    if (config == NULL) {
1023
0
        return _PyStatus_ERR("initialization config is NULL");
1024
0
    }
1025
1026
14
    PyStatus status;
1027
1028
14
    status = _PyRuntime_Initialize();
1029
14
    if (_PyStatus_EXCEPTION(status)) {
1030
0
        return status;
1031
0
    }
1032
14
    _PyRuntimeState *runtime = &_PyRuntime;
1033
1034
14
    PyInterpreterState *interp = NULL;
1035
14
    status = pyinit_core(runtime, config, &interp);
1036
14
    if (_PyStatus_EXCEPTION(status)) {
1037
0
        return status;
1038
0
    }
1039
14
    config = &interp->config;
1040
1041
14
    if (config->_init_main) {
1042
14
        status = pyinit_main(runtime, interp);
1043
14
        if (_PyStatus_EXCEPTION(status)) {
1044
0
            return status;
1045
0
        }
1046
14
    }
1047
1048
14
    return _PyStatus_OK();
1049
14
}
1050
1051
1052
void
1053
Py_InitializeEx(int install_sigs)
1054
14
{
1055
14
    PyStatus status;
1056
1057
14
    status = _PyRuntime_Initialize();
1058
14
    if (_PyStatus_EXCEPTION(status)) {
1059
0
        Py_ExitStatusException(status);
1060
0
    }
1061
14
    _PyRuntimeState *runtime = &_PyRuntime;
1062
1063
14
    if (runtime->initialized) {
1064
        /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1065
0
        return;
1066
0
    }
1067
1068
14
    PyConfig config;
1069
14
    _PyConfig_InitCompatConfig(&config);
1070
1071
14
    config.install_signal_handlers = install_sigs;
1072
1073
14
    status = Py_InitializeFromConfig(&config);
1074
14
    if (_PyStatus_EXCEPTION(status)) {
1075
0
        Py_ExitStatusException(status);
1076
0
    }
1077
14
}
1078
1079
void
1080
Py_Initialize(void)
1081
0
{
1082
0
    Py_InitializeEx(1);
1083
0
}
1084
1085
1086
#ifdef COUNT_ALLOCS
1087
extern void _Py_dump_counts(FILE*);
1088
#endif
1089
1090
/* Flush stdout and stderr */
1091
1092
static int
1093
file_is_closed(PyObject *fobj)
1094
0
{
1095
0
    int r;
1096
0
    PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1097
0
    if (tmp == NULL) {
1098
0
        PyErr_Clear();
1099
0
        return 0;
1100
0
    }
1101
0
    r = PyObject_IsTrue(tmp);
1102
0
    Py_DECREF(tmp);
1103
0
    if (r < 0)
1104
0
        PyErr_Clear();
1105
0
    return r > 0;
1106
0
}
1107
1108
static int
1109
flush_std_files(void)
1110
0
{
1111
0
    PyObject *fout = _PySys_GetObjectId(&PyId_stdout);
1112
0
    PyObject *ferr = _PySys_GetObjectId(&PyId_stderr);
1113
0
    PyObject *tmp;
1114
0
    int status = 0;
1115
1116
0
    if (fout != NULL && fout != Py_None && !file_is_closed(fout)) {
1117
0
        tmp = _PyObject_CallMethodId(fout, &PyId_flush, NULL);
1118
0
        if (tmp == NULL) {
1119
0
            PyErr_WriteUnraisable(fout);
1120
0
            status = -1;
1121
0
        }
1122
0
        else
1123
0
            Py_DECREF(tmp);
1124
0
    }
1125
1126
0
    if (ferr != NULL && ferr != Py_None && !file_is_closed(ferr)) {
1127
0
        tmp = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
1128
0
        if (tmp == NULL) {
1129
0
            PyErr_Clear();
1130
0
            status = -1;
1131
0
        }
1132
0
        else
1133
0
            Py_DECREF(tmp);
1134
0
    }
1135
1136
0
    return status;
1137
0
}
1138
1139
/* Undo the effect of Py_Initialize().
1140
1141
   Beware: if multiple interpreter and/or thread states exist, these
1142
   are not wiped out; only the current thread and interpreter state
1143
   are deleted.  But since everything else is deleted, those other
1144
   interpreter and thread states should no longer be used.
1145
1146
   (XXX We should do better, e.g. wipe out all interpreters and
1147
   threads.)
1148
1149
   Locking: as above.
1150
1151
*/
1152
1153
int
1154
Py_FinalizeEx(void)
1155
0
{
1156
0
    int status = 0;
1157
1158
0
    _PyRuntimeState *runtime = &_PyRuntime;
1159
0
    if (!runtime->initialized) {
1160
0
        return status;
1161
0
    }
1162
1163
    // Wrap up existing "threading"-module-created, non-daemon threads.
1164
0
    wait_for_thread_shutdown();
1165
1166
    // Make any remaining pending calls.
1167
0
    _Py_FinishPendingCalls(runtime);
1168
1169
    /* Get current thread state and interpreter pointer */
1170
0
    PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
1171
0
    PyInterpreterState *interp = tstate->interp;
1172
1173
    /* The interpreter is still entirely intact at this point, and the
1174
     * exit funcs may be relying on that.  In particular, if some thread
1175
     * or exit func is still waiting to do an import, the import machinery
1176
     * expects Py_IsInitialized() to return true.  So don't say the
1177
     * runtime is uninitialized until after the exit funcs have run.
1178
     * Note that Threading.py uses an exit func to do a join on all the
1179
     * threads created thru it, so this also protects pending imports in
1180
     * the threads created via Threading.
1181
     */
1182
1183
0
    call_py_exitfuncs(interp);
1184
1185
    /* Copy the core config, PyInterpreterState_Delete() free
1186
       the core config memory */
1187
#ifdef Py_REF_DEBUG
1188
    int show_ref_count = interp->config.show_ref_count;
1189
#endif
1190
#ifdef Py_TRACE_REFS
1191
    int dump_refs = interp->config.dump_refs;
1192
#endif
1193
0
#ifdef WITH_PYMALLOC
1194
0
    int malloc_stats = interp->config.malloc_stats;
1195
0
#endif
1196
1197
    /* Remaining threads (e.g. daemon threads) will automatically exit
1198
       after taking the GIL (in PyEval_RestoreThread()). */
1199
0
    runtime->finalizing = tstate;
1200
0
    runtime->initialized = 0;
1201
0
    runtime->core_initialized = 0;
1202
1203
    /* Flush sys.stdout and sys.stderr */
1204
0
    if (flush_std_files() < 0) {
1205
0
        status = -1;
1206
0
    }
1207
1208
    /* Disable signal handling */
1209
0
    PyOS_FiniInterrupts();
1210
1211
    /* Collect garbage.  This may call finalizers; it's nice to call these
1212
     * before all modules are destroyed.
1213
     * XXX If a __del__ or weakref callback is triggered here, and tries to
1214
     * XXX import a module, bad things can happen, because Python no
1215
     * XXX longer believes it's initialized.
1216
     * XXX     Fatal Python error: Interpreter not initialized (version mismatch?)
1217
     * XXX is easy to provoke that way.  I've also seen, e.g.,
1218
     * XXX     Exception exceptions.ImportError: 'No module named sha'
1219
     * XXX         in <function callback at 0x008F5718> ignored
1220
     * XXX but I'm unclear on exactly how that one happens.  In any case,
1221
     * XXX I haven't seen a real-life report of either of these.
1222
     */
1223
0
    _PyGC_CollectIfEnabled();
1224
#ifdef COUNT_ALLOCS
1225
    /* With COUNT_ALLOCS, it helps to run GC multiple times:
1226
       each collection might release some types from the type
1227
       list, so they become garbage. */
1228
    while (_PyGC_CollectIfEnabled() > 0)
1229
        /* nothing */;
1230
#endif
1231
1232
    /* Clear all loghooks */
1233
    /* We want minimal exposure of this function, so define the extern
1234
     * here. The linker should discover the correct function without
1235
     * exporting a symbol. */
1236
0
    extern void _PySys_ClearAuditHooks(void);
1237
0
    _PySys_ClearAuditHooks();
1238
1239
    /* Destroy all modules */
1240
0
    PyImport_Cleanup();
1241
1242
    /* Print debug stats if any */
1243
0
    _PyEval_Fini();
1244
1245
    /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
1246
0
    if (flush_std_files() < 0) {
1247
0
        status = -1;
1248
0
    }
1249
1250
    /* Collect final garbage.  This disposes of cycles created by
1251
     * class definitions, for example.
1252
     * XXX This is disabled because it caused too many problems.  If
1253
     * XXX a __del__ or weakref callback triggers here, Python code has
1254
     * XXX a hard time running, because even the sys module has been
1255
     * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
1256
     * XXX One symptom is a sequence of information-free messages
1257
     * XXX coming from threads (if a __del__ or callback is invoked,
1258
     * XXX other threads can execute too, and any exception they encounter
1259
     * XXX triggers a comedy of errors as subsystem after subsystem
1260
     * XXX fails to find what it *expects* to find in sys to help report
1261
     * XXX the exception and consequent unexpected failures).  I've also
1262
     * XXX seen segfaults then, after adding print statements to the
1263
     * XXX Python code getting called.
1264
     */
1265
#if 0
1266
    _PyGC_CollectIfEnabled();
1267
#endif
1268
1269
    /* Disable tracemalloc after all Python objects have been destroyed,
1270
       so it is possible to use tracemalloc in objects destructor. */
1271
0
    _PyTraceMalloc_Fini();
1272
1273
    /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
1274
0
    _PyImport_Fini();
1275
1276
    /* Cleanup typeobject.c's internal caches. */
1277
0
    _PyType_Fini();
1278
1279
    /* unload faulthandler module */
1280
0
    _PyFaulthandler_Fini();
1281
1282
    /* Debugging stuff */
1283
#ifdef COUNT_ALLOCS
1284
    _Py_dump_counts(stderr);
1285
#endif
1286
    /* dump hash stats */
1287
0
    _PyHash_Fini();
1288
1289
#ifdef Py_REF_DEBUG
1290
    if (show_ref_count) {
1291
        _PyDebug_PrintTotalRefs();
1292
    }
1293
#endif
1294
1295
#ifdef Py_TRACE_REFS
1296
    /* Display all objects still alive -- this can invoke arbitrary
1297
     * __repr__ overrides, so requires a mostly-intact interpreter.
1298
     * Alas, a lot of stuff may still be alive now that will be cleaned
1299
     * up later.
1300
     */
1301
    if (dump_refs) {
1302
        _Py_PrintReferences(stderr);
1303
    }
1304
#endif /* Py_TRACE_REFS */
1305
1306
    /* Clear interpreter state and all thread states. */
1307
0
    PyInterpreterState_Clear(interp);
1308
1309
    /* Now we decref the exception classes.  After this point nothing
1310
       can raise an exception.  That's okay, because each Fini() method
1311
       below has been checked to make sure no exceptions are ever
1312
       raised.
1313
    */
1314
1315
0
    _PyExc_Fini();
1316
1317
    /* Sundry finalizers */
1318
0
    PyMethod_Fini();
1319
0
    PyFrame_Fini();
1320
0
    PyCFunction_Fini();
1321
0
    PyTuple_Fini();
1322
0
    PyList_Fini();
1323
0
    PySet_Fini();
1324
0
    PyBytes_Fini();
1325
0
    PyLong_Fini();
1326
0
    PyFloat_Fini();
1327
0
    PyDict_Fini();
1328
0
    PySlice_Fini();
1329
0
    _PyGC_Fini(runtime);
1330
0
    _PyWarnings_Fini(interp);
1331
0
    _Py_HashRandomization_Fini();
1332
0
    _PyArg_Fini();
1333
0
    PyAsyncGen_Fini();
1334
0
    _PyContext_Fini();
1335
1336
    /* Cleanup Unicode implementation */
1337
0
    _PyUnicode_Fini();
1338
1339
0
    _Py_ClearFileSystemEncoding();
1340
1341
    /* XXX Still allocated:
1342
       - various static ad-hoc pointers to interned strings
1343
       - int and float free list blocks
1344
       - whatever various modules and libraries allocate
1345
    */
1346
1347
0
    PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
1348
1349
    /* Cleanup auto-thread-state */
1350
0
    _PyGILState_Fini(runtime);
1351
1352
    /* Delete current thread. After this, many C API calls become crashy. */
1353
0
    PyThreadState_Swap(NULL);
1354
1355
0
    PyInterpreterState_Delete(interp);
1356
1357
#ifdef Py_TRACE_REFS
1358
    /* Display addresses (& refcnts) of all objects still alive.
1359
     * An address can be used to find the repr of the object, printed
1360
     * above by _Py_PrintReferences.
1361
     */
1362
    if (dump_refs) {
1363
        _Py_PrintReferenceAddresses(stderr);
1364
    }
1365
#endif /* Py_TRACE_REFS */
1366
0
#ifdef WITH_PYMALLOC
1367
0
    if (malloc_stats) {
1368
0
        _PyObject_DebugMallocStats(stderr);
1369
0
    }
1370
0
#endif
1371
1372
0
    call_ll_exitfuncs(runtime);
1373
1374
0
    _PyRuntime_Finalize();
1375
0
    return status;
1376
0
}
1377
1378
void
1379
Py_Finalize(void)
1380
0
{
1381
0
    Py_FinalizeEx();
1382
0
}
1383
1384
/* Create and initialize a new interpreter and thread, and return the
1385
   new thread.  This requires that Py_Initialize() has been called
1386
   first.
1387
1388
   Unsuccessful initialization yields a NULL pointer.  Note that *no*
1389
   exception information is available even in this case -- the
1390
   exception information is held in the thread, and there is no
1391
   thread.
1392
1393
   Locking: as above.
1394
1395
*/
1396
1397
static PyStatus
1398
new_interpreter(PyThreadState **tstate_p)
1399
0
{
1400
0
    PyStatus status;
1401
1402
0
    status = _PyRuntime_Initialize();
1403
0
    if (_PyStatus_EXCEPTION(status)) {
1404
0
        return status;
1405
0
    }
1406
0
    _PyRuntimeState *runtime = &_PyRuntime;
1407
1408
0
    if (!runtime->initialized) {
1409
0
        return _PyStatus_ERR("Py_Initialize must be called first");
1410
0
    }
1411
1412
    /* Issue #10915, #15751: The GIL API doesn't work with multiple
1413
       interpreters: disable PyGILState_Check(). */
1414
0
    _PyGILState_check_enabled = 0;
1415
1416
0
    PyInterpreterState *interp = PyInterpreterState_New();
1417
0
    if (interp == NULL) {
1418
0
        *tstate_p = NULL;
1419
0
        return _PyStatus_OK();
1420
0
    }
1421
1422
0
    PyThreadState *tstate = PyThreadState_New(interp);
1423
0
    if (tstate == NULL) {
1424
0
        PyInterpreterState_Delete(interp);
1425
0
        *tstate_p = NULL;
1426
0
        return _PyStatus_OK();
1427
0
    }
1428
1429
0
    PyThreadState *save_tstate = PyThreadState_Swap(tstate);
1430
1431
    /* Copy the current interpreter config into the new interpreter */
1432
0
    PyConfig *config;
1433
0
    if (save_tstate != NULL) {
1434
0
        config = &save_tstate->interp->config;
1435
0
    } else {
1436
        /* No current thread state, copy from the main interpreter */
1437
0
        PyInterpreterState *main_interp = PyInterpreterState_Main();
1438
0
        config = &main_interp->config;
1439
0
    }
1440
1441
0
    status = _PyConfig_Copy(&interp->config, config);
1442
0
    if (_PyStatus_EXCEPTION(status)) {
1443
0
        return status;
1444
0
    }
1445
0
    config = &interp->config;
1446
1447
0
    status = _PyExc_Init();
1448
0
    if (_PyStatus_EXCEPTION(status)) {
1449
0
        return status;
1450
0
    }
1451
1452
0
    status = _PyErr_Init();
1453
0
    if (_PyStatus_EXCEPTION(status)) {
1454
0
        return status;
1455
0
    }
1456
1457
1458
    /* XXX The following is lax in error checking */
1459
0
    PyObject *modules = PyDict_New();
1460
0
    if (modules == NULL) {
1461
0
        return _PyStatus_ERR("can't make modules dictionary");
1462
0
    }
1463
0
    interp->modules = modules;
1464
1465
0
    PyObject *sysmod = _PyImport_FindBuiltin("sys", modules);
1466
0
    if (sysmod != NULL) {
1467
0
        interp->sysdict = PyModule_GetDict(sysmod);
1468
0
        if (interp->sysdict == NULL) {
1469
0
            goto handle_error;
1470
0
        }
1471
0
        Py_INCREF(interp->sysdict);
1472
0
        PyDict_SetItemString(interp->sysdict, "modules", modules);
1473
0
        if (_PySys_InitMain(runtime, interp) < 0) {
1474
0
            return _PyStatus_ERR("can't finish initializing sys");
1475
0
        }
1476
0
    }
1477
0
    else if (PyErr_Occurred()) {
1478
0
        goto handle_error;
1479
0
    }
1480
1481
0
    PyObject *bimod = _PyImport_FindBuiltin("builtins", modules);
1482
0
    if (bimod != NULL) {
1483
0
        interp->builtins = PyModule_GetDict(bimod);
1484
0
        if (interp->builtins == NULL)
1485
0
            goto handle_error;
1486
0
        Py_INCREF(interp->builtins);
1487
0
    }
1488
0
    else if (PyErr_Occurred()) {
1489
0
        goto handle_error;
1490
0
    }
1491
1492
0
    if (bimod != NULL && sysmod != NULL) {
1493
0
        status = _PyBuiltins_AddExceptions(bimod);
1494
0
        if (_PyStatus_EXCEPTION(status)) {
1495
0
            return status;
1496
0
        }
1497
1498
0
        status = _PySys_SetPreliminaryStderr(interp->sysdict);
1499
0
        if (_PyStatus_EXCEPTION(status)) {
1500
0
            return status;
1501
0
        }
1502
1503
0
        status = _PyImportHooks_Init();
1504
0
        if (_PyStatus_EXCEPTION(status)) {
1505
0
            return status;
1506
0
        }
1507
1508
0
        status = init_importlib(interp, sysmod);
1509
0
        if (_PyStatus_EXCEPTION(status)) {
1510
0
            return status;
1511
0
        }
1512
1513
0
        status = init_importlib_external(interp);
1514
0
        if (_PyStatus_EXCEPTION(status)) {
1515
0
            return status;
1516
0
        }
1517
1518
0
        status = _PyUnicode_InitEncodings(tstate);
1519
0
        if (_PyStatus_EXCEPTION(status)) {
1520
0
            return status;
1521
0
        }
1522
1523
0
        status = init_sys_streams(interp);
1524
0
        if (_PyStatus_EXCEPTION(status)) {
1525
0
            return status;
1526
0
        }
1527
1528
0
        status = add_main_module(interp);
1529
0
        if (_PyStatus_EXCEPTION(status)) {
1530
0
            return status;
1531
0
        }
1532
1533
0
        if (config->site_import) {
1534
0
            status = init_import_size();
1535
0
            if (_PyStatus_EXCEPTION(status)) {
1536
0
                return status;
1537
0
            }
1538
0
        }
1539
0
    }
1540
1541
0
    if (PyErr_Occurred()) {
1542
0
        goto handle_error;
1543
0
    }
1544
1545
0
    *tstate_p = tstate;
1546
0
    return _PyStatus_OK();
1547
1548
0
handle_error:
1549
    /* Oops, it didn't work.  Undo it all. */
1550
1551
0
    PyErr_PrintEx(0);
1552
0
    PyThreadState_Clear(tstate);
1553
0
    PyThreadState_Swap(save_tstate);
1554
0
    PyThreadState_Delete(tstate);
1555
0
    PyInterpreterState_Delete(interp);
1556
1557
0
    *tstate_p = NULL;
1558
0
    return _PyStatus_OK();
1559
0
}
1560
1561
PyThreadState *
1562
Py_NewInterpreter(void)
1563
0
{
1564
0
    PyThreadState *tstate = NULL;
1565
0
    PyStatus status = new_interpreter(&tstate);
1566
0
    if (_PyStatus_EXCEPTION(status)) {
1567
0
        Py_ExitStatusException(status);
1568
0
    }
1569
0
    return tstate;
1570
1571
0
}
1572
1573
/* Delete an interpreter and its last thread.  This requires that the
1574
   given thread state is current, that the thread has no remaining
1575
   frames, and that it is its interpreter's only remaining thread.
1576
   It is a fatal error to violate these constraints.
1577
1578
   (Py_FinalizeEx() doesn't have these constraints -- it zaps
1579
   everything, regardless.)
1580
1581
   Locking: as above.
1582
1583
*/
1584
1585
void
1586
Py_EndInterpreter(PyThreadState *tstate)
1587
0
{
1588
0
    PyInterpreterState *interp = tstate->interp;
1589
1590
0
    if (tstate != _PyThreadState_GET())
1591
0
        Py_FatalError("Py_EndInterpreter: thread is not current");
1592
0
    if (tstate->frame != NULL)
1593
0
        Py_FatalError("Py_EndInterpreter: thread still has a frame");
1594
0
    interp->finalizing = 1;
1595
1596
    // Wrap up existing "threading"-module-created, non-daemon threads.
1597
0
    wait_for_thread_shutdown();
1598
1599
0
    call_py_exitfuncs(interp);
1600
1601
0
    if (tstate != interp->tstate_head || tstate->next != NULL)
1602
0
        Py_FatalError("Py_EndInterpreter: not the last thread");
1603
1604
0
    PyImport_Cleanup();
1605
0
    PyInterpreterState_Clear(interp);
1606
0
    PyThreadState_Swap(NULL);
1607
0
    PyInterpreterState_Delete(interp);
1608
0
}
1609
1610
/* Add the __main__ module */
1611
1612
static PyStatus
1613
add_main_module(PyInterpreterState *interp)
1614
14
{
1615
14
    PyObject *m, *d, *loader, *ann_dict;
1616
14
    m = PyImport_AddModule("__main__");
1617
14
    if (m == NULL)
1618
0
        return _PyStatus_ERR("can't create __main__ module");
1619
1620
14
    d = PyModule_GetDict(m);
1621
14
    ann_dict = PyDict_New();
1622
14
    if ((ann_dict == NULL) ||
1623
14
        (PyDict_SetItemString(d, "__annotations__", ann_dict) < 0)) {
1624
0
        return _PyStatus_ERR("Failed to initialize __main__.__annotations__");
1625
0
    }
1626
14
    Py_DECREF(ann_dict);
1627
1628
14
    if (PyDict_GetItemString(d, "__builtins__") == NULL) {
1629
14
        PyObject *bimod = PyImport_ImportModule("builtins");
1630
14
        if (bimod == NULL) {
1631
0
            return _PyStatus_ERR("Failed to retrieve builtins module");
1632
0
        }
1633
14
        if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
1634
0
            return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
1635
0
        }
1636
14
        Py_DECREF(bimod);
1637
14
    }
1638
1639
    /* Main is a little special - imp.is_builtin("__main__") will return
1640
     * False, but BuiltinImporter is still the most appropriate initial
1641
     * setting for its __loader__ attribute. A more suitable value will
1642
     * be set if __main__ gets further initialized later in the startup
1643
     * process.
1644
     */
1645
14
    loader = PyDict_GetItemString(d, "__loader__");
1646
14
    if (loader == NULL || loader == Py_None) {
1647
14
        PyObject *loader = PyObject_GetAttrString(interp->importlib,
1648
14
                                                  "BuiltinImporter");
1649
14
        if (loader == NULL) {
1650
0
            return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
1651
0
        }
1652
14
        if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
1653
0
            return _PyStatus_ERR("Failed to initialize __main__.__loader__");
1654
0
        }
1655
14
        Py_DECREF(loader);
1656
14
    }
1657
14
    return _PyStatus_OK();
1658
14
}
1659
1660
/* Import the site module (not into __main__ though) */
1661
1662
static PyStatus
1663
init_import_size(void)
1664
14
{
1665
14
    PyObject *m;
1666
14
    m = PyImport_ImportModule("site");
1667
14
    if (m == NULL) {
1668
0
        return _PyStatus_ERR("Failed to import the site module");
1669
0
    }
1670
14
    Py_DECREF(m);
1671
14
    return _PyStatus_OK();
1672
14
}
1673
1674
/* Check if a file descriptor is valid or not.
1675
   Return 0 if the file descriptor is invalid, return non-zero otherwise. */
1676
static int
1677
is_valid_fd(int fd)
1678
42
{
1679
/* dup() is faster than fstat(): fstat() can require input/output operations,
1680
   whereas dup() doesn't. There is a low risk of EMFILE/ENFILE at Python
1681
   startup. Problem: dup() doesn't check if the file descriptor is valid on
1682
   some platforms.
1683
1684
   bpo-30225: On macOS Tiger, when stdout is redirected to a pipe and the other
1685
   side of the pipe is closed, dup(1) succeed, whereas fstat(1, &st) fails with
1686
   EBADF. FreeBSD has similar issue (bpo-32849).
1687
1688
   Only use dup() on platforms where dup() is enough to detect invalid FD in
1689
   corner cases: on Linux and Windows (bpo-32849). */
1690
42
#if defined(__linux__) || defined(MS_WINDOWS)
1691
42
    if (fd < 0) {
1692
0
        return 0;
1693
0
    }
1694
42
    int fd2;
1695
1696
42
    _Py_BEGIN_SUPPRESS_IPH
1697
42
    fd2 = dup(fd);
1698
42
    if (fd2 >= 0) {
1699
42
        close(fd2);
1700
42
    }
1701
42
    _Py_END_SUPPRESS_IPH
1702
1703
42
    return (fd2 >= 0);
1704
#else
1705
    struct stat st;
1706
    return (fstat(fd, &st) == 0);
1707
#endif
1708
42
}
1709
1710
/* returns Py_None if the fd is not valid */
1711
static PyObject*
1712
create_stdio(const PyConfig *config, PyObject* io,
1713
    int fd, int write_mode, const char* name,
1714
    const wchar_t* encoding, const wchar_t* errors)
1715
42
{
1716
42
    PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
1717
42
    const char* mode;
1718
42
    const char* newline;
1719
42
    PyObject *line_buffering, *write_through;
1720
42
    int buffering, isatty;
1721
42
    _Py_IDENTIFIER(open);
1722
42
    _Py_IDENTIFIER(isatty);
1723
42
    _Py_IDENTIFIER(TextIOWrapper);
1724
42
    _Py_IDENTIFIER(mode);
1725
42
    const int buffered_stdio = config->buffered_stdio;
1726
1727
42
    if (!is_valid_fd(fd))
1728
0
        Py_RETURN_NONE;
1729
1730
    /* stdin is always opened in buffered mode, first because it shouldn't
1731
       make a difference in common use cases, second because TextIOWrapper
1732
       depends on the presence of a read1() method which only exists on
1733
       buffered streams.
1734
    */
1735
42
    if (!buffered_stdio && write_mode)
1736
0
        buffering = 0;
1737
42
    else
1738
42
        buffering = -1;
1739
42
    if (write_mode)
1740
28
        mode = "wb";
1741
14
    else
1742
14
        mode = "rb";
1743
42
    buf = _PyObject_CallMethodId(io, &PyId_open, "isiOOOi",
1744
42
                                 fd, mode, buffering,
1745
42
                                 Py_None, Py_None, /* encoding, errors */
1746
42
                                 Py_None, 0); /* newline, closefd */
1747
42
    if (buf == NULL)
1748
0
        goto error;
1749
1750
42
    if (buffering) {
1751
42
        _Py_IDENTIFIER(raw);
1752
42
        raw = _PyObject_GetAttrId(buf, &PyId_raw);
1753
42
        if (raw == NULL)
1754
0
            goto error;
1755
42
    }
1756
0
    else {
1757
0
        raw = buf;
1758
0
        Py_INCREF(raw);
1759
0
    }
1760
1761
#ifdef MS_WINDOWS
1762
    /* Windows console IO is always UTF-8 encoded */
1763
    if (PyWindowsConsoleIO_Check(raw))
1764
        encoding = L"utf-8";
1765
#endif
1766
1767
42
    text = PyUnicode_FromString(name);
1768
42
    if (text == NULL || _PyObject_SetAttrId(raw, &PyId_name, text) < 0)
1769
0
        goto error;
1770
42
    res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
1771
42
    if (res == NULL)
1772
0
        goto error;
1773
42
    isatty = PyObject_IsTrue(res);
1774
42
    Py_DECREF(res);
1775
42
    if (isatty == -1)
1776
0
        goto error;
1777
42
    if (!buffered_stdio)
1778
0
        write_through = Py_True;
1779
42
    else
1780
42
        write_through = Py_False;
1781
42
    if (isatty && buffered_stdio)
1782
0
        line_buffering = Py_True;
1783
42
    else
1784
42
        line_buffering = Py_False;
1785
1786
42
    Py_CLEAR(raw);
1787
42
    Py_CLEAR(text);
1788
1789
#ifdef MS_WINDOWS
1790
    /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
1791
       newlines to "\n".
1792
       sys.stdout and sys.stderr: translate "\n" to "\r\n". */
1793
    newline = NULL;
1794
#else
1795
    /* sys.stdin: split lines at "\n".
1796
       sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
1797
42
    newline = "\n";
1798
42
#endif
1799
1800
42
    PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
1801
42
    if (encoding_str == NULL) {
1802
0
        Py_CLEAR(buf);
1803
0
        goto error;
1804
0
    }
1805
1806
42
    PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
1807
42
    if (errors_str == NULL) {
1808
0
        Py_CLEAR(buf);
1809
0
        Py_CLEAR(encoding_str);
1810
0
        goto error;
1811
0
    }
1812
1813
42
    stream = _PyObject_CallMethodId(io, &PyId_TextIOWrapper, "OOOsOO",
1814
42
                                    buf, encoding_str, errors_str,
1815
42
                                    newline, line_buffering, write_through);
1816
42
    Py_CLEAR(buf);
1817
42
    Py_CLEAR(encoding_str);
1818
42
    Py_CLEAR(errors_str);
1819
42
    if (stream == NULL)
1820
0
        goto error;
1821
1822
42
    if (write_mode)
1823
28
        mode = "w";
1824
14
    else
1825
14
        mode = "r";
1826
42
    text = PyUnicode_FromString(mode);
1827
42
    if (!text || _PyObject_SetAttrId(stream, &PyId_mode, text) < 0)
1828
0
        goto error;
1829
42
    Py_CLEAR(text);
1830
42
    return stream;
1831
1832
0
error:
1833
0
    Py_XDECREF(buf);
1834
0
    Py_XDECREF(stream);
1835
0
    Py_XDECREF(text);
1836
0
    Py_XDECREF(raw);
1837
1838
0
    if (PyErr_ExceptionMatches(PyExc_OSError) && !is_valid_fd(fd)) {
1839
        /* Issue #24891: the file descriptor was closed after the first
1840
           is_valid_fd() check was called. Ignore the OSError and set the
1841
           stream to None. */
1842
0
        PyErr_Clear();
1843
0
        Py_RETURN_NONE;
1844
0
    }
1845
0
    return NULL;
1846
0
}
1847
1848
/* Initialize sys.stdin, stdout, stderr and builtins.open */
1849
static PyStatus
1850
init_sys_streams(PyInterpreterState *interp)
1851
14
{
1852
14
    PyObject *iomod = NULL, *wrapper;
1853
14
    PyObject *bimod = NULL;
1854
14
    PyObject *m;
1855
14
    PyObject *std = NULL;
1856
14
    int fd;
1857
14
    PyObject * encoding_attr;
1858
14
    PyStatus res = _PyStatus_OK();
1859
14
    PyConfig *config = &interp->config;
1860
1861
    /* Check that stdin is not a directory
1862
       Using shell redirection, you can redirect stdin to a directory,
1863
       crashing the Python interpreter. Catch this common mistake here
1864
       and output a useful error message. Note that under MS Windows,
1865
       the shell already prevents that. */
1866
14
#ifndef MS_WINDOWS
1867
14
    struct _Py_stat_struct sb;
1868
14
    if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
1869
14
        S_ISDIR(sb.st_mode)) {
1870
0
        return _PyStatus_ERR("<stdin> is a directory, cannot continue");
1871
0
    }
1872
14
#endif
1873
1874
    /* Hack to avoid a nasty recursion issue when Python is invoked
1875
       in verbose mode: pre-import the Latin-1 and UTF-8 codecs */
1876
14
    if ((m = PyImport_ImportModule("encodings.utf_8")) == NULL) {
1877
0
        goto error;
1878
0
    }
1879
14
    Py_DECREF(m);
1880
1881
14
    if (!(m = PyImport_ImportModule("encodings.latin_1"))) {
1882
0
        goto error;
1883
0
    }
1884
14
    Py_DECREF(m);
1885
1886
14
    if (!(bimod = PyImport_ImportModule("builtins"))) {
1887
0
        goto error;
1888
0
    }
1889
1890
14
    if (!(iomod = PyImport_ImportModule("io"))) {
1891
0
        goto error;
1892
0
    }
1893
14
    if (!(wrapper = PyObject_GetAttrString(iomod, "OpenWrapper"))) {
1894
0
        goto error;
1895
0
    }
1896
1897
    /* Set builtins.open */
1898
14
    if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
1899
0
        Py_DECREF(wrapper);
1900
0
        goto error;
1901
0
    }
1902
14
    Py_DECREF(wrapper);
1903
1904
    /* Set sys.stdin */
1905
14
    fd = fileno(stdin);
1906
    /* Under some conditions stdin, stdout and stderr may not be connected
1907
     * and fileno() may point to an invalid file descriptor. For example
1908
     * GUI apps don't have valid standard streams by default.
1909
     */
1910
14
    std = create_stdio(config, iomod, fd, 0, "<stdin>",
1911
14
                       config->stdio_encoding,
1912
14
                       config->stdio_errors);
1913
14
    if (std == NULL)
1914
0
        goto error;
1915
14
    PySys_SetObject("__stdin__", std);
1916
14
    _PySys_SetObjectId(&PyId_stdin, std);
1917
14
    Py_DECREF(std);
1918
1919
    /* Set sys.stdout */
1920
14
    fd = fileno(stdout);
1921
14
    std = create_stdio(config, iomod, fd, 1, "<stdout>",
1922
14
                       config->stdio_encoding,
1923
14
                       config->stdio_errors);
1924
14
    if (std == NULL)
1925
0
        goto error;
1926
14
    PySys_SetObject("__stdout__", std);
1927
14
    _PySys_SetObjectId(&PyId_stdout, std);
1928
14
    Py_DECREF(std);
1929
1930
14
#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
1931
    /* Set sys.stderr, replaces the preliminary stderr */
1932
14
    fd = fileno(stderr);
1933
14
    std = create_stdio(config, iomod, fd, 1, "<stderr>",
1934
14
                       config->stdio_encoding,
1935
14
                       L"backslashreplace");
1936
14
    if (std == NULL)
1937
0
        goto error;
1938
1939
    /* Same as hack above, pre-import stderr's codec to avoid recursion
1940
       when import.c tries to write to stderr in verbose mode. */
1941
14
    encoding_attr = PyObject_GetAttrString(std, "encoding");
1942
14
    if (encoding_attr != NULL) {
1943
14
        const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
1944
14
        if (std_encoding != NULL) {
1945
14
            PyObject *codec_info = _PyCodec_Lookup(std_encoding);
1946
14
            Py_XDECREF(codec_info);
1947
14
        }
1948
14
        Py_DECREF(encoding_attr);
1949
14
    }
1950
14
    PyErr_Clear();  /* Not a fatal error if codec isn't available */
1951
1952
14
    if (PySys_SetObject("__stderr__", std) < 0) {
1953
0
        Py_DECREF(std);
1954
0
        goto error;
1955
0
    }
1956
14
    if (_PySys_SetObjectId(&PyId_stderr, std) < 0) {
1957
0
        Py_DECREF(std);
1958
0
        goto error;
1959
0
    }
1960
14
    Py_DECREF(std);
1961
14
#endif
1962
1963
14
    goto done;
1964
1965
0
error:
1966
0
    res = _PyStatus_ERR("can't initialize sys standard streams");
1967
1968
14
done:
1969
14
    _Py_ClearStandardStreamEncoding();
1970
1971
14
    Py_XDECREF(bimod);
1972
14
    Py_XDECREF(iomod);
1973
14
    return res;
1974
0
}
1975
1976
1977
static void
1978
_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
1979
                              PyThreadState *tstate)
1980
0
{
1981
0
    fputc('\n', stderr);
1982
0
    fflush(stderr);
1983
1984
    /* display the current Python stack */
1985
0
    _Py_DumpTracebackThreads(fd, interp, tstate);
1986
0
}
1987
1988
/* Print the current exception (if an exception is set) with its traceback,
1989
   or display the current Python stack.
1990
1991
   Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
1992
   called on catastrophic cases.
1993
1994
   Return 1 if the traceback was displayed, 0 otherwise. */
1995
1996
static int
1997
_Py_FatalError_PrintExc(int fd)
1998
0
{
1999
0
    PyObject *ferr, *res;
2000
0
    PyObject *exception, *v, *tb;
2001
0
    int has_tb;
2002
2003
0
    PyErr_Fetch(&exception, &v, &tb);
2004
0
    if (exception == NULL) {
2005
        /* No current exception */
2006
0
        return 0;
2007
0
    }
2008
2009
0
    ferr = _PySys_GetObjectId(&PyId_stderr);
2010
0
    if (ferr == NULL || ferr == Py_None) {
2011
        /* sys.stderr is not set yet or set to None,
2012
           no need to try to display the exception */
2013
0
        return 0;
2014
0
    }
2015
2016
0
    PyErr_NormalizeException(&exception, &v, &tb);
2017
0
    if (tb == NULL) {
2018
0
        tb = Py_None;
2019
0
        Py_INCREF(tb);
2020
0
    }
2021
0
    PyException_SetTraceback(v, tb);
2022
0
    if (exception == NULL) {
2023
        /* PyErr_NormalizeException() failed */
2024
0
        return 0;
2025
0
    }
2026
2027
0
    has_tb = (tb != Py_None);
2028
0
    PyErr_Display(exception, v, tb);
2029
0
    Py_XDECREF(exception);
2030
0
    Py_XDECREF(v);
2031
0
    Py_XDECREF(tb);
2032
2033
    /* sys.stderr may be buffered: call sys.stderr.flush() */
2034
0
    res = _PyObject_CallMethodId(ferr, &PyId_flush, NULL);
2035
0
    if (res == NULL)
2036
0
        PyErr_Clear();
2037
0
    else
2038
0
        Py_DECREF(res);
2039
2040
0
    return has_tb;
2041
0
}
2042
2043
/* Print fatal error message and abort */
2044
2045
#ifdef MS_WINDOWS
2046
static void
2047
fatal_output_debug(const char *msg)
2048
{
2049
    /* buffer of 256 bytes allocated on the stack */
2050
    WCHAR buffer[256 / sizeof(WCHAR)];
2051
    size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
2052
    size_t msglen;
2053
2054
    OutputDebugStringW(L"Fatal Python error: ");
2055
2056
    msglen = strlen(msg);
2057
    while (msglen) {
2058
        size_t i;
2059
2060
        if (buflen > msglen) {
2061
            buflen = msglen;
2062
        }
2063
2064
        /* Convert the message to wchar_t. This uses a simple one-to-one
2065
           conversion, assuming that the this error message actually uses
2066
           ASCII only. If this ceases to be true, we will have to convert. */
2067
        for (i=0; i < buflen; ++i) {
2068
            buffer[i] = msg[i];
2069
        }
2070
        buffer[i] = L'\0';
2071
        OutputDebugStringW(buffer);
2072
2073
        msg += buflen;
2074
        msglen -= buflen;
2075
    }
2076
    OutputDebugStringW(L"\n");
2077
}
2078
#endif
2079
2080
2081
static void
2082
fatal_error_dump_runtime(FILE *stream, _PyRuntimeState *runtime)
2083
0
{
2084
0
    fprintf(stream, "Python runtime state: ");
2085
0
    if (runtime->finalizing) {
2086
0
        fprintf(stream, "finalizing (tstate=%p)", runtime->finalizing);
2087
0
    }
2088
0
    else if (runtime->initialized) {
2089
0
        fprintf(stream, "initialized");
2090
0
    }
2091
0
    else if (runtime->core_initialized) {
2092
0
        fprintf(stream, "core initialized");
2093
0
    }
2094
0
    else if (runtime->preinitialized) {
2095
0
        fprintf(stream, "preinitialized");
2096
0
    }
2097
0
    else if (runtime->preinitializing) {
2098
0
        fprintf(stream, "preinitializing");
2099
0
    }
2100
0
    else {
2101
0
        fprintf(stream, "unknown");
2102
0
    }
2103
0
    fprintf(stream, "\n");
2104
0
    fflush(stream);
2105
0
}
2106
2107
2108
static void _Py_NO_RETURN
2109
fatal_error(const char *prefix, const char *msg, int status)
2110
0
{
2111
0
    FILE *stream = stderr;
2112
0
    const int fd = fileno(stream);
2113
0
    static int reentrant = 0;
2114
2115
0
    if (reentrant) {
2116
        /* Py_FatalError() caused a second fatal error.
2117
           Example: flush_std_files() raises a recursion error. */
2118
0
        goto exit;
2119
0
    }
2120
0
    reentrant = 1;
2121
2122
0
    fprintf(stream, "Fatal Python error: ");
2123
0
    if (prefix) {
2124
0
        fputs(prefix, stream);
2125
0
        fputs(": ", stream);
2126
0
    }
2127
0
    if (msg) {
2128
0
        fputs(msg, stream);
2129
0
    }
2130
0
    else {
2131
0
        fprintf(stream, "<message not set>");
2132
0
    }
2133
0
    fputs("\n", stream);
2134
0
    fflush(stream); /* it helps in Windows debug build */
2135
2136
0
    _PyRuntimeState *runtime = &_PyRuntime;
2137
0
    fatal_error_dump_runtime(stream, runtime);
2138
2139
0
    PyThreadState *tstate = _PyRuntimeState_GetThreadState(runtime);
2140
0
    PyInterpreterState *interp = NULL;
2141
0
    if (tstate != NULL) {
2142
0
        interp = tstate->interp;
2143
0
    }
2144
2145
    /* Check if the current thread has a Python thread state
2146
       and holds the GIL.
2147
2148
       tss_tstate is NULL if Py_FatalError() is called from a C thread which
2149
       has no Python thread state.
2150
2151
       tss_tstate != tstate if the current Python thread does not hold the GIL.
2152
       */
2153
0
    PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
2154
0
    int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
2155
0
    if (has_tstate_and_gil) {
2156
        /* If an exception is set, print the exception with its traceback */
2157
0
        if (!_Py_FatalError_PrintExc(fd)) {
2158
            /* No exception is set, or an exception is set without traceback */
2159
0
            _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
2160
0
        }
2161
0
    }
2162
0
    else {
2163
0
        _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
2164
0
    }
2165
2166
    /* The main purpose of faulthandler is to display the traceback.
2167
       This function already did its best to display a traceback.
2168
       Disable faulthandler to prevent writing a second traceback
2169
       on abort(). */
2170
0
    _PyFaulthandler_Fini();
2171
2172
    /* Check if the current Python thread hold the GIL */
2173
0
    if (has_tstate_and_gil) {
2174
        /* Flush sys.stdout and sys.stderr */
2175
0
        flush_std_files();
2176
0
    }
2177
2178
#ifdef MS_WINDOWS
2179
    fatal_output_debug(msg);
2180
#endif /* MS_WINDOWS */
2181
2182
0
exit:
2183
0
    if (status < 0) {
2184
#if defined(MS_WINDOWS) && defined(_DEBUG)
2185
        DebugBreak();
2186
#endif
2187
0
        abort();
2188
0
    }
2189
0
    else {
2190
0
        exit(status);
2191
0
    }
2192
0
}
2193
2194
void _Py_NO_RETURN
2195
Py_FatalError(const char *msg)
2196
0
{
2197
0
    fatal_error(NULL, msg, -1);
2198
0
}
2199
2200
void _Py_NO_RETURN
2201
Py_ExitStatusException(PyStatus status)
2202
0
{
2203
0
    if (_PyStatus_IS_EXIT(status)) {
2204
0
        exit(status.exitcode);
2205
0
    }
2206
0
    else if (_PyStatus_IS_ERROR(status)) {
2207
0
        fatal_error(status.func, status.err_msg, 1);
2208
0
    }
2209
0
    else {
2210
0
        Py_FatalError("Py_ExitStatusException() must not be called on success");
2211
0
    }
2212
0
}
2213
2214
/* Clean up and exit */
2215
2216
#  include "pythread.h"
2217
2218
/* For the atexit module. */
2219
void _Py_PyAtExit(void (*func)(PyObject *), PyObject *module)
2220
1
{
2221
1
    PyInterpreterState *is = _PyInterpreterState_Get();
2222
2223
    /* Guard against API misuse (see bpo-17852) */
2224
1
    assert(is->pyexitfunc == NULL || is->pyexitfunc == func);
2225
2226
1
    is->pyexitfunc = func;
2227
1
    is->pyexitmodule = module;
2228
1
}
2229
2230
static void
2231
call_py_exitfuncs(PyInterpreterState *istate)
2232
0
{
2233
0
    if (istate->pyexitfunc == NULL)
2234
0
        return;
2235
2236
0
    (*istate->pyexitfunc)(istate->pyexitmodule);
2237
0
    PyErr_Clear();
2238
0
}
2239
2240
/* Wait until threading._shutdown completes, provided
2241
   the threading module was imported in the first place.
2242
   The shutdown routine will wait until all non-daemon
2243
   "threading" threads have completed. */
2244
static void
2245
wait_for_thread_shutdown(void)
2246
0
{
2247
0
    _Py_IDENTIFIER(_shutdown);
2248
0
    PyObject *result;
2249
0
    PyObject *threading = _PyImport_GetModuleId(&PyId_threading);
2250
0
    if (threading == NULL) {
2251
0
        if (PyErr_Occurred()) {
2252
0
            PyErr_WriteUnraisable(NULL);
2253
0
        }
2254
        /* else: threading not imported */
2255
0
        return;
2256
0
    }
2257
0
    result = _PyObject_CallMethodId(threading, &PyId__shutdown, NULL);
2258
0
    if (result == NULL) {
2259
0
        PyErr_WriteUnraisable(threading);
2260
0
    }
2261
0
    else {
2262
0
        Py_DECREF(result);
2263
0
    }
2264
0
    Py_DECREF(threading);
2265
0
}
2266
2267
0
#define NEXITFUNCS 32
2268
int Py_AtExit(void (*func)(void))
2269
0
{
2270
0
    if (_PyRuntime.nexitfuncs >= NEXITFUNCS)
2271
0
        return -1;
2272
0
    _PyRuntime.exitfuncs[_PyRuntime.nexitfuncs++] = func;
2273
0
    return 0;
2274
0
}
2275
2276
static void
2277
call_ll_exitfuncs(_PyRuntimeState *runtime)
2278
0
{
2279
0
    while (runtime->nexitfuncs > 0) {
2280
        /* pop last function from the list */
2281
0
        runtime->nexitfuncs--;
2282
0
        void (*exitfunc)(void) = runtime->exitfuncs[runtime->nexitfuncs];
2283
0
        runtime->exitfuncs[runtime->nexitfuncs] = NULL;
2284
2285
0
        exitfunc();
2286
0
    }
2287
2288
0
    fflush(stdout);
2289
0
    fflush(stderr);
2290
0
}
2291
2292
void _Py_NO_RETURN
2293
Py_Exit(int sts)
2294
0
{
2295
0
    if (Py_FinalizeEx() < 0) {
2296
0
        sts = 120;
2297
0
    }
2298
2299
0
    exit(sts);
2300
0
}
2301
2302
static PyStatus
2303
init_signals(void)
2304
0
{
2305
0
#ifdef SIGPIPE
2306
0
    PyOS_setsig(SIGPIPE, SIG_IGN);
2307
0
#endif
2308
#ifdef SIGXFZ
2309
    PyOS_setsig(SIGXFZ, SIG_IGN);
2310
#endif
2311
0
#ifdef SIGXFSZ
2312
0
    PyOS_setsig(SIGXFSZ, SIG_IGN);
2313
0
#endif
2314
0
    PyOS_InitInterrupts(); /* May imply init_signals() */
2315
0
    if (PyErr_Occurred()) {
2316
0
        return _PyStatus_ERR("can't import signal");
2317
0
    }
2318
0
    return _PyStatus_OK();
2319
0
}
2320
2321
2322
/* Restore signals that the interpreter has called SIG_IGN on to SIG_DFL.
2323
 *
2324
 * All of the code in this function must only use async-signal-safe functions,
2325
 * listed at `man 7 signal` or
2326
 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2327
 */
2328
void
2329
_Py_RestoreSignals(void)
2330
0
{
2331
0
#ifdef SIGPIPE
2332
0
    PyOS_setsig(SIGPIPE, SIG_DFL);
2333
0
#endif
2334
#ifdef SIGXFZ
2335
    PyOS_setsig(SIGXFZ, SIG_DFL);
2336
#endif
2337
0
#ifdef SIGXFSZ
2338
0
    PyOS_setsig(SIGXFSZ, SIG_DFL);
2339
0
#endif
2340
0
}
2341
2342
2343
/*
2344
 * The file descriptor fd is considered ``interactive'' if either
2345
 *   a) isatty(fd) is TRUE, or
2346
 *   b) the -i flag was given, and the filename associated with
2347
 *      the descriptor is NULL or "<stdin>" or "???".
2348
 */
2349
int
2350
Py_FdIsInteractive(FILE *fp, const char *filename)
2351
0
{
2352
0
    if (isatty((int)fileno(fp)))
2353
0
        return 1;
2354
0
    if (!Py_InteractiveFlag)
2355
0
        return 0;
2356
0
    return (filename == NULL) ||
2357
0
           (strcmp(filename, "<stdin>") == 0) ||
2358
0
           (strcmp(filename, "???") == 0);
2359
0
}
2360
2361
2362
/* Wrappers around sigaction() or signal(). */
2363
2364
PyOS_sighandler_t
2365
PyOS_getsig(int sig)
2366
0
{
2367
0
#ifdef HAVE_SIGACTION
2368
0
    struct sigaction context;
2369
0
    if (sigaction(sig, NULL, &context) == -1)
2370
0
        return SIG_ERR;
2371
0
    return context.sa_handler;
2372
#else
2373
    PyOS_sighandler_t handler;
2374
/* Special signal handling for the secure CRT in Visual Studio 2005 */
2375
#if defined(_MSC_VER) && _MSC_VER >= 1400
2376
    switch (sig) {
2377
    /* Only these signals are valid */
2378
    case SIGINT:
2379
    case SIGILL:
2380
    case SIGFPE:
2381
    case SIGSEGV:
2382
    case SIGTERM:
2383
    case SIGBREAK:
2384
    case SIGABRT:
2385
        break;
2386
    /* Don't call signal() with other values or it will assert */
2387
    default:
2388
        return SIG_ERR;
2389
    }
2390
#endif /* _MSC_VER && _MSC_VER >= 1400 */
2391
    handler = signal(sig, SIG_IGN);
2392
    if (handler != SIG_ERR)
2393
        signal(sig, handler);
2394
    return handler;
2395
#endif
2396
0
}
2397
2398
/*
2399
 * All of the code in this function must only use async-signal-safe functions,
2400
 * listed at `man 7 signal` or
2401
 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
2402
 */
2403
PyOS_sighandler_t
2404
PyOS_setsig(int sig, PyOS_sighandler_t handler)
2405
0
{
2406
0
#ifdef HAVE_SIGACTION
2407
    /* Some code in Modules/signalmodule.c depends on sigaction() being
2408
     * used here if HAVE_SIGACTION is defined.  Fix that if this code
2409
     * changes to invalidate that assumption.
2410
     */
2411
0
    struct sigaction context, ocontext;
2412
0
    context.sa_handler = handler;
2413
0
    sigemptyset(&context.sa_mask);
2414
0
    context.sa_flags = 0;
2415
0
    if (sigaction(sig, &context, &ocontext) == -1)
2416
0
        return SIG_ERR;
2417
0
    return ocontext.sa_handler;
2418
#else
2419
    PyOS_sighandler_t oldhandler;
2420
    oldhandler = signal(sig, handler);
2421
#ifdef HAVE_SIGINTERRUPT
2422
    siginterrupt(sig, 1);
2423
#endif
2424
    return oldhandler;
2425
#endif
2426
0
}
2427
2428
#ifdef __cplusplus
2429
}
2430
#endif