Coverage Report

Created: 2026-01-17 06:45

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