Coverage Report

Created: 2026-02-09 07:07

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