Coverage Report

Created: 2026-04-12 06:54

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