Coverage Report

Created: 2026-12-01 06:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/cpython/Python/sysmodule.c
Line
Count
Source
1
2
/* System module */
3
4
/*
5
Various bits of information used by the interpreter are collected in
6
module 'sys'.
7
Function member:
8
- exit(sts): raise SystemExit
9
Data members:
10
- stdin, stdout, stderr: standard file objects
11
- modules: the table of modules (dictionary)
12
- path: module search path (list of strings)
13
- argv: script arguments (list of strings)
14
- ps1, ps2: optional primary and secondary prompts (strings)
15
*/
16
17
#include "Python.h"
18
#include "pycore_audit.h"         // _Py_AuditHookEntry
19
#include "pycore_call.h"          // _PyObject_CallNoArgs()
20
#include "pycore_ceval.h"         // _PyEval_SetAsyncGenFinalizer()
21
#include "pycore_frame.h"         // _PyInterpreterFrame
22
#include "pycore_import.h"        // _PyImport_SetDLOpenFlags()
23
#include "pycore_initconfig.h"    // _PyStatus_EXCEPTION()
24
#include "pycore_interpframe.h"   // _PyFrame_GetFirstComplete()
25
#include "pycore_long.h"          // _PY_LONG_MAX_STR_DIGITS_THRESHOLD
26
#include "pycore_modsupport.h"    // _PyModule_CreateInitialized()
27
#include "pycore_namespace.h"     // _PyNamespace_New()
28
#include "pycore_object.h"        // _PyObject_DebugTypeStats()
29
#include "pycore_optimizer.h"     // _PyDumpExecutors()
30
#include "pycore_pathconfig.h"    // _PyPathConfig_ComputeSysPath0()
31
#include "pycore_pyerrors.h"      // _PyErr_GetRaisedException()
32
#include "pycore_pylifecycle.h"   // _PyErr_WriteUnraisableDefaultHook()
33
#include "pycore_pymath.h"        // _PY_SHORT_FLOAT_REPR
34
#include "pycore_pymem.h"         // _PyMem_DefaultRawFree()
35
#include "pycore_pystate.h"       // _PyThreadState_GET()
36
#include "pycore_pystats.h"       // _Py_PrintSpecializationStats()
37
#include "pycore_runtime.h"       // _PyRuntimeState_Get*()
38
#include "pycore_structseq.h"     // _PyStructSequence_InitBuiltinWithFlags()
39
#include "pycore_sysmodule.h"     // export _PySys_GetSizeOf()
40
#include "pycore_unicodeobject.h" // _PyUnicode_InternImmortal()
41
42
#include "pydtrace.h"             // PyDTrace_AUDIT()
43
#include "osdefs.h"               // DELIM
44
#include "stdlib_module_names.h"  // _Py_stdlib_module_names
45
46
#ifdef HAVE_UNISTD_H
47
#  include <unistd.h>             // getpid()
48
#endif
49
50
#ifdef MS_WINDOWS
51
#  ifndef WIN32_LEAN_AND_MEAN
52
#    define WIN32_LEAN_AND_MEAN
53
#  endif
54
#  include <windows.h>
55
#endif /* MS_WINDOWS */
56
57
#ifdef MS_COREDLL
58
extern void *PyWin_DLLhModule;
59
/* A string loaded from the DLL at startup: */
60
extern const char *PyWin_DLLVersionString;
61
#endif
62
63
#ifdef __EMSCRIPTEN__
64
#  include <emscripten.h>
65
#endif
66
67
#ifdef __wasi__
68
#  include <wasi/version.h>
69
#endif
70
71
#ifdef HAVE_FCNTL_H
72
#  include <fcntl.h>
73
#endif
74
75
/*[clinic input]
76
module sys
77
[clinic start generated code]*/
78
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
79
80
#include "clinic/sysmodule.c.h"
81
82
83
PyObject *
84
PySys_GetAttr(PyObject *name)
85
0
{
86
0
    if (!PyUnicode_Check(name)) {
87
0
        PyErr_Format(PyExc_TypeError,
88
0
                     "attribute name must be string, not '%T'",
89
0
                     name);
90
0
        return NULL;
91
0
    }
92
0
    PyThreadState *tstate = _PyThreadState_GET();
93
0
    PyObject *sysdict = tstate->interp->sysdict;
94
0
    if (sysdict == NULL) {
95
0
        PyErr_SetString(PyExc_RuntimeError, "no sys module");
96
0
        return NULL;
97
0
    }
98
0
    PyObject *value;
99
0
    if (PyDict_GetItemRef(sysdict, name, &value) == 0) {
100
0
        PyErr_Format(PyExc_RuntimeError, "lost sys.%U", name);
101
0
    }
102
0
    return value;
103
0
}
104
105
PyObject *
106
PySys_GetAttrString(const char *name)
107
37
{
108
37
    PyThreadState *tstate = _PyThreadState_GET();
109
37
    PyObject *sysdict = tstate->interp->sysdict;
110
37
    if (sysdict == NULL) {
111
0
        PyErr_SetString(PyExc_RuntimeError, "no sys module");
112
0
        return NULL;
113
0
    }
114
37
    PyObject *value;
115
37
    if (PyDict_GetItemStringRef(sysdict, name, &value) == 0) {
116
0
        PyErr_Format(PyExc_RuntimeError, "lost sys.%s", name);
117
0
    }
118
37
    return value;
119
37
}
120
121
int
122
PySys_GetOptionalAttr(PyObject *name, PyObject **value)
123
0
{
124
0
    if (!PyUnicode_Check(name)) {
125
0
        PyErr_Format(PyExc_TypeError,
126
0
                     "attribute name must be string, not '%T'",
127
0
                     name);
128
0
        *value = NULL;
129
0
        return -1;
130
0
    }
131
0
    PyThreadState *tstate = _PyThreadState_GET();
132
0
    PyObject *sysdict = tstate->interp->sysdict;
133
0
    if (sysdict == NULL) {
134
0
        *value = NULL;
135
0
        return 0;
136
0
    }
137
0
    return PyDict_GetItemRef(sysdict, name, value);
138
0
}
139
140
int
141
PySys_GetOptionalAttrString(const char *name, PyObject **value)
142
37
{
143
37
    PyThreadState *tstate = _PyThreadState_GET();
144
37
    PyObject *sysdict = tstate->interp->sysdict;
145
37
    if (sysdict == NULL) {
146
0
        *value = NULL;
147
0
        return 0;
148
0
    }
149
37
    return PyDict_GetItemStringRef(sysdict, name, value);
150
37
}
151
152
PyObject *
153
PySys_GetObject(const char *name)
154
0
{
155
0
    PyThreadState *tstate = _PyThreadState_GET();
156
0
    PyObject *sysdict = tstate->interp->sysdict;
157
0
    if (sysdict == NULL) {
158
0
        return NULL;
159
0
    }
160
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
161
0
    PyObject *value;
162
0
    (void) PyDict_GetItemStringRef(sysdict, name, &value);
163
    /* XXX Suppress a new exception if it was raised and restore
164
     * the old one. */
165
0
    if (_PyErr_Occurred(tstate)) {
166
0
        PyErr_FormatUnraisable("Exception ignored in PySys_GetObject()");
167
0
    }
168
0
    _PyErr_SetRaisedException(tstate, exc);
169
0
    Py_XDECREF(value);  // return a borrowed reference
170
0
    return value;
171
0
}
172
173
static int
174
sys_set_object(PyInterpreterState *interp, PyObject *key, PyObject *v)
175
259
{
176
259
    if (key == NULL) {
177
0
        return -1;
178
0
    }
179
259
    PyObject *sd = interp->sysdict;
180
259
    if (sd == NULL) {
181
0
        PyErr_SetString(PyExc_RuntimeError, "no sys module");
182
0
        return -1;
183
0
    }
184
259
    if (v == NULL) {
185
0
        if (PyDict_Pop(sd, key, NULL) < 0) {
186
0
            return -1;
187
0
        }
188
0
        return 0;
189
0
    }
190
259
    else {
191
259
        return PyDict_SetItem(sd, key, v);
192
259
    }
193
259
}
194
195
int
196
_PySys_SetAttr(PyObject *key, PyObject *v)
197
148
{
198
148
    PyInterpreterState *interp = _PyInterpreterState_GET();
199
148
    return sys_set_object(interp, key, v);
200
148
}
201
202
static int
203
sys_set_object_str(PyInterpreterState *interp, const char *name, PyObject *v)
204
111
{
205
111
    PyObject *key = v ? PyUnicode_InternFromString(name)
206
111
                      : PyUnicode_FromString(name);
207
111
    int r = sys_set_object(interp, key, v);
208
111
    Py_XDECREF(key);
209
111
    return r;
210
111
}
211
212
int
213
PySys_SetObject(const char *name, PyObject *v)
214
111
{
215
111
    PyInterpreterState *interp = _PyInterpreterState_GET();
216
111
    return sys_set_object_str(interp, name, v);
217
111
}
218
219
int
220
_PySys_ClearAttrString(PyInterpreterState *interp,
221
                       const char *name, int verbose)
222
0
{
223
0
    if (verbose) {
224
0
        PySys_WriteStderr("# clear sys.%s\n", name);
225
0
    }
226
    /* To play it safe, we set the attr to None instead of deleting it. */
227
0
    if (PyDict_SetItemString(interp->sysdict, name, Py_None) < 0) {
228
0
        return -1;
229
0
    }
230
0
    return 0;
231
0
}
232
233
234
static int
235
should_audit(PyInterpreterState *interp)
236
899k
{
237
    /* interp must not be NULL, but test it just in case for extra safety */
238
899k
    assert(interp != NULL);
239
899k
    if (!interp) {
240
0
        return 0;
241
0
    }
242
899k
    return (interp->runtime->audit_hooks.head
243
899k
            || interp->audit_hooks
244
425k
            || PyDTrace_AUDIT_ENABLED());
245
899k
}
246
247
248
static int
249
sys_audit_tstate(PyThreadState *ts, const char *event,
250
                 const char *argFormat, va_list vargs)
251
880k
{
252
880k
    assert(event != NULL);
253
880k
    assert(!argFormat || !strchr(argFormat, 'N'));
254
255
880k
    if (!ts) {
256
        /* Audit hooks cannot be called with a NULL thread state */
257
0
        return 0;
258
0
    }
259
260
    /* The current implementation cannot be called if tstate is not
261
       the current Python thread state. */
262
880k
    assert(ts == _PyThreadState_GET());
263
264
    /* Early exit when no hooks are registered */
265
880k
    PyInterpreterState *is = ts->interp;
266
880k
    if (!should_audit(is)) {
267
420k
        return 0;
268
420k
    }
269
270
459k
    PyObject *eventName = NULL;
271
459k
    PyObject *eventArgs = NULL;
272
459k
    PyObject *hooks = NULL;
273
459k
    PyObject *hook = NULL;
274
459k
    int res = -1;
275
276
459k
    int dtrace = PyDTrace_AUDIT_ENABLED();
277
278
279
459k
    PyObject *exc = _PyErr_GetRaisedException(ts);
280
281
    /* Initialize event args now */
282
459k
    if (argFormat && argFormat[0]) {
283
459k
        eventArgs = Py_VaBuildValue(argFormat, vargs);
284
459k
        if (eventArgs && !PyTuple_Check(eventArgs)) {
285
101k
            PyObject *argTuple = PyTuple_Pack(1, eventArgs);
286
101k
            Py_SETREF(eventArgs, argTuple);
287
101k
        }
288
459k
    }
289
0
    else {
290
0
        eventArgs = PyTuple_New(0);
291
0
    }
292
459k
    if (!eventArgs) {
293
0
        goto exit;
294
0
    }
295
296
    /* Call global hooks
297
     *
298
     * We don't worry about any races on hooks getting added,
299
     * since that would not leave is in an inconsistent state. */
300
459k
    _Py_AuditHookEntry *e = is->runtime->audit_hooks.head;
301
459k
    for (; e; e = e->next) {
302
0
        if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
303
0
            goto exit;
304
0
        }
305
0
    }
306
307
    /* Dtrace USDT point */
308
459k
    if (dtrace) {
309
0
        PyDTrace_AUDIT(event, (void *)eventArgs);
310
0
    }
311
312
    /* Call interpreter hooks */
313
459k
    if (is->audit_hooks) {
314
459k
        eventName = PyUnicode_FromString(event);
315
459k
        if (!eventName) {
316
0
            goto exit;
317
0
        }
318
319
459k
        hooks = PyObject_GetIter(is->audit_hooks);
320
459k
        if (!hooks) {
321
0
            goto exit;
322
0
        }
323
324
        /* Disallow tracing in hooks unless explicitly enabled */
325
459k
        PyThreadState_EnterTracing(ts);
326
919k
        while ((hook = PyIter_Next(hooks)) != NULL) {
327
459k
            PyObject *o;
328
459k
            int canTrace = PyObject_GetOptionalAttr(hook, &_Py_ID(__cantrace__), &o);
329
459k
            if (o) {
330
0
                canTrace = PyObject_IsTrue(o);
331
0
                Py_DECREF(o);
332
0
            }
333
459k
            if (canTrace < 0) {
334
0
                break;
335
0
            }
336
459k
            if (canTrace) {
337
0
                PyThreadState_LeaveTracing(ts);
338
0
            }
339
459k
            PyObject* args[2] = {eventName, eventArgs};
340
459k
            o = _PyObject_VectorcallTstate(ts, hook, args, 2, NULL);
341
459k
            if (canTrace) {
342
0
                PyThreadState_EnterTracing(ts);
343
0
            }
344
459k
            if (!o) {
345
0
                break;
346
0
            }
347
459k
            Py_DECREF(o);
348
459k
            Py_CLEAR(hook);
349
459k
        }
350
459k
        PyThreadState_LeaveTracing(ts);
351
459k
        if (_PyErr_Occurred(ts)) {
352
0
            goto exit;
353
0
        }
354
459k
    }
355
356
459k
    res = 0;
357
358
459k
exit:
359
459k
    Py_XDECREF(hook);
360
459k
    Py_XDECREF(hooks);
361
459k
    Py_XDECREF(eventName);
362
459k
    Py_XDECREF(eventArgs);
363
364
459k
    if (!res) {
365
459k
        _PyErr_SetRaisedException(ts, exc);
366
459k
    }
367
0
    else {
368
0
        assert(_PyErr_Occurred(ts));
369
0
        Py_XDECREF(exc);
370
0
    }
371
372
459k
    return res;
373
459k
}
374
375
int
376
_PySys_Audit(PyThreadState *tstate, const char *event,
377
             const char *argFormat, ...)
378
35.4k
{
379
35.4k
    va_list vargs;
380
35.4k
    va_start(vargs, argFormat);
381
35.4k
    int res = sys_audit_tstate(tstate, event, argFormat, vargs);
382
35.4k
    va_end(vargs);
383
35.4k
    return res;
384
35.4k
}
385
386
int
387
PySys_Audit(const char *event, const char *argFormat, ...)
388
845k
{
389
845k
    PyThreadState *tstate = _PyThreadState_GET();
390
845k
    va_list vargs;
391
845k
    va_start(vargs, argFormat);
392
845k
    int res = sys_audit_tstate(tstate, event, argFormat, vargs);
393
845k
    va_end(vargs);
394
845k
    return res;
395
845k
}
396
397
int
398
PySys_AuditTuple(const char *event, PyObject *args)
399
0
{
400
0
    if (args == NULL) {
401
0
        return PySys_Audit(event, NULL);
402
0
    }
403
404
0
    if (!PyTuple_Check(args)) {
405
0
        PyErr_Format(PyExc_TypeError, "args must be tuple, got %s",
406
0
                     Py_TYPE(args)->tp_name);
407
0
        return -1;
408
0
    }
409
0
    return PySys_Audit(event, "O", args);
410
0
}
411
412
/* We expose this function primarily for our own cleanup during
413
 * finalization. In general, it should not need to be called,
414
 * and as such the function is not exported.
415
 *
416
 * Must be finalizing to clear hooks */
417
void
418
_PySys_ClearAuditHooks(PyThreadState *ts)
419
0
{
420
0
    assert(ts != NULL);
421
0
    if (!ts) {
422
0
        return;
423
0
    }
424
425
0
    _PyRuntimeState *runtime = ts->interp->runtime;
426
    /* The hooks are global so we have to check for runtime finalization. */
427
0
    PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
428
0
    assert(finalizing == ts);
429
0
    if (finalizing != ts) {
430
0
        return;
431
0
    }
432
433
0
    const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
434
0
    if (config->verbose) {
435
0
        PySys_WriteStderr("# clear sys.audit hooks\n");
436
0
    }
437
438
    /* Hooks can abort later hooks for this event, but cannot
439
       abort the clear operation itself. */
440
0
    _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
441
0
    _PyErr_Clear(ts);
442
443
    /* We don't worry about the very unlikely race right here,
444
     * since it's entirely benign.  Nothing else removes entries
445
     * from the list and adding an entry right now would not cause
446
     * any trouble. */
447
0
    _Py_AuditHookEntry *e = runtime->audit_hooks.head, *n;
448
0
    runtime->audit_hooks.head = NULL;
449
0
    while (e) {
450
0
        n = e->next;
451
0
        free(e);
452
0
        e = n;
453
0
    }
454
0
}
455
456
static void
457
add_audit_hook_entry_unlocked(_PyRuntimeState *runtime,
458
                              _Py_AuditHookEntry *entry)
459
0
{
460
0
    if (runtime->audit_hooks.head == NULL) {
461
0
        runtime->audit_hooks.head = entry;
462
0
    }
463
0
    else {
464
0
        _Py_AuditHookEntry *last = runtime->audit_hooks.head;
465
0
        while (last->next) {
466
0
            last = last->next;
467
0
        }
468
0
        last->next = entry;
469
0
    }
470
0
}
471
472
int
473
PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
474
0
{
475
    /* tstate can be NULL, so access directly _PyRuntime:
476
       PySys_AddAuditHook() can be called before Python is initialized. */
477
0
    _PyRuntimeState *runtime = &_PyRuntime;
478
0
    PyThreadState *tstate;
479
0
    if (_PyRuntimeState_GetInitialized(runtime)) {
480
0
        tstate = _PyThreadState_GET();
481
0
    }
482
0
    else {
483
0
        tstate = NULL;
484
0
    }
485
486
    /* Invoke existing audit hooks to allow them an opportunity to abort. */
487
    /* Cannot invoke hooks until we are initialized */
488
0
    if (tstate != NULL) {
489
0
        if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
490
0
            if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
491
                /* We do not report errors derived from RuntimeError */
492
0
                _PyErr_Clear(tstate);
493
0
                return 0;
494
0
            }
495
0
            return -1;
496
0
        }
497
0
    }
498
499
    /* Use malloc(), not PyMem_RawMalloc(): a hook can be added before
500
       Py_Initialize(), and the entry is freed during finalization, after
501
       PYTHONMALLOC may have changed the raw allocator (and, in debug builds,
502
       the allocator under the debug hooks). */
503
0
    _Py_AuditHookEntry *e = (_Py_AuditHookEntry*)malloc(
504
0
            sizeof(_Py_AuditHookEntry));
505
0
    if (!e) {
506
0
        if (tstate != NULL) {
507
0
            _PyErr_NoMemory(tstate);
508
0
        }
509
0
        return -1;
510
0
    }
511
0
    e->next = NULL;
512
0
    e->hookCFunction = (Py_AuditHookFunction)hook;
513
0
    e->userData = userData;
514
515
0
    PyMutex_Lock(&runtime->audit_hooks.mutex);
516
0
    add_audit_hook_entry_unlocked(runtime, e);
517
0
    PyMutex_Unlock(&runtime->audit_hooks.mutex);
518
519
0
    return 0;
520
0
}
521
522
/*[clinic input]
523
sys.addaudithook
524
525
    hook: object
526
527
Adds a new audit hook callback.
528
[clinic start generated code]*/
529
530
static PyObject *
531
sys_addaudithook_impl(PyObject *module, PyObject *hook)
532
/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
533
4
{
534
4
    PyThreadState *tstate = _PyThreadState_GET();
535
536
    /* Invoke existing audit hooks to allow them an opportunity to abort. */
537
4
    if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
538
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
539
            /* We do not report errors derived from RuntimeError */
540
0
            _PyErr_Clear(tstate);
541
0
            Py_RETURN_NONE;
542
0
        }
543
0
        return NULL;
544
0
    }
545
546
4
    PyInterpreterState *interp = tstate->interp;
547
4
    if (interp->audit_hooks == NULL) {
548
4
        interp->audit_hooks = PyList_New(0);
549
4
        if (interp->audit_hooks == NULL) {
550
0
            return NULL;
551
0
        }
552
        /* Avoid having our list of hooks show up in the GC module */
553
4
        PyObject_GC_UnTrack(interp->audit_hooks);
554
4
    }
555
556
4
    if (PyList_Append(interp->audit_hooks, hook) < 0) {
557
0
        return NULL;
558
0
    }
559
560
4
    Py_RETURN_NONE;
