Coverage Report

Created: 2026-03-08 06:40

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/pylifecycle.c
Line
Count
Source
1
/* Python interpreter top-level routines, including init/exit */
2
3
#include "Python.h"
4
#include "pycore_audit.h"         // _PySys_ClearAuditHooks()
5
#include "pycore_call.h"          // _PyObject_CallMethod()
6
#include "pycore_ceval.h"         // _PyEval_FiniGIL()
7
#include "pycore_codecs.h"        // _PyCodec_Lookup()
8
#include "pycore_context.h"       // _PyContext_Init()
9
#include "pycore_dict.h"          // _PyDict_Fini()
10
#include "pycore_exceptions.h"    // _PyExc_InitTypes()
11
#include "pycore_fileutils.h"     // _Py_ResetForceASCII()
12
#include "pycore_floatobject.h"   // _PyFloat_InitTypes()
13
#include "pycore_freelist.h"      // _PyObject_ClearFreeLists()
14
#include "pycore_global_objects_fini_generated.h"  // _PyStaticObjects_CheckRefcnt()
15
#include "pycore_initconfig.h"    // _PyStatus_OK()
16
#include "pycore_interpolation.h" // _PyInterpolation_InitTypes()
17
#include "pycore_long.h"          // _PyLong_InitTypes()
18
#include "pycore_moduleobject.h"  // _PyModule_InitModuleDictWatcher()
19
#include "pycore_object.h"        // _PyDebug_PrintTotalRefs()
20
#include "pycore_obmalloc.h"      // _PyMem_init_obmalloc()
21
#include "pycore_optimizer.h"     // _Py_Executors_InvalidateAll
22
#include "pycore_pathconfig.h"    // _PyPathConfig_UpdateGlobal()
23
#include "pycore_pyerrors.h"      // _PyErr_Occurred()
24
#include "pycore_pylifecycle.h"   // _PyErr_Print()
25
#include "pycore_pymem.h"         // _PyObject_DebugMallocStats()
26
#include "pycore_pystate.h"       // _PyThreadState_GET()
27
#include "pycore_runtime.h"       // _Py_ID()
28
#include "pycore_runtime_init.h"  // _PyRuntimeState_INIT
29
#include "pycore_setobject.h"     // _PySet_NextEntry()
30
#include "pycore_stats.h"         // _PyStats_InterpInit()
31
#include "pycore_sysmodule.h"     // _PySys_ClearAttrString()
32
#include "pycore_traceback.h"     // _Py_DumpTracebackThreads()
33
#include "pycore_typeobject.h"    // _PyTypes_InitTypes()
34
#include "pycore_typevarobject.h" // _Py_clear_generic_types()
35
#include "pycore_unicodeobject.h" // _PyUnicode_InitTypes()
36
#include "pycore_uniqueid.h"      // _PyObject_FinalizeUniqueIdPool()
37
#include "pycore_warnings.h"      // _PyWarnings_InitState()
38
#include "pycore_weakref.h"       // _PyWeakref_GET_REF()
39
#ifdef _Py_JIT
40
#include "pycore_jit.h"           // _PyJIT_Fini()
41
#endif
42
43
#include "opcode.h"
44
45
#include <locale.h>               // setlocale()
46
#include <stdlib.h>               // getenv()
47
#ifdef HAVE_UNISTD_H
48
#  include <unistd.h>             // isatty()
49
#endif
50
51
#if defined(__APPLE__)
52
#  include <AvailabilityMacros.h>
53
#  include <TargetConditionals.h>
54
#  include <mach-o/loader.h>
55
// The os_log unified logging APIs were introduced in macOS 10.12, iOS 10.0,
56
// tvOS 10.0, and watchOS 3.0;
57
#  if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE
58
#    define HAS_APPLE_SYSTEM_LOG 1
59
#  elif defined(TARGET_OS_OSX) && TARGET_OS_OSX
60
#    if defined(MAC_OS_X_VERSION_10_12) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_12
61
#      define HAS_APPLE_SYSTEM_LOG 1
62
#    else
63
#      define HAS_APPLE_SYSTEM_LOG 0
64
#    endif
65
#  else
66
#    define HAS_APPLE_SYSTEM_LOG 0
67
#  endif
68
69
#  if HAS_APPLE_SYSTEM_LOG
70
#    include <os/log.h>
71
#  endif
72
#endif
73
74
#ifdef HAVE_SIGNAL_H
75
#  include <signal.h>             // SIG_IGN
76
#endif
77
78
#ifdef HAVE_LANGINFO_H
79
#  include <langinfo.h>           // nl_langinfo(CODESET)
80
#endif
81
82
#ifdef HAVE_FCNTL_H
83
#  include <fcntl.h>              // F_GETFD
84
#endif
85
86
#ifdef MS_WINDOWS
87
#  undef BYTE
88
#endif
89
90
0
#define PUTS(fd, str) (void)_Py_write_noraise(fd, str, (int)strlen(str))
91
92
93
/* Forward declarations */
94
static PyStatus add_main_module(PyInterpreterState *interp);
95
static PyStatus init_import_site(void);
96
static PyStatus init_set_builtins_open(void);
97
static PyStatus init_sys_streams(PyThreadState *tstate);
98
#ifdef __ANDROID__
99
static PyStatus init_android_streams(PyThreadState *tstate);
100
#endif
101
#if defined(__APPLE__) && HAS_APPLE_SYSTEM_LOG
102
static PyStatus init_apple_streams(PyThreadState *tstate);
103
#endif
104
static void wait_for_thread_shutdown(PyThreadState *tstate);
105
static void finalize_subinterpreters(void);
106
static void call_ll_exitfuncs(_PyRuntimeState *runtime);
107
108
109
/* The following places the `_PyRuntime` structure in a location that can be
110
 * found without any external information. This is meant to ease access to the
111
 * interpreter state for various runtime debugging tools, but is *not* an
112
 * officially supported feature */
113
114
/* Suppress deprecation warning for PyBytesObject.ob_shash */
115
_Py_COMP_DIAG_PUSH
116
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
117
118
GENERATE_DEBUG_SECTION(PyRuntime, _PyRuntimeState _PyRuntime)
119
= _PyRuntimeState_INIT(_PyRuntime, _Py_Debug_Cookie);
120
_Py_COMP_DIAG_POP
121
122
123
static int runtime_initialized = 0;
124
125
PyStatus
126
_PyRuntime_Initialize(void)
127
2.61k
{
128
    /* XXX We only initialize once in the process, which aligns with
129
       the static initialization of the former globals now found in
130
       _PyRuntime.  However, _PyRuntime *should* be initialized with
131
       every Py_Initialize() call, but doing so breaks the runtime.
132
       This is because the runtime state is not properly finalized
133
       currently. */
134
2.61k
    if (runtime_initialized) {
135
2.58k
        return _PyStatus_OK();
136
2.58k
    }
137
34
    runtime_initialized = 1;
138
139
34
    return _PyRuntimeState_Init(&_PyRuntime);
140
2.61k
}
141
142
void
143
_PyRuntime_Finalize(void)
144
0
{
145
0
    _PyRuntimeState_Fini(&_PyRuntime);
146
0
    runtime_initialized = 0;
147
0
}
148
149
int
150
Py_IsFinalizing(void)
151
0
{
152
0
    return _PyRuntimeState_GetFinalizing(&_PyRuntime) != NULL;
153
0
}
154
155
/* Hack to force loading of object files */
156
int (*_PyOS_mystrnicmp_hack)(const char *, const char *, Py_ssize_t) = \
157
    PyOS_mystrnicmp; /* Python/pystrcmp.o */
158
159
160
/* APIs to access the initialization flags
161
 *
162
 * Can be called prior to Py_Initialize.
163
 */
164
165
int
166
_Py_IsCoreInitialized(void)
167
0
{
168
0
    return _PyRuntime.core_initialized;
169
0
}
170
171
int
172
Py_IsInitialized(void)
173
0
{
174
0
    return _PyRuntime.initialized;
175
0
}
176
177
178
/* Helper functions to better handle the legacy C locale
179
 *
180
 * The legacy C locale assumes ASCII as the default text encoding, which
181
 * causes problems not only for the CPython runtime, but also other
182
 * components like GNU readline.
183
 *
184
 * Accordingly, when the CLI detects it, it attempts to coerce it to a
185
 * more capable UTF-8 based alternative as follows:
186
 *
187
 *     if (_Py_LegacyLocaleDetected()) {
188
 *         _Py_CoerceLegacyLocale();
189
 *     }
190
 *
191
 * See the documentation of the PYTHONCOERCECLOCALE setting for more details.
192
 *
193
 * Locale coercion also impacts the default error handler for the standard
194
 * streams: while the usual default is "strict", the default for the legacy
195
 * C locale and for any of the coercion target locales is "surrogateescape".
196
 */
197
198
int
199
_Py_LegacyLocaleDetected(int warn)
200
0
{
201
0
#ifndef MS_WINDOWS
202
0
    if (!warn) {
203
0
        const char *locale_override = getenv("LC_ALL");
204
0
        if (locale_override != NULL && *locale_override != '\0') {
205
            /* Don't coerce C locale if the LC_ALL environment variable
206
               is set */
207
0
            return 0;
208
0
        }
209
0
    }
210
211
    /* On non-Windows systems, the C locale is considered a legacy locale */
212
    /* XXX (ncoghlan): some platforms (notably Mac OS X) don't appear to treat
213
     *                 the POSIX locale as a simple alias for the C locale, so
214
     *                 we may also want to check for that explicitly.
215
     */
216
0
    const char *ctype_loc = setlocale(LC_CTYPE, NULL);
217
0
    if (ctype_loc == NULL) {
218
0
        return 0;
219
0
    }
220
0
    return (strcmp(ctype_loc, "C") == 0 || strcmp(ctype_loc, "POSIX") == 0);
221
#else
222
    /* Windows uses code pages instead of locales, so no locale is legacy */
223
    return 0;
224
#endif
225
0
}
226
227
#ifndef MS_WINDOWS
228
static const char *_C_LOCALE_WARNING =
229
    "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII "
230
    "encoding), which may cause Unicode compatibility problems. Using C.UTF-8, "
231
    "C.utf8, or UTF-8 (if available) as alternative Unicode-compatible "
232
    "locales is recommended.\n";
233
234
static void
235
emit_stderr_warning_for_legacy_locale(_PyRuntimeState *runtime)
236
34
{
237
34
    const PyPreConfig *preconfig = &runtime->preconfig;
238
34
    if (preconfig->coerce_c_locale_warn && _Py_LegacyLocaleDetected(1)) {
239
0
        PySys_FormatStderr("%s", _C_LOCALE_WARNING);
240
0
    }
241
34
}
242
#endif   /* !defined(MS_WINDOWS) */
243
244
typedef struct _CandidateLocale {
245
    const char *locale_name; /* The locale to try as a coercion target */
246
} _LocaleCoercionTarget;
247
248
static _LocaleCoercionTarget _TARGET_LOCALES[] = {
249
    {"C.UTF-8"},
250
    {"C.utf8"},
251
    {"UTF-8"},
252
    {NULL}
253
};
254
255
256
int
257
_Py_IsLocaleCoercionTarget(const char *ctype_loc)
258
0
{
259
0
    const _LocaleCoercionTarget *target = NULL;
260
0
    for (target = _TARGET_LOCALES; target->locale_name; target++) {
261
0
        if (strcmp(ctype_loc, target->locale_name) == 0) {
262
0
            return 1;
263
0
        }
264
0
    }
265
0
    return 0;
266
0
}
267
268
269
#ifdef PY_COERCE_C_LOCALE
270
static const char C_LOCALE_COERCION_WARNING[] =
271
    "Python detected LC_CTYPE=C: LC_CTYPE coerced to %.20s (set another locale "
272
    "or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).\n";
273
274
static int
275
_coerce_default_locale_settings(int warn, const _LocaleCoercionTarget *target)
276
0
{
277
0
    const char *newloc = target->locale_name;
278
279
    /* Reset locale back to currently configured defaults */
280
0
    _Py_SetLocaleFromEnv(LC_ALL);
281
282
    /* Set the relevant locale environment variable */
283
0
    if (setenv("LC_CTYPE", newloc, 1)) {
284
0
        fprintf(stderr,
285
0
                "Error setting LC_CTYPE, skipping C locale coercion\n");
286
0
        return 0;
287
0
    }
288
0
    if (warn) {
289
0
        fprintf(stderr, C_LOCALE_COERCION_WARNING, newloc);
290
0
    }
291
292
    /* Reconfigure with the overridden environment variables */
293
0
    _Py_SetLocaleFromEnv(LC_ALL);
294
0
    return 1;
295
0
}
296
#endif
297
298
int
299
_Py_CoerceLegacyLocale(int warn)
300
0
{
301
0
    int coerced = 0;
302
0
#ifdef PY_COERCE_C_LOCALE
303
0
    char *oldloc = NULL;
304
305
0
    oldloc = _PyMem_RawStrdup(setlocale(LC_CTYPE, NULL));
306
0
    if (oldloc == NULL) {
307
0
        return coerced;
308
0
    }
309
310
0
    const char *locale_override = getenv("LC_ALL");
311
0
    if (locale_override == NULL || *locale_override == '\0') {
312
        /* LC_ALL is also not set (or is set to an empty string) */
313
0
        const _LocaleCoercionTarget *target = NULL;
314
0
        for (target = _TARGET_LOCALES; target->locale_name; target++) {
315
0
            const char *new_locale = setlocale(LC_CTYPE,
316
0
                                               target->locale_name);
317
0
            if (new_locale != NULL) {
318
0
#if !defined(_Py_FORCE_UTF8_LOCALE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
319
                /* Also ensure that nl_langinfo works in this locale */
320
0
                char *codeset = nl_langinfo(CODESET);
321
0
                if (!codeset || *codeset == '\0') {
322
                    /* CODESET is not set or empty, so skip coercion */
323
0
                    new_locale = NULL;
324
0
                    _Py_SetLocaleFromEnv(LC_CTYPE);
325
0
                    continue;
326
0
                }
327
0
#endif
328
                /* Successfully configured locale, so make it the default */
329
0
                coerced = _coerce_default_locale_settings(warn, target);
330
0
                goto done;
331
0
            }
332
0
        }
333
0
    }
334
    /* No C locale warning here, as Py_Initialize will emit one later */
335
336
0
    setlocale(LC_CTYPE, oldloc);
337
338
0
done:
339
0
    PyMem_RawFree(oldloc);
340
0
#endif
341
0
    return coerced;
342
0
}
343
344
/* _Py_SetLocaleFromEnv() is a wrapper around setlocale(category, "") to
345
 * isolate the idiosyncrasies of different libc implementations. It reads the
346
 * appropriate environment variable and uses its value to select the locale for
347
 * 'category'. */
348
char *
349
_Py_SetLocaleFromEnv(int category)
350
68
{
351
68
    char *res;
352
#ifdef __ANDROID__
353
    const char *locale;
354
    const char **pvar;
355
#ifdef PY_COERCE_C_LOCALE
356
    const char *coerce_c_locale;
357
#endif
358
    const char *utf8_locale = "C.UTF-8";
359
    const char *env_var_set[] = {
360
        "LC_ALL",
361
        "LC_CTYPE",
362
        "LANG",
363
        NULL,
364
    };
365
366
    /* Android setlocale(category, "") doesn't check the environment variables
367
     * and incorrectly sets the "C" locale at API 24 and older APIs. We only
368
     * check the environment variables listed in env_var_set. */
369
    for (pvar=env_var_set; *pvar; pvar++) {
370
        locale = getenv(*pvar);
371
        if (locale != NULL && *locale != '\0') {
372
            if (strcmp(locale, utf8_locale) == 0 ||
373
                    strcmp(locale, "en_US.UTF-8") == 0) {
374
                return setlocale(category, utf8_locale);
375
            }
376
            return setlocale(category, "C");
377
        }
378
    }
379
380
    /* Android uses UTF-8, so explicitly set the locale to C.UTF-8 if none of
381
     * LC_ALL, LC_CTYPE, or LANG is set to a non-empty string.
382
     * Quote from POSIX section "8.2 Internationalization Variables":
383
     * "4. If the LANG environment variable is not set or is set to the empty
384
     * string, the implementation-defined default locale shall be used." */
385
386
#ifdef PY_COERCE_C_LOCALE
387
    coerce_c_locale = getenv("PYTHONCOERCECLOCALE");
388
    if (coerce_c_locale == NULL || strcmp(coerce_c_locale, "0") != 0) {
389
        /* Some other ported code may check the environment variables (e.g. in
390
         * extension modules), so we make sure that they match the locale
391
         * configuration */
392
        if (setenv("LC_CTYPE", utf8_locale, 1)) {
393
            fprintf(stderr, "Warning: failed setting the LC_CTYPE "
394
                            "environment variable to %s\n", utf8_locale);
395
        }
396
    }
397
#endif
398
    res = setlocale(category, utf8_locale);
399
#else /* !defined(__ANDROID__) */
400
68
    res = setlocale(category, "");
401
68
#endif
402
68
    _Py_ResetForceASCII();
403
68
    return res;
404
68
}
405
406
407
static int
408
interpreter_update_config(PyThreadState *tstate, int only_update_path_config)
409
34
{
410
34
    const PyConfig *config = &tstate->interp->config;
411
412
34
    if (!only_update_path_config) {
413
0
        PyStatus status = _PyConfig_Write(config, tstate->interp->runtime);
414
0
        if (_PyStatus_EXCEPTION(status)) {
415
0
            _PyErr_SetFromPyStatus(status);
416
0
            return -1;
417
0
        }
418
0
    }
419
420
34
    if (_Py_IsMainInterpreter(tstate->interp)) {
421
34
        PyStatus status = _PyPathConfig_UpdateGlobal(config);
422
34
        if (_PyStatus_EXCEPTION(status)) {
423
0
            _PyErr_SetFromPyStatus(status);
424
0
            return -1;
425
0
        }
426
34
    }
427
428
34
    tstate->interp->long_state.max_str_digits = config->int_max_str_digits;
429
430
    // Update the sys module for the new configuration
431
34
    if (_PySys_UpdateConfig(tstate) < 0) {
432
0
        return -1;
433
0
    }
434
34
    return 0;
435
34
}
436
437
438
/* Global initializations.  Can be undone by Py_Finalize().  Don't
439
   call this twice without an intervening Py_Finalize() call.
440
441
   Every call to Py_InitializeFromConfig, Py_Initialize or Py_InitializeEx
442
   must have a corresponding call to Py_Finalize.
443
444
   Locking: you must hold the interpreter lock while calling these APIs.
445
   (If the lock has not yet been initialized, that's equivalent to
446
   having the lock, but you cannot use multiple threads.)
447
448
*/
449
450
static PyStatus
451
pyinit_core_reconfigure(_PyRuntimeState *runtime,
452
                        PyThreadState **tstate_p,
453
                        const PyConfig *config)
