blob: b9349effe3c87baa8814b9dca647b7f681d9a961 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020018#include "pycore_ceval.h" // _Py_RecursionLimitLowerWaterMark()
Victor Stinner384621c2020-06-22 17:27:35 +020019#include "pycore_initconfig.h" // _PyStatus_EXCEPTION()
20#include "pycore_object.h" // _PyObject_IS_GC()
21#include "pycore_pathconfig.h" // _PyPathConfig_ComputeSysPath0()
22#include "pycore_pyerrors.h" // _PyErr_Fetch()
23#include "pycore_pylifecycle.h" // _PyErr_WriteUnraisableDefaultHook()
Victor Stinnerd9ea5ca2020-04-15 02:57:50 +020024#include "pycore_pymem.h" // _PyMem_SetDefaultAllocator()
25#include "pycore_pystate.h" // _PyThreadState_GET()
Victor Stinner384621c2020-06-22 17:27:35 +020026#include "pycore_tuple.h" // _PyTuple_FromArray()
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000027
Victor Stinner384621c2020-06-22 17:27:35 +020028#include "code.h"
29#include "frameobject.h" // PyFrame_GetBack()
Victor Stinner361dcdc2020-04-15 03:24:57 +020030#include "pydtrace.h"
31#include "osdefs.h" // DELIM
Victor Stinner9852cb32021-01-25 23:12:50 +010032#include "stdlib_module_names.h" // _Py_stdlib_module_names
Stefan Krah1845d142016-04-25 21:38:53 +020033#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000034
Mark Hammond8696ebc2002-10-08 02:44:31 +000035#ifdef MS_WINDOWS
36#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000037#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000038#endif /* MS_WINDOWS */
39
Guido van Rossum9b38a141996-09-11 23:12:24 +000040#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000041extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000042/* A string loaded from the DLL at startup: */
43extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000044#endif
45
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080046/*[clinic input]
47module sys
48[clinic start generated code]*/
49/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
50
51#include "clinic/sysmodule.c.h"
52
Victor Stinnerbd303c12013-11-07 23:07:29 +010053_Py_IDENTIFIER(_);
54_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070055_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010056_Py_IDENTIFIER(buffer);
57_Py_IDENTIFIER(builtins);
58_Py_IDENTIFIER(encoding);
59_Py_IDENTIFIER(path);
60_Py_IDENTIFIER(stdout);
61_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070062_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010063_Py_IDENTIFIER(write);
64
Victor Stinner838f2642019-06-13 22:41:23 +020065static PyObject *
66sys_get_object_id(PyThreadState *tstate, _Py_Identifier *key)
Victor Stinnerd67bd452013-11-06 22:36:40 +010067{
Victor Stinner838f2642019-06-13 22:41:23 +020068 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020069 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010070 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020071 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +020072 PyObject *exc_type, *exc_value, *exc_tb;
73 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
74 PyObject *value = _PyDict_GetItemIdWithError(sd, key);
75 /* XXX Suppress a new exception if it was raised and restore
76 * the old one. */
77 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
78 return value;
Victor Stinnerd67bd452013-11-06 22:36:40 +010079}
80
81PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +020082_PySys_GetObjectId(_Py_Identifier *key)
83{
84 PyThreadState *tstate = _PyThreadState_GET();
85 return sys_get_object_id(tstate, key);
86}
87
Victor Stinneraf1d64d2020-11-04 17:34:34 +010088static PyObject *
89_PySys_GetObject(PyThreadState *tstate, const char *name)
90{
91 PyObject *sysdict = tstate->interp->sysdict;
92 if (sysdict == NULL) {
93 return NULL;
94 }
95 return _PyDict_GetItemStringWithError(sysdict, name);
96}
97
Victor Stinner838f2642019-06-13 22:41:23 +020098PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000099PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000100{
Victor Stinner838f2642019-06-13 22:41:23 +0200101 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100102
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200103 PyObject *exc_type, *exc_value, *exc_tb;
104 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100105 PyObject *value = _PySys_GetObject(tstate, name);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200106 /* XXX Suppress a new exception if it was raised and restore
107 * the old one. */
108 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
109 return value;
110}
111
112static int
113sys_set_object(PyThreadState *tstate, PyObject *key, PyObject *v)
114{
115 if (key == NULL) {
116 return -1;
117 }
118 PyObject *sd = tstate->interp->sysdict;
119 if (v == NULL) {
120 v = _PyDict_Pop(sd, key, Py_None);
121 if (v == NULL) {
122 return -1;
123 }
124 Py_DECREF(v);
125 return 0;
126 }
127 else {
128 return PyDict_SetItem(sd, key, v);
129 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000130}
131
Victor Stinner838f2642019-06-13 22:41:23 +0200132static int
133sys_set_object_id(PyThreadState *tstate, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +0100134{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200135 return sys_set_object(tstate, _PyUnicode_FromId(key), v);
Victor Stinnerd67bd452013-11-06 22:36:40 +0100136}
137
138int
Victor Stinner838f2642019-06-13 22:41:23 +0200139_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000140{
Victor Stinner838f2642019-06-13 22:41:23 +0200141 PyThreadState *tstate = _PyThreadState_GET();
142 return sys_set_object_id(tstate, key, v);
143}
144
145static int
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200146sys_set_object_str(PyThreadState *tstate, const char *name, PyObject *v)
Victor Stinner838f2642019-06-13 22:41:23 +0200147{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200148 PyObject *key = v ? PyUnicode_InternFromString(name)
149 : PyUnicode_FromString(name);
150 int r = sys_set_object(tstate, key, v);
151 Py_XDECREF(key);
152 return r;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000153}
154
Victor Stinner838f2642019-06-13 22:41:23 +0200155int
156PySys_SetObject(const char *name, PyObject *v)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700157{
Victor Stinner838f2642019-06-13 22:41:23 +0200158 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200159 return sys_set_object_str(tstate, name, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200160}
161
Victor Stinner08faf002020-03-26 18:57:32 +0100162
Victor Stinner838f2642019-06-13 22:41:23 +0200163static int
Victor Stinner08faf002020-03-26 18:57:32 +0100164should_audit(PyInterpreterState *is)
Victor Stinner838f2642019-06-13 22:41:23 +0200165{
Victor Stinner08faf002020-03-26 18:57:32 +0100166 /* tstate->interp cannot be NULL, but test it just in case
167 for extra safety */
168 assert(is != NULL);
169 if (!is) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700170 return 0;
171 }
Victor Stinner08faf002020-03-26 18:57:32 +0100172 return (is->runtime->audit_hook_head
173 || is->audit_hooks
174 || PyDTrace_AUDIT_ENABLED());
Steve Dowerb82e17e2019-05-23 08:45:22 -0700175}
176
Steve Dowerb82e17e2019-05-23 08:45:22 -0700177
Victor Stinner08faf002020-03-26 18:57:32 +0100178static int
179sys_audit_tstate(PyThreadState *ts, const char *event,
180 const char *argFormat, va_list vargs)
181{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700182 /* N format is inappropriate, because you do not know
183 whether the reference is consumed by the call.
184 Assert rather than exception for perf reasons */
185 assert(!argFormat || !strchr(argFormat, 'N'));
186
Victor Stinner08faf002020-03-26 18:57:32 +0100187 if (!ts) {
188 /* Audit hooks cannot be called with a NULL thread state */
Steve Dowerb82e17e2019-05-23 08:45:22 -0700189 return 0;
190 }
191
Victor Stinner08faf002020-03-26 18:57:32 +0100192 /* The current implementation cannot be called if tstate is not
193 the current Python thread state. */
194 assert(ts == _PyThreadState_GET());
195
196 /* Early exit when no hooks are registered */
197 PyInterpreterState *is = ts->interp;
198 if (!should_audit(is)) {
199 return 0;
200 }
201
202 PyObject *eventName = NULL;
203 PyObject *eventArgs = NULL;
204 PyObject *hooks = NULL;
205 PyObject *hook = NULL;
206 int res = -1;
207
Steve Dowerb82e17e2019-05-23 08:45:22 -0700208 int dtrace = PyDTrace_AUDIT_ENABLED();
209
210 PyObject *exc_type, *exc_value, *exc_tb;
Victor Stinner08faf002020-03-26 18:57:32 +0100211 _PyErr_Fetch(ts, &exc_type, &exc_value, &exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700212
213 /* Initialize event args now */
214 if (argFormat && argFormat[0]) {
Victor Stinner08faf002020-03-26 18:57:32 +0100215 eventArgs = _Py_VaBuildValue_SizeT(argFormat, vargs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700216 if (eventArgs && !PyTuple_Check(eventArgs)) {
217 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
218 Py_DECREF(eventArgs);
219 eventArgs = argTuple;
220 }
Victor Stinner08faf002020-03-26 18:57:32 +0100221 }
222 else {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700223 eventArgs = PyTuple_New(0);
224 }
225 if (!eventArgs) {
226 goto exit;
227 }
228
229 /* Call global hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100230 _Py_AuditHookEntry *e = is->runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700231 for (; e; e = e->next) {
232 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
233 goto exit;
234 }
235 }
236
237 /* Dtrace USDT point */
238 if (dtrace) {
Andy Lestere6be9b52020-02-11 20:28:35 -0600239 PyDTrace_AUDIT(event, (void *)eventArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700240 }
241
242 /* Call interpreter hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100243 if (is->audit_hooks) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700244 eventName = PyUnicode_FromString(event);
245 if (!eventName) {
246 goto exit;
247 }
248
249 hooks = PyObject_GetIter(is->audit_hooks);
250 if (!hooks) {
251 goto exit;
252 }
253
254 /* Disallow tracing in hooks unless explicitly enabled */
255 ts->tracing++;
256 ts->use_tracing = 0;
257 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300258 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700259 PyObject *o;
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300260 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700261 if (o) {
262 canTrace = PyObject_IsTrue(o);
263 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700264 }
265 if (canTrace < 0) {
266 break;
267 }
268 if (canTrace) {
269 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
270 ts->tracing--;
271 }
Victor Stinner08faf002020-03-26 18:57:32 +0100272 PyObject* args[2] = {eventName, eventArgs};
273 o = _PyObject_FastCallTstate(ts, hook, args, 2);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700274 if (canTrace) {
275 ts->tracing++;
276 ts->use_tracing = 0;
277 }
278 if (!o) {
279 break;
280 }
281 Py_DECREF(o);
282 Py_CLEAR(hook);
283 }
284 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
285 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200286 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700287 goto exit;
288 }
289 }
290
291 res = 0;
292
293exit:
294 Py_XDECREF(hook);
295 Py_XDECREF(hooks);
296 Py_XDECREF(eventName);
297 Py_XDECREF(eventArgs);
298
Victor Stinner08faf002020-03-26 18:57:32 +0100299 if (!res) {
300 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
301 }
302 else {
303 assert(_PyErr_Occurred(ts));
304 Py_XDECREF(exc_type);
305 Py_XDECREF(exc_value);
306 Py_XDECREF(exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700307 }
308
309 return res;
310}
311
Victor Stinner08faf002020-03-26 18:57:32 +0100312int
313_PySys_Audit(PyThreadState *tstate, const char *event,
314 const char *argFormat, ...)
315{
316 va_list vargs;
317#ifdef HAVE_STDARG_PROTOTYPES
318 va_start(vargs, argFormat);
319#else
320 va_start(vargs);
321#endif
322 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
323 va_end(vargs);
324 return res;
325}
326
327int
328PySys_Audit(const char *event, const char *argFormat, ...)
329{
330 PyThreadState *tstate = _PyThreadState_GET();
331 va_list vargs;
332#ifdef HAVE_STDARG_PROTOTYPES
333 va_start(vargs, argFormat);
334#else
335 va_start(vargs);
336#endif
337 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
338 va_end(vargs);
339 return res;
340}
341
Steve Dowerb82e17e2019-05-23 08:45:22 -0700342/* We expose this function primarily for our own cleanup during
343 * finalization. In general, it should not need to be called,
Victor Stinner08faf002020-03-26 18:57:32 +0100344 * and as such the function is not exported.
345 *
346 * Must be finalizing to clear hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200347void
Victor Stinner08faf002020-03-26 18:57:32 +0100348_PySys_ClearAuditHooks(PyThreadState *ts)
Victor Stinner838f2642019-06-13 22:41:23 +0200349{
Victor Stinner08faf002020-03-26 18:57:32 +0100350 assert(ts != NULL);
351 if (!ts) {
352 return;
353 }
354
355 _PyRuntimeState *runtime = ts->interp->runtime;
Victor Stinner7b3c2522020-03-07 00:24:23 +0100356 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
Victor Stinner08faf002020-03-26 18:57:32 +0100357 assert(finalizing == ts);
358 if (finalizing != ts) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700359 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200360 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700361
Victor Stinnerda7933e2020-04-13 03:04:28 +0200362 const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
Victor Stinner838f2642019-06-13 22:41:23 +0200363 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700364 PySys_WriteStderr("# clear sys.audit hooks\n");
365 }
366
367 /* Hooks can abort later hooks for this event, but cannot
368 abort the clear operation itself. */
Victor Stinner08faf002020-03-26 18:57:32 +0100369 _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200370 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700371
Victor Stinner08faf002020-03-26 18:57:32 +0100372 _Py_AuditHookEntry *e = runtime->audit_hook_head, *n;
373 runtime->audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700374 while (e) {
375 n = e->next;
376 PyMem_RawFree(e);
377 e = n;
378 }
379}
380
381int
382PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
383{
Victor Stinner08faf002020-03-26 18:57:32 +0100384 /* tstate can be NULL, so access directly _PyRuntime:
385 PySys_AddAuditHook() can be called before Python is initialized. */
Victor Stinner838f2642019-06-13 22:41:23 +0200386 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner08faf002020-03-26 18:57:32 +0100387 PyThreadState *tstate;
388 if (runtime->initialized) {
389 tstate = _PyRuntimeState_GetThreadState(runtime);
390 }
391 else {
392 tstate = NULL;
393 }
Victor Stinner838f2642019-06-13 22:41:23 +0200394
Steve Dowerb82e17e2019-05-23 08:45:22 -0700395 /* Invoke existing audit hooks to allow them an opportunity to abort. */
396 /* Cannot invoke hooks until we are initialized */
Victor Stinner08faf002020-03-26 18:57:32 +0100397 if (tstate != NULL) {
398 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800399 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
400 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200401 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700402 return 0;
403 }
404 return -1;
405 }
406 }
407
Victor Stinner08faf002020-03-26 18:57:32 +0100408 _Py_AuditHookEntry *e = runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700409 if (!e) {
410 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner08faf002020-03-26 18:57:32 +0100411 runtime->audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700412 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200413 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700414 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200415 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700416 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
417 sizeof(_Py_AuditHookEntry));
418 }
419
420 if (!e) {
Victor Stinner08faf002020-03-26 18:57:32 +0100421 if (tstate != NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200422 _PyErr_NoMemory(tstate);
423 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700424 return -1;
425 }
426
427 e->next = NULL;
428 e->hookCFunction = (Py_AuditHookFunction)hook;
429 e->userData = userData;
430
431 return 0;
432}
433
434/*[clinic input]
435sys.addaudithook
436
437 hook: object
438
439Adds a new audit hook callback.
440[clinic start generated code]*/
441
442static PyObject *
443sys_addaudithook_impl(PyObject *module, PyObject *hook)
444/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
445{
Victor Stinner838f2642019-06-13 22:41:23 +0200446 PyThreadState *tstate = _PyThreadState_GET();
447
Steve Dowerb82e17e2019-05-23 08:45:22 -0700448 /* Invoke existing audit hooks to allow them an opportunity to abort. */
Victor Stinner08faf002020-03-26 18:57:32 +0100449 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200450 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700451 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200452 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700453 Py_RETURN_NONE;
454 }
455 return NULL;
456 }
457
Victor Stinner838f2642019-06-13 22:41:23 +0200458 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700459 if (is->audit_hooks == NULL) {
460 is->audit_hooks = PyList_New(0);
461 if (is->audit_hooks == NULL) {
462 return NULL;
463 }
464 }
465
466 if (PyList_Append(is->audit_hooks, hook) < 0) {
467 return NULL;
468 }
469
470 Py_RETURN_NONE;
471}
472
473PyDoc_STRVAR(audit_doc,
474"audit(event, *args)\n\
475\n\
476Passes the event to any audit hooks that are attached.");
477
478static PyObject *
479sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
480{
Victor Stinner838f2642019-06-13 22:41:23 +0200481 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200482 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner838f2642019-06-13 22:41:23 +0200483
Steve Dowerb82e17e2019-05-23 08:45:22 -0700484 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200485 _PyErr_SetString(tstate, PyExc_TypeError,
486 "audit() missing 1 required positional argument: "
487 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700488 return NULL;
489 }
490
Victor Stinner08faf002020-03-26 18:57:32 +0100491 if (!should_audit(tstate->interp)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700492 Py_RETURN_NONE;
493 }
494
495 PyObject *auditEvent = args[0];
496 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200497 _PyErr_SetString(tstate, PyExc_TypeError,
498 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700499 return NULL;
500 }
501 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200502 _PyErr_Format(tstate, PyExc_TypeError,
503 "expected str for argument 'event', not %.200s",
504 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700505 return NULL;
506 }
507 const char *event = PyUnicode_AsUTF8(auditEvent);
508 if (!event) {
509 return NULL;
510 }
511
512 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
513 if (!auditArgs) {
514 return NULL;
515 }
516
Victor Stinner08faf002020-03-26 18:57:32 +0100517 int res = _PySys_Audit(tstate, event, "O", auditArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700518 Py_DECREF(auditArgs);
519
520 if (res < 0) {
521 return NULL;
522 }
523
524 Py_RETURN_NONE;
525}
526
527
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400528static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200529sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400530{
Victor Stinner838f2642019-06-13 22:41:23 +0200531 PyThreadState *tstate = _PyThreadState_GET();
532 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300533 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400534
535 if (envar == NULL || strlen(envar) == 0) {
536 envar = "pdb.set_trace";
537 }
538 else if (!strcmp(envar, "0")) {
539 /* The breakpoint is explicitly no-op'd. */
540 Py_RETURN_NONE;
541 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300542 /* According to POSIX the string returned by getenv() might be invalidated
543 * or the string content might be overwritten by a subsequent call to
544 * getenv(). Since importing a module can performs the getenv() calls,
545 * we need to save a copy of envar. */
546 envar = _PyMem_RawStrdup(envar);
547 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200548 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300549 return NULL;
550 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200551 const char *last_dot = strrchr(envar, '.');
552 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400553 PyObject *modulepath = NULL;
554
555 if (last_dot == NULL) {
556 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
557 modulepath = PyUnicode_FromString("builtins");
558 attrname = envar;
559 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200560 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400561 /* Split on the last dot; */
562 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
563 attrname = last_dot + 1;
564 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200565 else {
566 goto warn;
567 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400568 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300569 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400570 return NULL;
571 }
572
Anthony Sottiledce345c2018-11-01 10:25:05 -0700573 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400574 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400575
576 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200577 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200578 goto warn;
579 }
580 PyMem_RawFree(envar);
581 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400582 }
583
584 PyObject *hook = PyObject_GetAttrString(module, attrname);
585 Py_DECREF(module);
586
587 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200588 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200589 goto warn;
590 }
591 PyMem_RawFree(envar);
592 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400593 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300594 PyMem_RawFree(envar);
Petr Viktorinffd97532020-02-11 17:46:57 +0100595 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400596 Py_DECREF(hook);
597 return retval;
598
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200599 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400600 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200601 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400602 int status = PyErr_WarnFormat(
603 PyExc_RuntimeWarning, 0,
604 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300605 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400606 if (status < 0) {
607 /* Printing the warning raised an exception. */
608 return NULL;
609 }
610 /* The warning was (probably) issued. */
611 Py_RETURN_NONE;
612}
613
614PyDoc_STRVAR(breakpointhook_doc,
615"breakpointhook(*args, **kws)\n"
616"\n"
617"This hook function is called by built-in breakpoint().\n"
618);
619
Victor Stinner13d49ee2010-12-04 17:24:33 +0000620/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
621 error handler. If sys.stdout has a buffer attribute, use
622 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
623 sys.stdout.write(redecoded).
624
625 Helper function for sys_displayhook(). */
626static int
Andy Lesterda4d6562020-03-05 22:34:36 -0600627sys_displayhook_unencodable(PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000628{
629 PyObject *stdout_encoding = NULL;
630 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200631 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000632 int ret;
633
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200634 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000635 if (stdout_encoding == NULL)
636 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200637 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000638 if (stdout_encoding_str == NULL)
639 goto error;
640
641 repr_str = PyObject_Repr(o);
642 if (repr_str == NULL)
643 goto error;
644 encoded = PyUnicode_AsEncodedString(repr_str,
645 stdout_encoding_str,
646 "backslashreplace");
647 Py_DECREF(repr_str);
648 if (encoded == NULL)
649 goto error;
650
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300651 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
652 Py_DECREF(encoded);
653 goto error;
654 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000655 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200656 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000657 Py_DECREF(buffer);
658 Py_DECREF(encoded);
659 if (result == NULL)
660 goto error;
661 Py_DECREF(result);
662 }
663 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000664 escaped_str = PyUnicode_FromEncodedObject(encoded,
665 stdout_encoding_str,
666 "strict");
667 Py_DECREF(encoded);
668 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
669 Py_DECREF(escaped_str);
670 goto error;
671 }
672 Py_DECREF(escaped_str);
673 }
674 ret = 0;
675 goto finally;
676
677error:
678 ret = -1;
679finally:
680 Py_XDECREF(stdout_encoding);
681 return ret;
682}
683
Tal Einatede0b6f2018-12-31 17:12:08 +0200684/*[clinic input]
685sys.displayhook
686
687 object as o: object
688 /
689
690Print an object to sys.stdout and also save it in builtins._
691[clinic start generated code]*/
692
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000693static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200694sys_displayhook(PyObject *module, PyObject *o)
695/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000697 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100698 PyObject *builtins;
699 static PyObject *newline = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200700 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000701
Eric Snow3f9eee62017-09-15 16:35:20 -0600702 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000703 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200704 if (!_PyErr_Occurred(tstate)) {
705 _PyErr_SetString(tstate, PyExc_RuntimeError,
706 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100707 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 return NULL;
709 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600710 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 /* Print value except if None */
713 /* After printing, also assign to '_' */
714 /* Before, set '_' to None to avoid recursion */
715 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200716 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200718 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000719 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200720 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000721 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200722 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 return NULL;
724 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000725 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200726 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Andy Lesterda4d6562020-03-05 22:34:36 -0600727 int err;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000728 /* repr(o) is not encodable to sys.stdout.encoding with
729 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200730 _PyErr_Clear(tstate);
Andy Lesterda4d6562020-03-05 22:34:36 -0600731 err = sys_displayhook_unencodable(outf, o);
Victor Stinner838f2642019-06-13 22:41:23 +0200732 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000733 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200734 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000735 }
736 else {
737 return NULL;
738 }
739 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100740 if (newline == NULL) {
741 newline = PyUnicode_FromString("\n");
742 if (newline == NULL)
743 return NULL;
744 }
745 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000746 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200747 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000748 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200749 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000750}
751
Tal Einatede0b6f2018-12-31 17:12:08 +0200752
753/*[clinic input]
754sys.excepthook
755
756 exctype: object
757 value: object
758 traceback: object
759 /
760
761Handle an exception by displaying it with a traceback on sys.stderr.
762[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000763
764static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200765sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
766 PyObject *traceback)
767/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000768{
Tal Einatede0b6f2018-12-31 17:12:08 +0200769 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200770 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000771}
772
Tal Einatede0b6f2018-12-31 17:12:08 +0200773
774/*[clinic input]
775sys.exc_info
776
777Return current exception information: (type, value, traceback).
778
779Return information about the most recent exception caught by an except
780clause in the current stack frame or in an older stack frame.
781[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000782
783static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200784sys_exc_info_impl(PyObject *module)
785/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000786{
Victor Stinner50b48572018-11-01 01:51:40 +0100787 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000788 return Py_BuildValue(
789 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100790 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
791 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
792 err_info->exc_traceback != NULL ?
793 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000794}
795
Tal Einatede0b6f2018-12-31 17:12:08 +0200796
797/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200798sys.unraisablehook
799
800 unraisable: object
801 /
802
803Handle an unraisable exception.
804
805The unraisable argument has the following attributes:
806
807* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200808* exc_value: Exception value, can be None.
809* exc_traceback: Exception traceback, can be None.
810* err_msg: Error message, can be None.
811* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200812[clinic start generated code]*/
813
814static PyObject *
815sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200816/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200817{
818 return _PyErr_WriteUnraisableDefaultHook(unraisable);
819}
820
821
822/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200823sys.exit
824
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300825 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200826 /
827
828Exit the interpreter by raising SystemExit(status).
829
830If the status is omitted or None, it defaults to zero (i.e., success).
831If the status is an integer, it will be used as the system exit status.
832If it is another kind of object, it will be printed and the system
833exit status will be one (i.e., failure).
834[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000835
836static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200837sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300838/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000839{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinner838f2642019-06-13 22:41:23 +0200841 PyThreadState *tstate = _PyThreadState_GET();
842 _PyErr_SetObject(tstate, PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000843 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000844}
845
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000846
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000847
Tal Einatede0b6f2018-12-31 17:12:08 +0200848/*[clinic input]
849sys.getdefaultencoding
850
851Return the current default encoding used by the Unicode implementation.
852[clinic start generated code]*/
853
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000854static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200855sys_getdefaultencoding_impl(PyObject *module)
856/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000859}
860
Tal Einatede0b6f2018-12-31 17:12:08 +0200861/*[clinic input]
862sys.getfilesystemencoding
863
864Return the encoding used to convert Unicode filenames to OS filenames.
865[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000866
867static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200868sys_getfilesystemencoding_impl(PyObject *module)
869/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000870{
Victor Stinner81a7be32020-04-14 15:14:01 +0200871 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200872 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400873 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000874}
875
Tal Einatede0b6f2018-12-31 17:12:08 +0200876/*[clinic input]
877sys.getfilesystemencodeerrors
878
879Return the error mode used Unicode to OS filename conversion.
880[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000881
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000882static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200883sys_getfilesystemencodeerrors_impl(PyObject *module)
884/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700885{
Victor Stinner81a7be32020-04-14 15:14:01 +0200886 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200887 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400888 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700889}
890
Tal Einatede0b6f2018-12-31 17:12:08 +0200891/*[clinic input]
892sys.intern
893
894 string as s: unicode
895 /
896
897``Intern'' the given string.
898
899This enters the string in the (global) table of interned strings whose
900purpose is to speed up dictionary lookups. Return the string itself or
901the previously interned string object with the same value.
902[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700903
904static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200905sys_intern_impl(PyObject *module, PyObject *s)
906/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000907{
Victor Stinner838f2642019-06-13 22:41:23 +0200908 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 if (PyUnicode_CheckExact(s)) {
910 Py_INCREF(s);
911 PyUnicode_InternInPlace(&s);
912 return s;
913 }
914 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200915 _PyErr_Format(tstate, PyExc_TypeError,
Victor Stinnera102ed72020-02-07 02:24:48 +0100916 "can't intern %.400s", Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 return NULL;
918 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000919}
920
Georg Brandl66a796e2006-12-19 20:50:34 +0000921
Fred Drake5755ce62001-06-27 19:19:46 +0000922/*
923 * Cached interned string objects used for calling the profile and
924 * trace functions. Initialized by trace_init().
925 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000926static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000927
928static int
929trace_init(void)
930{
Nick Coghlan5a851672017-09-08 10:14:16 +1000931 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200932 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000933 "c_call", "c_exception", "c_return",
934 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200935 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyObject *name;
937 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000938 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 if (whatstrings[i] == NULL) {
940 name = PyUnicode_InternFromString(whatnames[i]);
941 if (name == NULL)
942 return -1;
943 whatstrings[i] = name;
944 }
945 }
946 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000947}
948
949
950static PyObject *
Victor Stinner309d7cc2020-03-13 16:39:12 +0100951call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000952 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000953{
Victor Stinner78da82b2016-08-20 01:22:57 +0200954 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200956 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100957
Victor Stinner838f2642019-06-13 22:41:23 +0200958 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200959 stack[0] = (PyObject *)frame;
960 stack[1] = whatstrings[what];
961 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 /* call the Python-level function */
Victor Stinner309d7cc2020-03-13 16:39:12 +0100964 PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000965
Victor Stinner78da82b2016-08-20 01:22:57 +0200966 PyFrame_LocalsToFast(frame, 1);
967 if (result == NULL) {
968 PyTraceBack_Here(frame);
969 }
970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000972}
973
974static int
975profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000977{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100978 if (arg == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 arg = Py_None;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100980 }
981
982 PyThreadState *tstate = _PyThreadState_GET();
983 PyObject *result = call_trampoline(tstate, self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100985 _PyEval_SetProfile(tstate, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return -1;
987 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 Py_DECREF(result);
990 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000991}
992
993static int
994trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000996{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 PyObject *callback;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100998 if (what == PyTrace_CALL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 callback = self;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001000 }
1001 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 callback = frame->f_trace;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001003 }
1004 if (callback == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return 0;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001006 }
1007
1008 PyThreadState *tstate = _PyThreadState_GET();
1009 PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01001011 _PyEval_SetTrace(tstate, NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001012 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return -1;
1014 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01001015
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001016 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +03001017 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 }
1019 else {
1020 Py_DECREF(result);
1021 }
1022 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00001023}
Fred Draked0838392001-06-16 21:02:31 +00001024
Fred Drake8b4d01d2000-05-09 19:57:01 +00001025static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001026sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001027{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001028 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001030 }
1031
1032 PyThreadState *tstate = _PyThreadState_GET();
1033 if (args == Py_None) {
1034 if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
1035 return NULL;
1036 }
1037 }
1038 else {
1039 if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
1040 return NULL;
1041 }
1042 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001043 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001044}
1045
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001046PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001047"settrace(function)\n\
1048\n\
1049Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001050function call. See the debugger chapter in the library manual."
1051);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001052
Tal Einatede0b6f2018-12-31 17:12:08 +02001053/*[clinic input]
1054sys.gettrace
1055
1056Return the global debug tracing function set with sys.settrace.
1057
1058See the debugger chapter in the library manual.
1059[clinic start generated code]*/
1060
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001061static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001062sys_gettrace_impl(PyObject *module)
1063/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001064{
Victor Stinner50b48572018-11-01 01:51:40 +01001065 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001067
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 if (temp == NULL)
1069 temp = Py_None;
1070 Py_INCREF(temp);
1071 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001072}
1073
Christian Heimes9bd667a2008-01-20 15:14:11 +00001074static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001075sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001076{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001077 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001079 }
1080
1081 PyThreadState *tstate = _PyThreadState_GET();
1082 if (args == Py_None) {
1083 if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1084 return NULL;
1085 }
1086 }
1087 else {
1088 if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
1089 return NULL;
1090 }
1091 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001092 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001093}
1094
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001095PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001096"setprofile(function)\n\
1097\n\
1098Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001099and return. See the profiler chapter in the library manual."
1100);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001101
Tal Einatede0b6f2018-12-31 17:12:08 +02001102/*[clinic input]
1103sys.getprofile
1104
1105Return the profiling function set with sys.setprofile.
1106
1107See the profiler chapter in the library manual.
1108[clinic start generated code]*/
1109
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001110static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001111sys_getprofile_impl(PyObject *module)
1112/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001113{
Victor Stinner50b48572018-11-01 01:51:40 +01001114 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001117 if (temp == NULL)
1118 temp = Py_None;
1119 Py_INCREF(temp);
1120 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001121}
1122
Tim Peterse5e065b2003-07-06 18:36:54 +00001123
Tal Einatede0b6f2018-12-31 17:12:08 +02001124/*[clinic input]
1125sys.setswitchinterval
1126
1127 interval: double
1128 /
1129
1130Set the ideal thread switching delay inside the Python interpreter.
1131
1132The actual frequency of switching threads can be lower if the
1133interpreter executes long sequences of uninterruptible code
1134(this is implementation-specific and workload-dependent).
1135
1136The parameter must represent the desired switching delay in seconds
1137A typical value is 0.005 (5 milliseconds).
1138[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001139
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001140static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001141sys_setswitchinterval_impl(PyObject *module, double interval)
1142/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001143{
Victor Stinner838f2642019-06-13 22:41:23 +02001144 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001145 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001146 _PyErr_SetString(tstate, PyExc_ValueError,
1147 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 return NULL;
1149 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001150 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001151 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001152}
1153
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001154
Tal Einatede0b6f2018-12-31 17:12:08 +02001155/*[clinic input]
1156sys.getswitchinterval -> double
1157
1158Return the current thread switch interval; see sys.setswitchinterval().
1159[clinic start generated code]*/
1160
1161static double
1162sys_getswitchinterval_impl(PyObject *module)
1163/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001164{
Tal Einatede0b6f2018-12-31 17:12:08 +02001165 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001166}
1167
Tal Einatede0b6f2018-12-31 17:12:08 +02001168/*[clinic input]
1169sys.setrecursionlimit
1170
1171 limit as new_limit: int
1172 /
1173
1174Set the maximum depth of the Python interpreter stack to n.
1175
1176This limit prevents infinite recursion from causing an overflow of the C
1177stack and crashing Python. The highest possible limit is platform-
1178dependent.
1179[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001180
Tim Peterse5e065b2003-07-06 18:36:54 +00001181static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001182sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1183/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001184{
Victor Stinner838f2642019-06-13 22:41:23 +02001185 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001186
Victor Stinner50856d52015-10-13 00:11:21 +02001187 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001188 _PyErr_SetString(tstate, PyExc_ValueError,
1189 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 return NULL;
1191 }
Victor Stinner50856d52015-10-13 00:11:21 +02001192
1193 /* Issue #25274: When the recursion depth hits the recursion limit in
1194 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1195 set to 1 and a RecursionError is raised. The overflowed flag is reset
1196 to 0 when the recursion depth goes below the low-water mark: see
1197 Py_LeaveRecursiveCall().
1198
1199 Reject too low new limit if the current recursion depth is higher than
1200 the new low-water mark. Otherwise it may not be possible anymore to
1201 reset the overflowed flag to 0. */
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001202 if (tstate->recursion_depth >= new_limit) {
Victor Stinner838f2642019-06-13 22:41:23 +02001203 _PyErr_Format(tstate, PyExc_RecursionError,
1204 "cannot set the recursion limit to %i at "
1205 "the recursion depth %i: the limit is too low",
1206 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001207 return NULL;
1208 }
1209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001211 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001212}
1213
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001214/*[clinic input]
1215sys.set_coroutine_origin_tracking_depth
1216
1217 depth: int
1218
1219Enable or disable origin tracking for coroutine objects in this thread.
1220
Tal Einatede0b6f2018-12-31 17:12:08 +02001221Coroutine objects will track 'depth' frames of traceback information
1222about where they came from, available in their cr_origin attribute.
1223
1224Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001225[clinic start generated code]*/
1226
1227static PyObject *
1228sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001229/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001230{
Victor Stinner838f2642019-06-13 22:41:23 +02001231 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001232 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001233 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001234 return NULL;
1235 }
Victor Stinner838f2642019-06-13 22:41:23 +02001236 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001237 Py_RETURN_NONE;
1238}
1239
1240/*[clinic input]
1241sys.get_coroutine_origin_tracking_depth -> int
1242
1243Check status of origin tracking for coroutine objects in this thread.
1244[clinic start generated code]*/
1245
1246static int
1247sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1248/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1249{
1250 return _PyEval_GetCoroutineOriginTrackingDepth();
1251}
1252
Yury Selivanoveb636452016-09-08 22:01:51 -07001253static PyTypeObject AsyncGenHooksType;
1254
1255PyDoc_STRVAR(asyncgen_hooks_doc,
1256"asyncgen_hooks\n\
1257\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001258A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001259generators hooks. The attributes are read only.");
1260
1261static PyStructSequence_Field asyncgen_hooks_fields[] = {
1262 {"firstiter", "Hook to intercept first iteration"},
1263 {"finalizer", "Hook to intercept finalization"},
1264 {0}
1265};
1266
1267static PyStructSequence_Desc asyncgen_hooks_desc = {
1268 "asyncgen_hooks", /* name */
1269 asyncgen_hooks_doc, /* doc */
1270 asyncgen_hooks_fields , /* fields */
1271 2
1272};
1273
Yury Selivanoveb636452016-09-08 22:01:51 -07001274static PyObject *
1275sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1276{
1277 static char *keywords[] = {"firstiter", "finalizer", NULL};
1278 PyObject *firstiter = NULL;
1279 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001280 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001281
1282 if (!PyArg_ParseTupleAndKeywords(
1283 args, kw, "|OO", keywords,
1284 &firstiter, &finalizer)) {
1285 return NULL;
1286 }
1287
1288 if (finalizer && finalizer != Py_None) {
1289 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001290 _PyErr_Format(tstate, PyExc_TypeError,
1291 "callable finalizer expected, got %.50s",
1292 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001293 return NULL;
1294 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001295 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1296 return NULL;
1297 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001298 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001299 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1300 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001301 }
1302
1303 if (firstiter && firstiter != Py_None) {
1304 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001305 _PyErr_Format(tstate, PyExc_TypeError,
1306 "callable firstiter expected, got %.50s",
1307 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001308 return NULL;
1309 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001310 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1311 return NULL;
1312 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001313 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001314 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1315 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001316 }
1317
1318 Py_RETURN_NONE;
1319}
1320
1321PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001322"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001323\n\
1324Set a finalizer for async generators objects."
1325);
1326
Tal Einatede0b6f2018-12-31 17:12:08 +02001327/*[clinic input]
1328sys.get_asyncgen_hooks
1329
1330Return the installed asynchronous generators hooks.
1331
1332This returns a namedtuple of the form (firstiter, finalizer).
1333[clinic start generated code]*/
1334
Yury Selivanoveb636452016-09-08 22:01:51 -07001335static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001336sys_get_asyncgen_hooks_impl(PyObject *module)
1337/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001338{
1339 PyObject *res;
1340 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1341 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1342
1343 res = PyStructSequence_New(&AsyncGenHooksType);
1344 if (res == NULL) {
1345 return NULL;
1346 }
1347
1348 if (firstiter == NULL) {
1349 firstiter = Py_None;
1350 }
1351
1352 if (finalizer == NULL) {
1353 finalizer = Py_None;
1354 }
1355
1356 Py_INCREF(firstiter);
1357 PyStructSequence_SET_ITEM(res, 0, firstiter);
1358
1359 Py_INCREF(finalizer);
1360 PyStructSequence_SET_ITEM(res, 1, finalizer);
1361
1362 return res;
1363}
1364
Yury Selivanoveb636452016-09-08 22:01:51 -07001365
Mark Dickinsondc787d22010-05-23 13:33:13 +00001366static PyTypeObject Hash_InfoType;
1367
1368PyDoc_STRVAR(hash_info_doc,
1369"hash_info\n\
1370\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001371A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001372hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001373
1374static PyStructSequence_Field hash_info_fields[] = {
1375 {"width", "width of the type used for hashing, in bits"},
1376 {"modulus", "prime number giving the modulus on which the hash "
1377 "function is based"},
1378 {"inf", "value to be used for hash of a positive infinity"},
1379 {"nan", "value to be used for hash of a nan"},
1380 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001381 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1382 "memoryviews"},
1383 {"hash_bits", "internal output size of hash algorithm"},
1384 {"seed_bits", "seed size of hash algorithm"},
1385 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001386 {NULL, NULL}
1387};
1388
1389static PyStructSequence_Desc hash_info_desc = {
1390 "sys.hash_info",
1391 hash_info_doc,
1392 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001393 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001394};
1395
Matthias Klosed885e952010-07-06 10:53:30 +00001396static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001397get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001398{
1399 PyObject *hash_info;
1400 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001401 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001402 hash_info = PyStructSequence_New(&Hash_InfoType);
1403 if (hash_info == NULL)
1404 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001405 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001406 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001407 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001408 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001409 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001410 PyStructSequence_SET_ITEM(hash_info, field++,
1411 PyLong_FromLong(_PyHASH_INF));
1412 PyStructSequence_SET_ITEM(hash_info, field++,
1413 PyLong_FromLong(_PyHASH_NAN));
1414 PyStructSequence_SET_ITEM(hash_info, field++,
1415 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001416 PyStructSequence_SET_ITEM(hash_info, field++,
1417 PyUnicode_FromString(hashfunc->name));
1418 PyStructSequence_SET_ITEM(hash_info, field++,
1419 PyLong_FromLong(hashfunc->hash_bits));
1420 PyStructSequence_SET_ITEM(hash_info, field++,
1421 PyLong_FromLong(hashfunc->seed_bits));
1422 PyStructSequence_SET_ITEM(hash_info, field++,
1423 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001424 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001425 Py_CLEAR(hash_info);
1426 return NULL;
1427 }
1428 return hash_info;
1429}
Tal Einatede0b6f2018-12-31 17:12:08 +02001430/*[clinic input]
1431sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001432
Tal Einatede0b6f2018-12-31 17:12:08 +02001433Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001434
Tal Einatede0b6f2018-12-31 17:12:08 +02001435The recursion limit is the maximum depth of the Python interpreter
1436stack. This limit prevents infinite recursion from causing an overflow
1437of the C stack and crashing Python.
1438[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001439
1440static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001441sys_getrecursionlimit_impl(PyObject *module)
1442/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001445}
1446
Mark Hammond8696ebc2002-10-08 02:44:31 +00001447#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001448
Eric Smithf7bb5782010-01-27 00:44:57 +00001449static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1450
1451static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 {"major", "Major version number"},
1453 {"minor", "Minor version number"},
1454 {"build", "Build number"},
1455 {"platform", "Operating system platform"},
1456 {"service_pack", "Latest Service Pack installed on the system"},
1457 {"service_pack_major", "Service Pack major version number"},
1458 {"service_pack_minor", "Service Pack minor version number"},
1459 {"suite_mask", "Bit mask identifying available product suites"},
1460 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001461 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001463};
1464
1465static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001466 "sys.getwindowsversion", /* name */
1467 sys_getwindowsversion__doc__, /* doc */
1468 windows_version_fields, /* fields */
1469 5 /* For backward compatibility,
1470 only the first 5 items are accessible
1471 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001472};
1473
Steve Dower3e96f322015-03-02 08:01:10 -08001474/* Disable deprecation warnings about GetVersionEx as the result is
1475 being passed straight through to the caller, who is responsible for
1476 using it correctly. */
1477#pragma warning(push)
1478#pragma warning(disable:4996)
1479
Tal Einatede0b6f2018-12-31 17:12:08 +02001480/*[clinic input]
1481sys.getwindowsversion
1482
1483Return info about the running version of Windows as a named tuple.
1484
1485The members are named: major, minor, build, platform, service_pack,
1486service_pack_major, service_pack_minor, suite_mask, product_type and
1487platform_version. For backward compatibility, only the first 5 items
1488are available by indexing. All elements are numbers, except
1489service_pack and platform_type which are strings, and platform_version
1490which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1491workstation, 2 for a domain controller, 3 for a server.
1492Platform_version is a 3-tuple containing a version number that is
1493intended for identifying the OS rather than feature detection.
1494[clinic start generated code]*/
1495
Mark Hammond8696ebc2002-10-08 02:44:31 +00001496static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001497sys_getwindowsversion_impl(PyObject *module)
1498/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 PyObject *version;
1501 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001502 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001503 DWORD realMajor, realMinor, realBuild;
1504 HANDLE hKernel32;
1505 wchar_t kernel32_path[MAX_PATH];
1506 LPVOID verblock;
1507 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001508 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001511 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 version = PyStructSequence_New(&WindowsVersionType);
1515 if (version == NULL)
1516 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1519 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1520 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1521 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001522 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1524 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1525 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1526 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001527
Steve Dower74f4af72016-09-17 17:27:48 -07001528 realMajor = ver.dwMajorVersion;
1529 realMinor = ver.dwMinorVersion;
1530 realBuild = ver.dwBuildNumber;
1531
1532 // GetVersion will lie if we are running in a compatibility mode.
1533 // We need to read the version info from a system file resource
1534 // to accurately identify the OS version. If we fail for any reason,
1535 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001536 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001537 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001538 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001539 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1540 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1541 (verblock = PyMem_RawMalloc(verblock_size))) {
1542 VS_FIXEDFILEINFO *ffi;
1543 UINT ffi_len;
1544
1545 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1546 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1547 realMajor = HIWORD(ffi->dwProductVersionMS);
1548 realMinor = LOWORD(ffi->dwProductVersionMS);
1549 realBuild = HIWORD(ffi->dwProductVersionLS);
1550 }
1551 PyMem_RawFree(verblock);
1552 }
Segev Finer48fb7662017-06-04 20:52:27 +03001553 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1554 realMajor,
1555 realMinor,
1556 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001557 ));
1558
Victor Stinner838f2642019-06-13 22:41:23 +02001559 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001560 Py_DECREF(version);
1561 return NULL;
1562 }
Steve Dower74f4af72016-09-17 17:27:48 -07001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001565}
1566
Steve Dower3e96f322015-03-02 08:01:10 -08001567#pragma warning(pop)
1568
Tal Einatede0b6f2018-12-31 17:12:08 +02001569/*[clinic input]
1570sys._enablelegacywindowsfsencoding
1571
1572Changes the default filesystem encoding to mbcs:replace.
1573
1574This is done for consistency with earlier versions of Python. See PEP
1575529 for more information.
1576
1577This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1578environment variable before launching Python.
1579[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001580
1581static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001582sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1583/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001584{
Victor Stinner709d23d2019-05-02 14:56:30 -04001585 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001586 return NULL;
1587 }
Steve Dowercc16be82016-09-08 10:35:16 -07001588 Py_RETURN_NONE;
1589}
1590
Mark Hammond8696ebc2002-10-08 02:44:31 +00001591#endif /* MS_WINDOWS */
1592
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001593#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001594
1595/*[clinic input]
1596sys.setdlopenflags
1597
1598 flags as new_val: int
1599 /
1600
1601Set the flags used by the interpreter for dlopen calls.
1602
1603This is used, for example, when the interpreter loads extension
1604modules. Among other things, this will enable a lazy resolving of
1605symbols when importing a module, if called as sys.setdlopenflags(0).
1606To share symbols across extension modules, call as
1607sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1608modules can be found in the os module (RTLD_xxx constants, e.g.
1609os.RTLD_LAZY).
1610[clinic start generated code]*/
1611
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001612static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001613sys_setdlopenflags_impl(PyObject *module, int new_val)
1614/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001615{
Victor Stinner838f2642019-06-13 22:41:23 +02001616 PyThreadState *tstate = _PyThreadState_GET();
1617 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001618 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001619}
1620
Tal Einatede0b6f2018-12-31 17:12:08 +02001621
1622/*[clinic input]
1623sys.getdlopenflags
1624
1625Return the current value of the flags that are used for dlopen calls.
1626
1627The flag constants are defined in the os module.
1628[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001629
1630static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001631sys_getdlopenflags_impl(PyObject *module)
1632/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001633{
Victor Stinner838f2642019-06-13 22:41:23 +02001634 PyThreadState *tstate = _PyThreadState_GET();
1635 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001636}
1637
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001639
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001640#ifdef USE_MALLOPT
1641/* Link with -lmalloc (or -lmpc) on an SGI */
1642#include <malloc.h>
1643
Tal Einatede0b6f2018-12-31 17:12:08 +02001644/*[clinic input]
1645sys.mdebug
1646
1647 flag: int
1648 /
1649[clinic start generated code]*/
1650
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001651static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001652sys_mdebug_impl(PyObject *module, int flag)
1653/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001654{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001657 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001658}
1659#endif /* USE_MALLOPT */
1660
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001661size_t
1662_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001666 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001667 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001668
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001670 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001671 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001672 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001673
Benjamin Petersonce798522012-01-22 11:24:29 -05001674 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001676 if (!_PyErr_Occurred(tstate)) {
1677 _PyErr_Format(tstate, PyExc_TypeError,
1678 "Type %.100s doesn't define __sizeof__",
1679 Py_TYPE(o)->tp_name);
1680 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 }
1682 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001683 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 Py_DECREF(method);
1685 }
1686
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001687 if (res == NULL)
1688 return (size_t)-1;
1689
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001690 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001691 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001692 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001693 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001695 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001696 _PyErr_SetString(tstate, PyExc_ValueError,
1697 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001698 return (size_t)-1;
1699 }
1700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 /* add gc_head size */
Hai Shi675d9a32020-04-15 02:11:20 +08001702 if (_PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001703 return ((size_t)size) + sizeof(PyGC_Head);
1704 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001705}
1706
1707static PyObject *
1708sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1709{
1710 static char *kwlist[] = {"object", "default", 0};
1711 size_t size;
1712 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001713 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001714
1715 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001716 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001717 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001718 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001719
1720 size = _PySys_GetSizeOf(o);
1721
Victor Stinner838f2642019-06-13 22:41:23 +02001722 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001723 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001724 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1725 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001726 Py_INCREF(dflt);
1727 return dflt;
1728 }
1729 else
1730 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001732
1733 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001734}
1735
1736PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001737"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001738\n\
1739Return the size of object in bytes.");
1740
Tal Einatede0b6f2018-12-31 17:12:08 +02001741/*[clinic input]
1742sys.getrefcount -> Py_ssize_t
1743
1744 object: object
1745 /
1746
1747Return the reference count of object.
1748
1749The count returned is generally one higher than you might expect,
1750because it includes the (temporary) reference as an argument to
1751getrefcount().
1752[clinic start generated code]*/
1753
1754static Py_ssize_t
1755sys_getrefcount_impl(PyObject *module, PyObject *object)
1756/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001757{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001758 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001759}
1760
Tim Peters4be93d02002-07-07 19:59:50 +00001761#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001762/*[clinic input]
1763sys.gettotalrefcount -> Py_ssize_t
1764[clinic start generated code]*/
1765
1766static Py_ssize_t
1767sys_gettotalrefcount_impl(PyObject *module)
1768/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001769{
Tal Einatede0b6f2018-12-31 17:12:08 +02001770 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001771}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001772#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001773
Tal Einatede0b6f2018-12-31 17:12:08 +02001774/*[clinic input]
1775sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001776
Tal Einatede0b6f2018-12-31 17:12:08 +02001777Return the number of memory blocks currently allocated.
1778[clinic start generated code]*/
1779
1780static Py_ssize_t
1781sys_getallocatedblocks_impl(PyObject *module)
1782/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001783{
Tal Einatede0b6f2018-12-31 17:12:08 +02001784 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001785}
1786
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001787
Tal Einatede0b6f2018-12-31 17:12:08 +02001788/*[clinic input]
1789sys._getframe
1790
1791 depth: int = 0
1792 /
1793
1794Return a frame object from the call stack.
1795
1796If optional integer depth is given, return the frame object that many
1797calls below the top of the stack. If that is deeper than the call
1798stack, ValueError is raised. The default for depth is zero, returning
1799the frame at the top of the call stack.
1800
1801This function should be used for internal and specialized purposes
1802only.
1803[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001804
1805static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001806sys__getframe_impl(PyObject *module, int depth)
1807/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001808{
Victor Stinner838f2642019-06-13 22:41:23 +02001809 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner70364772020-04-29 03:28:46 +02001810 PyFrameObject *f = PyThreadState_GetFrame(tstate);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001811
Victor Stinner08faf002020-03-26 18:57:32 +01001812 if (_PySys_Audit(tstate, "sys._getframe", "O", f) < 0) {
Victor Stinner70364772020-04-29 03:28:46 +02001813 Py_DECREF(f);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001814 return NULL;
1815 }
1816
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 while (depth > 0 && f != NULL) {
Victor Stinner70364772020-04-29 03:28:46 +02001818 PyFrameObject *back = PyFrame_GetBack(f);
1819 Py_DECREF(f);
1820 f = back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 --depth;
1822 }
1823 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001824 _PyErr_SetString(tstate, PyExc_ValueError,
1825 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return NULL;
1827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001829}
1830
Tal Einatede0b6f2018-12-31 17:12:08 +02001831/*[clinic input]
1832sys._current_frames
1833
1834Return a dict mapping each thread's thread id to its current stack frame.
1835
1836This function should be used for specialized purposes only.
1837[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001838
1839static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001840sys__current_frames_impl(PyObject *module)
1841/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001844}
1845
Tal Einatede0b6f2018-12-31 17:12:08 +02001846/*[clinic input]
Julien Danjou64366fa2020-11-02 15:16:25 +01001847sys._current_exceptions
1848
1849Return a dict mapping each thread's identifier to its current raised exception.
1850
1851This function should be used for specialized purposes only.
1852[clinic start generated code]*/
1853
1854static PyObject *
1855sys__current_exceptions_impl(PyObject *module)
1856/*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
1857{
1858 return _PyThread_CurrentExceptions();
1859}
1860
1861/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +02001862sys.call_tracing
1863
1864 func: object
1865 args as funcargs: object(subclass_of='&PyTuple_Type')
1866 /
1867
1868Call func(*args), while tracing is enabled.
1869
1870The tracing state is saved, and restored afterwards. This is intended
1871to be called from a debugger from a checkpoint, to recursively debug
1872some other code.
1873[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001874
1875static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001876sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1877/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001880}
1881
Victor Stinner048afd92016-11-28 11:59:04 +01001882
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001883#ifdef __cplusplus
1884extern "C" {
1885#endif
1886
Tal Einatede0b6f2018-12-31 17:12:08 +02001887/*[clinic input]
1888sys._debugmallocstats
1889
1890Print summary info to stderr about the state of pymalloc's structures.
1891
1892In Py_DEBUG mode, also perform some expensive internal consistency
1893checks.
1894[clinic start generated code]*/
1895
David Malcolm49526f42012-06-22 14:55:41 -04001896static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001897sys__debugmallocstats_impl(PyObject *module)
1898/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001899{
1900#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001901 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001902 fputc('\n', stderr);
1903 }
David Malcolm49526f42012-06-22 14:55:41 -04001904#endif
1905 _PyObject_DebugTypeStats(stderr);
1906
1907 Py_RETURN_NONE;
1908}
David Malcolm49526f42012-06-22 14:55:41 -04001909
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001910#ifdef Py_TRACE_REFS
Joannah Nanjekye46b5c6b2020-12-22 18:31:46 -04001911/* Defined in objects.c because it uses static globals in that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001912extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001913#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001914
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001915#ifdef DYNAMIC_EXECUTION_PROFILE
Joannah Nanjekye46b5c6b2020-12-22 18:31:46 -04001916/* Defined in ceval.c because it uses static globals in that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001917extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001918#endif
1919
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001920#ifdef __cplusplus
1921}
1922#endif
1923
Tal Einatede0b6f2018-12-31 17:12:08 +02001924
1925/*[clinic input]
1926sys._clear_type_cache
1927
1928Clear the internal type lookup cache.
1929[clinic start generated code]*/
1930
Christian Heimes15ebc882008-02-04 18:48:49 +00001931static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001932sys__clear_type_cache_impl(PyObject *module)
1933/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyType_ClearCache();
1936 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001937}
1938
Tal Einatede0b6f2018-12-31 17:12:08 +02001939/*[clinic input]
1940sys.is_finalizing
1941
1942Return True if Python is exiting.
1943[clinic start generated code]*/
1944
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001945static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001946sys_is_finalizing_impl(PyObject *module)
1947/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001948{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001949 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001950}
1951
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001952#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001953/*[clinic input]
1954sys.getandroidapilevel
1955
1956Return the build time API version of Android as an integer.
1957[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001958
1959static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001960sys_getandroidapilevel_impl(PyObject *module)
1961/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001962{
1963 return PyLong_FromLong(ANDROID_API_LEVEL);
1964}
1965#endif /* ANDROID_API_LEVEL */
1966
1967
Steve Dowerb82e17e2019-05-23 08:45:22 -07001968
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001969static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001971 SYS_ADDAUDITHOOK_METHODDEF
1972 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001973 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001974 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001975 SYS__CLEAR_TYPE_CACHE_METHODDEF
1976 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001977 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001978 SYS_DISPLAYHOOK_METHODDEF
1979 SYS_EXC_INFO_METHODDEF
1980 SYS_EXCEPTHOOK_METHODDEF
1981 SYS_EXIT_METHODDEF
1982 SYS_GETDEFAULTENCODING_METHODDEF
1983 SYS_GETDLOPENFLAGS_METHODDEF
1984 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001985#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001987#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001988 SYS_GETFILESYSTEMENCODING_METHODDEF
1989 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001990#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001992#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001993 SYS_GETTOTALREFCOUNT_METHODDEF
1994 SYS_GETREFCOUNT_METHODDEF
1995 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001996 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001997 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001998 SYS__GETFRAME_METHODDEF
1999 SYS_GETWINDOWSVERSION_METHODDEF
2000 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
2001 SYS_INTERN_METHODDEF
2002 SYS_IS_FINALIZING_METHODDEF
2003 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002004 SYS_SETSWITCHINTERVAL_METHODDEF
2005 SYS_GETSWITCHINTERVAL_METHODDEF
2006 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002008 SYS_GETPROFILE_METHODDEF
2009 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002011 SYS_GETTRACE_METHODDEF
2012 SYS_CALL_TRACING_METHODDEF
2013 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002014 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2015 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002016 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002017 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002018 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2019 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002020 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002022};
2023
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002024
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002025static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002026list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PyObject *list = PyList_New(0);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002029 if (list == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 return NULL;
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002031 }
2032 for (Py_ssize_t i = 0; PyImport_Inittab[i].name != NULL; i++) {
2033 PyObject *name = PyUnicode_FromString(PyImport_Inittab[i].name);
2034 if (name == NULL) {
2035 goto error;
2036 }
2037 if (PyList_Append(list, name) < 0) {
2038 Py_DECREF(name);
2039 goto error;
2040 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 Py_DECREF(name);
2042 }
2043 if (PyList_Sort(list) != 0) {
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002044 goto error;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 }
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002046 PyObject *tuple = PyList_AsTuple(list);
2047 Py_DECREF(list);
2048 return tuple;
2049
2050error:
2051 Py_DECREF(list);
2052 return NULL;
Guido van Rossum34679b71993-01-26 13:33:44 +00002053}
2054
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002055
2056static PyObject *
Victor Stinner9852cb32021-01-25 23:12:50 +01002057list_stdlib_module_names(void)
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002058{
Victor Stinner9852cb32021-01-25 23:12:50 +01002059 Py_ssize_t len = Py_ARRAY_LENGTH(_Py_stdlib_module_names);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002060 PyObject *names = PyTuple_New(len);
2061 if (names == NULL) {
2062 return NULL;
2063 }
2064
2065 for (Py_ssize_t i = 0; i < len; i++) {
Victor Stinner9852cb32021-01-25 23:12:50 +01002066 PyObject *name = PyUnicode_FromString(_Py_stdlib_module_names[i]);
Victor Stinnerdb584bd2021-01-25 13:24:42 +01002067 if (name == NULL) {
2068 Py_DECREF(names);
2069 return NULL;
2070 }
2071 PyTuple_SET_ITEM(names, i, name);
2072 }
2073
2074 PyObject *set = PyObject_CallFunction((PyObject *)&PyFrozenSet_Type,
2075 "(O)", names);
2076 Py_DECREF(names);
2077 return set;
2078}
2079
2080
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002081/* Pre-initialization support for sys.warnoptions and sys._xoptions
2082 *
2083 * Modern internal code paths:
2084 * These APIs get called after _Py_InitializeCore and get to use the
2085 * regular CPython list, dict, and unicode APIs.
2086 *
2087 * Legacy embedding code paths:
2088 * The multi-phase initialization API isn't public yet, so embedding
2089 * apps still need to be able configure sys.warnoptions and sys._xoptions
2090 * before they call Py_Initialize. To support this, we stash copies of
2091 * the supplied wchar * sequences in linked lists, and then migrate the
2092 * contents of those lists to the sys module in _PyInitializeCore.
2093 *
2094 */
2095
2096struct _preinit_entry {
2097 wchar_t *value;
2098 struct _preinit_entry *next;
2099};
2100
2101typedef struct _preinit_entry *_Py_PreInitEntry;
2102
2103static _Py_PreInitEntry _preinit_warnoptions = NULL;
2104static _Py_PreInitEntry _preinit_xoptions = NULL;
2105
2106static _Py_PreInitEntry
2107_alloc_preinit_entry(const wchar_t *value)
2108{
2109 /* To get this to work, we have to initialize the runtime implicitly */
2110 _PyRuntime_Initialize();
2111
2112 /* Force default allocator, so we can ensure that it also gets used to
2113 * destroy the linked list in _clear_preinit_entries.
2114 */
2115 PyMemAllocatorEx old_alloc;
2116 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2117
2118 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2119 if (node != NULL) {
2120 node->value = _PyMem_RawWcsdup(value);
2121 if (node->value == NULL) {
2122 PyMem_RawFree(node);
2123 node = NULL;
2124 };
2125 };
2126
2127 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2128 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002129}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002130
2131static int
2132_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2133{
2134 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2135 if (new_entry == NULL) {
2136 return -1;
2137 }
2138 /* We maintain the linked list in this order so it's easy to play back
2139 * the add commands in the same order later on in _Py_InitializeCore
2140 */
2141 _Py_PreInitEntry last_entry = *optionlist;
2142 if (last_entry == NULL) {
2143 *optionlist = new_entry;
2144 } else {
2145 while (last_entry->next != NULL) {
2146 last_entry = last_entry->next;
2147 }
2148 last_entry->next = new_entry;
2149 }
2150 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002151}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002152
2153static void
2154_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2155{
2156 _Py_PreInitEntry current = *optionlist;
2157 *optionlist = NULL;
2158 /* Deallocate the nodes and their contents using the default allocator */
2159 PyMemAllocatorEx old_alloc;
2160 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2161 while (current != NULL) {
2162 _Py_PreInitEntry next = current->next;
2163 PyMem_RawFree(current->value);
2164 PyMem_RawFree(current);
2165 current = next;
2166 }
2167 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002168}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002169
Victor Stinner120b7072019-08-23 18:03:08 +01002170
2171PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002172_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002173{
Victor Stinner120b7072019-08-23 18:03:08 +01002174 PyStatus status;
2175 _Py_PreInitEntry entry;
2176
2177 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002178 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002179 if (_PyStatus_EXCEPTION(status)) {
2180 return status;
2181 }
2182 }
2183
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002184 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002185 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002186}
2187
Victor Stinner120b7072019-08-23 18:03:08 +01002188
2189PyStatus
2190_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002191{
Victor Stinner120b7072019-08-23 18:03:08 +01002192 PyStatus status;
2193 _Py_PreInitEntry entry;
2194
2195 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2196 status = PyWideStringList_Append(&config->xoptions, entry->value);
2197 if (_PyStatus_EXCEPTION(status)) {
2198 return status;
2199 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002200 }
2201
Victor Stinner120b7072019-08-23 18:03:08 +01002202 _clear_preinit_entries(&_preinit_xoptions);
2203 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002204}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002205
Victor Stinner120b7072019-08-23 18:03:08 +01002206
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002207static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002208get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002209{
Victor Stinner838f2642019-06-13 22:41:23 +02002210 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002211 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002212 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2213 * interpreter config. When that happens, we need to properly set
2214 * the `warnoptions` reference in the main interpreter config as well.
2215 *
2216 * For Python 3.7, we shouldn't be able to get here due to the
2217 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2218 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2219 * call optional for embedding applications, thus making this
2220 * reachable again.
2221 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002222 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002223 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002224 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002225 }
2226 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002227 Py_DECREF(warnoptions);
2228 return NULL;
2229 }
2230 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002231 }
2232 return warnoptions;
2233}
Guido van Rossum23fff912000-12-15 22:02:05 +00002234
2235void
2236PySys_ResetWarnOptions(void)
2237{
Victor Stinner50b48572018-11-01 01:51:40 +01002238 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002239 if (tstate == NULL) {
2240 _clear_preinit_entries(&_preinit_warnoptions);
2241 return;
2242 }
2243
Victor Stinner838f2642019-06-13 22:41:23 +02002244 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 if (warnoptions == NULL || !PyList_Check(warnoptions))
2246 return;
2247 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002248}
2249
Victor Stinnere1b29952018-10-30 14:31:42 +01002250static int
Victor Stinner838f2642019-06-13 22:41:23 +02002251_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002252{
Victor Stinner838f2642019-06-13 22:41:23 +02002253 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002254 if (warnoptions == NULL) {
2255 return -1;
2256 }
2257 if (PyList_Append(warnoptions, option)) {
2258 return -1;
2259 }
2260 return 0;
2261}
2262
2263void
2264PySys_AddWarnOptionUnicode(PyObject *option)
2265{
Victor Stinner838f2642019-06-13 22:41:23 +02002266 PyThreadState *tstate = _PyThreadState_GET();
2267 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002268 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002269 if (tstate) {
2270 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002271 }
2272 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002273}
2274
2275void
2276PySys_AddWarnOption(const wchar_t *s)
2277{
Victor Stinner50b48572018-11-01 01:51:40 +01002278 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002279 if (tstate == NULL) {
2280 _append_preinit_entry(&_preinit_warnoptions, s);
2281 return;
2282 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002283 PyObject *unicode;
2284 unicode = PyUnicode_FromWideChar(s, -1);
2285 if (unicode == NULL)
2286 return;
2287 PySys_AddWarnOptionUnicode(unicode);
2288 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002289}
2290
Christian Heimes33fe8092008-04-13 13:53:33 +00002291int
2292PySys_HasWarnOptions(void)
2293{
Victor Stinner838f2642019-06-13 22:41:23 +02002294 PyThreadState *tstate = _PyThreadState_GET();
2295 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002296 return (warnoptions != NULL && PyList_Check(warnoptions)
2297 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002298}
2299
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002300static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002301get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002302{
Victor Stinner838f2642019-06-13 22:41:23 +02002303 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002304 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002305 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2306 * interpreter config. When that happens, we need to properly set
2307 * the `xoptions` reference in the main interpreter config as well.
2308 *
2309 * For Python 3.7, we shouldn't be able to get here due to the
2310 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2311 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2312 * call optional for embedding applications, thus making this
2313 * reachable again.
2314 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002315 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002316 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002317 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002318 }
2319 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002320 Py_DECREF(xoptions);
2321 return NULL;
2322 }
2323 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002324 }
2325 return xoptions;
2326}
2327
Victor Stinnere1b29952018-10-30 14:31:42 +01002328static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002329_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002330{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002331 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002332
Victor Stinner838f2642019-06-13 22:41:23 +02002333 PyThreadState *tstate = _PyThreadState_GET();
2334 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002335 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002336 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002337 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002338
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002339 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002340 if (!name_end) {
2341 name = PyUnicode_FromWideChar(s, -1);
2342 value = Py_True;
2343 Py_INCREF(value);
2344 }
2345 else {
2346 name = PyUnicode_FromWideChar(s, name_end - s);
2347 value = PyUnicode_FromWideChar(name_end + 1, -1);
2348 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002349 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002350 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002351 }
2352 if (PyDict_SetItem(opts, name, value) < 0) {
2353 goto error;
2354 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002355 Py_DECREF(name);
2356 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002357 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002358
2359error:
2360 Py_XDECREF(name);
2361 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002362 return -1;
2363}
2364
2365void
2366PySys_AddXOption(const wchar_t *s)
2367{
Victor Stinner50b48572018-11-01 01:51:40 +01002368 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002369 if (tstate == NULL) {
2370 _append_preinit_entry(&_preinit_xoptions, s);
2371 return;
2372 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002373 if (_PySys_AddXOptionWithError(s) < 0) {
2374 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002375 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002376 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002377}
2378
2379PyObject *
2380PySys_GetXOptions(void)
2381{
Victor Stinner838f2642019-06-13 22:41:23 +02002382 PyThreadState *tstate = _PyThreadState_GET();
2383 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002384}
2385
Guido van Rossum40552d01998-08-06 03:34:39 +00002386/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2387 Two literals concatenated works just fine. If you have a K&R compiler
2388 or other abomination that however *does* understand longer strings,
2389 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002390PyDoc_VAR(sys_doc) =
2391PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002392"This module provides access to some objects used or maintained by the\n\
2393interpreter and to functions that interact strongly with the interpreter.\n\
2394\n\
2395Dynamic objects:\n\
2396\n\
2397argv -- command line arguments; argv[0] is the script pathname if known\n\
2398path -- module search path; path[0] is the script directory, else ''\n\
2399modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002400\n\
2401displayhook -- called to show results in an interactive session\n\
2402excepthook -- called to handle any uncaught exception other than SystemExit\n\
2403 To customize printing in an interactive session or to install a custom\n\
2404 top-level exception handler, assign other functions to replace these.\n\
2405\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002406stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002407stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002408stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002409 By assigning other file objects (or objects that behave like files)\n\
2410 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002411\n\
2412last_type -- type of last uncaught exception\n\
2413last_value -- value of last uncaught exception\n\
2414last_traceback -- traceback of last uncaught exception\n\
2415 These three are only available in an interactive session after a\n\
2416 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002417"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002418)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002419/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002420PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002421"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002422Static objects:\n\
2423\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002424builtin_module_names -- tuple of module names built into this interpreter\n\
2425copyright -- copyright notice pertaining to this interpreter\n\
2426exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002427executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002428float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002429float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002430hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002431hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002432implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002433int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002434maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002435maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002436platform -- platform identifier\n\
2437prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002438thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002439version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002440version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002441"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002442)
Steve Dowercc16be82016-09-08 10:35:16 -07002443#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002444/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002445PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002446"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002447winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002448"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002449)
Steve Dowercc16be82016-09-08 10:35:16 -07002450#endif /* MS_COREDLL */
2451#ifdef MS_WINDOWS
2452/* concatenating string here */
2453PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002454"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002455"
2456)
2457#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002458PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002459"__stdin__ -- the original stdin; don't touch!\n\
2460__stdout__ -- the original stdout; don't touch!\n\
2461__stderr__ -- the original stderr; don't touch!\n\
2462__displayhook__ -- the original displayhook; don't touch!\n\
2463__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002464\n\
2465Functions:\n\
2466\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002467displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002468excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002469exc_info() -- return thread-safe information about the current exception\n\
2470exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002471getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002472getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002473getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002474getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002475getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002476gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002477setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002478setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002479setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002480settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002481"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002482)
Fred Drakeccede592000-08-14 20:59:57 +00002483/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002484
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002485
2486PyDoc_STRVAR(flags__doc__,
2487"sys.flags\n\
2488\n\
2489Flags provided through command line arguments or environment vars.");
2490
2491static PyTypeObject FlagsType;
2492
2493static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002495 {"inspect", "-i"},
2496 {"interactive", "-i"},
2497 {"optimize", "-O or -OO"},
2498 {"dont_write_bytecode", "-B"},
2499 {"no_user_site", "-s"},
2500 {"no_site", "-S"},
2501 {"ignore_environment", "-E"},
2502 {"verbose", "-v"},
Georg Brandl8aa7e992010-12-28 18:30:18 +00002503 {"bytes_warning", "-b"},
2504 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002505 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002506 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002507 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002508 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002510};
2511
2512static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 "sys.flags", /* name */
2514 flags__doc__, /* doc */
2515 flags_fields, /* fields */
Victor Stinner1def7752020-04-23 03:03:24 +02002516 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002517};
2518
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002519static int
2520set_flags_from_config(PyObject *flags, PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002521{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002522 PyInterpreterState *interp = tstate->interp;
2523 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002524 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002525
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002526 // _PySys_UpdateConfig() modifies sys.flags in-place:
2527 // Py_XDECREF() is needed in this case.
2528 Py_ssize_t pos = 0;
2529#define SetFlagObj(expr) \
2530 do { \
2531 PyObject *value = (expr); \
2532 if (value == NULL) { \
2533 return -1; \
2534 } \
2535 Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
2536 PyStructSequence_SET_ITEM(flags, pos, value); \
2537 pos++; \
2538 } while (0)
2539#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002540
Victor Stinnerfbca9082018-08-30 00:50:45 +02002541 SetFlag(config->parser_debug);
2542 SetFlag(config->inspect);
2543 SetFlag(config->interactive);
2544 SetFlag(config->optimization_level);
2545 SetFlag(!config->write_bytecode);
2546 SetFlag(!config->user_site_directory);
2547 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002548 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002549 SetFlag(config->verbose);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002550 SetFlag(config->bytes_warning);
2551 SetFlag(config->quiet);
2552 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002553 SetFlag(config->isolated);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002554 SetFlagObj(PyBool_FromLong(config->dev_mode));
Victor Stinner20004952019-03-26 02:31:11 +01002555 SetFlag(preconfig->utf8_mode);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002556#undef SetFlagObj
Victor Stinner91106cd2017-12-13 12:29:09 +01002557#undef SetFlag
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002558 return 0;
2559}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002560
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002561
2562static PyObject*
2563make_flags(PyThreadState *tstate)
2564{
2565 PyObject *flags = PyStructSequence_New(&FlagsType);
2566 if (flags == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 return NULL;
2568 }
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002569
2570 if (set_flags_from_config(flags, tstate) < 0) {
2571 Py_DECREF(flags);
2572 return NULL;
2573 }
2574 return flags;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002575}
2576
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002577
Eric Smith0e5b5622009-02-06 01:32:42 +00002578PyDoc_STRVAR(version_info__doc__,
2579"sys.version_info\n\
2580\n\
2581Version information as a named tuple.");
2582
2583static PyTypeObject VersionInfoType;
2584
2585static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 {"major", "Major release number"},
2587 {"minor", "Minor release number"},
2588 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002589 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 {"serial", "Serial release number"},
2591 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002592};
2593
2594static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 "sys.version_info", /* name */
2596 version_info__doc__, /* doc */
2597 version_info_fields, /* fields */
2598 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002599};
2600
2601static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002602make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 PyObject *version_info;
2605 char *s;
2606 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 version_info = PyStructSequence_New(&VersionInfoType);
2609 if (version_info == NULL) {
2610 return NULL;
2611 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 /*
2614 * These release level checks are mutually exclusive and cover
2615 * the field, so don't get too fancy with the pre-processor!
2616 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002617#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002619#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002621#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002623#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002625#endif
2626
2627#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002628 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002629#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 SetIntItem(PY_MAJOR_VERSION);
2633 SetIntItem(PY_MINOR_VERSION);
2634 SetIntItem(PY_MICRO_VERSION);
2635 SetStrItem(s);
2636 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002637#undef SetIntItem
2638#undef SetStrItem
2639
Victor Stinner838f2642019-06-13 22:41:23 +02002640 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 Py_CLEAR(version_info);
2642 return NULL;
2643 }
2644 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002645}
2646
Brett Cannon3adc7b72012-07-09 14:22:12 -04002647/* sys.implementation values */
2648#define NAME "cpython"
2649const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002650#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2651#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002652#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002653const char *_PySys_ImplCacheTag = TAG;
2654#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002655#undef MAJOR
2656#undef MINOR
2657#undef TAG
2658
Barry Warsaw409da152012-06-03 16:18:47 -04002659static PyObject *
2660make_impl_info(PyObject *version_info)
2661{
2662 int res;
2663 PyObject *impl_info, *value, *ns;
2664
2665 impl_info = PyDict_New();
2666 if (impl_info == NULL)
2667 return NULL;
2668
2669 /* populate the dict */
2670
Brett Cannon3adc7b72012-07-09 14:22:12 -04002671 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002672 if (value == NULL)
2673 goto error;
2674 res = PyDict_SetItemString(impl_info, "name", value);
2675 Py_DECREF(value);
2676 if (res < 0)
2677 goto error;
2678
Brett Cannon3adc7b72012-07-09 14:22:12 -04002679 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002680 if (value == NULL)
2681 goto error;
2682 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2683 Py_DECREF(value);
2684 if (res < 0)
2685 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002686
2687 res = PyDict_SetItemString(impl_info, "version", version_info);
2688 if (res < 0)
2689 goto error;
2690
2691 value = PyLong_FromLong(PY_VERSION_HEX);
2692 if (value == NULL)
2693 goto error;
2694 res = PyDict_SetItemString(impl_info, "hexversion", value);
2695 Py_DECREF(value);
2696 if (res < 0)
2697 goto error;
2698
doko@ubuntu.com55532312016-06-14 08:55:19 +02002699#ifdef MULTIARCH
2700 value = PyUnicode_FromString(MULTIARCH);
2701 if (value == NULL)
2702 goto error;
2703 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2704 Py_DECREF(value);
2705 if (res < 0)
2706 goto error;
2707#endif
2708
Barry Warsaw409da152012-06-03 16:18:47 -04002709 /* dict ready */
2710
2711 ns = _PyNamespace_New(impl_info);
2712 Py_DECREF(impl_info);
2713 return ns;
2714
2715error:
2716 Py_CLEAR(impl_info);
2717 return NULL;
2718}
2719
Martin v. Löwis1a214512008-06-11 05:26:20 +00002720static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyModuleDef_HEAD_INIT,
2722 "sys",
2723 sys_doc,
2724 -1, /* multiple "initialization" just copies the module dict. */
2725 sys_methods,
2726 NULL,
2727 NULL,
2728 NULL,
2729 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002730};
2731
Eric Snow6b4be192017-05-22 21:36:03 -07002732/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002733#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002734 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002735 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002736 if (v == NULL) { \
2737 goto err_occurred; \
2738 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002739 res = PyDict_SetItemString(sysdict, key, v); \
2740 Py_DECREF(v); \
2741 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002742 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002743 } \
2744 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002745
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002746#define SET_SYS_FROM_STRING(key, value) \
2747 SET_SYS(key, PyUnicode_FromString(value))
2748
Victor Stinner331a6a52019-05-27 16:39:22 +02002749static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002750_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002751{
Victor Stinnerab672812019-01-23 15:04:40 +01002752 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002753 int res;
2754
Nick Coghland6009512014-11-20 21:39:37 +10002755 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002756
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002757#define COPY_SYS_ATTR(tokey, fromkey) \
2758 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002759
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002760 COPY_SYS_ATTR("__displayhook__", "displayhook");
2761 COPY_SYS_ATTR("__excepthook__", "excepthook");
2762 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2763 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2764
2765#undef COPY_SYS_ATTR
2766
2767 SET_SYS_FROM_STRING("version", Py_GetVersion());
2768 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2769 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2770 _Py_gitversion()));
2771 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2772 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2773 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2774 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2775 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2776 SET_SYS("float_info", PyFloat_GetInfo());
2777 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002778 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002779 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002780 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2781 goto type_init_failed;
2782 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002783 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002784 SET_SYS("hash_info", get_hash_info(tstate));
2785 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2786 SET_SYS("builtin_module_names", list_builtin_module_names());
Victor Stinner9852cb32021-01-25 23:12:50 +01002787 SET_SYS("stdlib_module_names", list_stdlib_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002788#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002789 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002790#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002791 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002792#endif
Fred Drake099325e2000-08-14 15:47:03 +00002793
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002794#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002795 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2796 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002797#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002798#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002799 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002800#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002803 if (VersionInfoType.tp_name == NULL) {
2804 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002805 &version_info_desc) < 0) {
2806 goto type_init_failed;
2807 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002808 }
Victor Stinner838f2642019-06-13 22:41:23 +02002809 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002810 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 /* prevent user from creating new instances */
2812 VersionInfoType.tp_init = NULL;
2813 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002814 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002815 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2816 _PyErr_Clear(tstate);
2817 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002818
Barry Warsaw409da152012-06-03 16:18:47 -04002819 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002820 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002821
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002822 // sys.flags: updated in-place later by _PySys_UpdateConfig()
Victor Stinner1c8f0592013-07-22 22:24:54 +02002823 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002824 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2825 goto type_init_failed;
2826 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002827 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002828 SET_SYS("flags", make_flags(tstate));
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002829 /* prevent user from creating new instances */
2830 FlagsType.tp_init = NULL;
2831 FlagsType.tp_new = NULL;
2832 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2833 if (res < 0) {
2834 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2835 goto err_occurred;
2836 }
2837 _PyErr_Clear(tstate);
2838 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002839
2840#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 /* getwindowsversion */
2842 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002843 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002844 &windows_version_desc) < 0) {
2845 goto type_init_failed;
2846 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002847 /* prevent user from creating new instances */
2848 WindowsVersionType.tp_init = NULL;
2849 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002850 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002851 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002852 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2853 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002854 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002855#endif
2856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002858#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002859 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002860#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002861 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002862#endif
2863
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002864 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002865
Yury Selivanoveb636452016-09-08 22:01:51 -07002866 /* initialize asyncgen_hooks */
2867 if (AsyncGenHooksType.tp_name == NULL) {
2868 if (PyStructSequence_InitType2(
2869 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002870 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002871 }
2872 }
2873
Victor Stinneref75a622020-11-12 15:14:13 +01002874 /* adding sys.path_hooks and sys.path_importer_cache */
2875 SET_SYS("meta_path", PyList_New(0));
2876 SET_SYS("path_importer_cache", PyDict_New());
2877 SET_SYS("path_hooks", PyList_New(0));
2878
Victor Stinner838f2642019-06-13 22:41:23 +02002879 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002880 goto err_occurred;
2881 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002882 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002883
2884type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002885 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002886
2887err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002888 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002889}
2890
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002891static int
2892sys_add_xoption(PyObject *opts, const wchar_t *s)
2893{
2894 PyObject *name, *value;
2895
2896 const wchar_t *name_end = wcschr(s, L'=');
2897 if (!name_end) {
2898 name = PyUnicode_FromWideChar(s, -1);
2899 value = Py_True;
2900 Py_INCREF(value);
2901 }
2902 else {
2903 name = PyUnicode_FromWideChar(s, name_end - s);
2904 value = PyUnicode_FromWideChar(name_end + 1, -1);
2905 }
2906 if (name == NULL || value == NULL) {
2907 goto error;
2908 }
2909 if (PyDict_SetItem(opts, name, value) < 0) {
2910 goto error;
2911 }
2912 Py_DECREF(name);
2913 Py_DECREF(value);
2914 return 0;
2915
2916error:
2917 Py_XDECREF(name);
2918 Py_XDECREF(value);
2919 return -1;
2920}
2921
2922
2923static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002924sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002925{
2926 Py_ssize_t nxoption = config->xoptions.length;
2927 wchar_t * const * xoptions = config->xoptions.items;
2928 PyObject *dict = PyDict_New();
2929 if (dict == NULL) {
2930 return NULL;
2931 }
2932
2933 for (Py_ssize_t i=0; i < nxoption; i++) {
2934 const wchar_t *option = xoptions[i];
2935 if (sys_add_xoption(dict, option) < 0) {
2936 Py_DECREF(dict);
2937 return NULL;
2938 }
2939 }
2940
2941 return dict;
2942}
2943
2944
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002945// Update sys attributes for a new PyConfig configuration.
2946// This function also adds attributes that _PySys_InitCore() didn't add.
Eric Snow6b4be192017-05-22 21:36:03 -07002947int
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002948_PySys_UpdateConfig(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002949{
Victor Stinner838f2642019-06-13 22:41:23 +02002950 PyObject *sysdict = tstate->interp->sysdict;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002951 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002952 int res;
2953
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002954#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002955 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002956
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002957#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002958 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002959
Victor Stinner9e1b8282020-11-10 13:21:52 +01002960#define COPY_WSTR(SYS_ATTR, WSTR) \
2961 if (WSTR != NULL) { \
2962 SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
2963 }
2964
Victor Stinnerf3cb8142020-11-05 18:12:33 +01002965 if (config->module_search_paths_set) {
2966 COPY_LIST("path", config->module_search_paths);
2967 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002968
Victor Stinner9e1b8282020-11-10 13:21:52 +01002969 COPY_WSTR("executable", config->executable);
2970 COPY_WSTR("_base_executable", config->base_executable);
2971 COPY_WSTR("prefix", config->prefix);
2972 COPY_WSTR("base_prefix", config->base_prefix);
2973 COPY_WSTR("exec_prefix", config->exec_prefix);
2974 COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
2975 COPY_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002976
Carl Meyerb193fa92018-06-15 22:40:56 -06002977 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002978 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002979 } else {
2980 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2981 }
2982
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002983 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002984 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002985 COPY_LIST("warnoptions", config->warnoptions);
2986
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002987 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002988
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002989#undef SET_SYS_FROM_WSTR
Victor Stinner9e1b8282020-11-10 13:21:52 +01002990#undef COPY_LIST
2991#undef COPY_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002992
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002993 // sys.flags
2994 PyObject *flags = _PySys_GetObject(tstate, "flags"); // borrowed ref
2995 if (flags == NULL) {
2996 return -1;
2997 }
2998 if (set_flags_from_config(flags, tstate) < 0) {
2999 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003000 }
3001
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03003002 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07003003
Victor Stinner838f2642019-06-13 22:41:23 +02003004 if (_PyErr_Occurred(tstate)) {
3005 goto err_occurred;
3006 }
3007
Eric Snow6b4be192017-05-22 21:36:03 -07003008 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01003009
3010err_occurred:
3011 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07003012}
3013
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03003014#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01003015#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07003016
Victor Stinnerab672812019-01-23 15:04:40 +01003017
3018/* Set up a preliminary stderr printer until we have enough
3019 infrastructure for the io module in place.
3020
3021 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003022static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01003023_PySys_SetPreliminaryStderr(PyObject *sysdict)
3024{
3025 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3026 if (pstderr == NULL) {
3027 goto error;
3028 }
3029 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3030 goto error;
3031 }
3032 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3033 goto error;
3034 }
3035 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003036 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003037
3038error:
3039 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003040 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003041}
3042
3043
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003044/* Create sys module without all attributes.
3045 _PySys_UpdateConfig() should be called later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003046PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01003047_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003048{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003049 assert(!_PyErr_Occurred(tstate));
3050
Victor Stinnerb45d2592019-06-20 00:05:23 +02003051 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003052
Victor Stinnerab672812019-01-23 15:04:40 +01003053 PyObject *modules = PyDict_New();
3054 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003055 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003056 }
3057 interp->modules = modules;
3058
3059 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3060 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003061 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003062 }
3063
3064 PyObject *sysdict = PyModule_GetDict(sysmod);
3065 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003066 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003067 }
3068 Py_INCREF(sysdict);
3069 interp->sysdict = sysdict;
3070
3071 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003072 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003073 }
3074
Victor Stinner331a6a52019-05-27 16:39:22 +02003075 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3076 if (_PyStatus_EXCEPTION(status)) {
3077 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003078 }
3079
Victor Stinner01b1cc12019-11-20 02:27:56 +01003080 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003081 if (_PyStatus_EXCEPTION(status)) {
3082 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003083 }
3084
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003085 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3086 goto error;
3087 }
3088
3089 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003090
3091 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003092 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003093
3094error:
3095 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003096}
3097
3098
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003099static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003100makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003101{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003102 int i, n;
3103 const wchar_t *p;
3104 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003106 n = 1;
3107 p = path;
3108 while ((p = wcschr(p, delim)) != NULL) {
3109 n++;
3110 p++;
3111 }
3112 v = PyList_New(n);
3113 if (v == NULL)
3114 return NULL;
3115 for (i = 0; ; i++) {
3116 p = wcschr(path, delim);
3117 if (p == NULL)
3118 p = path + wcslen(path); /* End of string */
3119 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3120 if (w == NULL) {
3121 Py_DECREF(v);
3122 return NULL;
3123 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003124 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003125 if (*p == '\0')
3126 break;
3127 path = p+1;
3128 }
3129 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003130}
3131
3132void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003133PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003135 PyObject *v;
3136 if ((v = makepathobject(path, DELIM)) == NULL)
3137 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003138 PyThreadState *tstate = _PyThreadState_GET();
3139 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003140 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003141 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003142 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003143}
3144
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003145static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003146make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003147{
Victor Stinner74f65682019-03-15 15:08:05 +01003148 PyObject *list = PyList_New(argc);
3149 if (list == NULL) {
3150 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003151 }
Victor Stinner74f65682019-03-15 15:08:05 +01003152
3153 for (Py_ssize_t i = 0; i < argc; i++) {
3154 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3155 if (v == NULL) {
3156 Py_DECREF(list);
3157 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003158 }
Victor Stinner74f65682019-03-15 15:08:05 +01003159 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 }
Victor Stinner74f65682019-03-15 15:08:05 +01003161 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003162}
3163
Victor Stinner11a247d2017-12-13 21:05:57 +01003164void
3165PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003166{
Victor Stinnerc4868252019-08-23 11:04:16 +01003167 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003168 PyThreadState *tstate = _PyThreadState_GET();
3169
Victor Stinner74f65682019-03-15 15:08:05 +01003170 if (argc < 1 || argv == NULL) {
3171 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003172 argv = empty_argv;
3173 argc = 1;
3174 }
3175
3176 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003177 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003178 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003179 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02003180 if (sys_set_object_str(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003181 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003182 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003183 }
3184 Py_DECREF(av);
3185
3186 if (updatepath) {
3187 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3188 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003189 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003190 PyObject *path0 = NULL;
3191 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3192 if (path0 == NULL) {
3193 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003194 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003195
Victor Stinner838f2642019-06-13 22:41:23 +02003196 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003197 if (sys_path != NULL) {
3198 if (PyList_Insert(sys_path, 0, path0) < 0) {
3199 Py_DECREF(path0);
3200 Py_FatalError("can't prepend path0 to sys.path");
3201 }
3202 }
3203 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003204 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003205 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003206}
Guido van Rossuma890e681998-05-12 14:59:24 +00003207
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003208void
3209PySys_SetArgv(int argc, wchar_t **argv)
3210{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003211 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003212}
3213
Victor Stinner14284c22010-04-23 12:02:30 +00003214/* Reimplementation of PyFile_WriteString() no calling indirectly
3215 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3216
3217static int
Victor Stinner79766632010-08-16 17:36:42 +00003218sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003219{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003220 if (file == NULL)
3221 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003222 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003223 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003225 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003227 Py_DECREF(result);
3228 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003229}
3230
Victor Stinner79766632010-08-16 17:36:42 +00003231static int
3232sys_pyfile_write(const char *text, PyObject *file)
3233{
3234 PyObject *unicode = NULL;
3235 int err;
3236
3237 if (file == NULL)
3238 return -1;
3239
3240 unicode = PyUnicode_FromString(text);
3241 if (unicode == NULL)
3242 return -1;
3243
3244 err = sys_pyfile_write_unicode(unicode, file);
3245 Py_DECREF(unicode);
3246 return err;
3247}
Guido van Rossuma890e681998-05-12 14:59:24 +00003248
3249/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3250 Adapted from code submitted by Just van Rossum.
3251
3252 PySys_WriteStdout(format, ...)
3253 PySys_WriteStderr(format, ...)
3254
3255 The first function writes to sys.stdout; the second to sys.stderr. When
3256 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003257 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003258
Victor Stinner14284c22010-04-23 12:02:30 +00003259 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003260 signal handlers: they may raise a new exception whereas sys_write()
3261 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003262
Guido van Rossuma890e681998-05-12 14:59:24 +00003263 Both take a printf-style format string as their first argument followed
3264 by a variable length argument list determined by the format string.
3265
3266 *** WARNING ***
3267
3268 The format should limit the total size of the formatted output string to
3269 1000 bytes. In particular, this means that no unrestricted "%s" formats
3270 should occur; these should be limited using "%.<N>s where <N> is a
3271 decimal number calculated so that <N> plus the maximum size of other
3272 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3273 which can print hundreds of digits for very large numbers.
3274
3275 */
3276
3277static void
Victor Stinner09054372013-11-06 22:41:44 +01003278sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 PyObject *file;
3281 PyObject *error_type, *error_value, *error_traceback;
3282 char buffer[1001];
3283 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003284 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003285
Victor Stinner838f2642019-06-13 22:41:23 +02003286 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3287 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3289 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003290 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 fputs(buffer, fp);
3292 }
3293 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3294 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003295 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003296 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 }
Victor Stinner838f2642019-06-13 22:41:23 +02003298 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003299}
3300
3301void
Guido van Rossuma890e681998-05-12 14:59:24 +00003302PySys_WriteStdout(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_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003308 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003309}
3310
3311void
Guido van Rossuma890e681998-05-12 14:59:24 +00003312PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003314 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003316 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003317 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003318 va_end(va);
3319}
3320
3321static void
Victor Stinner09054372013-11-06 22:41:44 +01003322sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003323{
3324 PyObject *file, *message;
3325 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003326 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003327 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003328
Victor Stinner838f2642019-06-13 22:41:23 +02003329 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3330 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003331 message = PyUnicode_FromFormatV(format, va);
3332 if (message != NULL) {
3333 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003334 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003335 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003336 if (utf8 != NULL)
3337 fputs(utf8, fp);
3338 }
3339 Py_DECREF(message);
3340 }
Victor Stinner838f2642019-06-13 22:41:23 +02003341 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003342}
3343
3344void
3345PySys_FormatStdout(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_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003351 va_end(va);
3352}
3353
3354void
3355PySys_FormatStderr(const char *format, ...)
3356{
3357 va_list va;
3358
3359 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003360 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003361 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003362}