561
4
}
562
563
/*[clinic input]
564
sys.audit
565
566
    event: str
567
    /
568
    *args: tuple
569
570
Passes the event to any audit hooks that are attached.
571
[clinic start generated code]*/
572
573
static PyObject *
574
sys_audit_impl(PyObject *module, const char *event, PyObject *args)
575
/*[clinic end generated code: output=1d0fc82da768f49d input=ec3b688527945109]*/
576
18.6k
{
577
18.6k
    PyThreadState *tstate = _PyThreadState_GET();
578
18.6k
    _Py_EnsureTstateNotNULL(tstate);
579
580
18.6k
    if (!should_audit(tstate->interp)) {
581
5.14k
        Py_RETURN_NONE;
582
5.14k
    }
583
584
13.5k
    int res = _PySys_Audit(tstate, event, "O", args);
585
13.5k
    if (res < 0) {
586
0
        return NULL;
587
0
    }
588
589
13.5k
    Py_RETURN_NONE;
590
13.5k
}
591
592
593
static PyObject *
594
sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
595
0
{
596
0
    PyThreadState *tstate = _PyThreadState_GET();
597
0
    assert(!_PyErr_Occurred(tstate));
598
0
    char *envar = Py_GETENV("PYTHONBREAKPOINT");
599
600
0
    if (envar == NULL || strlen(envar) == 0) {
601
0
        envar = "pdb.set_trace";
602
0
    }
603
0
    else if (!strcmp(envar, "0")) {
604
        /* The breakpoint is explicitly no-op'd. */
605
0
        Py_RETURN_NONE;
606
0
    }
607
    /* According to POSIX the string returned by getenv() might be invalidated
608
     * or the string content might be overwritten by a subsequent call to
609
     * getenv().  Since importing a module can performs the getenv() calls,
610
     * we need to save a copy of envar. */
611
0
    envar = _PyMem_RawStrdup(envar);
612
0
    if (envar == NULL) {
613
0
        _PyErr_NoMemory(tstate);
614
0
        return NULL;
615
0
    }
616
0
    const char *last_dot = strrchr(envar, '.');
617
0
    const char *attrname = NULL;
618
0
    PyObject *modulepath = NULL;
619
620
0
    if (last_dot == NULL) {
621
        /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
622
0
        modulepath = &_Py_ID(builtins);
623
0
        attrname = envar;
624
0
    }
625
0
    else if (last_dot != envar) {
626
        /* Split on the last dot; */
627
0
        modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
628
0
        attrname = last_dot + 1;
629
0
    }
630
0
    else {
631
0
        goto warn;
632
0
    }
633
0
    if (modulepath == NULL) {
634
0
        PyMem_RawFree(envar);
635
0
        return NULL;
636
0
    }
637
638
0
    PyObject *module = PyImport_Import(modulepath);
639
0
    Py_DECREF(modulepath);
640
641
0
    if (module == NULL) {
642
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
643
0
            goto warn;
644
0
        }
645
0
        PyMem_RawFree(envar);
646
0
        return NULL;
647
0
    }
648
649
0
    PyObject *hook = PyObject_GetAttrString(module, attrname);
650
0
    Py_DECREF(module);
651
652
0
    if (hook == NULL) {
653
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
654
0
            goto warn;
655
0
        }
656
0
        PyMem_RawFree(envar);
657
0
        return NULL;
658
0
    }
659
0
    PyMem_RawFree(envar);
660
0
    PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
661
0
    Py_DECREF(hook);
662
0
    return retval;
663
664
0
  warn:
665
    /* If any of the imports went wrong, then warn and ignore. */
666
0
    _PyErr_Clear(tstate);
667
0
    int status = PyErr_WarnFormat(
668
0
        PyExc_RuntimeWarning, 0,
669
0
        "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
670
0
    PyMem_RawFree(envar);
671
0
    if (status < 0) {
672
        /* Printing the warning raised an exception. */
673
0
        return NULL;
674
0
    }
675
    /* The warning was (probably) issued. */
676
0
    Py_RETURN_NONE;
677
0
}
678
679
PyDoc_STRVAR(breakpointhook_doc,
680
"breakpointhook($module, /, *args, **kwargs)\n"
681
"--\n"
682
"\n"
683
"This hook function is called by built-in breakpoint().\n"
684
);
685
686
/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
687
   error handler. If sys.stdout has a buffer attribute, use
688
   sys.stdout.buffer.write(encoded), otherwise redecode the string and use
689
   sys.stdout.write(redecoded).
690
691
   Helper function for sys_displayhook(). */
692
static int
693
sys_displayhook_unencodable(PyObject *outf, PyObject *o)
694
0
{
695
0
    PyObject *stdout_encoding = NULL;
696
0
    PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
697
0
    const char *stdout_encoding_str;
698
0
    int ret;
699
700
0
    stdout_encoding = PyObject_GetAttr(outf, &_Py_ID(encoding));
701
0
    if (stdout_encoding == NULL)
702
0
        goto error;
703
0
    stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
704
0
    if (stdout_encoding_str == NULL)
705
0
        goto error;
706
707
0
    repr_str = PyObject_Repr(o);
708
0
    if (repr_str == NULL)
709
0
        goto error;
710
0
    encoded = PyUnicode_AsEncodedString(repr_str,
711
0
                                        stdout_encoding_str,
712
0
                                        "backslashreplace");
713
0
    Py_DECREF(repr_str);
714
0
    if (encoded == NULL)
715
0
        goto error;
716
717
0
    if (PyObject_GetOptionalAttr(outf, &_Py_ID(buffer), &buffer) < 0) {
718
0
        Py_DECREF(encoded);
719
0
        goto error;
720
0
    }
721
0
    if (buffer) {
722
0
        result = PyObject_CallMethodOneArg(buffer, &_Py_ID(write), encoded);
723
0
        Py_DECREF(buffer);
724
0
        Py_DECREF(encoded);
725
0
        if (result == NULL)
726
0
            goto error;
727
0
        Py_DECREF(result);
728
0
    }
729
0
    else {
730
0
        escaped_str = PyUnicode_FromEncodedObject(encoded,
731
0
                                                  stdout_encoding_str,
732
0
                                                  "strict");
733
0
        Py_DECREF(encoded);
734
0
        if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
735
0
            Py_DECREF(escaped_str);
736
0
            goto error;
737
0
        }
738
0
        Py_DECREF(escaped_str);
739
0
    }
740
0
    ret = 0;
741
0
    goto finally;
742
743
0
error:
744
0
    ret = -1;
745
0
finally:
746
0
    Py_XDECREF(stdout_encoding);
747
0
    return ret;
748
0
}
749
750
/*[clinic input]
751
sys.displayhook
752
753
    object as o: object
754
    /
755
756
Print an object to sys.stdout and also save it in builtins._
757
[clinic start generated code]*/
758
759
static PyObject *
760
sys_displayhook(PyObject *module, PyObject *o)
761
/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
762
0
{
763
0
    PyObject *outf;
764
0
    PyObject *builtins;
765
0
    PyThreadState *tstate = _PyThreadState_GET();
766
767
0
    builtins = PyImport_GetModule(&_Py_ID(builtins));
768
0
    if (builtins == NULL) {
769
0
        if (!_PyErr_Occurred(tstate)) {
770
0
            _PyErr_SetString(tstate, PyExc_RuntimeError,
771
0
                             "lost builtins module");
772
0
        }
773
0
        return NULL;
774
0
    }
775
0
    Py_DECREF(builtins);
776
777
    /* Print value except if None */
778
    /* After printing, also assign to '_' */
779
    /* Before, set '_' to None to avoid recursion */
780
0
    if (o == Py_None) {
781
0
        Py_RETURN_NONE;
782
0
    }
783
0
    if (PyObject_SetAttr(builtins, _Py_LATIN1_CHR('_'), Py_None) != 0)
784
0
        return NULL;
785
0
    outf = PySys_GetAttr(&_Py_ID(stdout));
786
0
    if (outf == NULL) {
787
0
        return NULL;
788
0
    }
789
0
    if (outf == Py_None) {
790
0
        _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
791
0
        Py_DECREF(outf);
792
0
        return NULL;
793
0
    }
794
0
    if (PyFile_WriteObject(o, outf, 0) != 0) {
795
0
        if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
796
0
            int err;
797
            /* repr(o) is not encodable to sys.stdout.encoding with
798
             * sys.stdout.errors error handler (which is probably 'strict') */
799
0
            _PyErr_Clear(tstate);
800
0
            err = sys_displayhook_unencodable(outf, o);
801
0
            if (err) {
802
0
                Py_DECREF(outf);
803
0
                return NULL;
804
0
            }
805
0
        }
806
0
        else {
807
0
            Py_DECREF(outf);
808
0
            return NULL;
809
0
        }
810
0
    }
811
0
    if (PyFile_WriteObject(_Py_LATIN1_CHR('\n'), outf, Py_PRINT_RAW) != 0) {
812
0
        Py_DECREF(outf);
813
0
        return NULL;
814
0
    }
815
0
    Py_DECREF(outf);
816
0
    if (PyObject_SetAttr(builtins, _Py_LATIN1_CHR('_'), o) != 0) {
817
0
        return NULL;
818
0
    }
819
0
    Py_RETURN_NONE;
820
0
}
821
822
823
/*[clinic input]
824
sys.excepthook
825
826
    exctype:   object
827
    value:     object
828
    traceback: object
829
    /
830
831
Handle an exception by displaying it with a traceback on sys.stderr.
832
[clinic start generated code]*/
833
834
static PyObject *
835
sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
836
                    PyObject *traceback)
837
/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
838
0
{
839
0
    PyErr_Display(NULL, value, traceback);
840
0
    Py_RETURN_NONE;
841
0
}
842
843
844
/*[clinic input]
845
sys.exception
846
847
Return the current exception.
848
849
Return the most recent exception caught by an except clause
850
in the current stack frame or in an older stack frame, or None
851
if no such exception exists.
852
[clinic start generated code]*/
853
854
static PyObject *
855
sys_exception_impl(PyObject *module)
856
/*[clinic end generated code: output=2381ee2f25953e40 input=c88fbb94b6287431]*/
857
0
{
858
0
    _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
859
0
    if (err_info->exc_value != NULL) {
860
0
        return Py_NewRef(err_info->exc_value);
861
0
    }
862
0
    Py_RETURN_NONE;
863
0
}
864
865
866
/*[clinic input]
867
sys.exc_info
868
869
Return current exception information: (type, value, traceback).
870
871
Return information about the most recent exception caught by an except
872
clause in the current stack frame or in an older stack frame.
873
[clinic start generated code]*/
874
875
static PyObject *
876
sys_exc_info_impl(PyObject *module)
877
/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
878
0
{
879
0
    _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
880
0
    return _PyErr_StackItemToExcInfoTuple(err_info);
881
0
}
882
883
884
/*[clinic input]
885
sys.unraisablehook
886
887
    unraisable: object
888
    /
889
890
Handle an unraisable exception.
891
892
The unraisable argument has the following attributes:
893
894
* exc_type: Exception type.
895
* exc_value: Exception value, can be None.
896
* exc_traceback: Exception traceback, can be None.
897
* err_msg: Error message, can be None.
898
* object: Object causing the exception, can be None.
899
[clinic start generated code]*/
900
901
static PyObject *
902
sys_unraisablehook(PyObject *module, PyObject *unraisable)
903
/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
904
0
{
905
0
    return _PyErr_WriteUnraisableDefaultHook(unraisable);
906
0
}
907
908
909
/*[clinic input]
910
sys.exit
911
912
    status: object = None
913
    /
914
915
Exit the interpreter by raising SystemExit(status).
916
917
If the status is omitted or None, it defaults to zero (i.e., success).
918
If the status is an integer, it will be used as the system exit status.
919
If it is another kind of object, it will be printed and the system
920
exit status will be one (i.e., failure).
921
[clinic start generated code]*/
922
923
static PyObject *
924
sys_exit_impl(PyObject *module, PyObject *status)
925
/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
926
0
{
927
    /* Raise SystemExit so callers may catch it or clean up. */
928
0
    PyErr_SetObject(PyExc_SystemExit, status);
929
0
    return NULL;
930
0
}
931
932
933
static PyObject *
934
get_utf8_unicode(void)
935
78
{
936
78
    _Py_DECLARE_STR(utf_8, "utf-8");
937
78
    PyObject *ret = &_Py_STR(utf_8);
938
78
    return Py_NewRef(ret);
939
78
}
940
941
/*[clinic input]
942
sys.getdefaultencoding
943
944
Return the current default encoding used by the Unicode implementation.
945
[clinic start generated code]*/
946
947
static PyObject *
948
sys_getdefaultencoding_impl(PyObject *module)
949
/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
950
0
{
951
0
    return get_utf8_unicode();
952
0
}
953
954
/*[clinic input]
955
sys.getfilesystemencoding
956
957
Return the encoding used to convert Unicode filenames to OS filenames.
958
[clinic start generated code]*/
959
960
static PyObject *
961
sys_getfilesystemencoding_impl(PyObject *module)
962
/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
963
78
{
964
78
    PyInterpreterState *interp = _PyInterpreterState_GET();
965
78
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
966
967
78
    if (wcscmp(config->filesystem_encoding, L"utf-8") == 0) {
968
78
        return get_utf8_unicode();
969
78
    }
970
971
0
    PyObject *u = PyUnicode_FromWideChar(config->filesystem_encoding, -1);
972
0
    if (u == NULL) {
973
0
        return NULL;
974
0
    }
975
0
    _PyUnicode_InternImmortal(interp, &u);
976
0
    return u;
977
0
}
978
979
/*[clinic input]
980
sys.getfilesystemencodeerrors
981
982
Return the error mode used Unicode to OS filename conversion.
983
[clinic start generated code]*/
984
985
static PyObject *
986
sys_getfilesystemencodeerrors_impl(PyObject *module)
987
/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
988
37
{
989
37
    PyInterpreterState *interp = _PyInterpreterState_GET();
990
37
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
991
37
    PyObject *u = PyUnicode_FromWideChar(config->filesystem_errors, -1);
992
37
    if (u == NULL) {
993
0
        return NULL;
994
0
    }
995
37
    _PyUnicode_InternImmortal(interp, &u);
996
37
    return u;
997
37
}
998
999
/*[clinic input]
1000
sys.intern
1001
1002
    string as s: unicode
1003
    /
1004
1005
``Intern'' the given string.
1006
1007
This enters the string in the (global) table of interned strings whose
1008
purpose is to speed up dictionary lookups. Return the string itself or
1009
the previously interned string object with the same value.
1010
[clinic start generated code]*/
1011
1012
static PyObject *
1013
sys_intern_impl(PyObject *module, PyObject *s)
1014
/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
1015
1.64k
{
1016
1.64k
    if (PyUnicode_CheckExact(s)) {
1017
1.64k
        PyInterpreterState *interp = _PyInterpreterState_GET();
1018
1.64k
        Py_INCREF(s);
1019
1.64k
        _PyUnicode_InternMortal(interp, &s);
1020
1.64k
        return s;
1021
1.64k
    }
1022
0
    else {
1023
0
        PyErr_Format(PyExc_TypeError,
1024
0
                     "can't intern %.400s", Py_TYPE(s)->tp_name);
1025
0
        return NULL;
1026
0
    }
1027
1.64k
}
1028
1029
1030
/*[clinic input]
1031
sys._is_interned -> bool
1032
1033
  string: unicode
1034
  /
1035
1036
Return True if the given string is "interned".
1037
[clinic start generated code]*/
1038
1039
static int
1040
sys__is_interned_impl(PyObject *module, PyObject *string)
1041
/*[clinic end generated code: output=c3678267b4e9d7ed input=039843e17883b606]*/
1042
0
{
1043
0
    return PyUnicode_CHECK_INTERNED(string);
1044
0
}
1045
1046
/*[clinic input]
1047
sys._is_immortal -> bool
1048
1049
  op: object
1050
  /
1051
1052
Return True if the given object is "immortal" per PEP 683.
1053
1054
This function should be used for specialized purposes only.
1055
[clinic start generated code]*/
1056
1057
static int
1058
sys__is_immortal_impl(PyObject *module, PyObject *op)
1059
/*[clinic end generated code: output=c2f5d6a80efb8d1a input=4609c9bf5481db76]*/
1060
0
{
1061
0
    return PyUnstable_IsImmortal(op);
1062
0
}
1063
1064
/*
1065
 * Cached interned string objects used for calling the profile and
1066
 * trace functions.
1067
 */
1068
static PyObject *whatstrings[8] = {
1069
   &_Py_ID(call),
1070
   &_Py_ID(exception),
1071
   &_Py_ID(line),
1072
   &_Py_ID(return),
1073
   &_Py_ID(c_call),
1074
   &_Py_ID(c_exception),
1075
   &_Py_ID(c_return),
1076
   &_Py_ID(opcode),
1077
};
1078
1079
1080
static PyObject *
1081
call_trampoline(PyThreadState *tstate, PyObject* callback,
1082
                PyFrameObject *frame, int what, PyObject *arg)
1083
0
{
1084
    /* call the Python-level function */
1085
0
    if (arg == NULL) {
1086
0
        arg = Py_None;
1087
0
    }
1088
0
    PyObject *args[3] = {(PyObject *)frame, whatstrings[what], arg};
1089
0
    PyObject *result = _PyObject_VectorcallTstate(tstate, callback, args, 3, NULL);
1090
1091
0
    return result;
1092
0
}
1093
1094
static int
1095
profile_trampoline(PyObject *self, PyFrameObject *frame,
1096
                   int what, PyObject *arg)
1097
0
{
1098
0
    PyThreadState *tstate = _PyThreadState_GET();
1099
0
    PyObject *result = call_trampoline(tstate, self, frame, what, arg);
1100
0
    if (result == NULL) {
1101
0
        _PyEval_SetProfile(tstate, NULL, NULL);
1102
0
        return -1;
1103
0
    }
1104
1105
0
    Py_DECREF(result);
1106
0
    return 0;
1107
0
}
1108
1109
static int
1110
trace_trampoline(PyObject *self, PyFrameObject *frame,
1111
                 int what, PyObject *arg)
1112
0
{
1113
0
    PyObject *callback;
1114
0
    if (what == PyTrace_CALL) {
1115
0
        callback = self;
1116
0
    }
1117
0
    else {
1118
0
        callback = frame->f_trace;
1119
0
    }
1120
0
    if (callback == NULL) {
1121
0
        return 0;
1122
0
    }
1123
1124
0
    PyThreadState *tstate = _PyThreadState_GET();
1125
0
    PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
1126
0
    if (result == NULL) {
1127
0
        _PyEval_SetTrace(tstate, NULL, NULL);
1128
0
        Py_CLEAR(frame->f_trace);
1129
0
        return -1;
1130
0
    }
1131
1132
0
    if (result != Py_None) {
1133
0
        Py_XSETREF(frame->f_trace, result);
1134
0
    }
1135
0
    else {
1136
0
        Py_DECREF(result);
1137
0
    }
1138
0
    return 0;
1139
0
}
1140
1141
/*[clinic input]
1142
sys.settrace
1143
1144
    function: object
1145
    /
1146
1147
Set the global debug tracing function.
1148
1149
It will be called on each function call.  See the debugger chapter
1150
in the library manual.
1151
[clinic start generated code]*/
1152
1153
static PyObject *
1154
sys_settrace(PyObject *module, PyObject *function)
1155
/*[clinic end generated code: output=999d12e9d6ec4678 input=8107feb01c5f1c4e]*/
1156
0
{
1157
0
    PyThreadState *tstate = _PyThreadState_GET();
1158
0
    if (function == Py_None) {
1159
0
        if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
1160
0
            return NULL;
1161
0
        }
1162
0
    }
1163
0
    else {
1164
0
        if (_PyEval_SetTrace(tstate, trace_trampoline, function) < 0) {
1165
0
            return NULL;
1166
0
        }
1167
0
    }
1168
0
    Py_RETURN_NONE;
1169
0
}
1170
1171
/*[clinic input]
1172
@permit_long_summary
1173
sys._settraceallthreads
1174
1175
    function as arg: object
1176
    /
1177
1178
Set the global debug tracing function in all running threads belonging to the current interpreter.
1179
1180
It will be called on each function call. See the debugger chapter
1181
in the library manual.
1182
[clinic start generated code]*/
1183
1184
static PyObject *
1185
sys__settraceallthreads(PyObject *module, PyObject *arg)
1186
/*[clinic end generated code: output=161cca30207bf3ca input=e5750f5dc01142eb]*/
1187
0
{
1188
0
    PyObject* argument = NULL;
1189
0
    Py_tracefunc func = NULL;
1190
1191
0
    if (arg != Py_None) {
1192
0
        func = trace_trampoline;
1193
0
        argument = arg;
1194
0
    }
1195
1196
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1197
0
    if (_PyEval_SetTraceAllThreads(interp, func, argument) < 0) {
1198
0
        return NULL;
1199
0
    }
1200
0
    Py_RETURN_NONE;
1201
0
}
1202
1203
/*[clinic input]
1204
sys.gettrace
1205
1206
Return the global debug tracing function set with sys.settrace.
1207
1208
See the debugger chapter in the library manual.
1209
[clinic start generated code]*/
1210
1211
static PyObject *
1212
sys_gettrace_impl(PyObject *module)
1213
/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
1214
0
{
1215
0
    PyThreadState *tstate = _PyThreadState_GET();
1216
0
    PyObject *temp = tstate->c_traceobj;
1217
1218
0
    if (temp == NULL)
1219
0
        temp = Py_None;
1220
0
    return Py_NewRef(temp);
1221
0
}
1222
1223
/*[clinic input]
1224
sys.setprofile
1225
1226
    function: object
1227
    /
1228
1229
Set the profiling function.
1230
1231
It will be called on each function call and return.  See the profiler
1232
chapter in the library manual.
1233
[clinic start generated code]*/
1234
1235
static PyObject *
1236
sys_setprofile(PyObject *module, PyObject *function)
1237
/*[clinic end generated code: output=1c3503105939db9c input=055d0d7961413a62]*/
1238
0
{
1239
0
    PyThreadState *tstate = _PyThreadState_GET();
1240
0
    if (function == Py_None) {
1241
0
        if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1242
0
            return NULL;
1243
0
        }
1244
0
    }
1245
0
    else {
1246
0
        if (_PyEval_SetProfile(tstate, profile_trampoline, function) < 0) {
1247
0
            return NULL;
1248
0
        }
1249
0
    }
1250
0
    Py_RETURN_NONE;