454
0
{
455
0
    PyStatus status;
456
0
    PyThreadState *tstate = _PyThreadState_GET();
457
0
    if (!tstate) {
458
0
        return _PyStatus_ERR("failed to read thread state");
459
0
    }
460
0
    *tstate_p = tstate;
461
462
0
    PyInterpreterState *interp = tstate->interp;
463
0
    if (interp == NULL) {
464
0
        return _PyStatus_ERR("can't make main interpreter");
465
0
    }
466
0
    assert(interp->_ready);
467
468
0
    status = _PyConfig_Write(config, runtime);
469
0
    if (_PyStatus_EXCEPTION(status)) {
470
0
        return status;
471
0
    }
472
473
0
    status = _PyConfig_Copy(&interp->config, config);
474
0
    if (_PyStatus_EXCEPTION(status)) {
475
0
        return status;
476
0
    }
477
0
    config = _PyInterpreterState_GetConfig(interp);
478
479
0
    if (config->_install_importlib) {
480
0
        status = _PyPathConfig_UpdateGlobal(config);
481
0
        if (_PyStatus_EXCEPTION(status)) {
482
0
            return status;
483
0
        }
484
0
    }
485
0
    return _PyStatus_OK();
486
0
}
487
488
489
static PyStatus
490
pycore_init_runtime(_PyRuntimeState *runtime,
491
                    const PyConfig *config)
492
34
{
493
34
    if (runtime->initialized) {
494
0
        return _PyStatus_ERR("main interpreter already initialized");
495
0
    }
496
497
34
    PyStatus status = _PyConfig_Write(config, runtime);
498
34
    if (_PyStatus_EXCEPTION(status)) {
499
0
        return status;
500
0
    }
501
502
    /* Py_Finalize leaves _Py_Finalizing set in order to help daemon
503
     * threads behave a little more gracefully at interpreter shutdown.
504
     * We clobber it here so the new interpreter can start with a clean
505
     * slate.
506
     *
507
     * However, this may still lead to misbehaviour if there are daemon
508
     * threads still hanging around from a previous Py_Initialize/Finalize
509
     * pair :(
510
     */
511
34
    _PyRuntimeState_SetFinalizing(runtime, NULL);
512
513
34
    _Py_InitVersion();
514
34
    _Py_DumpTraceback_Init();
515
516
34
    status = _Py_HashRandomization_Init(config);
517
34
    if (_PyStatus_EXCEPTION(status)) {
518
0
        return status;
519
0
    }
520
521
34
    status = _PyImport_Init();
522
34
    if (_PyStatus_EXCEPTION(status)) {
523
0
        return status;
524
0
    }
525
526
34
    status = _PyInterpreterState_Enable(runtime);
527
34
    if (_PyStatus_EXCEPTION(status)) {
528
0
        return status;
529
0
    }
530
34
    return _PyStatus_OK();
531
34
}
532
533
534
static PyStatus
535
init_interp_settings(PyInterpreterState *interp,
536
                     const PyInterpreterConfig *config)
537
34
{
538
34
    assert(interp->feature_flags == 0);
539
540
34
    if (config->use_main_obmalloc) {
541
34
        interp->feature_flags |= Py_RTFLAGS_USE_MAIN_OBMALLOC;
542
34
    }
543
0
    else if (!config->check_multi_interp_extensions) {
544
        /* The reason: PyModuleDef.m_base.m_copy leaks objects between
545
           interpreters. */
546
0
        return _PyStatus_ERR("per-interpreter obmalloc does not support "
547
0
                             "single-phase init extension modules");
548
0
    }
549
#ifdef Py_GIL_DISABLED
550
    if (!_Py_IsMainInterpreter(interp) &&
551
        !config->check_multi_interp_extensions)
552
    {
553
        return _PyStatus_ERR("The free-threaded build does not support "
554
                             "single-phase init extension modules in "
555
                             "subinterpreters");
556
    }
557
#endif
558
559
34
    if (config->allow_fork) {
560
34
        interp->feature_flags |= Py_RTFLAGS_FORK;
561
34
    }
562
34
    if (config->allow_exec) {
563
34
        interp->feature_flags |= Py_RTFLAGS_EXEC;
564
34
    }
565
    // Note that fork+exec is always allowed.
566
567
34
    if (config->allow_threads) {
568
34
        interp->feature_flags |= Py_RTFLAGS_THREADS;
569
34
    }
570
34
    if (config->allow_daemon_threads) {
571
34
        interp->feature_flags |= Py_RTFLAGS_DAEMON_THREADS;
572
34
    }
573
574
34
    if (config->check_multi_interp_extensions) {
575
0
        interp->feature_flags |= Py_RTFLAGS_MULTI_INTERP_EXTENSIONS;
576
0
    }
577
578
34
    switch (config->gil) {
579
0
    case PyInterpreterConfig_DEFAULT_GIL: break;
580
0
    case PyInterpreterConfig_SHARED_GIL: break;
581
34
    case PyInterpreterConfig_OWN_GIL: break;
582
0
    default:
583
0
        return _PyStatus_ERR("invalid interpreter config 'gil' value");
584
34
    }
585
586
34
    return _PyStatus_OK();
587
34
}
588
589
590
static void
591
init_interp_create_gil(PyThreadState *tstate, int gil)
592
34
{
593
    /* finalize_interp_delete() comment explains why _PyEval_FiniGIL() is
594
       only called here. */
595
    // XXX This is broken with a per-interpreter GIL.
596
34
    _PyEval_FiniGIL(tstate->interp);
597
598
    /* Auto-thread-state API */
599
34
    _PyGILState_SetTstate(tstate);
600
601
34
    int own_gil = (gil == PyInterpreterConfig_OWN_GIL);
602
603
    /* Create the GIL and take it */
604
34
    _PyEval_InitGIL(tstate, own_gil);
605
34
}
606
607
static int
608
builtins_dict_watcher(PyDict_WatchEvent event, PyObject *dict, PyObject *key, PyObject *new_value)
609
0
{
610
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
611
#ifdef _Py_TIER2
612
    if (interp->rare_events.builtin_dict < _Py_MAX_ALLOWED_BUILTINS_MODIFICATIONS) {
613
        _Py_Executors_InvalidateAll(interp, 1);
614
    }
615
#endif
616
0
    RARE_EVENT_INTERP_INC(interp, builtin_dict);
617
0
    return 0;
618
0
}
619
620
static PyStatus
621
pycore_create_interpreter(_PyRuntimeState *runtime,
622
                          const PyConfig *src_config,
623
                          PyThreadState **tstate_p)
624
34
{
625
34
    PyStatus status;
626
34
    PyInterpreterState *interp;
627
34
    status = _PyInterpreterState_New(NULL, &interp);
628
34
    if (_PyStatus_EXCEPTION(status)) {
629
0
        return status;
630
0
    }
631
34
    assert(interp != NULL);
632
34
    assert(_Py_IsMainInterpreter(interp));
633
34
    _PyInterpreterState_SetWhence(interp, _PyInterpreterState_WHENCE_RUNTIME);
634
34
    interp->_ready = 1;
635
636
    /* Initialize the module dict watcher early, before any modules are created */
637
34
    if (_PyModule_InitModuleDictWatcher(interp) != 0) {
638
0
        return _PyStatus_ERR("failed to initialize module dict watcher");
639
0
    }
640
641
34
    status = _PyConfig_Copy(&interp->config, src_config);
642
34
    if (_PyStatus_EXCEPTION(status)) {
643
0
        return status;
644
0
    }
645
646
    /* Auto-thread-state API */
647
34
    status = _PyGILState_Init(interp);
648
34
    if (_PyStatus_EXCEPTION(status)) {
649
0
        return status;
650
0
    }
651
652
34
    PyInterpreterConfig config = _PyInterpreterConfig_LEGACY_INIT;
653
    // The main interpreter always has its own GIL and supports single-phase
654
    // init extensions.
655
34
    config.gil = PyInterpreterConfig_OWN_GIL;
656
34
    config.check_multi_interp_extensions = 0;
657
34
    status = init_interp_settings(interp, &config);
658
34
    if (_PyStatus_EXCEPTION(status)) {
659
0
        return status;
660
0
    }
661
662
    // This could be done in init_interpreter() (in pystate.c) if it
663
    // didn't depend on interp->feature_flags being set already.
664
34
    status = _PyObject_InitState(interp);
665
34
    if (_PyStatus_EXCEPTION(status)) {
666
0
        return status;
667
0
    }
668
669
#ifdef Py_STATS
670
    // initialize pystats.  This must be done after the settings are loaded.
671
    status = _PyStats_InterpInit(interp);
672
    if (_PyStatus_EXCEPTION(status)) {
673
        return status;
674
    }
675
#endif
676
677
    // initialize the interp->obmalloc state.  This must be done after
678
    // the settings are loaded (so that feature_flags are set) but before
679
    // any calls are made to obmalloc functions.
680
34
    if (_PyMem_init_obmalloc(interp) < 0) {
681
0
        return _PyStatus_NO_MEMORY();
682
0
    }
683
684
34
    status = _PyTraceMalloc_Init();
685
34
    if (_PyStatus_EXCEPTION(status)) {
686
0
        return status;
687
0
    }
688
689
34
    PyThreadState *tstate = _PyThreadState_New(interp,
690
34
                                               _PyThreadState_WHENCE_INIT);
691
34
    if (tstate == NULL) {
692
0
        return _PyStatus_ERR("can't make first thread");
693
0
    }
694
34
    runtime->main_tstate = tstate;
695
34
    _PyThreadState_Bind(tstate);
696
697
34
    init_interp_create_gil(tstate, config.gil);
698
699
34
    *tstate_p = tstate;
700
34
    return _PyStatus_OK();
701
34
}
702
703
704
static PyStatus
705
pycore_init_global_objects(PyInterpreterState *interp)
706
34
{
707
34
    PyStatus status;
708
709
34
    _PyFloat_InitState(interp);
710
711
34
    status = _PyUnicode_InitGlobalObjects(interp);
712
34
    if (_PyStatus_EXCEPTION(status)) {
713
0
        return status;
714
0
    }
715
716
34
    _PyUnicode_InitState(interp);
717
718
34
    if (_Py_IsMainInterpreter(interp)) {
719
34
        _Py_GetConstant_Init();
720
34
    }
721
722
34
    return _PyStatus_OK();
723
34
}
724
725
726
static PyStatus
727
pycore_init_types(PyInterpreterState *interp)
728
34
{
729
34
    PyStatus status;
730
731
34
    status = _PyTypes_InitTypes(interp);
732
34
    if (_PyStatus_EXCEPTION(status)) {
733
0
        return status;
734
0
    }
735
736
34
    status = _PyLong_InitTypes(interp);
737
34
    if (_PyStatus_EXCEPTION(status)) {
738
0
        return status;
739
0
    }
740
741
34
    status = _PyUnicode_InitTypes(interp);
742
34
    if (_PyStatus_EXCEPTION(status)) {
743
0
        return status;
744
0
    }
745
746
34
    status = _PyFloat_InitTypes(interp);
747
34
    if (_PyStatus_EXCEPTION(status)) {
748
0
        return status;
749
0
    }
750
751
34
    if (_PyExc_InitTypes(interp) < 0) {
752
0
        return _PyStatus_ERR("failed to initialize an exception type");
753
0
    }
754
755
34
    status = _PyExc_InitGlobalObjects(interp);
756
34
    if (_PyStatus_EXCEPTION(status)) {
757
0
        return status;
758
0
    }
759
760
34
    status = _PyExc_InitState(interp);
761
34
    if (_PyStatus_EXCEPTION(status)) {
762
0
        return status;
763
0
    }
764
765
34
    status = _PyErr_InitTypes(interp);
766
34
    if (_PyStatus_EXCEPTION(status)) {
767
0
        return status;
768
0
    }
769
770
34
    status = _PyContext_Init(interp);
771
34
    if (_PyStatus_EXCEPTION(status)) {
772
0
        return status;
773
0
    }
774
775
34
    status = _PyXI_InitTypes(interp);
776
34
    if (_PyStatus_EXCEPTION(status)) {
777
0
        return status;
778
0
    }
779
780
34
    status = _PyInterpolation_InitTypes(interp);
781
34
    if (_PyStatus_EXCEPTION(status)) {
782
0
        return status;
783
0
    }
784
785
34
    status = _PyDateTime_InitTypes(interp);
786
34
    if (_PyStatus_EXCEPTION(status)) {
787
0
        return status;
788
0
    }
789
790
34
    return _PyStatus_OK();
791
34
}
792
793
static PyStatus
794
pycore_init_builtins(PyThreadState *tstate)
795
34
{
796
34
    PyInterpreterState *interp = tstate->interp;
797
798
34
    PyObject *bimod = _PyBuiltin_Init(interp);
799
34
    if (bimod == NULL) {
800
0
        goto error;
801
0
    }
802
803
34
    PyObject *modules = _PyImport_GetModules(interp);
804
34
    if (_PyImport_FixupBuiltin(tstate, bimod, "builtins", modules) < 0) {
805
0
        goto error;
806
0
    }
807
808
34
    PyObject *builtins_dict = PyModule_GetDict(bimod);
809
34
    if (builtins_dict == NULL) {
810
0
        goto error;
811
0
    }
812
34
    interp->builtins = Py_NewRef(builtins_dict);
813
814
34
    PyObject *isinstance = PyDict_GetItemWithError(builtins_dict, &_Py_ID(isinstance));
815
34
    if (!isinstance) {
816
0
        goto error;
817
0
    }
818
34
    interp->callable_cache.isinstance = isinstance;
819
820
34
    PyObject *len = PyDict_GetItemWithError(builtins_dict, &_Py_ID(len));
821
34
    if (!len) {
822
0
        goto error;
823
0
    }
824
34
    interp->callable_cache.len = len;
825
826
34
    PyObject *all = PyDict_GetItemWithError(builtins_dict, &_Py_ID(all));
827
34
    if (!all) {
828
0
        goto error;
829
0
    }
830
831
34
    PyObject *any = PyDict_GetItemWithError(builtins_dict, &_Py_ID(any));
832
34
    if (!any) {
833
0
        goto error;
834
0
    }
835
836
34
    interp->common_consts[CONSTANT_ASSERTIONERROR] = PyExc_AssertionError;
837
34
    interp->common_consts[CONSTANT_NOTIMPLEMENTEDERROR] = PyExc_NotImplementedError;
838
34
    interp->common_consts[CONSTANT_BUILTIN_TUPLE] = (PyObject*)&PyTuple_Type;
839
34
    interp->common_consts[CONSTANT_BUILTIN_ALL] = all;
840
34
    interp->common_consts[CONSTANT_BUILTIN_ANY] = any;
841
34
    interp->common_consts[CONSTANT_BUILTIN_LIST] = (PyObject*)&PyList_Type;
842
34
    interp->common_consts[CONSTANT_BUILTIN_SET] = (PyObject*)&PySet_Type;
843
844
272
    for (int i=0; i < NUM_COMMON_CONSTANTS; i++) {
845
238
        assert(interp->common_consts[i] != NULL);
846
238
    }
847
848
34
    PyObject *list_append = _PyType_Lookup(&PyList_Type, &_Py_ID(append));
849
34
    if (list_append == NULL) {
850
0
        goto error;
851
0
    }
852
34
    interp->callable_cache.list_append = list_append;
853
854
34
    PyObject *object__getattribute__ = _PyType_Lookup(&PyBaseObject_Type, &_Py_ID(__getattribute__));
855
34
    if (object__getattribute__ == NULL) {
856
0
        goto error;
857
0
    }
858
34
    interp->callable_cache.object__getattribute__ = object__getattribute__;
859
860
34
    if (_PyType_InitSlotDefs(interp) < 0) {
861
0
        return _PyStatus_ERR("failed to init slotdefs");
862
0
    }
863
864
34
    if (_PyBuiltins_AddExceptions(bimod) < 0) {
865
0
        return _PyStatus_ERR("failed to add exceptions to builtins");
866
0
    }
867
868
34
    interp->builtins_copy = PyDict_Copy(interp->builtins);
869
34
    if (interp->builtins_copy == NULL) {
870
0
        goto error;
871
0
    }
872
34
    Py_DECREF(bimod);
873
874
34
    if (_PyImport_InitDefaultImportFunc(interp) < 0) {
875
0
        goto error;
876
0
    }
877
878
34
    assert(!_PyErr_Occurred(tstate));
879
34
    return _PyStatus_OK();
880
881
0
error:
882
0
    Py_XDECREF(bimod);
883
0
    return _PyStatus_ERR("can't initialize builtins module");
884
34
}
885
886
887
static PyStatus
888
pycore_interp_init(PyThreadState *tstate)
889
34
{
890
34
    _PyThreadStateImpl *_tstate = (_PyThreadStateImpl *)tstate;
891
34
    if (_tstate->c_stack_hard_limit == 0) {
892
0
        _Py_InitializeRecursionLimits(tstate);
893
0
    }
894
34
    PyInterpreterState *interp = tstate->interp;
895
34
    PyStatus status;
896
34
    PyObject *sysmod = NULL;
897
898
    // Create singletons before the first PyType_Ready() call, since
899
    // PyType_Ready() uses singletons like the Unicode empty string (tp_doc)
900
    // and the empty tuple singletons (tp_bases).
901
34
    status = pycore_init_global_objects(interp);
902
34
    if (_PyStatus_EXCEPTION(status)) {
903
0
        return status;
904
0
    }
905
906
34
    status = _PyCode_Init(interp);
907
34
    if (_PyStatus_EXCEPTION(status)) {
908
0
        return status;
909
0
    }
910
911
34
    status = _PyDtoa_Init(interp);
912
34
    if (_PyStatus_EXCEPTION(status)) {
913
0
        return status;
914
0
    }
915
916
    // The GC must be initialized before the first GC collection.
917
34
    status = _PyGC_Init(interp);
918
34
    if (_PyStatus_EXCEPTION(status)) {
919
0
        return status;
920
0
    }
921
922
34
    status = pycore_init_types(interp);
923
34
    if (_PyStatus_EXCEPTION(status)) {
924
0
        goto done;
925
0
    }
926
927
34
    if (_PyWarnings_InitState(interp) < 0) {
928
0
        return _PyStatus_ERR("can't initialize warnings");
929
0
    }
930
931
34
    status = _PyAtExit_Init(interp);
932
34
    if (_PyStatus_EXCEPTION(status)) {
933
0
        return status;
934
0
    }
935
936
34
    status = _PySys_Create(tstate, &sysmod);
937
34
    if (_PyStatus_EXCEPTION(status)) {
938
0
        goto done;
939
0
    }
940
941
34
    status = pycore_init_builtins(tstate);
942
34
    if (_PyStatus_EXCEPTION(status)) {
943
0
        goto done;
944
0
    }
945
946
34
    status = _PyXI_Init(interp);
947
34
    if (_PyStatus_EXCEPTION(status)) {
948
0
        goto done;
949
0
    }
950
951
34
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
952
953
34
    status = _PyImport_InitCore(tstate, sysmod, config->_install_importlib);
954
34
    if (_PyStatus_EXCEPTION(status)) {
955
0
        goto done;
956
0
    }
957
958
34
done:
959
    /* sys.modules['sys'] contains a strong reference to the module */
960
34
    Py_XDECREF(sysmod);
961
34
    return status;
962
34
}
963
964
965
static PyStatus
966
pyinit_config(_PyRuntimeState *runtime,
967
              PyThreadState **tstate_p,
968
              const PyConfig *config)
