Coverage Report

Created: 2025-08-26 06:26

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