1251
0
}
1252
1253
/*[clinic input]
1254
@permit_long_summary
1255
sys._setprofileallthreads
1256
1257
    function as arg: object
1258
    /
1259
1260
Set the profiling function in all running threads belonging to the current interpreter.
1261
1262
It will be called on each function call and return.  See the profiler
1263
chapter in the library manual.
1264
[clinic start generated code]*/
1265
1266
static PyObject *
1267
sys__setprofileallthreads(PyObject *module, PyObject *arg)
1268
/*[clinic end generated code: output=2d61319e27b309fe input=9a3dc3352c63b471]*/
1269
0
{
1270
0
    PyObject* argument = NULL;
1271
0
    Py_tracefunc func = NULL;
1272
1273
0
    if (arg != Py_None) {
1274
0
        func = profile_trampoline;
1275
0
        argument = arg;
1276
0
    }
1277
1278
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1279
0
    if (_PyEval_SetProfileAllThreads(interp, func, argument) < 0) {
1280
0
        return NULL;
1281
0
    }
1282
0
    Py_RETURN_NONE;
1283
0
}
1284
1285
/*[clinic input]
1286
sys.getprofile
1287
1288
Return the profiling function set with sys.setprofile.
1289
1290
See the profiler chapter in the library manual.
1291
[clinic start generated code]*/
1292
1293
static PyObject *
1294
sys_getprofile_impl(PyObject *module)
1295
/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
1296
0
{
1297
0
    PyThreadState *tstate = _PyThreadState_GET();
1298
0
    PyObject *temp = tstate->c_profileobj;
1299
1300
0
    if (temp == NULL)
1301
0
        temp = Py_None;
1302
0
    return Py_NewRef(temp);
1303
0
}
1304
1305
1306
/*[clinic input]
1307
sys.setswitchinterval
1308
1309
    interval: double
1310
    /
1311
1312
Set the ideal thread switching delay inside the Python interpreter.
1313
1314
The actual frequency of switching threads can be lower if the
1315
interpreter executes long sequences of uninterruptible code
1316
(this is implementation-specific and workload-dependent).
1317
1318
The parameter must represent the desired switching delay in seconds
1319
A typical value is 0.005 (5 milliseconds).
1320
[clinic start generated code]*/
1321
1322
static PyObject *
1323
sys_setswitchinterval_impl(PyObject *module, double interval)
1324
/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
1325
0
{
1326
0
    if (interval <= 0.0) {
1327
0
        PyErr_SetString(PyExc_ValueError,
1328
0
                        "switch interval must be strictly positive");
1329
0
        return NULL;
1330
0
    }
1331
0
    _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
1332
0
    Py_RETURN_NONE;
1333
0
}
1334
1335
1336
/*[clinic input]
1337
sys.getswitchinterval -> double
1338
1339
Return the current thread switch interval; see sys.setswitchinterval().
1340
[clinic start generated code]*/
1341
1342
static double
1343
sys_getswitchinterval_impl(PyObject *module)
1344
/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
1345
0
{
1346
0
    return 1e-6 * _PyEval_GetSwitchInterval();
1347
0
}
1348
1349
/*[clinic input]
1350
sys.setrecursionlimit
1351
1352
    limit as new_limit: int
1353
    /
1354
1355
Set the maximum depth of the Python interpreter stack to n.
1356
1357
This limit prevents infinite recursion from causing an overflow of the C
1358
stack and crashing Python.  The highest possible limit is platform-
1359
dependent.
1360
[clinic start generated code]*/
1361
1362
static PyObject *
1363
sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1364
/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
1365
232
{
1366
232
    PyThreadState *tstate = _PyThreadState_GET();
1367
1368
232
    if (new_limit < 1) {
1369
0
        _PyErr_SetString(tstate, PyExc_ValueError,
1370
0
                         "recursion limit must be greater or equal than 1");
1371
0
        return NULL;
1372
0
    }
1373
1374
    /* Reject too low new limit if the current recursion depth is higher than
1375
       the new low-water mark. */
1376
232
    int depth = tstate->py_recursion_limit - tstate->py_recursion_remaining;
1377
232
    if (depth >= new_limit) {
1378
0
        _PyErr_Format(tstate, PyExc_RecursionError,
1379
0
                      "cannot set the recursion limit to %i at "
1380
0
                      "the recursion depth %i: the limit is too low",
1381
0
                      new_limit, depth);
1382
0
        return NULL;
1383
0
    }
1384
1385
232
    Py_SetRecursionLimit(new_limit);
1386
232
    Py_RETURN_NONE;
1387
232
}
1388
1389
/*[clinic input]
1390
sys.set_coroutine_origin_tracking_depth
1391
1392
  depth: int
1393
1394
Enable or disable origin tracking for coroutine objects in this thread.
1395
1396
Coroutine objects will track 'depth' frames of traceback information
1397
about where they came from, available in their cr_origin attribute.
1398
1399
Set a depth of 0 to disable.
1400
[clinic start generated code]*/
1401
1402
static PyObject *
1403
sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
1404
/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
1405
0
{
1406
0
    if (_PyEval_SetCoroutineOriginTrackingDepth(depth) < 0) {
1407
0
        return NULL;
1408
0
    }
1409
0
    Py_RETURN_NONE;
1410
0
}
1411
1412
/*[clinic input]
1413
sys.get_coroutine_origin_tracking_depth -> int
1414
1415
Check status of origin tracking for coroutine objects in this thread.
1416
[clinic start generated code]*/
1417
1418
static int
1419
sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1420
/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1421
0
{
1422
0
    return _PyEval_GetCoroutineOriginTrackingDepth();
1423
0
}
1424
1425
static PyTypeObject AsyncGenHooksType;
1426
1427
PyDoc_STRVAR(asyncgen_hooks_doc,
1428
"asyncgen_hooks\n\
1429
\n\
1430
A named tuple providing information about asynchronous\n\
1431
generators hooks.  The attributes are read only.");
1432
1433
static PyStructSequence_Field asyncgen_hooks_fields[] = {
1434
    {"firstiter", "Hook to intercept first iteration"},
1435
    {"finalizer", "Hook to intercept finalization"},
1436
    {0}
1437
};
1438
1439
static PyStructSequence_Desc asyncgen_hooks_desc = {
1440
    "asyncgen_hooks",          /* name */
1441
    asyncgen_hooks_doc,        /* doc */
1442
    asyncgen_hooks_fields ,    /* fields */
1443
    2
1444
};
1445
1446
/*[clinic input]
1447
sys.set_asyncgen_hooks
1448
1449
    firstiter: object = NULL
1450
    finalizer: object = NULL
1451
1452
Set a finalizer for async generators objects.
1453
[clinic start generated code]*/
1454
1455
static PyObject *
1456
sys_set_asyncgen_hooks_impl(PyObject *module, PyObject *firstiter,
1457
                            PyObject *finalizer)
1458
/*[clinic end generated code: output=6fe3b2dd3f9a9db5 input=ef6a1e96361234be]*/
1459
0
{
1460
0
    if (finalizer && finalizer != Py_None) {
1461
0
        if (!PyCallable_Check(finalizer)) {
1462
0
            PyErr_Format(PyExc_TypeError,
1463
0
                         "callable finalizer expected, got %.50s",
1464
0
                         Py_TYPE(finalizer)->tp_name);
1465
0
            return NULL;
1466
0
        }
1467
0
    }
1468
1469
0
    if (firstiter && firstiter != Py_None) {
1470
0
        if (!PyCallable_Check(firstiter)) {
1471
0
            PyErr_Format(PyExc_TypeError,
1472
0
                         "callable firstiter expected, got %.50s",
1473
0
                         Py_TYPE(firstiter)->tp_name);
1474
0
            return NULL;
1475
0
        }
1476
0
    }
1477
1478
0
    PyObject *cur_finalizer = _PyEval_GetAsyncGenFinalizer();
1479
1480
0
    if (finalizer && finalizer != Py_None) {
1481
0
        if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1482
0
            return NULL;
1483
0
        }
1484
0
    }
1485
0
    else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1486
0
        return NULL;
1487
0
    }
1488
1489
0
    if (firstiter && firstiter != Py_None) {
1490
0
        if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1491
0
            goto error;
1492
0
        }
1493
0
    }
1494
0
    else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1495
0
        goto error;
1496
0
    }
1497
1498
0
    Py_RETURN_NONE;
1499
1500
0
error:
1501
0
    _PyEval_SetAsyncGenFinalizer(cur_finalizer);
1502
0
    return NULL;
1503
0
}
1504
1505
/*[clinic input]
1506
sys.get_asyncgen_hooks
1507
1508
Return the installed asynchronous generators hooks.
1509
1510
This returns a namedtuple of the form (firstiter, finalizer).
1511
[clinic start generated code]*/
1512
1513
static PyObject *
1514
sys_get_asyncgen_hooks_impl(PyObject *module)
1515
/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
1516
0
{
1517
0
    PyObject *res;
1518
0
    PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1519
0
    PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1520
1521
0
    res = PyStructSequence_New(&AsyncGenHooksType);
1522
0
    if (res == NULL) {
1523
0
        return NULL;
1524
0
    }
1525
1526
0
    if (firstiter == NULL) {
1527
0
        firstiter = Py_None;
1528
0
    }
1529
1530
0
    if (finalizer == NULL) {
1531
0
        finalizer = Py_None;
1532
0
    }
1533
1534
0
    PyStructSequence_SET_ITEM(res, 0, Py_NewRef(firstiter));
1535
0
    PyStructSequence_SET_ITEM(res, 1, Py_NewRef(finalizer));
1536
1537
0
    return res;
1538
0
}
1539
1540
1541
static PyTypeObject Hash_InfoType;
1542
1543
PyDoc_STRVAR(hash_info_doc,
1544
"hash_info\n\
1545
\n\
1546
A named tuple providing parameters used for computing\n\
1547
hashes. The attributes are read only.");
1548
1549
static PyStructSequence_Field hash_info_fields[] = {
1550
    {"width", "width of the type used for hashing, in bits"},
1551
    {"modulus", "prime number giving the modulus on which the hash "
1552
                "function is based"},
1553
    {"inf", "value to be used for hash of a positive infinity"},
1554
    {"nan", "value to be used for hash of a nan"},
1555
    {"imag", "multiplier used for the imaginary part of a complex number"},
1556
    {"algorithm", "name of the algorithm for hashing of str, bytes and "
1557
                  "memoryviews"},
1558
    {"hash_bits", "internal output size of hash algorithm"},
1559
    {"seed_bits", "seed size of hash algorithm"},
1560
    {"cutoff", "small string optimization cutoff"},
1561
    {NULL, NULL}
1562
};
1563
1564
static PyStructSequence_Desc hash_info_desc = {
1565
    "sys.hash_info",
1566
    hash_info_doc,
1567
    hash_info_fields,
1568
    9,
1569
};
1570
1571
static PyObject *
1572
get_hash_info(PyThreadState *tstate)
1573
37
{
1574
37
    PyObject *hash_info;
1575
37
    int field = 0;
1576
37
    PyHash_FuncDef *hashfunc;
1577
37
    hash_info = PyStructSequence_New(&Hash_InfoType);
1578
37
    if (hash_info == NULL) {
1579
0
        return NULL;
1580
0
    }
1581
37
    hashfunc = PyHash_GetFuncDef();
1582
1583
37
#define SET_HASH_INFO_ITEM(CALL)                             \
1584
333
    do {                                                     \
1585
333
        PyObject *item = (CALL);                             \
1586
333
        if (item == NULL) {                                  \
1587
0
            Py_CLEAR(hash_info);                             \
1588
0
            return NULL;                                     \
1589
0
        }                                                    \
1590
333
        PyStructSequence_SET_ITEM(hash_info, field++, item); \
1591
333
    } while(0)
1592
1593
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(8 * sizeof(Py_hash_t)));
1594
37
    SET_HASH_INFO_ITEM(PyLong_FromSsize_t(PyHASH_MODULUS));
1595
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(PyHASH_INF));
1596
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(0));  // This is no longer used
1597
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(PyHASH_IMAG));
1598
37
    SET_HASH_INFO_ITEM(PyUnicode_FromString(hashfunc->name));
1599
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(hashfunc->hash_bits));
1600
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(hashfunc->seed_bits));
1601
37
    SET_HASH_INFO_ITEM(PyLong_FromLong(Py_HASH_CUTOFF));
1602
1603
37
#undef SET_HASH_INFO_ITEM
1604
1605
37
    return hash_info;
1606
37
}
1607
/*[clinic input]
1608
sys.getrecursionlimit
1609
1610
Return the current value of the recursion limit.
1611
1612
The recursion limit is the maximum depth of the Python interpreter
1613
stack.  This limit prevents infinite recursion from causing an overflow
1614
of the C stack and crashing Python.
1615
[clinic start generated code]*/
1616
1617
static PyObject *
1618
sys_getrecursionlimit_impl(PyObject *module)
1619
/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
1620
500
{
1621
500
    return PyLong_FromLong(Py_GetRecursionLimit());
1622
500
}
1623
1624
#ifdef MS_WINDOWS
1625
1626
static PyTypeObject WindowsVersionType = { 0 };
1627
1628
static PyStructSequence_Field windows_version_fields[] = {
1629
    {"major", "Major version number"},
1630
    {"minor", "Minor version number"},
1631
    {"build", "Build number"},
1632
    {"platform", "Operating system platform"},
1633
    {"service_pack", "Latest Service Pack installed on the system"},
1634
    {"service_pack_major", "Service Pack major version number"},
1635
    {"service_pack_minor", "Service Pack minor version number"},
1636
    {"suite_mask", "Bit mask identifying available product suites"},
1637
    {"product_type", "System product type"},
1638
    {"platform_version", "Diagnostic version number"},
1639
    {"device_family", "'Desktop', 'Xbox' or 'UWP'"},
1640
    {0}
1641
};
1642
1643
static PyStructSequence_Desc windows_version_desc = {
1644
    "sys.getwindowsversion",       /* name */
1645
    sys_getwindowsversion__doc__,  /* doc */
1646
    windows_version_fields,        /* fields */
1647
    5                              /* For backward compatibility,
1648
                                      only the first 5 items are accessible
1649
                                      via indexing, the rest are name only */
1650
};
1651
1652
#ifdef MS_WINDOWS_DESKTOP
1653
static PyObject *
1654
_sys_getwindowsversion_from_kernel32(void)
1655
{
1656
    HANDLE hKernel32;
1657
    wchar_t kernel32_path[MAX_PATH];
1658
    LPVOID verblock;
1659
    DWORD verblock_size;
1660
    VS_FIXEDFILEINFO *ffi;
1661
    UINT ffi_len;
1662
    DWORD realMajor, realMinor, realBuild;
1663
1664
    Py_BEGIN_ALLOW_THREADS
1665
    hKernel32 = GetModuleHandleW(L"kernel32.dll");
1666
    Py_END_ALLOW_THREADS
1667
    if (!hKernel32 || !GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH)) {
1668
        PyErr_SetFromWindowsErr(0);
1669
        return NULL;
1670
    }
1671
    verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL);
1672
    if (!verblock_size) {
1673
        PyErr_SetFromWindowsErr(0);
1674
        return NULL;
1675
    }
1676
    verblock = PyMem_RawMalloc(verblock_size);
1677
    if (!verblock ||
1678
        !GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) ||
1679
        !VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1680
        PyErr_SetFromWindowsErr(0);
1681
        if (verblock) {
1682
            PyMem_RawFree(verblock);
1683
        }
1684
        return NULL;
1685
    }
1686
1687
    realMajor = HIWORD(ffi->dwProductVersionMS);
1688
    realMinor = LOWORD(ffi->dwProductVersionMS);
1689
    realBuild = HIWORD(ffi->dwProductVersionLS);
1690
    PyMem_RawFree(verblock);
1691
    return Py_BuildValue("(kkk)", realMajor, realMinor, realBuild);
1692
}
1693
#endif /* MS_WINDOWS_DESKTOP */
1694
1695
/* Disable deprecation warnings about GetVersionEx as the result is
1696
   being passed straight through to the caller, who is responsible for
1697
   using it correctly. */
1698
#pragma warning(push)
1699
#pragma warning(disable:4996)
1700
1701
/*[clinic input]
1702
sys.getwindowsversion
1703
1704
Return info about the running version of Windows as a named tuple.
1705
1706
The members are named: major, minor, build, platform, service_pack,
1707
service_pack_major, service_pack_minor, suite_mask, product_type and
1708
platform_version. For backward compatibility, only the first 5 items
1709
are available by indexing. All elements are numbers, except
1710
service_pack and platform_type which are strings, and platform_version
1711
which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1712
workstation, 2 for a domain controller, 3 for a server.
1713
Platform_version is a 3-tuple containing a version number that is
1714
intended for identifying the OS rather than feature detection.
1715
[clinic start generated code]*/
1716
1717
static PyObject *
1718
sys_getwindowsversion_impl(PyObject *module)
1719
/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
1720
{
1721
    PyObject *version;
1722
    int pos = 0;
1723
1724
    if (PyObject_GetOptionalAttrString(module, "_cached_windows_version", &version) < 0) {
1725
        return NULL;
1726
    };
1727
    if (version && PyObject_TypeCheck(version, &WindowsVersionType)) {
1728
        return version;
1729
    }
1730
    Py_XDECREF(version);
1731
1732
    OSVERSIONINFOEXW ver;
1733
    ZeroMemory(&ver, sizeof(ver));
1734
    ver.dwOSVersionInfoSize = sizeof(ver);
1735
    if (!GetVersionExW((OSVERSIONINFOW*) &ver))
1736
        return PyErr_SetFromWindowsErr(0);
1737
1738
    version = PyStructSequence_New(&WindowsVersionType);
1739
    if (version == NULL)
1740
        return NULL;
1741
1742
#define SET_VERSION_INFO(CALL)                               \
1743
    do {                                                     \
1744
        PyObject *item = (CALL);                             \
1745
        if (item == NULL) {                                  \
1746
            goto error;                                      \
1747
        }                                                    \
1748
        PyStructSequence_SET_ITEM(version, pos++, item);     \
1749
    } while(0)
1750
1751
    SET_VERSION_INFO(PyLong_FromLong(ver.dwMajorVersion));
1752
    SET_VERSION_INFO(PyLong_FromLong(ver.dwMinorVersion));
1753
    SET_VERSION_INFO(PyLong_FromLong(ver.dwBuildNumber));
1754
    SET_VERSION_INFO(PyLong_FromLong(ver.dwPlatformId));
1755
    SET_VERSION_INFO(PyUnicode_FromWideChar(ver.szCSDVersion, -1));
1756
    SET_VERSION_INFO(PyLong_FromLong(ver.wServicePackMajor));
1757
    SET_VERSION_INFO(PyLong_FromLong(ver.wServicePackMinor));
1758
    SET_VERSION_INFO(PyLong_FromLong(ver.wSuiteMask));
1759
    SET_VERSION_INFO(PyLong_FromLong(ver.wProductType));
1760
1761
#if defined(MS_WINDOWS_DESKTOP)
1762
    // GetVersion will lie if we are running in a compatibility mode.
1763
    // We need to read the version info from a system file resource
1764
    // to accurately identify the OS version. If we fail for any reason,
1765
    // just return whatever GetVersion said.
1766
    PyObject *realVersion = _sys_getwindowsversion_from_kernel32();
1767
    if (!realVersion) {
1768
        if (!PyErr_ExceptionMatches(PyExc_WindowsError)) {
1769
            goto error;
1770
        }
1771
1772
        PyErr_Clear();
1773
        realVersion = Py_BuildValue("(kkk)",
1774
            ver.dwMajorVersion,
1775
            ver.dwMinorVersion,
1776
            ver.dwBuildNumber
1777
        );
1778
    }
1779
1780
    SET_VERSION_INFO(realVersion);
1781
    SET_VERSION_INFO(PyUnicode_FromString("Desktop"));
1782
#elif defined(MS_WINDOWS_GAMES)
1783
    SET_VERSION_INFO(Py_BuildValue("(kkk)", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber));
1784
    SET_VERSION_INFO(PyUnicode_FromString("Xbox"));
1785
#else
1786
    SET_VERSION_INFO(Py_BuildValue("(kkk)", ver.dwMajorVersion, ver.dwMinorVersion, ver.dwBuildNumber));
1787
    SET_VERSION_INFO(PyUnicode_FromString("UWP"));
1788
#endif
1789
1790
#undef SET_VERSION_INFO
1791
1792
    if (PyObject_SetAttrString(module, "_cached_windows_version", version) < 0) {
1793
        goto error;
1794
    }
1795
1796
    return version;
1797
1798
error:
1799
    Py_DECREF(version);
1800
    return NULL;
1801
}
1802
1803
#pragma warning(pop)
1804
#endif /* MS_WINDOWS */
1805
1806
#ifdef HAVE_DLOPEN
1807
1808
/*[clinic input]
1809
sys.setdlopenflags
1810
1811
    flags as new_val: int
1812
    /
1813
1814
Set the flags used by the interpreter for dlopen calls.
1815
1816
This is used, for example, when the interpreter loads extension
1817
modules. Among other things, this will enable a lazy resolving of
1818
symbols when importing a module, if called as sys.setdlopenflags(0).
1819
To share symbols across extension modules, call as
1820
sys.setdlopenflags(os.RTLD_GLOBAL).  Symbolic names for the flag
1821
modules can be found in the os module (RTLD_xxx constants, e.g.
1822
os.RTLD_LAZY).
1823
[clinic start generated code]*/
1824
1825
static PyObject *
1826
sys_setdlopenflags_impl(PyObject *module, int new_val)
1827
/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
1828
0
{
1829
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1830
0
    _PyImport_SetDLOpenFlags(interp, new_val);
1831
0
    Py_RETURN_NONE;
1832
0
}
1833
1834
1835
/*[clinic input]
1836
sys.getdlopenflags
1837
1838
Return the current value of the flags that are used for dlopen calls.
1839
1840
The flag constants are defined in the os module.
1841
[clinic start generated code]*/
1842
1843
static PyObject *
1844
sys_getdlopenflags_impl(PyObject *module)
1845
/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
1846
0
{
1847
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1848
0
    return PyLong_FromLong(
1849
0
            _PyImport_GetDLOpenFlags(interp));
1850
0
}
1851
1852
#endif  /* HAVE_DLOPEN */
1853
1854
#ifdef USE_MALLOPT
1855
/* Link with -lmalloc (or -lmpc) on an SGI */
1856
#include <malloc.h>
1857
1858
/*[clinic input]
1859
sys.mdebug
1860
1861
    flag: int
1862
    /
1863
[clinic start generated code]*/
1864
1865
static PyObject *
1866
sys_mdebug_impl(PyObject *module, int flag)
1867
/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
1868
{
1869
    int flag;
1870
    mallopt(M_DEBUG, flag);
1871
    Py_RETURN_NONE;
1872
}
1873
#endif /* USE_MALLOPT */
1874
1875
1876
/*[clinic input]
1877
@permit_long_summary
1878
sys.get_int_max_str_digits
1879
1880
Return the maximum string digits limit for non-binary int<->str conversions.
1881
[clinic start generated code]*/
1882
1883
static PyObject *
1884
sys_get_int_max_str_digits_impl(PyObject *module)
1885
/*[clinic end generated code: output=0042f5e8ae0e8631 input=77fb74e987ba7ecb]*/
1886
0
{
1887
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
1888
0
    int maxdigits = _Py_atomic_load_int(&interp->long_state.max_str_digits);
1889
0
    return PyLong_FromLong(maxdigits);
1890
0
}
1891
1892
1893
/*[clinic input]
1894
@permit_long_summary
1895
sys.set_int_max_str_digits
1896
1897
    maxdigits: int
1898
1899
Set the maximum string digits limit for non-binary int<->str conversions.
1900
[clinic start generated code]*/
1901
1902
static PyObject *
1903
sys_set_int_max_str_digits_impl(PyObject *module, int maxdigits)
1904
/*[clinic end generated code: output=734d4c2511f2a56d input=d4c0bf50c466d57a]*/
1905
0
{
1906
0
    if (_PySys_SetIntMaxStrDigits(maxdigits) < 0) {
1907
0
        return NULL;
1908
0
    }
1909
0
    Py_RETURN_NONE;
1910
0
}
1911
1912
size_t
1913
_PySys_GetSizeOf(PyObject *o)
1914
0
{
1915
0
    PyObject *res = NULL;
1916
0
    PyObject *method;
1917
0
    Py_ssize_t size;
1918
0
    PyThreadState *tstate = _PyThreadState_GET();
1919
1920
    /* Make sure the type is initialized. float gets initialized late */
1921
0
    if (PyType_Ready(Py_TYPE(o)) < 0) {
1922
0
        return (size_t)-1;
1923
0
    }
1924
1925
0
    method = _PyObject_LookupSpecial(o, &_Py_ID(__sizeof__));
1926
0
    if (method == NULL) {
1927
0
        if (!_PyErr_Occurred(tstate)) {
1928
0
            _PyErr_Format(tstate, PyExc_TypeError,
1929
0
                          "Type %.100s doesn't define __sizeof__",
1930
0
                          Py_TYPE(o)->tp_name);
1931
0
        }
1932
0
    }
1933
0
    else {
1934
0
        res = _PyObject_CallNoArgs(method);
1935
0
        Py_DECREF(method);
1936
0
    }
1937
1938
0
    if (res == NULL)
1939
0
        return (size_t)-1;
1940
1941
0
    size = PyLong_AsSsize_t(res);
1942
0
    Py_DECREF(res);
1943
0
    if (size == -1 && _PyErr_Occurred(tstate))
1944
0
        return (size_t)-1;
1945
1946
0
    if (size < 0) {
1947
0
        _PyErr_SetString(tstate, PyExc_ValueError,
1948
0
                          "__sizeof__() should return >= 0");
1949
0
        return (size_t)-1;
1950
0
    }
1951
1952
0
    size_t presize = 0;
1953
0
    if (!Py_IS_TYPE(o, &PyType_Type) ||
1954
0
         PyType_HasFeature((PyTypeObject *)o, Py_TPFLAGS_HEAPTYPE))
1955
0
    {
1956
        /* Add the size of the pre-header if "o" is not a static type */
1957
0
        presize = _PyType_PreHeaderSize(Py_TYPE(o));
1958
0
    }
1959
1960
0
    return (size_t)size + presize;
1961
0
}
1962
1963
/*[clinic input]
1964
sys.getsizeof
1965
1966
    object as o: object
1967
    default as dflt: object = NULL
1968
1969
Return the size of object in bytes.
1970
[clinic start generated code]*/
1971
1972
static PyObject *
1973
sys_getsizeof_impl(PyObject *module, PyObject *o, PyObject *dflt)
1974
/*[clinic end generated code: output=c9dee8179ae2a973 input=fd71e98f0e3ae131]*/
1975
0
{
1976
0
    size_t size;
1977
0
    PyThreadState *tstate = _PyThreadState_GET();
1978
1979
0
    size = _PySys_GetSizeOf(o);
1980
1981
0
    if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
1982
        /* Has a default value been given */
1983
0
        if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1984
0
            _PyErr_Clear(tstate);
1985
0
            return Py_NewRef(dflt);
1986
0
        }