969
34
{
970
34
    PyStatus status = pycore_init_runtime(runtime, config);
971
34
    if (_PyStatus_EXCEPTION(status)) {
972
0
        return status;
973
0
    }
974
975
34
    PyThreadState *tstate;
976
34
    status = pycore_create_interpreter(runtime, config, &tstate);
977
34
    if (_PyStatus_EXCEPTION(status)) {
978
0
        return status;
979
0
    }
980
34
    *tstate_p = tstate;
981
982
34
    status = pycore_interp_init(tstate);
983
34
    if (_PyStatus_EXCEPTION(status)) {
984
0
        return status;
985
0
    }
986
987
    /* Only when we get here is the runtime core fully initialized */
988
34
    runtime->core_initialized = 1;
989
34
    return _PyStatus_OK();
990
34
}
991
992
993
PyStatus
994
_Py_PreInitializeFromPyArgv(const PyPreConfig *src_config, const _PyArgv *args)
995
34
{
996
34
    PyStatus status;
997
998
34
    if (src_config == NULL) {
999
0
        return _PyStatus_ERR("preinitialization config is NULL");
1000
0
    }
1001
1002
34
    status = _PyRuntime_Initialize();
1003
34
    if (_PyStatus_EXCEPTION(status)) {
1004
0
        return status;
1005
0
    }
1006
34
    _PyRuntimeState *runtime = &_PyRuntime;
1007
1008
34
    if (runtime->preinitialized) {
1009
        /* If it's already configured: ignored the new configuration */
1010
0
        return _PyStatus_OK();
1011
0
    }
1012
1013
    /* Note: preinitializing remains 1 on error, it is only set to 0
1014
       at exit on success. */
1015
34
    runtime->preinitializing = 1;
1016
1017
34
    PyPreConfig config;
1018
1019
34
    status = _PyPreConfig_InitFromPreConfig(&config, src_config);
1020
34
    if (_PyStatus_EXCEPTION(status)) {
1021
0
        return status;
1022
0
    }
1023
1024
34
    status = _PyPreConfig_Read(&config, args);
1025
34
    if (_PyStatus_EXCEPTION(status)) {
1026
0
        return status;
1027
0
    }
1028
1029
34
    status = _PyPreConfig_Write(&config);
1030
34
    if (_PyStatus_EXCEPTION(status)) {
1031
0
        return status;
1032
0
    }
1033
1034
34
    runtime->preinitializing = 0;
1035
34
    runtime->preinitialized = 1;
1036
34
    return _PyStatus_OK();
1037
34
}
1038
1039
1040
PyStatus
1041
Py_PreInitializeFromBytesArgs(const PyPreConfig *src_config, Py_ssize_t argc, char **argv)
1042
0
{
1043
0
    _PyArgv args = {.use_bytes_argv = 1, .argc = argc, .bytes_argv = argv};
1044
0
    return _Py_PreInitializeFromPyArgv(src_config, &args);
1045
0
}
1046
1047
1048
PyStatus
1049
Py_PreInitializeFromArgs(const PyPreConfig *src_config, Py_ssize_t argc, wchar_t **argv)
1050
0
{
1051
0
    _PyArgv args = {.use_bytes_argv = 0, .argc = argc, .wchar_argv = argv};
1052
0
    return _Py_PreInitializeFromPyArgv(src_config, &args);
1053
0
}
1054
1055
1056
PyStatus
1057
Py_PreInitialize(const PyPreConfig *src_config)
1058
34
{
1059
34
    return _Py_PreInitializeFromPyArgv(src_config, NULL);
1060
34
}
1061
1062
1063
PyStatus
1064
_Py_PreInitializeFromConfig(const PyConfig *config,
1065
                            const _PyArgv *args)
1066
2.48k
{
1067
2.48k
    assert(config != NULL);
1068
1069
2.48k
    PyStatus status = _PyRuntime_Initialize();
1070
2.48k
    if (_PyStatus_EXCEPTION(status)) {
1071
0
        return status;
1072
0
    }
1073
2.48k
    _PyRuntimeState *runtime = &_PyRuntime;
1074
1075
2.48k
    if (runtime->preinitialized) {
1076
        /* Already initialized: do nothing */
1077
2.44k
        return _PyStatus_OK();
1078
2.44k
    }
1079
1080
34
    PyPreConfig preconfig;
1081
1082
34
    _PyPreConfig_InitFromConfig(&preconfig, config);
1083
1084
34
    if (!config->parse_argv) {
1085
34
        return Py_PreInitialize(&preconfig);
1086
34
    }
1087
0
    else if (args == NULL) {
1088
0
        _PyArgv config_args = {
1089
0
            .use_bytes_argv = 0,
1090
0
            .argc = config->argv.length,
1091
0
            .wchar_argv = config->argv.items};
1092
0
        return _Py_PreInitializeFromPyArgv(&preconfig, &config_args);
1093
0
    }
1094
0
    else {
1095
0
        return _Py_PreInitializeFromPyArgv(&preconfig, args);
1096
0
    }
1097
34
}
1098
1099
1100
/* Begin interpreter initialization
1101
 *
1102
 * On return, the first thread and interpreter state have been created,
1103
 * but the compiler, signal handling, multithreading and
1104
 * multiple interpreter support, and codec infrastructure are not yet
1105
 * available.
1106
 *
1107
 * The import system will support builtin and frozen modules only.
1108
 * The only supported io is writing to sys.stderr
1109
 *
1110
 * If any operation invoked by this function fails, a fatal error is
1111
 * issued and the function does not return.
1112
 *
1113
 * Any code invoked from this function should *not* assume it has access
1114
 * to the Python C API (unless the API is explicitly listed as being
1115
 * safe to call without calling Py_Initialize first)
1116
 */
1117
static PyStatus
1118
pyinit_core(_PyRuntimeState *runtime,
1119
            const PyConfig *src_config,
1120
            PyThreadState **tstate_p)
1121
34
{
1122
34
    PyStatus status;
1123
1124
34
    status = _Py_PreInitializeFromConfig(src_config, NULL);
1125
34
    if (_PyStatus_EXCEPTION(status)) {
1126
0
        return status;
1127
0
    }
1128
1129
34
    PyConfig config;
1130
34
    PyConfig_InitPythonConfig(&config);
1131
1132
34
    status = _PyConfig_Copy(&config, src_config);
1133
34
    if (_PyStatus_EXCEPTION(status)) {
1134
0
        goto done;
1135
0
    }
1136
1137
    // Read the configuration, but don't compute the path configuration
1138
    // (it is computed in the main init).
1139
34
    status = _PyConfig_Read(&config, 0);
1140
34
    if (_PyStatus_EXCEPTION(status)) {
1141
0
        goto done;
1142
0
    }
1143
1144
34
    if (!runtime->core_initialized) {
1145
34
        status = pyinit_config(runtime, tstate_p, &config);
1146
34
    }
1147
0
    else {
1148
0
        status = pyinit_core_reconfigure(runtime, tstate_p, &config);
1149
0
    }
1150
34
    if (_PyStatus_EXCEPTION(status)) {
1151
0
        goto done;
1152
0
    }
1153
1154
34
done:
1155
34
    PyConfig_Clear(&config);
1156
34
    return status;
1157
34
}
1158
1159
1160
/* Py_Initialize() has already been called: update the main interpreter
1161
   configuration. Example of bpo-34008: Py_Main() called after
1162
   Py_Initialize(). */
1163
static PyStatus
1164
pyinit_main_reconfigure(PyThreadState *tstate)
1165
0
{
1166
0
    if (interpreter_update_config(tstate, 0) < 0) {
1167
0
        return _PyStatus_ERR("fail to reconfigure Python");
1168
0
    }
1169
0
    return _PyStatus_OK();
1170
0
}
1171
1172
1173
#ifdef Py_DEBUG
1174
static void
1175
run_presite(PyThreadState *tstate)
1176
{
1177
    PyInterpreterState *interp = tstate->interp;
1178
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
1179
1180
    if (!config->run_presite) {
1181
        return;
1182
    }
1183
1184
    PyObject *presite_modname = PyUnicode_FromWideChar(
1185
        config->run_presite,
1186
        wcslen(config->run_presite)
1187
    );
1188
    if (presite_modname == NULL) {
1189
        fprintf(stderr, "Could not convert pre-site module name to unicode\n");
1190
    }
1191
    else {
1192
        PyObject *presite = PyImport_Import(presite_modname);
1193
        if (presite == NULL) {
1194
            fprintf(stderr, "pre-site import failed:\n");
1195
            _PyErr_Print(tstate);
1196
        }
1197
        Py_XDECREF(presite);
1198
        Py_DECREF(presite_modname);
1199
    }
1200
}
1201
#endif
1202
1203
1204
static PyStatus
1205
init_interp_main(PyThreadState *tstate)
1206
34
{
1207
34
    assert(!_PyErr_Occurred(tstate));
1208
1209
34
    PyStatus status;
1210
34
    int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
1211
34
    PyInterpreterState *interp = tstate->interp;
1212
34
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
1213
1214
34
    if (!config->_install_importlib) {
1215
        /* Special mode for freeze_importlib: run with no import system
1216
         *
1217
         * This means anything which needs support from extension modules
1218
         * or pure Python code in the standard library won't work.
1219
         */
1220
0
        if (is_main_interp) {
1221
0
            interp->runtime->initialized = 1;
1222
0
        }
1223
0
        return _PyStatus_OK();
1224
0
    }
1225
1226
    // Initialize the import-related configuration.
1227
34
    status = _PyConfig_InitImportConfig(&interp->config);
1228
34
    if (_PyStatus_EXCEPTION(status)) {
1229
0
        return status;
1230
0
    }
1231
1232
34
    if (interpreter_update_config(tstate, 1) < 0) {
1233
0
        return _PyStatus_ERR("failed to update the Python config");
1234
0
    }
1235
1236
34
    status = _PyImport_InitExternal(tstate);
1237
34
    if (_PyStatus_EXCEPTION(status)) {
1238
0
        return status;
1239
0
    }
1240
1241
34
    if (is_main_interp) {
1242
        /* initialize the faulthandler module */
1243
34
        status = _PyFaulthandler_Init(config->faulthandler);
1244
34
        if (_PyStatus_EXCEPTION(status)) {
1245
0
            return status;
1246
0
        }
1247
34
    }
1248
1249
34
    status = _PyUnicode_InitEncodings(tstate);
1250
34
    if (_PyStatus_EXCEPTION(status)) {
1251
0
        return status;
1252
0
    }
1253
1254
34
    if (is_main_interp) {
1255
34
        if (_PySignal_Init(config->install_signal_handlers) < 0) {
1256
0
            return _PyStatus_ERR("can't initialize signals");
1257
0
        }
1258
1259
34
        if (config->tracemalloc) {
1260
0
           if (_PyTraceMalloc_Start(config->tracemalloc) < 0) {
1261
0
                return _PyStatus_ERR("can't start tracemalloc");
1262
0
            }
1263
0
        }
1264
1265
34
#ifdef PY_HAVE_PERF_TRAMPOLINE
1266
34
        if (config->perf_profiling) {
1267
0
            _PyPerf_Callbacks *cur_cb;
1268
0
            if (config->perf_profiling == 1) {
1269
0
                cur_cb = &_Py_perfmap_callbacks;
1270
0
            }
1271
0
            else {
1272
0
                cur_cb = &_Py_perfmap_jit_callbacks;
1273
0
            }
1274
0
            if (_PyPerfTrampoline_SetCallbacks(cur_cb) < 0 ||
1275
0
                    _PyPerfTrampoline_Init(config->perf_profiling) < 0) {
1276
0
                return _PyStatus_ERR("can't initialize the perf trampoline");
1277
0
            }
1278
0
        }
1279
34
#endif
1280
34
    }
1281
1282
34
    status = init_sys_streams(tstate);
1283
34
    if (_PyStatus_EXCEPTION(status)) {
1284
0
        return status;
1285
0
    }
1286
1287
34
    status = init_set_builtins_open();
1288
34
    if (_PyStatus_EXCEPTION(status)) {
1289
0
        return status;
1290
0
    }
1291
1292
#ifdef __ANDROID__
1293
    status = init_android_streams(tstate);
1294
    if (_PyStatus_EXCEPTION(status)) {
1295
        return status;
1296
    }
1297
#endif
1298
#if defined(__APPLE__) && HAS_APPLE_SYSTEM_LOG
1299
    if (config->use_system_logger) {
1300
        status = init_apple_streams(tstate);
1301
        if (_PyStatus_EXCEPTION(status)) {
1302
            return status;
1303
        }
1304
    }
1305
#endif
1306
1307
#ifdef Py_DEBUG
1308
    run_presite(tstate);
1309
#endif
1310
1311
34
    status = add_main_module(interp);
1312
34
    if (_PyStatus_EXCEPTION(status)) {
1313
0
        return status;
1314
0
    }
1315
1316
34
    if (is_main_interp) {
1317
        /* Initialize warnings. */
1318
34
        PyObject *warnoptions;
1319
34
        if (PySys_GetOptionalAttrString("warnoptions", &warnoptions) < 0) {
1320
0
            return _PyStatus_ERR("can't initialize warnings");
1321
0
        }
1322
34
        if (warnoptions != NULL && PyList_Check(warnoptions) &&
1323
34
            PyList_Size(warnoptions) > 0)
1324
0
        {
1325
0
            PyObject *warnings_module = PyImport_ImportModule("warnings");
1326
0
            if (warnings_module == NULL) {
1327
0
                fprintf(stderr, "'import warnings' failed; traceback:\n");
1328
0
                _PyErr_Print(tstate);
1329
0
            }
1330
0
            Py_XDECREF(warnings_module);
1331
0
        }
1332
34
        Py_XDECREF(warnoptions);
1333
1334
34
        interp->runtime->initialized = 1;
1335
34
    }
1336
1337
34
    if (config->site_import) {
1338
34
        status = init_import_site();
1339
34
        if (_PyStatus_EXCEPTION(status)) {
1340
0
            return status;
1341
0
        }
1342
34
    }
1343
1344
    // Initialize lazy imports based on configuration. Do this after site
1345
    // module is imported to avoid circular imports during startup.
1346
34
    if (config->lazy_imports != -1) {
1347
0
        PyImport_LazyImportsMode lazy_mode;
1348
0
        if (config->lazy_imports == 1) {
1349
0
            lazy_mode = PyImport_LAZY_ALL;
1350
0
        }
1351
0
        else {
1352
0
            lazy_mode = PyImport_LAZY_NONE;
1353
0
        }
1354
0
        if (PyImport_SetLazyImportsMode(lazy_mode) < 0) {
1355
0
            return _PyStatus_ERR("failed to set lazy imports mode");
1356
0
        }
1357
0
    }
1358
    // If config->lazy_imports == -1, use the default mode, no change needed.
1359
1360
34
    if (is_main_interp) {
1361
34
#ifndef MS_WINDOWS
1362
34
        emit_stderr_warning_for_legacy_locale(interp->runtime);
1363
34
#endif
1364
34
    }
1365
1366
    // Turn on experimental tier 2 (uops-based) optimizer
1367
    // This is also needed when the JIT is enabled
1368
#ifdef _Py_TIER2
1369
    if (is_main_interp) {
1370
        int enabled = 1;
1371
#if _Py_TIER2 & 2
1372
        enabled = 0;
1373
#endif
1374
        char *env = Py_GETENV("PYTHON_JIT");
1375
        if (env && *env != '\0') {
1376
            // PYTHON_JIT=0|1 overrides the default
1377
            enabled = *env != '0';
1378
        }
1379
        if (enabled) {
1380
#ifdef _Py_JIT
1381
            // perf profiler works fine with tier 2 interpreter, so
1382
            // only checking for a "real JIT".
1383
            if (config->perf_profiling > 0) {
1384
                (void)PyErr_WarnEx(
1385
                    PyExc_RuntimeWarning,
1386
                    "JIT deactivated as perf profiling support is active",
1387
                    0);
1388
            } else
1389
#endif
1390
            {
1391
                interp->jit = true;
1392
            }
1393
        }
1394
    }
1395
#endif
1396
1397
34
    if (!is_main_interp) {
1398
        // The main interpreter is handled in Py_Main(), for now.
1399
0
        if (config->sys_path_0 != NULL) {
1400
0
            PyObject *path0 = PyUnicode_FromWideChar(config->sys_path_0, -1);
1401
0
            if (path0 == NULL) {
1402
0
                return _PyStatus_ERR("can't initialize sys.path[0]");
1403
0
            }
1404
0
            PyObject *sysdict = interp->sysdict;
1405
0
            if (sysdict == NULL) {
1406
0
                Py_DECREF(path0);
1407
0
                return _PyStatus_ERR("can't initialize sys.path[0]");
1408
0
            }
1409
0
            PyObject *sys_path = PyDict_GetItemWithError(sysdict, &_Py_ID(path));
1410
0
            if (sys_path == NULL) {
1411
0
                Py_DECREF(path0);
1412
0
                return _PyStatus_ERR("can't initialize sys.path[0]");
1413
0
            }
1414
0
            int res = PyList_Insert(sys_path, 0, path0);
1415
0
            Py_DECREF(path0);
1416
0
            if (res) {
1417
0
                return _PyStatus_ERR("can't initialize sys.path[0]");
1418
0
            }
1419
0
        }
1420
0
    }
1421
1422
1423
34
    interp->dict_state.watchers[0] = &builtins_dict_watcher;
1424
34
    if (PyDict_Watch(0, interp->builtins) != 0) {
1425
0
        return _PyStatus_ERR("failed to set builtin dict watcher");
1426
0
    }
1427
1428
34
    assert(!_PyErr_Occurred(tstate));
1429
1430
34
    return _PyStatus_OK();
1431
34
}
1432
1433
1434
/* Update interpreter state based on supplied configuration settings
1435
 *
1436
 * After calling this function, most of the restrictions on the interpreter
1437
 * are lifted. The only remaining incomplete settings are those related
1438
 * to the main module (sys.argv[0], __main__ metadata)
1439
 *
1440
 * Calling this when the interpreter is not initializing, is already
1441
 * initialized or without a valid current thread state is a fatal error.
1442
 * Other errors should be reported as normal Python exceptions with a
1443
 * non-zero return code.
1444
 */
