Coverage Report

Created: 2025-10-10 06:33

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