1987
0
        else
1988
0
            return NULL;
1989
0
    }
1990
1991
0
    return PyLong_FromSize_t(size);
1992
0
}
1993
1994
/*[clinic input]
1995
sys.getrefcount -> Py_ssize_t
1996
1997
    object:  object
1998
    /
1999
2000
Return the reference count of object.
2001
2002
The count returned is generally one higher than you might expect,
2003
because it includes the (temporary) reference as an argument to
2004
getrefcount().
2005
[clinic start generated code]*/
2006
2007
static Py_ssize_t
2008
sys_getrefcount_impl(PyObject *module, PyObject *object)
2009
/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
2010
4
{
2011
4
    return Py_REFCNT(object);
2012
4
}
2013
2014
#ifdef Py_REF_DEBUG
2015
/*[clinic input]
2016
sys.gettotalrefcount -> Py_ssize_t
2017
[clinic start generated code]*/
2018
2019
static Py_ssize_t
2020
sys_gettotalrefcount_impl(PyObject *module)
2021
/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
2022
{
2023
    /* It may make sense to return the total for the current interpreter
2024
       or have a second function that does so. */
2025
    return _Py_GetGlobalRefTotal();
2026
}
2027
2028
#endif /* Py_REF_DEBUG */
2029
2030
/*[clinic input]
2031
sys.getallocatedblocks -> Py_ssize_t
2032
2033
Return the number of memory blocks currently allocated.
2034
[clinic start generated code]*/
2035
2036
static Py_ssize_t
2037
sys_getallocatedblocks_impl(PyObject *module)
2038
/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
2039
0
{
2040
    // It might make sense to return the count
2041
    // for just the current interpreter.
2042
0
    return _Py_GetGlobalAllocatedBlocks();
2043
0
}
2044
2045
/*[clinic input]
2046
sys.getunicodeinternedsize -> Py_ssize_t
2047
2048
    *
2049
    _only_immortal: bool = False
2050
2051
Return the number of elements of the unicode interned dictionary
2052
[clinic start generated code]*/
2053
2054
static Py_ssize_t
2055
sys_getunicodeinternedsize_impl(PyObject *module, int _only_immortal)
2056
/*[clinic end generated code: output=29a6377a94a14f70 input=0330b3408dd5bcc6]*/
2057
0
{
2058
0
    if (_only_immortal) {
2059
0
        return _PyUnicode_InternedSize_Immortal();
2060
0
    }
2061
0
    else {
2062
0
        return _PyUnicode_InternedSize();
2063
0
    }
2064
0
}
2065
2066
/*[clinic input]
2067
sys._getframe
2068
2069
    depth: int = 0
2070
    /
2071
2072
Return a frame object from the call stack.
2073
2074
If optional integer depth is given, return the frame object that many
2075
calls below the top of the stack.  If that is deeper than the call
2076
stack, ValueError is raised.  The default for depth is zero, returning
2077
the frame at the top of the call stack.
2078
2079
This function should be used for internal and specialized purposes
2080
only.
2081
[clinic start generated code]*/
2082
2083
static PyObject *
2084
sys__getframe_impl(PyObject *module, int depth)
2085
/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
2086
21.4k
{
2087
21.4k
    PyThreadState *tstate = _PyThreadState_GET();
2088
21.4k
    _PyInterpreterFrame *frame = tstate->current_frame;
2089
2090
21.4k
    if (frame != NULL) {
2091
42.9k
        while (depth > 0) {
2092
21.4k
            frame = _PyFrame_GetFirstComplete(frame->previous);
2093
21.4k
            if (frame == NULL) {
2094
0
                break;
2095
0
            }
2096
21.4k
            --depth;
2097
21.4k
        }
2098
21.4k
    }
2099
21.4k
    if (frame == NULL) {
2100
0
        _PyErr_SetString(tstate, PyExc_ValueError,
2101
0
                         "call stack is not deep enough");
2102
0
        return NULL;
2103
0
    }
2104
2105
21.4k
    PyObject *pyFrame = Py_XNewRef((PyObject *)_PyFrame_GetFrameObject(frame));
2106
21.4k
    if (pyFrame && _PySys_Audit(tstate, "sys._getframe", "(O)", pyFrame) < 0) {
2107
0
        Py_DECREF(pyFrame);
2108
0
        return NULL;
2109
0
    }
2110
21.4k
    return pyFrame;
2111
21.4k
}
2112
2113
/*[clinic input]
2114
@permit_long_summary
2115
sys._current_frames
2116
2117
Return a dict mapping each thread's thread id to its current stack frame.
2118
2119
This function should be used for specialized purposes only.
2120
[clinic start generated code]*/
2121
2122
static PyObject *
2123
sys__current_frames_impl(PyObject *module)
2124
/*[clinic end generated code: output=d2a41ac0a0a3809a input=e1ce34f43501e0d6]*/
2125
0
{
2126
0
    return _PyThread_CurrentFrames();
2127
0
}
2128
2129
/*[clinic input]
2130
@permit_long_summary
2131
sys._current_exceptions
2132
2133
Return a dict mapping each thread's identifier to its current raised exception.
2134
2135
This function should be used for specialized purposes only.
2136
[clinic start generated code]*/
2137
2138
static PyObject *
2139
sys__current_exceptions_impl(PyObject *module)
2140
/*[clinic end generated code: output=2ccfd838c746f0ba input=4ba429b6cfcd736d]*/
2141
0
{
2142
0
    return _PyThread_CurrentExceptions();
2143
0
}
2144
2145
/*[clinic input]
2146
sys.call_tracing
2147
2148
    func: object
2149
    args as funcargs: object(subclass_of='&PyTuple_Type')
2150
    /
2151
2152
Call func(*args), while tracing is enabled.
2153
2154
The tracing state is saved, and restored afterwards.  This is intended
2155
to be called from a debugger from a checkpoint, to recursively debug
2156
some other code.
2157
[clinic start generated code]*/
2158
2159
static PyObject *
2160
sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
2161
/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
2162
0
{
2163
0
    return _PyEval_CallTracing(func, funcargs);
2164
0
}
2165
2166
/*[clinic input]
2167
sys._debugmallocstats
2168
2169
Print summary info to stderr about the state of pymalloc's structures.
2170
2171
In Py_DEBUG mode, also perform some expensive internal consistency
2172
checks.
2173
[clinic start generated code]*/
2174
2175
static PyObject *
2176
sys__debugmallocstats_impl(PyObject *module)
2177
/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
2178
0
{
2179
0
#ifdef WITH_PYMALLOC
2180
0
    if (_PyObject_DebugMallocStats(stderr)) {
2181
0
        fputc('\n', stderr);
2182
0
    }
2183
0
#endif
2184
0
    _PyObject_DebugTypeStats(stderr);
2185
2186
0
    Py_RETURN_NONE;
2187
0
}
2188
2189
#ifdef Py_TRACE_REFS
2190
/* Defined in objects.c because it uses static globals in that file */
2191
extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
2192
#endif
2193
2194
2195
/*[clinic input]
2196
sys._clear_type_cache
2197
2198
Clear the internal type lookup cache.
2199
[clinic start generated code]*/
2200
2201
static PyObject *
2202
sys__clear_type_cache_impl(PyObject *module)
2203
/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
2204
0
{
2205
0
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
2206
0
                     "sys._clear_type_cache() is deprecated and"
2207
0
                     " scheduled for removal in a future version."
2208
0
                     " Use sys._clear_internal_caches() instead.",
2209
0
                     1) < 0)
2210
0
    {
2211
0
        return NULL;
2212
0
    }
2213
0
    PyType_ClearCache();
2214
0
    Py_RETURN_NONE;
2215
0
}
2216
2217
/*[clinic input]
2218
sys._clear_internal_caches
2219
2220
Clear all internal performance-related caches.
2221
[clinic start generated code]*/
2222
2223
static PyObject *
2224
sys__clear_internal_caches_impl(PyObject *module)
2225
/*[clinic end generated code: output=0ee128670a4966d6 input=253e741ca744f6e8]*/
2226
0
{
2227
#ifdef _Py_TIER2
2228
    PyInterpreterState *interp = _PyInterpreterState_GET();
2229
    _Py_Executors_InvalidateAll(interp, 0);
2230
#endif
2231
#ifdef Py_GIL_DISABLED
2232
    if (_Py_ClearUnusedTLBC(_PyInterpreterState_GET()) < 0) {
2233
        return NULL;
2234
    }
2235
#endif
2236
0
    PyType_ClearCache();
2237
0
    Py_RETURN_NONE;
2238
0
}
2239
2240
/* Note that, for now, we do not have a per-interpreter equivalent
2241
  for sys.is_finalizing(). */
2242
2243
/*[clinic input]
2244
sys.is_finalizing
2245
2246
Return True if Python is exiting.
2247
[clinic start generated code]*/
2248
2249
static PyObject *
2250
sys_is_finalizing_impl(PyObject *module)
2251
/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
2252
0
{
2253
0
    return PyBool_FromLong(Py_IsFinalizing());
2254
0
}
2255
2256
2257
#ifdef Py_STATS
2258
/*[clinic input]
2259
sys._stats_on
2260
2261
Turns on stats gathering (stats gathering is off by default).
2262
[clinic start generated code]*/
2263
2264
static PyObject *
2265
sys__stats_on_impl(PyObject *module)
2266
/*[clinic end generated code: output=aca53eafcbb4d9fe input=43b5bfe145299e55]*/
2267
{
2268
    if (_Py_StatsOn() < 0) {
2269
        return NULL;
2270
    }
2271
    Py_RETURN_NONE;
2272
}
2273
2274
/*[clinic input]
2275
sys._stats_off
2276
2277
Turns off stats gathering (stats gathering is off by default).
2278
[clinic start generated code]*/
2279
2280
static PyObject *
2281
sys__stats_off_impl(PyObject *module)
2282
/*[clinic end generated code: output=1534c1ee63812214 input=d1a84c60c56cbce2]*/
2283
{
2284
    _Py_StatsOff();
2285
    Py_RETURN_NONE;
2286
}
2287
2288
/*[clinic input]
2289
sys._stats_clear
2290
2291
Clears the stats.
2292
[clinic start generated code]*/
2293
2294
static PyObject *
2295
sys__stats_clear_impl(PyObject *module)
2296
/*[clinic end generated code: output=fb65a2525ee50604 input=3e03f2654f44da96]*/
2297
{
2298
    _Py_StatsClear();
2299
    Py_RETURN_NONE;
2300
}
2301
2302
/*[clinic input]
2303
sys._stats_dump -> bool
2304
2305
Dump stats to file, and clears the stats.
2306
2307
Return False if no statistics were not dumped because stats gathering
2308
was off.
2309
[clinic start generated code]*/
2310
2311
static int
2312
sys__stats_dump_impl(PyObject *module)
2313
/*[clinic end generated code: output=6e346b4ba0de4489 input=7f3b7758cb59d2ff]*/
2314
{
2315
    int res = _Py_PrintSpecializationStats(1);
2316
    _Py_StatsClear();
2317
    return res;
2318
}
2319
#endif   // Py_STATS
2320
2321
2322
#ifdef ANDROID_API_LEVEL
2323
/*[clinic input]
2324
sys.getandroidapilevel
2325
2326
Return the build time API version of Android as an integer.
2327
[clinic start generated code]*/
2328
2329
static PyObject *
2330
sys_getandroidapilevel_impl(PyObject *module)
2331
/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
2332
{
2333
    return PyLong_FromLong(ANDROID_API_LEVEL);
2334
}
2335
#endif   /* ANDROID_API_LEVEL */
2336
2337
/*[clinic input]
2338
sys.activate_stack_trampoline
2339
2340
    backend: str
2341
    /
2342
2343
Activate stack profiler trampoline *backend*.
2344
[clinic start generated code]*/
2345
2346
static PyObject *
2347
sys_activate_stack_trampoline_impl(PyObject *module, const char *backend)
2348
/*[clinic end generated code: output=5783cdeb51874b43 input=a12df928758a82b4]*/
2349
0
{
2350
0
#ifdef PY_HAVE_PERF_TRAMPOLINE
2351
#ifdef _Py_JIT
2352
    // Perf state is process-wide, and only the main interpreter can enable
2353
    // the JIT. Check it even when called from a subinterpreter (gh-157247).
2354
    if (_PyInterpreterState_Main()->jit) {
2355
        PyErr_SetString(PyExc_ValueError, "Cannot activate the perf trampoline if the JIT is active");
2356
        return NULL;
2357
    }
2358
#endif
2359
2360
0
    if (strcmp(backend, "perf") == 0) {
2361
0
        _PyPerf_Callbacks cur_cb;
2362
0
        _PyPerfTrampoline_GetCallbacks(&cur_cb);
2363
0
        if (cur_cb.write_state != _Py_perfmap_callbacks.write_state) {
2364
0
            if (_PyPerfTrampoline_SetCallbacks(&_Py_perfmap_callbacks) < 0 ) {
2365
0
                PyErr_SetString(PyExc_ValueError, "can't activate perf trampoline");
2366
0
                return NULL;
2367
0
            }
2368
0
        }
2369
0
    }
2370
0
    else if (strcmp(backend, "perf_jit") == 0) {
2371
0
        _PyPerf_Callbacks cur_cb;
2372
0
        _PyPerfTrampoline_GetCallbacks(&cur_cb);
2373
0
        if (cur_cb.write_state != _Py_perfmap_jit_callbacks.write_state) {
2374
0
            if (_PyPerfTrampoline_SetCallbacks(&_Py_perfmap_jit_callbacks) < 0 ) {
2375
0
                PyErr_SetString(PyExc_ValueError, "can't activate perf jit trampoline");
2376
0
                return NULL;
2377
0
            }
2378
0
        }
2379
0
    }
2380
0
    else {
2381
0
        PyErr_Format(PyExc_ValueError, "invalid backend: %s", backend);
2382
0
        return NULL;
2383
0
    }
2384
0
    if (_PyPerfTrampoline_Init(1) < 0) {
2385
0
        return NULL;
2386
0
    }
2387
0
    Py_RETURN_NONE;
2388
#else
2389
    PyErr_SetString(PyExc_ValueError, "perf trampoline not available");
2390
    return NULL;
2391
#endif
2392
0
}
2393
2394
2395
/*[clinic input]
2396
sys.deactivate_stack_trampoline
2397
2398
Deactivate the current stack profiler trampoline backend.
2399
2400
If no stack profiler is activated, this function has no effect.
2401
[clinic start generated code]*/
2402
2403
static PyObject *
2404
sys_deactivate_stack_trampoline_impl(PyObject *module)
2405
/*[clinic end generated code: output=b50da25465df0ef1 input=9f629a6be9fe7fc8]*/
2406
0
{
2407
0
    if  (_PyPerfTrampoline_Init(0) < 0) {
2408
0
        return NULL;
2409
0
    }
2410
0
    Py_RETURN_NONE;
2411
0
}
2412
2413
/*[clinic input]
2414
sys.is_stack_trampoline_active
2415
2416
Return *True* if a stack profiler trampoline is active.
2417
[clinic start generated code]*/
2418
2419
static PyObject *
2420
sys_is_stack_trampoline_active_impl(PyObject *module)
2421
/*[clinic end generated code: output=ab2746de0ad9d293 input=29616b7bf6a0b703]*/
2422
0
{
2423
0
#ifdef PY_HAVE_PERF_TRAMPOLINE
2424
0
    if (_PyIsPerfTrampolineActive()) {
2425
0
        Py_RETURN_TRUE;
2426
0
    }
2427
0
#endif
2428
0
    Py_RETURN_FALSE;
2429
0
}
2430
2431
2432
/*[clinic input]
2433
sys.is_remote_debug_enabled
2434
2435
Return True if remote debugging is enabled, False otherwise.
2436
[clinic start generated code]*/
2437
2438
static PyObject *
2439
sys_is_remote_debug_enabled_impl(PyObject *module)
2440
/*[clinic end generated code: output=7ca3d38bdd5935eb input=7335c4a2fe8cf4f3]*/
2441
0
{
2442
#if !defined(Py_REMOTE_DEBUG) || !defined(Py_SUPPORTS_REMOTE_DEBUG)
2443
    Py_RETURN_FALSE;
2444
#else
2445
0
    const PyConfig *config = _Py_GetConfig();
2446
0
    return PyBool_FromLong(config->remote_debug);
2447
0
#endif
2448
0
}
2449
2450
/*[clinic input]
2451
sys.remote_exec
2452
2453
    pid: int
2454
    script: object
2455
2456
Executes a file containing Python code in a given remote Python process.
2457
2458
This function returns immediately, and the code will be executed by the
2459
target process's main thread at the next available opportunity,
2460
similarly to how signals are handled.  There is no interface to
2461
determine when the code has been executed.  The caller is responsible
2462
for making sure that the file still exists whenever the remote process
2463
tries to read it and that it hasn't been overwritten.
2464
2465
The remote process must be running a CPython interpreter of the same
2466
major and minor version as the local process.  If either the local or
2467
remote interpreter is pre-release (alpha, beta, or release candidate)
2468
then the local and remote interpreters must be the same exact version.
2469
2470
Args:
2471
     pid (int): The process ID of the target Python process.
2472
     script (str|bytes): The path to a file containing
2473
         the Python code to be executed.
2474
[clinic start generated code]*/
2475
2476
static PyObject *
2477
sys_remote_exec_impl(PyObject *module, int pid, PyObject *script)
2478
/*[clinic end generated code: output=7d94c56afe4a52c0 input=7bd58f8da20cb74c]*/
2479
0
{
2480
0
    PyObject *path;
2481
0
    const char *debugger_script_path;
2482
2483
0
    if (PyUnicode_FSConverter(script, &path) == 0) {
2484
0
        return NULL;
2485
0
    }
2486
2487
0
    if (PySys_Audit("sys.remote_exec", "iO", pid, script) < 0) {
2488
0
        goto error;
2489
0
    }
2490
2491
0
    debugger_script_path = PyBytes_AS_STRING(path);
2492
#ifdef MS_WINDOWS
2493
    PyObject *unicode_path;
2494
    if (PyUnicode_FSDecoder(path, &unicode_path) < 0) {
2495
        goto error;
2496
    }
2497
    // Use UTF-16 (wide char) version of the path for permission checks
2498
    wchar_t *debugger_script_path_w = PyUnicode_AsWideCharString(unicode_path, NULL);
2499
    Py_DECREF(unicode_path);
2500
    if (debugger_script_path_w == NULL) {
2501
        goto error;
2502
    }
2503
    DWORD attr = GetFileAttributesW(debugger_script_path_w);
2504
    if (attr == INVALID_FILE_ATTRIBUTES) {
2505
        DWORD err = GetLastError();
2506
        PyMem_Free(debugger_script_path_w);
2507
        if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) {
2508
            PyErr_SetString(PyExc_FileNotFoundError, "Script file does not exist");
2509
        }
2510
        else if (err == ERROR_ACCESS_DENIED) {
2511
            PyErr_SetString(PyExc_PermissionError, "Script file cannot be read");
2512
        }
2513
        else {
2514
            PyErr_SetFromWindowsErr(err);
2515
        }
2516
        goto error;
2517
    }