1445
static PyStatus
1446
pyinit_main(PyThreadState *tstate)
1447
34
{
1448
34
    PyInterpreterState *interp = tstate->interp;
1449
34
    if (!interp->runtime->core_initialized) {
1450
0
        return _PyStatus_ERR("runtime core not initialized");
1451
0
    }
1452
1453
34
    if (interp->runtime->initialized) {
1454
0
        return pyinit_main_reconfigure(tstate);
1455
0
    }
1456
1457
34
    PyStatus status = init_interp_main(tstate);
1458
34
    if (_PyStatus_EXCEPTION(status)) {
1459
0
        return status;
1460
0
    }
1461
34
    return _PyStatus_OK();
1462
34
}
1463
1464
1465
PyStatus
1466
Py_InitializeFromConfig(const PyConfig *config)
1467
34
{
1468
34
    if (config == NULL) {
1469
0
        return _PyStatus_ERR("initialization config is NULL");
1470
0
    }
1471
1472
34
    PyStatus status;
1473
1474
34
    status = _PyRuntime_Initialize();
1475
34
    if (_PyStatus_EXCEPTION(status)) {
1476
0
        return status;
1477
0
    }
1478
34
    _PyRuntimeState *runtime = &_PyRuntime;
1479
1480
34
    PyThreadState *tstate = NULL;
1481
34
    status = pyinit_core(runtime, config, &tstate);
1482
34
    if (_PyStatus_EXCEPTION(status)) {
1483
0
        return status;
1484
0
    }
1485
34
    config = _PyInterpreterState_GetConfig(tstate->interp);
1486
1487
34
    if (config->_init_main) {
1488
34
        status = pyinit_main(tstate);
1489
34
        if (_PyStatus_EXCEPTION(status)) {
1490
0
            return status;
1491
0
        }
1492
34
    }
1493
1494
34
    return _PyStatus_OK();
1495
34
}
1496
1497
1498
void
1499
Py_InitializeEx(int install_sigs)
1500
34
{
1501
34
    PyStatus status;
1502
1503
34
    status = _PyRuntime_Initialize();
1504
34
    if (_PyStatus_EXCEPTION(status)) {
1505
0
        Py_ExitStatusException(status);
1506
0
    }
1507
34
    _PyRuntimeState *runtime = &_PyRuntime;
1508
1509
34
    if (runtime->initialized) {
1510
        /* bpo-33932: Calling Py_Initialize() twice does nothing. */
1511
0
        return;
1512
0
    }
1513
1514
34
    PyConfig config;
1515
34
    _PyConfig_InitCompatConfig(&config);
1516
1517
34
    config.install_signal_handlers = install_sigs;
1518
1519
34
    status = Py_InitializeFromConfig(&config);
1520
34
    PyConfig_Clear(&config);
1521
34
    if (_PyStatus_EXCEPTION(status)) {
1522
0
        Py_ExitStatusException(status);
1523
0
    }
1524
34
}
1525
1526
void
1527
Py_Initialize(void)
1528
34
{
1529
34
    Py_InitializeEx(1);
1530
34
}
1531
1532
1533
PyStatus
1534
_Py_InitializeMain(void)
1535
0
{
1536
0
    PyStatus status = _PyRuntime_Initialize();
1537
0
    if (_PyStatus_EXCEPTION(status)) {
1538
0
        return status;
1539
0
    }
1540
0
    PyThreadState *tstate = _PyThreadState_GET();
1541
0
    return pyinit_main(tstate);
1542
0
}
1543
1544
1545
static void
1546
finalize_modules_delete_special(PyThreadState *tstate, int verbose)
1547
0
{
1548
    // List of names to clear in sys
1549
0
    static const char * const sys_deletes[] = {
1550
0
        "path", "argv", "ps1", "ps2", "last_exc",
1551
0
        "last_type", "last_value", "last_traceback",
1552
0
        "__interactivehook__",
1553
        // path_hooks and path_importer_cache are cleared
1554
        // by _PyImport_FiniExternal().
1555
        // XXX Clear meta_path in _PyImport_FiniCore().
1556
0
        "meta_path",
1557
0
        NULL
1558
0
    };
1559
1560
0
    static const char * const sys_files[] = {
1561
0
        "stdin", "__stdin__",
1562
0
        "stdout", "__stdout__",
1563
0
        "stderr", "__stderr__",
1564
0
        NULL
1565
0
    };
1566
1567
0
    PyInterpreterState *interp = tstate->interp;
1568
0
    if (verbose) {
1569
0
        PySys_WriteStderr("# clear builtins._\n");
1570
0
    }
1571
0
    if (PyDict_SetItemString(interp->builtins, "_", Py_None) < 0) {
1572
0
        PyErr_FormatUnraisable("Exception ignored while "
1573
0
                               "setting builtin variable _");
1574
0
    }
1575
1576
0
    const char * const *p;
1577
0
    for (p = sys_deletes; *p != NULL; p++) {
1578
0
        if (_PySys_ClearAttrString(interp, *p, verbose) < 0) {
1579
0
            PyErr_FormatUnraisable("Exception ignored while "
1580
0
                                   "clearing sys.%s", *p);
1581
0
        }
1582
0
    }
1583
0
    for (p = sys_files; *p != NULL; p+=2) {
1584
0
        const char *name = p[0];
1585
0
        const char *orig_name = p[1];
1586
0
        if (verbose) {
1587
0
            PySys_WriteStderr("# restore sys.%s\n", name);
1588
0
        }
1589
0
        PyObject *value;
1590
0
        if (PyDict_GetItemStringRef(interp->sysdict, orig_name, &value) < 0) {
1591
0
            PyErr_FormatUnraisable("Exception ignored while "
1592
0
                                   "restoring sys.%s", name);
1593
0
        }
1594
0
        if (value == NULL) {
1595
0
            value = Py_NewRef(Py_None);
1596
0
        }
1597
0
        if (PyDict_SetItemString(interp->sysdict, name, value) < 0) {
1598
0
            PyErr_FormatUnraisable("Exception ignored while "
1599
0
                                   "restoring sys.%s", name);
1600
0
        }
1601
0
        Py_DECREF(value);
1602
0
    }
1603
0
}
1604
1605
1606
static PyObject*
1607
finalize_remove_modules(PyObject *modules, int verbose)
1608
0
{
1609
0
    PyObject *weaklist = PyList_New(0);
1610
0
    if (weaklist == NULL) {
1611
0
        PyErr_FormatUnraisable("Exception ignored while removing modules");
1612
0
    }
1613
1614
0
#define STORE_MODULE_WEAKREF(name, mod) \
1615
0
        if (weaklist != NULL) { \
1616
0
            PyObject *wr = PyWeakref_NewRef(mod, NULL); \
1617
0
            if (wr) { \
1618
0
                PyObject *tup = PyTuple_Pack(2, name, wr); \
1619
0
                if (!tup || PyList_Append(weaklist, tup) < 0) { \
1620
0
                    PyErr_FormatUnraisable("Exception ignored while removing modules"); \
1621
0
                } \
1622
0
                Py_XDECREF(tup); \
1623
0
                Py_DECREF(wr); \
1624
0
            } \
1625
0
            else { \
1626
0
                PyErr_FormatUnraisable("Exception ignored while removing modules"); \
1627
0
            } \
1628
0
        }
1629
1630
0
#define CLEAR_MODULE(name, mod) \
1631
0
        if (PyModule_Check(mod)) { \
1632
0
            if (verbose && PyUnicode_Check(name)) { \
1633
0
                PySys_FormatStderr("# cleanup[2] removing %U\n", name); \
1634
0
            } \
1635
0
            STORE_MODULE_WEAKREF(name, mod); \
1636
0
            if (PyObject_SetItem(modules, name, Py_None) < 0) { \
1637
0
                PyErr_FormatUnraisable("Exception ignored while removing modules"); \
1638
0
            } \
1639
0
        }
1640
1641
0
    if (PyDict_CheckExact(modules)) {
1642
0
        Py_ssize_t pos = 0;
1643
0
        PyObject *key, *value;
1644
0
        while (PyDict_Next(modules, &pos, &key, &value)) {
1645
0
            CLEAR_MODULE(key, value);
1646
0
        }
1647
0
    }
1648
0
    else {
1649
0
        PyObject *iterator = PyObject_GetIter(modules);
1650
0
        if (iterator == NULL) {
1651
0
            PyErr_FormatUnraisable("Exception ignored while removing modules");
1652
0
        }
1653
0
        else {
1654
0
            PyObject *key;
1655
0
            while ((key = PyIter_Next(iterator))) {
1656
0
                PyObject *value = PyObject_GetItem(modules, key);
1657
0
                if (value == NULL) {
1658
0
                    PyErr_FormatUnraisable("Exception ignored while removing modules");
1659
0
                    Py_DECREF(key);
1660
0
                    continue;
1661
0
                }
1662
0
                CLEAR_MODULE(key, value);
1663
0
                Py_DECREF(value);
1664
0
                Py_DECREF(key);
1665
0
            }
1666
0
            if (PyErr_Occurred()) {
1667
0
                PyErr_FormatUnraisable("Exception ignored while removing modules");
1668
0
            }
1669
0
            Py_DECREF(iterator);
1670
0
        }
1671
0
    }
1672
0
#undef CLEAR_MODULE
1673
0
#undef STORE_MODULE_WEAKREF
1674
1675
0
    return weaklist;
1676
0
}
1677
1678
1679
static void
1680
finalize_clear_modules_dict(PyObject *modules)
1681
0
{
1682
0
    if (PyDict_CheckExact(modules)) {
1683
0
        PyDict_Clear(modules);
1684
0
    }
1685
0
    else {
1686
0
        if (PyObject_CallMethodNoArgs(modules, &_Py_ID(clear)) == NULL) {
1687
0
            PyErr_FormatUnraisable("Exception ignored while clearing sys.modules");
1688
0
        }
1689
0
    }
1690
0
}
1691
1692
1693
static void
1694
finalize_restore_builtins(PyThreadState *tstate)
1695
0
{
1696
0
    PyInterpreterState *interp = tstate->interp;
1697
0
    PyObject *dict = PyDict_Copy(interp->builtins);
1698
0
    if (dict == NULL) {
1699
0
        PyErr_FormatUnraisable("Exception ignored while restoring builtins");
1700
0
    }
1701
0
    PyDict_Clear(interp->builtins);
1702
0
    if (PyDict_Update(interp->builtins, interp->builtins_copy)) {
1703
0
        PyErr_FormatUnraisable("Exception ignored while restoring builtins");
1704
0
    }
1705
0
    Py_XDECREF(dict);
1706
0
}
1707
1708
1709
static void
1710
finalize_modules_clear_weaklist(PyInterpreterState *interp,
1711
                                PyObject *weaklist, int verbose)
1712
0
{
1713
    // First clear modules imported later
1714
0
    for (Py_ssize_t i = PyList_GET_SIZE(weaklist) - 1; i >= 0; i--) {
1715
0
        PyObject *tup = PyList_GET_ITEM(weaklist, i);
1716
0
        PyObject *name = PyTuple_GET_ITEM(tup, 0);
1717
0
        PyObject *mod = _PyWeakref_GET_REF(PyTuple_GET_ITEM(tup, 1));
1718
0
        if (mod == NULL) {
1719
0
            continue;
1720
0
        }
1721
0
        assert(PyModule_Check(mod));
1722
0
        PyObject *dict = _PyModule_GetDict(mod);  // borrowed reference
1723
0
        if (dict == interp->builtins || dict == interp->sysdict) {
1724
0
            Py_DECREF(mod);
1725
0
            continue;
1726
0
        }
1727
0
        if (verbose && PyUnicode_Check(name)) {
1728
0
            PySys_FormatStderr("# cleanup[3] wiping %U\n", name);
1729
0
        }
1730
0
        _PyModule_Clear(mod);
1731
0
        Py_DECREF(mod);
1732
0
    }
1733
0
}
1734
1735
1736
static void
1737
finalize_clear_sys_builtins_dict(PyInterpreterState *interp, int verbose)
1738
0
{
1739
    // Clear sys dict
1740
0
    if (verbose) {
1741
0
        PySys_FormatStderr("# cleanup[3] wiping sys\n");
1742
0
    }
1743
0
    _PyModule_ClearDict(interp->sysdict);
1744
1745
    // Clear builtins dict
1746
0
    if (verbose) {
1747
0
        PySys_FormatStderr("# cleanup[3] wiping builtins\n");
1748
0
    }
1749
0
    _PyModule_ClearDict(interp->builtins);
1750
0
}
1751
1752
1753
/* Clear modules, as good as we can */
1754
// XXX Move most of this to import.c.
1755
static void
1756
finalize_modules(PyThreadState *tstate)
1757
0
{
1758
0
    PyInterpreterState *interp = tstate->interp;
1759
1760
    // Invalidate all executors and turn off JIT:
1761
0
    interp->jit = false;
1762
0
    interp->compiling = false;
1763
#ifdef _Py_TIER2
1764
    _Py_Executors_InvalidateAll(interp, 0);
1765
#endif
1766
1767
    // Stop watching __builtin__ modifications
1768
0
    if (PyDict_Unwatch(0, interp->builtins) < 0) {
1769
        // might happen if interp is cleared before watching the __builtin__
1770
0
        PyErr_Clear();
1771
0
    }
1772
0
    PyObject *modules = _PyImport_GetModules(interp);
1773
0
    if (modules == NULL) {
1774
        // Already done
1775
0
        return;
1776
0
    }
1777
0
    int verbose = _PyInterpreterState_GetConfig(interp)->verbose;
1778
1779
    // Delete some special builtins._ and sys attributes first.  These are
1780
    // common places where user values hide and people complain when their
1781
    // destructors fail.  Since the modules containing them are
1782
    // deleted *last* of all, they would come too late in the normal
1783
    // destruction order.  Sigh.
1784
    //
1785
    // XXX Perhaps these precautions are obsolete. Who knows?
1786
0
    finalize_modules_delete_special(tstate, verbose);
1787
1788
    // Remove all modules from sys.modules, hoping that garbage collection
1789
    // can reclaim most of them: set all sys.modules values to None.
1790
    //
1791
    // We prepare a list which will receive (name, weakref) tuples of
1792
    // modules when they are removed from sys.modules.  The name is used
1793
    // for diagnosis messages (in verbose mode), while the weakref helps
1794
    // detect those modules which have been held alive.
1795
0
    PyObject *weaklist = finalize_remove_modules(modules, verbose);
1796
1797
    // Clear the modules dict
1798
0
    finalize_clear_modules_dict(modules);
1799
1800
    // Restore the original builtins dict, to ensure that any
1801
    // user data gets cleared.
1802
0
    finalize_restore_builtins(tstate);
1803
1804
    // Collect garbage
1805
0
    _PyGC_CollectNoFail(tstate);
1806
1807
    // Dump GC stats before it's too late, since it uses the warnings
1808
    // machinery.
1809
0
    _PyGC_DumpShutdownStats(interp);
1810
1811
0
    if (weaklist != NULL) {
1812
        // Now, if there are any modules left alive, clear their globals to
1813
        // minimize potential leaks.  All C extension modules actually end
1814
        // up here, since they are kept alive in the interpreter state.
1815
        //
1816
        // The special treatment of "builtins" here is because even
1817
        // when it's not referenced as a module, its dictionary is
1818
        // referenced by almost every module's __builtins__.  Since
1819
        // deleting a module clears its dictionary (even if there are
1820
        // references left to it), we need to delete the "builtins"
1821
        // module last.  Likewise, we don't delete sys until the very
1822
        // end because it is implicitly referenced (e.g. by print).
1823
        //
1824
        // Since dict is ordered in CPython 3.6+, modules are saved in
1825
        // importing order.  First clear modules imported later.
1826
0
        finalize_modules_clear_weaklist(interp, weaklist, verbose);
1827
0
        Py_DECREF(weaklist);
1828
0
    }
1829
1830
    // Clear sys and builtins modules dict
1831
0
    finalize_clear_sys_builtins_dict(interp, verbose);
1832
1833
    // Clear module dict copies stored in the interpreter state:
1834
    // clear PyInterpreterState.modules_by_index and
1835
    // clear PyModuleDef.m_base.m_copy (of extensions not using the multi-phase
1836
    // initialization API)
1837
0
    _PyImport_ClearModulesByIndex(interp);
1838
1839
    // Clear the dict of lazily loaded module nname to submodule names
1840
0
    _PyImport_ClearLazyModules(interp);
1841
1842
    // Clear and delete the modules directory.  Actual modules will
1843
    // still be there only if imported during the execution of some
1844
    // destructor.
1845
0
    _PyImport_ClearModules(interp);
1846
1847
    // Collect garbage once more
1848
0
    _PyGC_CollectNoFail(tstate);
1849
0
}
1850
1851
1852
/* Flush stdout and stderr */
1853
1854
static int
1855
file_is_closed(PyObject *fobj)
1856
0
{
1857
0
    int r;
1858
0
    PyObject *tmp = PyObject_GetAttrString(fobj, "closed");
1859
0
    if (tmp == NULL) {
1860
0
        PyErr_Clear();
1861
0
        return 0;
1862
0
    }
1863
0
    r = PyObject_IsTrue(tmp);
1864
0
    Py_DECREF(tmp);
1865
0
    if (r < 0)
1866
0
        PyErr_Clear();
1867
0
    return r > 0;
1868
0
}
1869
1870
1871
static int
1872
flush_std_files(void)
1873
0
{
1874
0
    PyObject *file;
1875
0
    int status = 0;
1876
1877
0
    if (PySys_GetOptionalAttr(&_Py_ID(stdout), &file) < 0) {
1878
0
        status = -1;
1879
0
    }
1880
0
    else if (file != NULL && file != Py_None && !file_is_closed(file)) {
1881
0
        if (_PyFile_Flush(file) < 0) {
1882
0
            status = -1;
1883
0
        }
1884
0
    }
1885
0
    if (status < 0) {
1886
0
        PyErr_FormatUnraisable("Exception ignored while flushing sys.stdout");
1887
0
    }
1888
0
    Py_XDECREF(file);
1889
1890
0
    if (PySys_GetOptionalAttr(&_Py_ID(stderr), &file) < 0) {
1891
0
        PyErr_Clear();
1892
0
        status = -1;
1893
0
    }
1894
0
    else if (file != NULL && file != Py_None && !file_is_closed(file)) {
1895
0
        if (_PyFile_Flush(file) < 0) {
1896
0
            PyErr_Clear();
1897
0
            status = -1;
1898
0
        }
1899
0
    }
1900
0
    Py_XDECREF(file);
1901
1902
0
    return status;
1903
0
}
1904
1905
/* Undo the effect of Py_Initialize().
1906
1907
   Beware: if multiple interpreter and/or thread states exist, these
1908
   are not wiped out; only the current thread and interpreter state
1909
   are deleted.  But since everything else is deleted, those other
1910
   interpreter and thread states should no longer be used.
1911
1912
   (XXX We should do better, e.g. wipe out all interpreters and
1913
   threads.)
1914
1915
   Locking: as above.
1916
1917
*/
1918
1919
1920
static void
1921
finalize_interp_types(PyInterpreterState *interp)
1922
0
{
1923
0
    _PyTypes_FiniExtTypes(interp);
1924
0
    _PyUnicode_FiniTypes(interp);
1925
0
    _PySys_FiniTypes(interp);
1926
0
    _PyXI_FiniTypes(interp);
1927
0
    _PyExc_Fini(interp);
1928
0
    _PyFloat_FiniType(interp);
1929
0
    _PyLong_FiniTypes(interp);
1930
0
    _PyThread_FiniType(interp);
1931
    // XXX fini collections module static types (_PyStaticType_Dealloc())
1932
    // XXX fini IO module static types (_PyStaticType_Dealloc())
1933
0
    _PyErr_FiniTypes(interp);
1934
0
    _PyTypes_FiniTypes(interp);
1935
1936
0
    _PyTypes_Fini(interp);
1937
#ifdef Py_GIL_DISABLED
1938
    _PyObject_FinalizeUniqueIdPool(interp);
1939
#endif
1940
1941
0
    _PyCode_Fini(interp);
1942
1943
    // Call _PyUnicode_ClearInterned() before _PyDict_Fini() since it uses
1944
    // a dict internally.
1945
0
    _PyUnicode_ClearInterned(interp);
1946
1947
0
    _PyUnicode_Fini(interp);
1948
1949
0
#ifndef Py_GIL_DISABLED
1950
    // With Py_GIL_DISABLED:
1951
    // the freelists for the current thread state have already been cleared.
1952
0
    struct _Py_freelists *freelists = _Py_freelists_GET();
1953
0
    _PyObject_ClearFreeLists(freelists, 1);
1954
0
#endif
1955
1956
#ifdef Py_DEBUG
1957
    _PyStaticObjects_CheckRefcnt(interp);
1958
#endif
1959
0
}
1960
1961
1962
static void
1963
finalize_interp_clear(PyThreadState *tstate)
1964
0
{
1965
0
    int is_main_interp = _Py_IsMainInterpreter(tstate->interp);
1966
1967
0
    _PyXI_Fini(tstate->interp);
1968
0
    _PyExc_ClearExceptionGroupType(tstate->interp);
1969
0
    _Py_clear_generic_types(tstate->interp);
1970
0
    _PyTypes_FiniCachedDescriptors(tstate->interp);
1971
1972
    /* Clear interpreter state and all thread states */
1973
0
    _PyInterpreterState_Clear(tstate);
1974
1975
    /* Clear all loghooks */
1976
    /* Both _PySys_Audit function and users still need PyObject, such as tuple.
1977
       Call _PySys_ClearAuditHooks when PyObject available. */
1978
0
    if (is_main_interp) {
1979
0
        _PySys_ClearAuditHooks(tstate);
1980
0
    }
1981
1982
0
    if (is_main_interp) {
1983
0
        _Py_HashRandomization_Fini();
1984
0
        _PyArg_Fini();
1985
0
        _Py_ClearFileSystemEncoding();
1986
0
        _PyPerfTrampoline_Fini();
1987
0
    }
1988
1989
0
    finalize_interp_types(tstate->interp);
1990
1991
    /* Finalize dtoa at last so that finalizers calling repr of float doesn't crash */
1992
0
    _PyDtoa_Fini(tstate->interp);
1993
1994
    /* Free any delayed free requests immediately */
1995
0
    _PyMem_FiniDelayed(tstate->interp);
1996
1997
    /* finalize_interp_types may allocate Python objects so we may need to
1998
       abandon mimalloc segments again */
1999
0
    _PyThreadState_ClearMimallocHeaps(tstate);
2000
0
}
2001
2002
2003
static void
2004
finalize_interp_delete(PyInterpreterState *interp)
2005
0
{
2006
    /* Cleanup auto-thread-state */
2007
0
    _PyGILState_Fini(interp);
2008
2009
    /* We can't call _PyEval_FiniGIL() here because destroying the GIL lock can
2010
       fail when it is being awaited by another running daemon thread (see
2011
       bpo-9901). Instead pycore_create_interpreter() destroys the previously
2012
       created GIL, which ensures that Py_Initialize / Py_FinalizeEx can be
2013
       called multiple times. */
2014
2015
0
    PyInterpreterState_Delete(interp);
2016
0
}
2017
2018
2019
/* Conceptually, there isn't a good reason for Py_Finalize()
2020
   to be called in any other thread than the one where Py_Initialize()
2021
   was called.  Consequently, it would make sense to fail if the thread
2022
   or thread state (or interpreter) don't match.  However, such
2023
   constraints have never been enforced, and, as unlikely as it may be,
2024
   there may be users relying on the unconstrained behavior.  Thus,
2025
   we do our best here to accommodate that possibility. */
