Coverage Report

Created: 2025-07-04 06:49

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