2518
    PyMem_Free(debugger_script_path_w);
2519
#else // MS_WINDOWS
2520
0
    if (access(debugger_script_path, F_OK | R_OK) != 0) {
2521
0
        switch (errno) {
2522
0
            case ENOENT:
2523
0
                PyErr_SetString(PyExc_FileNotFoundError, "Script file does not exist");
2524
0
                break;
2525
0
            case EACCES:
2526
0
                PyErr_SetString(PyExc_PermissionError, "Script file cannot be read");
2527
0
                break;
2528
0
            default:
2529
0
                PyErr_SetFromErrno(PyExc_OSError);
2530
0
        }
2531
0
        goto error;
2532
0
    }
2533
0
#endif // MS_WINDOWS
2534
0
    if (_PySysRemoteDebug_SendExec(pid, 0, debugger_script_path) < 0) {
2535
0
        goto error;
2536
0
    }
2537
2538
0
    Py_DECREF(path);
2539
0
    Py_RETURN_NONE;
2540
2541
0
error:
2542
0
    Py_DECREF(path);
2543
0
    return NULL;
2544
0
}
2545
2546
2547
2548
/*[clinic input]
2549
sys._dump_tracelets
2550
2551
    outpath: object
2552
2553
Dump the graph of tracelets in graphviz format
2554
[clinic start generated code]*/
2555
2556
static PyObject *
2557
sys__dump_tracelets_impl(PyObject *module, PyObject *outpath)
2558
/*[clinic end generated code: output=a7fe265e2bc3b674 input=5bff6880cd28ffd1]*/
2559
0
{
2560
0
    FILE *out = Py_fopen(outpath, "wb");
2561
0
    if (out == NULL) {
2562
0
        return NULL;
2563
0
    }
2564
0
    int err = _PyDumpExecutors(out);
2565
0
    fclose(out);
2566
0
    if (err) {
2567
0
        return NULL;
2568
0
    }
2569
0
    Py_RETURN_NONE;
2570
0
}
2571
2572
2573
/*[clinic input]
2574
sys._getframemodulename
2575
2576
    depth: int = 0
2577
2578
Return the name of the module for a calling frame.
2579
2580
The default depth returns the module containing the call to this API.
2581
A more typical use in a library will pass a depth of 1 to get the user's
2582
module rather than the library module.
2583
2584
If no frame, module, or name can be found, returns None.
2585
[clinic start generated code]*/
2586
2587
static PyObject *
2588
sys__getframemodulename_impl(PyObject *module, int depth)
2589
/*[clinic end generated code: output=1d70ef691f09d2db input=d4f1a8ed43b8fb46]*/
2590
164
{
2591
164
    if (PySys_Audit("sys._getframemodulename", "i", depth) < 0) {
2592
0
        return NULL;
2593
0
    }
2594
164
    _PyInterpreterFrame *f = _PyThreadState_GET()->current_frame;
2595
336
    while (f && (_PyFrame_IsIncomplete(f) || depth-- > 0)) {
2596
172
        f = f->previous;
2597
172
    }
2598
164
    if (f == NULL || PyStackRef_IsNull(f->f_funcobj)) {
2599
0
        Py_RETURN_NONE;
2600
0
    }
2601
164
    PyObject *func = PyStackRef_AsPyObjectBorrow(f->f_funcobj);
2602
164
    PyObject *r = PyFunction_GetModule(func);
2603
164
    if (!r) {
2604
0
        PyErr_Clear();
2605
0
        r = Py_None;
2606
0
    }
2607
164
    return Py_NewRef(r);
2608
164
}
2609
2610
/*[clinic input]
2611
sys._get_cpu_count_config -> int
2612
2613
Private function for getting PyConfig.cpu_count
2614
[clinic start generated code]*/
2615
2616
static int
2617
sys__get_cpu_count_config_impl(PyObject *module)
2618
/*[clinic end generated code: output=36611bb5efad16dc input=523e1ade2204084e]*/
2619
37
{
2620
37
    const PyConfig *config = _Py_GetConfig();
2621
37
    return config->cpu_count;
2622
37
}
2623
2624
/*[clinic input]
2625
sys._baserepl
2626
2627
Private function for getting the base REPL
2628
[clinic start generated code]*/
2629
2630
static PyObject *
2631
sys__baserepl_impl(PyObject *module)
2632
/*[clinic end generated code: output=f19a36375ebe0a45 input=ade0ebb9fab56f3c]*/
2633
0
{
2634
0
    PyCompilerFlags cf = _PyCompilerFlags_INIT;
2635
0
    PyRun_AnyFileExFlags(stdin, "<stdin>", 0, &cf);
2636
0
    Py_RETURN_NONE;
2637
0
}
2638
2639
2640
/*[clinic input]
2641
sys._is_gil_enabled -> bool
2642
2643
Return True if the GIL is currently enabled and False otherwise.
2644
[clinic start generated code]*/
2645
2646
static int
2647
sys__is_gil_enabled_impl(PyObject *module)
2648
/*[clinic end generated code: output=57732cf53f5b9120 input=7e9c47f15a00e809]*/
2649
0
{
2650
#ifdef Py_GIL_DISABLED
2651
    return _PyEval_IsGILEnabled(_PyThreadState_GET());
2652
#else
2653
0
    return 1;
2654
0
#endif
2655
0
}
2656
2657
2658
#ifndef MS_WINDOWS
2659
static PerfMapState perf_map_state;
2660
#endif
2661
2662
0
PyAPI_FUNC(int) PyUnstable_PerfMapState_Init(void) {
2663
0
#ifndef MS_WINDOWS
2664
0
    char filename[100];
2665
0
    pid_t pid = getpid();
2666
    // Use nofollow flag to prevent symlink attacks.
2667
0
    int flags = O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW;
2668
0
#ifdef O_CLOEXEC
2669
0
    flags |= O_CLOEXEC;
2670
0
#endif
2671
0
    snprintf(filename, sizeof(filename) - 1, "/tmp/perf-%jd.map",
2672
0
                (intmax_t)pid);
2673
0
    int fd = open(filename, flags, 0600);
2674
0
    if (fd == -1) {
2675
0
        return -1;
2676
0
    }
2677
0
    else{
2678
0
        perf_map_state.perf_map = fdopen(fd, "a");
2679
0
        if (perf_map_state.perf_map == NULL) {
2680
0
            close(fd);
2681
0
            return -1;
2682
0
        }
2683
0
    }
2684
0
    perf_map_state.map_lock = PyThread_allocate_lock();
2685
0
    if (perf_map_state.map_lock == NULL) {
2686
0
        fclose(perf_map_state.perf_map);
2687
0
        return -2;
2688
0
    }
2689
0
#endif
2690
0
    return 0;
2691
0
}
2692
2693
PyAPI_FUNC(int) PyUnstable_WritePerfMapEntry(
2694
    const void *code_addr,
2695
    size_t code_size,
2696
    const char *entry_name
2697
0
) {
2698
0
#ifndef MS_WINDOWS
2699
0
    if (perf_map_state.perf_map == NULL) {
2700
0
        int ret = PyUnstable_PerfMapState_Init();
2701
0
        if (ret != 0){
2702
0
            return ret;
2703
0
        }
2704
0
    }
2705
0
    PyThread_acquire_lock(perf_map_state.map_lock, 1);
2706
0
    fprintf(perf_map_state.perf_map, "%" PRIxPTR " %zx %s\n", (uintptr_t) code_addr, code_size, entry_name);
2707
0
    fflush(perf_map_state.perf_map);
2708
0
    PyThread_release_lock(perf_map_state.map_lock);
2709
0
#endif
2710
0
    return 0;
2711
0
}
2712
2713
0
PyAPI_FUNC(void) PyUnstable_PerfMapState_Fini(void) {
2714
0
#ifndef MS_WINDOWS
2715
0
    if (perf_map_state.perf_map != NULL) {
2716
        // close the file
2717
0
        PyThread_acquire_lock(perf_map_state.map_lock, 1);
2718
0
        fclose(perf_map_state.perf_map);
2719
0
        PyThread_release_lock(perf_map_state.map_lock);
2720
2721
        // clean up the lock and state
2722
0
        PyThread_free_lock(perf_map_state.map_lock);
2723
0
        perf_map_state.perf_map = NULL;
2724
0
    }
2725
0
#endif
2726
0
}
2727
2728
0
PyAPI_FUNC(int) PyUnstable_CopyPerfMapFile(const char* parent_filename) {
2729
0
#ifndef MS_WINDOWS
2730
0
    if (perf_map_state.perf_map == NULL) {
2731
0
        int ret = PyUnstable_PerfMapState_Init();
2732
0
        if (ret != 0) {
2733
0
            return ret;
2734
0
        }
2735
0
    }
2736
0
    FILE* from = fopen(parent_filename, "r");
2737
0
    if (!from) {
2738
0
        return -1;
2739
0
    }
2740
0
    char buf[4096];
2741
0
    PyThread_acquire_lock(perf_map_state.map_lock, 1);
2742
0
    int result = 0;
2743
0
    while (1) {
2744
0
        size_t bytes_read = fread(buf, 1, sizeof(buf), from);
2745
0
        if (bytes_read == 0) {
2746
0
            if (ferror(from)) {
2747
0
                result = -1;
2748
0
            }
2749
0
            break;
2750
0
        }
2751
2752
0
        size_t bytes_written = fwrite(buf, 1, bytes_read, perf_map_state.perf_map);
2753
0
        if (bytes_written < bytes_read) {
2754
0
            result = -1;
2755
0
            break;
2756
0
        }
2757
2758
0
        if (fflush(perf_map_state.perf_map) != 0) {
2759
0
            result = -1;
2760
0
            break;
2761
0
        }
2762
2763
0
        if (bytes_read < sizeof(buf) && feof(from)) {
2764
0
            break;
2765
0
        }
2766
0
    }
2767
0
    fclose(from);
2768
0
    PyThread_release_lock(perf_map_state.map_lock);
2769
0
    return result;
2770
0
#endif
2771
0
    return 0;
2772
0
}
2773
2774
/*[clinic input]
2775
sys.set_lazy_imports_filter
2776
2777
    filter: object
2778
2779
Set the lazy imports filter callback.
2780
2781
The filter receives three positional arguments:
2782
2783
(importing_module_name, resolved_imported_module_name, fromlist)
2784
2785
The filter returns True to allow a lazy import, or False to force an
2786
eager import.
2787
The filter runs when the import statement executes.
2788
2789
Pass None to clear the filter.
2790
[clinic start generated code]*/
2791
2792
static PyObject *
2793
sys_set_lazy_imports_filter_impl(PyObject *module, PyObject *filter)
2794
/*[clinic end generated code: output=10251d49469c278c input=c19391861fdd55d5]*/
2795
0
{
2796
0
    if (PyImport_SetLazyImportsFilter(filter) < 0) {
2797
0
        return NULL;
2798
0
    }
2799
2800
0
    Py_RETURN_NONE;
2801
0
}
2802
2803
/*[clinic input]
2804
sys.get_lazy_imports_filter
2805
2806
Get the current lazy imports filter callback.
2807
2808
Returns the filter callable or None if no filter is set.
2809
[clinic start generated code]*/
2810
2811
static PyObject *
2812
sys_get_lazy_imports_filter_impl(PyObject *module)
2813
/*[clinic end generated code: output=3bf73022892165af input=cf1e07cb8e203c94]*/
2814
0
{
2815
0
    PyObject *filter = PyImport_GetLazyImportsFilter();
2816
0
    if (filter == NULL) {
2817
0
        assert(!PyErr_Occurred());
2818
0
        Py_RETURN_NONE;
2819
0
    }
2820
0
    return filter;
2821
0
}
2822
2823
/*[clinic input]
2824
sys.set_lazy_imports
2825
2826
    mode: object
2827
2828
Set the lazy import mode for the current interpreter.
2829
2830
The mode parameter must be one of these strings:
2831
- "all": Make eligible module-scope imports potentially lazy.
2832
- "normal": Respect the 'lazy' keyword and __lazy_modules__.
2833
2834
The filter from sys.set_lazy_imports_filter can force an eager import.
2835
2836
[clinic start generated code]*/
2837
2838
static PyObject *
2839
sys_set_lazy_imports_impl(PyObject *module, PyObject *mode)
2840
/*[clinic end generated code: output=1ff34ba6c4feaf73 input=b8d9528c12efa7f0]*/
2841
0
{
2842
0
    PyImport_LazyImportsMode lazy_mode;
2843
0
    if (!PyUnicode_Check(mode)) {
2844
0
        PyErr_SetString(PyExc_TypeError,
2845
0
                        "mode must be a string: 'normal' or 'all'");
2846
0
        return NULL;
2847
0
    }
2848
0
    if (PyUnicode_CompareWithASCIIString(mode, "normal") == 0) {
2849
0
        lazy_mode = PyImport_LAZY_NORMAL;
2850
0
    }
2851
0
    else if (PyUnicode_CompareWithASCIIString(mode, "all") == 0) {
2852
0
        lazy_mode = PyImport_LAZY_ALL;
2853
0
    }
2854
0
    else {
2855
0
        PyErr_SetString(PyExc_ValueError,
2856
0
                        "mode must be 'normal' or 'all'");
2857
0
        return NULL;
2858
0
    }
2859
2860
0
    if (PyImport_SetLazyImportsMode(lazy_mode)) {
2861
0
        return NULL;
2862
0
    }
2863
0
    Py_RETURN_NONE;
2864
0
}
2865
2866
/*[clinic input]
2867
sys.get_lazy_imports
2868
2869
Return the lazy import mode for the current interpreter.
2870
2871
The mode is "all" if eligible module-scope imports are potentially lazy.
2872
The default mode, "normal", respects the 'lazy' keyword and
2873
__lazy_modules__.
2874
2875
[clinic start generated code]*/
2876
2877
static PyObject *
2878
sys_get_lazy_imports_impl(PyObject *module)
2879
/*[clinic end generated code: output=4147dec48c51ae99 input=ca95d71297deea55]*/
2880
0
{
2881
0
    switch (PyImport_GetLazyImportsMode()) {
2882
0
        case PyImport_LAZY_NORMAL:
2883
0
            return PyUnicode_FromString("normal");
2884
0
        case PyImport_LAZY_ALL:
2885
0
            return PyUnicode_FromString("all");
2886
0
        default:
2887
0
            PyErr_SetString(PyExc_RuntimeError, "unknown lazy imports mode");
2888
0
            return NULL;
2889
0
    }
2890
0
}
2891
2892
static PyMethodDef sys_methods[] = {
2893
    /* Might as well keep this in alphabetic order */
2894
    SYS_ADDAUDITHOOK_METHODDEF
2895
    SYS_AUDIT_METHODDEF
2896
    {"breakpointhook", _PyCFunction_CAST(sys_breakpointhook),
2897
     METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
2898
    SYS__CLEAR_INTERNAL_CACHES_METHODDEF
2899
    SYS__CLEAR_TYPE_CACHE_METHODDEF
2900
    SYS__CURRENT_FRAMES_METHODDEF
2901
    SYS__CURRENT_EXCEPTIONS_METHODDEF
2902
    SYS_DISPLAYHOOK_METHODDEF
2903
    SYS_EXCEPTION_METHODDEF
2904
    SYS_EXC_INFO_METHODDEF
2905
    SYS_EXCEPTHOOK_METHODDEF
2906
    SYS_EXIT_METHODDEF
2907
    SYS_GETDEFAULTENCODING_METHODDEF
2908
    SYS_GETDLOPENFLAGS_METHODDEF
2909
    SYS_GETALLOCATEDBLOCKS_METHODDEF
2910
    SYS_GETUNICODEINTERNEDSIZE_METHODDEF
2911
    SYS_GETFILESYSTEMENCODING_METHODDEF
2912
    SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
2913
#ifdef Py_TRACE_REFS
2914
    {"getobjects", _Py_GetObjects, METH_VARARGS},
2915
#endif
2916
    SYS_GETTOTALREFCOUNT_METHODDEF
2917
    SYS_GETREFCOUNT_METHODDEF
2918
    SYS_GETRECURSIONLIMIT_METHODDEF
2919
    SYS_GETSIZEOF_METHODDEF
2920
    SYS__GETFRAME_METHODDEF
2921
    SYS__GETFRAMEMODULENAME_METHODDEF
2922
    SYS_GETWINDOWSVERSION_METHODDEF
2923
    SYS__IS_IMMORTAL_METHODDEF
2924
    SYS_INTERN_METHODDEF
2925
    SYS__IS_INTERNED_METHODDEF
2926
    SYS_IS_FINALIZING_METHODDEF
2927
    SYS_MDEBUG_METHODDEF
2928
    SYS_SETSWITCHINTERVAL_METHODDEF
2929
    SYS_GETSWITCHINTERVAL_METHODDEF
2930
    SYS_SETDLOPENFLAGS_METHODDEF
2931
    SYS_SETPROFILE_METHODDEF
2932
    SYS__SETPROFILEALLTHREADS_METHODDEF
2933
    SYS_GETPROFILE_METHODDEF
2934
    SYS_SETRECURSIONLIMIT_METHODDEF
2935
    SYS_SETTRACE_METHODDEF
2936
    SYS__SETTRACEALLTHREADS_METHODDEF
2937
    SYS_GETTRACE_METHODDEF
2938
    SYS_CALL_TRACING_METHODDEF
2939
    SYS__DEBUGMALLOCSTATS_METHODDEF
2940
    SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2941
    SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2942
    SYS_SET_ASYNCGEN_HOOKS_METHODDEF
2943
    SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2944
    SYS_GETANDROIDAPILEVEL_METHODDEF
2945
    SYS_ACTIVATE_STACK_TRAMPOLINE_METHODDEF
2946
    SYS_DEACTIVATE_STACK_TRAMPOLINE_METHODDEF
2947
    SYS_IS_STACK_TRAMPOLINE_ACTIVE_METHODDEF
2948
    SYS_IS_REMOTE_DEBUG_ENABLED_METHODDEF
2949
    SYS_REMOTE_EXEC_METHODDEF
2950
    SYS_UNRAISABLEHOOK_METHODDEF
2951
    SYS_GET_INT_MAX_STR_DIGITS_METHODDEF
2952
    SYS_SET_INT_MAX_STR_DIGITS_METHODDEF
2953
    SYS_GET_LAZY_IMPORTS_METHODDEF
2954
    SYS_SET_LAZY_IMPORTS_METHODDEF
2955
    SYS_GET_LAZY_IMPORTS_FILTER_METHODDEF
2956
    SYS_SET_LAZY_IMPORTS_FILTER_METHODDEF
2957
    SYS__BASEREPL_METHODDEF
2958
#ifdef Py_STATS
2959
    SYS__STATS_ON_METHODDEF
2960
    SYS__STATS_OFF_METHODDEF
2961
    SYS__STATS_CLEAR_METHODDEF
2962
    SYS__STATS_DUMP_METHODDEF
2963
#endif
2964
    SYS__GET_CPU_COUNT_CONFIG_METHODDEF
2965
    SYS__IS_GIL_ENABLED_METHODDEF
2966
    SYS__DUMP_TRACELETS_METHODDEF
2967
    {NULL, NULL}  // sentinel
2968
};
2969
2970
2971
static PyObject *
2972
list_builtin_module_names(void)
2973
37
{
2974
37
    PyObject *list = _PyImport_GetBuiltinModuleNames();
2975
37
    if (list == NULL) {
2976
0
        return NULL;
2977
0
    }
2978
37
    if (PyList_Sort(list) != 0) {
2979
0
        goto error;
2980
0
    }
2981
37
    PyObject *tuple = PyList_AsTuple(list);
2982
37
    Py_DECREF(list);
2983
37
    return tuple;
2984
2985
0
error:
2986
0
    Py_DECREF(list);
2987
0
    return NULL;
2988
37
}
2989
2990
2991
static PyObject *
2992
list_stdlib_module_names(void)
2993
37
{
2994
37
    Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
2995
37
    PyObject *names = PyTuple_New(len);
2996
37
    if (names == NULL) {
2997
0
        return NULL;
2998
0
    }
2999
3000
11.0k
    for (Py_ssize_t i = 0; i < len; i++) {
3001
10.9k
        PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
3002
10.9k
        if (name == NULL) {
3003
0
            Py_DECREF(names);
3004
0
            return NULL;
3005
0
        }
3006
10.9k
        PyTuple_SET_ITEM(names, i, name);
3007
10.9k
    }
3008
3009
37
    PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
3010
37
                                          "(O)", names);
3011
37
    Py_DECREF(names);
3012
37
    return set;
3013
37
}
3014
3015
3016
/* Pre-initialization support for sys.warnoptions and sys._xoptions
3017
 *
3018
 * Modern internal code paths:
3019
 *   These APIs get called after _Py_InitializeCore and get to use the
3020
 *   regular CPython list, dict, and unicode APIs.
3021
 *
3022
 * Legacy embedding code paths:
3023
 *   The multi-phase initialization API isn't public yet, so embedding
3024
 *   apps still need to be able configure sys.warnoptions and sys._xoptions
3025
 *   before they call Py_Initialize. To support this, we stash copies of
3026
 *   the supplied wchar * sequences in linked lists, and then migrate the
3027
 *   contents of those lists to the sys module in _PyInitializeCore.
3028
 *
3029
 */