2026
2027
static PyThreadState *
2028
resolve_final_tstate(_PyRuntimeState *runtime)
2029
0
{
2030
0
    PyThreadState *main_tstate = runtime->main_tstate;
2031
0
    assert(main_tstate != NULL);
2032
0
    assert(main_tstate->thread_id == runtime->main_thread);
2033
0
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
2034
0
    assert(main_tstate->interp == main_interp);
2035
2036
0
    PyThreadState *tstate = _PyThreadState_GET();
2037
0
    if (_Py_IsMainThread()) {
2038
0
        if (tstate != main_tstate) {
2039
            /* This implies that Py_Finalize() was called while
2040
               a non-main interpreter was active or while the main
2041
               tstate was temporarily swapped out with another.
2042
               Neither case should be allowed, but, until we get around
2043
               to fixing that (and Py_Exit()), we're letting it go. */
2044
0
            (void)PyThreadState_Swap(main_tstate);
2045
0
        }
2046
0
    }
2047
0
    else {
2048
        /* This is another unfortunate case where Py_Finalize() was
2049
           called when it shouldn't have been.  We can't simply switch
2050
           over to the main thread.  At the least, however, we can make
2051
           sure the main interpreter is active. */
2052
0
        if (!_Py_IsMainInterpreter(tstate->interp)) {
2053
            /* We don't go to the trouble of updating runtime->main_tstate
2054
               since it will be dead soon anyway. */
2055
0
            main_tstate =
2056
0
                _PyThreadState_New(main_interp, _PyThreadState_WHENCE_FINI);
2057
0
            if (main_tstate != NULL) {
2058
0
                _PyThreadState_Bind(main_tstate);
2059
0
                (void)PyThreadState_Swap(main_tstate);
2060
0
            }
2061
0
            else {
2062
                /* Fall back to the current tstate.  It's better than nothing. */
2063
                // XXX No it's not
2064
0
                main_tstate = tstate;
2065
0
            }
2066
0
        }
2067
0
    }
2068
0
    assert(main_tstate != NULL);
2069
2070
    /* We might want to warn if main_tstate->current_frame != NULL. */
2071
2072
0
    return main_tstate;
2073
0
}
2074
2075
#ifdef Py_GIL_DISABLED
2076
#define ASSERT_WORLD_STOPPED(interp) assert(interp->runtime->stoptheworld.world_stopped)
2077
#else
2078
#define ASSERT_WORLD_STOPPED(interp)
2079
#endif
2080
2081
static int
2082
interp_has_threads(PyInterpreterState *interp)
2083
0
{
2084
    /* This needs to check for non-daemon threads only, otherwise we get stuck
2085
     * in an infinite loop. */
2086
0
    assert(interp != NULL);
2087
0
    ASSERT_WORLD_STOPPED(interp);
2088
0
    assert(interp->threads.head != NULL);
2089
0
    if (interp->threads.head->next == NULL) {
2090
        // No other threads active, easy way out.
2091
0
        return 0;
2092
0
    }
2093
2094
    // We don't have to worry about locking this because the
2095
    // world is stopped.
2096
0
    _Py_FOR_EACH_TSTATE_UNLOCKED(interp, tstate) {
2097
0
        if (tstate->_whence == _PyThreadState_WHENCE_THREADING) {
2098
0
            return 1;
2099
0
        }
2100
0
    }
2101
2102
0
    return 0;
2103
0
}
2104
2105
static int
2106
interp_has_pending_calls(PyInterpreterState *interp)
2107
0
{
2108
0
    assert(interp != NULL);
2109
0
    ASSERT_WORLD_STOPPED(interp);
2110
0
    return interp->ceval.pending.npending != 0;
2111
0
}
2112
2113
static int
2114
interp_has_atexit_callbacks(PyInterpreterState *interp)
2115
0
{
2116
0
    assert(interp != NULL);
2117
0
    assert(interp->atexit.callbacks != NULL);
2118
0
    ASSERT_WORLD_STOPPED(interp);
2119
0
    assert(PyList_CheckExact(interp->atexit.callbacks));
2120
0
    return PyList_GET_SIZE(interp->atexit.callbacks) != 0;
2121
0
}
2122
2123
static int
2124
runtime_has_subinterpreters(_PyRuntimeState *runtime)
2125
0
{
2126
0
    assert(runtime != NULL);
2127
0
    HEAD_LOCK(runtime);
2128
0
    PyInterpreterState *interp = runtime->interpreters.head;
2129
0
    HEAD_UNLOCK(runtime);
2130
0
    return interp->next != NULL;
2131
0
}
2132
2133
static void
2134
make_pre_finalization_calls(PyThreadState *tstate, int subinterpreters)
2135
0
{
2136
0
    assert(tstate != NULL);
2137
0
    PyInterpreterState *interp = tstate->interp;
2138
    /* Each of these functions can start one another, e.g. a pending call
2139
     * could start a thread or vice versa. To ensure that we properly clean
2140
     * call everything, we run these in a loop until none of them run anything. */
2141
0
    for (;;) {
2142
0
        assert(!interp->runtime->stoptheworld.world_stopped);
2143
2144
        // Wrap up existing "threading"-module-created, non-daemon threads.
2145
0
        wait_for_thread_shutdown(tstate);
2146
2147
        // Make any remaining pending calls.
2148
0
        _Py_FinishPendingCalls(tstate);
2149
2150
        /* The interpreter is still entirely intact at this point, and the
2151
        * exit funcs may be relying on that.  In particular, if some thread
2152
        * or exit func is still waiting to do an import, the import machinery
2153
        * expects Py_IsInitialized() to return true.  So don't say the
2154
        * runtime is uninitialized until after the exit funcs have run.
2155
        * Note that Threading.py uses an exit func to do a join on all the
2156
        * threads created thru it, so this also protects pending imports in
2157
        * the threads created via Threading.
2158
        */
2159
2160
0
        _PyAtExit_Call(tstate->interp);
2161
2162
0
        if (subinterpreters) {
2163
            /* Clean up any lingering subinterpreters.
2164
2165
            Two preconditions need to be met here:
2166
2167
                - This has to happen before _PyRuntimeState_SetFinalizing is
2168
                called, or else threads might get prematurely blocked.
2169
                - The world must not be stopped, as finalizers can run.
2170
            */
2171
0
            finalize_subinterpreters();
2172
0
        }
2173
2174
2175
        /* Stop the world to prevent other threads from creating threads or
2176
         * atexit callbacks. On the default build, this is simply locked by
2177
         * the GIL. For pending calls, we acquire the dedicated mutex, because
2178
         * Py_AddPendingCall() can be called without an attached thread state.
2179
         */
2180
2181
0
        PyMutex_Lock(&interp->ceval.pending.mutex);
2182
        // XXX Why does _PyThreadState_DeleteList() rely on all interpreters
2183
        // being stopped?
2184
0
        _PyEval_StopTheWorldAll(interp->runtime);
2185
0
        int has_subinterpreters = subinterpreters
2186
0
                                    ? runtime_has_subinterpreters(interp->runtime)
2187
0
                                    : 0;
2188
0
        int should_continue = (interp_has_threads(interp)
2189
0
                              || interp_has_atexit_callbacks(interp)
2190
0
                              || interp_has_pending_calls(interp)
2191
0
                              || has_subinterpreters);
2192
0
        if (!should_continue) {
2193
0
            break;
2194
0
        }
2195
0
        _PyEval_StartTheWorldAll(interp->runtime);
2196
0
        PyMutex_Unlock(&interp->ceval.pending.mutex);
2197
0
    }
2198
0
    assert(PyMutex_IsLocked(&interp->ceval.pending.mutex));
2199
0
    ASSERT_WORLD_STOPPED(interp);
2200
0
}
2201
2202
static int
2203
_Py_Finalize(_PyRuntimeState *runtime)
2204
0
{
2205
0
    int status = 0;
2206
2207
    /* Bail out early if already finalized (or never initialized). */
2208
0
    if (!runtime->initialized) {
2209
0
        return status;
2210
0
    }
2211
2212
    /* Get final thread state pointer. */
2213
0
    PyThreadState *tstate = resolve_final_tstate(runtime);
2214
2215
    // Block some operations.
2216
0
    tstate->interp->finalizing = 1;
2217
2218
    // This call stops the world and takes the pending calls lock.
2219
0
    make_pre_finalization_calls(tstate, /*subinterpreters=*/1);
2220
2221
0
    assert(_PyThreadState_GET() == tstate);
2222
2223
    /* Copy the core config, PyInterpreterState_Delete() free
2224
       the core config memory */
2225
#ifdef Py_REF_DEBUG
2226
    int show_ref_count = tstate->interp->config.show_ref_count;
2227
#endif
2228
#ifdef Py_TRACE_REFS
2229
    int dump_refs = tstate->interp->config.dump_refs;
2230
    wchar_t *dump_refs_file = tstate->interp->config.dump_refs_file;
2231
#endif
2232
0
#ifdef WITH_PYMALLOC
2233
0
    int malloc_stats = tstate->interp->config.malloc_stats;
2234
0
#endif
2235
2236
    /* Ensure that remaining threads are detached */
2237
0
    ASSERT_WORLD_STOPPED(tstate->interp);
2238
2239
    /* Remaining daemon threads will be trapped in PyThread_hang_thread
2240
       when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
2241
0
    _PyInterpreterState_SetFinalizing(tstate->interp, tstate);
2242
0
    _PyRuntimeState_SetFinalizing(runtime, tstate);
2243
0
    runtime->initialized = 0;
2244
0
    runtime->core_initialized = 0;
2245
2246
    // XXX Call something like _PyImport_Disable() here?
2247
2248
    /* Remove the state of all threads of the interpreter, except for the
2249
       current thread. In practice, only daemon threads should still be alive,
2250
       except if wait_for_thread_shutdown() has been cancelled by CTRL+C.
2251
       We start the world once we are the only thread state left,
2252
       before we call destructors. */
2253
0
    PyThreadState *list = _PyThreadState_RemoveExcept(tstate);
2254
0
    for (PyThreadState *p = list; p != NULL; p = p->next) {
2255
0
        _PyThreadState_SetShuttingDown(p);
2256
0
    }
2257
0
    _PyEval_StartTheWorldAll(runtime);
2258
0
    PyMutex_Unlock(&tstate->interp->ceval.pending.mutex);
2259
2260
    /* Clear frames of other threads to call objects destructors. Destructors
2261
       will be called in the current Python thread. Since
2262
       _PyRuntimeState_SetFinalizing() has been called, no other Python thread
2263
       can take the GIL at this point: if they try, they will hang in
2264
       _PyThreadState_HangThread. */
2265
0
    _PyThreadState_DeleteList(list, /*is_after_fork=*/0);
2266
2267
    /* At this point no Python code should be running at all.
2268
       The only thread state left should be the main thread of the main
2269
       interpreter (AKA tstate), in which this code is running right now.
2270
       There may be other OS threads running but none of them will have
2271
       thread states associated with them, nor will be able to create
2272
       new thread states.
2273
2274
       Thus tstate is the only possible thread state from here on out.
2275
       It may still be used during finalization to run Python code as
2276
       needed or provide runtime state (e.g. sys.modules) but that will
2277
       happen sparingly.  Furthermore, the order of finalization aims
2278
       to not need a thread (or interpreter) state as soon as possible.
2279
     */
2280
    // XXX Make sure we are preventing the creating of any new thread states
2281
    // (or interpreters).
2282
2283
    /* Flush sys.stdout and sys.stderr */
2284
0
    if (flush_std_files() < 0) {
2285
0
        status = -1;
2286
0
    }
2287
2288
    /* Disable signal handling */
2289
0
    _PySignal_Fini();
2290
2291
    /* Collect garbage.  This may call finalizers; it's nice to call these
2292
     * before all modules are destroyed.
2293
     * XXX If a __del__ or weakref callback is triggered here, and tries to
2294
     * XXX import a module, bad things can happen, because Python no
2295
     * XXX longer believes it's initialized.
2296
     * XXX     Fatal Python error: Interpreter not initialized (version mismatch?)
2297
     * XXX is easy to provoke that way.  I've also seen, e.g.,
2298
     * XXX     Exception exceptions.ImportError: 'No module named sha'
2299
     * XXX         in <function callback at 0x008F5718> ignored
2300
     * XXX but I'm unclear on exactly how that one happens.  In any case,
2301
     * XXX I haven't seen a real-life report of either of these.
2302
     */
2303
0
    PyGC_Collect();
2304
2305
    /* Destroy all modules */
2306
0
    _PyImport_FiniExternal(tstate->interp);
2307
0
    finalize_modules(tstate);
2308
2309
    /* Print debug stats if any */
2310
0
    _PyEval_Fini();
2311
2312
2313
    /* Flush sys.stdout and sys.stderr (again, in case more was printed) */
2314
0
    if (flush_std_files() < 0) {
2315
0
        status = -1;
2316
0
    }
2317
2318
    /* Collect final garbage.  This disposes of cycles created by
2319
     * class definitions, for example.
2320
     * XXX This is disabled because it caused too many problems.  If
2321
     * XXX a __del__ or weakref callback triggers here, Python code has
2322
     * XXX a hard time running, because even the sys module has been
2323
     * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
2324
     * XXX One symptom is a sequence of information-free messages
2325
     * XXX coming from threads (if a __del__ or callback is invoked,
2326
     * XXX other threads can execute too, and any exception they encounter
2327
     * XXX triggers a comedy of errors as subsystem after subsystem
2328
     * XXX fails to find what it *expects* to find in sys to help report
2329
     * XXX the exception and consequent unexpected failures).  I've also
2330
     * XXX seen segfaults then, after adding print statements to the
2331
     * XXX Python code getting called.
2332
     */
2333
#if 0
2334
    _PyGC_CollectIfEnabled();
2335
#endif
2336
2337
    /* Disable tracemalloc after all Python objects have been destroyed,
2338
       so it is possible to use tracemalloc in objects destructor. */
2339
0
    _PyTraceMalloc_Fini();
2340
2341
    /* Finalize any remaining import state */
2342
    // XXX Move these up to where finalize_modules() is currently.
2343
0
    _PyImport_FiniCore(tstate->interp);
2344
0
    _PyImport_Fini();
2345
2346
    /* unload faulthandler module */
2347
0
    _PyFaulthandler_Fini();
2348
2349
    /* dump hash stats */
2350
0
    _PyHash_Fini();
2351
2352
#ifdef Py_TRACE_REFS
2353
    /* Display all objects still alive -- this can invoke arbitrary
2354
     * __repr__ overrides, so requires a mostly-intact interpreter.
2355
     * Alas, a lot of stuff may still be alive now that will be cleaned
2356
     * up later.
2357
     */
2358
2359
    FILE *dump_refs_fp = NULL;
2360
    if (dump_refs_file != NULL) {
2361
        dump_refs_fp = _Py_wfopen(dump_refs_file, L"w");
2362
        if (dump_refs_fp == NULL) {
2363
            fprintf(stderr, "PYTHONDUMPREFSFILE: cannot create file: %ls\n", dump_refs_file);
2364
        }
2365
    }
2366
2367
    if (dump_refs) {
2368
        _Py_PrintReferences(tstate->interp, stderr);
2369
    }
2370
2371
    if (dump_refs_fp != NULL) {
2372
        _Py_PrintReferences(tstate->interp, dump_refs_fp);
2373
    }
2374
#endif /* Py_TRACE_REFS */
2375
2376
    /* At this point there's almost no other Python code that will run,
2377
       nor interpreter state needed.  The only possibility is the
2378
       finalizers of the objects stored on tstate (and tstate->interp),
2379
       which are triggered via finalize_interp_clear().
2380
2381
       For now we operate as though none of those finalizers actually
2382
       need an operational thread state or interpreter.  In reality,
2383
       those finalizers may rely on some part of tstate or
2384
       tstate->interp, and/or may raise exceptions
2385
       or otherwise fail.
2386
     */
2387
    // XXX Do this sooner during finalization.
2388
    // XXX Ensure finalizer errors are handled properly.
2389
2390
0
    finalize_interp_clear(tstate);
2391
2392
#ifdef _Py_JIT
2393
    /* Free JIT shim memory */
2394
    _PyJIT_Fini();
2395
#endif
2396
2397
#ifdef Py_TRACE_REFS
2398
    /* Display addresses (& refcnts) of all objects still alive.
2399
     * An address can be used to find the repr of the object, printed
2400
     * above by _Py_PrintReferences. */
2401
    if (dump_refs) {
2402
        _Py_PrintReferenceAddresses(tstate->interp, stderr);
2403
    }
2404
    if (dump_refs_fp != NULL) {
2405
        _Py_PrintReferenceAddresses(tstate->interp, dump_refs_fp);
2406
        fclose(dump_refs_fp);
2407
    }
2408
#endif /* Py_TRACE_REFS */
2409
2410
0
#ifdef WITH_PYMALLOC
2411
0
    if (malloc_stats) {
2412
0
        _PyObject_DebugMallocStats(stderr);
2413
0
    }
2414
0
#endif
2415
2416
0
    finalize_interp_delete(tstate->interp);
2417
2418
#ifdef Py_REF_DEBUG
2419
    if (show_ref_count) {
2420
        _PyDebug_PrintTotalRefs();
2421
    }
2422
    _Py_FinalizeRefTotal(runtime);
2423
#endif
2424
0
    _Py_FinalizeAllocatedBlocks(runtime);
2425
2426
0
    call_ll_exitfuncs(runtime);
2427
2428
0
    _PyRuntime_Finalize();
2429
0
    return status;
2430
0
}
2431
2432
int
2433
Py_FinalizeEx(void)
2434
0
{
2435
0
    return _Py_Finalize(&_PyRuntime);
2436
0
}
2437
2438
void
2439
Py_Finalize(void)
2440
0
{
2441
0
    (void)_Py_Finalize(&_PyRuntime);
2442
0
}
2443
2444
2445
/* Create and initialize a new interpreter and thread, and return the
2446
   new thread.  This requires that Py_Initialize() has been called
2447
   first.
2448
2449
   Unsuccessful initialization yields a NULL pointer.  Note that *no*
2450
   exception information is available even in this case -- the
2451
   exception information is held in the thread, and there is no
2452
   thread.
2453
2454
   Locking: as above.
2455
2456
*/
2457
2458
static PyStatus
2459
new_interpreter(PyThreadState **tstate_p,
2460
                const PyInterpreterConfig *config, long whence)
