blob: a36d90f9de168295f84358cb94cb0d04fdcb939f [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020018#include "pycore_ceval.h" // _Py_RecursionLimitLowerWaterMark()
Victor Stinner384621c2020-06-22 17:27:35 +020019#include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
20#include "pycore_object.h" // _PyObject_IS_GC()
21#include "pycore_pathconfig.h" // _PyPathConfig_ComputeSysPath0()
22#include "pycore_pyerrors.h" // _PyErr_Fetch()
23#include "pycore_pylifecycle.h" // _PyErr_WriteUnraisableDefaultHook()
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020024#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
25#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner384621c2020-06-22 17:27:35 +020026#include "pycore_tuple.h" // _PyTuple_FromArray()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000027
Victor Stinner384621c2020-06-22 17:27:35 +020028#include "code.h"
29#include "frameobject.h" // PyFrame_GetBack()
Victor Stinner361dcdc2020-04-15 03:24:57 +020030#include "pydtrace.h"
31#include "osdefs.h" // DELIM
Victor Stinner9852cb32021-01-25 23:12:50 +010032#include "stdlib_module_names.h" // _Py_stdlib_module_names
Stefan Krah1845d142016-04-25 21:38:53 +020033#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Mark Hammond8696ebc2002-10-08 02:44:31 +000035#ifdef MS_WINDOWS
36#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000037#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000038#endif /* MS_WINDOWS */
39
Guido van Rossum9b38a141996-09-11 23:12:24 +000040#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000041extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000042/* A string loaded from the DLL at startup: */
43extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000044#endif
45
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080046/*[clinic input]
47module sys
48[clinic start generated code]*/
49/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
50
51#include "clinic/sysmodule.c.h"
52
Victor Stinnerbd303c12013-11-07 23:07:29 +010053_Py_IDENTIFIER(_);
54_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070055_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010056_Py_IDENTIFIER(buffer);
57_Py_IDENTIFIER(builtins);
58_Py_IDENTIFIER(encoding);
59_Py_IDENTIFIER(path);
60_Py_IDENTIFIER(stdout);
61_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070062_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010063_Py_IDENTIFIER(write);
64
Victor Stinner838f2642019-06-13 22:41:23 +020065static PyObject *
66sys_get_object_id(PyThreadState *tstate, _Py_Identifier *key)
Victor Stinnerd67bd452013-11-06 22:36:40 +010067{
Victor Stinner838f2642019-06-13 22:41:23 +020068 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020069 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010070 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020071 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +020072 PyObject *exc_type, *exc_value, *exc_tb;
73 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
74 PyObject *value = _PyDict_GetItemIdWithError(sd, key);
75 /* XXX Suppress a new exception if it was raised and restore
76 * the old one. */
77 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
78 return value;
Victor Stinnerd67bd452013-11-06 22:36:40 +010079}
80
81PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +020082_PySys_GetObjectId(_Py_Identifier *key)
83{
84 PyThreadState *tstate = _PyThreadState_GET();
85 return sys_get_object_id(tstate, key);
86}
87
Victor Stinneraf1d64d2020-11-04 17:34:34 +010088static PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +010089_PySys_GetObject(PyInterpreterState *interp, const char *name)
Victor Stinneraf1d64d2020-11-04 17:34:34 +010090{
Victor Stinnerbcb094b2021-02-19 15:10:45 +010091 PyObject *sysdict = interp->sysdict;
Victor Stinneraf1d64d2020-11-04 17:34:34 +010092 if (sysdict == NULL) {
93 return NULL;
94 }
95 return _PyDict_GetItemStringWithError(sysdict, name);
96}
97
Victor Stinner838f2642019-06-13 22:41:23 +020098PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000099PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Victor Stinner838f2642019-06-13 22:41:23 +0200101 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100102
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200103 PyObject *exc_type, *exc_value, *exc_tb;
104 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100105 PyObject *value = _PySys_GetObject(tstate->interp, name);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200106 /* XXX Suppress a new exception if it was raised and restore
107 * the old one. */
108 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
109 return value;
110}
111
112static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100113sys_set_object(PyInterpreterState *interp, PyObject *key, PyObject *v)
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200114{
115 if (key == NULL) {
116 return -1;
117 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100118 PyObject *sd = interp->sysdict;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200119 if (v == NULL) {
120 v = _PyDict_Pop(sd, key, Py_None);
121 if (v == NULL) {
122 return -1;
123 }
124 Py_DECREF(v);
125 return 0;
126 }
127 else {
128 return PyDict_SetItem(sd, key, v);
129 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Victor Stinner838f2642019-06-13 22:41:23 +0200132static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100133sys_set_object_id(PyInterpreterState *interp, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +0100134{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100135 return sys_set_object(interp, _PyUnicode_FromId(key), v);
Victor Stinnerd67bd452013-11-06 22:36:40 +0100136}
137
138int
Victor Stinner838f2642019-06-13 22:41:23 +0200139_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100141 PyInterpreterState *interp = _PyInterpreterState_GET();
142 return sys_set_object_id(interp, key, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200143}
144
145static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100146sys_set_object_str(PyInterpreterState *interp, const char *name, PyObject *v)
Victor Stinner838f2642019-06-13 22:41:23 +0200147{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200148 PyObject *key = v ? PyUnicode_InternFromString(name)
149 : PyUnicode_FromString(name);
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100150 int r = sys_set_object(interp, key, v);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200151 Py_XDECREF(key);
152 return r;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Victor Stinner838f2642019-06-13 22:41:23 +0200155int
156PySys_SetObject(const char *name, PyObject *v)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700157{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100158 PyInterpreterState *interp = _PyInterpreterState_GET();
159 return sys_set_object_str(interp, name, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200160}
161
Victor Stinner08faf002020-03-26 18:57:32 +0100162
Victor Stinner838f2642019-06-13 22:41:23 +0200163static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100164should_audit(PyInterpreterState *interp)
Victor Stinner838f2642019-06-13 22:41:23 +0200165{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100166 /* interp must not be NULL, but test it just in case for extra safety */
167 assert(interp != NULL);
168 if (!interp) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700169 return 0;
170 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100171 return (interp->runtime->audit_hook_head
172 || interp->audit_hooks
Victor Stinner08faf002020-03-26 18:57:32 +0100173 || PyDTrace_AUDIT_ENABLED());
Steve Dowerb82e17e2019-05-23 08:45:22 -0700174}
175
Steve Dowerb82e17e2019-05-23 08:45:22 -0700176
Victor Stinner08faf002020-03-26 18:57:32 +0100177static int
178sys_audit_tstate(PyThreadState *ts, const char *event,
179 const char *argFormat, va_list vargs)
180{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700181 /* N format is inappropriate, because you do not know
182 whether the reference is consumed by the call.
183 Assert rather than exception for perf reasons */
184 assert(!argFormat || !strchr(argFormat, 'N'));
185
Victor Stinner08faf002020-03-26 18:57:32 +0100186 if (!ts) {
187 /* Audit hooks cannot be called with a NULL thread state */
Steve Dowerb82e17e2019-05-23 08:45:22 -0700188 return 0;
189 }
190
Victor Stinner08faf002020-03-26 18:57:32 +0100191 /* The current implementation cannot be called if tstate is not
192 the current Python thread state. */
193 assert(ts == _PyThreadState_GET());
194
195 /* Early exit when no hooks are registered */
196 PyInterpreterState *is = ts->interp;
197 if (!should_audit(is)) {
198 return 0;
199 }
200
201 PyObject *eventName = NULL;
202 PyObject *eventArgs = NULL;
203 PyObject *hooks = NULL;
204 PyObject *hook = NULL;
205 int res = -1;
206
Steve Dowerb82e17e2019-05-23 08:45:22 -0700207 int dtrace = PyDTrace_AUDIT_ENABLED();
208
209 PyObject *exc_type, *exc_value, *exc_tb;
Victor Stinner08faf002020-03-26 18:57:32 +0100210 _PyErr_Fetch(ts, &exc_type, &exc_value, &exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700211
212 /* Initialize event args now */
213 if (argFormat && argFormat[0]) {
Victor Stinner08faf002020-03-26 18:57:32 +0100214 eventArgs = _Py_VaBuildValue_SizeT(argFormat, vargs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700215 if (eventArgs && !PyTuple_Check(eventArgs)) {
216 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
217 Py_DECREF(eventArgs);
218 eventArgs = argTuple;
219 }
Victor Stinner08faf002020-03-26 18:57:32 +0100220 }
221 else {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700222 eventArgs = PyTuple_New(0);
223 }
224 if (!eventArgs) {
225 goto exit;
226 }
227
228 /* Call global hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100229 _Py_AuditHookEntry *e = is->runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700230 for (; e; e = e->next) {
231 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
232 goto exit;
233 }
234 }
235
236 /* Dtrace USDT point */
237 if (dtrace) {
Andy Lestere6be9b52020-02-11 20:28:35 -0600238 PyDTrace_AUDIT(event, (void *)eventArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700239 }
240
241 /* Call interpreter hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100242 if (is->audit_hooks) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700243 eventName = PyUnicode_FromString(event);
244 if (!eventName) {
245 goto exit;
246 }
247
248 hooks = PyObject_GetIter(is->audit_hooks);
249 if (!hooks) {
250 goto exit;
251 }
252
253 /* Disallow tracing in hooks unless explicitly enabled */
254 ts->tracing++;
Mark Shannon9e7b2072021-04-13 11:08:14 +0100255 ts->cframe->use_tracing = 0;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700256 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300257 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700258 PyObject *o;
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300259 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 if (o) {
261 canTrace = PyObject_IsTrue(o);
262 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700263 }
264 if (canTrace < 0) {
265 break;
266 }
267 if (canTrace) {
Mark Shannon9e7b2072021-04-13 11:08:14 +0100268 ts->cframe->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700269 ts->tracing--;
270 }
Victor Stinner08faf002020-03-26 18:57:32 +0100271 PyObject* args[2] = {eventName, eventArgs};
272 o = _PyObject_FastCallTstate(ts, hook, args, 2);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700273 if (canTrace) {
274 ts->tracing++;
Mark Shannon9e7b2072021-04-13 11:08:14 +0100275 ts->cframe->use_tracing = 0;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700276 }
277 if (!o) {
278 break;
279 }
280 Py_DECREF(o);
281 Py_CLEAR(hook);
282 }
Mark Shannon9e7b2072021-04-13 11:08:14 +0100283 ts->cframe->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700284 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200285 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700286 goto exit;
287 }
288 }
289
290 res = 0;
291
292exit:
293 Py_XDECREF(hook);
294 Py_XDECREF(hooks);
295 Py_XDECREF(eventName);
296 Py_XDECREF(eventArgs);
297
Victor Stinner08faf002020-03-26 18:57:32 +0100298 if (!res) {
299 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
300 }
301 else {
302 assert(_PyErr_Occurred(ts));
303 Py_XDECREF(exc_type);
304 Py_XDECREF(exc_value);
305 Py_XDECREF(exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700306 }
307
308 return res;
309}
310
Victor Stinner08faf002020-03-26 18:57:32 +0100311int
312_PySys_Audit(PyThreadState *tstate, const char *event,
313 const char *argFormat, ...)
314{
315 va_list vargs;
316#ifdef HAVE_STDARG_PROTOTYPES
317 va_start(vargs, argFormat);
318#else
319 va_start(vargs);
320#endif
321 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
322 va_end(vargs);
323 return res;
324}
325
326int
327PySys_Audit(const char *event, const char *argFormat, ...)
328{
329 PyThreadState *tstate = _PyThreadState_GET();
330 va_list vargs;
331#ifdef HAVE_STDARG_PROTOTYPES
332 va_start(vargs, argFormat);
333#else
334 va_start(vargs);
335#endif
336 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
337 va_end(vargs);
338 return res;
339}
340
Steve Dowerb82e17e2019-05-23 08:45:22 -0700341/* We expose this function primarily for our own cleanup during
342 * finalization. In general, it should not need to be called,
Victor Stinner08faf002020-03-26 18:57:32 +0100343 * and as such the function is not exported.
344 *
345 * Must be finalizing to clear hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200346void
Victor Stinner08faf002020-03-26 18:57:32 +0100347_PySys_ClearAuditHooks(PyThreadState *ts)
Victor Stinner838f2642019-06-13 22:41:23 +0200348{
Victor Stinner08faf002020-03-26 18:57:32 +0100349 assert(ts != NULL);
350 if (!ts) {
351 return;
352 }
353
354 _PyRuntimeState *runtime = ts->interp->runtime;
Victor Stinner7b3c2522020-03-07 00:24:23 +0100355 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
Victor Stinner08faf002020-03-26 18:57:32 +0100356 assert(finalizing == ts);
357 if (finalizing != ts) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700358 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200359 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700360
Victor Stinnerda7933e2020-04-13 03:04:28 +0200361 const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
Victor Stinner838f2642019-06-13 22:41:23 +0200362 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700363 PySys_WriteStderr("# clear sys.audit hooks\n");
364 }
365
366 /* Hooks can abort later hooks for this event, but cannot
367 abort the clear operation itself. */
Victor Stinner08faf002020-03-26 18:57:32 +0100368 _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200369 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700370
Victor Stinner08faf002020-03-26 18:57:32 +0100371 _Py_AuditHookEntry *e = runtime->audit_hook_head, *n;
372 runtime->audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700373 while (e) {
374 n = e->next;
375 PyMem_RawFree(e);
376 e = n;
377 }
378}
379
380int
381PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
382{
Victor Stinner08faf002020-03-26 18:57:32 +0100383 /* tstate can be NULL, so access directly _PyRuntime:
384 PySys_AddAuditHook() can be called before Python is initialized. */
Victor Stinner838f2642019-06-13 22:41:23 +0200385 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner08faf002020-03-26 18:57:32 +0100386 PyThreadState *tstate;
387 if (runtime->initialized) {
388 tstate = _PyRuntimeState_GetThreadState(runtime);
389 }
390 else {
391 tstate = NULL;
392 }
Victor Stinner838f2642019-06-13 22:41:23 +0200393
Steve Dowerb82e17e2019-05-23 08:45:22 -0700394 /* Invoke existing audit hooks to allow them an opportunity to abort. */
395 /* Cannot invoke hooks until we are initialized */
Victor Stinner08faf002020-03-26 18:57:32 +0100396 if (tstate != NULL) {
397 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800398 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
399 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200400 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700401 return 0;
402 }
403 return -1;
404 }
405 }
406
Victor Stinner08faf002020-03-26 18:57:32 +0100407 _Py_AuditHookEntry *e = runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700408 if (!e) {
409 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner08faf002020-03-26 18:57:32 +0100410 runtime->audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700411 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200412 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700413 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200414 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700415 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
416 sizeof(_Py_AuditHookEntry));
417 }
418
419 if (!e) {
Victor Stinner08faf002020-03-26 18:57:32 +0100420 if (tstate != NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200421 _PyErr_NoMemory(tstate);
422 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700423 return -1;
424 }
425
426 e->next = NULL;
427 e->hookCFunction = (Py_AuditHookFunction)hook;
428 e->userData = userData;
429
430 return 0;
431}
432
433/*[clinic input]
434sys.addaudithook
435
436 hook: object
437
438Adds a new audit hook callback.
439[clinic start generated code]*/
440
441static PyObject *
442sys_addaudithook_impl(PyObject *module, PyObject *hook)
443/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
444{
Victor Stinner838f2642019-06-13 22:41:23 +0200445 PyThreadState *tstate = _PyThreadState_GET();
446
Steve Dowerb82e17e2019-05-23 08:45:22 -0700447 /* Invoke existing audit hooks to allow them an opportunity to abort. */
Victor Stinner08faf002020-03-26 18:57:32 +0100448 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200449 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700450 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200451 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700452 Py_RETURN_NONE;
453 }
454 return NULL;
455 }
456
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100457 PyInterpreterState *interp = tstate->interp;
458 if (interp->audit_hooks == NULL) {
459 interp->audit_hooks = PyList_New(0);
460 if (interp->audit_hooks == NULL) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700461 return NULL;
462 }
463 }
464
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100465 if (PyList_Append(interp->audit_hooks, hook) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700466 return NULL;
467 }
468
469 Py_RETURN_NONE;
470}
471
472PyDoc_STRVAR(audit_doc,
473"audit(event, *args)\n\
474\n\
475Passes the event to any audit hooks that are attached.");
476
477static PyObject *
478sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
479{
Victor Stinner838f2642019-06-13 22:41:23 +0200480 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200481 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner838f2642019-06-13 22:41:23 +0200482
Steve Dowerb82e17e2019-05-23 08:45:22 -0700483 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200484 _PyErr_SetString(tstate, PyExc_TypeError,
485 "audit() missing 1 required positional argument: "
486 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700487 return NULL;
488 }
489
Victor Stinner08faf002020-03-26 18:57:32 +0100490 if (!should_audit(tstate->interp)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700491 Py_RETURN_NONE;
492 }
493
494 PyObject *auditEvent = args[0];
495 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200496 _PyErr_SetString(tstate, PyExc_TypeError,
497 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700498 return NULL;
499 }
500 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200501 _PyErr_Format(tstate, PyExc_TypeError,
502 "expected str for argument 'event', not %.200s",
503 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700504 return NULL;
505 }
506 const char *event = PyUnicode_AsUTF8(auditEvent);
507 if (!event) {
508 return NULL;
509 }
510
511 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
512 if (!auditArgs) {
513 return NULL;
514 }
515
Victor Stinner08faf002020-03-26 18:57:32 +0100516 int res = _PySys_Audit(tstate, event, "O", auditArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700517 Py_DECREF(auditArgs);
518
519 if (res < 0) {
520 return NULL;
521 }
522
523 Py_RETURN_NONE;
524}
525
526
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400527static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200528sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400529{
Victor Stinner838f2642019-06-13 22:41:23 +0200530 PyThreadState *tstate = _PyThreadState_GET();
531 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300532 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400533
534 if (envar == NULL || strlen(envar) == 0) {
535 envar = "pdb.set_trace";
536 }
537 else if (!strcmp(envar, "0")) {
538 /* The breakpoint is explicitly no-op'd. */
539 Py_RETURN_NONE;
540 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300541 /* According to POSIX the string returned by getenv() might be invalidated
542 * or the string content might be overwritten by a subsequent call to
543 * getenv(). Since importing a module can performs the getenv() calls,
544 * we need to save a copy of envar. */
545 envar = _PyMem_RawStrdup(envar);
546 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200547 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300548 return NULL;
549 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200550 const char *last_dot = strrchr(envar, '.');
551 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400552 PyObject *modulepath = NULL;
553
554 if (last_dot == NULL) {
555 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
556 modulepath = PyUnicode_FromString("builtins");
557 attrname = envar;
558 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200559 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400560 /* Split on the last dot; */
561 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
562 attrname = last_dot + 1;
563 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200564 else {
565 goto warn;
566 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400567 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300568 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400569 return NULL;
570 }
571
Anthony Sottiledce345c2018-11-01 10:25:05 -0700572 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400573 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400574
575 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200576 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200577 goto warn;
578 }
579 PyMem_RawFree(envar);
580 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400581 }
582
583 PyObject *hook = PyObject_GetAttrString(module, attrname);
584 Py_DECREF(module);
585
586 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200587 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200588 goto warn;
589 }
590 PyMem_RawFree(envar);
591 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400592 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300593 PyMem_RawFree(envar);
Petr Viktorinffd97532020-02-11 17:46:57 +0100594 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400595 Py_DECREF(hook);
596 return retval;
597
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200598 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400599 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200600 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400601 int status = PyErr_WarnFormat(
602 PyExc_RuntimeWarning, 0,
603 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300604 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400605 if (status < 0) {
606 /* Printing the warning raised an exception. */
607 return NULL;
608 }
609 /* The warning was (probably) issued. */
610 Py_RETURN_NONE;
611}
612
613PyDoc_STRVAR(breakpointhook_doc,
614"breakpointhook(*args, **kws)\n"
615"\n"
616"This hook function is called by built-in breakpoint().\n"
617);
618
Victor Stinner13d49ee2010-12-04 17:24:33 +0000619/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
620 error handler. If sys.stdout has a buffer attribute, use
621 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
622 sys.stdout.write(redecoded).
623
624 Helper function for sys_displayhook(). */
625static int
Andy Lesterda4d6562020-03-05 22:34:36 -0600626sys_displayhook_unencodable(PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000627{
628 PyObject *stdout_encoding = NULL;
629 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200630 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000631 int ret;
632
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200633 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000634 if (stdout_encoding == NULL)
635 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200636 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000637 if (stdout_encoding_str == NULL)
638 goto error;
639
640 repr_str = PyObject_Repr(o);
641 if (repr_str == NULL)
642 goto error;
643 encoded = PyUnicode_AsEncodedString(repr_str,
644 stdout_encoding_str,
645 "backslashreplace");
646 Py_DECREF(repr_str);
647 if (encoded == NULL)
648 goto error;
649
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300650 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
651 Py_DECREF(encoded);
652 goto error;
653 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000654 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200655 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000656 Py_DECREF(buffer);
657 Py_DECREF(encoded);
658 if (result == NULL)
659 goto error;
660 Py_DECREF(result);
661 }
662 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000663 escaped_str = PyUnicode_FromEncodedObject(encoded,
664 stdout_encoding_str,
665 "strict");
666 Py_DECREF(encoded);
667 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
668 Py_DECREF(escaped_str);
669 goto error;
670 }
671 Py_DECREF(escaped_str);
672 }
673 ret = 0;
674 goto finally;
675
676error:
677 ret = -1;
678finally:
679 Py_XDECREF(stdout_encoding);
680 return ret;
681}
682
Tal Einatede0b6f2018-12-31 17:12:08 +0200683/*[clinic input]
684sys.displayhook
685
686 object as o: object
687 /
688
689Print an object to sys.stdout and also save it in builtins._
690[clinic start generated code]*/
691
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000692static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200693sys_displayhook(PyObject *module, PyObject *o)
694/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100697 PyObject *builtins;
698 static PyObject *newline = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200699 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000700
Eric Snow3f9eee62017-09-15 16:35:20 -0600701 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200703 if (!_PyErr_Occurred(tstate)) {
704 _PyErr_SetString(tstate, PyExc_RuntimeError,
705 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100706 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return NULL;
708 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600709 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Print value except if None */
712 /* After printing, also assign to '_' */
713 /* Before, set '_' to None to avoid recursion */
714 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200715 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200717 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200719 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200721 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return NULL;
723 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000724 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200725 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Andy Lesterda4d6562020-03-05 22:34:36 -0600726 int err;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000727 /* repr(o) is not encodable to sys.stdout.encoding with
728 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200729 _PyErr_Clear(tstate);
Andy Lesterda4d6562020-03-05 22:34:36 -0600730 err = sys_displayhook_unencodable(outf, o);
Victor Stinner838f2642019-06-13 22:41:23 +0200731 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000732 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200733 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000734 }
735 else {
736 return NULL;
737 }
738 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100739 if (newline == NULL) {
740 newline = PyUnicode_FromString("\n");
741 if (newline == NULL)
742 return NULL;
743 }
744 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200746 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200748 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000749}
750
Tal Einatede0b6f2018-12-31 17:12:08 +0200751
752/*[clinic input]
753sys.excepthook
754
755 exctype: object
756 value: object
757 traceback: object
758 /
759
760Handle an exception by displaying it with a traceback on sys.stderr.
761[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000762
763static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200764sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
765 PyObject *traceback)
766/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000767{
Tal Einatede0b6f2018-12-31 17:12:08 +0200768 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200769 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000770}
771
Tal Einatede0b6f2018-12-31 17:12:08 +0200772
773/*[clinic input]
774sys.exc_info
775
776Return current exception information: (type, value, traceback).
777
778Return information about the most recent exception caught by an except
779clause in the current stack frame or in an older stack frame.
780[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000781
782static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200783sys_exc_info_impl(PyObject *module)
784/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000785{
Victor Stinner50b48572018-11-01 01:51:40 +0100786 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return Py_BuildValue(
788 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100789 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
790 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
791 err_info->exc_traceback != NULL ?
792 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000793}
794
Tal Einatede0b6f2018-12-31 17:12:08 +0200795
796/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200797sys.unraisablehook
798
799 unraisable: object
800 /
801
802Handle an unraisable exception.
803
804The unraisable argument has the following attributes:
805
806* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200807* exc_value: Exception value, can be None.
808* exc_traceback: Exception traceback, can be None.
809* err_msg: Error message, can be None.
810* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200811[clinic start generated code]*/
812
813static PyObject *
814sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200815/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200816{
817 return _PyErr_WriteUnraisableDefaultHook(unraisable);
818}
819
820
821/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200822sys.exit
823
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300824 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200825 /
826
827Exit the interpreter by raising SystemExit(status).
828
829If the status is omitted or None, it defaults to zero (i.e., success).
830If the status is an integer, it will be used as the system exit status.
831If it is another kind of object, it will be printed and the system
832exit status will be one (i.e., failure).
833[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000834
835static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200836sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300837/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinneracde3f12021-02-19 15:07:59 +0100840 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000841 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000842}
843
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000844
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000845
Tal Einatede0b6f2018-12-31 17:12:08 +0200846/*[clinic input]
847sys.getdefaultencoding
848
849Return the current default encoding used by the Unicode implementation.
850[clinic start generated code]*/
851
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000852static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200853sys_getdefaultencoding_impl(PyObject *module)
854/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000857}
858
Tal Einatede0b6f2018-12-31 17:12:08 +0200859/*[clinic input]
860sys.getfilesystemencoding
861
862Return the encoding used to convert Unicode filenames to OS filenames.
863[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000864
865static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200866sys_getfilesystemencoding_impl(PyObject *module)
867/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000868{
Victor Stinner81a7be32020-04-14 15:14:01 +0200869 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200870 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400871 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000872}
873
Tal Einatede0b6f2018-12-31 17:12:08 +0200874/*[clinic input]
875sys.getfilesystemencodeerrors
876
877Return the error mode used Unicode to OS filename conversion.
878[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000879
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000880static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200881sys_getfilesystemencodeerrors_impl(PyObject *module)
882/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700883{
Victor Stinner81a7be32020-04-14 15:14:01 +0200884 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200885 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400886 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700887}
888
Tal Einatede0b6f2018-12-31 17:12:08 +0200889/*[clinic input]
890sys.intern
891
892 string as s: unicode
893 /
894
895``Intern'' the given string.
896
897This enters the string in the (global) table of interned strings whose
898purpose is to speed up dictionary lookups. Return the string itself or
899the previously interned string object with the same value.
900[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700901
902static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200903sys_intern_impl(PyObject *module, PyObject *s)
904/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (PyUnicode_CheckExact(s)) {
907 Py_INCREF(s);
908 PyUnicode_InternInPlace(&s);
909 return s;
910 }
911 else {
Victor Stinneracde3f12021-02-19 15:07:59 +0100912 PyErr_Format(PyExc_TypeError,
913 "can't intern %.400s", Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 return NULL;
915 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000916}
917
Georg Brandl66a796e2006-12-19 20:50:34 +0000918
Fred Drake5755ce62001-06-27 19:19:46 +0000919/*
920 * Cached interned string objects used for calling the profile and
921 * trace functions. Initialized by trace_init().
922 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000923static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000924
925static int
926trace_init(void)
927{
Nick Coghlan5a851672017-09-08 10:14:16 +1000928 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200929 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000930 "c_call", "c_exception", "c_return",
931 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200932 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 PyObject *name;
934 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000935 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (whatstrings[i] == NULL) {
937 name = PyUnicode_InternFromString(whatnames[i]);
938 if (name == NULL)
939 return -1;
940 whatstrings[i] = name;
941 }
942 }
943 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000944}
945
946
947static PyObject *
Victor Stinner309d7cc2020-03-13 16:39:12 +0100948call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000950{
Victor Stinner78da82b2016-08-20 01:22:57 +0200951 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200953 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100954
Victor Stinner838f2642019-06-13 22:41:23 +0200955 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200956 stack[0] = (PyObject *)frame;
957 stack[1] = whatstrings[what];
958 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 /* call the Python-level function */
Victor Stinner309d7cc2020-03-13 16:39:12 +0100961 PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000962
Victor Stinner78da82b2016-08-20 01:22:57 +0200963 PyFrame_LocalsToFast(frame, 1);
964 if (result == NULL) {
965 PyTraceBack_Here(frame);
966 }
967
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000969}
970
971static int
972profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000973 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000974{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100975 if (arg == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 arg = Py_None;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100977 }
978
979 PyThreadState *tstate = _PyThreadState_GET();
980 PyObject *result = call_trampoline(tstate, self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100982 _PyEval_SetProfile(tstate, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 return -1;
984 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 Py_DECREF(result);
987 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000988}
989
990static int
991trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000992 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000993{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 PyObject *callback;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100995 if (what == PyTrace_CALL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 callback = self;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100997 }
998 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 callback = frame->f_trace;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001000 }
1001 if (callback == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 return 0;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001003 }
1004
1005 PyThreadState *tstate = _PyThreadState_GET();
1006 PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001007 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01001008 _PyEval_SetTrace(tstate, NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001009 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return -1;
1011 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +03001014 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 }
1016 else {
1017 Py_DECREF(result);
1018 }
1019 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00001020}
Fred Draked0838392001-06-16 21:02:31 +00001021
Fred Drake8b4d01d2000-05-09 19:57:01 +00001022static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001023sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001024{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001025 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001027 }
1028
1029 PyThreadState *tstate = _PyThreadState_GET();
1030 if (args == Py_None) {
1031 if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
1032 return NULL;
1033 }
1034 }
1035 else {
1036 if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
1037 return NULL;
1038 }
1039 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001040 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001041}
1042
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001043PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001044"settrace(function)\n\
1045\n\
1046Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001047function call. See the debugger chapter in the library manual."
1048);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001049
Tal Einatede0b6f2018-12-31 17:12:08 +02001050/*[clinic input]
1051sys.gettrace
1052
1053Return the global debug tracing function set with sys.settrace.
1054
1055See the debugger chapter in the library manual.
1056[clinic start generated code]*/
1057
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001058static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001059sys_gettrace_impl(PyObject *module)
1060/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001061{
Victor Stinner50b48572018-11-01 01:51:40 +01001062 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 if (temp == NULL)
1066 temp = Py_None;
1067 Py_INCREF(temp);
1068 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001069}
1070
Christian Heimes9bd667a2008-01-20 15:14:11 +00001071static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001072sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001073{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001074 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001076 }
1077
1078 PyThreadState *tstate = _PyThreadState_GET();
1079 if (args == Py_None) {
1080 if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1081 return NULL;
1082 }
1083 }
1084 else {
1085 if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
1086 return NULL;
1087 }
1088 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001089 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001090}
1091
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001092PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001093"setprofile(function)\n\
1094\n\
1095Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001096and return. See the profiler chapter in the library manual."
1097);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001098
Tal Einatede0b6f2018-12-31 17:12:08 +02001099/*[clinic input]
1100sys.getprofile
1101
1102Return the profiling function set with sys.setprofile.
1103
1104See the profiler chapter in the library manual.
1105[clinic start generated code]*/
1106
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001107static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001108sys_getprofile_impl(PyObject *module)
1109/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001110{
Victor Stinner50b48572018-11-01 01:51:40 +01001111 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (temp == NULL)
1115 temp = Py_None;
1116 Py_INCREF(temp);
1117 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001118}
1119
Tim Peterse5e065b2003-07-06 18:36:54 +00001120
Tal Einatede0b6f2018-12-31 17:12:08 +02001121/*[clinic input]
1122sys.setswitchinterval
1123
1124 interval: double
1125 /
1126
1127Set the ideal thread switching delay inside the Python interpreter.
1128
1129The actual frequency of switching threads can be lower if the
1130interpreter executes long sequences of uninterruptible code
1131(this is implementation-specific and workload-dependent).
1132
1133The parameter must represent the desired switching delay in seconds
1134A typical value is 0.005 (5 milliseconds).
1135[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001136
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001137static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001138sys_setswitchinterval_impl(PyObject *module, double interval)
1139/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001140{
Tal Einatede0b6f2018-12-31 17:12:08 +02001141 if (interval <= 0.0) {
Victor Stinneracde3f12021-02-19 15:07:59 +01001142 PyErr_SetString(PyExc_ValueError,
1143 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return NULL;
1145 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001146 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001147 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001148}
1149
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001150
Tal Einatede0b6f2018-12-31 17:12:08 +02001151/*[clinic input]
1152sys.getswitchinterval -> double
1153
1154Return the current thread switch interval; see sys.setswitchinterval().
1155[clinic start generated code]*/
1156
1157static double
1158sys_getswitchinterval_impl(PyObject *module)
1159/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001160{
Tal Einatede0b6f2018-12-31 17:12:08 +02001161 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001162}
1163
Tal Einatede0b6f2018-12-31 17:12:08 +02001164/*[clinic input]
1165sys.setrecursionlimit
1166
1167 limit as new_limit: int
1168 /
1169
1170Set the maximum depth of the Python interpreter stack to n.
1171
1172This limit prevents infinite recursion from causing an overflow of the C
1173stack and crashing Python. The highest possible limit is platform-
1174dependent.
1175[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001176
Tim Peterse5e065b2003-07-06 18:36:54 +00001177static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001178sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1179/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001180{
Victor Stinner838f2642019-06-13 22:41:23 +02001181 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001182
Victor Stinner50856d52015-10-13 00:11:21 +02001183 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001184 _PyErr_SetString(tstate, PyExc_ValueError,
1185 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 return NULL;
1187 }
Victor Stinner50856d52015-10-13 00:11:21 +02001188
1189 /* Issue #25274: When the recursion depth hits the recursion limit in
1190 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1191 set to 1 and a RecursionError is raised. The overflowed flag is reset
1192 to 0 when the recursion depth goes below the low-water mark: see
1193 Py_LeaveRecursiveCall().
1194
1195 Reject too low new limit if the current recursion depth is higher than
1196 the new low-water mark. Otherwise it may not be possible anymore to
1197 reset the overflowed flag to 0. */
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001198 if (tstate->recursion_depth >= new_limit) {
Victor Stinner838f2642019-06-13 22:41:23 +02001199 _PyErr_Format(tstate, PyExc_RecursionError,
1200 "cannot set the recursion limit to %i at "
1201 "the recursion depth %i: the limit is too low",
1202 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001203 return NULL;
1204 }
1205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001207 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001208}
1209
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001210/*[clinic input]
1211sys.set_coroutine_origin_tracking_depth
1212
1213 depth: int
1214
1215Enable or disable origin tracking for coroutine objects in this thread.
1216
Tal Einatede0b6f2018-12-31 17:12:08 +02001217Coroutine objects will track 'depth' frames of traceback information
1218about where they came from, available in their cr_origin attribute.
1219
1220Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001221[clinic start generated code]*/
1222
1223static PyObject *
1224sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001225/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001226{
Victor Stinner838f2642019-06-13 22:41:23 +02001227 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001228 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001229 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001230 return NULL;
1231 }
Victor Stinner838f2642019-06-13 22:41:23 +02001232 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001233 Py_RETURN_NONE;
1234}
1235
1236/*[clinic input]
1237sys.get_coroutine_origin_tracking_depth -> int
1238
1239Check status of origin tracking for coroutine objects in this thread.
1240[clinic start generated code]*/
1241
1242static int
1243sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1244/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1245{
1246 return _PyEval_GetCoroutineOriginTrackingDepth();
1247}
1248
Yury Selivanoveb636452016-09-08 22:01:51 -07001249static PyTypeObject AsyncGenHooksType;
1250
1251PyDoc_STRVAR(asyncgen_hooks_doc,
1252"asyncgen_hooks\n\
1253\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001254A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001255generators hooks. The attributes are read only.");
1256
1257static PyStructSequence_Field asyncgen_hooks_fields[] = {
1258 {"firstiter", "Hook to intercept first iteration"},
1259 {"finalizer", "Hook to intercept finalization"},
1260 {0}
1261};
1262
1263static PyStructSequence_Desc asyncgen_hooks_desc = {
1264 "asyncgen_hooks", /* name */
1265 asyncgen_hooks_doc, /* doc */
1266 asyncgen_hooks_fields , /* fields */
1267 2
1268};
1269
Yury Selivanoveb636452016-09-08 22:01:51 -07001270static PyObject *
1271sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1272{
1273 static char *keywords[] = {"firstiter", "finalizer", NULL};
1274 PyObject *firstiter = NULL;
1275 PyObject *finalizer = NULL;
1276
1277 if (!PyArg_ParseTupleAndKeywords(
1278 args, kw, "|OO", keywords,
1279 &firstiter, &finalizer)) {
1280 return NULL;
1281 }
1282
1283 if (finalizer && finalizer != Py_None) {
1284 if (!PyCallable_Check(finalizer)) {
Victor Stinneracde3f12021-02-19 15:07:59 +01001285 PyErr_Format(PyExc_TypeError,
1286 "callable finalizer expected, got %.50s",
1287 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001288 return NULL;
1289 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001290 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1291 return NULL;
1292 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001293 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001294 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1295 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001296 }
1297
1298 if (firstiter && firstiter != Py_None) {
1299 if (!PyCallable_Check(firstiter)) {
Victor Stinneracde3f12021-02-19 15:07:59 +01001300 PyErr_Format(PyExc_TypeError,
1301 "callable firstiter expected, got %.50s",
1302 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001303 return NULL;
1304 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001305 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1306 return NULL;
1307 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001308 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001309 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1310 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001311 }
1312
1313 Py_RETURN_NONE;
1314}
1315
1316PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001317"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001318\n\
1319Set a finalizer for async generators objects."
1320);
1321
Tal Einatede0b6f2018-12-31 17:12:08 +02001322/*[clinic input]
1323sys.get_asyncgen_hooks
1324
1325Return the installed asynchronous generators hooks.
1326
1327This returns a namedtuple of the form (firstiter, finalizer).
1328[clinic start generated code]*/
1329
Yury Selivanoveb636452016-09-08 22:01:51 -07001330static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001331sys_get_asyncgen_hooks_impl(PyObject *module)
1332/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001333{
1334 PyObject *res;
1335 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1336 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1337
1338 res = PyStructSequence_New(&AsyncGenHooksType);
1339 if (res == NULL) {
1340 return NULL;
1341 }
1342
1343 if (firstiter == NULL) {
1344 firstiter = Py_None;
1345 }
1346
1347 if (finalizer == NULL) {
1348 finalizer = Py_None;
1349 }
1350
1351 Py_INCREF(firstiter);
1352 PyStructSequence_SET_ITEM(res, 0, firstiter);
1353
1354 Py_INCREF(finalizer);
1355 PyStructSequence_SET_ITEM(res, 1, finalizer);
1356
1357 return res;
1358}
1359
Yury Selivanoveb636452016-09-08 22:01:51 -07001360
Mark Dickinsondc787d22010-05-23 13:33:13 +00001361static PyTypeObject Hash_InfoType;
1362
1363PyDoc_STRVAR(hash_info_doc,
1364"hash_info\n\
1365\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001366A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001367hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001368
1369static PyStructSequence_Field hash_info_fields[] = {
1370 {"width", "width of the type used for hashing, in bits"},
1371 {"modulus", "prime number giving the modulus on which the hash "
1372 "function is based"},
1373 {"inf", "value to be used for hash of a positive infinity"},
1374 {"nan", "value to be used for hash of a nan"},
1375 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001376 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1377 "memoryviews"},
1378 {"hash_bits", "internal output size of hash algorithm"},
1379 {"seed_bits", "seed size of hash algorithm"},
1380 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001381 {NULL, NULL}
1382};
1383
1384static PyStructSequence_Desc hash_info_desc = {
1385 "sys.hash_info",
1386 hash_info_doc,
1387 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001388 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001389};
1390
Matthias Klosed885e952010-07-06 10:53:30 +00001391static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001392get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001393{
1394 PyObject *hash_info;
1395 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001396 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001397 hash_info = PyStructSequence_New(&Hash_InfoType);
1398 if (hash_info == NULL)
1399 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001400 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001401 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001402 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001403 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001404 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001405 PyStructSequence_SET_ITEM(hash_info, field++,
1406 PyLong_FromLong(_PyHASH_INF));
1407 PyStructSequence_SET_ITEM(hash_info, field++,
1408 PyLong_FromLong(_PyHASH_NAN));
1409 PyStructSequence_SET_ITEM(hash_info, field++,
1410 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001411 PyStructSequence_SET_ITEM(hash_info, field++,
1412 PyUnicode_FromString(hashfunc->name));
1413 PyStructSequence_SET_ITEM(hash_info, field++,
1414 PyLong_FromLong(hashfunc->hash_bits));
1415 PyStructSequence_SET_ITEM(hash_info, field++,
1416 PyLong_FromLong(hashfunc->seed_bits));
1417 PyStructSequence_SET_ITEM(hash_info, field++,
1418 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001419 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001420 Py_CLEAR(hash_info);
1421 return NULL;
1422 }
1423 return hash_info;
1424}
Tal Einatede0b6f2018-12-31 17:12:08 +02001425/*[clinic input]
1426sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001427
Tal Einatede0b6f2018-12-31 17:12:08 +02001428Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001429
Tal Einatede0b6f2018-12-31 17:12:08 +02001430The recursion limit is the maximum depth of the Python interpreter
1431stack. This limit prevents infinite recursion from causing an overflow
1432of the C stack and crashing Python.
1433[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001434
1435static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001436sys_getrecursionlimit_impl(PyObject *module)
1437/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001438{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001439 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001440}
1441
Mark Hammond8696ebc2002-10-08 02:44:31 +00001442#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001443
Eric Smithf7bb5782010-01-27 00:44:57 +00001444static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1445
1446static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 {"major", "Major version number"},
1448 {"minor", "Minor version number"},
1449 {"build", "Build number"},
1450 {"platform", "Operating system platform"},
1451 {"service_pack", "Latest Service Pack installed on the system"},
1452 {"service_pack_major", "Service Pack major version number"},
1453 {"service_pack_minor", "Service Pack minor version number"},
1454 {"suite_mask", "Bit mask identifying available product suites"},
1455 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001456 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001458};
1459
1460static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001461 "sys.getwindowsversion", /* name */
1462 sys_getwindowsversion__doc__, /* doc */
1463 windows_version_fields, /* fields */
1464 5 /* For backward compatibility,
1465 only the first 5 items are accessible
1466 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001467};
1468
Steve Dower3e96f322015-03-02 08:01:10 -08001469/* Disable deprecation warnings about GetVersionEx as the result is
1470 being passed straight through to the caller, who is responsible for
1471 using it correctly. */
1472#pragma warning(push)
1473#pragma warning(disable:4996)
1474
Tal Einatede0b6f2018-12-31 17:12:08 +02001475/*[clinic input]
1476sys.getwindowsversion
1477
1478Return info about the running version of Windows as a named tuple.
1479
1480The members are named: major, minor, build, platform, service_pack,
1481service_pack_major, service_pack_minor, suite_mask, product_type and
1482platform_version. For backward compatibility, only the first 5 items
1483are available by indexing. All elements are numbers, except
1484service_pack and platform_type which are strings, and platform_version
1485which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1486workstation, 2 for a domain controller, 3 for a server.
1487Platform_version is a 3-tuple containing a version number that is
1488intended for identifying the OS rather than feature detection.
1489[clinic start generated code]*/
1490
Mark Hammond8696ebc2002-10-08 02:44:31 +00001491static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001492sys_getwindowsversion_impl(PyObject *module)
1493/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyObject *version;
1496 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001497 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001498 DWORD realMajor, realMinor, realBuild;
1499 HANDLE hKernel32;
1500 wchar_t kernel32_path[MAX_PATH];
1501 LPVOID verblock;
1502 DWORD verblock_size;
1503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001505 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 version = PyStructSequence_New(&WindowsVersionType);
1509 if (version == NULL)
1510 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1513 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1514 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1515 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001516 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1518 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1519 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1520 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001521
Steve Dower74f4af72016-09-17 17:27:48 -07001522 realMajor = ver.dwMajorVersion;
1523 realMinor = ver.dwMinorVersion;
1524 realBuild = ver.dwBuildNumber;
1525
1526 // GetVersion will lie if we are running in a compatibility mode.
1527 // We need to read the version info from a system file resource
1528 // to accurately identify the OS version. If we fail for any reason,
1529 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001530 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001531 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001532 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001533 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1534 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1535 (verblock = PyMem_RawMalloc(verblock_size))) {
1536 VS_FIXEDFILEINFO *ffi;
1537 UINT ffi_len;
1538
1539 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1540 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1541 realMajor = HIWORD(ffi->dwProductVersionMS);
1542 realMinor = LOWORD(ffi->dwProductVersionMS);
1543 realBuild = HIWORD(ffi->dwProductVersionLS);
1544 }
1545 PyMem_RawFree(verblock);
1546 }
Segev Finer48fb7662017-06-04 20:52:27 +03001547 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1548 realMajor,
1549 realMinor,
1550 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001551 ));
1552
Victor Stinneracde3f12021-02-19 15:07:59 +01001553 if (PyErr_Occurred()) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001554 Py_DECREF(version);
1555 return NULL;
1556 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001558}
1559
Steve Dower3e96f322015-03-02 08:01:10 -08001560#pragma warning(pop)
1561
Tal Einatede0b6f2018-12-31 17:12:08 +02001562/*[clinic input]
1563sys._enablelegacywindowsfsencoding
1564
1565Changes the default filesystem encoding to mbcs:replace.
1566
1567This is done for consistency with earlier versions of Python. See PEP
1568529 for more information.
1569
1570This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1571environment variable before launching Python.
1572[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001573
1574static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001575sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1576/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001577{
Victor Stinner709d23d2019-05-02 14:56:30 -04001578 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001579 return NULL;
1580 }
Steve Dowercc16be82016-09-08 10:35:16 -07001581 Py_RETURN_NONE;
1582}
1583
Mark Hammond8696ebc2002-10-08 02:44:31 +00001584#endif /* MS_WINDOWS */
1585
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001586#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001587
1588/*[clinic input]
1589sys.setdlopenflags
1590
1591 flags as new_val: int
1592 /
1593
1594Set the flags used by the interpreter for dlopen calls.
1595
1596This is used, for example, when the interpreter loads extension
1597modules. Among other things, this will enable a lazy resolving of
1598symbols when importing a module, if called as sys.setdlopenflags(0).
1599To share symbols across extension modules, call as
1600sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1601modules can be found in the os module (RTLD_xxx constants, e.g.
1602os.RTLD_LAZY).
1603[clinic start generated code]*/
1604
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001605static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001606sys_setdlopenflags_impl(PyObject *module, int new_val)
1607/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001608{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001609 PyInterpreterState *interp = _PyInterpreterState_GET();
1610 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001611 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001612}
1613
Tal Einatede0b6f2018-12-31 17:12:08 +02001614
1615/*[clinic input]
1616sys.getdlopenflags
1617
1618Return the current value of the flags that are used for dlopen calls.
1619
1620The flag constants are defined in the os module.
1621[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001622
1623static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001624sys_getdlopenflags_impl(PyObject *module)
1625/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001626{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01001627 PyInterpreterState *interp = _PyInterpreterState_GET();
1628 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001629}
1630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001632
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001633#ifdef USE_MALLOPT
1634/* Link with -lmalloc (or -lmpc) on an SGI */
1635#include <malloc.h>
1636
Tal Einatede0b6f2018-12-31 17:12:08 +02001637/*[clinic input]
1638sys.mdebug
1639
1640 flag: int
1641 /
1642[clinic start generated code]*/
1643
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001644static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001645sys_mdebug_impl(PyObject *module, int flag)
1646/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001650 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001651}
1652#endif /* USE_MALLOPT */
1653
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001654size_t
1655_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001659 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001660 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001661
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001663 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001664 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001665 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001666
Benjamin Petersonce798522012-01-22 11:24:29 -05001667 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001669 if (!_PyErr_Occurred(tstate)) {
1670 _PyErr_Format(tstate, PyExc_TypeError,
1671 "Type %.100s doesn't define __sizeof__",
1672 Py_TYPE(o)->tp_name);
1673 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 }
1675 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001676 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 Py_DECREF(method);
1678 }
1679
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001680 if (res == NULL)
1681 return (size_t)-1;
1682
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001683 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001684 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001685 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001686 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001688 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001689 _PyErr_SetString(tstate, PyExc_ValueError,
1690 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001691 return (size_t)-1;
1692 }
1693
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* add gc_head size */
Hai Shi675d9a32020-04-15 02:11:20 +08001695 if (_PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001696 return ((size_t)size) + sizeof(PyGC_Head);
1697 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001698}
1699
1700static PyObject *
1701sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1702{
1703 static char *kwlist[] = {"object", "default", 0};
1704 size_t size;
1705 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001706 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001707
1708 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001709 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001710 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001711 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001712
1713 size = _PySys_GetSizeOf(o);
1714
Victor Stinner838f2642019-06-13 22:41:23 +02001715 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001716 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001717 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1718 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001719 Py_INCREF(dflt);
1720 return dflt;
1721 }
1722 else
1723 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001725
1726 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001727}
1728
1729PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001730"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001731\n\
1732Return the size of object in bytes.");
1733
Tal Einatede0b6f2018-12-31 17:12:08 +02001734/*[clinic input]
1735sys.getrefcount -> Py_ssize_t
1736
1737 object: object
1738 /
1739
1740Return the reference count of object.
1741
1742The count returned is generally one higher than you might expect,
1743because it includes the (temporary) reference as an argument to
1744getrefcount().
1745[clinic start generated code]*/
1746
1747static Py_ssize_t
1748sys_getrefcount_impl(PyObject *module, PyObject *object)
1749/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001750{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001751 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001752}
1753
Tim Peters4be93d02002-07-07 19:59:50 +00001754#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001755/*[clinic input]
1756sys.gettotalrefcount -> Py_ssize_t
1757[clinic start generated code]*/
1758
1759static Py_ssize_t
1760sys_gettotalrefcount_impl(PyObject *module)
1761/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001762{
Tal Einatede0b6f2018-12-31 17:12:08 +02001763 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001764}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001765#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001766
Tal Einatede0b6f2018-12-31 17:12:08 +02001767/*[clinic input]
1768sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001769
Tal Einatede0b6f2018-12-31 17:12:08 +02001770Return the number of memory blocks currently allocated.
1771[clinic start generated code]*/
1772
1773static Py_ssize_t
1774sys_getallocatedblocks_impl(PyObject *module)
1775/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001776{
Tal Einatede0b6f2018-12-31 17:12:08 +02001777 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001778}
1779
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001780
Tal Einatede0b6f2018-12-31 17:12:08 +02001781/*[clinic input]
1782sys._getframe
1783
1784 depth: int = 0
1785 /
1786
1787Return a frame object from the call stack.
1788
1789If optional integer depth is given, return the frame object that many
1790calls below the top of the stack. If that is deeper than the call
1791stack, ValueError is raised. The default for depth is zero, returning
1792the frame at the top of the call stack.
1793
1794This function should be used for internal and specialized purposes
1795only.
1796[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001797
1798static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001799sys__getframe_impl(PyObject *module, int depth)
1800/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001801{
Victor Stinner838f2642019-06-13 22:41:23 +02001802 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner70364772020-04-29 03:28:46 +02001803 PyFrameObject *f = PyThreadState_GetFrame(tstate);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001804
Victor Stinner08faf002020-03-26 18:57:32 +01001805 if (_PySys_Audit(tstate, "sys._getframe", "O", f) < 0) {
Victor Stinner70364772020-04-29 03:28:46 +02001806 Py_DECREF(f);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001807 return NULL;
1808 }
1809
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 while (depth > 0 && f != NULL) {
Victor Stinner70364772020-04-29 03:28:46 +02001811 PyFrameObject *back = PyFrame_GetBack(f);
1812 Py_DECREF(f);
1813 f = back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 --depth;
1815 }
1816 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001817 _PyErr_SetString(tstate, PyExc_ValueError,
1818 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return NULL;
1820 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001822}
1823
Tal Einatede0b6f2018-12-31 17:12:08 +02001824/*[clinic input]
1825sys._current_frames
1826
1827Return a dict mapping each thread's thread id to its current stack frame.
1828
1829This function should be used for specialized purposes only.
1830[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001831
1832static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001833sys__current_frames_impl(PyObject *module)
1834/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001837}
1838
Tal Einatede0b6f2018-12-31 17:12:08 +02001839/*[clinic input]
Julien Danjou64366fa2020-11-02 15:16:25 +01001840sys._current_exceptions
1841
1842Return a dict mapping each thread's identifier to its current raised exception.
1843
1844This function should be used for specialized purposes only.
1845[clinic start generated code]*/
1846
1847static PyObject *
1848sys__current_exceptions_impl(PyObject *module)
1849/*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
1850{
1851 return _PyThread_CurrentExceptions();
1852}
1853
1854/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +02001855sys.call_tracing
1856
1857 func: object
1858 args as funcargs: object(subclass_of='&PyTuple_Type')
1859 /
1860
1861Call func(*args), while tracing is enabled.
1862
1863The tracing state is saved, and restored afterwards. This is intended
1864to be called from a debugger from a checkpoint, to recursively debug
1865some other code.
1866[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001867
1868static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001869sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1870/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001873}
1874
Victor Stinner048afd92016-11-28 11:59:04 +01001875
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001876#ifdef __cplusplus
1877extern "C" {
1878#endif
1879
Tal Einatede0b6f2018-12-31 17:12:08 +02001880/*[clinic input]
1881sys._debugmallocstats
1882
1883Print summary info to stderr about the state of pymalloc's structures.
1884
1885In Py_DEBUG mode, also perform some expensive internal consistency
1886checks.
1887[clinic start generated code]*/
1888
David Malcolm49526f42012-06-22 14:55:41 -04001889static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001890sys__debugmallocstats_impl(PyObject *module)
1891/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001892{
1893#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001894 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001895 fputc('\n', stderr);
1896 }
David Malcolm49526f42012-06-22 14:55:41 -04001897#endif
1898 _PyObject_DebugTypeStats(stderr);
1899
1900 Py_RETURN_NONE;
1901}
David Malcolm49526f42012-06-22 14:55:41 -04001902
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001903#ifdef Py_TRACE_REFS
Joannah Nanjekye46b5c6b2020-12-22 18:31:46 -04001904/* Defined in objects.c because it uses static globals in that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001905extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001906#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001907
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001908#ifdef DYNAMIC_EXECUTION_PROFILE
Joannah Nanjekye46b5c6b2020-12-22 18:31:46 -04001909/* Defined in ceval.c because it uses static globals in that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001910extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001911#endif
1912
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001913#ifdef __cplusplus
1914}
1915#endif
1916
Tal Einatede0b6f2018-12-31 17:12:08 +02001917
1918/*[clinic input]
1919sys._clear_type_cache
1920
1921Clear the internal type lookup cache.
1922[clinic start generated code]*/
1923
Christian Heimes15ebc882008-02-04 18:48:49 +00001924static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001925sys__clear_type_cache_impl(PyObject *module)
1926/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyType_ClearCache();
1929 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001930}
1931
Tal Einatede0b6f2018-12-31 17:12:08 +02001932/*[clinic input]
1933sys.is_finalizing
1934
1935Return True if Python is exiting.
1936[clinic start generated code]*/
1937
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001938static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001939sys_is_finalizing_impl(PyObject *module)
1940/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001941{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001942 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001943}
1944
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001945#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001946/*[clinic input]
1947sys.getandroidapilevel
1948
1949Return the build time API version of Android as an integer.
1950[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001951
1952static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001953sys_getandroidapilevel_impl(PyObject *module)
1954/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001955{
1956 return PyLong_FromLong(ANDROID_API_LEVEL);
1957}
1958#endif /* ANDROID_API_LEVEL */
1959
1960
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001961/*[clinic input]
1962sys._deactivate_opcache
1963
1964Deactivate the opcode cache permanently
1965[clinic start generated code]*/
1966
1967static PyObject *
1968sys__deactivate_opcache_impl(PyObject *module)
1969/*[clinic end generated code: output=00e20982bd012122 input=501eac146735ccf9]*/
1970{
1971 _PyEval_DeactivateOpCache();
1972 Py_RETURN_NONE;
1973}
1974
Steve Dowerb82e17e2019-05-23 08:45:22 -07001975
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001976static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001978 SYS_ADDAUDITHOOK_METHODDEF
1979 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001980 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001981 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001982 SYS__CLEAR_TYPE_CACHE_METHODDEF
1983 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001984 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001985 SYS_DISPLAYHOOK_METHODDEF
1986 SYS_EXC_INFO_METHODDEF
1987 SYS_EXCEPTHOOK_METHODDEF
1988 SYS_EXIT_METHODDEF
1989 SYS_GETDEFAULTENCODING_METHODDEF
1990 SYS_GETDLOPENFLAGS_METHODDEF
1991 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001992#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001993 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001994#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001995 SYS_GETFILESYSTEMENCODING_METHODDEF
1996 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001997#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001999#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02002000 SYS_GETTOTALREFCOUNT_METHODDEF
2001 SYS_GETREFCOUNT_METHODDEF
2002 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002003 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002005 SYS__GETFRAME_METHODDEF
2006 SYS_GETWINDOWSVERSION_METHODDEF
2007 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
2008 SYS_INTERN_METHODDEF
2009 SYS_IS_FINALIZING_METHODDEF
2010 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002011 SYS_SETSWITCHINTERVAL_METHODDEF
2012 SYS_GETSWITCHINTERVAL_METHODDEF
2013 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002014 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002015 SYS_GETPROFILE_METHODDEF
2016 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002018 SYS_GETTRACE_METHODDEF
2019 SYS_CALL_TRACING_METHODDEF
2020 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002021 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2022 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002023 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002024 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002025 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2026 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002027 SYS_UNRAISABLEHOOK_METHODDEF
Pablo Galindoaf5fa132021-02-28 22:41:09 +00002028 SYS__DEACTIVATE_OPCACHE_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002030};
2031
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002032
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002033static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002034list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 PyObject *list = PyList_New(0);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002037 if (list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 return NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002039 }
2040 for (Py_ssize_t i = 0; PyImport_Inittab[i].name != NULL; i++) {
2041 PyObject *name = PyUnicode_FromString(PyImport_Inittab[i].name);
2042 if (name == NULL) {
2043 goto error;
2044 }
2045 if (PyList_Append(list, name) < 0) {
2046 Py_DECREF(name);
2047 goto error;
2048 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 Py_DECREF(name);
2050 }
2051 if (PyList_Sort(list) != 0) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002052 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002054 PyObject *tuple = PyList_AsTuple(list);
2055 Py_DECREF(list);
2056 return tuple;
2057
2058error:
2059 Py_DECREF(list);
2060 return NULL;
Guido van Rossum34679b71993-01-26 13:33:44 +00002061}
2062
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002063
2064static PyObject *
Victor Stinner9852cb32021-01-25 23:12:50 +01002065list_stdlib_module_names(void)
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002066{
Victor Stinner9852cb32021-01-25 23:12:50 +01002067 Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002068 PyObject *names = PyTuple_New(len);
2069 if (names == NULL) {
2070 return NULL;
2071 }
2072
2073 for (Py_ssize_t i = 0; i < len; i++) {
Victor Stinner9852cb32021-01-25 23:12:50 +01002074 PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002075 if (name == NULL) {
2076 Py_DECREF(names);
2077 return NULL;
2078 }
2079 PyTuple_SET_ITEM(names, i, name);
2080 }
2081
2082 PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
2083 "(O)", names);
2084 Py_DECREF(names);
2085 return set;
2086}
2087
2088
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002089/* Pre-initialization support for sys.warnoptions and sys._xoptions
2090 *
2091 * Modern internal code paths:
2092 * These APIs get called after _Py_InitializeCore and get to use the
2093 * regular CPython list, dict, and unicode APIs.
2094 *
2095 * Legacy embedding code paths:
2096 * The multi-phase initialization API isn't public yet, so embedding
2097 * apps still need to be able configure sys.warnoptions and sys._xoptions
2098 * before they call Py_Initialize. To support this, we stash copies of
2099 * the supplied wchar * sequences in linked lists, and then migrate the
2100 * contents of those lists to the sys module in _PyInitializeCore.
2101 *
2102 */
2103
2104struct _preinit_entry {
2105 wchar_t *value;
2106 struct _preinit_entry *next;
2107};
2108
2109typedef struct _preinit_entry *_Py_PreInitEntry;
2110
2111static _Py_PreInitEntry _preinit_warnoptions = NULL;
2112static _Py_PreInitEntry _preinit_xoptions = NULL;
2113
2114static _Py_PreInitEntry
2115_alloc_preinit_entry(const wchar_t *value)
2116{
2117 /* To get this to work, we have to initialize the runtime implicitly */
2118 _PyRuntime_Initialize();
2119
2120 /* Force default allocator, so we can ensure that it also gets used to
2121 * destroy the linked list in _clear_preinit_entries.
2122 */
2123 PyMemAllocatorEx old_alloc;
2124 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2125
2126 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2127 if (node != NULL) {
2128 node->value = _PyMem_RawWcsdup(value);
2129 if (node->value == NULL) {
2130 PyMem_RawFree(node);
2131 node = NULL;
2132 };
2133 };
2134
2135 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2136 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002137}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002138
2139static int
2140_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2141{
2142 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2143 if (new_entry == NULL) {
2144 return -1;
2145 }
2146 /* We maintain the linked list in this order so it's easy to play back
2147 * the add commands in the same order later on in _Py_InitializeCore
2148 */
2149 _Py_PreInitEntry last_entry = *optionlist;
2150 if (last_entry == NULL) {
2151 *optionlist = new_entry;
2152 } else {
2153 while (last_entry->next != NULL) {
2154 last_entry = last_entry->next;
2155 }
2156 last_entry->next = new_entry;
2157 }
2158 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002159}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002160
2161static void
2162_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2163{
2164 _Py_PreInitEntry current = *optionlist;
2165 *optionlist = NULL;
2166 /* Deallocate the nodes and their contents using the default allocator */
2167 PyMemAllocatorEx old_alloc;
2168 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2169 while (current != NULL) {
2170 _Py_PreInitEntry next = current->next;
2171 PyMem_RawFree(current->value);
2172 PyMem_RawFree(current);
2173 current = next;
2174 }
2175 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002176}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002177
Victor Stinner120b7072019-08-23 18:03:08 +01002178
2179PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002180_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002181{
Victor Stinner120b7072019-08-23 18:03:08 +01002182 PyStatus status;
2183 _Py_PreInitEntry entry;
2184
2185 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002186 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002187 if (_PyStatus_EXCEPTION(status)) {
2188 return status;
2189 }
2190 }
2191
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002192 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002193 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002194}
2195
Victor Stinner120b7072019-08-23 18:03:08 +01002196
2197PyStatus
2198_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002199{
Victor Stinner120b7072019-08-23 18:03:08 +01002200 PyStatus status;
2201 _Py_PreInitEntry entry;
2202
2203 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2204 status = PyWideStringList_Append(&config->xoptions, entry->value);
2205 if (_PyStatus_EXCEPTION(status)) {
2206 return status;
2207 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002208 }
2209
Victor Stinner120b7072019-08-23 18:03:08 +01002210 _clear_preinit_entries(&_preinit_xoptions);
2211 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002212}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002213
Victor Stinner120b7072019-08-23 18:03:08 +01002214
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002215static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002216get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002217{
Victor Stinner838f2642019-06-13 22:41:23 +02002218 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002219 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002220 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2221 * interpreter config. When that happens, we need to properly set
2222 * the `warnoptions` reference in the main interpreter config as well.
2223 *
2224 * For Python 3.7, we shouldn't be able to get here due to the
2225 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2226 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2227 * call optional for embedding applications, thus making this
2228 * reachable again.
2229 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002230 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002231 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002232 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002233 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002234 if (sys_set_object_id(tstate->interp, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002235 Py_DECREF(warnoptions);
2236 return NULL;
2237 }
2238 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002239 }
2240 return warnoptions;
2241}
Guido van Rossum23fff912000-12-15 22:02:05 +00002242
2243void
2244PySys_ResetWarnOptions(void)
2245{
Victor Stinner50b48572018-11-01 01:51:40 +01002246 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002247 if (tstate == NULL) {
2248 _clear_preinit_entries(&_preinit_warnoptions);
2249 return;
2250 }
2251
Victor Stinner838f2642019-06-13 22:41:23 +02002252 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002253 if (warnoptions == NULL || !PyList_Check(warnoptions))
2254 return;
2255 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002256}
2257
Victor Stinnere1b29952018-10-30 14:31:42 +01002258static int
Victor Stinner838f2642019-06-13 22:41:23 +02002259_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002260{
Victor Stinner838f2642019-06-13 22:41:23 +02002261 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002262 if (warnoptions == NULL) {
2263 return -1;
2264 }
2265 if (PyList_Append(warnoptions, option)) {
2266 return -1;
2267 }
2268 return 0;
2269}
2270
2271void
2272PySys_AddWarnOptionUnicode(PyObject *option)
2273{
Victor Stinner838f2642019-06-13 22:41:23 +02002274 PyThreadState *tstate = _PyThreadState_GET();
2275 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002276 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002277 if (tstate) {
2278 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002279 }
2280 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002281}
2282
2283void
2284PySys_AddWarnOption(const wchar_t *s)
2285{
Victor Stinner50b48572018-11-01 01:51:40 +01002286 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002287 if (tstate == NULL) {
2288 _append_preinit_entry(&_preinit_warnoptions, s);
2289 return;
2290 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002291 PyObject *unicode;
2292 unicode = PyUnicode_FromWideChar(s, -1);
2293 if (unicode == NULL)
2294 return;
2295 PySys_AddWarnOptionUnicode(unicode);
2296 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002297}
2298
Christian Heimes33fe8092008-04-13 13:53:33 +00002299int
2300PySys_HasWarnOptions(void)
2301{
Victor Stinner838f2642019-06-13 22:41:23 +02002302 PyThreadState *tstate = _PyThreadState_GET();
2303 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002304 return (warnoptions != NULL && PyList_Check(warnoptions)
2305 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002306}
2307
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002308static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002309get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002310{
Victor Stinner838f2642019-06-13 22:41:23 +02002311 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002312 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002313 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2314 * interpreter config. When that happens, we need to properly set
2315 * the `xoptions` reference in the main interpreter config as well.
2316 *
2317 * For Python 3.7, we shouldn't be able to get here due to the
2318 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2319 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2320 * call optional for embedding applications, thus making this
2321 * reachable again.
2322 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002323 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002324 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002325 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002326 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002327 if (sys_set_object_id(tstate->interp, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002328 Py_DECREF(xoptions);
2329 return NULL;
2330 }
2331 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002332 }
2333 return xoptions;
2334}
2335
Victor Stinnere1b29952018-10-30 14:31:42 +01002336static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002337_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002338{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002339 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002340
Victor Stinner838f2642019-06-13 22:41:23 +02002341 PyThreadState *tstate = _PyThreadState_GET();
2342 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002343 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002344 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002345 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002346
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002347 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002348 if (!name_end) {
2349 name = PyUnicode_FromWideChar(s, -1);
2350 value = Py_True;
2351 Py_INCREF(value);
2352 }
2353 else {
2354 name = PyUnicode_FromWideChar(s, name_end - s);
2355 value = PyUnicode_FromWideChar(name_end + 1, -1);
2356 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002357 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002358 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002359 }
2360 if (PyDict_SetItem(opts, name, value) < 0) {
2361 goto error;
2362 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002363 Py_DECREF(name);
2364 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002365 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002366
2367error:
2368 Py_XDECREF(name);
2369 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002370 return -1;
2371}
2372
2373void
2374PySys_AddXOption(const wchar_t *s)
2375{
Victor Stinner50b48572018-11-01 01:51:40 +01002376 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002377 if (tstate == NULL) {
2378 _append_preinit_entry(&_preinit_xoptions, s);
2379 return;
2380 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002381 if (_PySys_AddXOptionWithError(s) < 0) {
2382 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002383 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002384 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002385}
2386
2387PyObject *
2388PySys_GetXOptions(void)
2389{
Victor Stinner838f2642019-06-13 22:41:23 +02002390 PyThreadState *tstate = _PyThreadState_GET();
2391 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002392}
2393
Guido van Rossum40552d01998-08-06 03:34:39 +00002394/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2395 Two literals concatenated works just fine. If you have a K&R compiler
2396 or other abomination that however *does* understand longer strings,
2397 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002398PyDoc_VAR(sys_doc) =
2399PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002400"This module provides access to some objects used or maintained by the\n\
2401interpreter and to functions that interact strongly with the interpreter.\n\
2402\n\
2403Dynamic objects:\n\
2404\n\
2405argv -- command line arguments; argv[0] is the script pathname if known\n\
2406path -- module search path; path[0] is the script directory, else ''\n\
2407modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002408\n\
2409displayhook -- called to show results in an interactive session\n\
2410excepthook -- called to handle any uncaught exception other than SystemExit\n\
2411 To customize printing in an interactive session or to install a custom\n\
2412 top-level exception handler, assign other functions to replace these.\n\
2413\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002414stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002415stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002416stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002417 By assigning other file objects (or objects that behave like files)\n\
2418 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002419\n\
2420last_type -- type of last uncaught exception\n\
2421last_value -- value of last uncaught exception\n\
2422last_traceback -- traceback of last uncaught exception\n\
2423 These three are only available in an interactive session after a\n\
2424 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002425"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002426)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002427/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002428PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002429"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002430Static objects:\n\
2431\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002432builtin_module_names -- tuple of module names built into this interpreter\n\
2433copyright -- copyright notice pertaining to this interpreter\n\
2434exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002435executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002436float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002437float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002438hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002439hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002440implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002441int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002442maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002443maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002444platform -- platform identifier\n\
2445prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002446thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002447version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002448version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002449"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002450)
Steve Dowercc16be82016-09-08 10:35:16 -07002451#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002452/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002453PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002454"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002455winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002456"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002457)
Steve Dowercc16be82016-09-08 10:35:16 -07002458#endif /* MS_COREDLL */
2459#ifdef MS_WINDOWS
2460/* concatenating string here */
2461PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002462"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002463"
2464)
2465#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002466PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002467"__stdin__ -- the original stdin; don't touch!\n\
2468__stdout__ -- the original stdout; don't touch!\n\
2469__stderr__ -- the original stderr; don't touch!\n\
2470__displayhook__ -- the original displayhook; don't touch!\n\
2471__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002472\n\
2473Functions:\n\
2474\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002475displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002476excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002477exc_info() -- return thread-safe information about the current exception\n\
2478exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002479getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002480getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002481getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002482getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002483getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002484gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002485setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002486setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002487setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002488settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002489"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002490)
Fred Drakeccede592000-08-14 20:59:57 +00002491/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002492
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002493
2494PyDoc_STRVAR(flags__doc__,
2495"sys.flags\n\
2496\n\
2497Flags provided through command line arguments or environment vars.");
2498
2499static PyTypeObject FlagsType;
2500
2501static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 {"inspect", "-i"},
2504 {"interactive", "-i"},
2505 {"optimize", "-O or -OO"},
2506 {"dont_write_bytecode", "-B"},
2507 {"no_user_site", "-s"},
2508 {"no_site", "-S"},
2509 {"ignore_environment", "-E"},
2510 {"verbose", "-v"},
Georg Brandl8aa7e992010-12-28 18:30:18 +00002511 {"bytes_warning", "-b"},
2512 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002513 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002514 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002515 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002516 {"utf8_mode", "-X utf8"},
Inada Naoki48274832021-03-29 12:28:14 +09002517 {"warn_default_encoding", "-X warn_default_encoding"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002519};
2520
2521static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 "sys.flags", /* name */
2523 flags__doc__, /* doc */
2524 flags_fields, /* fields */
Inada Naoki48274832021-03-29 12:28:14 +09002525 16
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002526};
2527
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002528static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002529set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002530{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002531 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002532 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002533
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002534 // _PySys_UpdateConfig() modifies sys.flags in-place:
2535 // Py_XDECREF() is needed in this case.
2536 Py_ssize_t pos = 0;
2537#define SetFlagObj(expr) \
2538 do { \
2539 PyObject *value = (expr); \
2540 if (value == NULL) { \
2541 return -1; \
2542 } \
2543 Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
2544 PyStructSequence_SET_ITEM(flags, pos, value); \
2545 pos++; \
2546 } while (0)
2547#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002548
Victor Stinnerfbca9082018-08-30 00:50:45 +02002549 SetFlag(config->parser_debug);
2550 SetFlag(config->inspect);
2551 SetFlag(config->interactive);
2552 SetFlag(config->optimization_level);
2553 SetFlag(!config->write_bytecode);
2554 SetFlag(!config->user_site_directory);
2555 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002556 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002557 SetFlag(config->verbose);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002558 SetFlag(config->bytes_warning);
2559 SetFlag(config->quiet);
2560 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002561 SetFlag(config->isolated);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002562 SetFlagObj(PyBool_FromLong(config->dev_mode));
Victor Stinner20004952019-03-26 02:31:11 +01002563 SetFlag(preconfig->utf8_mode);
Inada Naoki48274832021-03-29 12:28:14 +09002564 SetFlag(config->warn_default_encoding);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002565#undef SetFlagObj
Victor Stinner91106cd2017-12-13 12:29:09 +01002566#undef SetFlag
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002567 return 0;
2568}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002569
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002570
2571static PyObject*
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002572make_flags(PyInterpreterState *interp)
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002573{
2574 PyObject *flags = PyStructSequence_New(&FlagsType);
2575 if (flags == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 return NULL;
2577 }
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002578
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002579 if (set_flags_from_config(interp, flags) < 0) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002580 Py_DECREF(flags);
2581 return NULL;
2582 }
2583 return flags;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002584}
2585
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002586
Eric Smith0e5b5622009-02-06 01:32:42 +00002587PyDoc_STRVAR(version_info__doc__,
2588"sys.version_info\n\
2589\n\
2590Version information as a named tuple.");
2591
2592static PyTypeObject VersionInfoType;
2593
2594static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 {"major", "Major release number"},
2596 {"minor", "Minor release number"},
2597 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002598 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 {"serial", "Serial release number"},
2600 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002601};
2602
2603static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 "sys.version_info", /* name */
2605 version_info__doc__, /* doc */
2606 version_info_fields, /* fields */
2607 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002608};
2609
2610static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002611make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 PyObject *version_info;
2614 char *s;
2615 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 version_info = PyStructSequence_New(&VersionInfoType);
2618 if (version_info == NULL) {
2619 return NULL;
2620 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 /*
2623 * These release level checks are mutually exclusive and cover
2624 * the field, so don't get too fancy with the pre-processor!
2625 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002626#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002627 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002628#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002630#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002632#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002633 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002634#endif
2635
2636#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002638#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002639 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 SetIntItem(PY_MAJOR_VERSION);
2642 SetIntItem(PY_MINOR_VERSION);
2643 SetIntItem(PY_MICRO_VERSION);
2644 SetStrItem(s);
2645 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002646#undef SetIntItem
2647#undef SetStrItem
2648
Victor Stinner838f2642019-06-13 22:41:23 +02002649 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002650 Py_CLEAR(version_info);
2651 return NULL;
2652 }
2653 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002654}
2655
Brett Cannon3adc7b72012-07-09 14:22:12 -04002656/* sys.implementation values */
2657#define NAME "cpython"
2658const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002659#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2660#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002661#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002662const char *_PySys_ImplCacheTag = TAG;
2663#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002664#undef MAJOR
2665#undef MINOR
2666#undef TAG
2667
Barry Warsaw409da152012-06-03 16:18:47 -04002668static PyObject *
2669make_impl_info(PyObject *version_info)
2670{
2671 int res;
2672 PyObject *impl_info, *value, *ns;
2673
2674 impl_info = PyDict_New();
2675 if (impl_info == NULL)
2676 return NULL;
2677
2678 /* populate the dict */
2679
Brett Cannon3adc7b72012-07-09 14:22:12 -04002680 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002681 if (value == NULL)
2682 goto error;
2683 res = PyDict_SetItemString(impl_info, "name", value);
2684 Py_DECREF(value);
2685 if (res < 0)
2686 goto error;
2687
Brett Cannon3adc7b72012-07-09 14:22:12 -04002688 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002689 if (value == NULL)
2690 goto error;
2691 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2692 Py_DECREF(value);
2693 if (res < 0)
2694 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002695
2696 res = PyDict_SetItemString(impl_info, "version", version_info);
2697 if (res < 0)
2698 goto error;
2699
2700 value = PyLong_FromLong(PY_VERSION_HEX);
2701 if (value == NULL)
2702 goto error;
2703 res = PyDict_SetItemString(impl_info, "hexversion", value);
2704 Py_DECREF(value);
2705 if (res < 0)
2706 goto error;
2707
doko@ubuntu.com55532312016-06-14 08:55:19 +02002708#ifdef MULTIARCH
2709 value = PyUnicode_FromString(MULTIARCH);
2710 if (value == NULL)
2711 goto error;
2712 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2713 Py_DECREF(value);
2714 if (res < 0)
2715 goto error;
2716#endif
2717
Barry Warsaw409da152012-06-03 16:18:47 -04002718 /* dict ready */
2719
2720 ns = _PyNamespace_New(impl_info);
2721 Py_DECREF(impl_info);
2722 return ns;
2723
2724error:
2725 Py_CLEAR(impl_info);
2726 return NULL;
2727}
2728
Martin v. Löwis1a214512008-06-11 05:26:20 +00002729static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002730 PyModuleDef_HEAD_INIT,
2731 "sys",
2732 sys_doc,
2733 -1, /* multiple "initialization" just copies the module dict. */
2734 sys_methods,
2735 NULL,
2736 NULL,
2737 NULL,
2738 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002739};
2740
Eric Snow6b4be192017-05-22 21:36:03 -07002741/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002742#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002743 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002744 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002745 if (v == NULL) { \
2746 goto err_occurred; \
2747 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002748 res = PyDict_SetItemString(sysdict, key, v); \
2749 Py_DECREF(v); \
2750 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002751 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002752 } \
2753 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002754
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002755#define SET_SYS_FROM_STRING(key, value) \
2756 SET_SYS(key, PyUnicode_FromString(value))
2757
Victor Stinner331a6a52019-05-27 16:39:22 +02002758static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002759_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002760{
Victor Stinnerab672812019-01-23 15:04:40 +01002761 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002762 int res;
2763
Nick Coghland6009512014-11-20 21:39:37 +10002764 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002765
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002766#define COPY_SYS_ATTR(tokey, fromkey) \
2767 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002768
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002769 COPY_SYS_ATTR("__displayhook__", "displayhook");
2770 COPY_SYS_ATTR("__excepthook__", "excepthook");
2771 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2772 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2773
2774#undef COPY_SYS_ATTR
2775
2776 SET_SYS_FROM_STRING("version", Py_GetVersion());
2777 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2778 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2779 _Py_gitversion()));
2780 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2781 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2782 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2783 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2784 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2785 SET_SYS("float_info", PyFloat_GetInfo());
2786 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002787 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002788 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002789 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2790 goto type_init_failed;
2791 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002792 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002793 SET_SYS("hash_info", get_hash_info(tstate));
2794 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2795 SET_SYS("builtin_module_names", list_builtin_module_names());
Victor Stinner9852cb32021-01-25 23:12:50 +01002796 SET_SYS("stdlib_module_names", list_stdlib_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002797#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002798 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002799#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002800 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002801#endif
Fred Drake099325e2000-08-14 15:47:03 +00002802
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002803#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002804 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2805 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002806#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002807#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002808 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002809#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002812 if (VersionInfoType.tp_name == NULL) {
2813 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002814 &version_info_desc) < 0) {
2815 goto type_init_failed;
2816 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002817 }
Victor Stinner838f2642019-06-13 22:41:23 +02002818 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002819 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 /* prevent user from creating new instances */
2821 VersionInfoType.tp_init = NULL;
2822 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002823 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002824 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2825 _PyErr_Clear(tstate);
2826 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002827
Barry Warsaw409da152012-06-03 16:18:47 -04002828 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002829 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002830
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002831 // sys.flags: updated in-place later by _PySys_UpdateConfig()
Victor Stinner1c8f0592013-07-22 22:24:54 +02002832 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002833 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2834 goto type_init_failed;
2835 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002836 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002837 SET_SYS("flags", make_flags(tstate->interp));
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002838 /* prevent user from creating new instances */
2839 FlagsType.tp_init = NULL;
2840 FlagsType.tp_new = NULL;
2841 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2842 if (res < 0) {
2843 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2844 goto err_occurred;
2845 }
2846 _PyErr_Clear(tstate);
2847 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002848
2849#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 /* getwindowsversion */
2851 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002852 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002853 &windows_version_desc) < 0) {
2854 goto type_init_failed;
2855 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002856 /* prevent user from creating new instances */
2857 WindowsVersionType.tp_init = NULL;
2858 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002859 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002860 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002861 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2862 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002863 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002864#endif
2865
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002866 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002867#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002868 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002869#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002870 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002871#endif
2872
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002873 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002874
Yury Selivanoveb636452016-09-08 22:01:51 -07002875 /* initialize asyncgen_hooks */
2876 if (AsyncGenHooksType.tp_name == NULL) {
2877 if (PyStructSequence_InitType2(
2878 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002879 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002880 }
2881 }
2882
Victor Stinneref75a622020-11-12 15:14:13 +01002883 /* adding sys.path_hooks and sys.path_importer_cache */
2884 SET_SYS("meta_path", PyList_New(0));
2885 SET_SYS("path_importer_cache", PyDict_New());
2886 SET_SYS("path_hooks", PyList_New(0));
2887
Victor Stinner838f2642019-06-13 22:41:23 +02002888 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002889 goto err_occurred;
2890 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002891 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002892
2893type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002894 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002895
2896err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002897 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002898}
2899
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002900static int
2901sys_add_xoption(PyObject *opts, const wchar_t *s)
2902{
2903 PyObject *name, *value;
2904
2905 const wchar_t *name_end = wcschr(s, L'=');
2906 if (!name_end) {
2907 name = PyUnicode_FromWideChar(s, -1);
2908 value = Py_True;
2909 Py_INCREF(value);
2910 }
2911 else {
2912 name = PyUnicode_FromWideChar(s, name_end - s);
2913 value = PyUnicode_FromWideChar(name_end + 1, -1);
2914 }
2915 if (name == NULL || value == NULL) {
2916 goto error;
2917 }
2918 if (PyDict_SetItem(opts, name, value) < 0) {
2919 goto error;
2920 }
2921 Py_DECREF(name);
2922 Py_DECREF(value);
2923 return 0;
2924
2925error:
2926 Py_XDECREF(name);
2927 Py_XDECREF(value);
2928 return -1;
2929}
2930
2931
2932static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002933sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002934{
2935 Py_ssize_t nxoption = config->xoptions.length;
2936 wchar_t * const * xoptions = config->xoptions.items;
2937 PyObject *dict = PyDict_New();
2938 if (dict == NULL) {
2939 return NULL;
2940 }
2941
2942 for (Py_ssize_t i=0; i < nxoption; i++) {
2943 const wchar_t *option = xoptions[i];
2944 if (sys_add_xoption(dict, option) < 0) {
2945 Py_DECREF(dict);
2946 return NULL;
2947 }
2948 }
2949
2950 return dict;
2951}
2952
2953
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002954// Update sys attributes for a new PyConfig configuration.
2955// This function also adds attributes that _PySys_InitCore() didn't add.
Eric Snow6b4be192017-05-22 21:36:03 -07002956int
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002957_PySys_UpdateConfig(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002958{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002959 PyInterpreterState *interp = tstate->interp;
2960 PyObject *sysdict = interp->sysdict;
2961 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002962 int res;
2963
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002964#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002965 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002966
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002967#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002968 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002969
Victor Stinner9e1b8282020-11-10 13:21:52 +01002970#define COPY_WSTR(SYS_ATTR, WSTR) \
2971 if (WSTR != NULL) { \
2972 SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
2973 }
2974
Victor Stinnerf3cb8142020-11-05 18:12:33 +01002975 if (config->module_search_paths_set) {
2976 COPY_LIST("path", config->module_search_paths);
2977 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002978
Victor Stinner9e1b8282020-11-10 13:21:52 +01002979 COPY_WSTR("executable", config->executable);
2980 COPY_WSTR("_base_executable", config->base_executable);
2981 COPY_WSTR("prefix", config->prefix);
2982 COPY_WSTR("base_prefix", config->base_prefix);
2983 COPY_WSTR("exec_prefix", config->exec_prefix);
2984 COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
2985 COPY_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002986
Carl Meyerb193fa92018-06-15 22:40:56 -06002987 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002988 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002989 } else {
2990 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2991 }
2992
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002993 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002994 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002995 COPY_LIST("warnoptions", config->warnoptions);
2996
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002997 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002998
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002999#undef SET_SYS_FROM_WSTR
Victor Stinner9e1b8282020-11-10 13:21:52 +01003000#undef COPY_LIST
3001#undef COPY_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01003002
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003003 // sys.flags
Victor Stinnerbcb094b2021-02-19 15:10:45 +01003004 PyObject *flags = _PySys_GetObject(interp, "flags"); // borrowed ref
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003005 if (flags == NULL) {
3006 return -1;
3007 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01003008 if (set_flags_from_config(interp, flags) < 0) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003009 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003010 }
3011
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03003012 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07003013
Victor Stinner838f2642019-06-13 22:41:23 +02003014 if (_PyErr_Occurred(tstate)) {
3015 goto err_occurred;
3016 }
3017
Eric Snow6b4be192017-05-22 21:36:03 -07003018 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01003019
3020err_occurred:
3021 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003022}
3023
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03003024#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01003025#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07003026
Victor Stinnerab672812019-01-23 15:04:40 +01003027
3028/* Set up a preliminary stderr printer until we have enough
3029 infrastructure for the io module in place.
3030
3031 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003032static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01003033_PySys_SetPreliminaryStderr(PyObject *sysdict)
3034{
3035 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3036 if (pstderr == NULL) {
3037 goto error;
3038 }
3039 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3040 goto error;
3041 }
3042 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3043 goto error;
3044 }
3045 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003046 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003047
3048error:
3049 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003050 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003051}
3052
3053
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003054/* Create sys module without all attributes.
3055 _PySys_UpdateConfig() should be called later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003056PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01003057_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003058{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003059 assert(!_PyErr_Occurred(tstate));
3060
Victor Stinnerb45d2592019-06-20 00:05:23 +02003061 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003062
Victor Stinnerab672812019-01-23 15:04:40 +01003063 PyObject *modules = PyDict_New();
3064 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003065 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003066 }
3067 interp->modules = modules;
3068
3069 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3070 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003071 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003072 }
3073
3074 PyObject *sysdict = PyModule_GetDict(sysmod);
3075 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003076 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003077 }
3078 Py_INCREF(sysdict);
3079 interp->sysdict = sysdict;
3080
3081 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003082 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003083 }
3084
Victor Stinner331a6a52019-05-27 16:39:22 +02003085 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3086 if (_PyStatus_EXCEPTION(status)) {
3087 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003088 }
3089
Victor Stinner01b1cc12019-11-20 02:27:56 +01003090 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003091 if (_PyStatus_EXCEPTION(status)) {
3092 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003093 }
3094
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003095 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3096 goto error;
3097 }
3098
3099 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003100
3101 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003102 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003103
3104error:
3105 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003106}
3107
3108
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003109static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003110makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 int i, n;
3113 const wchar_t *p;
3114 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003116 n = 1;
3117 p = path;
3118 while ((p = wcschr(p, delim)) != NULL) {
3119 n++;
3120 p++;
3121 }
3122 v = PyList_New(n);
3123 if (v == NULL)
3124 return NULL;
3125 for (i = 0; ; i++) {
3126 p = wcschr(path, delim);
3127 if (p == NULL)
3128 p = path + wcslen(path); /* End of string */
3129 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3130 if (w == NULL) {
3131 Py_DECREF(v);
3132 return NULL;
3133 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003134 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 if (*p == '\0')
3136 break;
3137 path = p+1;
3138 }
3139 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003140}
3141
3142void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003143PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 PyObject *v;
3146 if ((v = makepathobject(path, DELIM)) == NULL)
3147 Py_FatalError("can't create sys.path");
Victor Stinnerbcb094b2021-02-19 15:10:45 +01003148 PyInterpreterState *interp = _PyInterpreterState_GET();
3149 if (sys_set_object_id(interp, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003151 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003153}
3154
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003155static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003156make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003157{
Victor Stinner74f65682019-03-15 15:08:05 +01003158 PyObject *list = PyList_New(argc);
3159 if (list == NULL) {
3160 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003161 }
Victor Stinner74f65682019-03-15 15:08:05 +01003162
3163 for (Py_ssize_t i = 0; i < argc; i++) {
3164 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3165 if (v == NULL) {
3166 Py_DECREF(list);
3167 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003168 }
Victor Stinner74f65682019-03-15 15:08:05 +01003169 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003170 }
Victor Stinner74f65682019-03-15 15:08:05 +01003171 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003172}
3173
Victor Stinner11a247d2017-12-13 21:05:57 +01003174void
3175PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003176{
Victor Stinnerc4868252019-08-23 11:04:16 +01003177 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003178 PyThreadState *tstate = _PyThreadState_GET();
3179
Victor Stinner74f65682019-03-15 15:08:05 +01003180 if (argc < 1 || argv == NULL) {
3181 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003182 argv = empty_argv;
3183 argc = 1;
3184 }
3185
3186 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003187 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003188 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003189 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01003190 if (sys_set_object_str(tstate->interp, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003191 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003192 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003193 }
3194 Py_DECREF(av);
3195
3196 if (updatepath) {
3197 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3198 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003199 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003200 PyObject *path0 = NULL;
3201 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3202 if (path0 == NULL) {
3203 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003204 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003205
Victor Stinner838f2642019-06-13 22:41:23 +02003206 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003207 if (sys_path != NULL) {
3208 if (PyList_Insert(sys_path, 0, path0) < 0) {
3209 Py_DECREF(path0);
3210 Py_FatalError("can't prepend path0 to sys.path");
3211 }
3212 }
3213 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003214 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003215 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003216}
Guido van Rossuma890e681998-05-12 14:59:24 +00003217
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003218void
3219PySys_SetArgv(int argc, wchar_t **argv)
3220{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003221 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003222}
3223
Victor Stinner14284c22010-04-23 12:02:30 +00003224/* Reimplementation of PyFile_WriteString() no calling indirectly
3225 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3226
3227static int
Victor Stinner79766632010-08-16 17:36:42 +00003228sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003229{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003230 if (file == NULL)
3231 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003232 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003233 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003235 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003237 Py_DECREF(result);
3238 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003239}
3240
Victor Stinner79766632010-08-16 17:36:42 +00003241static int
3242sys_pyfile_write(const char *text, PyObject *file)
3243{
3244 PyObject *unicode = NULL;
3245 int err;
3246
3247 if (file == NULL)
3248 return -1;
3249
3250 unicode = PyUnicode_FromString(text);
3251 if (unicode == NULL)
3252 return -1;
3253
3254 err = sys_pyfile_write_unicode(unicode, file);
3255 Py_DECREF(unicode);
3256 return err;
3257}
Guido van Rossuma890e681998-05-12 14:59:24 +00003258
3259/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3260 Adapted from code submitted by Just van Rossum.
3261
3262 PySys_WriteStdout(format, ...)
3263 PySys_WriteStderr(format, ...)
3264
3265 The first function writes to sys.stdout; the second to sys.stderr. When
3266 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003267 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003268
Victor Stinner14284c22010-04-23 12:02:30 +00003269 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003270 signal handlers: they may raise a new exception whereas sys_write()
3271 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003272
Guido van Rossuma890e681998-05-12 14:59:24 +00003273 Both take a printf-style format string as their first argument followed
3274 by a variable length argument list determined by the format string.
3275
3276 *** WARNING ***
3277
3278 The format should limit the total size of the formatted output string to
3279 1000 bytes. In particular, this means that no unrestricted "%s" formats
3280 should occur; these should be limited using "%.<N>s where <N> is a
3281 decimal number calculated so that <N> plus the maximum size of other
3282 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3283 which can print hundreds of digits for very large numbers.
3284
3285 */
3286
3287static void
Victor Stinner09054372013-11-06 22:41:44 +01003288sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 PyObject *file;
3291 PyObject *error_type, *error_value, *error_traceback;
3292 char buffer[1001];
3293 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003294 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003295
Victor Stinner838f2642019-06-13 22:41:23 +02003296 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3297 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3299 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003300 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003301 fputs(buffer, fp);
3302 }
3303 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3304 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003305 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003307 }
Victor Stinner838f2642019-06-13 22:41:23 +02003308 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003309}
3310
3311void
Guido van Rossuma890e681998-05-12 14:59:24 +00003312PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003317 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003318 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003319}
3320
3321void
Guido van Rossuma890e681998-05-12 14:59:24 +00003322PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003324 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003326 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003327 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003328 va_end(va);
3329}
3330
3331static void
Victor Stinner09054372013-11-06 22:41:44 +01003332sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003333{
3334 PyObject *file, *message;
3335 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003336 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003337 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003338
Victor Stinner838f2642019-06-13 22:41:23 +02003339 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3340 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003341 message = PyUnicode_FromFormatV(format, va);
3342 if (message != NULL) {
3343 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003344 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003345 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003346 if (utf8 != NULL)
3347 fputs(utf8, fp);
3348 }
3349 Py_DECREF(message);
3350 }
Victor Stinner838f2642019-06-13 22:41:23 +02003351 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003352}
3353
3354void
3355PySys_FormatStdout(const char *format, ...)
3356{
3357 va_list va;
3358
3359 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003360 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003361 va_end(va);
3362}
3363
3364void
3365PySys_FormatStderr(const char *format, ...)
3366{
3367 va_list va;
3368
3369 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003370 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003371 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003372}