blob: 33d4e2bbb6eac8b652066a3e258ad29d1c4f079b [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 *
89_PySys_GetObject(PyThreadState *tstate, const char *name)
90{
91 PyObject *sysdict = tstate->interp->sysdict;
92 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 Stinneraf1d64d2020-11-04 17:34:34 +0100105 PyObject *value = _PySys_GetObject(tstate, 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
113sys_set_object(PyThreadState *tstate, PyObject *key, PyObject *v)
114{
115 if (key == NULL) {
116 return -1;
117 }
118 PyObject *sd = tstate->interp->sysdict;
119 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
133sys_set_object_id(PyThreadState *tstate, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +0100134{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200135 return sys_set_object(tstate, _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 Stinner838f2642019-06-13 22:41:23 +0200141 PyThreadState *tstate = _PyThreadState_GET();
142 return sys_set_object_id(tstate, key, v);
143}
144
145static int
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200146sys_set_object_str(PyThreadState *tstate, 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);
150 int r = sys_set_object(tstate, key, v);
151 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 Stinner838f2642019-06-13 22:41:23 +0200158 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200159 return sys_set_object_str(tstate, 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 Stinner08faf002020-03-26 18:57:32 +0100164should_audit(PyInterpreterState *is)
Victor Stinner838f2642019-06-13 22:41:23 +0200165{
Victor Stinner08faf002020-03-26 18:57:32 +0100166 /* tstate->interp cannot be NULL, but test it just in case
167 for extra safety */
168 assert(is != NULL);
169 if (!is) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700170 return 0;
171 }
Victor Stinner08faf002020-03-26 18:57:32 +0100172 return (is->runtime->audit_hook_head
173 || is->audit_hooks
174 || PyDTrace_AUDIT_ENABLED());
Steve Dowerb82e17e2019-05-23 08:45:22 -0700175}
176
Steve Dowerb82e17e2019-05-23 08:45:22 -0700177
Victor Stinner08faf002020-03-26 18:57:32 +0100178static int
179sys_audit_tstate(PyThreadState *ts, const char *event,
180 const char *argFormat, va_list vargs)
181{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700182 /* N format is inappropriate, because you do not know
183 whether the reference is consumed by the call.
184 Assert rather than exception for perf reasons */
185 assert(!argFormat || !strchr(argFormat, 'N'));
186
Victor Stinner08faf002020-03-26 18:57:32 +0100187 if (!ts) {
188 /* Audit hooks cannot be called with a NULL thread state */
Steve Dowerb82e17e2019-05-23 08:45:22 -0700189 return 0;
190 }
191
Victor Stinner08faf002020-03-26 18:57:32 +0100192 /* The current implementation cannot be called if tstate is not
193 the current Python thread state. */
194 assert(ts == _PyThreadState_GET());
195
196 /* Early exit when no hooks are registered */
197 PyInterpreterState *is = ts->interp;
198 if (!should_audit(is)) {
199 return 0;
200 }
201
202 PyObject *eventName = NULL;
203 PyObject *eventArgs = NULL;
204 PyObject *hooks = NULL;
205 PyObject *hook = NULL;
206 int res = -1;
207
Steve Dowerb82e17e2019-05-23 08:45:22 -0700208 int dtrace = PyDTrace_AUDIT_ENABLED();
209
210 PyObject *exc_type, *exc_value, *exc_tb;
Victor Stinner08faf002020-03-26 18:57:32 +0100211 _PyErr_Fetch(ts, &exc_type, &exc_value, &exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700212
213 /* Initialize event args now */
214 if (argFormat && argFormat[0]) {
Victor Stinner08faf002020-03-26 18:57:32 +0100215 eventArgs = _Py_VaBuildValue_SizeT(argFormat, vargs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700216 if (eventArgs && !PyTuple_Check(eventArgs)) {
217 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
218 Py_DECREF(eventArgs);
219 eventArgs = argTuple;
220 }
Victor Stinner08faf002020-03-26 18:57:32 +0100221 }
222 else {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700223 eventArgs = PyTuple_New(0);
224 }
225 if (!eventArgs) {
226 goto exit;
227 }
228
229 /* Call global hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100230 _Py_AuditHookEntry *e = is->runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700231 for (; e; e = e->next) {
232 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
233 goto exit;
234 }
235 }
236
237 /* Dtrace USDT point */
238 if (dtrace) {
Andy Lestere6be9b52020-02-11 20:28:35 -0600239 PyDTrace_AUDIT(event, (void *)eventArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700240 }
241
242 /* Call interpreter hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100243 if (is->audit_hooks) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700244 eventName = PyUnicode_FromString(event);
245 if (!eventName) {
246 goto exit;
247 }
248
249 hooks = PyObject_GetIter(is->audit_hooks);
250 if (!hooks) {
251 goto exit;
252 }
253
254 /* Disallow tracing in hooks unless explicitly enabled */
255 ts->tracing++;
256 ts->use_tracing = 0;
257 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300258 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700259 PyObject *o;
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300260 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700261 if (o) {
262 canTrace = PyObject_IsTrue(o);
263 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700264 }
265 if (canTrace < 0) {
266 break;
267 }
268 if (canTrace) {
269 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
270 ts->tracing--;
271 }
Victor Stinner08faf002020-03-26 18:57:32 +0100272 PyObject* args[2] = {eventName, eventArgs};
273 o = _PyObject_FastCallTstate(ts, hook, args, 2);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700274 if (canTrace) {
275 ts->tracing++;
276 ts->use_tracing = 0;
277 }
278 if (!o) {
279 break;
280 }
281 Py_DECREF(o);
282 Py_CLEAR(hook);
283 }
284 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
285 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200286 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700287 goto exit;
288 }
289 }
290
291 res = 0;
292
293exit:
294 Py_XDECREF(hook);
295 Py_XDECREF(hooks);
296 Py_XDECREF(eventName);
297 Py_XDECREF(eventArgs);
298
Victor Stinner08faf002020-03-26 18:57:32 +0100299 if (!res) {
300 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
301 }
302 else {
303 assert(_PyErr_Occurred(ts));
304 Py_XDECREF(exc_type);
305 Py_XDECREF(exc_value);
306 Py_XDECREF(exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700307 }
308
309 return res;
310}
311
Victor Stinner08faf002020-03-26 18:57:32 +0100312int
313_PySys_Audit(PyThreadState *tstate, const char *event,
314 const char *argFormat, ...)
315{
316 va_list vargs;
317#ifdef HAVE_STDARG_PROTOTYPES
318 va_start(vargs, argFormat);
319#else
320 va_start(vargs);
321#endif
322 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
323 va_end(vargs);
324 return res;
325}
326
327int
328PySys_Audit(const char *event, const char *argFormat, ...)
329{
330 PyThreadState *tstate = _PyThreadState_GET();
331 va_list vargs;
332#ifdef HAVE_STDARG_PROTOTYPES
333 va_start(vargs, argFormat);
334#else
335 va_start(vargs);
336#endif
337 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
338 va_end(vargs);
339 return res;
340}
341
Steve Dowerb82e17e2019-05-23 08:45:22 -0700342/* We expose this function primarily for our own cleanup during
343 * finalization. In general, it should not need to be called,
Victor Stinner08faf002020-03-26 18:57:32 +0100344 * and as such the function is not exported.
345 *
346 * Must be finalizing to clear hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200347void
Victor Stinner08faf002020-03-26 18:57:32 +0100348_PySys_ClearAuditHooks(PyThreadState *ts)
Victor Stinner838f2642019-06-13 22:41:23 +0200349{
Victor Stinner08faf002020-03-26 18:57:32 +0100350 assert(ts != NULL);
351 if (!ts) {
352 return;
353 }
354
355 _PyRuntimeState *runtime = ts->interp->runtime;
Victor Stinner7b3c2522020-03-07 00:24:23 +0100356 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
Victor Stinner08faf002020-03-26 18:57:32 +0100357 assert(finalizing == ts);
358 if (finalizing != ts) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700359 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200360 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700361
Victor Stinnerda7933e2020-04-13 03:04:28 +0200362 const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
Victor Stinner838f2642019-06-13 22:41:23 +0200363 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700364 PySys_WriteStderr("# clear sys.audit hooks\n");
365 }
366
367 /* Hooks can abort later hooks for this event, but cannot
368 abort the clear operation itself. */
Victor Stinner08faf002020-03-26 18:57:32 +0100369 _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200370 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700371
Victor Stinner08faf002020-03-26 18:57:32 +0100372 _Py_AuditHookEntry *e = runtime->audit_hook_head, *n;
373 runtime->audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700374 while (e) {
375 n = e->next;
376 PyMem_RawFree(e);
377 e = n;
378 }
379}
380
381int
382PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
383{
Victor Stinner08faf002020-03-26 18:57:32 +0100384 /* tstate can be NULL, so access directly _PyRuntime:
385 PySys_AddAuditHook() can be called before Python is initialized. */
Victor Stinner838f2642019-06-13 22:41:23 +0200386 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner08faf002020-03-26 18:57:32 +0100387 PyThreadState *tstate;
388 if (runtime->initialized) {
389 tstate = _PyRuntimeState_GetThreadState(runtime);
390 }
391 else {
392 tstate = NULL;
393 }
Victor Stinner838f2642019-06-13 22:41:23 +0200394
Steve Dowerb82e17e2019-05-23 08:45:22 -0700395 /* Invoke existing audit hooks to allow them an opportunity to abort. */
396 /* Cannot invoke hooks until we are initialized */
Victor Stinner08faf002020-03-26 18:57:32 +0100397 if (tstate != NULL) {
398 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800399 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
400 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200401 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700402 return 0;
403 }
404 return -1;
405 }
406 }
407
Victor Stinner08faf002020-03-26 18:57:32 +0100408 _Py_AuditHookEntry *e = runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700409 if (!e) {
410 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner08faf002020-03-26 18:57:32 +0100411 runtime->audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700412 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200413 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700414 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200415 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700416 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
417 sizeof(_Py_AuditHookEntry));
418 }
419
420 if (!e) {
Victor Stinner08faf002020-03-26 18:57:32 +0100421 if (tstate != NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200422 _PyErr_NoMemory(tstate);
423 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700424 return -1;
425 }
426
427 e->next = NULL;
428 e->hookCFunction = (Py_AuditHookFunction)hook;
429 e->userData = userData;
430
431 return 0;
432}
433
434/*[clinic input]
435sys.addaudithook
436
437 hook: object
438
439Adds a new audit hook callback.
440[clinic start generated code]*/
441
442static PyObject *
443sys_addaudithook_impl(PyObject *module, PyObject *hook)
444/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
445{
Victor Stinner838f2642019-06-13 22:41:23 +0200446 PyThreadState *tstate = _PyThreadState_GET();
447
Steve Dowerb82e17e2019-05-23 08:45:22 -0700448 /* Invoke existing audit hooks to allow them an opportunity to abort. */
Victor Stinner08faf002020-03-26 18:57:32 +0100449 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200450 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700451 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200452 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700453 Py_RETURN_NONE;
454 }
455 return NULL;
456 }
457
Victor Stinner838f2642019-06-13 22:41:23 +0200458 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700459 if (is->audit_hooks == NULL) {
460 is->audit_hooks = PyList_New(0);
461 if (is->audit_hooks == NULL) {
462 return NULL;
463 }
464 }
465
466 if (PyList_Append(is->audit_hooks, hook) < 0) {
467 return NULL;
468 }
469
470 Py_RETURN_NONE;
471}
472
473PyDoc_STRVAR(audit_doc,
474"audit(event, *args)\n\
475\n\
476Passes the event to any audit hooks that are attached.");
477
478static PyObject *
479sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
480{
Victor Stinner838f2642019-06-13 22:41:23 +0200481 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200482 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner838f2642019-06-13 22:41:23 +0200483
Steve Dowerb82e17e2019-05-23 08:45:22 -0700484 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200485 _PyErr_SetString(tstate, PyExc_TypeError,
486 "audit() missing 1 required positional argument: "
487 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700488 return NULL;
489 }
490
Victor Stinner08faf002020-03-26 18:57:32 +0100491 if (!should_audit(tstate->interp)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700492 Py_RETURN_NONE;
493 }
494
495 PyObject *auditEvent = args[0];
496 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200497 _PyErr_SetString(tstate, PyExc_TypeError,
498 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700499 return NULL;
500 }
501 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200502 _PyErr_Format(tstate, PyExc_TypeError,
503 "expected str for argument 'event', not %.200s",
504 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700505 return NULL;
506 }
507 const char *event = PyUnicode_AsUTF8(auditEvent);
508 if (!event) {
509 return NULL;
510 }
511
512 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
513 if (!auditArgs) {
514 return NULL;
515 }
516
Victor Stinner08faf002020-03-26 18:57:32 +0100517 int res = _PySys_Audit(tstate, event, "O", auditArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700518 Py_DECREF(auditArgs);
519
520 if (res < 0) {
521 return NULL;
522 }
523
524 Py_RETURN_NONE;
525}
526
527
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400528static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200529sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400530{
Victor Stinner838f2642019-06-13 22:41:23 +0200531 PyThreadState *tstate = _PyThreadState_GET();
532 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300533 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400534
535 if (envar == NULL || strlen(envar) == 0) {
536 envar = "pdb.set_trace";
537 }
538 else if (!strcmp(envar, "0")) {
539 /* The breakpoint is explicitly no-op'd. */
540 Py_RETURN_NONE;
541 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300542 /* According to POSIX the string returned by getenv() might be invalidated
543 * or the string content might be overwritten by a subsequent call to
544 * getenv(). Since importing a module can performs the getenv() calls,
545 * we need to save a copy of envar. */
546 envar = _PyMem_RawStrdup(envar);
547 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200548 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300549 return NULL;
550 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200551 const char *last_dot = strrchr(envar, '.');
552 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400553 PyObject *modulepath = NULL;
554
555 if (last_dot == NULL) {
556 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
557 modulepath = PyUnicode_FromString("builtins");
558 attrname = envar;
559 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200560 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400561 /* Split on the last dot; */
562 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
563 attrname = last_dot + 1;
564 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200565 else {
566 goto warn;
567 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400568 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300569 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400570 return NULL;
571 }
572
Anthony Sottiledce345c2018-11-01 10:25:05 -0700573 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400574 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400575
576 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200577 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200578 goto warn;
579 }
580 PyMem_RawFree(envar);
581 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400582 }
583
584 PyObject *hook = PyObject_GetAttrString(module, attrname);
585 Py_DECREF(module);
586
587 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200588 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200589 goto warn;
590 }
591 PyMem_RawFree(envar);
592 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400593 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300594 PyMem_RawFree(envar);
Petr Viktorinffd97532020-02-11 17:46:57 +0100595 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400596 Py_DECREF(hook);
597 return retval;
598
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200599 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400600 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200601 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400602 int status = PyErr_WarnFormat(
603 PyExc_RuntimeWarning, 0,
604 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300605 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400606 if (status < 0) {
607 /* Printing the warning raised an exception. */
608 return NULL;
609 }
610 /* The warning was (probably) issued. */
611 Py_RETURN_NONE;
612}
613
614PyDoc_STRVAR(breakpointhook_doc,
615"breakpointhook(*args, **kws)\n"
616"\n"
617"This hook function is called by built-in breakpoint().\n"
618);
619
Victor Stinner13d49ee2010-12-04 17:24:33 +0000620/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
621 error handler. If sys.stdout has a buffer attribute, use
622 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
623 sys.stdout.write(redecoded).
624
625 Helper function for sys_displayhook(). */
626static int
Andy Lesterda4d6562020-03-05 22:34:36 -0600627sys_displayhook_unencodable(PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000628{
629 PyObject *stdout_encoding = NULL;
630 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200631 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000632 int ret;
633
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200634 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000635 if (stdout_encoding == NULL)
636 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200637 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000638 if (stdout_encoding_str == NULL)
639 goto error;
640
641 repr_str = PyObject_Repr(o);
642 if (repr_str == NULL)
643 goto error;
644 encoded = PyUnicode_AsEncodedString(repr_str,
645 stdout_encoding_str,
646 "backslashreplace");
647 Py_DECREF(repr_str);
648 if (encoded == NULL)
649 goto error;
650
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300651 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
652 Py_DECREF(encoded);
653 goto error;
654 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000655 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200656 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000657 Py_DECREF(buffer);
658 Py_DECREF(encoded);
659 if (result == NULL)
660 goto error;
661 Py_DECREF(result);
662 }
663 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000664 escaped_str = PyUnicode_FromEncodedObject(encoded,
665 stdout_encoding_str,
666 "strict");
667 Py_DECREF(encoded);
668 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
669 Py_DECREF(escaped_str);
670 goto error;
671 }
672 Py_DECREF(escaped_str);
673 }
674 ret = 0;
675 goto finally;
676
677error:
678 ret = -1;
679finally:
680 Py_XDECREF(stdout_encoding);
681 return ret;
682}
683
Tal Einatede0b6f2018-12-31 17:12:08 +0200684/*[clinic input]
685sys.displayhook
686
687 object as o: object
688 /
689
690Print an object to sys.stdout and also save it in builtins._
691[clinic start generated code]*/
692
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000693static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200694sys_displayhook(PyObject *module, PyObject *o)
695/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100698 PyObject *builtins;
699 static PyObject *newline = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200700 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000701
Eric Snow3f9eee62017-09-15 16:35:20 -0600702 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200704 if (!_PyErr_Occurred(tstate)) {
705 _PyErr_SetString(tstate, PyExc_RuntimeError,
706 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100707 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return NULL;
709 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600710 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Print value except if None */
713 /* After printing, also assign to '_' */
714 /* Before, set '_' to None to avoid recursion */
715 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200716 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200718 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200720 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200722 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return NULL;
724 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000725 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200726 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Andy Lesterda4d6562020-03-05 22:34:36 -0600727 int err;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000728 /* repr(o) is not encodable to sys.stdout.encoding with
729 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200730 _PyErr_Clear(tstate);
Andy Lesterda4d6562020-03-05 22:34:36 -0600731 err = sys_displayhook_unencodable(outf, o);
Victor Stinner838f2642019-06-13 22:41:23 +0200732 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000733 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200734 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000735 }
736 else {
737 return NULL;
738 }
739 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100740 if (newline == NULL) {
741 newline = PyUnicode_FromString("\n");
742 if (newline == NULL)
743 return NULL;
744 }
745 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200747 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200749 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000750}
751
Tal Einatede0b6f2018-12-31 17:12:08 +0200752
753/*[clinic input]
754sys.excepthook
755
756 exctype: object
757 value: object
758 traceback: object
759 /
760
761Handle an exception by displaying it with a traceback on sys.stderr.
762[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000763
764static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200765sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
766 PyObject *traceback)
767/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000768{
Tal Einatede0b6f2018-12-31 17:12:08 +0200769 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200770 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000771}
772
Tal Einatede0b6f2018-12-31 17:12:08 +0200773
774/*[clinic input]
775sys.exc_info
776
777Return current exception information: (type, value, traceback).
778
779Return information about the most recent exception caught by an except
780clause in the current stack frame or in an older stack frame.
781[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000782
783static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200784sys_exc_info_impl(PyObject *module)
785/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000786{
Victor Stinner50b48572018-11-01 01:51:40 +0100787 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 return Py_BuildValue(
789 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100790 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
791 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
792 err_info->exc_traceback != NULL ?
793 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000794}
795
Tal Einatede0b6f2018-12-31 17:12:08 +0200796
797/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200798sys.unraisablehook
799
800 unraisable: object
801 /
802
803Handle an unraisable exception.
804
805The unraisable argument has the following attributes:
806
807* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200808* exc_value: Exception value, can be None.
809* exc_traceback: Exception traceback, can be None.
810* err_msg: Error message, can be None.
811* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200812[clinic start generated code]*/
813
814static PyObject *
815sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200816/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200817{
818 return _PyErr_WriteUnraisableDefaultHook(unraisable);
819}
820
821
822/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200823sys.exit
824
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300825 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200826 /
827
828Exit the interpreter by raising SystemExit(status).
829
830If the status is omitted or None, it defaults to zero (i.e., success).
831If the status is an integer, it will be used as the system exit status.
832If it is another kind of object, it will be printed and the system
833exit status will be one (i.e., failure).
834[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000835
836static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200837sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300838/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinneracde3f12021-02-19 15:07:59 +0100841 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000843}
844
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000845
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000846
Tal Einatede0b6f2018-12-31 17:12:08 +0200847/*[clinic input]
848sys.getdefaultencoding
849
850Return the current default encoding used by the Unicode implementation.
851[clinic start generated code]*/
852
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000853static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200854sys_getdefaultencoding_impl(PyObject *module)
855/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000858}
859
Tal Einatede0b6f2018-12-31 17:12:08 +0200860/*[clinic input]
861sys.getfilesystemencoding
862
863Return the encoding used to convert Unicode filenames to OS filenames.
864[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000865
866static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200867sys_getfilesystemencoding_impl(PyObject *module)
868/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000869{
Victor Stinner81a7be32020-04-14 15:14:01 +0200870 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200871 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400872 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000873}
874
Tal Einatede0b6f2018-12-31 17:12:08 +0200875/*[clinic input]
876sys.getfilesystemencodeerrors
877
878Return the error mode used Unicode to OS filename conversion.
879[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000880
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000881static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200882sys_getfilesystemencodeerrors_impl(PyObject *module)
883/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700884{
Victor Stinner81a7be32020-04-14 15:14:01 +0200885 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200886 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400887 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700888}
889
Tal Einatede0b6f2018-12-31 17:12:08 +0200890/*[clinic input]
891sys.intern
892
893 string as s: unicode
894 /
895
896``Intern'' the given string.
897
898This enters the string in the (global) table of interned strings whose
899purpose is to speed up dictionary lookups. Return the string itself or
900the previously interned string object with the same value.
901[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700902
903static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200904sys_intern_impl(PyObject *module, PyObject *s)
905/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 if (PyUnicode_CheckExact(s)) {
908 Py_INCREF(s);
909 PyUnicode_InternInPlace(&s);
910 return s;
911 }
912 else {
Victor Stinneracde3f12021-02-19 15:07:59 +0100913 PyErr_Format(PyExc_TypeError,
914 "can't intern %.400s", Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000915 return NULL;
916 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000917}
918
Georg Brandl66a796e2006-12-19 20:50:34 +0000919
Fred Drake5755ce62001-06-27 19:19:46 +0000920/*
921 * Cached interned string objects used for calling the profile and
922 * trace functions. Initialized by trace_init().
923 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000924static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000925
926static int
927trace_init(void)
928{
Nick Coghlan5a851672017-09-08 10:14:16 +1000929 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200930 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000931 "c_call", "c_exception", "c_return",
932 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200933 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *name;
935 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000936 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (whatstrings[i] == NULL) {
938 name = PyUnicode_InternFromString(whatnames[i]);
939 if (name == NULL)
940 return -1;
941 whatstrings[i] = name;
942 }
943 }
944 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000945}
946
947
948static PyObject *
Victor Stinner309d7cc2020-03-13 16:39:12 +0100949call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000951{
Victor Stinner78da82b2016-08-20 01:22:57 +0200952 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200954 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100955
Victor Stinner838f2642019-06-13 22:41:23 +0200956 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200957 stack[0] = (PyObject *)frame;
958 stack[1] = whatstrings[what];
959 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000961 /* call the Python-level function */
Victor Stinner309d7cc2020-03-13 16:39:12 +0100962 PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000963
Victor Stinner78da82b2016-08-20 01:22:57 +0200964 PyFrame_LocalsToFast(frame, 1);
965 if (result == NULL) {
966 PyTraceBack_Here(frame);
967 }
968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000970}
971
972static int
973profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000975{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100976 if (arg == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 arg = Py_None;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100978 }
979
980 PyThreadState *tstate = _PyThreadState_GET();
981 PyObject *result = call_trampoline(tstate, self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100983 _PyEval_SetProfile(tstate, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return -1;
985 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100986
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 Py_DECREF(result);
988 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000989}
990
991static int
992trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyObject *callback;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100996 if (what == PyTrace_CALL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 callback = self;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100998 }
999 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 callback = frame->f_trace;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001001 }
1002 if (callback == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001003 return 0;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001004 }
1005
1006 PyThreadState *tstate = _PyThreadState_GET();
1007 PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01001009 _PyEval_SetTrace(tstate, NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001010 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 return -1;
1012 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01001013
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +03001015 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 }
1017 else {
1018 Py_DECREF(result);
1019 }
1020 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00001021}
Fred Draked0838392001-06-16 21:02:31 +00001022
Fred Drake8b4d01d2000-05-09 19:57:01 +00001023static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001024sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001025{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001026 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001027 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001028 }
1029
1030 PyThreadState *tstate = _PyThreadState_GET();
1031 if (args == Py_None) {
1032 if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
1033 return NULL;
1034 }
1035 }
1036 else {
1037 if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
1038 return NULL;
1039 }
1040 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001041 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001042}
1043
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001044PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001045"settrace(function)\n\
1046\n\
1047Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001048function call. See the debugger chapter in the library manual."
1049);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001050
Tal Einatede0b6f2018-12-31 17:12:08 +02001051/*[clinic input]
1052sys.gettrace
1053
1054Return the global debug tracing function set with sys.settrace.
1055
1056See the debugger chapter in the library manual.
1057[clinic start generated code]*/
1058
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001059static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001060sys_gettrace_impl(PyObject *module)
1061/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001062{
Victor Stinner50b48572018-11-01 01:51:40 +01001063 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (temp == NULL)
1067 temp = Py_None;
1068 Py_INCREF(temp);
1069 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001070}
1071
Christian Heimes9bd667a2008-01-20 15:14:11 +00001072static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001073sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001074{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001075 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001077 }
1078
1079 PyThreadState *tstate = _PyThreadState_GET();
1080 if (args == Py_None) {
1081 if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1082 return NULL;
1083 }
1084 }
1085 else {
1086 if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
1087 return NULL;
1088 }
1089 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001090 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001091}
1092
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001093PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001094"setprofile(function)\n\
1095\n\
1096Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001097and return. See the profiler chapter in the library manual."
1098);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001099
Tal Einatede0b6f2018-12-31 17:12:08 +02001100/*[clinic input]
1101sys.getprofile
1102
1103Return the profiling function set with sys.setprofile.
1104
1105See the profiler chapter in the library manual.
1106[clinic start generated code]*/
1107
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001108static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001109sys_getprofile_impl(PyObject *module)
1110/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001111{
Victor Stinner50b48572018-11-01 01:51:40 +01001112 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (temp == NULL)
1116 temp = Py_None;
1117 Py_INCREF(temp);
1118 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001119}
1120
Tim Peterse5e065b2003-07-06 18:36:54 +00001121
Tal Einatede0b6f2018-12-31 17:12:08 +02001122/*[clinic input]
1123sys.setswitchinterval
1124
1125 interval: double
1126 /
1127
1128Set the ideal thread switching delay inside the Python interpreter.
1129
1130The actual frequency of switching threads can be lower if the
1131interpreter executes long sequences of uninterruptible code
1132(this is implementation-specific and workload-dependent).
1133
1134The parameter must represent the desired switching delay in seconds
1135A typical value is 0.005 (5 milliseconds).
1136[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001137
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001138static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001139sys_setswitchinterval_impl(PyObject *module, double interval)
1140/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001141{
Tal Einatede0b6f2018-12-31 17:12:08 +02001142 if (interval <= 0.0) {
Victor Stinneracde3f12021-02-19 15:07:59 +01001143 PyErr_SetString(PyExc_ValueError,
1144 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 return NULL;
1146 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001147 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001148 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001149}
1150
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001151
Tal Einatede0b6f2018-12-31 17:12:08 +02001152/*[clinic input]
1153sys.getswitchinterval -> double
1154
1155Return the current thread switch interval; see sys.setswitchinterval().
1156[clinic start generated code]*/
1157
1158static double
1159sys_getswitchinterval_impl(PyObject *module)
1160/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001161{
Tal Einatede0b6f2018-12-31 17:12:08 +02001162 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001163}
1164
Tal Einatede0b6f2018-12-31 17:12:08 +02001165/*[clinic input]
1166sys.setrecursionlimit
1167
1168 limit as new_limit: int
1169 /
1170
1171Set the maximum depth of the Python interpreter stack to n.
1172
1173This limit prevents infinite recursion from causing an overflow of the C
1174stack and crashing Python. The highest possible limit is platform-
1175dependent.
1176[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001177
Tim Peterse5e065b2003-07-06 18:36:54 +00001178static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001179sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1180/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001181{
Victor Stinner838f2642019-06-13 22:41:23 +02001182 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001183
Victor Stinner50856d52015-10-13 00:11:21 +02001184 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001185 _PyErr_SetString(tstate, PyExc_ValueError,
1186 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return NULL;
1188 }
Victor Stinner50856d52015-10-13 00:11:21 +02001189
1190 /* Issue #25274: When the recursion depth hits the recursion limit in
1191 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1192 set to 1 and a RecursionError is raised. The overflowed flag is reset
1193 to 0 when the recursion depth goes below the low-water mark: see
1194 Py_LeaveRecursiveCall().
1195
1196 Reject too low new limit if the current recursion depth is higher than
1197 the new low-water mark. Otherwise it may not be possible anymore to
1198 reset the overflowed flag to 0. */
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001199 if (tstate->recursion_depth >= new_limit) {
Victor Stinner838f2642019-06-13 22:41:23 +02001200 _PyErr_Format(tstate, PyExc_RecursionError,
1201 "cannot set the recursion limit to %i at "
1202 "the recursion depth %i: the limit is too low",
1203 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001204 return NULL;
1205 }
1206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001208 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001209}
1210
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001211/*[clinic input]
1212sys.set_coroutine_origin_tracking_depth
1213
1214 depth: int
1215
1216Enable or disable origin tracking for coroutine objects in this thread.
1217
Tal Einatede0b6f2018-12-31 17:12:08 +02001218Coroutine objects will track 'depth' frames of traceback information
1219about where they came from, available in their cr_origin attribute.
1220
1221Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001222[clinic start generated code]*/
1223
1224static PyObject *
1225sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001226/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001227{
Victor Stinner838f2642019-06-13 22:41:23 +02001228 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001229 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001230 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001231 return NULL;
1232 }
Victor Stinner838f2642019-06-13 22:41:23 +02001233 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001234 Py_RETURN_NONE;
1235}
1236
1237/*[clinic input]
1238sys.get_coroutine_origin_tracking_depth -> int
1239
1240Check status of origin tracking for coroutine objects in this thread.
1241[clinic start generated code]*/
1242
1243static int
1244sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1245/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1246{
1247 return _PyEval_GetCoroutineOriginTrackingDepth();
1248}
1249
Yury Selivanoveb636452016-09-08 22:01:51 -07001250static PyTypeObject AsyncGenHooksType;
1251
1252PyDoc_STRVAR(asyncgen_hooks_doc,
1253"asyncgen_hooks\n\
1254\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001255A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001256generators hooks. The attributes are read only.");
1257
1258static PyStructSequence_Field asyncgen_hooks_fields[] = {
1259 {"firstiter", "Hook to intercept first iteration"},
1260 {"finalizer", "Hook to intercept finalization"},
1261 {0}
1262};
1263
1264static PyStructSequence_Desc asyncgen_hooks_desc = {
1265 "asyncgen_hooks", /* name */
1266 asyncgen_hooks_doc, /* doc */
1267 asyncgen_hooks_fields , /* fields */
1268 2
1269};
1270
Yury Selivanoveb636452016-09-08 22:01:51 -07001271static PyObject *
1272sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1273{
1274 static char *keywords[] = {"firstiter", "finalizer", NULL};
1275 PyObject *firstiter = NULL;
1276 PyObject *finalizer = NULL;
1277
1278 if (!PyArg_ParseTupleAndKeywords(
1279 args, kw, "|OO", keywords,
1280 &firstiter, &finalizer)) {
1281 return NULL;
1282 }
1283
1284 if (finalizer && finalizer != Py_None) {
1285 if (!PyCallable_Check(finalizer)) {
Victor Stinneracde3f12021-02-19 15:07:59 +01001286 PyErr_Format(PyExc_TypeError,
1287 "callable finalizer expected, got %.50s",
1288 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001289 return NULL;
1290 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001291 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1292 return NULL;
1293 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001294 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001295 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1296 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001297 }
1298
1299 if (firstiter && firstiter != Py_None) {
1300 if (!PyCallable_Check(firstiter)) {
Victor Stinneracde3f12021-02-19 15:07:59 +01001301 PyErr_Format(PyExc_TypeError,
1302 "callable firstiter expected, got %.50s",
1303 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001304 return NULL;
1305 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001306 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1307 return NULL;
1308 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001309 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001310 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1311 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001312 }
1313
1314 Py_RETURN_NONE;
1315}
1316
1317PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001318"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001319\n\
1320Set a finalizer for async generators objects."
1321);
1322
Tal Einatede0b6f2018-12-31 17:12:08 +02001323/*[clinic input]
1324sys.get_asyncgen_hooks
1325
1326Return the installed asynchronous generators hooks.
1327
1328This returns a namedtuple of the form (firstiter, finalizer).
1329[clinic start generated code]*/
1330
Yury Selivanoveb636452016-09-08 22:01:51 -07001331static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001332sys_get_asyncgen_hooks_impl(PyObject *module)
1333/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001334{
1335 PyObject *res;
1336 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1337 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1338
1339 res = PyStructSequence_New(&AsyncGenHooksType);
1340 if (res == NULL) {
1341 return NULL;
1342 }
1343
1344 if (firstiter == NULL) {
1345 firstiter = Py_None;
1346 }
1347
1348 if (finalizer == NULL) {
1349 finalizer = Py_None;
1350 }
1351
1352 Py_INCREF(firstiter);
1353 PyStructSequence_SET_ITEM(res, 0, firstiter);
1354
1355 Py_INCREF(finalizer);
1356 PyStructSequence_SET_ITEM(res, 1, finalizer);
1357
1358 return res;
1359}
1360
Yury Selivanoveb636452016-09-08 22:01:51 -07001361
Mark Dickinsondc787d22010-05-23 13:33:13 +00001362static PyTypeObject Hash_InfoType;
1363
1364PyDoc_STRVAR(hash_info_doc,
1365"hash_info\n\
1366\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001367A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001368hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001369
1370static PyStructSequence_Field hash_info_fields[] = {
1371 {"width", "width of the type used for hashing, in bits"},
1372 {"modulus", "prime number giving the modulus on which the hash "
1373 "function is based"},
1374 {"inf", "value to be used for hash of a positive infinity"},
1375 {"nan", "value to be used for hash of a nan"},
1376 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001377 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1378 "memoryviews"},
1379 {"hash_bits", "internal output size of hash algorithm"},
1380 {"seed_bits", "seed size of hash algorithm"},
1381 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001382 {NULL, NULL}
1383};
1384
1385static PyStructSequence_Desc hash_info_desc = {
1386 "sys.hash_info",
1387 hash_info_doc,
1388 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001389 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001390};
1391
Matthias Klosed885e952010-07-06 10:53:30 +00001392static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001393get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001394{
1395 PyObject *hash_info;
1396 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001397 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001398 hash_info = PyStructSequence_New(&Hash_InfoType);
1399 if (hash_info == NULL)
1400 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001401 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001402 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001403 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001404 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001405 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001406 PyStructSequence_SET_ITEM(hash_info, field++,
1407 PyLong_FromLong(_PyHASH_INF));
1408 PyStructSequence_SET_ITEM(hash_info, field++,
1409 PyLong_FromLong(_PyHASH_NAN));
1410 PyStructSequence_SET_ITEM(hash_info, field++,
1411 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001412 PyStructSequence_SET_ITEM(hash_info, field++,
1413 PyUnicode_FromString(hashfunc->name));
1414 PyStructSequence_SET_ITEM(hash_info, field++,
1415 PyLong_FromLong(hashfunc->hash_bits));
1416 PyStructSequence_SET_ITEM(hash_info, field++,
1417 PyLong_FromLong(hashfunc->seed_bits));
1418 PyStructSequence_SET_ITEM(hash_info, field++,
1419 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001420 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001421 Py_CLEAR(hash_info);
1422 return NULL;
1423 }
1424 return hash_info;
1425}
Tal Einatede0b6f2018-12-31 17:12:08 +02001426/*[clinic input]
1427sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001428
Tal Einatede0b6f2018-12-31 17:12:08 +02001429Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001430
Tal Einatede0b6f2018-12-31 17:12:08 +02001431The recursion limit is the maximum depth of the Python interpreter
1432stack. This limit prevents infinite recursion from causing an overflow
1433of the C stack and crashing Python.
1434[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001435
1436static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001437sys_getrecursionlimit_impl(PyObject *module)
1438/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001441}
1442
Mark Hammond8696ebc2002-10-08 02:44:31 +00001443#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001444
Eric Smithf7bb5782010-01-27 00:44:57 +00001445static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1446
1447static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 {"major", "Major version number"},
1449 {"minor", "Minor version number"},
1450 {"build", "Build number"},
1451 {"platform", "Operating system platform"},
1452 {"service_pack", "Latest Service Pack installed on the system"},
1453 {"service_pack_major", "Service Pack major version number"},
1454 {"service_pack_minor", "Service Pack minor version number"},
1455 {"suite_mask", "Bit mask identifying available product suites"},
1456 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001457 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001459};
1460
1461static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001462 "sys.getwindowsversion", /* name */
1463 sys_getwindowsversion__doc__, /* doc */
1464 windows_version_fields, /* fields */
1465 5 /* For backward compatibility,
1466 only the first 5 items are accessible
1467 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001468};
1469
Steve Dower3e96f322015-03-02 08:01:10 -08001470/* Disable deprecation warnings about GetVersionEx as the result is
1471 being passed straight through to the caller, who is responsible for
1472 using it correctly. */
1473#pragma warning(push)
1474#pragma warning(disable:4996)
1475
Tal Einatede0b6f2018-12-31 17:12:08 +02001476/*[clinic input]
1477sys.getwindowsversion
1478
1479Return info about the running version of Windows as a named tuple.
1480
1481The members are named: major, minor, build, platform, service_pack,
1482service_pack_major, service_pack_minor, suite_mask, product_type and
1483platform_version. For backward compatibility, only the first 5 items
1484are available by indexing. All elements are numbers, except
1485service_pack and platform_type which are strings, and platform_version
1486which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1487workstation, 2 for a domain controller, 3 for a server.
1488Platform_version is a 3-tuple containing a version number that is
1489intended for identifying the OS rather than feature detection.
1490[clinic start generated code]*/
1491
Mark Hammond8696ebc2002-10-08 02:44:31 +00001492static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001493sys_getwindowsversion_impl(PyObject *module)
1494/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001495{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001496 PyObject *version;
1497 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001498 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001499 DWORD realMajor, realMinor, realBuild;
1500 HANDLE hKernel32;
1501 wchar_t kernel32_path[MAX_PATH];
1502 LPVOID verblock;
1503 DWORD verblock_size;
1504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001506 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 version = PyStructSequence_New(&WindowsVersionType);
1510 if (version == NULL)
1511 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1514 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1515 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1516 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001517 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1519 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1520 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1521 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001522
Steve Dower74f4af72016-09-17 17:27:48 -07001523 realMajor = ver.dwMajorVersion;
1524 realMinor = ver.dwMinorVersion;
1525 realBuild = ver.dwBuildNumber;
1526
1527 // GetVersion will lie if we are running in a compatibility mode.
1528 // We need to read the version info from a system file resource
1529 // to accurately identify the OS version. If we fail for any reason,
1530 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001531 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001532 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001533 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001534 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1535 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1536 (verblock = PyMem_RawMalloc(verblock_size))) {
1537 VS_FIXEDFILEINFO *ffi;
1538 UINT ffi_len;
1539
1540 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1541 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1542 realMajor = HIWORD(ffi->dwProductVersionMS);
1543 realMinor = LOWORD(ffi->dwProductVersionMS);
1544 realBuild = HIWORD(ffi->dwProductVersionLS);
1545 }
1546 PyMem_RawFree(verblock);
1547 }
Segev Finer48fb7662017-06-04 20:52:27 +03001548 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1549 realMajor,
1550 realMinor,
1551 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001552 ));
1553
Victor Stinneracde3f12021-02-19 15:07:59 +01001554 if (PyErr_Occurred()) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001555 Py_DECREF(version);
1556 return NULL;
1557 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001559}
1560
Steve Dower3e96f322015-03-02 08:01:10 -08001561#pragma warning(pop)
1562
Tal Einatede0b6f2018-12-31 17:12:08 +02001563/*[clinic input]
1564sys._enablelegacywindowsfsencoding
1565
1566Changes the default filesystem encoding to mbcs:replace.
1567
1568This is done for consistency with earlier versions of Python. See PEP
1569529 for more information.
1570
1571This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1572environment variable before launching Python.
1573[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001574
1575static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001576sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1577/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001578{
Victor Stinner709d23d2019-05-02 14:56:30 -04001579 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001580 return NULL;
1581 }
Steve Dowercc16be82016-09-08 10:35:16 -07001582 Py_RETURN_NONE;
1583}
1584
Mark Hammond8696ebc2002-10-08 02:44:31 +00001585#endif /* MS_WINDOWS */
1586
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001587#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001588
1589/*[clinic input]
1590sys.setdlopenflags
1591
1592 flags as new_val: int
1593 /
1594
1595Set the flags used by the interpreter for dlopen calls.
1596
1597This is used, for example, when the interpreter loads extension
1598modules. Among other things, this will enable a lazy resolving of
1599symbols when importing a module, if called as sys.setdlopenflags(0).
1600To share symbols across extension modules, call as
1601sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1602modules can be found in the os module (RTLD_xxx constants, e.g.
1603os.RTLD_LAZY).
1604[clinic start generated code]*/
1605
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001606static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001607sys_setdlopenflags_impl(PyObject *module, int new_val)
1608/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001609{
Victor Stinner838f2642019-06-13 22:41:23 +02001610 PyThreadState *tstate = _PyThreadState_GET();
1611 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001612 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001613}
1614
Tal Einatede0b6f2018-12-31 17:12:08 +02001615
1616/*[clinic input]
1617sys.getdlopenflags
1618
1619Return the current value of the flags that are used for dlopen calls.
1620
1621The flag constants are defined in the os module.
1622[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001623
1624static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001625sys_getdlopenflags_impl(PyObject *module)
1626/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001627{
Victor Stinner838f2642019-06-13 22:41:23 +02001628 PyThreadState *tstate = _PyThreadState_GET();
1629 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001630}
1631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001633
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001634#ifdef USE_MALLOPT
1635/* Link with -lmalloc (or -lmpc) on an SGI */
1636#include <malloc.h>
1637
Tal Einatede0b6f2018-12-31 17:12:08 +02001638/*[clinic input]
1639sys.mdebug
1640
1641 flag: int
1642 /
1643[clinic start generated code]*/
1644
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001645static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001646sys_mdebug_impl(PyObject *module, int flag)
1647/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001651 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001652}
1653#endif /* USE_MALLOPT */
1654
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001655size_t
1656_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001660 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001661 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001664 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001665 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001666 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001667
Benjamin Petersonce798522012-01-22 11:24:29 -05001668 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001670 if (!_PyErr_Occurred(tstate)) {
1671 _PyErr_Format(tstate, PyExc_TypeError,
1672 "Type %.100s doesn't define __sizeof__",
1673 Py_TYPE(o)->tp_name);
1674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
1676 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001677 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 Py_DECREF(method);
1679 }
1680
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001681 if (res == NULL)
1682 return (size_t)-1;
1683
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001684 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001685 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001686 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001687 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001689 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001690 _PyErr_SetString(tstate, PyExc_ValueError,
1691 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001692 return (size_t)-1;
1693 }
1694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 /* add gc_head size */
Hai Shi675d9a32020-04-15 02:11:20 +08001696 if (_PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001697 return ((size_t)size) + sizeof(PyGC_Head);
1698 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001699}
1700
1701static PyObject *
1702sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1703{
1704 static char *kwlist[] = {"object", "default", 0};
1705 size_t size;
1706 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001707 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001708
1709 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001710 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001711 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001712 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001713
1714 size = _PySys_GetSizeOf(o);
1715
Victor Stinner838f2642019-06-13 22:41:23 +02001716 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001717 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001718 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1719 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001720 Py_INCREF(dflt);
1721 return dflt;
1722 }
1723 else
1724 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001726
1727 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001728}
1729
1730PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001731"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001732\n\
1733Return the size of object in bytes.");
1734
Tal Einatede0b6f2018-12-31 17:12:08 +02001735/*[clinic input]
1736sys.getrefcount -> Py_ssize_t
1737
1738 object: object
1739 /
1740
1741Return the reference count of object.
1742
1743The count returned is generally one higher than you might expect,
1744because it includes the (temporary) reference as an argument to
1745getrefcount().
1746[clinic start generated code]*/
1747
1748static Py_ssize_t
1749sys_getrefcount_impl(PyObject *module, PyObject *object)
1750/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001751{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001752 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001753}
1754
Tim Peters4be93d02002-07-07 19:59:50 +00001755#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001756/*[clinic input]
1757sys.gettotalrefcount -> Py_ssize_t
1758[clinic start generated code]*/
1759
1760static Py_ssize_t
1761sys_gettotalrefcount_impl(PyObject *module)
1762/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001763{
Tal Einatede0b6f2018-12-31 17:12:08 +02001764 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001765}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001766#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001767
Tal Einatede0b6f2018-12-31 17:12:08 +02001768/*[clinic input]
1769sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001770
Tal Einatede0b6f2018-12-31 17:12:08 +02001771Return the number of memory blocks currently allocated.
1772[clinic start generated code]*/
1773
1774static Py_ssize_t
1775sys_getallocatedblocks_impl(PyObject *module)
1776/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001777{
Tal Einatede0b6f2018-12-31 17:12:08 +02001778 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001779}
1780
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001781
Tal Einatede0b6f2018-12-31 17:12:08 +02001782/*[clinic input]
1783sys._getframe
1784
1785 depth: int = 0
1786 /
1787
1788Return a frame object from the call stack.
1789
1790If optional integer depth is given, return the frame object that many
1791calls below the top of the stack. If that is deeper than the call
1792stack, ValueError is raised. The default for depth is zero, returning
1793the frame at the top of the call stack.
1794
1795This function should be used for internal and specialized purposes
1796only.
1797[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001798
1799static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001800sys__getframe_impl(PyObject *module, int depth)
1801/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001802{
Victor Stinner838f2642019-06-13 22:41:23 +02001803 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner70364772020-04-29 03:28:46 +02001804 PyFrameObject *f = PyThreadState_GetFrame(tstate);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001805
Victor Stinner08faf002020-03-26 18:57:32 +01001806 if (_PySys_Audit(tstate, "sys._getframe", "O", f) < 0) {
Victor Stinner70364772020-04-29 03:28:46 +02001807 Py_DECREF(f);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001808 return NULL;
1809 }
1810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 while (depth > 0 && f != NULL) {
Victor Stinner70364772020-04-29 03:28:46 +02001812 PyFrameObject *back = PyFrame_GetBack(f);
1813 Py_DECREF(f);
1814 f = back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 --depth;
1816 }
1817 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001818 _PyErr_SetString(tstate, PyExc_ValueError,
1819 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return NULL;
1821 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001823}
1824
Tal Einatede0b6f2018-12-31 17:12:08 +02001825/*[clinic input]
1826sys._current_frames
1827
1828Return a dict mapping each thread's thread id to its current stack frame.
1829
1830This function should be used for specialized purposes only.
1831[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001832
1833static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001834sys__current_frames_impl(PyObject *module)
1835/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001838}
1839
Tal Einatede0b6f2018-12-31 17:12:08 +02001840/*[clinic input]
Julien Danjou64366fa2020-11-02 15:16:25 +01001841sys._current_exceptions
1842
1843Return a dict mapping each thread's identifier to its current raised exception.
1844
1845This function should be used for specialized purposes only.
1846[clinic start generated code]*/
1847
1848static PyObject *
1849sys__current_exceptions_impl(PyObject *module)
1850/*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
1851{
1852 return _PyThread_CurrentExceptions();
1853}
1854
1855/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +02001856sys.call_tracing
1857
1858 func: object
1859 args as funcargs: object(subclass_of='&PyTuple_Type')
1860 /
1861
1862Call func(*args), while tracing is enabled.
1863
1864The tracing state is saved, and restored afterwards. This is intended
1865to be called from a debugger from a checkpoint, to recursively debug
1866some other code.
1867[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001868
1869static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001870sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1871/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001874}
1875
Victor Stinner048afd92016-11-28 11:59:04 +01001876
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001877#ifdef __cplusplus
1878extern "C" {
1879#endif
1880
Tal Einatede0b6f2018-12-31 17:12:08 +02001881/*[clinic input]
1882sys._debugmallocstats
1883
1884Print summary info to stderr about the state of pymalloc's structures.
1885
1886In Py_DEBUG mode, also perform some expensive internal consistency
1887checks.
1888[clinic start generated code]*/
1889
David Malcolm49526f42012-06-22 14:55:41 -04001890static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001891sys__debugmallocstats_impl(PyObject *module)
1892/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001893{
1894#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001895 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001896 fputc('\n', stderr);
1897 }
David Malcolm49526f42012-06-22 14:55:41 -04001898#endif
1899 _PyObject_DebugTypeStats(stderr);
1900
1901 Py_RETURN_NONE;
1902}
David Malcolm49526f42012-06-22 14:55:41 -04001903
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001904#ifdef Py_TRACE_REFS
Joannah Nanjekye46b5c6b2020-12-22 18:31:46 -04001905/* Defined in objects.c because it uses static globals in that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001906extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001907#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001908
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001909#ifdef DYNAMIC_EXECUTION_PROFILE
Joannah Nanjekye46b5c6b2020-12-22 18:31:46 -04001910/* Defined in ceval.c because it uses static globals in that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001911extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001912#endif
1913
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001914#ifdef __cplusplus
1915}
1916#endif
1917
Tal Einatede0b6f2018-12-31 17:12:08 +02001918
1919/*[clinic input]
1920sys._clear_type_cache
1921
1922Clear the internal type lookup cache.
1923[clinic start generated code]*/
1924
Christian Heimes15ebc882008-02-04 18:48:49 +00001925static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001926sys__clear_type_cache_impl(PyObject *module)
1927/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyType_ClearCache();
1930 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001931}
1932
Tal Einatede0b6f2018-12-31 17:12:08 +02001933/*[clinic input]
1934sys.is_finalizing
1935
1936Return True if Python is exiting.
1937[clinic start generated code]*/
1938
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001939static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001940sys_is_finalizing_impl(PyObject *module)
1941/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001942{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001943 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001944}
1945
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001946#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001947/*[clinic input]
1948sys.getandroidapilevel
1949
1950Return the build time API version of Android as an integer.
1951[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001952
1953static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001954sys_getandroidapilevel_impl(PyObject *module)
1955/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001956{
1957 return PyLong_FromLong(ANDROID_API_LEVEL);
1958}
1959#endif /* ANDROID_API_LEVEL */
1960
1961
Steve Dowerb82e17e2019-05-23 08:45:22 -07001962
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001963static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001965 SYS_ADDAUDITHOOK_METHODDEF
1966 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001967 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001968 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001969 SYS__CLEAR_TYPE_CACHE_METHODDEF
1970 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001971 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001972 SYS_DISPLAYHOOK_METHODDEF
1973 SYS_EXC_INFO_METHODDEF
1974 SYS_EXCEPTHOOK_METHODDEF
1975 SYS_EXIT_METHODDEF
1976 SYS_GETDEFAULTENCODING_METHODDEF
1977 SYS_GETDLOPENFLAGS_METHODDEF
1978 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001979#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001981#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001982 SYS_GETFILESYSTEMENCODING_METHODDEF
1983 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001984#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001986#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001987 SYS_GETTOTALREFCOUNT_METHODDEF
1988 SYS_GETREFCOUNT_METHODDEF
1989 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001990 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001992 SYS__GETFRAME_METHODDEF
1993 SYS_GETWINDOWSVERSION_METHODDEF
1994 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1995 SYS_INTERN_METHODDEF
1996 SYS_IS_FINALIZING_METHODDEF
1997 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001998 SYS_SETSWITCHINTERVAL_METHODDEF
1999 SYS_GETSWITCHINTERVAL_METHODDEF
2000 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002002 SYS_GETPROFILE_METHODDEF
2003 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002005 SYS_GETTRACE_METHODDEF
2006 SYS_CALL_TRACING_METHODDEF
2007 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002008 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2009 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002010 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002011 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002012 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2013 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002014 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002016};
2017
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002018
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002019static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002020list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 PyObject *list = PyList_New(0);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002023 if (list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 return NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002025 }
2026 for (Py_ssize_t i = 0; PyImport_Inittab[i].name != NULL; i++) {
2027 PyObject *name = PyUnicode_FromString(PyImport_Inittab[i].name);
2028 if (name == NULL) {
2029 goto error;
2030 }
2031 if (PyList_Append(list, name) < 0) {
2032 Py_DECREF(name);
2033 goto error;
2034 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 Py_DECREF(name);
2036 }
2037 if (PyList_Sort(list) != 0) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002038 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002040 PyObject *tuple = PyList_AsTuple(list);
2041 Py_DECREF(list);
2042 return tuple;
2043
2044error:
2045 Py_DECREF(list);
2046 return NULL;
Guido van Rossum34679b71993-01-26 13:33:44 +00002047}
2048
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002049
2050static PyObject *
Victor Stinner9852cb32021-01-25 23:12:50 +01002051list_stdlib_module_names(void)
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002052{
Victor Stinner9852cb32021-01-25 23:12:50 +01002053 Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002054 PyObject *names = PyTuple_New(len);
2055 if (names == NULL) {
2056 return NULL;
2057 }
2058
2059 for (Py_ssize_t i = 0; i < len; i++) {
Victor Stinner9852cb32021-01-25 23:12:50 +01002060 PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002061 if (name == NULL) {
2062 Py_DECREF(names);
2063 return NULL;
2064 }
2065 PyTuple_SET_ITEM(names, i, name);
2066 }
2067
2068 PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
2069 "(O)", names);
2070 Py_DECREF(names);
2071 return set;
2072}
2073
2074
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002075/* Pre-initialization support for sys.warnoptions and sys._xoptions
2076 *
2077 * Modern internal code paths:
2078 * These APIs get called after _Py_InitializeCore and get to use the
2079 * regular CPython list, dict, and unicode APIs.
2080 *
2081 * Legacy embedding code paths:
2082 * The multi-phase initialization API isn't public yet, so embedding
2083 * apps still need to be able configure sys.warnoptions and sys._xoptions
2084 * before they call Py_Initialize. To support this, we stash copies of
2085 * the supplied wchar * sequences in linked lists, and then migrate the
2086 * contents of those lists to the sys module in _PyInitializeCore.
2087 *
2088 */
2089
2090struct _preinit_entry {
2091 wchar_t *value;
2092 struct _preinit_entry *next;
2093};
2094
2095typedef struct _preinit_entry *_Py_PreInitEntry;
2096
2097static _Py_PreInitEntry _preinit_warnoptions = NULL;
2098static _Py_PreInitEntry _preinit_xoptions = NULL;
2099
2100static _Py_PreInitEntry
2101_alloc_preinit_entry(const wchar_t *value)
2102{
2103 /* To get this to work, we have to initialize the runtime implicitly */
2104 _PyRuntime_Initialize();
2105
2106 /* Force default allocator, so we can ensure that it also gets used to
2107 * destroy the linked list in _clear_preinit_entries.
2108 */
2109 PyMemAllocatorEx old_alloc;
2110 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2111
2112 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2113 if (node != NULL) {
2114 node->value = _PyMem_RawWcsdup(value);
2115 if (node->value == NULL) {
2116 PyMem_RawFree(node);
2117 node = NULL;
2118 };
2119 };
2120
2121 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2122 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002123}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002124
2125static int
2126_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2127{
2128 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2129 if (new_entry == NULL) {
2130 return -1;
2131 }
2132 /* We maintain the linked list in this order so it's easy to play back
2133 * the add commands in the same order later on in _Py_InitializeCore
2134 */
2135 _Py_PreInitEntry last_entry = *optionlist;
2136 if (last_entry == NULL) {
2137 *optionlist = new_entry;
2138 } else {
2139 while (last_entry->next != NULL) {
2140 last_entry = last_entry->next;
2141 }
2142 last_entry->next = new_entry;
2143 }
2144 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002145}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002146
2147static void
2148_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2149{
2150 _Py_PreInitEntry current = *optionlist;
2151 *optionlist = NULL;
2152 /* Deallocate the nodes and their contents using the default allocator */
2153 PyMemAllocatorEx old_alloc;
2154 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2155 while (current != NULL) {
2156 _Py_PreInitEntry next = current->next;
2157 PyMem_RawFree(current->value);
2158 PyMem_RawFree(current);
2159 current = next;
2160 }
2161 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002162}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002163
Victor Stinner120b7072019-08-23 18:03:08 +01002164
2165PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002166_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002167{
Victor Stinner120b7072019-08-23 18:03:08 +01002168 PyStatus status;
2169 _Py_PreInitEntry entry;
2170
2171 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002172 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002173 if (_PyStatus_EXCEPTION(status)) {
2174 return status;
2175 }
2176 }
2177
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002178 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002179 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002180}
2181
Victor Stinner120b7072019-08-23 18:03:08 +01002182
2183PyStatus
2184_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002185{
Victor Stinner120b7072019-08-23 18:03:08 +01002186 PyStatus status;
2187 _Py_PreInitEntry entry;
2188
2189 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2190 status = PyWideStringList_Append(&config->xoptions, entry->value);
2191 if (_PyStatus_EXCEPTION(status)) {
2192 return status;
2193 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002194 }
2195
Victor Stinner120b7072019-08-23 18:03:08 +01002196 _clear_preinit_entries(&_preinit_xoptions);
2197 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002198}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002199
Victor Stinner120b7072019-08-23 18:03:08 +01002200
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002201static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002202get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002203{
Victor Stinner838f2642019-06-13 22:41:23 +02002204 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002205 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002206 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2207 * interpreter config. When that happens, we need to properly set
2208 * the `warnoptions` reference in the main interpreter config as well.
2209 *
2210 * For Python 3.7, we shouldn't be able to get here due to the
2211 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2212 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2213 * call optional for embedding applications, thus making this
2214 * reachable again.
2215 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002216 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002217 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002218 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002219 }
2220 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002221 Py_DECREF(warnoptions);
2222 return NULL;
2223 }
2224 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002225 }
2226 return warnoptions;
2227}
Guido van Rossum23fff912000-12-15 22:02:05 +00002228
2229void
2230PySys_ResetWarnOptions(void)
2231{
Victor Stinner50b48572018-11-01 01:51:40 +01002232 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002233 if (tstate == NULL) {
2234 _clear_preinit_entries(&_preinit_warnoptions);
2235 return;
2236 }
2237
Victor Stinner838f2642019-06-13 22:41:23 +02002238 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (warnoptions == NULL || !PyList_Check(warnoptions))
2240 return;
2241 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002242}
2243
Victor Stinnere1b29952018-10-30 14:31:42 +01002244static int
Victor Stinner838f2642019-06-13 22:41:23 +02002245_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002246{
Victor Stinner838f2642019-06-13 22:41:23 +02002247 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002248 if (warnoptions == NULL) {
2249 return -1;
2250 }
2251 if (PyList_Append(warnoptions, option)) {
2252 return -1;
2253 }
2254 return 0;
2255}
2256
2257void
2258PySys_AddWarnOptionUnicode(PyObject *option)
2259{
Victor Stinner838f2642019-06-13 22:41:23 +02002260 PyThreadState *tstate = _PyThreadState_GET();
2261 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002262 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002263 if (tstate) {
2264 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002265 }
2266 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002267}
2268
2269void
2270PySys_AddWarnOption(const wchar_t *s)
2271{
Victor Stinner50b48572018-11-01 01:51:40 +01002272 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002273 if (tstate == NULL) {
2274 _append_preinit_entry(&_preinit_warnoptions, s);
2275 return;
2276 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002277 PyObject *unicode;
2278 unicode = PyUnicode_FromWideChar(s, -1);
2279 if (unicode == NULL)
2280 return;
2281 PySys_AddWarnOptionUnicode(unicode);
2282 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002283}
2284
Christian Heimes33fe8092008-04-13 13:53:33 +00002285int
2286PySys_HasWarnOptions(void)
2287{
Victor Stinner838f2642019-06-13 22:41:23 +02002288 PyThreadState *tstate = _PyThreadState_GET();
2289 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002290 return (warnoptions != NULL && PyList_Check(warnoptions)
2291 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002292}
2293
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002294static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002295get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002296{
Victor Stinner838f2642019-06-13 22:41:23 +02002297 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002298 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002299 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2300 * interpreter config. When that happens, we need to properly set
2301 * the `xoptions` reference in the main interpreter config as well.
2302 *
2303 * For Python 3.7, we shouldn't be able to get here due to the
2304 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2305 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2306 * call optional for embedding applications, thus making this
2307 * reachable again.
2308 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002309 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002310 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002311 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002312 }
2313 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002314 Py_DECREF(xoptions);
2315 return NULL;
2316 }
2317 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002318 }
2319 return xoptions;
2320}
2321
Victor Stinnere1b29952018-10-30 14:31:42 +01002322static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002323_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002324{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002325 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002326
Victor Stinner838f2642019-06-13 22:41:23 +02002327 PyThreadState *tstate = _PyThreadState_GET();
2328 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002329 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002330 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002331 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002332
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002333 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002334 if (!name_end) {
2335 name = PyUnicode_FromWideChar(s, -1);
2336 value = Py_True;
2337 Py_INCREF(value);
2338 }
2339 else {
2340 name = PyUnicode_FromWideChar(s, name_end - s);
2341 value = PyUnicode_FromWideChar(name_end + 1, -1);
2342 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002343 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002344 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002345 }
2346 if (PyDict_SetItem(opts, name, value) < 0) {
2347 goto error;
2348 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002349 Py_DECREF(name);
2350 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002351 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002352
2353error:
2354 Py_XDECREF(name);
2355 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002356 return -1;
2357}
2358
2359void
2360PySys_AddXOption(const wchar_t *s)
2361{
Victor Stinner50b48572018-11-01 01:51:40 +01002362 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002363 if (tstate == NULL) {
2364 _append_preinit_entry(&_preinit_xoptions, s);
2365 return;
2366 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002367 if (_PySys_AddXOptionWithError(s) < 0) {
2368 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002369 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002370 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002371}
2372
2373PyObject *
2374PySys_GetXOptions(void)
2375{
Victor Stinner838f2642019-06-13 22:41:23 +02002376 PyThreadState *tstate = _PyThreadState_GET();
2377 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002378}
2379
Guido van Rossum40552d01998-08-06 03:34:39 +00002380/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2381 Two literals concatenated works just fine. If you have a K&R compiler
2382 or other abomination that however *does* understand longer strings,
2383 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002384PyDoc_VAR(sys_doc) =
2385PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002386"This module provides access to some objects used or maintained by the\n\
2387interpreter and to functions that interact strongly with the interpreter.\n\
2388\n\
2389Dynamic objects:\n\
2390\n\
2391argv -- command line arguments; argv[0] is the script pathname if known\n\
2392path -- module search path; path[0] is the script directory, else ''\n\
2393modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002394\n\
2395displayhook -- called to show results in an interactive session\n\
2396excepthook -- called to handle any uncaught exception other than SystemExit\n\
2397 To customize printing in an interactive session or to install a custom\n\
2398 top-level exception handler, assign other functions to replace these.\n\
2399\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002400stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002401stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002402stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002403 By assigning other file objects (or objects that behave like files)\n\
2404 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002405\n\
2406last_type -- type of last uncaught exception\n\
2407last_value -- value of last uncaught exception\n\
2408last_traceback -- traceback of last uncaught exception\n\
2409 These three are only available in an interactive session after a\n\
2410 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002411"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002412)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002413/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002414PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002415"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002416Static objects:\n\
2417\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002418builtin_module_names -- tuple of module names built into this interpreter\n\
2419copyright -- copyright notice pertaining to this interpreter\n\
2420exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002421executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002422float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002423float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002424hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002425hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002426implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002427int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002428maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002429maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002430platform -- platform identifier\n\
2431prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002432thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002433version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002434version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002435"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002436)
Steve Dowercc16be82016-09-08 10:35:16 -07002437#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002438/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002439PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002440"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002441winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002442"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002443)
Steve Dowercc16be82016-09-08 10:35:16 -07002444#endif /* MS_COREDLL */
2445#ifdef MS_WINDOWS
2446/* concatenating string here */
2447PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002448"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002449"
2450)
2451#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002452PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002453"__stdin__ -- the original stdin; don't touch!\n\
2454__stdout__ -- the original stdout; don't touch!\n\
2455__stderr__ -- the original stderr; don't touch!\n\
2456__displayhook__ -- the original displayhook; don't touch!\n\
2457__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002458\n\
2459Functions:\n\
2460\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002461displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002462excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002463exc_info() -- return thread-safe information about the current exception\n\
2464exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002465getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002466getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002467getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002468getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002469getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002470gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002471setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002472setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002473setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002474settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002475"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002476)
Fred Drakeccede592000-08-14 20:59:57 +00002477/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002478
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002479
2480PyDoc_STRVAR(flags__doc__,
2481"sys.flags\n\
2482\n\
2483Flags provided through command line arguments or environment vars.");
2484
2485static PyTypeObject FlagsType;
2486
2487static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 {"inspect", "-i"},
2490 {"interactive", "-i"},
2491 {"optimize", "-O or -OO"},
2492 {"dont_write_bytecode", "-B"},
2493 {"no_user_site", "-s"},
2494 {"no_site", "-S"},
2495 {"ignore_environment", "-E"},
2496 {"verbose", "-v"},
Georg Brandl8aa7e992010-12-28 18:30:18 +00002497 {"bytes_warning", "-b"},
2498 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002499 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002500 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002501 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002502 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002504};
2505
2506static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 "sys.flags", /* name */
2508 flags__doc__, /* doc */
2509 flags_fields, /* fields */
Victor Stinner1def7752020-04-23 03:03:24 +02002510 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002511};
2512
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002513static int
2514set_flags_from_config(PyObject *flags, PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002515{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002516 PyInterpreterState *interp = tstate->interp;
2517 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002518 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002519
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002520 // _PySys_UpdateConfig() modifies sys.flags in-place:
2521 // Py_XDECREF() is needed in this case.
2522 Py_ssize_t pos = 0;
2523#define SetFlagObj(expr) \
2524 do { \
2525 PyObject *value = (expr); \
2526 if (value == NULL) { \
2527 return -1; \
2528 } \
2529 Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
2530 PyStructSequence_SET_ITEM(flags, pos, value); \
2531 pos++; \
2532 } while (0)
2533#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002534
Victor Stinnerfbca9082018-08-30 00:50:45 +02002535 SetFlag(config->parser_debug);
2536 SetFlag(config->inspect);
2537 SetFlag(config->interactive);
2538 SetFlag(config->optimization_level);
2539 SetFlag(!config->write_bytecode);
2540 SetFlag(!config->user_site_directory);
2541 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002542 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002543 SetFlag(config->verbose);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002544 SetFlag(config->bytes_warning);
2545 SetFlag(config->quiet);
2546 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002547 SetFlag(config->isolated);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002548 SetFlagObj(PyBool_FromLong(config->dev_mode));
Victor Stinner20004952019-03-26 02:31:11 +01002549 SetFlag(preconfig->utf8_mode);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002550#undef SetFlagObj
Victor Stinner91106cd2017-12-13 12:29:09 +01002551#undef SetFlag
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002552 return 0;
2553}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002554
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002555
2556static PyObject*
2557make_flags(PyThreadState *tstate)
2558{
2559 PyObject *flags = PyStructSequence_New(&FlagsType);
2560 if (flags == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 return NULL;
2562 }
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002563
2564 if (set_flags_from_config(flags, tstate) < 0) {
2565 Py_DECREF(flags);
2566 return NULL;
2567 }
2568 return flags;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002569}
2570
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002571
Eric Smith0e5b5622009-02-06 01:32:42 +00002572PyDoc_STRVAR(version_info__doc__,
2573"sys.version_info\n\
2574\n\
2575Version information as a named tuple.");
2576
2577static PyTypeObject VersionInfoType;
2578
2579static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 {"major", "Major release number"},
2581 {"minor", "Minor release number"},
2582 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002583 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 {"serial", "Serial release number"},
2585 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002586};
2587
2588static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 "sys.version_info", /* name */
2590 version_info__doc__, /* doc */
2591 version_info_fields, /* fields */
2592 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002593};
2594
2595static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002596make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002597{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 PyObject *version_info;
2599 char *s;
2600 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 version_info = PyStructSequence_New(&VersionInfoType);
2603 if (version_info == NULL) {
2604 return NULL;
2605 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 /*
2608 * These release level checks are mutually exclusive and cover
2609 * the field, so don't get too fancy with the pre-processor!
2610 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002611#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002613#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002615#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002617#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002619#endif
2620
2621#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002623#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002626 SetIntItem(PY_MAJOR_VERSION);
2627 SetIntItem(PY_MINOR_VERSION);
2628 SetIntItem(PY_MICRO_VERSION);
2629 SetStrItem(s);
2630 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002631#undef SetIntItem
2632#undef SetStrItem
2633
Victor Stinner838f2642019-06-13 22:41:23 +02002634 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002635 Py_CLEAR(version_info);
2636 return NULL;
2637 }
2638 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002639}
2640
Brett Cannon3adc7b72012-07-09 14:22:12 -04002641/* sys.implementation values */
2642#define NAME "cpython"
2643const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002644#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2645#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002646#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002647const char *_PySys_ImplCacheTag = TAG;
2648#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002649#undef MAJOR
2650#undef MINOR
2651#undef TAG
2652
Barry Warsaw409da152012-06-03 16:18:47 -04002653static PyObject *
2654make_impl_info(PyObject *version_info)
2655{
2656 int res;
2657 PyObject *impl_info, *value, *ns;
2658
2659 impl_info = PyDict_New();
2660 if (impl_info == NULL)
2661 return NULL;
2662
2663 /* populate the dict */
2664
Brett Cannon3adc7b72012-07-09 14:22:12 -04002665 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002666 if (value == NULL)
2667 goto error;
2668 res = PyDict_SetItemString(impl_info, "name", value);
2669 Py_DECREF(value);
2670 if (res < 0)
2671 goto error;
2672
Brett Cannon3adc7b72012-07-09 14:22:12 -04002673 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002674 if (value == NULL)
2675 goto error;
2676 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2677 Py_DECREF(value);
2678 if (res < 0)
2679 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002680
2681 res = PyDict_SetItemString(impl_info, "version", version_info);
2682 if (res < 0)
2683 goto error;
2684
2685 value = PyLong_FromLong(PY_VERSION_HEX);
2686 if (value == NULL)
2687 goto error;
2688 res = PyDict_SetItemString(impl_info, "hexversion", value);
2689 Py_DECREF(value);
2690 if (res < 0)
2691 goto error;
2692
doko@ubuntu.com55532312016-06-14 08:55:19 +02002693#ifdef MULTIARCH
2694 value = PyUnicode_FromString(MULTIARCH);
2695 if (value == NULL)
2696 goto error;
2697 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2698 Py_DECREF(value);
2699 if (res < 0)
2700 goto error;
2701#endif
2702
Barry Warsaw409da152012-06-03 16:18:47 -04002703 /* dict ready */
2704
2705 ns = _PyNamespace_New(impl_info);
2706 Py_DECREF(impl_info);
2707 return ns;
2708
2709error:
2710 Py_CLEAR(impl_info);
2711 return NULL;
2712}
2713
Martin v. Löwis1a214512008-06-11 05:26:20 +00002714static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyModuleDef_HEAD_INIT,
2716 "sys",
2717 sys_doc,
2718 -1, /* multiple "initialization" just copies the module dict. */
2719 sys_methods,
2720 NULL,
2721 NULL,
2722 NULL,
2723 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002724};
2725
Eric Snow6b4be192017-05-22 21:36:03 -07002726/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002727#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002728 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002729 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002730 if (v == NULL) { \
2731 goto err_occurred; \
2732 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002733 res = PyDict_SetItemString(sysdict, key, v); \
2734 Py_DECREF(v); \
2735 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002736 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002737 } \
2738 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002739
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002740#define SET_SYS_FROM_STRING(key, value) \
2741 SET_SYS(key, PyUnicode_FromString(value))
2742
Victor Stinner331a6a52019-05-27 16:39:22 +02002743static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002744_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002745{
Victor Stinnerab672812019-01-23 15:04:40 +01002746 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002747 int res;
2748
Nick Coghland6009512014-11-20 21:39:37 +10002749 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002750
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002751#define COPY_SYS_ATTR(tokey, fromkey) \
2752 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002753
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002754 COPY_SYS_ATTR("__displayhook__", "displayhook");
2755 COPY_SYS_ATTR("__excepthook__", "excepthook");
2756 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2757 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2758
2759#undef COPY_SYS_ATTR
2760
2761 SET_SYS_FROM_STRING("version", Py_GetVersion());
2762 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2763 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2764 _Py_gitversion()));
2765 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2766 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2767 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2768 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2769 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2770 SET_SYS("float_info", PyFloat_GetInfo());
2771 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002772 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002773 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002774 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2775 goto type_init_failed;
2776 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002777 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002778 SET_SYS("hash_info", get_hash_info(tstate));
2779 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2780 SET_SYS("builtin_module_names", list_builtin_module_names());
Victor Stinner9852cb32021-01-25 23:12:50 +01002781 SET_SYS("stdlib_module_names", list_stdlib_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002782#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002783 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002784#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002785 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002786#endif
Fred Drake099325e2000-08-14 15:47:03 +00002787
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002788#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002789 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2790 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002791#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002792#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002793 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002794#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002797 if (VersionInfoType.tp_name == NULL) {
2798 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002799 &version_info_desc) < 0) {
2800 goto type_init_failed;
2801 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002802 }
Victor Stinner838f2642019-06-13 22:41:23 +02002803 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002804 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 /* prevent user from creating new instances */
2806 VersionInfoType.tp_init = NULL;
2807 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002808 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002809 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2810 _PyErr_Clear(tstate);
2811 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002812
Barry Warsaw409da152012-06-03 16:18:47 -04002813 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002814 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002815
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002816 // sys.flags: updated in-place later by _PySys_UpdateConfig()
Victor Stinner1c8f0592013-07-22 22:24:54 +02002817 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002818 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2819 goto type_init_failed;
2820 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002821 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002822 SET_SYS("flags", make_flags(tstate));
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002823 /* prevent user from creating new instances */
2824 FlagsType.tp_init = NULL;
2825 FlagsType.tp_new = NULL;
2826 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2827 if (res < 0) {
2828 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2829 goto err_occurred;
2830 }
2831 _PyErr_Clear(tstate);
2832 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002833
2834#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 /* getwindowsversion */
2836 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002837 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002838 &windows_version_desc) < 0) {
2839 goto type_init_failed;
2840 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 /* prevent user from creating new instances */
2842 WindowsVersionType.tp_init = NULL;
2843 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002844 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002845 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002846 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2847 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002848 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002849#endif
2850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002852#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002853 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002854#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002855 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002856#endif
2857
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002858 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002859
Yury Selivanoveb636452016-09-08 22:01:51 -07002860 /* initialize asyncgen_hooks */
2861 if (AsyncGenHooksType.tp_name == NULL) {
2862 if (PyStructSequence_InitType2(
2863 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002864 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002865 }
2866 }
2867
Victor Stinneref75a622020-11-12 15:14:13 +01002868 /* adding sys.path_hooks and sys.path_importer_cache */
2869 SET_SYS("meta_path", PyList_New(0));
2870 SET_SYS("path_importer_cache", PyDict_New());
2871 SET_SYS("path_hooks", PyList_New(0));
2872
Victor Stinner838f2642019-06-13 22:41:23 +02002873 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002874 goto err_occurred;
2875 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002876 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002877
2878type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002879 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002880
2881err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002882 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002883}
2884
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002885static int
2886sys_add_xoption(PyObject *opts, const wchar_t *s)
2887{
2888 PyObject *name, *value;
2889
2890 const wchar_t *name_end = wcschr(s, L'=');
2891 if (!name_end) {
2892 name = PyUnicode_FromWideChar(s, -1);
2893 value = Py_True;
2894 Py_INCREF(value);
2895 }
2896 else {
2897 name = PyUnicode_FromWideChar(s, name_end - s);
2898 value = PyUnicode_FromWideChar(name_end + 1, -1);
2899 }
2900 if (name == NULL || value == NULL) {
2901 goto error;
2902 }
2903 if (PyDict_SetItem(opts, name, value) < 0) {
2904 goto error;
2905 }
2906 Py_DECREF(name);
2907 Py_DECREF(value);
2908 return 0;
2909
2910error:
2911 Py_XDECREF(name);
2912 Py_XDECREF(value);
2913 return -1;
2914}
2915
2916
2917static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002918sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002919{
2920 Py_ssize_t nxoption = config->xoptions.length;
2921 wchar_t * const * xoptions = config->xoptions.items;
2922 PyObject *dict = PyDict_New();
2923 if (dict == NULL) {
2924 return NULL;
2925 }
2926
2927 for (Py_ssize_t i=0; i < nxoption; i++) {
2928 const wchar_t *option = xoptions[i];
2929 if (sys_add_xoption(dict, option) < 0) {
2930 Py_DECREF(dict);
2931 return NULL;
2932 }
2933 }
2934
2935 return dict;
2936}
2937
2938
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002939// Update sys attributes for a new PyConfig configuration.
2940// This function also adds attributes that _PySys_InitCore() didn't add.
Eric Snow6b4be192017-05-22 21:36:03 -07002941int
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002942_PySys_UpdateConfig(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002943{
Victor Stinner838f2642019-06-13 22:41:23 +02002944 PyObject *sysdict = tstate->interp->sysdict;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002945 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002946 int res;
2947
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002948#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002949 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002950
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002951#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002952 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002953
Victor Stinner9e1b8282020-11-10 13:21:52 +01002954#define COPY_WSTR(SYS_ATTR, WSTR) \
2955 if (WSTR != NULL) { \
2956 SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
2957 }
2958
Victor Stinnerf3cb8142020-11-05 18:12:33 +01002959 if (config->module_search_paths_set) {
2960 COPY_LIST("path", config->module_search_paths);
2961 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002962
Victor Stinner9e1b8282020-11-10 13:21:52 +01002963 COPY_WSTR("executable", config->executable);
2964 COPY_WSTR("_base_executable", config->base_executable);
2965 COPY_WSTR("prefix", config->prefix);
2966 COPY_WSTR("base_prefix", config->base_prefix);
2967 COPY_WSTR("exec_prefix", config->exec_prefix);
2968 COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
2969 COPY_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002970
Carl Meyerb193fa92018-06-15 22:40:56 -06002971 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002972 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002973 } else {
2974 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2975 }
2976
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002977 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002978 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002979 COPY_LIST("warnoptions", config->warnoptions);
2980
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002981 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002982
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002983#undef SET_SYS_FROM_WSTR
Victor Stinner9e1b8282020-11-10 13:21:52 +01002984#undef COPY_LIST
2985#undef COPY_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002986
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002987 // sys.flags
2988 PyObject *flags = _PySys_GetObject(tstate, "flags"); // borrowed ref
2989 if (flags == NULL) {
2990 return -1;
2991 }
2992 if (set_flags_from_config(flags, tstate) < 0) {
2993 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002994 }
2995
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002996 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002997
Victor Stinner838f2642019-06-13 22:41:23 +02002998 if (_PyErr_Occurred(tstate)) {
2999 goto err_occurred;
3000 }
3001
Eric Snow6b4be192017-05-22 21:36:03 -07003002 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01003003
3004err_occurred:
3005 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003006}
3007
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03003008#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01003009#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07003010
Victor Stinnerab672812019-01-23 15:04:40 +01003011
3012/* Set up a preliminary stderr printer until we have enough
3013 infrastructure for the io module in place.
3014
3015 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003016static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01003017_PySys_SetPreliminaryStderr(PyObject *sysdict)
3018{
3019 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3020 if (pstderr == NULL) {
3021 goto error;
3022 }
3023 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3024 goto error;
3025 }
3026 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3027 goto error;
3028 }
3029 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003030 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003031
3032error:
3033 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003034 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003035}
3036
3037
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003038/* Create sys module without all attributes.
3039 _PySys_UpdateConfig() should be called later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003040PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01003041_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003042{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003043 assert(!_PyErr_Occurred(tstate));
3044
Victor Stinnerb45d2592019-06-20 00:05:23 +02003045 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003046
Victor Stinnerab672812019-01-23 15:04:40 +01003047 PyObject *modules = PyDict_New();
3048 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003049 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003050 }
3051 interp->modules = modules;
3052
3053 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3054 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003055 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003056 }
3057
3058 PyObject *sysdict = PyModule_GetDict(sysmod);
3059 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003060 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003061 }
3062 Py_INCREF(sysdict);
3063 interp->sysdict = sysdict;
3064
3065 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003066 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003067 }
3068
Victor Stinner331a6a52019-05-27 16:39:22 +02003069 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3070 if (_PyStatus_EXCEPTION(status)) {
3071 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003072 }
3073
Victor Stinner01b1cc12019-11-20 02:27:56 +01003074 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003075 if (_PyStatus_EXCEPTION(status)) {
3076 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003077 }
3078
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003079 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3080 goto error;
3081 }
3082
3083 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003084
3085 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003086 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003087
3088error:
3089 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003090}
3091
3092
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003093static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003094makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 int i, n;
3097 const wchar_t *p;
3098 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 n = 1;
3101 p = path;
3102 while ((p = wcschr(p, delim)) != NULL) {
3103 n++;
3104 p++;
3105 }
3106 v = PyList_New(n);
3107 if (v == NULL)
3108 return NULL;
3109 for (i = 0; ; i++) {
3110 p = wcschr(path, delim);
3111 if (p == NULL)
3112 p = path + wcslen(path); /* End of string */
3113 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3114 if (w == NULL) {
3115 Py_DECREF(v);
3116 return NULL;
3117 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003118 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 if (*p == '\0')
3120 break;
3121 path = p+1;
3122 }
3123 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003124}
3125
3126void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003127PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 PyObject *v;
3130 if ((v = makepathobject(path, DELIM)) == NULL)
3131 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003132 PyThreadState *tstate = _PyThreadState_GET();
3133 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003134 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003135 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003136 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003137}
3138
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003139static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003140make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003141{
Victor Stinner74f65682019-03-15 15:08:05 +01003142 PyObject *list = PyList_New(argc);
3143 if (list == NULL) {
3144 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003145 }
Victor Stinner74f65682019-03-15 15:08:05 +01003146
3147 for (Py_ssize_t i = 0; i < argc; i++) {
3148 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3149 if (v == NULL) {
3150 Py_DECREF(list);
3151 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003152 }
Victor Stinner74f65682019-03-15 15:08:05 +01003153 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003154 }
Victor Stinner74f65682019-03-15 15:08:05 +01003155 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003156}
3157
Victor Stinner11a247d2017-12-13 21:05:57 +01003158void
3159PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003160{
Victor Stinnerc4868252019-08-23 11:04:16 +01003161 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003162 PyThreadState *tstate = _PyThreadState_GET();
3163
Victor Stinner74f65682019-03-15 15:08:05 +01003164 if (argc < 1 || argv == NULL) {
3165 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003166 argv = empty_argv;
3167 argc = 1;
3168 }
3169
3170 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003171 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003172 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003173 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02003174 if (sys_set_object_str(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003175 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003176 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003177 }
3178 Py_DECREF(av);
3179
3180 if (updatepath) {
3181 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3182 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003183 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003184 PyObject *path0 = NULL;
3185 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3186 if (path0 == NULL) {
3187 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003188 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003189
Victor Stinner838f2642019-06-13 22:41:23 +02003190 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003191 if (sys_path != NULL) {
3192 if (PyList_Insert(sys_path, 0, path0) < 0) {
3193 Py_DECREF(path0);
3194 Py_FatalError("can't prepend path0 to sys.path");
3195 }
3196 }
3197 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003198 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003199 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003200}
Guido van Rossuma890e681998-05-12 14:59:24 +00003201
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003202void
3203PySys_SetArgv(int argc, wchar_t **argv)
3204{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003205 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003206}
3207
Victor Stinner14284c22010-04-23 12:02:30 +00003208/* Reimplementation of PyFile_WriteString() no calling indirectly
3209 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3210
3211static int
Victor Stinner79766632010-08-16 17:36:42 +00003212sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003213{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003214 if (file == NULL)
3215 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003216 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003217 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003218 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003219 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003220 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003221 Py_DECREF(result);
3222 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003223}
3224
Victor Stinner79766632010-08-16 17:36:42 +00003225static int
3226sys_pyfile_write(const char *text, PyObject *file)
3227{
3228 PyObject *unicode = NULL;
3229 int err;
3230
3231 if (file == NULL)
3232 return -1;
3233
3234 unicode = PyUnicode_FromString(text);
3235 if (unicode == NULL)
3236 return -1;
3237
3238 err = sys_pyfile_write_unicode(unicode, file);
3239 Py_DECREF(unicode);
3240 return err;
3241}
Guido van Rossuma890e681998-05-12 14:59:24 +00003242
3243/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3244 Adapted from code submitted by Just van Rossum.
3245
3246 PySys_WriteStdout(format, ...)
3247 PySys_WriteStderr(format, ...)
3248
3249 The first function writes to sys.stdout; the second to sys.stderr. When
3250 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003251 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003252
Victor Stinner14284c22010-04-23 12:02:30 +00003253 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003254 signal handlers: they may raise a new exception whereas sys_write()
3255 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003256
Guido van Rossuma890e681998-05-12 14:59:24 +00003257 Both take a printf-style format string as their first argument followed
3258 by a variable length argument list determined by the format string.
3259
3260 *** WARNING ***
3261
3262 The format should limit the total size of the formatted output string to
3263 1000 bytes. In particular, this means that no unrestricted "%s" formats
3264 should occur; these should be limited using "%.<N>s where <N> is a
3265 decimal number calculated so that <N> plus the maximum size of other
3266 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3267 which can print hundreds of digits for very large numbers.
3268
3269 */
3270
3271static void
Victor Stinner09054372013-11-06 22:41:44 +01003272sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 PyObject *file;
3275 PyObject *error_type, *error_value, *error_traceback;
3276 char buffer[1001];
3277 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003278 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003279
Victor Stinner838f2642019-06-13 22:41:23 +02003280 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3281 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3283 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003284 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003285 fputs(buffer, fp);
3286 }
3287 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3288 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003289 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 }
Victor Stinner838f2642019-06-13 22:41:23 +02003292 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003293}
3294
3295void
Guido van Rossuma890e681998-05-12 14:59:24 +00003296PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003301 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003302 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003303}
3304
3305void
Guido van Rossuma890e681998-05-12 14:59:24 +00003306PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003310 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003311 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003312 va_end(va);
3313}
3314
3315static void
Victor Stinner09054372013-11-06 22:41:44 +01003316sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003317{
3318 PyObject *file, *message;
3319 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003320 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003321 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003322
Victor Stinner838f2642019-06-13 22:41:23 +02003323 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3324 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003325 message = PyUnicode_FromFormatV(format, va);
3326 if (message != NULL) {
3327 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003328 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003329 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003330 if (utf8 != NULL)
3331 fputs(utf8, fp);
3332 }
3333 Py_DECREF(message);
3334 }
Victor Stinner838f2642019-06-13 22:41:23 +02003335 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003336}
3337
3338void
3339PySys_FormatStdout(const char *format, ...)
3340{
3341 va_list va;
3342
3343 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003344 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003345 va_end(va);
3346}
3347
3348void
3349PySys_FormatStderr(const char *format, ...)
3350{
3351 va_list va;
3352
3353 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003354 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003355 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003356}