2461
0
{
2462
0
    PyStatus status;
2463
2464
0
    status = _PyRuntime_Initialize();
2465
0
    if (_PyStatus_EXCEPTION(status)) {
2466
0
        return status;
2467
0
    }
2468
0
    _PyRuntimeState *runtime = &_PyRuntime;
2469
2470
0
    if (!runtime->initialized) {
2471
0
        return _PyStatus_ERR("Py_Initialize must be called first");
2472
0
    }
2473
2474
    /* Issue #10915, #15751: The GIL API doesn't work with multiple
2475
       interpreters: disable PyGILState_Check(). */
2476
0
    _Py_atomic_store_int_relaxed(&runtime->gilstate.check_enabled, 0);
2477
2478
    // XXX Might new_interpreter() have been called without the GIL held?
2479
0
    PyThreadState *save_tstate = _PyThreadState_GET();
2480
0
    PyThreadState *tstate = NULL;
2481
0
    PyInterpreterState *interp;
2482
0
    status = _PyInterpreterState_New(save_tstate, &interp);
2483
0
    if (interp == NULL) {
2484
0
        goto error;
2485
0
    }
2486
0
    _PyInterpreterState_SetWhence(interp, whence);
2487
0
    interp->_ready = 1;
2488
2489
    /* Initialize the module dict watcher early, before any modules are created */
2490
0
    if (_PyModule_InitModuleDictWatcher(interp) != 0) {
2491
0
        goto error;
2492
0
    }
2493
2494
    /* From this point until the init_interp_create_gil() call,
2495
       we must not do anything that requires that the GIL be held
2496
       (or otherwise exist).  That applies whether or not the new
2497
       interpreter has its own GIL (e.g. the main interpreter). */
2498
0
    if (save_tstate != NULL) {
2499
0
        _PyThreadState_Detach(save_tstate);
2500
0
    }
2501
2502
    /* Copy the current interpreter config into the new interpreter */
2503
0
    const PyConfig *src_config;
2504
0
    if (save_tstate != NULL) {
2505
0
        src_config = _PyInterpreterState_GetConfig(save_tstate->interp);
2506
0
    }
2507
0
    else
2508
0
    {
2509
        /* No current thread state, copy from the main interpreter */
2510
0
        PyInterpreterState *main_interp = _PyInterpreterState_Main();
2511
0
        src_config = _PyInterpreterState_GetConfig(main_interp);
2512
0
    }
2513
2514
    /* This does not require that the GIL be held. */
2515
0
    status = _PyConfig_Copy(&interp->config, src_config);
2516
0
    if (_PyStatus_EXCEPTION(status)) {
2517
0
        goto error;
2518
0
    }
2519
2520
    /* This does not require that the GIL be held. */
2521
0
    status = init_interp_settings(interp, config);
2522
0
    if (_PyStatus_EXCEPTION(status)) {
2523
0
        goto error;
2524
0
    }
2525
2526
    // This could be done in init_interpreter() (in pystate.c) if it
2527
    // didn't depend on interp->feature_flags being set already.
2528
0
    status = _PyObject_InitState(interp);
2529
0
    if (_PyStatus_EXCEPTION(status)) {
2530
0
        return status;
2531
0
    }
2532
2533
#ifdef Py_STATS
2534
    // initialize pystats.  This must be done after the settings are loaded.
2535
    status = _PyStats_InterpInit(interp);
2536
    if (_PyStatus_EXCEPTION(status)) {
2537
        return status;
2538
    }
2539
#endif
2540
2541
    // initialize the interp->obmalloc state.  This must be done after
2542
    // the settings are loaded (so that feature_flags are set) but before
2543
    // any calls are made to obmalloc functions.
2544
0
    if (_PyMem_init_obmalloc(interp) < 0) {
2545
0
        status = _PyStatus_NO_MEMORY();
2546
0
        goto error;
2547
0
    }
2548
2549
0
    tstate = _PyThreadState_New(interp, _PyThreadState_WHENCE_INIT);
2550
0
    if (tstate == NULL) {
2551
0
        status = _PyStatus_NO_MEMORY();
2552
0
        goto error;
2553
0
    }
2554
2555
0
    _PyThreadState_Bind(tstate);
2556
0
    init_interp_create_gil(tstate, config->gil);
2557
2558
    /* No objects have been created yet. */
2559
2560
0
    status = pycore_interp_init(tstate);
2561
0
    if (_PyStatus_EXCEPTION(status)) {
2562
0
        goto error;
2563
0
    }
2564
2565
0
    status = init_interp_main(tstate);
2566
0
    if (_PyStatus_EXCEPTION(status)) {
2567
0
        goto error;
2568
0
    }
2569
2570
0
    *tstate_p = tstate;
2571
0
    return _PyStatus_OK();
2572
2573
0
error:
2574
0
    *tstate_p = NULL;
2575
0
    if (tstate != NULL) {
2576
0
        Py_EndInterpreter(tstate);
2577
0
    } else if (interp != NULL) {
2578
0
        PyInterpreterState_Delete(interp);
2579
0
    }
2580
0
    if (save_tstate != NULL) {
2581
0
        _PyThreadState_Attach(save_tstate);
2582
0
    }
2583
0
    return status;
2584
0
}
2585
2586
PyStatus
2587
Py_NewInterpreterFromConfig(PyThreadState **tstate_p,
2588
                            const PyInterpreterConfig *config)
2589
0
{
2590
0
    long whence = _PyInterpreterState_WHENCE_CAPI;
2591
0
    return new_interpreter(tstate_p, config, whence);
2592
0
}
2593
2594
PyThreadState *
2595
Py_NewInterpreter(void)
2596
0
{
2597
0
    PyThreadState *tstate = NULL;
2598
0
    long whence = _PyInterpreterState_WHENCE_LEGACY_CAPI;
2599
0
    const PyInterpreterConfig config = _PyInterpreterConfig_LEGACY_INIT;
2600
0
    PyStatus status = new_interpreter(&tstate, &config, whence);
2601
0
    if (_PyStatus_EXCEPTION(status)) {
2602
0
        Py_ExitStatusException(status);
2603
0
    }
2604
0
    return tstate;
2605
0
}
2606
2607
/* Delete an interpreter.  This requires that the given thread state
2608
   is current, and that the thread has no remaining frames.
2609
   It is a fatal error to violate these constraints.
2610
2611
   (Py_FinalizeEx() doesn't have these constraints -- it zaps
2612
   everything, regardless.)
2613
2614
   Locking: as above.
2615
2616
*/
2617
2618
void
2619
Py_EndInterpreter(PyThreadState *tstate)
2620
0
{
2621
0
    PyInterpreterState *interp = tstate->interp;
2622
2623
0
    if (tstate != _PyThreadState_GET()) {
2624
0
        Py_FatalError("thread is not current");
2625
0
    }
2626
0
    if (tstate->current_frame != tstate->base_frame) {
2627
0
        Py_FatalError("thread still has a frame");
2628
0
    }
2629
0
    interp->finalizing = 1;
2630
2631
    // This call stops the world and takes the pending calls lock.
2632
0
    make_pre_finalization_calls(tstate, /*subinterpreters=*/0);
2633
2634
0
    ASSERT_WORLD_STOPPED(interp);
2635
    /* Remaining daemon threads will automatically exit
2636
       when they attempt to take the GIL (ex: PyEval_RestoreThread()). */
2637
0
    _PyInterpreterState_SetFinalizing(interp, tstate);
2638
2639
0
    PyThreadState *list = _PyThreadState_RemoveExcept(tstate);
2640
0
    for (PyThreadState *p = list; p != NULL; p = p->next) {
2641
0
        _PyThreadState_SetShuttingDown(p);
2642
0
    }
2643
2644
0
    _PyEval_StartTheWorldAll(interp->runtime);
2645
0
    PyMutex_Unlock(&interp->ceval.pending.mutex);
2646
0
    _PyThreadState_DeleteList(list, /*is_after_fork=*/0);
2647
2648
    // XXX Call something like _PyImport_Disable() here?
2649
2650
0
    _PyImport_FiniExternal(tstate->interp);
2651
0
    finalize_modules(tstate);
2652
0
    _PyImport_FiniCore(tstate->interp);
2653
2654
0
    finalize_interp_clear(tstate);
2655
0
    finalize_interp_delete(tstate->interp);
2656
0
}
2657
2658
int
2659
_Py_IsInterpreterFinalizing(PyInterpreterState *interp)
2660
205k
{
2661
    /* We check the runtime first since, in a daemon thread,
2662
       interp might be dangling pointer. */
2663
205k
    PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(&_PyRuntime);
2664
205k
    if (finalizing == NULL) {
2665
205k
        finalizing = _PyInterpreterState_GetFinalizing(interp);
2666
205k
    }
2667
205k
    return finalizing != NULL;
2668
205k
}
2669
2670
static void
2671
finalize_subinterpreters(void)
2672
0
{
2673
0
    PyThreadState *final_tstate = _PyThreadState_GET();
2674
0
    PyInterpreterState *main_interp = _PyInterpreterState_Main();
2675
0
    assert(final_tstate->interp == main_interp);
2676
0
    _PyRuntimeState *runtime = main_interp->runtime;
2677
0
    assert(!runtime->stoptheworld.world_stopped);
2678
0
    assert(_PyRuntimeState_GetFinalizing(runtime) == NULL);
2679
0
    struct pyinterpreters *interpreters = &runtime->interpreters;
2680
2681
    /* Get the first interpreter in the list. */
2682
0
    HEAD_LOCK(runtime);
2683
0
    PyInterpreterState *interp = interpreters->head;
2684
0
    if (interp == main_interp) {
2685
0
        interp = interp->next;
2686
0
    }
2687
0
    HEAD_UNLOCK(runtime);
2688
2689
    /* Bail out if there are no subinterpreters left. */
2690
0
    if (interp == NULL) {
2691
0
        return;
2692
0
    }
2693
2694
    /* Warn the user if they forgot to clean up subinterpreters. */
2695
0
    (void)PyErr_WarnEx(
2696
0
            PyExc_RuntimeWarning,
2697
0
            "remaining subinterpreters; "
2698
0
            "close them with Interpreter.close()",
2699
0
            0);
2700
2701
    /* Swap out the current tstate, which we know must belong
2702
       to the main interpreter. */
2703
0
    _PyThreadState_Detach(final_tstate);
2704
2705
    /* Clean up all remaining subinterpreters. */
2706
0
    while (interp != NULL) {
2707
        /* Make a tstate for finalization. */
2708
0
        PyThreadState *tstate = _PyThreadState_NewBound(interp, _PyThreadState_WHENCE_FINI);
2709
0
        if (tstate == NULL) {
2710
            // XXX Some graceful way to always get a thread state?
2711
0
            Py_FatalError("thread state allocation failed");
2712
0
        }
2713
2714
        /* Enter the subinterpreter. */
2715
0
        _PyThreadState_Attach(tstate);
2716
2717
        /* Destroy the subinterpreter. */
2718
0
        Py_EndInterpreter(tstate);
2719
0
        assert(_PyThreadState_GET() == NULL);
2720
2721
        /* Advance to the next interpreter. */
2722
0
        HEAD_LOCK(runtime);
2723
0
        interp = interpreters->head;
2724
0
        if (interp == main_interp) {
2725
0
            interp = interp->next;
2726
0
        }
2727
0
        HEAD_UNLOCK(runtime);
2728
0
    }
2729
2730
    /* Switch back to the main interpreter. */
2731
0
    _PyThreadState_Attach(final_tstate);
2732
0
}
2733
2734
2735
/* Add the __main__ module */
2736
2737
static PyStatus
2738
add_main_module(PyInterpreterState *interp)
2739
34
{
2740
34
    PyObject *m, *d;
2741
34
    m = PyImport_AddModuleObject(&_Py_ID(__main__));
2742
34
    if (m == NULL)
2743
0
        return _PyStatus_ERR("can't create __main__ module");
2744
2745
34
    d = PyModule_GetDict(m);
2746
2747
34
    int has_builtins = PyDict_ContainsString(d, "__builtins__");
2748
34
    if (has_builtins < 0) {
2749
0
        return _PyStatus_ERR("Failed to test __main__.__builtins__");
2750
0
    }
2751
34
    if (!has_builtins) {
2752
34
        PyObject *bimod = PyImport_ImportModule("builtins");
2753
34
        if (bimod == NULL) {
2754
0
            return _PyStatus_ERR("Failed to retrieve builtins module");
2755
0
        }
2756
34
        if (PyDict_SetItemString(d, "__builtins__", bimod) < 0) {
2757
0
            return _PyStatus_ERR("Failed to initialize __main__.__builtins__");
2758
0
        }
2759
34
        Py_DECREF(bimod);
2760
34
    }
2761
2762
    /* Main is a little special - BuiltinImporter is the most appropriate
2763
     * initial setting for its __loader__ attribute. A more suitable value
2764
     * will be set if __main__ gets further initialized later in the startup
2765
     * process.
2766
     */
2767
34
    PyObject *loader;
2768
34
    if (PyDict_GetItemStringRef(d, "__loader__", &loader) < 0) {
2769
0
        return _PyStatus_ERR("Failed to test __main__.__loader__");
2770
0
    }
2771
34
    int has_loader = !(loader == NULL || loader == Py_None);
2772
34
    Py_XDECREF(loader);
2773
34
    if (!has_loader) {
2774
34
        PyObject *loader = _PyImport_GetImportlibLoader(interp,
2775
34
                                                        "BuiltinImporter");
2776
34
        if (loader == NULL) {
2777
0
            return _PyStatus_ERR("Failed to retrieve BuiltinImporter");
2778
0
        }
2779
34
        if (PyDict_SetItemString(d, "__loader__", loader) < 0) {
2780
0
            return _PyStatus_ERR("Failed to initialize __main__.__loader__");
2781
0
        }
2782
34
        Py_DECREF(loader);
2783
34
    }
2784
34
    return _PyStatus_OK();
2785
34
}
2786
2787
/* Import the site module (not into __main__ though) */
2788
2789
static PyStatus
2790
init_import_site(void)
2791
34
{
2792
34
    PyObject *m;
2793
34
    m = PyImport_ImportModule("site");
2794
34
    if (m == NULL) {
2795
0
        return _PyStatus_ERR("Failed to import the site module");
2796
0
    }
2797
34
    Py_DECREF(m);
2798
34
    return _PyStatus_OK();
2799
34
}
2800
2801
/* returns Py_None if the fd is not valid */
2802
static PyObject*
2803
create_stdio(const PyConfig *config, PyObject* io,
2804
    int fd, int write_mode, const char* name,
2805
    const wchar_t* encoding, const wchar_t* errors)
