Coverage Report

Created: 2026-02-26 06:53

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