3030
3031
struct _preinit_entry {
3032
    wchar_t *value;
3033
    struct _preinit_entry *next;
3034
};
3035
3036
typedef struct _preinit_entry *_Py_PreInitEntry;
3037
3038
static _Py_PreInitEntry _preinit_warnoptions = NULL;
3039
static _Py_PreInitEntry _preinit_xoptions = NULL;
3040
3041
static _Py_PreInitEntry
3042
_alloc_preinit_entry(const wchar_t *value)
3043
0
{
3044
    /* To get this to work, we have to initialize the runtime implicitly */
3045
0
    _PyRuntime_Initialize();
3046
3047
    /* Use the default allocator, so we can ensure that it also gets used to
3048
     * destroy the linked list in _clear_preinit_entries.
3049
     */
3050
0
    _Py_PreInitEntry node = _PyMem_DefaultRawCalloc(1, sizeof(*node));
3051
0
    if (node != NULL) {
3052
0
        node->value = _PyMem_DefaultRawWcsdup(value);
3053
0
        if (node->value == NULL) {
3054
0
            _PyMem_DefaultRawFree(node);
3055
0
            node = NULL;
3056
0
        };
3057
0
    };
3058
0
    return node;
3059
0
}
3060
3061
static int
3062
_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
3063
0
{
3064
0
    _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
3065
0
    if (new_entry == NULL) {
3066
0
        return -1;
3067
0
    }
3068
    /* We maintain the linked list in this order so it's easy to play back
3069
     * the add commands in the same order later on in _Py_InitializeCore
3070
     */
3071
0
    _Py_PreInitEntry last_entry = *optionlist;
3072
0
    if (last_entry == NULL) {
3073
0
        *optionlist = new_entry;
3074
0
    } else {
3075
0
        while (last_entry->next != NULL) {
3076
0
            last_entry = last_entry->next;
3077
0
        }
3078
0
        last_entry->next = new_entry;
3079
0
    }
3080
0
    return 0;
3081
0
}
3082
3083
static void
3084
_clear_preinit_entries(_Py_PreInitEntry *optionlist)
3085
74
{
3086
74
    _Py_PreInitEntry current = *optionlist;
3087
74
    *optionlist = NULL;
3088
    /* Deallocate the nodes and their contents using the default allocator */
3089
74
    while (current != NULL) {
3090
0
        _Py_PreInitEntry next = current->next;
3091
0
        _PyMem_DefaultRawFree(current->value);
3092
0
        _PyMem_DefaultRawFree(current);
3093
0
        current = next;
3094
0
    }
3095
74
}
3096
3097
3098
PyStatus
3099
_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
3100
37
{
3101
37
    PyStatus status;
3102
37
    _Py_PreInitEntry entry;
3103
3104
37
    for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
3105
0
        status = PyWideStringList_Append(options, entry->value);
3106
0
        if (_PyStatus_EXCEPTION(status)) {
3107
0
            return status;
3108
0
        }
3109
0
    }
3110
3111
37
    _clear_preinit_entries(&_preinit_warnoptions);
3112
37
    return _PyStatus_OK();
3113
37
}
3114
3115
3116
PyStatus
3117
_PySys_ReadPreinitXOptions(PyConfig *config)
3118
37
{
3119
37
    PyStatus status;
3120
37
    _Py_PreInitEntry entry;
3121
3122
37
    for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
3123
0
        status = PyWideStringList_Append(&config->xoptions, entry->value);
3124
0
        if (_PyStatus_EXCEPTION(status)) {
3125
0
            return status;
3126
0
        }
3127
0
    }
3128
3129
37
    _clear_preinit_entries(&_preinit_xoptions);
3130
37
    return _PyStatus_OK();
3131
37
}
3132
3133
3134
static PyObject *
3135
get_warnoptions(PyThreadState *tstate)
3136
0
{
3137
0
    PyObject *warnoptions;
3138
0
    if (PySys_GetOptionalAttr(&_Py_ID(warnoptions), &warnoptions) < 0) {
3139
0
        return NULL;
3140
0
    }
3141
0
    if (warnoptions == NULL || !PyList_Check(warnoptions)) {
3142
        /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
3143
        *  interpreter config. When that happens, we need to properly set
3144
         * the `warnoptions` reference in the main interpreter config as well.
3145
         *
3146
         * For Python 3.7, we shouldn't be able to get here due to the
3147
         * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
3148
         * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
3149
         * call optional for embedding applications, thus making this
3150
         * reachable again.
3151
         */
3152
0
        Py_XDECREF(warnoptions);
3153
0
        warnoptions = PyList_New(0);
3154
0
        if (warnoptions == NULL) {
3155
0
            return NULL;
3156
0
        }
3157
0
        if (sys_set_object(tstate->interp, &_Py_ID(warnoptions), warnoptions)) {
3158
0
            Py_DECREF(warnoptions);
3159
0
            return NULL;
3160
0
        }
3161
0
    }
3162
0
    return warnoptions;
3163
0
}
3164
3165
PyAPI_FUNC(void)
3166
PySys_ResetWarnOptions(void)
3167
0
{
3168
0
    PyThreadState *tstate = _PyThreadState_GET();
3169
0
    if (tstate == NULL) {
3170
0
        _clear_preinit_entries(&_preinit_warnoptions);
3171
0
        return;
3172
0
    }
3173
3174
0
    PyObject *warnoptions;
3175
0
    if (PySys_GetOptionalAttr(&_Py_ID(warnoptions), &warnoptions) < 0) {
3176
0
        PyErr_Clear();
3177
0
        return;
3178
0
    }
3179
0
    if (warnoptions != NULL && PyList_Check(warnoptions)) {
3180
0
        PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
3181
0
    }
3182
0
    Py_XDECREF(warnoptions);
3183
0
}
3184
3185
static int
3186
_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
3187
0
{
3188
0
    assert(tstate != NULL);
3189
0
    PyObject *warnoptions = get_warnoptions(tstate);
3190
0
    if (warnoptions == NULL) {
3191
0
        return -1;
3192
0
    }
3193
0
    if (PyList_Append(warnoptions, option)) {
3194
0
        Py_DECREF(warnoptions);
3195
0
        return -1;
3196
0
    }
3197
0
    Py_DECREF(warnoptions);
3198
0
    return 0;
3199
0
}
3200
3201
// Removed in Python 3.13 API, but kept for the stable ABI
3202
PyAPI_FUNC(void)
3203
PySys_AddWarnOptionUnicode(PyObject *option)
3204
0
{
3205
0
    PyThreadState *tstate = _PyThreadState_GET();
3206
0
    _Py_EnsureTstateNotNULL(tstate);
3207
0
    assert(!_PyErr_Occurred(tstate));
3208
0
    if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
3209
        /* No return value, therefore clear error state if possible */
3210
0
        _PyErr_Clear(tstate);
3211
0
    }
3212
0
}
3213
3214
// Removed in Python 3.13 API, but kept for the stable ABI
3215
PyAPI_FUNC(void)
3216
PySys_AddWarnOption(const wchar_t *s)
3217
0
{
3218
0
    PyThreadState *tstate = _PyThreadState_GET();
3219
0
    if (tstate == NULL) {
3220
0
        _append_preinit_entry(&_preinit_warnoptions, s);
3221
0
        return;
3222
0
    }
3223
0
    PyObject *unicode;
3224
0
    unicode = PyUnicode_FromWideChar(s, -1);
3225
0
    if (unicode == NULL)
3226
0
        return;
3227
0
_Py_COMP_DIAG_PUSH
3228
0
_Py_COMP_DIAG_IGNORE_DEPR_DECLS
3229
0
    PySys_AddWarnOptionUnicode(unicode);
3230
0
_Py_COMP_DIAG_POP
3231
0
    Py_DECREF(unicode);
3232
0
}
3233
3234
// Removed in Python 3.13 API, but kept for the stable ABI
3235
PyAPI_FUNC(int)
3236
PySys_HasWarnOptions(void)
3237
0
{
3238
0
    PyObject *warnoptions;
3239
0
    if (PySys_GetOptionalAttr(&_Py_ID(warnoptions), &warnoptions) < 0) {
3240
0
        PyErr_Clear();
3241
0
        return 0;
3242
0
    }
3243
0
    int r = (warnoptions != NULL && PyList_Check(warnoptions) &&
3244
0
             PyList_GET_SIZE(warnoptions) > 0);
3245
0
    Py_XDECREF(warnoptions);
3246
0
    return r;
3247
0
}
3248
3249
static PyObject *
3250
get_xoptions(PyThreadState *tstate)
3251
0
{
3252
0
    PyObject *xoptions;
3253
0
    if (PySys_GetOptionalAttr(&_Py_ID(_xoptions), &xoptions) < 0) {
3254
0
        return NULL;
3255
0
    }
3256
0
    if (xoptions == NULL || !PyDict_Check(xoptions)) {
3257
        /* PEP432 TODO: we can reach this if xoptions is NULL in the main
3258
        *  interpreter config. When that happens, we need to properly set
3259
         * the `xoptions` reference in the main interpreter config as well.
3260
         *
3261
         * For Python 3.7, we shouldn't be able to get here due to the
3262
         * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
3263
         * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
3264
         * call optional for embedding applications, thus making this
3265
         * reachable again.
3266
         */
3267
0
        Py_XDECREF(xoptions);
3268
0
        xoptions = PyDict_New();
3269
0
        if (xoptions == NULL) {
3270
0
            return NULL;
3271
0
        }
3272
0
        if (sys_set_object(tstate->interp, &_Py_ID(_xoptions), xoptions)) {
3273
0
            Py_DECREF(xoptions);
3274
0
            return NULL;
3275
0
        }
3276
0
    }
3277
0
    return xoptions;
3278
0
}
3279
3280
static int
3281
_PySys_AddXOptionWithError(const wchar_t *s)
3282
0
{
3283
0
    PyObject *name = NULL, *value = NULL;
3284
3285
0
    PyThreadState *tstate = _PyThreadState_GET();
3286
0
    PyObject *opts = get_xoptions(tstate);
3287
0
    if (opts == NULL) {
3288
0
        goto error;
3289
0
    }
3290
3291
0
    const wchar_t *name_end = wcschr(s, L'=');
3292
0
    if (!name_end) {
3293
0
        name = PyUnicode_FromWideChar(s, -1);
3294
0
        if (name == NULL) {
3295
0
            goto error;
3296
0
        }
3297
0
        value = Py_NewRef(Py_True);
3298
0
    }
3299
0
    else {
3300
0
        name = PyUnicode_FromWideChar(s, name_end - s);
3301
0
        if (name == NULL) {
3302
0
            goto error;
3303
0
        }
3304
0
        value = PyUnicode_FromWideChar(name_end + 1, -1);
3305
0
        if (value == NULL) {
3306
0
            goto error;
3307
0
        }
3308
0
    }
3309
0
    if (PyDict_SetItem(opts, name, value) < 0) {
3310
0
        goto error;
3311
0
    }
3312
0
    Py_DECREF(name);
3313
0
    Py_DECREF(value);
3314
0
    Py_DECREF(opts);
3315
0
    return 0;
3316
3317
0
error:
3318
0
    Py_XDECREF(name);
3319
0
    Py_XDECREF(value);
3320
0
    Py_XDECREF(opts);
3321
0
    return -1;
3322
0
}
3323
3324
// Removed in Python 3.13 API, but kept for the stable ABI
3325
PyAPI_FUNC(void)
3326
PySys_AddXOption(const wchar_t *s)
3327
0
{
3328
0
    PyThreadState *tstate = _PyThreadState_GET();
3329
0
    if (tstate == NULL) {
3330
0
        _append_preinit_entry(&_preinit_xoptions, s);
3331
0
        return;
3332
0
    }
3333
0
    if (_PySys_AddXOptionWithError(s) < 0) {
3334
        /* No return value, therefore clear error state if possible */
3335
0
        _PyErr_Clear(tstate);
3336
0
    }
3337
0
}
3338
3339
PyObject *
3340
PySys_GetXOptions(void)
3341
0
{
3342
0
    PyThreadState *tstate = _PyThreadState_GET();
3343
0
    PyObject *opts = get_xoptions(tstate);
3344
0
    Py_XDECREF(opts);
3345
0
    return opts;
3346
0
}
3347
3348
/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
3349
   Two literals concatenated works just fine.  If you have a K&R compiler
3350
   or other abomination that however *does* understand longer strings,
3351
   get rid of the !!! comment in the middle and the quotes that surround it. */