2806
102
{
2807
102
    PyObject *buf = NULL, *stream = NULL, *text = NULL, *raw = NULL, *res;
2808
102
    const char* mode;
2809
102
    const char* newline;
2810
102
    PyObject *line_buffering, *write_through;
2811
102
    int buffering, isatty;
2812
102
    const int buffered_stdio = config->buffered_stdio;
2813
2814
102
    if (!_Py_IsValidFD(fd)) {
2815
0
        Py_RETURN_NONE;
2816
0
    }
2817
2818
    /* stdin is always opened in buffered mode, first because it shouldn't
2819
       make a difference in common use cases, second because TextIOWrapper
2820
       depends on the presence of a read1() method which only exists on
2821
       buffered streams.
2822
    */
2823
102
    if (!buffered_stdio && write_mode)
2824
0
        buffering = 0;
2825
102
    else
2826
102
        buffering = -1;
2827
102
    if (write_mode)
2828
68
        mode = "wb";
2829
34
    else
2830
34
        mode = "rb";
2831
102
    buf = _PyObject_CallMethod(io, &_Py_ID(open), "isiOOOO",
2832
102
                               fd, mode, buffering,
2833
102
                               Py_None, Py_None, /* encoding, errors */
2834
102
                               Py_None, Py_False); /* newline, closefd */
2835
102
    if (buf == NULL)
2836
0
        goto error;
2837
2838
102
    if (buffering) {
2839
102
        raw = PyObject_GetAttr(buf, &_Py_ID(raw));
2840
102
        if (raw == NULL)
2841
0
            goto error;
2842
102
    }
2843
0
    else {
2844
0
        raw = Py_NewRef(buf);
2845
0
    }
2846
2847
#ifdef HAVE_WINDOWS_CONSOLE_IO
2848
    /* Windows console IO is always UTF-8 encoded */
2849
    PyTypeObject *winconsoleio_type = (PyTypeObject *)PyImport_ImportModuleAttr(
2850
            &_Py_ID(_io), &_Py_ID(_WindowsConsoleIO));
2851
    if (winconsoleio_type == NULL) {
2852
        goto error;
2853
    }
2854
    int is_subclass = PyObject_TypeCheck(raw, winconsoleio_type);
2855
    Py_DECREF(winconsoleio_type);
2856
    if (is_subclass) {
2857
        encoding = L"utf-8";
2858
    }
2859
#endif
2860
2861
102
    text = PyUnicode_FromString(name);
2862
102
    if (text == NULL || PyObject_SetAttr(raw, &_Py_ID(name), text) < 0)
2863
0
        goto error;
2864
102
    res = PyObject_CallMethodNoArgs(raw, &_Py_ID(isatty));
2865
102
    if (res == NULL)
2866
0
        goto error;
2867
102
    isatty = PyObject_IsTrue(res);
2868
102
    Py_DECREF(res);
2869
102
    if (isatty == -1)
2870
0
        goto error;
2871
102
    if (!buffered_stdio)
2872
0
        write_through = Py_True;
2873
102
    else
2874
102
        write_through = Py_False;
2875
102
    if (buffered_stdio && (isatty || fd == fileno(stderr)))
2876
34
        line_buffering = Py_True;
2877
68
    else
2878
68
        line_buffering = Py_False;
2879
2880
102
    Py_CLEAR(raw);
2881
102
    Py_CLEAR(text);
2882
2883
#ifdef MS_WINDOWS
2884
    /* sys.stdin: enable universal newline mode, translate "\r\n" and "\r"
2885
       newlines to "\n".
2886
       sys.stdout and sys.stderr: translate "\n" to "\r\n". */
2887
    newline = NULL;
2888
#else
2889
    /* sys.stdin: split lines at "\n".
2890
       sys.stdout and sys.stderr: don't translate newlines (use "\n"). */
2891
102
    newline = "\n";
2892
102
#endif
2893
2894
102
    PyObject *encoding_str = PyUnicode_FromWideChar(encoding, -1);
2895
102
    if (encoding_str == NULL) {
2896
0
        Py_CLEAR(buf);
2897
0
        goto error;
2898
0
    }
2899
2900
102
    PyObject *errors_str = PyUnicode_FromWideChar(errors, -1);
2901
102
    if (errors_str == NULL) {
2902
0
        Py_CLEAR(buf);
2903
0
        Py_CLEAR(encoding_str);
2904
0
        goto error;
2905
0
    }
2906
2907
102
    stream = _PyObject_CallMethod(io, &_Py_ID(TextIOWrapper), "OOOsOO",
2908
102
                                  buf, encoding_str, errors_str,
2909
102
                                  newline, line_buffering, write_through);
2910
102
    Py_CLEAR(buf);
2911
102
    Py_CLEAR(encoding_str);
2912
102
    Py_CLEAR(errors_str);
2913
102
    if (stream == NULL)
2914
0
        goto error;
2915
2916
102
    if (write_mode)
2917
68
        mode = "w";
2918
34
    else
2919
34
        mode = "r";
2920
102
    text = PyUnicode_FromString(mode);
2921
102
    if (!text || PyObject_SetAttr(stream, &_Py_ID(mode), text) < 0)
2922
0
        goto error;
2923
102
    Py_CLEAR(text);
2924
102
    return stream;
2925
2926
0
error:
2927
0
    Py_XDECREF(buf);
2928
0
    Py_XDECREF(stream);
2929
0
    Py_XDECREF(text);
2930
0
    Py_XDECREF(raw);
2931
2932
0
    if (PyErr_ExceptionMatches(PyExc_OSError) && !_Py_IsValidFD(fd)) {
2933
        /* Issue #24891: the file descriptor was closed after the first
2934
           _Py_IsValidFD() check was called. Ignore the OSError and set the
2935
           stream to None. */
2936
0
        PyErr_Clear();
2937
0
        Py_RETURN_NONE;
2938
0
    }
2939
0
    return NULL;
2940
0
}
2941
2942
/* Set builtins.open to io.open */
2943
static PyStatus
2944
init_set_builtins_open(void)
2945
34
{
2946
34
    PyObject *wrapper;
2947
34
    PyObject *bimod = NULL;
2948
34
    PyStatus res = _PyStatus_OK();
2949
2950
34
    if (!(bimod = PyImport_ImportModule("builtins"))) {
2951
0
        goto error;
2952
0
    }
2953
2954
34
    if (!(wrapper = PyImport_ImportModuleAttrString("_io", "open"))) {
2955
0
        goto error;
2956
0
    }
2957
2958
    /* Set builtins.open */
2959
34
    if (PyObject_SetAttrString(bimod, "open", wrapper) == -1) {
2960
0
        Py_DECREF(wrapper);
2961
0
        goto error;
2962
0
    }
2963
34
    Py_DECREF(wrapper);
2964
34
    goto done;
2965
2966
0
error:
2967
0
    res = _PyStatus_ERR("can't initialize io.open");
2968
2969
34
done:
2970
34
    Py_XDECREF(bimod);
2971
34
    return res;
2972
0
}
2973
2974
2975
/* Create sys.stdin, sys.stdout and sys.stderr */
2976
static PyStatus
2977
init_sys_streams(PyThreadState *tstate)
2978
34
{
2979
34
    PyObject *iomod = NULL;
2980
34
    PyObject *std = NULL;
2981
34
    int fd;
2982
34
    PyObject * encoding_attr;
2983
34
    PyStatus res = _PyStatus_OK();
2984
34
    const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
2985
2986
    /* Check that stdin is not a directory
2987
       Using shell redirection, you can redirect stdin to a directory,
2988
       crashing the Python interpreter. Catch this common mistake here
2989
       and output a useful error message. Note that under MS Windows,
2990
       the shell already prevents that. */
2991
34
#ifndef MS_WINDOWS
2992
34
    struct _Py_stat_struct sb;
2993
34
    if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
2994
34
        S_ISDIR(sb.st_mode)) {
2995
0
        return _PyStatus_ERR("<stdin> is a directory, cannot continue");
2996
0
    }
2997
34
#endif
2998
2999
34
    if (!(iomod = PyImport_ImportModule("_io"))) {
3000
0
        goto error;
3001
0
    }
3002
3003
    /* Set sys.stdin */
3004
34
    fd = fileno(stdin);
3005
    /* Under some conditions stdin, stdout and stderr may not be connected
3006
     * and fileno() may point to an invalid file descriptor. For example
3007
     * GUI apps don't have valid standard streams by default.
3008
     */
3009
34
    std = create_stdio(config, iomod, fd, 0, "<stdin>",
3010
34
                       config->stdio_encoding,
3011
34
                       config->stdio_errors);
3012
34
    if (std == NULL)
3013
0
        goto error;
3014
34
    PySys_SetObject("__stdin__", std);
3015
34
    _PySys_SetAttr(&_Py_ID(stdin), std);
3016
34
    Py_DECREF(std);
3017
3018
    /* Set sys.stdout */
3019
34
    fd = fileno(stdout);
3020
34
    std = create_stdio(config, iomod, fd, 1, "<stdout>",
3021
34
                       config->stdio_encoding,
3022
34
                       config->stdio_errors);
3023
34
    if (std == NULL)
3024
0
        goto error;
3025
34
    PySys_SetObject("__stdout__", std);
3026
34
    _PySys_SetAttr(&_Py_ID(stdout), std);
3027
34
    Py_DECREF(std);
3028
3029
34
#if 1 /* Disable this if you have trouble debugging bootstrap stuff */
3030
    /* Set sys.stderr, replaces the preliminary stderr */
3031
34
    fd = fileno(stderr);
3032
34
    std = create_stdio(config, iomod, fd, 1, "<stderr>",
3033
34
                       config->stdio_encoding,
3034
34
                       L"backslashreplace");
3035
34
    if (std == NULL)
3036
0
        goto error;
3037
3038
    /* Same as hack above, pre-import stderr's codec to avoid recursion
3039
       when import.c tries to write to stderr in verbose mode. */
3040
34
    encoding_attr = PyObject_GetAttrString(std, "encoding");
3041
34
    if (encoding_attr != NULL) {
3042
34
        const char *std_encoding = PyUnicode_AsUTF8(encoding_attr);
3043
34
        if (std_encoding != NULL) {
3044
34
            PyObject *codec_info = _PyCodec_Lookup(std_encoding);
3045
34
            Py_XDECREF(codec_info);
3046
34
        }
3047
34
        Py_DECREF(encoding_attr);
3048
34
    }
3049
34
    _PyErr_Clear(tstate);  /* Not a fatal error if codec isn't available */
3050
3051
34
    if (PySys_SetObject("__stderr__", std) < 0) {
3052
0
        Py_DECREF(std);
3053
0
        goto error;
3054
0
    }
3055
34
    if (_PySys_SetAttr(&_Py_ID(stderr), std) < 0) {
3056
0
        Py_DECREF(std);
3057
0
        goto error;
3058
0
    }
3059
34
    Py_DECREF(std);
3060
34
#endif
3061
3062
34
    goto done;
3063
3064
0
error:
3065
0
    res = _PyStatus_ERR("can't initialize sys standard streams");
3066
3067
34
done:
3068
34
    Py_XDECREF(iomod);
3069
34
    return res;
3070
0
}
3071
3072
3073
#ifdef __ANDROID__
3074
#include <android/log.h>
3075
3076
static PyObject *
3077
android_log_write_impl(PyObject *self, PyObject *args)
3078
{
3079
    int prio = 0;
3080
    const char *tag = NULL;
3081
    const char *text = NULL;
3082
    if (!PyArg_ParseTuple(args, "isy", &prio, &tag, &text)) {
3083
        return NULL;
3084
    }
3085
3086
    // Despite its name, this function is part of the public API
3087
    // (https://developer.android.com/ndk/reference/group/logging).
3088
    __android_log_write(prio, tag, text);
3089
    Py_RETURN_NONE;
3090
}
3091
3092
3093
static PyMethodDef android_log_write_method = {
3094
    "android_log_write", android_log_write_impl, METH_VARARGS
3095
};
3096
3097
3098
static PyStatus
3099
init_android_streams(PyThreadState *tstate)
3100
{
3101
    PyStatus status = _PyStatus_OK();
3102
    PyObject *_android_support = NULL;
3103
    PyObject *android_log_write = NULL;
3104
    PyObject *result = NULL;
3105
3106
    _android_support = PyImport_ImportModule("_android_support");
3107
    if (_android_support == NULL) {
3108
        goto error;
3109
    }
3110
3111
    android_log_write = PyCFunction_New(&android_log_write_method, NULL);
3112
    if (android_log_write == NULL) {
3113
        goto error;
3114
    }
3115
3116
    // These log priorities match those used by Java's System.out and System.err.
3117
    result = PyObject_CallMethod(
3118
        _android_support, "init_streams", "Oii",
3119
        android_log_write, ANDROID_LOG_INFO, ANDROID_LOG_WARN);
3120
    if (result == NULL) {
3121
        goto error;
3122
    }
3123
3124
    goto done;
3125
3126
error:
3127
    _PyErr_Print(tstate);
3128
    status = _PyStatus_ERR("failed to initialize Android streams");
3129
3130
done:
3131
    Py_XDECREF(result);
3132
    Py_XDECREF(android_log_write);
3133
    Py_XDECREF(_android_support);
3134
    return status;
3135
}
3136
3137
#endif  // __ANDROID__
3138
3139
#if defined(__APPLE__) && HAS_APPLE_SYSTEM_LOG
3140
3141
static PyObject *
3142
apple_log_write_impl(PyObject *self, PyObject *args)
3143
{
3144
    int logtype = 0;
3145
    const char *text = NULL;
3146
    if (!PyArg_ParseTuple(args, "iy", &logtype, &text)) {
3147
        return NULL;
3148
    }
3149
3150
    // Pass the user-provided text through explicit %s formatting
3151
    // to avoid % literals being interpreted as a formatting directive.
3152
    os_log_with_type(OS_LOG_DEFAULT, logtype, "%s", text);
3153
    Py_RETURN_NONE;
3154
}
3155
3156
3157
static PyMethodDef apple_log_write_method = {
3158
    "apple_log_write", apple_log_write_impl, METH_VARARGS
3159
};
3160
3161
3162
static PyStatus
3163
init_apple_streams(PyThreadState *tstate)
3164
{
3165
    PyStatus status = _PyStatus_OK();
3166
    PyObject *_apple_support = NULL;
3167
    PyObject *apple_log_write = NULL;
3168
    PyObject *result = NULL;
3169
3170
    _apple_support = PyImport_ImportModule("_apple_support");
3171
    if (_apple_support == NULL) {
3172
        goto error;
3173
    }
3174
3175
    apple_log_write = PyCFunction_New(&apple_log_write_method, NULL);
3176
    if (apple_log_write == NULL) {
3177
        goto error;
3178
    }
3179
3180
    // Initialize the logging streams, sending stdout -> Default; stderr -> Error
3181
    result = PyObject_CallMethod(
3182
        _apple_support, "init_streams", "Oii",
3183
        apple_log_write, OS_LOG_TYPE_DEFAULT, OS_LOG_TYPE_ERROR);
3184
    if (result == NULL) {
3185
        goto error;
3186
    }
3187
    goto done;
3188
3189
error:
3190
    _PyErr_Print(tstate);
3191
    status = _PyStatus_ERR("failed to initialize Apple log streams");
3192
3193
done:
3194
    Py_XDECREF(result);
3195
    Py_XDECREF(apple_log_write);
3196
    Py_XDECREF(_apple_support);
3197
    return status;
3198
}
3199
3200
#endif  // __APPLE__ && HAS_APPLE_SYSTEM_LOG
3201
3202
3203
static void
3204
_Py_FatalError_DumpTracebacks(int fd, PyInterpreterState *interp,
3205
                              PyThreadState *tstate)
3206
0
{
3207
0
    PUTS(fd, "\n");
3208
3209
    /* display the current Python stack */
3210
0
#ifndef Py_GIL_DISABLED
3211
0
    _Py_DumpTracebackThreads(fd, interp, tstate);
3212
#else
3213
    _Py_DumpTraceback(fd, tstate);
3214
#endif
3215
0
}
3216
3217
/* Print the current exception (if an exception is set) with its traceback,
3218
   or display the current Python stack.
3219
3220
   Don't call PyErr_PrintEx() and the except hook, because Py_FatalError() is
3221
   called on catastrophic cases.
3222
3223
   Return 1 if the traceback was displayed, 0 otherwise. */
