Coverage Report

Created: 2026-03-23 06:45

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