3352
PyDoc_VAR(sys_doc) =
3353
PyDoc_STR(
3354
"This module provides access to some objects used or maintained by the\n\
3355
interpreter and to functions that interact strongly with the interpreter.\n\
3356
\n\
3357
Dynamic objects:\n\
3358
\n\
3359
argv -- command line arguments; argv[0] is the script pathname if known\n\
3360
path -- module search path; path[0] is the script directory, else ''\n\
3361
modules -- dictionary of loaded modules\n\
3362
\n\
3363
displayhook -- called to show results in an interactive session\n\
3364
excepthook -- called to handle any uncaught exception other than SystemExit\n\
3365
  To customize printing in an interactive session or to install a custom\n\
3366
  top-level exception handler, assign other functions to replace these.\n\
3367
\n\
3368
stdin -- standard input file object; used by input()\n\
3369
stdout -- standard output file object; used by print()\n\
3370
stderr -- standard error object; used for error messages\n\
3371
  By assigning other file objects (or objects that behave like files)\n\
3372
  to these, it is possible to redirect all of the interpreter's I/O.\n\
3373
\n\
3374
last_exc - the last uncaught exception\n\
3375
  Only available in an interactive session after a\n\
3376
  traceback has been printed.\n\
3377
last_type -- type of last uncaught exception\n\
3378
last_value -- value of last uncaught exception\n\
3379
last_traceback -- traceback of last uncaught exception\n\
3380
  These three are the (deprecated) legacy representation of last_exc.\n\
3381
"
3382
)
3383
/* concatenating string here */
3384
PyDoc_STR(
3385
"\n\
3386
Static objects:\n\
3387
\n\
3388
abi_info -- Python ABI information.\n\
3389
builtin_module_names -- tuple of module names built into this interpreter\n\
3390
copyright -- copyright notice pertaining to this interpreter\n\
3391
exec_prefix -- prefix used to find the machine-specific Python library\n\
3392
executable -- absolute path of the executable binary of the Python interpreter\n\
3393
float_info -- a named tuple with information about the float implementation.\n\
3394
float_repr_style -- string indicating the style of repr() output for floats\n\
3395
hash_info -- a named tuple with information about the hash algorithm.\n\
3396
hexversion -- version information encoded as a single integer\n\
3397
implementation -- Python implementation information.\n\
3398
int_info -- a named tuple with information about the int implementation.\n\
3399
maxsize -- the largest supported length of containers.\n\
3400
maxunicode -- the value of the largest Unicode code point\n\
3401
platform -- platform identifier\n\
3402
prefix -- prefix used to find the Python library\n\
3403
thread_info -- a named tuple with information about the thread implementation.\n\
3404
version -- the version of this interpreter as a string\n\
3405
version_info -- version information as a named tuple\n\
3406
"
3407
)
3408
#ifdef MS_COREDLL
3409
/* concatenating string here */
3410
PyDoc_STR(
3411
"dllhandle -- [Windows only] integer handle of the Python DLL\n\
3412
winver -- [Windows only] version number of the Python DLL\n\
3413
"
3414
)
3415
#endif /* MS_COREDLL */
3416
PyDoc_STR(
3417
"__stdin__ -- the original stdin; don't touch!\n\
3418
__stdout__ -- the original stdout; don't touch!\n\
3419
__stderr__ -- the original stderr; don't touch!\n\
3420
__displayhook__ -- the original displayhook; don't touch!\n\
3421
__excepthook__ -- the original excepthook; don't touch!\n\
3422
\n\
3423
Functions:\n\
3424
\n\
3425
displayhook() -- print an object to the screen, and save it in builtins._\n\
3426
excepthook() -- print an exception and its traceback to sys.stderr\n\
3427
exception() -- return the current thread's active exception\n\
3428
exc_info() -- return information about the current thread's active exception\n\
3429
exit() -- exit the interpreter by raising SystemExit\n\
3430
getdlopenflags() -- returns flags to be used for dlopen() calls\n\
3431
getprofile() -- get the global profiling function\n\
3432
getrefcount() -- return the reference count for an object (plus one :-)\n\
3433
getrecursionlimit() -- return the max recursion depth for the interpreter\n\
3434
getsizeof() -- return the size of an object in bytes\n\
3435
gettrace() -- get the global debug tracing function\n\
3436
setdlopenflags() -- set the flags to be used for dlopen() calls\n\
3437
setprofile() -- set the global profiling function\n\
3438
setrecursionlimit() -- set the max recursion depth for the interpreter\n\
3439
settrace() -- set the global debug tracing function\n\
3440
"
3441
)
3442
/* end of sys_doc */ ;
3443
3444
3445
PyDoc_STRVAR(flags__doc__,
3446
"sys.flags\n\
3447
\n\
3448
Flags provided through command line arguments or environment vars.");
3449
3450
static PyTypeObject FlagsType;
3451
3452
static PyStructSequence_Field flags_fields[] = {
3453
    {"debug",                   "-d"},
3454
    {"inspect",                 "-i"},
3455
    {"interactive",             "-i"},
3456
    {"optimize",                "-O or -OO"},
3457
    {"dont_write_bytecode",     "-B"},
3458
    {"no_user_site",            "-s"},
3459
    {"no_site",                 "-S"},
3460
    {"ignore_environment",      "-E"},
3461
    {"verbose",                 "-v"},
3462
    {"bytes_warning",           "-b"},
3463
    {"quiet",                   "-q"},
3464
    {"hash_randomization",      "-R"},
3465
    {"isolated",                "-I"},
3466
    {"dev_mode",                "-X dev"},
3467
    {"utf8_mode",               "-X utf8"},
3468
    {"warn_default_encoding",   "-X warn_default_encoding"},
3469
    {"safe_path",               "-P"},
3470
    {"int_max_str_digits",      "-X int_max_str_digits"},
3471
    // Fields below are only usable by sys.flags attribute name, not index:
3472
    {"gil",                     "-X gil"},
3473
    {"thread_inherit_context",  "-X thread_inherit_context"},
3474
    {"context_aware_warnings",  "-X context_aware_warnings"},
3475
    {"lazy_imports",            "-X lazy_imports"},
3476
    {0}
3477
};
3478
3479
0
#define SYS_FLAGS_INT_MAX_STR_DIGITS 17
3480
3481
static PyStructSequence_Desc flags_desc = {
3482
    "sys.flags",        /* name */
3483
    flags__doc__,       /* doc */
3484
    flags_fields,       /* fields */
3485
    18  /* NB - do not increase beyond 3.13's value of 18. */
3486
    // New sys.flags fields should NOT be tuple addressable per
3487
    // https://github.com/python/cpython/issues/122575#issuecomment-2416497086
3488
};
3489
3490
static void
3491
sys_set_flag(PyObject *flags, Py_ssize_t pos, PyObject *value)
3492
1.62k
{
3493
1.62k
    assert(pos >= 0 && pos < (Py_ssize_t)(Py_ARRAY_LENGTH(flags_fields) - 1));
3494
3495
1.62k
    PyObject *old_value = PyStructSequence_GET_ITEM(flags, pos);
3496
1.62k
    PyStructSequence_SET_ITEM(flags, pos, Py_NewRef(value));
3497
1.62k
    Py_XDECREF(old_value);
3498
1.62k
}
3499
3500
3501
int
3502
_PySys_SetFlagObj(Py_ssize_t pos, PyObject *value)
3503
0
{
3504
0
    PyObject *new_flags = NULL;
3505
0
    PyObject *flags_str = &_Py_ID(flags);  // immortal ref
3506
3507
0
    PyObject *old_flags = PySys_GetAttr(flags_str);
3508
0
    if (old_flags == NULL) {
3509
0
        goto error;
3510
0
    }
3511
3512
0
    new_flags = PyStructSequence_New(&FlagsType);
3513
0
    if (new_flags == NULL) {
3514
0
        goto error;
3515
0
    }
3516
3517
0
    for (Py_ssize_t i = 0; i < (Py_ssize_t)(Py_ARRAY_LENGTH(flags_fields) - 1); i++) {
3518
0
        if (i != pos) {
3519
0
            PyObject *old_value;
3520
0
            old_value = PyStructSequence_GET_ITEM(old_flags, i);  // borrowed ref
3521
0
            sys_set_flag(new_flags, i, old_value);
3522
0
        }
3523
0
        else {
3524
0
            sys_set_flag(new_flags, pos, value);
3525
0
        }
3526
0
    }
3527
3528
0
    int res = _PySys_SetAttr(flags_str, new_flags);
3529
0
    Py_DECREF(old_flags);
3530
0
    Py_DECREF(new_flags);
3531
0
    return res;
3532
3533
0
error:
3534
0
    Py_XDECREF(old_flags);
3535
0
    Py_XDECREF(new_flags);
3536
0
    return -1;
3537
0
}
3538
3539
3540
static int
3541
_PySys_SetFlagInt(Py_ssize_t pos, int value)
3542
0
{
3543
0
    PyObject *obj = PyLong_FromLong(value);
3544
0
    if (obj == NULL) {
3545
0
        return -1;
3546
0
    }
3547
3548
0
    int res = _PySys_SetFlagObj(pos, obj);
3549
0
    Py_DECREF(obj);
3550
0
    return res;
3551
0
}
3552
3553
3554
static int
3555
set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
3556
74
{
3557
74
    const PyPreConfig *preconfig = &interp->runtime->preconfig;
3558
74
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
3559
3560
74
    Py_ssize_t pos = 0;
3561
74
#define SetFlagObj(expr) \
3562
1.62k
    do { \
3563
1.62k
        PyObject *value = (expr); \
3564
1.62k
        if (value == NULL) { \
3565
0
            return -1; \
3566
0
        } \
3567
1.62k
        sys_set_flag(flags, pos, value); \
3568
1.62k
        Py_DECREF(value); \
3569
1.62k
        pos++; \
3570
1.62k
    } while (0)
3571
1.40k
#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
3572
3573
74
    SetFlag(config->parser_debug);
3574
74
    SetFlag(config->inspect);
3575
74
    SetFlag(config->interactive);
3576
74
    SetFlag(config->optimization_level);
3577
74
    SetFlag(!config->write_bytecode);
3578
74
    SetFlag(!config->user_site_directory);
3579
74
    SetFlag(!config->site_import);
3580
74
    SetFlag(!config->use_environment);
3581
74
    SetFlag(config->verbose);
3582
74
    SetFlag(config->bytes_warning);
3583
74
    SetFlag(config->quiet);
3584
74
    SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
3585
74
    SetFlag(config->isolated);
3586
74
    SetFlagObj(PyBool_FromLong(config->dev_mode));
3587
74
    SetFlag(preconfig->utf8_mode);
3588
74
    SetFlag(config->warn_default_encoding);
3589
74
    SetFlagObj(PyBool_FromLong(config->safe_path));
3590
74
    SetFlag(config->int_max_str_digits);
3591
#ifdef Py_GIL_DISABLED
3592
    if (config->enable_gil == _PyConfig_GIL_DEFAULT) {
3593
        SetFlagObj(Py_NewRef(Py_None));
3594
    }
3595
    else {
3596
        SetFlag(config->enable_gil);
3597
    }
3598
#else
3599
74
    SetFlagObj(PyLong_FromLong(1));
3600
74
#endif
3601
74
    SetFlag(config->thread_inherit_context);
3602
74
    SetFlag(config->context_aware_warnings);
3603
74
    SetFlag(config->lazy_imports);
3604
74
#undef SetFlagObj
3605
74
#undef SetFlag
3606
74
    return 0;
3607
74
}
3608
3609
3610
static PyObject*
3611
make_flags(PyInterpreterState *interp)
3612
37
{
3613
37
    PyObject *flags = PyStructSequence_New(&FlagsType);
3614
37
    if (flags == NULL) {
3615
0
        return NULL;
3616
0
    }
3617
3618
37
    if (set_flags_from_config(interp, flags) < 0) {
3619
0
        Py_DECREF(flags);
3620
0
        return NULL;
3621
0
    }
3622
37
    return flags;
3623
37
}
3624
3625
3626
PyDoc_STRVAR(version_info__doc__,
3627
"sys.version_info\n\
3628
\n\
3629
Version information as a named tuple.");
3630
3631
static PyTypeObject VersionInfoType;
3632
3633
static PyStructSequence_Field version_info_fields[] = {
3634
    {"major", "Major release number"},
3635
    {"minor", "Minor release number"},
3636
    {"micro", "Patch release number"},
3637
    {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
3638
    {"serial", "Serial release number"},
3639
    {0}
3640
};
3641
3642
static PyStructSequence_Desc version_info_desc = {
3643
    "sys.version_info",     /* name */
3644
    version_info__doc__,    /* doc */
3645
    version_info_fields,    /* fields */
3646
    5
3647
};
3648
3649
static PyObject *
3650
make_version_info(PyThreadState *tstate)
3651
37
{
3652
37
    PyObject *version_info;
3653
37
    char *s;
3654
37
    int pos = 0;
3655
3656
37
    version_info = PyStructSequence_New(&VersionInfoType);
3657
37
    if (version_info == NULL) {
3658
0
        return NULL;
3659
0
    }
3660
3661
    /*
3662
     * These release level checks are mutually exclusive and cover
3663
     * the field, so don't get too fancy with the pre-processor!
3664
     */
3665
37
#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
3666
37
    s = "alpha";
3667
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
3668
    s = "beta";
3669
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
3670
    s = "candidate";
3671
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
3672
    s = "final";
3673
#endif
3674
3675
37
#define SetIntItem(flag) \
3676
148
    PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
3677
37
#define SetStrItem(flag) \
3678
37
    PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
3679
3680
37
    SetIntItem(PY_MAJOR_VERSION);
3681
37
    SetIntItem(PY_MINOR_VERSION);
3682
37
    SetIntItem(PY_MICRO_VERSION);
3683
37
    SetStrItem(s);
3684
37
    SetIntItem(PY_RELEASE_SERIAL);
3685
37
#undef SetIntItem
3686
37
#undef SetStrItem
3687
3688
37
    if (_PyErr_Occurred(tstate)) {
3689
0
        Py_CLEAR(version_info);
3690
0
        return NULL;
3691
0
    }
3692
37
    return version_info;
3693
37
}
3694
3695
/* sys.implementation values */
3696
#ifndef _PY_IMPL_NAME
3697
#define _PY_IMPL_NAME "cpython"
3698
#endif
3699
const char *_PySys_ImplName = _PY_IMPL_NAME;
3700
#ifndef _PY_IMPL_CACHE_TAG
3701
#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
3702
#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
3703
#define _PY_IMPL_CACHE_TAG _PY_IMPL_NAME "-" MAJOR MINOR
3704
#endif
3705
const char *_PySys_ImplCacheTag = _PY_IMPL_CACHE_TAG;
3706
#ifdef MAJOR
3707
#undef MAJOR
3708
#endif
3709
#ifdef MINOR
3710
#undef MINOR
3711
#endif
3712
3713
static PyObject *
3714
make_impl_info(PyObject *version_info)
3715
37
{
3716
37
    int res;
3717
37
    PyObject *impl_info, *value, *ns;
3718
3719
37
    impl_info = PyDict_New();
3720
37
    if (impl_info == NULL)
3721
0
        return NULL;
3722
3723
    /* populate the dict */
3724
3725
37
    value = PyUnicode_FromString(_PySys_ImplName);
3726
37
    if (value == NULL)
3727
0
        goto error;
3728
37
    res = PyDict_SetItemString(impl_info, "name", value);
3729
37
    Py_DECREF(value);
3730
37
    if (res < 0)
3731
0
        goto error;
3732
3733
37
    value = _PySys_ImplCacheTag
3734
37
        ? PyUnicode_FromString(_PySys_ImplCacheTag)
3735
37
        : Py_NewRef(Py_None);
3736
37
    if (value == NULL) {
3737
0
        goto error;
3738
0
    }
3739
37
    res = PyDict_SetItemString(impl_info, "cache_tag", value);
3740
37
    Py_DECREF(value);
3741
37
    if (res < 0)
3742
0
        goto error;
3743
3744
37
    res = PyDict_SetItemString(impl_info, "version", version_info);
3745
37
    if (res < 0)
3746
0
        goto error;
3747
3748
37
    value = PyLong_FromLong(PY_VERSION_HEX);
3749
37
    if (value == NULL)
3750
0
        goto error;
3751
37
    res = PyDict_SetItemString(impl_info, "hexversion", value);
3752
37
    Py_DECREF(value);
3753
37
    if (res < 0)
3754
0
        goto error;
3755
3756
37
#ifdef MULTIARCH
3757
37
    value = PyUnicode_FromString(MULTIARCH);
3758
37
    if (value == NULL)
3759
0
        goto error;
3760
37
    res = PyDict_SetItemString(impl_info, "_multiarch", value);
3761
37
    Py_DECREF(value);
3762
37
    if (res < 0)
3763
0
        goto error;
3764
37
#endif
3765
3766
    // PEP-734
3767
#if defined(__wasi__) || defined(__EMSCRIPTEN__)
3768
    // It is not enabled on WASM builds just yet
3769
    value = Py_False;
3770
#else
3771
37
    value = Py_True;
3772
37
#endif
3773
37
    res = PyDict_SetItemString(impl_info, "supports_isolated_interpreters", value);
3774
37
    if (res < 0) {
3775
0
        goto error;
3776
0
    }
3777
3778
    /* dict ready */
3779
3780
37
    ns = _PyNamespace_New(impl_info);
3781
37
    Py_DECREF(impl_info);
3782
37
    return ns;
3783
3784
0
error:
3785
0
    Py_CLEAR(impl_info);
3786
0
    return NULL;
3787
37
}
3788
3789
3790
static PyObject *
3791
make_abi_info(void)
3792
37
{
3793
    // New entries should be added when needed for a supported platform,
3794
    // or by core dev consensus for enabling an unsupported one.
3795
3796
37
    PyObject *value;
3797
37
    PyObject *abi_info = PyDict_New();
3798
37
    if (abi_info == NULL) {
3799
0
        return NULL;
3800
0
    }
3801
3802
37
    value = PyLong_FromLong(sizeof(void *) * 8);
3803
37
    if (value == NULL) {
3804
0
        goto error;
3805
0
    }
3806
37
    if (PyDict_SetItem(abi_info, &_Py_ID(pointer_bits), value) < 0) {
3807
0
        goto error;
3808
0
    }
3809
37
    Py_DECREF(value);
3810
3811
#ifdef Py_GIL_DISABLED
3812
    value = Py_True;
3813
#else
3814
37
    value = Py_False;
3815
37
#endif
3816
37
    if (PyDict_SetItem(abi_info, &_Py_ID(free_threaded), value) < 0) {
3817
0
        goto error;
3818
0
    }
3819
3820
#ifdef Py_DEBUG
3821
    value = Py_True;
3822
#else
3823
37
    value = Py_False;
3824
37
#endif
3825
37
    if (PyDict_SetItem(abi_info, &_Py_ID(debug), value) < 0) {
3826
0
        goto error;
3827
0
    }
3828
3829
#if PY_BIG_ENDIAN
3830
    value = &_Py_ID(big);
3831
#else
3832
37
    value = &_Py_ID(little);
3833
37
#endif
3834
37
    if (PyDict_SetItem(abi_info, &_Py_ID(byteorder), value) < 0) {
3835
0
        goto error;
3836
0
    }
3837
3838
37
    PyObject *ns = _PyNamespace_New(abi_info);
3839
37
    Py_DECREF(abi_info);
3840
37
    return ns;
3841
3842
0
error:
3843
0
    Py_DECREF(abi_info);
3844
0
    Py_XDECREF(value);
3845
0
    return NULL;
3846
37
}
3847
3848
3849
#ifdef __wasi__
3850
3851
static PyObject *
3852
make_wasi_info(void)
3853
{
3854
#if defined(__wasip1__)
3855
    const char *wasi_version = "p1";
3856
#elif defined(__wasip2__)
3857
    const char *wasi_version = "p2";
3858
#elif defined(__wasip3__)
3859
    const char *wasi_version = "p3";
3860
#else
3861
#  error "Unknown WASI target version"
3862
#endif
3863
3864
    // The SDK version is only defined for SDK builds of wasi-libc.
3865
#ifdef __wasi_sdk_version__
3866
    const char *wasi_sdk_version = __wasi_sdk_version__;
3867
#else
3868
#  error "Unknown WASI SDK version"
3869
#endif
3870
3871
#ifdef __wasi_cooperative_threads__
3872
    PyObject *cooperative_threads = Py_True;
3873
#else
3874
    PyObject *cooperative_threads = Py_False;
3875
#endif
3876
3877
    PyObject *wasi_info = Py_BuildValue(
3878
        "{s:s,s:s,s:O}",
3879
        "wasi_version", wasi_version,
3880
        "wasi_sdk_version", wasi_sdk_version,
3881
        "cooperative_threads", cooperative_threads);
3882
    if (wasi_info == NULL) {
3883
        return NULL;
3884
    }
3885
    PyObject *ns = _PyNamespace_New(wasi_info);
3886
    Py_DECREF(wasi_info);
3887
    return ns;
3888
}
3889
3890
#endif // __wasi__
3891
3892
#ifdef __EMSCRIPTEN__
3893
3894
PyDoc_STRVAR(emscripten_info__doc__,
3895
"sys._emscripten_info\n\
3896
\n\
3897
WebAssembly Emscripten platform information.");
3898
3899
static PyTypeObject *EmscriptenInfoType;
3900
3901
static PyStructSequence_Field emscripten_info_fields[] = {
3902
    {"emscripten_version", "Emscripten version (major, minor, micro)"},
3903
    {"runtime", "Runtime (Node.JS version, browser user agent)"},
3904
    {"pthreads", "pthread support"},
3905
    {"shared_memory", "shared memory support"},
3906
    {0}
3907
};
3908
3909
static PyStructSequence_Desc emscripten_info_desc = {
3910
    "sys._emscripten_info",     /* name */
3911
    emscripten_info__doc__ ,    /* doc */
3912
    emscripten_info_fields,     /* fields */
3913
    4
3914
};
3915
3916
EM_JS_DEPS(_Py_emscripten_runtime, "$stringToNewUTF8")
3917
3918
EM_JS(char *, _Py_emscripten_runtime, (void), {
3919
    var info;
3920
    if (typeof process === "object") {
3921
        if (process.versions?.bun) {
3922
            info = `bun v${process.versions.bun}`;
3923
        } else if (process.versions?.deno) {
3924
            info = `deno v${process.versions.deno}`;
3925
        } else {
3926
            // As far as I can tell, every JavaScript runtime puts "node" in
3927
            // process.release.name. Pyodide once checked for
3928
            //
3929
            // process.release.name === "node"
3930
            //
3931
            // and this is apparently part of the reason other runtimes started
3932
            // lying about it. Similar to the situation with userAgent.
3933
            //
3934
            // But just in case some other JS runtime decides to tell us what it
3935
            // is, we'll pick it up.
3936
            const name = process.release?.name ?? "node";
3937
            info = `${name} ${process.version}`;
3938
        }
3939
        // Include v8 version if we know it
3940
        if (process.versions?.v8) {
3941
            info +=  ` (v8 ${process.versions.v8})`;
3942
        }
3943
    } else if (typeof navigator === "object") {
3944
        info = navigator.userAgent;
3945
    } else {
3946
        info = "UNKNOWN";
3947
    }
3948
#if __wasm64__
3949
    return BigInt(stringToNewUTF8(info));
3950
#else
3951
    return stringToNewUTF8(info);
3952
#endif
3953
});
3954
3955
static PyObject *
3956
make_emscripten_info(void)
3957
{
3958
    PyObject *emscripten_info = NULL;
3959
    PyObject *version = NULL;
3960
    char *ua;
3961
    int pos = 0;
3962
3963
    emscripten_info = PyStructSequence_New(EmscriptenInfoType);
3964
    if (emscripten_info == NULL) {
3965
        return NULL;
3966
    }
3967
3968
    version = Py_BuildValue("(iii)",
3969
        __EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__);
3970
    if (version == NULL) {
3971
        goto error;
3972
    }
3973
    PyStructSequence_SET_ITEM(emscripten_info, pos++, version);
3974
3975
    ua = _Py_emscripten_runtime();
3976
    if (ua != NULL) {
3977
        PyObject *oua = PyUnicode_DecodeUTF8(ua, strlen(ua), "strict");
3978
        free(ua);
3979
        if (oua == NULL) {
3980
            goto error;
3981
        }
3982
        PyStructSequence_SET_ITEM(emscripten_info, pos++, oua);
3983
    } else {
3984
        PyStructSequence_SET_ITEM(emscripten_info, pos++, Py_NewRef(Py_None));
3985
    }
3986
3987
#define SetBoolItem(flag) \
3988
    PyStructSequence_SET_ITEM(emscripten_info, pos++, PyBool_FromLong(flag))
3989
3990
#ifdef __EMSCRIPTEN_PTHREADS__
3991
    SetBoolItem(1);
3992
#else
3993
    SetBoolItem(0);
3994
#endif
3995
3996
#ifdef __EMSCRIPTEN_SHARED_MEMORY__
3997
    SetBoolItem(1);
3998
#else
3999
    SetBoolItem(0);
4000
#endif
4001
4002
#undef SetBoolItem
4003
4004
    if (PyErr_Occurred()) {
4005
        goto error;
4006
    }
4007
    return emscripten_info;
4008
4009
  error:
4010
    Py_CLEAR(emscripten_info);
4011
    return NULL;
4012
}
4013
4014
#endif // __EMSCRIPTEN__
4015
4016
static struct PyModuleDef sysmodule = {
4017
    PyModuleDef_HEAD_INIT,
4018
    "sys",
4019
    sys_doc,
4020
    -1, /* multiple "initialization" just copies the module dict. */
4021
    sys_methods,
4022
    NULL,
4023
    NULL,
4024
    NULL,
4025
    NULL
4026
};
4027
4028
/* Updating the sys namespace, returning NULL pointer on error */
4029
#define SET_SYS(key, value)                                \
4030
1.62k
    do {                                                   \
4031
1.62k
        PyObject *v = (value);                             \
4032
1.62k
        if (v == NULL) {                                   \
4033
0
            goto err_occurred;                             \
4034
0
        }                                                  \
4035
1.62k
        res = PyDict_SetItemString(sysdict, key, v);       \
4036
1.62k
        Py_DECREF(v);                                      \
4037
1.62k
        if (res < 0) {                                     \
4038
0
            goto err_occurred;                             \
4039
0
        }                                                  \
4040
1.62k
    } while (0)
4041
4042
#define SET_SYS_FROM_STRING(key, value) \
4043
185
        SET_SYS(key, PyUnicode_FromString(value))
4044
4045
static PyStatus
4046
_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
4047
37
{
4048
37
    PyObject *version_info;
4049
37
    int res;
4050
37
    PyInterpreterState *interp = tstate->interp;
4051
4052
    /* stdin/stdout/stderr are set in pylifecycle.c */
4053
4054
37
#define COPY_SYS_ATTR(tokey, fromkey) \
4055
148
        SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
4056
4057
37
    COPY_SYS_ATTR("__displayhook__", "displayhook");
4058
37
    COPY_SYS_ATTR("__excepthook__", "excepthook");
4059
37
    COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
4060
37
    COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
4061
4062
37
#undef COPY_SYS_ATTR
4063
4064
37
    SET_SYS_FROM_STRING("version", Py_GetVersion());
4065
37
    SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
4066
37
    SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
4067
37
                                  _Py_gitversion()));
4068
37
    SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
4069
37
    SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
4070
37
    SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
4071
37
    SET_SYS_FROM_STRING("platform", Py_GetPlatform());
4072
37
    SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
4073
37
    SET_SYS("float_info", PyFloat_GetInfo());
4074
37
    SET_SYS("int_info", PyLong_GetInfo());
4075
    /* initialize hash_info */
4076
37
    if (_PyStructSequence_InitBuiltin(interp, &Hash_InfoType,
4077
37
                                      &hash_info_desc) < 0)
4078
0
    {
4079
0
        goto type_init_failed;
4080
0
    }
4081
37
    SET_SYS("hash_info", get_hash_info(tstate));
4082
37
    SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
4083
37
    SET_SYS("builtin_module_names", list_builtin_module_names());
4084
37
    SET_SYS("stdlib_module_names", list_stdlib_module_names());
4085
#if PY_BIG_ENDIAN
4086
    SET_SYS("byteorder", &_Py_ID(big));
4087
#else
4088
37
    SET_SYS("byteorder", &_Py_ID(little));
4089
37
#endif
4090
4091
#ifdef MS_COREDLL
4092
    SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
4093
    SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
4094
#endif
4095
37
#ifdef ABIFLAGS
4096
37
    SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
4097
37
#endif
4098
4099
37
#define ENSURE_INFO_TYPE(TYPE, DESC) \
4100
74
    do { \
4101
74
        if (_PyStructSequence_InitBuiltinWithFlags( \
4102
74
                interp, &TYPE, &DESC, Py_TPFLAGS_DISALLOW_INSTANTIATION) < 0) { \
4103
0
            goto type_init_failed; \
4104
0
        } \
4105
74
    } while (0)
4106
4107
    /* version_info */
4108
37
    ENSURE_INFO_TYPE(VersionInfoType, version_info_desc);
4109
37
    version_info = make_version_info(tstate);
4110
37
    SET_SYS("version_info", version_info);
4111
4112
    /* implementation */
4113
37
    SET_SYS("implementation", make_impl_info(version_info));
4114
4115
    // sys.flags: updated later by _PySys_UpdateConfig()
4116
37
    ENSURE_INFO_TYPE(FlagsType, flags_desc);
4117
37
    SET_SYS("flags", make_flags(tstate->interp));
4118
4119
#if defined(MS_WINDOWS)
4120
    /* getwindowsversion */
4121
    ENSURE_INFO_TYPE(WindowsVersionType, windows_version_desc);
4122
4123
    SET_SYS_FROM_STRING("_vpath", VPATH);
4124
#endif
4125
4126
37
#undef ENSURE_INFO_TYPE
4127
4128
    /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
4129
37
#if _PY_SHORT_FLOAT_REPR == 1
4130
37
    SET_SYS("float_repr_style", &_Py_ID(short));
4131
#else
4132
    SET_SYS("float_repr_style", &_Py_ID(legacy));
4133
#endif
4134
4135
37
    SET_SYS("thread_info", PyThread_GetInfo());
4136
4137
37
    SET_SYS("abi_info", make_abi_info());
4138
4139
#ifdef __wasi__
4140
    SET_SYS("_wasi_info", make_wasi_info());
4141
#endif
4142
4143
    /* initialize asyncgen_hooks */
4144
37
    if (_PyStructSequence_InitBuiltin(interp, &AsyncGenHooksType,
4145
37
                                      &asyncgen_hooks_desc) < 0)
4146
0
    {
4147
0
        goto type_init_failed;
4148
0
    }
4149
4150
#ifdef __EMSCRIPTEN__
4151
    if (EmscriptenInfoType == NULL) {
4152
        EmscriptenInfoType = PyStructSequence_NewType(&emscripten_info_desc);
4153
        if (EmscriptenInfoType == NULL) {
4154
            goto type_init_failed;
4155
        }
4156
    }
4157
    SET_SYS("_emscripten_info", make_emscripten_info());
4158
#endif
4159
4160
    /* adding sys.path_hooks and sys.path_importer_cache */
4161
37
    SET_SYS("meta_path", PyList_New(0));
4162
37
    SET_SYS("path_importer_cache", PyDict_New());
4163
37
    SET_SYS("path_hooks", PyList_New(0));
4164
4165
37
    SET_SYS("_path0", Py_None);
4166
4167
37
    if (_PyErr_Occurred(tstate)) {
4168
0
        goto err_occurred;
4169
0
    }
4170
37
    return _PyStatus_OK();
4171
4172
0
type_init_failed:
4173
0
    return _PyStatus_ERR("failed to initialize a type");
4174
4175
0
err_occurred:
4176
0
    return _PyStatus_ERR("can't initialize sys module");
4177
37
}
4178
4179
4180
// Update sys attributes for a new PyConfig configuration.
4181
// This function also adds attributes that _PySys_InitCore() didn't add.
4182
int
4183
_PySys_UpdateConfig(PyThreadState *tstate)
4184
37
{
4185
37
    PyInterpreterState *interp = tstate->interp;
4186
37
    PyObject *sysdict = interp->sysdict;
4187
37
    const PyConfig *config = _PyInterpreterState_GetConfig(interp);
4188
37
    int res;
4189
4190
37
#define COPY_LIST(KEY, VALUE) \
4191
148
        SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
4192
4193
37
#define SET_SYS_FROM_WSTR(KEY, VALUE) \
4194
296
        SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
4195
4196
37
#define COPY_WSTR(SYS_ATTR, WSTR) \
4197
259
    if (WSTR != NULL) { \
4198
259
        SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
4199
259
    }
4200
4201
37
    if (config->module_search_paths_set) {
4202
37
        COPY_LIST("path", config->module_search_paths);
4203
37
    }
4204
4205
37
    COPY_WSTR("executable", config->executable);
4206
37
    COPY_WSTR("_base_executable", config->base_executable);
4207
37
    COPY_WSTR("prefix", config->prefix);
4208
37
    COPY_WSTR("base_prefix", config->base_prefix);
4209
37
    COPY_WSTR("exec_prefix", config->exec_prefix);
4210
37
    COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
4211
37
    COPY_WSTR("platlibdir", config->platlibdir);
4212
4213
37
    if (config->pycache_prefix != NULL) {
4214
0
        SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
4215
37
    } else {
4216
37
        if (PyDict_SetItemString(sysdict, "pycache_prefix", Py_None) < 0) {
4217
0
            return -1;
4218
0
        }
4219
37
    }
4220
4221
37
    COPY_LIST("argv", config->argv);
4222
37
    COPY_LIST("orig_argv", config->orig_argv);
4223
37
    COPY_LIST("warnoptions", config->warnoptions);
4224
4225
37
    SET_SYS("_xoptions", _PyConfig_CreateXOptionsDict(config));
4226
4227
37
    const wchar_t *stdlibdir = _Py_GetStdlibDir();
4228
37
    if (stdlibdir != NULL) {
4229
37
        SET_SYS_FROM_WSTR("_stdlib_dir", stdlibdir);
4230
37
    }
4231
0
    else {
4232
0
        if (PyDict_SetItemString(sysdict, "_stdlib_dir", Py_None) < 0) {
4233
0
            return -1;
4234
0
        }
4235
0
    }
4236
4237
37
#undef SET_SYS_FROM_WSTR
4238
37
#undef COPY_LIST
4239
37
#undef COPY_WSTR
4240
4241
    // replace sys.flags
4242
37
    PyObject *new_flags = PyStructSequence_New(&FlagsType);
4243
37
    if (new_flags == NULL) {
4244
0
        return -1;
4245
0
    }
4246
37
    if (set_flags_from_config(interp, new_flags) < 0) {
4247
0
        Py_DECREF(new_flags);
4248
0
        return -1;
4249
0
    }
4250
4251
37
    res = _PySys_SetAttr(&_Py_ID(flags), new_flags);
4252
37
    Py_DECREF(new_flags);
4253
37
    if (res < 0) {
4254
0
        return -1;
4255
0
    }
4256
4257
37
    SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
4258
4259
37
    if (_PyErr_Occurred(tstate)) {
4260
0
        goto err_occurred;
4261
0
    }
4262
4263
37
    return 0;
4264
4265
0
err_occurred:
4266
0
    return -1;
4267
37
}
4268
4269
#undef SET_SYS
4270
#undef SET_SYS_FROM_STRING
4271
4272
4273
/* Set up a preliminary stderr printer until we have enough
4274
   infrastructure for the io module in place.
4275
4276
   Use UTF-8/backslashreplace and ignore EAGAIN errors. */
4277
static PyStatus
4278
_PySys_SetPreliminaryStderr(PyObject *sysdict)
4279
37
{
4280
37
    PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
4281
37
    if (pstderr == NULL) {
4282
0
        goto error;
4283
0
    }
4284
37
    if (PyDict_SetItem(sysdict, &_Py_ID(stderr), pstderr) < 0) {
4285
0
        goto error;
4286
0
    }
4287
37
    if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
4288
0
        goto error;
4289
0
    }
4290
37
    Py_DECREF(pstderr);
4291
37
    return _PyStatus_OK();
4292
4293
0
error:
4294
0
    Py_XDECREF(pstderr);
4295
0
    return _PyStatus_ERR("can't set preliminary stderr");
4296
37
}
4297
4298
PyObject *_Py_CreateMonitoringObject(void);
4299
4300
/*[clinic input]
4301
module _jit
4302
[clinic start generated code]*/
4303
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=10952f74d7bbd972]*/
4304
4305
PyDoc_STRVAR(_jit_doc, "Utilities for observing just-in-time compilation.");
4306
4307
/*[clinic input]
4308
@permit_long_summary
4309
_jit.is_available -> bool
4310
Return True if the current Python executable supports JIT compilation, and False otherwise.
4311
[clinic start generated code]*/
4312
4313
static int
4314
_jit_is_available_impl(PyObject *module)
4315
/*[clinic end generated code: output=6849a9cd2ff4aac9 input=d009d751ae64c9ef]*/
4316
0
{
4317
0
    (void)module;
4318
#ifdef _Py_TIER2
4319
    return true;
4320
#else
4321
0
    return false;
4322
0
#endif
4323
0
}
4324
4325
/*[clinic input]
4326
@permit_long_summary
4327
_jit.is_enabled -> bool
4328
Return True if JIT compilation is enabled for the current Python process (implies sys._jit.is_available()), and False otherwise.
4329
[clinic start generated code]*/
4330
4331
static int
4332
_jit_is_enabled_impl(PyObject *module)
4333
/*[clinic end generated code: output=55865f8de993fe42 input=0524151e857f4f3a]*/
4334
0
{
4335
0
    (void)module;
4336
0
    return _PyInterpreterState_GET()->jit;
4337
0
}
4338
4339
/*[clinic input]
4340
@permit_long_summary
4341
_jit.is_active -> bool
4342
Return True if the topmost Python frame is currently executing JIT code (implies sys._jit.is_enabled()), and False otherwise.
4343
[clinic start generated code]*/
4344
4345
static int
4346
_jit_is_active_impl(PyObject *module)
4347
/*[clinic end generated code: output=7facca06b10064d4 input=081ee32563dc2086]*/
4348
0
{
4349
0
    (void)module;
4350
0
    return _PyThreadState_GET()->current_executor != NULL;
4351
0
}
4352
4353
static PyMethodDef _jit_methods[] = {
4354
    _JIT_IS_AVAILABLE_METHODDEF
4355
    _JIT_IS_ENABLED_METHODDEF
4356
    _JIT_IS_ACTIVE_METHODDEF
4357
    {NULL}
4358
};
4359
4360
static struct PyModuleDef _jit_module = {
4361
    PyModuleDef_HEAD_INIT,
4362
    .m_name = "sys._jit",
4363
    .m_doc = _jit_doc,
4364
    .m_size = -1,
4365
    .m_methods = _jit_methods,
4366
};
4367
4368
/* Create sys module without all attributes.
4369
   _PySys_UpdateConfig() should be called later to add remaining attributes. */