3224
3225
static int
3226
_Py_FatalError_PrintExc(PyThreadState *tstate)
3227
0
{
3228
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
3229
0
    if (exc == NULL) {
3230
        /* No current exception */
3231
0
        return 0;
3232
0
    }
3233
3234
0
    PyObject *ferr;
3235
0
    if (PySys_GetOptionalAttr(&_Py_ID(stderr), &ferr) < 0) {
3236
0
        _PyErr_Clear(tstate);
3237
0
    }
3238
0
    if (ferr == NULL || ferr == Py_None) {
3239
        /* sys.stderr is not set yet or set to None,
3240
           no need to try to display the exception */
3241
0
        Py_XDECREF(ferr);
3242
0
        Py_DECREF(exc);
3243
0
        return 0;
3244
0
    }
3245
3246
0
    PyErr_DisplayException(exc);
3247
3248
0
    PyObject *tb = PyException_GetTraceback(exc);
3249
0
    int has_tb = (tb != NULL) && (tb != Py_None);
3250
0
    Py_XDECREF(tb);
3251
0
    Py_DECREF(exc);
3252
3253
    /* sys.stderr may be buffered: call sys.stderr.flush() */
3254
0
    if (_PyFile_Flush(ferr) < 0) {
3255
0
        _PyErr_Clear(tstate);
3256
0
    }
3257
0
    Py_DECREF(ferr);
3258
3259
0
    return has_tb;
3260
0
}
3261
3262
/* Print fatal error message and abort */
3263
3264
#ifdef MS_WINDOWS
3265
static void
3266
fatal_output_debug(const char *msg)
3267
{
3268
    /* buffer of 256 bytes allocated on the stack */
3269
    WCHAR buffer[256 / sizeof(WCHAR)];
3270
    size_t buflen = Py_ARRAY_LENGTH(buffer) - 1;
3271
    size_t msglen;
3272
3273
    OutputDebugStringW(L"Fatal Python error: ");
3274
3275
    msglen = strlen(msg);
3276
    while (msglen) {
3277
        size_t i;
3278
3279
        if (buflen > msglen) {
3280
            buflen = msglen;
3281
        }
3282
3283
        /* Convert the message to wchar_t. This uses a simple one-to-one
3284
           conversion, assuming that the this error message actually uses
3285
           ASCII only. If this ceases to be true, we will have to convert. */
3286
        for (i=0; i < buflen; ++i) {
3287
            buffer[i] = msg[i];
3288
        }
3289
        buffer[i] = L'\0';
3290
        OutputDebugStringW(buffer);
3291
3292
        msg += buflen;
3293
        msglen -= buflen;
3294
    }
3295
    OutputDebugStringW(L"\n");
3296
}
3297
#endif
3298
3299
3300
static void
3301
fatal_error_dump_runtime(int fd, _PyRuntimeState *runtime)
3302
0
{
3303
0
    PUTS(fd, "Python runtime state: ");
3304
0
    PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
3305
0
    if (finalizing) {
3306
0
        PUTS(fd, "finalizing (tstate=0x");
3307
0
        _Py_DumpHexadecimal(fd, (uintptr_t)finalizing, sizeof(finalizing) * 2);
3308
0
        PUTS(fd, ")");
3309
0
    }
3310
0
    else if (runtime->initialized) {
3311
0
        PUTS(fd, "initialized");
3312
0
    }
3313
0
    else if (runtime->core_initialized) {
3314
0
        PUTS(fd, "core initialized");
3315
0
    }
3316
0
    else if (runtime->preinitialized) {
3317
0
        PUTS(fd, "preinitialized");
3318
0
    }
3319
0
    else if (runtime->preinitializing) {
3320
0
        PUTS(fd, "preinitializing");
3321
0
    }
3322
0
    else {
3323
0
        PUTS(fd, "unknown");
3324
0
    }
3325
0
    PUTS(fd, "\n");
3326
0
}
3327
3328
3329
static inline void _Py_NO_RETURN
3330
fatal_error_exit(int status)
3331
0
{
3332
0
    if (status < 0) {
3333
#if defined(MS_WINDOWS) && defined(Py_DEBUG)
3334
        DebugBreak();
3335
#endif
3336
0
        abort();
3337
0
    }
3338
0
    else {
3339
0
        exit(status);
3340
0
    }
3341
0
}
3342
3343
static inline int
3344
acquire_dict_lock_for_dump(PyObject *obj)
3345
0
{
3346
#ifdef Py_GIL_DISABLED
3347
    PyMutex *mutex = &obj->ob_mutex;
3348
    if (_PyMutex_LockTimed(mutex, 0, 0) == PY_LOCK_ACQUIRED) {
3349
        return 1;
3350
    }
3351
    return 0;
3352
#else
3353
0
    return 1;
3354
0
#endif
3355
0
}
3356
3357
static inline void
3358
release_dict_lock_for_dump(PyObject *obj)
3359
0
{
3360
#ifdef Py_GIL_DISABLED
3361
    PyMutex *mutex = &obj->ob_mutex;
3362
    // We can not call PyMutex_Unlock because it's not async-signal-safe.
3363
    // So not to wake up other threads, we just use a simple atomic store in here.
3364
    _Py_atomic_store_uint8(&mutex->_bits, _Py_UNLOCKED);
3365
#endif
3366
0
}
3367
3368
// Dump the list of extension modules of sys.modules, excluding stdlib modules
3369
// (sys.stdlib_module_names), into fd file descriptor.
3370
//
3371
// This function is called by a signal handler in faulthandler: avoid memory
3372
// allocations and keep the implementation simple. For example, the list is not
3373
// sorted on purpose.
3374
void
3375
_Py_DumpExtensionModules(int fd, PyInterpreterState *interp)
3376
0
{
3377
0
    if (interp == NULL) {
3378
0
        return;
3379
0
    }
3380
0
    PyObject *modules = _PyImport_GetModules(interp);
3381
0
    if (modules == NULL || !PyDict_Check(modules)) {
3382
0
        return;
3383
0
    }
3384
3385
0
    Py_ssize_t pos;
3386
0
    PyObject *key, *value;
3387
3388
    // Avoid PyDict_GetItemString() which calls PyUnicode_FromString(),
3389
    // memory cannot be allocated on the heap in a signal handler.
3390
    // Iterate on the dict instead.
3391
0
    PyObject *stdlib_module_names = NULL;
3392
0
    if (interp->sysdict != NULL) {
3393
0
        pos = 0;
3394
0
        if (!acquire_dict_lock_for_dump(interp->sysdict)) {
3395
            // If we cannot acquire the lock, just don't dump the list of extension modules.
3396
0
            return;
3397
0
        }
3398
0
        while (_PyDict_Next(interp->sysdict, &pos, &key, &value, NULL)) {
3399
0
            if (PyUnicode_Check(key)
3400
0
               && PyUnicode_CompareWithASCIIString(key, "stdlib_module_names") == 0) {
3401
0
                stdlib_module_names = value;
3402
0
                break;
3403
0
            }
3404
0
        }
3405
0
        release_dict_lock_for_dump(interp->sysdict);
3406
0
    }
3407
    // If we failed to get sys.stdlib_module_names or it's not a frozenset,
3408
    // don't exclude stdlib modules.
3409
0
    if (stdlib_module_names != NULL && !PyFrozenSet_Check(stdlib_module_names)) {
3410
0
        stdlib_module_names = NULL;
3411
0
    }
3412
3413
    // List extensions
3414
0
    int header = 1;
3415
0
    Py_ssize_t count = 0;
3416
0
    pos = 0;
3417
0
    if (!acquire_dict_lock_for_dump(modules)) {
3418
        // If we cannot acquire the lock, just don't dump the list of extension modules.
3419
0
        return;
3420
0
    }
3421
0
    while (_PyDict_Next(modules, &pos, &key, &value, NULL)) {
3422
0
        if (!PyUnicode_Check(key)) {
3423
0
            continue;
3424
0
        }
3425
0
        if (!_PyModule_IsExtension(value)) {
3426
0
            continue;
3427
0
        }
3428
        // Use the module name from the sys.modules key,
3429
        // don't attempt to get the module object name.
3430
0
        if (stdlib_module_names != NULL) {
3431
0
            int is_stdlib_ext = 0;
3432
3433
0
            Py_ssize_t i = 0;
3434
0
            PyObject *item;
3435
0
            Py_hash_t hash;
3436
            // if stdlib_module_names is not NULL, it is always a frozenset.
3437
0
            while (_PySet_NextEntry(stdlib_module_names, &i, &item, &hash)) {
3438
0
                if (!PyUnicode_Check(item)) {
3439
0
                    continue;
3440
0
                }
3441
0
                Py_ssize_t len = PyUnicode_GET_LENGTH(item);
3442
0
                if (PyUnicode_Tailmatch(key, item, 0, len, -1) == 1) {
3443
0
                    Py_ssize_t key_len = PyUnicode_GET_LENGTH(key);
3444
0
                    if (key_len == len) {
3445
0
                        is_stdlib_ext = 1;
3446
0
                        break;
3447
0
                    }
3448
0
                    assert(key_len > len);
3449
3450
                    // Ignore sub-modules of stdlib packages. For example,
3451
                    // ignore "math.integer" if key starts with "math.".
3452
0
                    Py_UCS4 ch = PyUnicode_ReadChar(key, len);
3453
0
                    if (ch == '.') {
3454
0
                        is_stdlib_ext = 1;
3455
0
                        break;
3456
0
                    }
3457
0
                }
3458
0
            }
3459
0
            if (is_stdlib_ext) {
3460
                // Ignore stdlib extension
3461
0
                continue;
3462
0
            }
3463
0
        }
3464
3465
0
        if (header) {
3466
0
            PUTS(fd, "\nExtension modules: ");
3467
0
            header = 0;
3468
0
        }
3469
0
        else {
3470
0
            PUTS(fd, ", ");
3471
0
        }
3472
3473
0
        _Py_DumpASCII(fd, key);
3474
0
        count++;
3475
0
    }
3476
0
    release_dict_lock_for_dump(modules);
3477
3478
0
    if (count) {
3479
0
        PUTS(fd, " (total: ");
3480
0
        _Py_DumpDecimal(fd, count);
3481
0
        PUTS(fd, ")");
3482
0
        PUTS(fd, "\n");
3483
0
    }
3484
0
}
3485
3486
3487
static void _Py_NO_RETURN
3488
fatal_error(int fd, int header, const char *prefix, const char *msg,
3489
            int status)
3490
0
{
3491
0
    static int reentrant = 0;
3492
3493
0
    if (reentrant) {
3494
        /* Py_FatalError() caused a second fatal error.
3495
           Example: flush_std_files() raises a recursion error. */
3496
0
        fatal_error_exit(status);
3497
0
    }
3498
0
    reentrant = 1;
3499
3500
0
    if (header) {
3501
0
        PUTS(fd, "Fatal Python error: ");
3502
0
        if (prefix) {
3503
0
            PUTS(fd, prefix);
3504
0
            PUTS(fd, ": ");
3505
0
        }
3506
0
        if (msg) {
3507
0
            PUTS(fd, msg);
3508
0
        }
3509
0
        else {
3510
0
            PUTS(fd, "<message not set>");
3511
0
        }
3512
0
        PUTS(fd, "\n");
3513
0
    }
3514
3515
0
    _PyRuntimeState *runtime = &_PyRuntime;
3516
0
    fatal_error_dump_runtime(fd, runtime);
3517
3518
    /* Check if the current thread has a Python thread state
3519
       and holds the GIL.
3520
3521
       tss_tstate is NULL if Py_FatalError() is called from a C thread which
3522
       has no Python thread state.
3523
3524
       tss_tstate != tstate if the current Python thread does not hold the GIL.
3525
       */
3526
0
    PyThreadState *tstate = _PyThreadState_GET();
3527
0
    PyInterpreterState *interp = NULL;
3528
0
    PyThreadState *tss_tstate = PyGILState_GetThisThreadState();
3529
0
    if (tstate != NULL) {
3530
0
        interp = tstate->interp;
3531
0
    }
3532
0
    else if (tss_tstate != NULL) {
3533
0
        interp = tss_tstate->interp;
3534
0
    }
3535
0
    int has_tstate_and_gil = (tss_tstate != NULL && tss_tstate == tstate);
3536
3537
0
    if (has_tstate_and_gil) {
3538
        /* If an exception is set, print the exception with its traceback */
3539
0
        if (!_Py_FatalError_PrintExc(tss_tstate)) {
3540
            /* No exception is set, or an exception is set without traceback */
3541
0
            _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
3542
0
        }
3543
0
    }
3544
0
    else {
3545
0
        _Py_FatalError_DumpTracebacks(fd, interp, tss_tstate);
3546
0
    }
3547
3548
0
    _Py_DumpExtensionModules(fd, interp);
3549
3550
    /* The main purpose of faulthandler is to display the traceback.
3551
       This function already did its best to display a traceback.
3552
       Disable faulthandler to prevent writing a second traceback
3553
       on abort(). */
3554
0
    _PyFaulthandler_Fini();
3555
3556
    /* Check if the current Python thread hold the GIL */
3557
0
    if (has_tstate_and_gil) {
3558
        /* Flush sys.stdout and sys.stderr */
3559
0
        flush_std_files();
3560
0
    }
3561
3562
#ifdef MS_WINDOWS
3563
    fatal_output_debug(msg);
3564
#endif /* MS_WINDOWS */
3565
3566
0
    fatal_error_exit(status);
3567
0
}
3568
3569
3570
#undef Py_FatalError
3571
3572
void _Py_NO_RETURN
3573
Py_FatalError(const char *msg)
3574
0
{
3575
0
    fatal_error(fileno(stderr), 1, NULL, msg, -1);
3576
0
}
3577
3578
3579
void _Py_NO_RETURN
3580
_Py_FatalErrorFunc(const char *func, const char *msg)
3581
0
{
3582
0
    fatal_error(fileno(stderr), 1, func, msg, -1);
3583
0
}
3584
3585
3586
void _Py_NO_RETURN
3587
_Py_FatalErrorFormat(const char *func, const char *format, ...)
3588
0
{
3589
0
    static int reentrant = 0;
3590
0
    if (reentrant) {
3591
        /* _Py_FatalErrorFormat() caused a second fatal error */
3592
0
        fatal_error_exit(-1);
3593
0
    }
3594
0
    reentrant = 1;
3595
3596
0
    FILE *stream = stderr;
3597
0
    const int fd = fileno(stream);
3598
0
    PUTS(fd, "Fatal Python error: ");
3599
0
    if (func) {
3600
0
        PUTS(fd, func);
3601
0
        PUTS(fd, ": ");
3602
0
    }
3603
3604
0
    va_list vargs;
3605
0
    va_start(vargs, format);
3606
0
    vfprintf(stream, format, vargs);
3607
0
    va_end(vargs);
3608
3609
0
    fputs("\n", stream);
3610
0
    fflush(stream);
3611
3612
0
    fatal_error(fd, 0, NULL, NULL, -1);
3613
0
}
3614
3615
3616
void _Py_NO_RETURN
3617
_Py_FatalRefcountErrorFunc(const char *func, const char *msg)
3618
0
{
3619
0
    _Py_FatalErrorFormat(func,
3620
0
                         "%s: bug likely caused by a refcount error "
3621
0
                         "in a C extension",
3622
0
                         msg);
3623
0
}
3624
3625
3626
void _Py_NO_RETURN
3627
Py_ExitStatusException(PyStatus status)
3628
0
{
3629
0
    if (_PyStatus_IS_EXIT(status)) {
3630
0
        exit(status.exitcode);
3631
0
    }
3632
0
    else if (_PyStatus_IS_ERROR(status)) {
3633
0
        fatal_error(fileno(stderr), 1, status.func, status.err_msg, 1);
3634
0
    }
3635
0
    else {
3636
0
        Py_FatalError("Py_ExitStatusException() must not be called on success");
3637
0
    }
3638
0
}
3639
3640
3641
static void
3642
handle_thread_shutdown_exception(PyThreadState *tstate)
3643
0
{
3644
0
    assert(tstate != NULL);
3645
0
    assert(_PyErr_Occurred(tstate));
3646
0
    PyInterpreterState *interp = tstate->interp;
3647
0
    assert(interp->threads.head != NULL);
3648
0
    _PyEval_StopTheWorld(interp);
3649
3650
    // We don't have to worry about locking this because the
3651
    // world is stopped.
3652
0
    _Py_FOR_EACH_TSTATE_UNLOCKED(interp, tstate) {
3653
0
        if (tstate->_whence == _PyThreadState_WHENCE_THREADING) {
3654
0
            tstate->_whence = _PyThreadState_WHENCE_THREADING_DAEMON;
3655
0
        }
3656
0
    }
3657
3658
0
    _PyEval_StartTheWorld(interp);
3659
0
    PyErr_FormatUnraisable("Exception ignored on threading shutdown");
3660
0
}
3661
3662
/* Wait until threading._shutdown completes, provided
3663
   the threading module was imported in the first place.
3664
   The shutdown routine will wait until all non-daemon
3665
   "threading" threads have completed. */
3666
static void
3667
wait_for_thread_shutdown(PyThreadState *tstate)
3668
0
{
3669
0
    PyObject *result;
3670
0
    PyObject *threading = PyImport_GetModule(&_Py_ID(threading));
3671
0
    if (threading == NULL) {
3672
0
        if (_PyErr_Occurred(tstate)) {
3673
0
            handle_thread_shutdown_exception(tstate);
3674
0
        }
3675
        /* else: threading not imported */
3676
0
        return;
3677
0
    }
3678
0
    result = PyObject_CallMethodNoArgs(threading, &_Py_ID(_shutdown));
3679
0
    if (result == NULL) {
3680
0
        handle_thread_shutdown_exception(tstate);
3681
0
    }
3682
0
    else {
3683
0
        Py_DECREF(result);
3684
0
    }
3685
0
    Py_DECREF(threading);
3686
0
}
3687
3688
int Py_AtExit(void (*func)(void))
3689
0
{
3690
0
    struct _atexit_runtime_state *state = &_PyRuntime.atexit;
3691
0
    PyMutex_Lock(&state->mutex);
3692
0
    if (state->ncallbacks >= NEXITFUNCS) {
3693
0
        PyMutex_Unlock(&state->mutex);
3694
0
        return -1;
3695
0
    }
3696
0
    state->callbacks[state->ncallbacks++] = func;
3697
0
    PyMutex_Unlock(&state->mutex);
3698
0
    return 0;
3699
0
}
3700
3701
static void
3702
call_ll_exitfuncs(_PyRuntimeState *runtime)
3703
0
{
3704
0
    atexit_callbackfunc exitfunc;
3705
0
    struct _atexit_runtime_state *state = &runtime->atexit;
3706
3707
0
    PyMutex_Lock(&state->mutex);
3708
0
    while (state->ncallbacks > 0) {
3709
        /* pop last function from the list */
3710
0
        state->ncallbacks--;
3711
0
        exitfunc = state->callbacks[state->ncallbacks];
3712
0
        state->callbacks[state->ncallbacks] = NULL;
3713
3714
0
        PyMutex_Unlock(&state->mutex);
3715
0
        exitfunc();
3716
0
        PyMutex_Lock(&state->mutex);
3717
0
    }
3718
0
    PyMutex_Unlock(&state->mutex);
3719
3720
0
    fflush(stdout);
3721
0
    fflush(stderr);
3722
0
}
3723
3724
void _Py_NO_RETURN
3725
Py_Exit(int sts)
3726
0
{
3727
0
    PyThreadState *tstate = _PyThreadState_GET();
3728
0
    if (tstate != NULL && _PyThreadState_IsRunningMain(tstate)) {
3729
0
        _PyInterpreterState_SetNotRunningMain(tstate->interp);
3730
0
    }
3731
0
    if (_Py_Finalize(&_PyRuntime) < 0) {
3732
0
        sts = 120;
3733
0
    }
3734
3735
0
    exit(sts);
3736
0
}
3737
3738
3739
/*
3740
 * The file descriptor fd is considered ``interactive'' if either
3741
 *   a) isatty(fd) is TRUE, or
3742
 *   b) the -i flag was given, and the filename associated with
3743
 *      the descriptor is NULL or "<stdin>" or "???".
3744
 */
3745
int
3746
Py_FdIsInteractive(FILE *fp, const char *filename)
3747
0
{
3748
0
    if (isatty(fileno(fp))) {
3749
0
        return 1;
3750
0
    }
3751
0
    if (!_Py_GetConfig()->interactive) {
3752
0
        return 0;
3753
0
    }
3754
0
    return ((filename == NULL)
3755
0
            || (strcmp(filename, "<stdin>") == 0)
3756
0
            || (strcmp(filename, "???") == 0));
3757
0
}
3758
3759
3760
int
3761
_Py_FdIsInteractive(FILE *fp, PyObject *filename)
3762
0
{
3763
0
    if (isatty(fileno(fp))) {
3764
0
        return 1;
3765
0
    }
3766
0
    if (!_Py_GetConfig()->interactive) {
3767
0
        return 0;
3768
0
    }
3769
0
    return ((filename == NULL)
3770
0
            || (PyUnicode_CompareWithASCIIString(filename, "<stdin>") == 0)
3771
0
            || (PyUnicode_CompareWithASCIIString(filename, "???") == 0));
3772
0
}
3773
3774
3775
/* Wrappers around sigaction() or signal(). */
3776
3777
PyOS_sighandler_t
3778
PyOS_getsig(int sig)
3779
2.17k
{
3780
2.17k
#ifdef HAVE_SIGACTION
3781
2.17k
    struct sigaction context;
3782
2.17k
    if (sigaction(sig, NULL, &context) == -1)
3783
68
        return SIG_ERR;
3784
2.10k
    return context.sa_handler;
3785
#else
3786
    PyOS_sighandler_t handler;
3787
/* Special signal handling for the secure CRT in Visual Studio 2005 */
3788
#if defined(_MSC_VER) && _MSC_VER >= 1400
3789
    switch (sig) {
3790
    /* Only these signals are valid */
3791
    case SIGINT:
3792
    case SIGILL:
3793
    case SIGFPE:
3794
    case SIGSEGV:
3795
    case SIGTERM:
3796
    case SIGBREAK:
3797
    case SIGABRT:
3798
        break;
3799
    /* Don't call signal() with other values or it will assert */
3800
    default:
3801
        return SIG_ERR;
3802
    }
3803
#endif /* _MSC_VER && _MSC_VER >= 1400 */
3804
    handler = signal(sig, SIG_IGN);
3805
    if (handler != SIG_ERR)
3806
        signal(sig, handler);
3807
    return handler;
3808
#endif
3809
2.17k
}
3810
3811
/*
3812
 * All of the code in this function must only use async-signal-safe functions,
3813
 * listed at `man 7 signal-safety` or
3814
 * http://www.opengroup.org/onlinepubs/009695399/functions/xsh_chap02_04.html.
3815
 */
3816
PyOS_sighandler_t
3817
PyOS_setsig(int sig, PyOS_sighandler_t handler)
3818
102
{
3819
102
#ifdef HAVE_SIGACTION
3820
    /* Some code in Modules/signalmodule.c depends on sigaction() being
3821
     * used here if HAVE_SIGACTION is defined.  Fix that if this code
3822
     * changes to invalidate that assumption.
3823
     */
3824
102
    struct sigaction context, ocontext;
3825
102
    context.sa_handler = handler;
3826
102
    sigemptyset(&context.sa_mask);
3827
    /* Using SA_ONSTACK is friendlier to other C/C++/Golang-VM code that
3828
     * extension module or embedding code may use where tiny thread stacks
3829
     * are used.  https://bugs.python.org/issue43390 */
3830
102
    context.sa_flags = SA_ONSTACK;
3831
102
    if (sigaction(sig, &context, &ocontext) == -1)
3832
0
        return SIG_ERR;
3833
102
    return ocontext.sa_handler;
3834
#else
3835
    PyOS_sighandler_t oldhandler;
3836
    oldhandler = signal(sig, handler);
3837
#ifdef HAVE_SIGINTERRUPT
3838
    siginterrupt(sig, 1);
3839
#endif
3840
    return oldhandler;
3841
#endif
3842
102
}