Coverage Report

Created: 2025-11-02 06:30

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