4370
PyStatus
4371
_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
4372
37
{
4373
37
    assert(!_PyErr_Occurred(tstate));
4374
4375
37
    PyInterpreterState *interp = tstate->interp;
4376
4377
37
    PyObject *modules = _PyImport_InitModules(interp);
4378
37
    if (modules == NULL) {
4379
0
        goto error;
4380
0
    }
4381
4382
37
    PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
4383
37
    if (sysmod == NULL) {
4384
0
        return _PyStatus_ERR("failed to create a module object");
4385
0
    }
4386
#ifdef Py_GIL_DISABLED
4387
    PyUnstable_Module_SetGIL(sysmod, Py_MOD_GIL_NOT_USED);
4388
#endif
4389
4390
37
    if (PyModule_AddIntMacro(sysmod, EXIT_SUCCESS) < 0) {
4391
0
        goto error;
4392
0
    }
4393
37
    if (PyModule_AddIntMacro(sysmod, EXIT_FAILURE) < 0) {
4394
0
        goto error;
4395
0
    }
4396
4397
37
    PyObject *sysdict = PyModule_GetDict(sysmod);
4398
37
    if (sysdict == NULL) {
4399
0
        goto error;
4400
0
    }
4401
37
    interp->sysdict = Py_NewRef(sysdict);
4402
4403
37
    interp->sysdict_copy = PyDict_Copy(sysdict);
4404
37
    if (interp->sysdict_copy == NULL) {
4405
0
        goto error;
4406
0
    }
4407
4408
37
    if (PyDict_SetItemString(sysdict, "modules", modules) < 0) {
4409
0
        goto error;
4410
0
    }
4411
4412
37
    PyObject *lazy_modules = _PyImport_InitLazyModules(interp); // borrowed reference
4413
37
    if (lazy_modules == NULL) {
4414
0
        goto error;
4415
0
    }
4416
4417
37
    if (PyDict_SetItemString(sysdict, "lazy_modules", lazy_modules) < 0) {
4418
0
        goto error;
4419
0
    }
4420
4421
37
    PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
4422
37
    if (_PyStatus_EXCEPTION(status)) {
4423
0
        return status;
4424
0
    }
4425
4426
37
    status = _PySys_InitCore(tstate, sysdict);
4427
37
    if (_PyStatus_EXCEPTION(status)) {
4428
0
        return status;
4429
0
    }
4430
4431
37
    if (_PyImport_FixupBuiltin(tstate, sysmod, "sys", modules) < 0) {
4432
0
        goto error;
4433
0
    }
4434
4435
37
    PyObject *monitoring = _Py_CreateMonitoringObject();
4436
37
    if (monitoring == NULL) {
4437
0
        goto error;
4438
0
    }
4439
37
    int err = PyDict_SetItemString(sysdict, "monitoring", monitoring);
4440
37
    Py_DECREF(monitoring);
4441
37
    if (err < 0) {
4442
0
        goto error;
4443
0
    }
4444
4445
37
    PyObject *_jit = _PyModule_CreateInitialized(&_jit_module, PYTHON_API_VERSION);
4446
37
    if (_jit == NULL) {
4447
0
        goto error;
4448
0
    }
4449
37
    err = PyDict_SetItemString(sysdict, "_jit", _jit);
4450
37
    Py_DECREF(_jit);
4451
37
    if (err) {
4452
0
        goto error;
4453
0
    }
4454
4455
37
    assert(!_PyErr_Occurred(tstate));
4456
4457
37
    *sysmod_p = sysmod;
4458
37
    return _PyStatus_OK();
4459
4460
0
error:
4461
0
    return _PyStatus_ERR("can't initialize sys module");
4462
37
}
4463
4464
4465
void
4466
_PySys_FiniTypes(PyInterpreterState *interp)
4467
0
{
4468
0
    _PyStructSequence_FiniBuiltin(interp, &VersionInfoType);
4469
0
    _PyStructSequence_FiniBuiltin(interp, &FlagsType);
4470
#if defined(MS_WINDOWS)
4471
    _PyStructSequence_FiniBuiltin(interp, &WindowsVersionType);
4472
#endif
4473
0
    _PyStructSequence_FiniBuiltin(interp, &Hash_InfoType);
4474
0
    _PyStructSequence_FiniBuiltin(interp, &AsyncGenHooksType);
4475
#ifdef __EMSCRIPTEN__
4476
    if (_Py_IsMainInterpreter(interp)) {
4477
        Py_CLEAR(EmscriptenInfoType);
4478
    }
4479
#endif
4480
0
}
4481
4482
4483
static PyObject *
4484
makepathobject(const wchar_t *path, wchar_t delim)
4485
0
{
4486
0
    int i, n;
4487
0
    const wchar_t *p;
4488
0
    PyObject *v, *w;
4489
4490
0
    n = 1;
4491
0
    p = path;
4492
0
    while ((p = wcschr(p, delim)) != NULL) {
4493
0
        n++;
4494
0
        p++;
4495
0
    }
4496
0
    v = PyList_New(n);
4497
0
    if (v == NULL)
4498
0
        return NULL;
4499
0
    for (i = 0; ; i++) {
4500
0
        p = wcschr(path, delim);
4501
0
        if (p == NULL)
4502
0
            p = path + wcslen(path); /* End of string */
4503
0
        w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
4504
0
        if (w == NULL) {
4505
0
            Py_DECREF(v);
4506
0
            return NULL;
4507
0
        }
4508
0
        PyList_SET_ITEM(v, i, w);
4509
0
        if (*p == '\0')
4510
0
            break;
4511
0
        path = p+1;
4512
0
    }
4513
0
    return v;
4514
0
}
4515
4516
// Removed in Python 3.13 API, but kept for the stable ABI
4517
PyAPI_FUNC(void)
4518
PySys_SetPath(const wchar_t *path)
4519
0
{
4520
0
    PyObject *v;
4521
0
    if ((v = makepathobject(path, DELIM)) == NULL)
4522
0
        Py_FatalError("can't create sys.path");
4523
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4524
0
    if (sys_set_object(interp, &_Py_ID(path), v) != 0) {
4525
0
        Py_FatalError("can't assign sys.path");
4526
0
    }
4527
0
    Py_DECREF(v);
4528
0
}
4529
4530
static PyObject *
4531
make_sys_argv(int argc, wchar_t * const * argv)
4532
0
{
4533
0
    PyObject *list = PyList_New(argc);
4534
0
    if (list == NULL) {
4535
0
        return NULL;
4536
0
    }
4537
4538
0
    for (Py_ssize_t i = 0; i < argc; i++) {
4539
0
        PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
4540
0
        if (v == NULL) {
4541
0
            Py_DECREF(list);
4542
0
            return NULL;
4543
0
        }
4544
0
        PyList_SET_ITEM(list, i, v);
4545
0
    }
4546
0
    return list;
4547
0
}
4548
4549
// Function removed from Python 3.16 limited C API, but kept in the stable ABI
4550
PyAPI_FUNC(void)
4551
PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
4552
0
{
4553
0
    wchar_t* empty_argv[1] = {L""};
4554
0
    PyThreadState *tstate = _PyThreadState_GET();
4555
4556
0
    if (argc < 1 || argv == NULL) {
4557
        /* Ensure at least one (empty) argument is seen */
4558
0
        argv = empty_argv;
4559
0
        argc = 1;
4560
0
    }
4561
4562
0
    PyObject *av = make_sys_argv(argc, argv);
4563
0
    if (av == NULL) {
4564
0
        Py_FatalError("no mem for sys.argv");
4565
0
    }
4566
0
    if (sys_set_object_str(tstate->interp, "argv", av) != 0) {
4567
0
        Py_DECREF(av);
4568
0
        Py_FatalError("can't assign sys.argv");
4569
0
    }
4570
0
    Py_DECREF(av);
4571
4572
0
    if (updatepath) {
4573
        /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
4574
           If argv[0] is a symlink, use the real path. */
4575
0
        const PyWideStringList argv_list = {.length = argc, .items = argv};
4576
0
        PyObject *path0 = NULL;
4577
0
        if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
4578
0
            if (path0 == NULL) {
4579
0
                Py_FatalError("can't compute path0 from argv");
4580
0
            }
4581
4582
0
            PyObject *sys_path;
4583
0
            if (PySys_GetOptionalAttr(&_Py_ID(path), &sys_path) < 0) {
4584
0
                Py_FatalError("can't get sys.path");
4585
0
            }
4586
0
            else if (sys_path != NULL) {
4587
0
                if (PyList_Insert(sys_path, 0, path0) < 0) {
4588
0
                    Py_FatalError("can't prepend path0 to sys.path");
4589
0
                }
4590
0
                Py_DECREF(sys_path);
4591
0
            }
4592
0
            Py_DECREF(path0);
4593
0
        }
4594
0
    }
4595
0
}
4596
4597
// Function removed from Python 3.16 limited C API, but kept in the stable ABI
4598
PyAPI_FUNC(void)
4599
PySys_SetArgv(int argc, wchar_t **argv)
4600
0
{
4601
0
    int isolated = 0;
4602
0
    PyThreadState *tstate = PyThreadState_GetUnchecked();
4603
0
    if (tstate != NULL) {
4604
0
        const PyConfig *config = &tstate->interp->config;
4605
0
        isolated = config->isolated;
4606
0
    }
4607
4608
0
    PySys_SetArgvEx(argc, argv, isolated == 0);
4609
0
}
4610
4611
/* Reimplementation of PyFile_WriteString() no calling indirectly
4612
   PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
4613
4614
static int
4615
sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
4616
0
{
4617
0
    if (file == NULL)
4618
0
        return -1;
4619
0
    assert(unicode != NULL);
4620
0
    PyObject *result = PyObject_CallMethodOneArg(file, &_Py_ID(write), unicode);
4621
0
    if (result == NULL) {
4622
0
        return -1;
4623
0
    }
4624
0
    Py_DECREF(result);
4625
0
    return 0;
4626
0
}
4627
4628
static int
4629
sys_pyfile_write(const char *text, PyObject *file)
4630
0
{
4631
0
    PyObject *unicode = NULL;
4632
0
    int err;
4633
4634
0
    if (file == NULL)
4635
0
        return -1;
4636
4637
0
    unicode = PyUnicode_FromString(text);
4638
0
    if (unicode == NULL)
4639
0
        return -1;
4640
4641
0
    err = sys_pyfile_write_unicode(unicode, file);
4642
0
    Py_DECREF(unicode);
4643
0
    return err;
4644
0
}
4645
4646
/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
4647
   Adapted from code submitted by Just van Rossum.
4648
4649
   PySys_WriteStdout(format, ...)
4650
   PySys_WriteStderr(format, ...)
4651
4652
      The first function writes to sys.stdout; the second to sys.stderr.  When
4653
      there is a problem, they write to the real (C level) stdout or stderr;
4654
      no exceptions are raised.
4655
4656
      PyErr_CheckSignals() is not called to avoid the execution of the Python
4657
      signal handlers: they may raise a new exception whereas sys_write()
4658
      ignores all exceptions.
4659
4660
      Both take a printf-style format string as their first argument followed
4661
      by a variable length argument list determined by the format string.
4662
4663
      *** WARNING ***
4664
4665
      The format should limit the total size of the formatted output string to
4666
      1000 bytes.  In particular, this means that no unrestricted "%s" formats
4667
      should occur; these should be limited using "%.<N>s where <N> is a
4668
      decimal number calculated so that <N> plus the maximum size of other
4669
      formatted text does not exceed 1000 bytes.  Also watch out for "%f",
4670
      which can print hundreds of digits for very large numbers.
4671
4672
 */
4673
4674
static void
4675
sys_write(PyObject *key, FILE *fp, const char *format, va_list va)
4676
0
{
4677
0
    PyObject *file;
4678
0
    char buffer[1001];
4679
0
    int written;
4680
0
    PyThreadState *tstate = _PyThreadState_GET();
4681
4682
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
4683
0
    written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
4684
0
    file = PySys_GetAttr(key);
4685
0
    if (sys_pyfile_write(buffer, file) != 0) {
4686
0
        _PyErr_Clear(tstate);
4687
0
        fputs(buffer, fp);
4688
0
    }
4689
0
    if (written < 0 || (size_t)written >= sizeof(buffer)) {
4690
0
        const char *truncated = "... truncated";
4691
0
        if (sys_pyfile_write(truncated, file) != 0)
4692
0
            fputs(truncated, fp);
4693
0
    }
4694
0
    Py_XDECREF(file);
4695
0
    _PyErr_SetRaisedException(tstate, exc);
4696
0
}
4697
4698
void
4699
PySys_WriteStdout(const char *format, ...)
4700
0
{
4701
0
    va_list va;
4702
4703
0
    va_start(va, format);
4704
0
    sys_write(&_Py_ID(stdout), stdout, format, va);
4705
0
    va_end(va);
4706
0
}
4707
4708
void
4709
PySys_WriteStderr(const char *format, ...)
4710
0
{
4711
0
    va_list va;
4712
4713
0
    va_start(va, format);
4714
0
    sys_write(&_Py_ID(stderr), stderr, format, va);
4715
0
    va_end(va);
4716
0
}
4717
4718
void
4719
_PySys_FormatV(PyObject *key, FILE *fp, const char *format, va_list va)
4720
0
{
4721
0
    PyObject *file, *message;
4722
0
    const char *utf8;
4723
0
    PyThreadState *tstate = _PyThreadState_GET();
4724
4725
0
    PyObject *exc = _PyErr_GetRaisedException(tstate);
4726
0
    message = PyUnicode_FromFormatV(format, va);
4727
0
    if (message != NULL) {
4728
0
        file = PySys_GetAttr(key);
4729
0
        if (sys_pyfile_write_unicode(message, file) != 0) {
4730
0
            _PyErr_Clear(tstate);
4731
0
            utf8 = PyUnicode_AsUTF8(message);
4732
0
            if (utf8 != NULL)
4733
0
                fputs(utf8, fp);
4734
0
        }
4735
0
        Py_XDECREF(file);
4736
0
        Py_DECREF(message);
4737
0
    }
4738
0
    _PyErr_SetRaisedException(tstate, exc);
4739
0
}
4740
4741
4742
void
4743
PySys_FormatStdout(const char *format, ...)
4744
0
{
4745
0
    va_list va;
4746
4747
0
    va_start(va, format);
4748
0
    _PySys_FormatV(&_Py_ID(stdout), stdout, format, va);
4749
0
    va_end(va);
4750
0
}
4751
4752
void
4753
PySys_FormatStderr(const char *format, ...)
4754
0
{
4755
0
    va_list va;
4756
4757
0
    va_start(va, format);
4758
0
    _PySys_FormatV(&_Py_ID(stderr), stderr, format, va);
4759
0
    va_end(va);
4760
0
}
4761
4762
4763
int
4764
_PySys_SetIntMaxStrDigits(int maxdigits)
4765
0
{
4766
0
    if (maxdigits != 0 && maxdigits < _PY_LONG_MAX_STR_DIGITS_THRESHOLD) {
4767
0
        PyErr_Format(
4768
0
            PyExc_ValueError, "maxdigits must be >= %d or 0 for unlimited",
4769
0
            _PY_LONG_MAX_STR_DIGITS_THRESHOLD);
4770
0
        return -1;
4771
0
    }
4772
4773
    // Set sys.flags.int_max_str_digits
4774
0
    const Py_ssize_t pos = SYS_FLAGS_INT_MAX_STR_DIGITS;
4775
0
    if (_PySys_SetFlagInt(pos, maxdigits) < 0) {
4776
0
        return -1;
4777
0
    }
4778
4779
    // Set PyInterpreterState.long_state.max_str_digits
4780
    // and PyInterpreterState.config.int_max_str_digits.
4781
0
    PyInterpreterState *interp = _PyInterpreterState_GET();
4782
0
    _Py_atomic_store_int(&interp->long_state.max_str_digits, maxdigits);
4783
0
    _Py_atomic_store_int(&interp->config.int_max_str_digits, maxdigits);
4784
0
    return 0;
4785
0
}