Coverage Report

Created: 2025-11-24 06:11

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