blob: ac49f7867a5cb3b2d833fbaab11d4a9b19d475cd [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()
Pablo Galindoc2931d32021-05-03 15:50:24 +010027#include "pycore_structseq.h" // PyStructSequence_InitType()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Victor Stinner384621c2020-06-22 17:27:35 +020029#include "code.h"
30#include "frameobject.h" // PyFrame_GetBack()
Victor Stinner361dcdc2020-04-15 03:24:57 +020031#include "pydtrace.h"
32#include "osdefs.h" // DELIM
Victor Stinner9852cb32021-01-25 23:12:50 +010033#include "stdlib_module_names.h" // _Py_stdlib_module_names
Stefan Krah1845d142016-04-25 21:38:53 +020034#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000035
Mark Hammond8696ebc2002-10-08 02:44:31 +000036#ifdef MS_WINDOWS
37#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000038#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000039#endif /* MS_WINDOWS */
40
Guido van Rossum9b38a141996-09-11 23:12:24 +000041#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000042extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000043/* A string loaded from the DLL at startup: */
44extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000045#endif
46
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080047/*[clinic input]
48module sys
49[clinic start generated code]*/
50/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
51
52#include "clinic/sysmodule.c.h"
53
Victor Stinnerbd303c12013-11-07 23:07:29 +010054_Py_IDENTIFIER(_);
55_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070056_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010057_Py_IDENTIFIER(buffer);
58_Py_IDENTIFIER(builtins);
59_Py_IDENTIFIER(encoding);
60_Py_IDENTIFIER(path);
61_Py_IDENTIFIER(stdout);
62_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070063_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010064_Py_IDENTIFIER(write);
65
Victor Stinner838f2642019-06-13 22:41:23 +020066static PyObject *
67sys_get_object_id(PyThreadState *tstate, _Py_Identifier *key)
Victor Stinnerd67bd452013-11-06 22:36:40 +010068{
Victor Stinner838f2642019-06-13 22:41:23 +020069 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020070 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010071 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020072 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +020073 PyObject *exc_type, *exc_value, *exc_tb;
74 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
75 PyObject *value = _PyDict_GetItemIdWithError(sd, key);
76 /* XXX Suppress a new exception if it was raised and restore
77 * the old one. */
78 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
79 return value;
Victor Stinnerd67bd452013-11-06 22:36:40 +010080}
81
82PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +020083_PySys_GetObjectId(_Py_Identifier *key)
84{
85 PyThreadState *tstate = _PyThreadState_GET();
86 return sys_get_object_id(tstate, key);
87}
88
Victor Stinneraf1d64d2020-11-04 17:34:34 +010089static PyObject *
Victor Stinnerbcb094b2021-02-19 15:10:45 +010090_PySys_GetObject(PyInterpreterState *interp, const char *name)
Victor Stinneraf1d64d2020-11-04 17:34:34 +010091{
Victor Stinnerbcb094b2021-02-19 15:10:45 +010092 PyObject *sysdict = interp->sysdict;
Victor Stinneraf1d64d2020-11-04 17:34:34 +010093 if (sysdict == NULL) {
94 return NULL;
95 }
96 return _PyDict_GetItemStringWithError(sysdict, name);
97}
98
Victor Stinner838f2642019-06-13 22:41:23 +020099PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +0000100PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Victor Stinner838f2642019-06-13 22:41:23 +0200102 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100103
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200104 PyObject *exc_type, *exc_value, *exc_tb;
105 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100106 PyObject *value = _PySys_GetObject(tstate->interp, name);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200107 /* XXX Suppress a new exception if it was raised and restore
108 * the old one. */
109 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
110 return value;
111}
112
113static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100114sys_set_object(PyInterpreterState *interp, PyObject *key, PyObject *v)
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200115{
116 if (key == NULL) {
117 return -1;
118 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100119 PyObject *sd = interp->sysdict;
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200120 if (v == NULL) {
121 v = _PyDict_Pop(sd, key, Py_None);
122 if (v == NULL) {
123 return -1;
124 }
125 Py_DECREF(v);
126 return 0;
127 }
128 else {
129 return PyDict_SetItem(sd, key, v);
130 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000131}
132
Victor Stinner838f2642019-06-13 22:41:23 +0200133static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100134sys_set_object_id(PyInterpreterState *interp, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +0100135{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100136 return sys_set_object(interp, _PyUnicode_FromId(key), v);
Victor Stinnerd67bd452013-11-06 22:36:40 +0100137}
138
139int
Victor Stinner838f2642019-06-13 22:41:23 +0200140_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000141{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100142 PyInterpreterState *interp = _PyInterpreterState_GET();
143 return sys_set_object_id(interp, key, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200144}
145
146static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100147sys_set_object_str(PyInterpreterState *interp, const char *name, PyObject *v)
Victor Stinner838f2642019-06-13 22:41:23 +0200148{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200149 PyObject *key = v ? PyUnicode_InternFromString(name)
150 : PyUnicode_FromString(name);
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100151 int r = sys_set_object(interp, key, v);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200152 Py_XDECREF(key);
153 return r;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000154}
155
Victor Stinner838f2642019-06-13 22:41:23 +0200156int
157PySys_SetObject(const char *name, PyObject *v)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700158{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100159 PyInterpreterState *interp = _PyInterpreterState_GET();
160 return sys_set_object_str(interp, name, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200161}
162
Victor Stinner08faf002020-03-26 18:57:32 +0100163
Victor Stinner838f2642019-06-13 22:41:23 +0200164static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100165should_audit(PyInterpreterState *interp)
Victor Stinner838f2642019-06-13 22:41:23 +0200166{
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100167 /* interp must not be NULL, but test it just in case for extra safety */
168 assert(interp != NULL);
169 if (!interp) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700170 return 0;
171 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100172 return (interp->runtime->audit_hook_head
173 || interp->audit_hooks
Victor Stinner08faf002020-03-26 18:57:32 +0100174 || 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++;
Mark Shannon9e7b2072021-04-13 11:08:14 +0100256 ts->cframe->use_tracing = 0;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700257 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) {
Mark Shannon9e7b2072021-04-13 11:08:14 +0100269 ts->cframe->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700270 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++;
Mark Shannon9e7b2072021-04-13 11:08:14 +0100276 ts->cframe->use_tracing = 0;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700277 }
278 if (!o) {
279 break;
280 }
281 Py_DECREF(o);
282 Py_CLEAR(hook);
283 }
Mark Shannon9e7b2072021-04-13 11:08:14 +0100284 ts->cframe->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700285 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 Stinnerbcb094b2021-02-19 15:10:45 +0100458 PyInterpreterState *interp = tstate->interp;
459 if (interp->audit_hooks == NULL) {
460 interp->audit_hooks = PyList_New(0);
461 if (interp->audit_hooks == NULL) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700462 return NULL;
463 }
464 }
465
Victor Stinnerbcb094b2021-02-19 15:10:45 +0100466 if (PyList_Append(interp->audit_hooks, hook) < 0) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700467 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++,
Raymond Hettingera07da092021-04-22 08:34:57 -07001409 PyLong_FromLong(0)); // This is no longer used
Mark Dickinsondc787d22010-05-23 13:33:13 +00001410 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 Stinnerbcb094b2021-02-19 15:10:45 +01001610 PyInterpreterState *interp = _PyInterpreterState_GET();
1611 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 Stinnerbcb094b2021-02-19 15:10:45 +01001628 PyInterpreterState *interp = _PyInterpreterState_GET();
1629 return PyLong_FromLong(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
Pablo Galindoaf5fa132021-02-28 22:41:09 +00001962/*[clinic input]
1963sys._deactivate_opcache
1964
1965Deactivate the opcode cache permanently
1966[clinic start generated code]*/
1967
1968static PyObject *
1969sys__deactivate_opcache_impl(PyObject *module)
1970/*[clinic end generated code: output=00e20982bd012122 input=501eac146735ccf9]*/
1971{
1972 _PyEval_DeactivateOpCache();
1973 Py_RETURN_NONE;
1974}
1975
Steve Dowerb82e17e2019-05-23 08:45:22 -07001976
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001977static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001979 SYS_ADDAUDITHOOK_METHODDEF
1980 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001981 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001982 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001983 SYS__CLEAR_TYPE_CACHE_METHODDEF
1984 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001985 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001986 SYS_DISPLAYHOOK_METHODDEF
1987 SYS_EXC_INFO_METHODDEF
1988 SYS_EXCEPTHOOK_METHODDEF
1989 SYS_EXIT_METHODDEF
1990 SYS_GETDEFAULTENCODING_METHODDEF
1991 SYS_GETDLOPENFLAGS_METHODDEF
1992 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001993#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001995#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001996 SYS_GETFILESYSTEMENCODING_METHODDEF
1997 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001998#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00002000#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02002001 SYS_GETTOTALREFCOUNT_METHODDEF
2002 SYS_GETREFCOUNT_METHODDEF
2003 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002004 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002006 SYS__GETFRAME_METHODDEF
2007 SYS_GETWINDOWSVERSION_METHODDEF
2008 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
2009 SYS_INTERN_METHODDEF
2010 SYS_IS_FINALIZING_METHODDEF
2011 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002012 SYS_SETSWITCHINTERVAL_METHODDEF
2013 SYS_GETSWITCHINTERVAL_METHODDEF
2014 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002016 SYS_GETPROFILE_METHODDEF
2017 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002019 SYS_GETTRACE_METHODDEF
2020 SYS_CALL_TRACING_METHODDEF
2021 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002022 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2023 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002024 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002025 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002026 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2027 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002028 SYS_UNRAISABLEHOOK_METHODDEF
Pablo Galindoaf5fa132021-02-28 22:41:09 +00002029 SYS__DEACTIVATE_OPCACHE_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002031};
2032
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002033
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002034static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002035list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 PyObject *list = PyList_New(0);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002038 if (list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 return NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002040 }
2041 for (Py_ssize_t i = 0; PyImport_Inittab[i].name != NULL; i++) {
2042 PyObject *name = PyUnicode_FromString(PyImport_Inittab[i].name);
2043 if (name == NULL) {
2044 goto error;
2045 }
2046 if (PyList_Append(list, name) < 0) {
2047 Py_DECREF(name);
2048 goto error;
2049 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 Py_DECREF(name);
2051 }
2052 if (PyList_Sort(list) != 0) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002053 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002055 PyObject *tuple = PyList_AsTuple(list);
2056 Py_DECREF(list);
2057 return tuple;
2058
2059error:
2060 Py_DECREF(list);
2061 return NULL;
Guido van Rossum34679b71993-01-26 13:33:44 +00002062}
2063
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002064
2065static PyObject *
Victor Stinner9852cb32021-01-25 23:12:50 +01002066list_stdlib_module_names(void)
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002067{
Victor Stinner9852cb32021-01-25 23:12:50 +01002068 Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002069 PyObject *names = PyTuple_New(len);
2070 if (names == NULL) {
2071 return NULL;
2072 }
2073
2074 for (Py_ssize_t i = 0; i < len; i++) {
Victor Stinner9852cb32021-01-25 23:12:50 +01002075 PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002076 if (name == NULL) {
2077 Py_DECREF(names);
2078 return NULL;
2079 }
2080 PyTuple_SET_ITEM(names, i, name);
2081 }
2082
2083 PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
2084 "(O)", names);
2085 Py_DECREF(names);
2086 return set;
2087}
2088
2089
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002090/* Pre-initialization support for sys.warnoptions and sys._xoptions
2091 *
2092 * Modern internal code paths:
2093 * These APIs get called after _Py_InitializeCore and get to use the
2094 * regular CPython list, dict, and unicode APIs.
2095 *
2096 * Legacy embedding code paths:
2097 * The multi-phase initialization API isn't public yet, so embedding
2098 * apps still need to be able configure sys.warnoptions and sys._xoptions
2099 * before they call Py_Initialize. To support this, we stash copies of
2100 * the supplied wchar * sequences in linked lists, and then migrate the
2101 * contents of those lists to the sys module in _PyInitializeCore.
2102 *
2103 */
2104
2105struct _preinit_entry {
2106 wchar_t *value;
2107 struct _preinit_entry *next;
2108};
2109
2110typedef struct _preinit_entry *_Py_PreInitEntry;
2111
2112static _Py_PreInitEntry _preinit_warnoptions = NULL;
2113static _Py_PreInitEntry _preinit_xoptions = NULL;
2114
2115static _Py_PreInitEntry
2116_alloc_preinit_entry(const wchar_t *value)
2117{
2118 /* To get this to work, we have to initialize the runtime implicitly */
2119 _PyRuntime_Initialize();
2120
2121 /* Force default allocator, so we can ensure that it also gets used to
2122 * destroy the linked list in _clear_preinit_entries.
2123 */
2124 PyMemAllocatorEx old_alloc;
2125 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2126
2127 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2128 if (node != NULL) {
2129 node->value = _PyMem_RawWcsdup(value);
2130 if (node->value == NULL) {
2131 PyMem_RawFree(node);
2132 node = NULL;
2133 };
2134 };
2135
2136 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2137 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002138}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002139
2140static int
2141_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2142{
2143 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2144 if (new_entry == NULL) {
2145 return -1;
2146 }
2147 /* We maintain the linked list in this order so it's easy to play back
2148 * the add commands in the same order later on in _Py_InitializeCore
2149 */
2150 _Py_PreInitEntry last_entry = *optionlist;
2151 if (last_entry == NULL) {
2152 *optionlist = new_entry;
2153 } else {
2154 while (last_entry->next != NULL) {
2155 last_entry = last_entry->next;
2156 }
2157 last_entry->next = new_entry;
2158 }
2159 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002160}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002161
2162static void
2163_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2164{
2165 _Py_PreInitEntry current = *optionlist;
2166 *optionlist = NULL;
2167 /* Deallocate the nodes and their contents using the default allocator */
2168 PyMemAllocatorEx old_alloc;
2169 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2170 while (current != NULL) {
2171 _Py_PreInitEntry next = current->next;
2172 PyMem_RawFree(current->value);
2173 PyMem_RawFree(current);
2174 current = next;
2175 }
2176 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002177}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002178
Victor Stinner120b7072019-08-23 18:03:08 +01002179
2180PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002181_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002182{
Victor Stinner120b7072019-08-23 18:03:08 +01002183 PyStatus status;
2184 _Py_PreInitEntry entry;
2185
2186 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002187 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002188 if (_PyStatus_EXCEPTION(status)) {
2189 return status;
2190 }
2191 }
2192
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002193 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002194 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002195}
2196
Victor Stinner120b7072019-08-23 18:03:08 +01002197
2198PyStatus
2199_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002200{
Victor Stinner120b7072019-08-23 18:03:08 +01002201 PyStatus status;
2202 _Py_PreInitEntry entry;
2203
2204 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2205 status = PyWideStringList_Append(&config->xoptions, entry->value);
2206 if (_PyStatus_EXCEPTION(status)) {
2207 return status;
2208 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002209 }
2210
Victor Stinner120b7072019-08-23 18:03:08 +01002211 _clear_preinit_entries(&_preinit_xoptions);
2212 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002213}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002214
Victor Stinner120b7072019-08-23 18:03:08 +01002215
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002216static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002217get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002218{
Victor Stinner838f2642019-06-13 22:41:23 +02002219 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002220 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002221 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2222 * interpreter config. When that happens, we need to properly set
2223 * the `warnoptions` reference in the main interpreter config as well.
2224 *
2225 * For Python 3.7, we shouldn't be able to get here due to the
2226 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2227 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2228 * call optional for embedding applications, thus making this
2229 * reachable again.
2230 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002231 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002232 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002233 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002234 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002235 if (sys_set_object_id(tstate->interp, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002236 Py_DECREF(warnoptions);
2237 return NULL;
2238 }
2239 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002240 }
2241 return warnoptions;
2242}
Guido van Rossum23fff912000-12-15 22:02:05 +00002243
2244void
2245PySys_ResetWarnOptions(void)
2246{
Victor Stinner50b48572018-11-01 01:51:40 +01002247 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002248 if (tstate == NULL) {
2249 _clear_preinit_entries(&_preinit_warnoptions);
2250 return;
2251 }
2252
Victor Stinner838f2642019-06-13 22:41:23 +02002253 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (warnoptions == NULL || !PyList_Check(warnoptions))
2255 return;
2256 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002257}
2258
Victor Stinnere1b29952018-10-30 14:31:42 +01002259static int
Victor Stinner838f2642019-06-13 22:41:23 +02002260_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002261{
Victor Stinner838f2642019-06-13 22:41:23 +02002262 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002263 if (warnoptions == NULL) {
2264 return -1;
2265 }
2266 if (PyList_Append(warnoptions, option)) {
2267 return -1;
2268 }
2269 return 0;
2270}
2271
2272void
2273PySys_AddWarnOptionUnicode(PyObject *option)
2274{
Victor Stinner838f2642019-06-13 22:41:23 +02002275 PyThreadState *tstate = _PyThreadState_GET();
2276 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002277 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002278 if (tstate) {
2279 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002280 }
2281 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002282}
2283
2284void
2285PySys_AddWarnOption(const wchar_t *s)
2286{
Victor Stinner50b48572018-11-01 01:51:40 +01002287 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002288 if (tstate == NULL) {
2289 _append_preinit_entry(&_preinit_warnoptions, s);
2290 return;
2291 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002292 PyObject *unicode;
2293 unicode = PyUnicode_FromWideChar(s, -1);
2294 if (unicode == NULL)
2295 return;
2296 PySys_AddWarnOptionUnicode(unicode);
2297 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002298}
2299
Christian Heimes33fe8092008-04-13 13:53:33 +00002300int
2301PySys_HasWarnOptions(void)
2302{
Victor Stinner838f2642019-06-13 22:41:23 +02002303 PyThreadState *tstate = _PyThreadState_GET();
2304 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002305 return (warnoptions != NULL && PyList_Check(warnoptions)
2306 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002307}
2308
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002309static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002310get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002311{
Victor Stinner838f2642019-06-13 22:41:23 +02002312 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002313 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002314 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2315 * interpreter config. When that happens, we need to properly set
2316 * the `xoptions` reference in the main interpreter config as well.
2317 *
2318 * For Python 3.7, we shouldn't be able to get here due to the
2319 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2320 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2321 * call optional for embedding applications, thus making this
2322 * reachable again.
2323 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002324 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002325 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002326 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002327 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002328 if (sys_set_object_id(tstate->interp, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002329 Py_DECREF(xoptions);
2330 return NULL;
2331 }
2332 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002333 }
2334 return xoptions;
2335}
2336
Victor Stinnere1b29952018-10-30 14:31:42 +01002337static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002338_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002339{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002340 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002341
Victor Stinner838f2642019-06-13 22:41:23 +02002342 PyThreadState *tstate = _PyThreadState_GET();
2343 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002344 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002345 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002346 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002347
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002348 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002349 if (!name_end) {
2350 name = PyUnicode_FromWideChar(s, -1);
2351 value = Py_True;
2352 Py_INCREF(value);
2353 }
2354 else {
2355 name = PyUnicode_FromWideChar(s, name_end - s);
2356 value = PyUnicode_FromWideChar(name_end + 1, -1);
2357 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002358 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002359 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002360 }
2361 if (PyDict_SetItem(opts, name, value) < 0) {
2362 goto error;
2363 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002364 Py_DECREF(name);
2365 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002366 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002367
2368error:
2369 Py_XDECREF(name);
2370 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002371 return -1;
2372}
2373
2374void
2375PySys_AddXOption(const wchar_t *s)
2376{
Victor Stinner50b48572018-11-01 01:51:40 +01002377 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002378 if (tstate == NULL) {
2379 _append_preinit_entry(&_preinit_xoptions, s);
2380 return;
2381 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002382 if (_PySys_AddXOptionWithError(s) < 0) {
2383 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002384 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002385 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002386}
2387
2388PyObject *
2389PySys_GetXOptions(void)
2390{
Victor Stinner838f2642019-06-13 22:41:23 +02002391 PyThreadState *tstate = _PyThreadState_GET();
2392 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002393}
2394
Guido van Rossum40552d01998-08-06 03:34:39 +00002395/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2396 Two literals concatenated works just fine. If you have a K&R compiler
2397 or other abomination that however *does* understand longer strings,
2398 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002399PyDoc_VAR(sys_doc) =
2400PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002401"This module provides access to some objects used or maintained by the\n\
2402interpreter and to functions that interact strongly with the interpreter.\n\
2403\n\
2404Dynamic objects:\n\
2405\n\
2406argv -- command line arguments; argv[0] is the script pathname if known\n\
2407path -- module search path; path[0] is the script directory, else ''\n\
2408modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002409\n\
2410displayhook -- called to show results in an interactive session\n\
2411excepthook -- called to handle any uncaught exception other than SystemExit\n\
2412 To customize printing in an interactive session or to install a custom\n\
2413 top-level exception handler, assign other functions to replace these.\n\
2414\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002415stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002416stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002417stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002418 By assigning other file objects (or objects that behave like files)\n\
2419 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002420\n\
2421last_type -- type of last uncaught exception\n\
2422last_value -- value of last uncaught exception\n\
2423last_traceback -- traceback of last uncaught exception\n\
2424 These three are only available in an interactive session after a\n\
2425 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002426"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002427)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002428/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002429PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002430"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002431Static objects:\n\
2432\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002433builtin_module_names -- tuple of module names built into this interpreter\n\
2434copyright -- copyright notice pertaining to this interpreter\n\
2435exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002436executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002437float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002438float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002439hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002440hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002441implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002442int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002443maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002444maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002445platform -- platform identifier\n\
2446prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002447thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002448version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002449version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002450"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002451)
Steve Dowercc16be82016-09-08 10:35:16 -07002452#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002453/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002454PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002455"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002456winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002457"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002458)
Steve Dowercc16be82016-09-08 10:35:16 -07002459#endif /* MS_COREDLL */
2460#ifdef MS_WINDOWS
2461/* concatenating string here */
2462PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002463"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002464"
2465)
2466#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002467PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002468"__stdin__ -- the original stdin; don't touch!\n\
2469__stdout__ -- the original stdout; don't touch!\n\
2470__stderr__ -- the original stderr; don't touch!\n\
2471__displayhook__ -- the original displayhook; don't touch!\n\
2472__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002473\n\
2474Functions:\n\
2475\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002476displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002477excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002478exc_info() -- return thread-safe information about the current exception\n\
2479exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002480getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002481getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002482getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002483getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002484getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002485gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002486setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002487setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002488setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002489settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002490"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002491)
Fred Drakeccede592000-08-14 20:59:57 +00002492/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002493
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002494
2495PyDoc_STRVAR(flags__doc__,
2496"sys.flags\n\
2497\n\
2498Flags provided through command line arguments or environment vars.");
2499
2500static PyTypeObject FlagsType;
2501
2502static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 {"inspect", "-i"},
2505 {"interactive", "-i"},
2506 {"optimize", "-O or -OO"},
2507 {"dont_write_bytecode", "-B"},
2508 {"no_user_site", "-s"},
2509 {"no_site", "-S"},
2510 {"ignore_environment", "-E"},
2511 {"verbose", "-v"},
Georg Brandl8aa7e992010-12-28 18:30:18 +00002512 {"bytes_warning", "-b"},
2513 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002514 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002515 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002516 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002517 {"utf8_mode", "-X utf8"},
Inada Naoki48274832021-03-29 12:28:14 +09002518 {"warn_default_encoding", "-X warn_default_encoding"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002520};
2521
2522static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 "sys.flags", /* name */
2524 flags__doc__, /* doc */
2525 flags_fields, /* fields */
Inada Naoki48274832021-03-29 12:28:14 +09002526 16
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002527};
2528
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002529static int
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002530set_flags_from_config(PyInterpreterState *interp, PyObject *flags)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002531{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002532 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002533 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002534
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002535 // _PySys_UpdateConfig() modifies sys.flags in-place:
2536 // Py_XDECREF() is needed in this case.
2537 Py_ssize_t pos = 0;
2538#define SetFlagObj(expr) \
2539 do { \
2540 PyObject *value = (expr); \
2541 if (value == NULL) { \
2542 return -1; \
2543 } \
2544 Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
2545 PyStructSequence_SET_ITEM(flags, pos, value); \
2546 pos++; \
2547 } while (0)
2548#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002549
Victor Stinnerfbca9082018-08-30 00:50:45 +02002550 SetFlag(config->parser_debug);
2551 SetFlag(config->inspect);
2552 SetFlag(config->interactive);
2553 SetFlag(config->optimization_level);
2554 SetFlag(!config->write_bytecode);
2555 SetFlag(!config->user_site_directory);
2556 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002557 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002558 SetFlag(config->verbose);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002559 SetFlag(config->bytes_warning);
2560 SetFlag(config->quiet);
2561 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002562 SetFlag(config->isolated);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002563 SetFlagObj(PyBool_FromLong(config->dev_mode));
Victor Stinner20004952019-03-26 02:31:11 +01002564 SetFlag(preconfig->utf8_mode);
Inada Naoki48274832021-03-29 12:28:14 +09002565 SetFlag(config->warn_default_encoding);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002566#undef SetFlagObj
Victor Stinner91106cd2017-12-13 12:29:09 +01002567#undef SetFlag
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002568 return 0;
2569}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002570
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002571
2572static PyObject*
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002573make_flags(PyInterpreterState *interp)
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002574{
2575 PyObject *flags = PyStructSequence_New(&FlagsType);
2576 if (flags == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 return NULL;
2578 }
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002579
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002580 if (set_flags_from_config(interp, flags) < 0) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002581 Py_DECREF(flags);
2582 return NULL;
2583 }
2584 return flags;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002585}
2586
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002587
Eric Smith0e5b5622009-02-06 01:32:42 +00002588PyDoc_STRVAR(version_info__doc__,
2589"sys.version_info\n\
2590\n\
2591Version information as a named tuple.");
2592
2593static PyTypeObject VersionInfoType;
2594
2595static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 {"major", "Major release number"},
2597 {"minor", "Minor release number"},
2598 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002599 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 {"serial", "Serial release number"},
2601 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002602};
2603
2604static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 "sys.version_info", /* name */
2606 version_info__doc__, /* doc */
2607 version_info_fields, /* fields */
2608 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002609};
2610
2611static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002612make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002614 PyObject *version_info;
2615 char *s;
2616 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 version_info = PyStructSequence_New(&VersionInfoType);
2619 if (version_info == NULL) {
2620 return NULL;
2621 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 /*
2624 * These release level checks are mutually exclusive and cover
2625 * the field, so don't get too fancy with the pre-processor!
2626 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002627#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002629#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002631#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002633#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002634 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002635#endif
2636
2637#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002638 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002639#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002640 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 SetIntItem(PY_MAJOR_VERSION);
2643 SetIntItem(PY_MINOR_VERSION);
2644 SetIntItem(PY_MICRO_VERSION);
2645 SetStrItem(s);
2646 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002647#undef SetIntItem
2648#undef SetStrItem
2649
Victor Stinner838f2642019-06-13 22:41:23 +02002650 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 Py_CLEAR(version_info);
2652 return NULL;
2653 }
2654 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002655}
2656
Brett Cannon3adc7b72012-07-09 14:22:12 -04002657/* sys.implementation values */
2658#define NAME "cpython"
2659const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002660#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2661#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002662#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002663const char *_PySys_ImplCacheTag = TAG;
2664#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002665#undef MAJOR
2666#undef MINOR
2667#undef TAG
2668
Barry Warsaw409da152012-06-03 16:18:47 -04002669static PyObject *
2670make_impl_info(PyObject *version_info)
2671{
2672 int res;
2673 PyObject *impl_info, *value, *ns;
2674
2675 impl_info = PyDict_New();
2676 if (impl_info == NULL)
2677 return NULL;
2678
2679 /* populate the dict */
2680
Brett Cannon3adc7b72012-07-09 14:22:12 -04002681 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002682 if (value == NULL)
2683 goto error;
2684 res = PyDict_SetItemString(impl_info, "name", value);
2685 Py_DECREF(value);
2686 if (res < 0)
2687 goto error;
2688
Brett Cannon3adc7b72012-07-09 14:22:12 -04002689 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002690 if (value == NULL)
2691 goto error;
2692 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2693 Py_DECREF(value);
2694 if (res < 0)
2695 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002696
2697 res = PyDict_SetItemString(impl_info, "version", version_info);
2698 if (res < 0)
2699 goto error;
2700
2701 value = PyLong_FromLong(PY_VERSION_HEX);
2702 if (value == NULL)
2703 goto error;
2704 res = PyDict_SetItemString(impl_info, "hexversion", value);
2705 Py_DECREF(value);
2706 if (res < 0)
2707 goto error;
2708
doko@ubuntu.com55532312016-06-14 08:55:19 +02002709#ifdef MULTIARCH
2710 value = PyUnicode_FromString(MULTIARCH);
2711 if (value == NULL)
2712 goto error;
2713 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2714 Py_DECREF(value);
2715 if (res < 0)
2716 goto error;
2717#endif
2718
Barry Warsaw409da152012-06-03 16:18:47 -04002719 /* dict ready */
2720
2721 ns = _PyNamespace_New(impl_info);
2722 Py_DECREF(impl_info);
2723 return ns;
2724
2725error:
2726 Py_CLEAR(impl_info);
2727 return NULL;
2728}
2729
Martin v. Löwis1a214512008-06-11 05:26:20 +00002730static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyModuleDef_HEAD_INIT,
2732 "sys",
2733 sys_doc,
2734 -1, /* multiple "initialization" just copies the module dict. */
2735 sys_methods,
2736 NULL,
2737 NULL,
2738 NULL,
2739 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002740};
2741
Eric Snow6b4be192017-05-22 21:36:03 -07002742/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002743#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002744 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002745 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002746 if (v == NULL) { \
2747 goto err_occurred; \
2748 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002749 res = PyDict_SetItemString(sysdict, key, v); \
2750 Py_DECREF(v); \
2751 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002752 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002753 } \
2754 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002755
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002756#define SET_SYS_FROM_STRING(key, value) \
2757 SET_SYS(key, PyUnicode_FromString(value))
2758
Victor Stinner331a6a52019-05-27 16:39:22 +02002759static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002760_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002761{
Victor Stinnerab672812019-01-23 15:04:40 +01002762 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002763 int res;
2764
Nick Coghland6009512014-11-20 21:39:37 +10002765 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002766
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002767#define COPY_SYS_ATTR(tokey, fromkey) \
2768 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002769
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002770 COPY_SYS_ATTR("__displayhook__", "displayhook");
2771 COPY_SYS_ATTR("__excepthook__", "excepthook");
2772 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2773 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2774
2775#undef COPY_SYS_ATTR
2776
2777 SET_SYS_FROM_STRING("version", Py_GetVersion());
2778 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2779 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2780 _Py_gitversion()));
2781 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2782 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2783 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2784 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2785 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2786 SET_SYS("float_info", PyFloat_GetInfo());
2787 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002788 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002789 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002790 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2791 goto type_init_failed;
2792 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002793 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002794 SET_SYS("hash_info", get_hash_info(tstate));
2795 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2796 SET_SYS("builtin_module_names", list_builtin_module_names());
Victor Stinner9852cb32021-01-25 23:12:50 +01002797 SET_SYS("stdlib_module_names", list_stdlib_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002798#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002799 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002800#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002801 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002802#endif
Fred Drake099325e2000-08-14 15:47:03 +00002803
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002804#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002805 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2806 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002807#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002808#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002809 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002810#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002811
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002813 if (VersionInfoType.tp_name == NULL) {
Victor Stinner3bb09942021-04-30 12:46:15 +02002814 if (_PyStructSequence_InitType(&VersionInfoType,
2815 &version_info_desc,
2816 Py_TPFLAGS_DISALLOW_INSTANTIATION) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002817 goto type_init_failed;
2818 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002819 }
Victor Stinner838f2642019-06-13 22:41:23 +02002820 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002821 SET_SYS("version_info", version_info);
Eric Smith0e5b5622009-02-06 01:32:42 +00002822
Barry Warsaw409da152012-06-03 16:18:47 -04002823 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002824 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002825
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002826 // sys.flags: updated in-place later by _PySys_UpdateConfig()
Victor Stinner1c8f0592013-07-22 22:24:54 +02002827 if (FlagsType.tp_name == 0) {
Victor Stinner3bb09942021-04-30 12:46:15 +02002828 if (_PyStructSequence_InitType(&FlagsType, &flags_desc,
2829 Py_TPFLAGS_DISALLOW_INSTANTIATION) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002830 goto type_init_failed;
2831 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002832 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002833 SET_SYS("flags", make_flags(tstate->interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002834
2835#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 /* getwindowsversion */
Victor Stinner3bb09942021-04-30 12:46:15 +02002837 if (WindowsVersionType.tp_name == 0) {
2838 if (_PyStructSequence_InitType(&WindowsVersionType,
2839 &windows_version_desc,
2840 Py_TPFLAGS_DISALLOW_INSTANTIATION) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002841 goto type_init_failed;
2842 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002843 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002844#endif
2845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002846 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002847#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002848 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002849#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002850 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002851#endif
2852
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002853 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002854
Yury Selivanoveb636452016-09-08 22:01:51 -07002855 /* initialize asyncgen_hooks */
2856 if (AsyncGenHooksType.tp_name == NULL) {
2857 if (PyStructSequence_InitType2(
2858 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002859 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002860 }
2861 }
2862
Victor Stinneref75a622020-11-12 15:14:13 +01002863 /* adding sys.path_hooks and sys.path_importer_cache */
2864 SET_SYS("meta_path", PyList_New(0));
2865 SET_SYS("path_importer_cache", PyDict_New());
2866 SET_SYS("path_hooks", PyList_New(0));
2867
Victor Stinner838f2642019-06-13 22:41:23 +02002868 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002869 goto err_occurred;
2870 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002871 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002872
2873type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002874 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002875
2876err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002877 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002878}
2879
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002880static int
2881sys_add_xoption(PyObject *opts, const wchar_t *s)
2882{
2883 PyObject *name, *value;
2884
2885 const wchar_t *name_end = wcschr(s, L'=');
2886 if (!name_end) {
2887 name = PyUnicode_FromWideChar(s, -1);
2888 value = Py_True;
2889 Py_INCREF(value);
2890 }
2891 else {
2892 name = PyUnicode_FromWideChar(s, name_end - s);
2893 value = PyUnicode_FromWideChar(name_end + 1, -1);
2894 }
2895 if (name == NULL || value == NULL) {
2896 goto error;
2897 }
2898 if (PyDict_SetItem(opts, name, value) < 0) {
2899 goto error;
2900 }
2901 Py_DECREF(name);
2902 Py_DECREF(value);
2903 return 0;
2904
2905error:
2906 Py_XDECREF(name);
2907 Py_XDECREF(value);
2908 return -1;
2909}
2910
2911
2912static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002913sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002914{
2915 Py_ssize_t nxoption = config->xoptions.length;
2916 wchar_t * const * xoptions = config->xoptions.items;
2917 PyObject *dict = PyDict_New();
2918 if (dict == NULL) {
2919 return NULL;
2920 }
2921
2922 for (Py_ssize_t i=0; i < nxoption; i++) {
2923 const wchar_t *option = xoptions[i];
2924 if (sys_add_xoption(dict, option) < 0) {
2925 Py_DECREF(dict);
2926 return NULL;
2927 }
2928 }
2929
2930 return dict;
2931}
2932
2933
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002934// Update sys attributes for a new PyConfig configuration.
2935// This function also adds attributes that _PySys_InitCore() didn't add.
Eric Snow6b4be192017-05-22 21:36:03 -07002936int
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002937_PySys_UpdateConfig(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002938{
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002939 PyInterpreterState *interp = tstate->interp;
2940 PyObject *sysdict = interp->sysdict;
2941 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002942 int res;
2943
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002944#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002945 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002946
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002947#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002948 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002949
Victor Stinner9e1b8282020-11-10 13:21:52 +01002950#define COPY_WSTR(SYS_ATTR, WSTR) \
2951 if (WSTR != NULL) { \
2952 SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
2953 }
2954
Victor Stinnerf3cb8142020-11-05 18:12:33 +01002955 if (config->module_search_paths_set) {
2956 COPY_LIST("path", config->module_search_paths);
2957 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002958
Victor Stinner9e1b8282020-11-10 13:21:52 +01002959 COPY_WSTR("executable", config->executable);
2960 COPY_WSTR("_base_executable", config->base_executable);
2961 COPY_WSTR("prefix", config->prefix);
2962 COPY_WSTR("base_prefix", config->base_prefix);
2963 COPY_WSTR("exec_prefix", config->exec_prefix);
2964 COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
2965 COPY_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002966
Carl Meyerb193fa92018-06-15 22:40:56 -06002967 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002968 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002969 } else {
2970 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2971 }
2972
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002973 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002974 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002975 COPY_LIST("warnoptions", config->warnoptions);
2976
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002977 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002978
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002979#undef SET_SYS_FROM_WSTR
Victor Stinner9e1b8282020-11-10 13:21:52 +01002980#undef COPY_LIST
2981#undef COPY_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002982
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002983 // sys.flags
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002984 PyObject *flags = _PySys_GetObject(interp, "flags"); // borrowed ref
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002985 if (flags == NULL) {
2986 return -1;
2987 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01002988 if (set_flags_from_config(interp, flags) < 0) {
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002989 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002990 }
2991
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002992 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002993
Victor Stinner838f2642019-06-13 22:41:23 +02002994 if (_PyErr_Occurred(tstate)) {
2995 goto err_occurred;
2996 }
2997
Eric Snow6b4be192017-05-22 21:36:03 -07002998 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002999
3000err_occurred:
3001 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003002}
3003
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03003004#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01003005#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07003006
Victor Stinnerab672812019-01-23 15:04:40 +01003007
3008/* Set up a preliminary stderr printer until we have enough
3009 infrastructure for the io module in place.
3010
Victor Stinner4908fae2021-04-30 14:56:27 +02003011 Use UTF-8/backslashreplace and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003012static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01003013_PySys_SetPreliminaryStderr(PyObject *sysdict)
3014{
3015 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3016 if (pstderr == NULL) {
3017 goto error;
3018 }
3019 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3020 goto error;
3021 }
3022 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3023 goto error;
3024 }
3025 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003026 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003027
3028error:
3029 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003030 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003031}
3032
3033
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003034/* Create sys module without all attributes.
3035 _PySys_UpdateConfig() should be called later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003036PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01003037_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003038{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003039 assert(!_PyErr_Occurred(tstate));
3040
Victor Stinnerb45d2592019-06-20 00:05:23 +02003041 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003042
Victor Stinnerab672812019-01-23 15:04:40 +01003043 PyObject *modules = PyDict_New();
3044 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003045 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003046 }
3047 interp->modules = modules;
3048
3049 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3050 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003051 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003052 }
3053
3054 PyObject *sysdict = PyModule_GetDict(sysmod);
3055 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003056 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003057 }
3058 Py_INCREF(sysdict);
3059 interp->sysdict = sysdict;
3060
3061 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003062 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003063 }
3064
Victor Stinner331a6a52019-05-27 16:39:22 +02003065 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3066 if (_PyStatus_EXCEPTION(status)) {
3067 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003068 }
3069
Victor Stinner01b1cc12019-11-20 02:27:56 +01003070 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003071 if (_PyStatus_EXCEPTION(status)) {
3072 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003073 }
3074
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003075 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3076 goto error;
3077 }
3078
3079 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003080
3081 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003082 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003083
3084error:
3085 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003086}
3087
3088
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003089static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003090makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003092 int i, n;
3093 const wchar_t *p;
3094 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 n = 1;
3097 p = path;
3098 while ((p = wcschr(p, delim)) != NULL) {
3099 n++;
3100 p++;
3101 }
3102 v = PyList_New(n);
3103 if (v == NULL)
3104 return NULL;
3105 for (i = 0; ; i++) {
3106 p = wcschr(path, delim);
3107 if (p == NULL)
3108 p = path + wcslen(path); /* End of string */
3109 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3110 if (w == NULL) {
3111 Py_DECREF(v);
3112 return NULL;
3113 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003114 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003115 if (*p == '\0')
3116 break;
3117 path = p+1;
3118 }
3119 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003120}
3121
3122void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003123PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003124{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 PyObject *v;
3126 if ((v = makepathobject(path, DELIM)) == NULL)
3127 Py_FatalError("can't create sys.path");
Victor Stinnerbcb094b2021-02-19 15:10:45 +01003128 PyInterpreterState *interp = _PyInterpreterState_GET();
3129 if (sys_set_object_id(interp, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003131 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003133}
3134
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003135static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003136make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003137{
Victor Stinner74f65682019-03-15 15:08:05 +01003138 PyObject *list = PyList_New(argc);
3139 if (list == NULL) {
3140 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003141 }
Victor Stinner74f65682019-03-15 15:08:05 +01003142
3143 for (Py_ssize_t i = 0; i < argc; i++) {
3144 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3145 if (v == NULL) {
3146 Py_DECREF(list);
3147 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003148 }
Victor Stinner74f65682019-03-15 15:08:05 +01003149 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003150 }
Victor Stinner74f65682019-03-15 15:08:05 +01003151 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003152}
3153
Victor Stinner11a247d2017-12-13 21:05:57 +01003154void
3155PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003156{
Victor Stinnerc4868252019-08-23 11:04:16 +01003157 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003158 PyThreadState *tstate = _PyThreadState_GET();
3159
Victor Stinner74f65682019-03-15 15:08:05 +01003160 if (argc < 1 || argv == NULL) {
3161 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003162 argv = empty_argv;
3163 argc = 1;
3164 }
3165
3166 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003167 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003168 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003169 }
Victor Stinnerbcb094b2021-02-19 15:10:45 +01003170 if (sys_set_object_str(tstate->interp, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003171 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003172 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003173 }
3174 Py_DECREF(av);
3175
3176 if (updatepath) {
3177 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3178 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003179 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003180 PyObject *path0 = NULL;
3181 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3182 if (path0 == NULL) {
3183 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003184 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003185
Victor Stinner838f2642019-06-13 22:41:23 +02003186 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003187 if (sys_path != NULL) {
3188 if (PyList_Insert(sys_path, 0, path0) < 0) {
3189 Py_DECREF(path0);
3190 Py_FatalError("can't prepend path0 to sys.path");
3191 }
3192 }
3193 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003194 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003195 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003196}
Guido van Rossuma890e681998-05-12 14:59:24 +00003197
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003198void
3199PySys_SetArgv(int argc, wchar_t **argv)
3200{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003201 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003202}
3203
Victor Stinner14284c22010-04-23 12:02:30 +00003204/* Reimplementation of PyFile_WriteString() no calling indirectly
3205 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3206
3207static int
Victor Stinner79766632010-08-16 17:36:42 +00003208sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003209{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003210 if (file == NULL)
3211 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003212 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003213 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003214 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003215 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003217 Py_DECREF(result);
3218 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003219}
3220
Victor Stinner79766632010-08-16 17:36:42 +00003221static int
3222sys_pyfile_write(const char *text, PyObject *file)
3223{
3224 PyObject *unicode = NULL;
3225 int err;
3226
3227 if (file == NULL)
3228 return -1;
3229
3230 unicode = PyUnicode_FromString(text);
3231 if (unicode == NULL)
3232 return -1;
3233
3234 err = sys_pyfile_write_unicode(unicode, file);
3235 Py_DECREF(unicode);
3236 return err;
3237}
Guido van Rossuma890e681998-05-12 14:59:24 +00003238
3239/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3240 Adapted from code submitted by Just van Rossum.
3241
3242 PySys_WriteStdout(format, ...)
3243 PySys_WriteStderr(format, ...)
3244
3245 The first function writes to sys.stdout; the second to sys.stderr. When
3246 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003247 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003248
Victor Stinner14284c22010-04-23 12:02:30 +00003249 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003250 signal handlers: they may raise a new exception whereas sys_write()
3251 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003252
Guido van Rossuma890e681998-05-12 14:59:24 +00003253 Both take a printf-style format string as their first argument followed
3254 by a variable length argument list determined by the format string.
3255
3256 *** WARNING ***
3257
3258 The format should limit the total size of the formatted output string to
3259 1000 bytes. In particular, this means that no unrestricted "%s" formats
3260 should occur; these should be limited using "%.<N>s where <N> is a
3261 decimal number calculated so that <N> plus the maximum size of other
3262 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3263 which can print hundreds of digits for very large numbers.
3264
3265 */
3266
3267static void
Victor Stinner09054372013-11-06 22:41:44 +01003268sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 PyObject *file;
3271 PyObject *error_type, *error_value, *error_traceback;
3272 char buffer[1001];
3273 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003274 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003275
Victor Stinner838f2642019-06-13 22:41:23 +02003276 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3277 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3279 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003280 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 fputs(buffer, fp);
3282 }
3283 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3284 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003285 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 }
Victor Stinner838f2642019-06-13 22:41:23 +02003288 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003289}
3290
3291void
Guido van Rossuma890e681998-05-12 14:59:24 +00003292PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003294 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003297 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003299}
3300
3301void
Guido van Rossuma890e681998-05-12 14:59:24 +00003302PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003304 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003306 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003307 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003308 va_end(va);
3309}
3310
3311static void
Victor Stinner09054372013-11-06 22:41:44 +01003312sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003313{
3314 PyObject *file, *message;
3315 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003316 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003317 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003318
Victor Stinner838f2642019-06-13 22:41:23 +02003319 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3320 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003321 message = PyUnicode_FromFormatV(format, va);
3322 if (message != NULL) {
3323 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003324 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003325 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003326 if (utf8 != NULL)
3327 fputs(utf8, fp);
3328 }
3329 Py_DECREF(message);
3330 }
Victor Stinner838f2642019-06-13 22:41:23 +02003331 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003332}
3333
3334void
3335PySys_FormatStdout(const char *format, ...)
3336{
3337 va_list va;
3338
3339 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003340 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003341 va_end(va);
3342}
3343
3344void
3345PySys_FormatStderr(const char *format, ...)
3346{
3347 va_list va;
3348
3349 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003350 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003351 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003352}