blob: 749b96455d679683a523071199864e5290896bec [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
Stefan Krah1845d142016-04-25 21:38:53 +020032#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000033
Mark Hammond8696ebc2002-10-08 02:44:31 +000034#ifdef MS_WINDOWS
35#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000036#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000037#endif /* MS_WINDOWS */
38
Guido van Rossum9b38a141996-09-11 23:12:24 +000039#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000040extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000041/* A string loaded from the DLL at startup: */
42extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000043#endif
44
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080045/*[clinic input]
46module sys
47[clinic start generated code]*/
48/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
49
50#include "clinic/sysmodule.c.h"
51
Victor Stinnerbd303c12013-11-07 23:07:29 +010052_Py_IDENTIFIER(_);
53_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070054_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010055_Py_IDENTIFIER(buffer);
56_Py_IDENTIFIER(builtins);
57_Py_IDENTIFIER(encoding);
58_Py_IDENTIFIER(path);
59_Py_IDENTIFIER(stdout);
60_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070061_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010062_Py_IDENTIFIER(write);
63
Victor Stinner838f2642019-06-13 22:41:23 +020064static PyObject *
65sys_get_object_id(PyThreadState *tstate, _Py_Identifier *key)
Victor Stinnerd67bd452013-11-06 22:36:40 +010066{
Victor Stinner838f2642019-06-13 22:41:23 +020067 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020068 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010069 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020070 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +020071 PyObject *exc_type, *exc_value, *exc_tb;
72 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
73 PyObject *value = _PyDict_GetItemIdWithError(sd, key);
74 /* XXX Suppress a new exception if it was raised and restore
75 * the old one. */
76 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
77 return value;
Victor Stinnerd67bd452013-11-06 22:36:40 +010078}
79
80PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +020081_PySys_GetObjectId(_Py_Identifier *key)
82{
83 PyThreadState *tstate = _PyThreadState_GET();
84 return sys_get_object_id(tstate, key);
85}
86
87PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000088PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000089{
Victor Stinner838f2642019-06-13 22:41:23 +020090 PyThreadState *tstate = _PyThreadState_GET();
91 PyObject *sd = tstate->interp->sysdict;
Victor Stinnercaba55b2018-08-03 15:33:52 +020092 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020094 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +020095 PyObject *exc_type, *exc_value, *exc_tb;
96 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
97 PyObject *value = _PyDict_GetItemStringWithError(sd, name);
98 /* XXX Suppress a new exception if it was raised and restore
99 * the old one. */
100 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
101 return value;
102}
103
104static int
105sys_set_object(PyThreadState *tstate, PyObject *key, PyObject *v)
106{
107 if (key == NULL) {
108 return -1;
109 }
110 PyObject *sd = tstate->interp->sysdict;
111 if (v == NULL) {
112 v = _PyDict_Pop(sd, key, Py_None);
113 if (v == NULL) {
114 return -1;
115 }
116 Py_DECREF(v);
117 return 0;
118 }
119 else {
120 return PyDict_SetItem(sd, key, v);
121 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000122}
123
Victor Stinner838f2642019-06-13 22:41:23 +0200124static int
125sys_set_object_id(PyThreadState *tstate, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +0100126{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200127 return sys_set_object(tstate, _PyUnicode_FromId(key), v);
Victor Stinnerd67bd452013-11-06 22:36:40 +0100128}
129
130int
Victor Stinner838f2642019-06-13 22:41:23 +0200131_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000132{
Victor Stinner838f2642019-06-13 22:41:23 +0200133 PyThreadState *tstate = _PyThreadState_GET();
134 return sys_set_object_id(tstate, key, v);
135}
136
137static int
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200138sys_set_object_str(PyThreadState *tstate, const char *name, PyObject *v)
Victor Stinner838f2642019-06-13 22:41:23 +0200139{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200140 PyObject *key = v ? PyUnicode_InternFromString(name)
141 : PyUnicode_FromString(name);
142 int r = sys_set_object(tstate, key, v);
143 Py_XDECREF(key);
144 return r;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000145}
146
Victor Stinner838f2642019-06-13 22:41:23 +0200147int
148PySys_SetObject(const char *name, PyObject *v)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700149{
Victor Stinner838f2642019-06-13 22:41:23 +0200150 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200151 return sys_set_object_str(tstate, name, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200152}
153
Victor Stinner08faf002020-03-26 18:57:32 +0100154
Victor Stinner838f2642019-06-13 22:41:23 +0200155static int
Victor Stinner08faf002020-03-26 18:57:32 +0100156should_audit(PyInterpreterState *is)
Victor Stinner838f2642019-06-13 22:41:23 +0200157{
Victor Stinner08faf002020-03-26 18:57:32 +0100158 /* tstate->interp cannot be NULL, but test it just in case
159 for extra safety */
160 assert(is != NULL);
161 if (!is) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700162 return 0;
163 }
Victor Stinner08faf002020-03-26 18:57:32 +0100164 return (is->runtime->audit_hook_head
165 || is->audit_hooks
166 || PyDTrace_AUDIT_ENABLED());
Steve Dowerb82e17e2019-05-23 08:45:22 -0700167}
168
Steve Dowerb82e17e2019-05-23 08:45:22 -0700169
Victor Stinner08faf002020-03-26 18:57:32 +0100170static int
171sys_audit_tstate(PyThreadState *ts, const char *event,
172 const char *argFormat, va_list vargs)
173{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700174 /* N format is inappropriate, because you do not know
175 whether the reference is consumed by the call.
176 Assert rather than exception for perf reasons */
177 assert(!argFormat || !strchr(argFormat, 'N'));
178
Victor Stinner08faf002020-03-26 18:57:32 +0100179 if (!ts) {
180 /* Audit hooks cannot be called with a NULL thread state */
Steve Dowerb82e17e2019-05-23 08:45:22 -0700181 return 0;
182 }
183
Victor Stinner08faf002020-03-26 18:57:32 +0100184 /* The current implementation cannot be called if tstate is not
185 the current Python thread state. */
186 assert(ts == _PyThreadState_GET());
187
188 /* Early exit when no hooks are registered */
189 PyInterpreterState *is = ts->interp;
190 if (!should_audit(is)) {
191 return 0;
192 }
193
194 PyObject *eventName = NULL;
195 PyObject *eventArgs = NULL;
196 PyObject *hooks = NULL;
197 PyObject *hook = NULL;
198 int res = -1;
199
Steve Dowerb82e17e2019-05-23 08:45:22 -0700200 int dtrace = PyDTrace_AUDIT_ENABLED();
201
202 PyObject *exc_type, *exc_value, *exc_tb;
Victor Stinner08faf002020-03-26 18:57:32 +0100203 _PyErr_Fetch(ts, &exc_type, &exc_value, &exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700204
205 /* Initialize event args now */
206 if (argFormat && argFormat[0]) {
Victor Stinner08faf002020-03-26 18:57:32 +0100207 eventArgs = _Py_VaBuildValue_SizeT(argFormat, vargs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700208 if (eventArgs && !PyTuple_Check(eventArgs)) {
209 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
210 Py_DECREF(eventArgs);
211 eventArgs = argTuple;
212 }
Victor Stinner08faf002020-03-26 18:57:32 +0100213 }
214 else {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700215 eventArgs = PyTuple_New(0);
216 }
217 if (!eventArgs) {
218 goto exit;
219 }
220
221 /* Call global hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100222 _Py_AuditHookEntry *e = is->runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700223 for (; e; e = e->next) {
224 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
225 goto exit;
226 }
227 }
228
229 /* Dtrace USDT point */
230 if (dtrace) {
Andy Lestere6be9b52020-02-11 20:28:35 -0600231 PyDTrace_AUDIT(event, (void *)eventArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700232 }
233
234 /* Call interpreter hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100235 if (is->audit_hooks) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700236 eventName = PyUnicode_FromString(event);
237 if (!eventName) {
238 goto exit;
239 }
240
241 hooks = PyObject_GetIter(is->audit_hooks);
242 if (!hooks) {
243 goto exit;
244 }
245
246 /* Disallow tracing in hooks unless explicitly enabled */
247 ts->tracing++;
248 ts->use_tracing = 0;
249 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300250 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700251 PyObject *o;
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300252 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700253 if (o) {
254 canTrace = PyObject_IsTrue(o);
255 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700256 }
257 if (canTrace < 0) {
258 break;
259 }
260 if (canTrace) {
261 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
262 ts->tracing--;
263 }
Victor Stinner08faf002020-03-26 18:57:32 +0100264 PyObject* args[2] = {eventName, eventArgs};
265 o = _PyObject_FastCallTstate(ts, hook, args, 2);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700266 if (canTrace) {
267 ts->tracing++;
268 ts->use_tracing = 0;
269 }
270 if (!o) {
271 break;
272 }
273 Py_DECREF(o);
274 Py_CLEAR(hook);
275 }
276 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
277 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200278 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700279 goto exit;
280 }
281 }
282
283 res = 0;
284
285exit:
286 Py_XDECREF(hook);
287 Py_XDECREF(hooks);
288 Py_XDECREF(eventName);
289 Py_XDECREF(eventArgs);
290
Victor Stinner08faf002020-03-26 18:57:32 +0100291 if (!res) {
292 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
293 }
294 else {
295 assert(_PyErr_Occurred(ts));
296 Py_XDECREF(exc_type);
297 Py_XDECREF(exc_value);
298 Py_XDECREF(exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700299 }
300
301 return res;
302}
303
Victor Stinner08faf002020-03-26 18:57:32 +0100304int
305_PySys_Audit(PyThreadState *tstate, const char *event,
306 const char *argFormat, ...)
307{
308 va_list vargs;
309#ifdef HAVE_STDARG_PROTOTYPES
310 va_start(vargs, argFormat);
311#else
312 va_start(vargs);
313#endif
314 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
315 va_end(vargs);
316 return res;
317}
318
319int
320PySys_Audit(const char *event, const char *argFormat, ...)
321{
322 PyThreadState *tstate = _PyThreadState_GET();
323 va_list vargs;
324#ifdef HAVE_STDARG_PROTOTYPES
325 va_start(vargs, argFormat);
326#else
327 va_start(vargs);
328#endif
329 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
330 va_end(vargs);
331 return res;
332}
333
Steve Dowerb82e17e2019-05-23 08:45:22 -0700334/* We expose this function primarily for our own cleanup during
335 * finalization. In general, it should not need to be called,
Victor Stinner08faf002020-03-26 18:57:32 +0100336 * and as such the function is not exported.
337 *
338 * Must be finalizing to clear hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200339void
Victor Stinner08faf002020-03-26 18:57:32 +0100340_PySys_ClearAuditHooks(PyThreadState *ts)
Victor Stinner838f2642019-06-13 22:41:23 +0200341{
Victor Stinner08faf002020-03-26 18:57:32 +0100342 assert(ts != NULL);
343 if (!ts) {
344 return;
345 }
346
347 _PyRuntimeState *runtime = ts->interp->runtime;
Victor Stinner7b3c2522020-03-07 00:24:23 +0100348 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
Victor Stinner08faf002020-03-26 18:57:32 +0100349 assert(finalizing == ts);
350 if (finalizing != ts) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700351 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200352 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700353
Victor Stinnerda7933e2020-04-13 03:04:28 +0200354 const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
Victor Stinner838f2642019-06-13 22:41:23 +0200355 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700356 PySys_WriteStderr("# clear sys.audit hooks\n");
357 }
358
359 /* Hooks can abort later hooks for this event, but cannot
360 abort the clear operation itself. */
Victor Stinner08faf002020-03-26 18:57:32 +0100361 _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200362 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700363
Victor Stinner08faf002020-03-26 18:57:32 +0100364 _Py_AuditHookEntry *e = runtime->audit_hook_head, *n;
365 runtime->audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700366 while (e) {
367 n = e->next;
368 PyMem_RawFree(e);
369 e = n;
370 }
371}
372
373int
374PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
375{
Victor Stinner08faf002020-03-26 18:57:32 +0100376 /* tstate can be NULL, so access directly _PyRuntime:
377 PySys_AddAuditHook() can be called before Python is initialized. */
Victor Stinner838f2642019-06-13 22:41:23 +0200378 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner08faf002020-03-26 18:57:32 +0100379 PyThreadState *tstate;
380 if (runtime->initialized) {
381 tstate = _PyRuntimeState_GetThreadState(runtime);
382 }
383 else {
384 tstate = NULL;
385 }
Victor Stinner838f2642019-06-13 22:41:23 +0200386
Steve Dowerb82e17e2019-05-23 08:45:22 -0700387 /* Invoke existing audit hooks to allow them an opportunity to abort. */
388 /* Cannot invoke hooks until we are initialized */
Victor Stinner08faf002020-03-26 18:57:32 +0100389 if (tstate != NULL) {
390 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800391 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
392 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200393 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700394 return 0;
395 }
396 return -1;
397 }
398 }
399
Victor Stinner08faf002020-03-26 18:57:32 +0100400 _Py_AuditHookEntry *e = runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700401 if (!e) {
402 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner08faf002020-03-26 18:57:32 +0100403 runtime->audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700404 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200405 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700406 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200407 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700408 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
409 sizeof(_Py_AuditHookEntry));
410 }
411
412 if (!e) {
Victor Stinner08faf002020-03-26 18:57:32 +0100413 if (tstate != NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200414 _PyErr_NoMemory(tstate);
415 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700416 return -1;
417 }
418
419 e->next = NULL;
420 e->hookCFunction = (Py_AuditHookFunction)hook;
421 e->userData = userData;
422
423 return 0;
424}
425
426/*[clinic input]
427sys.addaudithook
428
429 hook: object
430
431Adds a new audit hook callback.
432[clinic start generated code]*/
433
434static PyObject *
435sys_addaudithook_impl(PyObject *module, PyObject *hook)
436/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
437{
Victor Stinner838f2642019-06-13 22:41:23 +0200438 PyThreadState *tstate = _PyThreadState_GET();
439
Steve Dowerb82e17e2019-05-23 08:45:22 -0700440 /* Invoke existing audit hooks to allow them an opportunity to abort. */
Victor Stinner08faf002020-03-26 18:57:32 +0100441 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200442 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700443 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200444 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700445 Py_RETURN_NONE;
446 }
447 return NULL;
448 }
449
Victor Stinner838f2642019-06-13 22:41:23 +0200450 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700451 if (is->audit_hooks == NULL) {
452 is->audit_hooks = PyList_New(0);
453 if (is->audit_hooks == NULL) {
454 return NULL;
455 }
456 }
457
458 if (PyList_Append(is->audit_hooks, hook) < 0) {
459 return NULL;
460 }
461
462 Py_RETURN_NONE;
463}
464
465PyDoc_STRVAR(audit_doc,
466"audit(event, *args)\n\
467\n\
468Passes the event to any audit hooks that are attached.");
469
470static PyObject *
471sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
472{
Victor Stinner838f2642019-06-13 22:41:23 +0200473 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200474 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner838f2642019-06-13 22:41:23 +0200475
Steve Dowerb82e17e2019-05-23 08:45:22 -0700476 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200477 _PyErr_SetString(tstate, PyExc_TypeError,
478 "audit() missing 1 required positional argument: "
479 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700480 return NULL;
481 }
482
Victor Stinner08faf002020-03-26 18:57:32 +0100483 if (!should_audit(tstate->interp)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700484 Py_RETURN_NONE;
485 }
486
487 PyObject *auditEvent = args[0];
488 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200489 _PyErr_SetString(tstate, PyExc_TypeError,
490 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700491 return NULL;
492 }
493 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200494 _PyErr_Format(tstate, PyExc_TypeError,
495 "expected str for argument 'event', not %.200s",
496 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700497 return NULL;
498 }
499 const char *event = PyUnicode_AsUTF8(auditEvent);
500 if (!event) {
501 return NULL;
502 }
503
504 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
505 if (!auditArgs) {
506 return NULL;
507 }
508
Victor Stinner08faf002020-03-26 18:57:32 +0100509 int res = _PySys_Audit(tstate, event, "O", auditArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700510 Py_DECREF(auditArgs);
511
512 if (res < 0) {
513 return NULL;
514 }
515
516 Py_RETURN_NONE;
517}
518
519
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400520static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200521sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400522{
Victor Stinner838f2642019-06-13 22:41:23 +0200523 PyThreadState *tstate = _PyThreadState_GET();
524 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300525 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400526
527 if (envar == NULL || strlen(envar) == 0) {
528 envar = "pdb.set_trace";
529 }
530 else if (!strcmp(envar, "0")) {
531 /* The breakpoint is explicitly no-op'd. */
532 Py_RETURN_NONE;
533 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300534 /* According to POSIX the string returned by getenv() might be invalidated
535 * or the string content might be overwritten by a subsequent call to
536 * getenv(). Since importing a module can performs the getenv() calls,
537 * we need to save a copy of envar. */
538 envar = _PyMem_RawStrdup(envar);
539 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200540 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300541 return NULL;
542 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200543 const char *last_dot = strrchr(envar, '.');
544 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400545 PyObject *modulepath = NULL;
546
547 if (last_dot == NULL) {
548 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
549 modulepath = PyUnicode_FromString("builtins");
550 attrname = envar;
551 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200552 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400553 /* Split on the last dot; */
554 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
555 attrname = last_dot + 1;
556 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200557 else {
558 goto warn;
559 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400560 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300561 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400562 return NULL;
563 }
564
Anthony Sottiledce345c2018-11-01 10:25:05 -0700565 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400566 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400567
568 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200569 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200570 goto warn;
571 }
572 PyMem_RawFree(envar);
573 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400574 }
575
576 PyObject *hook = PyObject_GetAttrString(module, attrname);
577 Py_DECREF(module);
578
579 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200580 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200581 goto warn;
582 }
583 PyMem_RawFree(envar);
584 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400585 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300586 PyMem_RawFree(envar);
Petr Viktorinffd97532020-02-11 17:46:57 +0100587 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400588 Py_DECREF(hook);
589 return retval;
590
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200591 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400592 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200593 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400594 int status = PyErr_WarnFormat(
595 PyExc_RuntimeWarning, 0,
596 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300597 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400598 if (status < 0) {
599 /* Printing the warning raised an exception. */
600 return NULL;
601 }
602 /* The warning was (probably) issued. */
603 Py_RETURN_NONE;
604}
605
606PyDoc_STRVAR(breakpointhook_doc,
607"breakpointhook(*args, **kws)\n"
608"\n"
609"This hook function is called by built-in breakpoint().\n"
610);
611
Victor Stinner13d49ee2010-12-04 17:24:33 +0000612/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
613 error handler. If sys.stdout has a buffer attribute, use
614 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
615 sys.stdout.write(redecoded).
616
617 Helper function for sys_displayhook(). */
618static int
Andy Lesterda4d6562020-03-05 22:34:36 -0600619sys_displayhook_unencodable(PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000620{
621 PyObject *stdout_encoding = NULL;
622 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200623 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000624 int ret;
625
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200626 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000627 if (stdout_encoding == NULL)
628 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200629 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000630 if (stdout_encoding_str == NULL)
631 goto error;
632
633 repr_str = PyObject_Repr(o);
634 if (repr_str == NULL)
635 goto error;
636 encoded = PyUnicode_AsEncodedString(repr_str,
637 stdout_encoding_str,
638 "backslashreplace");
639 Py_DECREF(repr_str);
640 if (encoded == NULL)
641 goto error;
642
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300643 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
644 Py_DECREF(encoded);
645 goto error;
646 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000647 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200648 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000649 Py_DECREF(buffer);
650 Py_DECREF(encoded);
651 if (result == NULL)
652 goto error;
653 Py_DECREF(result);
654 }
655 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000656 escaped_str = PyUnicode_FromEncodedObject(encoded,
657 stdout_encoding_str,
658 "strict");
659 Py_DECREF(encoded);
660 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
661 Py_DECREF(escaped_str);
662 goto error;
663 }
664 Py_DECREF(escaped_str);
665 }
666 ret = 0;
667 goto finally;
668
669error:
670 ret = -1;
671finally:
672 Py_XDECREF(stdout_encoding);
673 return ret;
674}
675
Tal Einatede0b6f2018-12-31 17:12:08 +0200676/*[clinic input]
677sys.displayhook
678
679 object as o: object
680 /
681
682Print an object to sys.stdout and also save it in builtins._
683[clinic start generated code]*/
684
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000685static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200686sys_displayhook(PyObject *module, PyObject *o)
687/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000688{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100690 PyObject *builtins;
691 static PyObject *newline = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200692 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000693
Eric Snow3f9eee62017-09-15 16:35:20 -0600694 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200696 if (!_PyErr_Occurred(tstate)) {
697 _PyErr_SetString(tstate, PyExc_RuntimeError,
698 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100699 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 return NULL;
701 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600702 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000703
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 /* Print value except if None */
705 /* After printing, also assign to '_' */
706 /* Before, set '_' to None to avoid recursion */
707 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200708 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200710 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200712 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200714 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return NULL;
716 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000717 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200718 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Andy Lesterda4d6562020-03-05 22:34:36 -0600719 int err;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000720 /* repr(o) is not encodable to sys.stdout.encoding with
721 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200722 _PyErr_Clear(tstate);
Andy Lesterda4d6562020-03-05 22:34:36 -0600723 err = sys_displayhook_unencodable(outf, o);
Victor Stinner838f2642019-06-13 22:41:23 +0200724 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000725 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200726 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000727 }
728 else {
729 return NULL;
730 }
731 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100732 if (newline == NULL) {
733 newline = PyUnicode_FromString("\n");
734 if (newline == NULL)
735 return NULL;
736 }
737 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200739 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200741 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000742}
743
Tal Einatede0b6f2018-12-31 17:12:08 +0200744
745/*[clinic input]
746sys.excepthook
747
748 exctype: object
749 value: object
750 traceback: object
751 /
752
753Handle an exception by displaying it with a traceback on sys.stderr.
754[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000755
756static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200757sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
758 PyObject *traceback)
759/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000760{
Tal Einatede0b6f2018-12-31 17:12:08 +0200761 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200762 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000763}
764
Tal Einatede0b6f2018-12-31 17:12:08 +0200765
766/*[clinic input]
767sys.exc_info
768
769Return current exception information: (type, value, traceback).
770
771Return information about the most recent exception caught by an except
772clause in the current stack frame or in an older stack frame.
773[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000774
775static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200776sys_exc_info_impl(PyObject *module)
777/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000778{
Victor Stinner50b48572018-11-01 01:51:40 +0100779 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 return Py_BuildValue(
781 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100782 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
783 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
784 err_info->exc_traceback != NULL ?
785 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000786}
787
Tal Einatede0b6f2018-12-31 17:12:08 +0200788
789/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200790sys.unraisablehook
791
792 unraisable: object
793 /
794
795Handle an unraisable exception.
796
797The unraisable argument has the following attributes:
798
799* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200800* exc_value: Exception value, can be None.
801* exc_traceback: Exception traceback, can be None.
802* err_msg: Error message, can be None.
803* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200804[clinic start generated code]*/
805
806static PyObject *
807sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200808/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200809{
810 return _PyErr_WriteUnraisableDefaultHook(unraisable);
811}
812
813
814/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200815sys.exit
816
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300817 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200818 /
819
820Exit the interpreter by raising SystemExit(status).
821
822If the status is omitted or None, it defaults to zero (i.e., success).
823If the status is an integer, it will be used as the system exit status.
824If it is another kind of object, it will be printed and the system
825exit status will be one (i.e., failure).
826[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000827
828static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200829sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300830/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinner838f2642019-06-13 22:41:23 +0200833 PyThreadState *tstate = _PyThreadState_GET();
834 _PyErr_SetObject(tstate, PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000836}
837
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000838
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000839
Tal Einatede0b6f2018-12-31 17:12:08 +0200840/*[clinic input]
841sys.getdefaultencoding
842
843Return the current default encoding used by the Unicode implementation.
844[clinic start generated code]*/
845
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000846static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200847sys_getdefaultencoding_impl(PyObject *module)
848/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000849{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000851}
852
Tal Einatede0b6f2018-12-31 17:12:08 +0200853/*[clinic input]
854sys.getfilesystemencoding
855
856Return the encoding used to convert Unicode filenames to OS filenames.
857[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000858
859static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200860sys_getfilesystemencoding_impl(PyObject *module)
861/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000862{
Victor Stinner81a7be32020-04-14 15:14:01 +0200863 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200864 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400865 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000866}
867
Tal Einatede0b6f2018-12-31 17:12:08 +0200868/*[clinic input]
869sys.getfilesystemencodeerrors
870
871Return the error mode used Unicode to OS filename conversion.
872[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000873
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000874static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200875sys_getfilesystemencodeerrors_impl(PyObject *module)
876/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700877{
Victor Stinner81a7be32020-04-14 15:14:01 +0200878 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200879 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400880 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700881}
882
Tal Einatede0b6f2018-12-31 17:12:08 +0200883/*[clinic input]
884sys.intern
885
886 string as s: unicode
887 /
888
889``Intern'' the given string.
890
891This enters the string in the (global) table of interned strings whose
892purpose is to speed up dictionary lookups. Return the string itself or
893the previously interned string object with the same value.
894[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700895
896static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200897sys_intern_impl(PyObject *module, PyObject *s)
898/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000899{
Victor Stinner838f2642019-06-13 22:41:23 +0200900 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 if (PyUnicode_CheckExact(s)) {
902 Py_INCREF(s);
903 PyUnicode_InternInPlace(&s);
904 return s;
905 }
906 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200907 _PyErr_Format(tstate, PyExc_TypeError,
Victor Stinnera102ed72020-02-07 02:24:48 +0100908 "can't intern %.400s", Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 return NULL;
910 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000911}
912
Georg Brandl66a796e2006-12-19 20:50:34 +0000913
Fred Drake5755ce62001-06-27 19:19:46 +0000914/*
915 * Cached interned string objects used for calling the profile and
916 * trace functions. Initialized by trace_init().
917 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000918static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000919
920static int
921trace_init(void)
922{
Nick Coghlan5a851672017-09-08 10:14:16 +1000923 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200924 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000925 "c_call", "c_exception", "c_return",
926 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200927 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyObject *name;
929 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000930 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 if (whatstrings[i] == NULL) {
932 name = PyUnicode_InternFromString(whatnames[i]);
933 if (name == NULL)
934 return -1;
935 whatstrings[i] = name;
936 }
937 }
938 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000939}
940
941
942static PyObject *
Victor Stinner309d7cc2020-03-13 16:39:12 +0100943call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000945{
Victor Stinner78da82b2016-08-20 01:22:57 +0200946 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200948 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100949
Victor Stinner838f2642019-06-13 22:41:23 +0200950 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200951 stack[0] = (PyObject *)frame;
952 stack[1] = whatstrings[what];
953 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 /* call the Python-level function */
Victor Stinner309d7cc2020-03-13 16:39:12 +0100956 PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000957
Victor Stinner78da82b2016-08-20 01:22:57 +0200958 PyFrame_LocalsToFast(frame, 1);
959 if (result == NULL) {
960 PyTraceBack_Here(frame);
961 }
962
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000964}
965
966static int
967profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000969{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100970 if (arg == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 arg = Py_None;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100972 }
973
974 PyThreadState *tstate = _PyThreadState_GET();
975 PyObject *result = call_trampoline(tstate, self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100977 _PyEval_SetProfile(tstate, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 return -1;
979 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100980
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000981 Py_DECREF(result);
982 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000983}
984
985static int
986trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000987 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000988{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 PyObject *callback;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100990 if (what == PyTrace_CALL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 callback = self;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100992 }
993 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 callback = frame->f_trace;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100995 }
996 if (callback == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000997 return 0;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100998 }
999
1000 PyThreadState *tstate = _PyThreadState_GET();
1001 PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01001003 _PyEval_SetTrace(tstate, NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001004 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return -1;
1006 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01001007
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +03001009 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 }
1011 else {
1012 Py_DECREF(result);
1013 }
1014 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00001015}
Fred Draked0838392001-06-16 21:02:31 +00001016
Fred Drake8b4d01d2000-05-09 19:57:01 +00001017static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001018sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001019{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001020 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001022 }
1023
1024 PyThreadState *tstate = _PyThreadState_GET();
1025 if (args == Py_None) {
1026 if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
1027 return NULL;
1028 }
1029 }
1030 else {
1031 if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
1032 return NULL;
1033 }
1034 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001035 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001036}
1037
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001038PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001039"settrace(function)\n\
1040\n\
1041Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001042function call. See the debugger chapter in the library manual."
1043);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001044
Tal Einatede0b6f2018-12-31 17:12:08 +02001045/*[clinic input]
1046sys.gettrace
1047
1048Return the global debug tracing function set with sys.settrace.
1049
1050See the debugger chapter in the library manual.
1051[clinic start generated code]*/
1052
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001053static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001054sys_gettrace_impl(PyObject *module)
1055/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001056{
Victor Stinner50b48572018-11-01 01:51:40 +01001057 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 if (temp == NULL)
1061 temp = Py_None;
1062 Py_INCREF(temp);
1063 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001064}
1065
Christian Heimes9bd667a2008-01-20 15:14:11 +00001066static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001067sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001068{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001069 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001071 }
1072
1073 PyThreadState *tstate = _PyThreadState_GET();
1074 if (args == Py_None) {
1075 if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1076 return NULL;
1077 }
1078 }
1079 else {
1080 if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
1081 return NULL;
1082 }
1083 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001084 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001085}
1086
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001087PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001088"setprofile(function)\n\
1089\n\
1090Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001091and return. See the profiler chapter in the library manual."
1092);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001093
Tal Einatede0b6f2018-12-31 17:12:08 +02001094/*[clinic input]
1095sys.getprofile
1096
1097Return the profiling function set with sys.setprofile.
1098
1099See the profiler chapter in the library manual.
1100[clinic start generated code]*/
1101
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001102static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001103sys_getprofile_impl(PyObject *module)
1104/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001105{
Victor Stinner50b48572018-11-01 01:51:40 +01001106 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (temp == NULL)
1110 temp = Py_None;
1111 Py_INCREF(temp);
1112 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001113}
1114
Tim Peterse5e065b2003-07-06 18:36:54 +00001115
Tal Einatede0b6f2018-12-31 17:12:08 +02001116/*[clinic input]
1117sys.setswitchinterval
1118
1119 interval: double
1120 /
1121
1122Set the ideal thread switching delay inside the Python interpreter.
1123
1124The actual frequency of switching threads can be lower if the
1125interpreter executes long sequences of uninterruptible code
1126(this is implementation-specific and workload-dependent).
1127
1128The parameter must represent the desired switching delay in seconds
1129A typical value is 0.005 (5 milliseconds).
1130[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001131
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001132static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001133sys_setswitchinterval_impl(PyObject *module, double interval)
1134/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001135{
Victor Stinner838f2642019-06-13 22:41:23 +02001136 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001137 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001138 _PyErr_SetString(tstate, PyExc_ValueError,
1139 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return NULL;
1141 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001142 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001143 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001144}
1145
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001146
Tal Einatede0b6f2018-12-31 17:12:08 +02001147/*[clinic input]
1148sys.getswitchinterval -> double
1149
1150Return the current thread switch interval; see sys.setswitchinterval().
1151[clinic start generated code]*/
1152
1153static double
1154sys_getswitchinterval_impl(PyObject *module)
1155/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001156{
Tal Einatede0b6f2018-12-31 17:12:08 +02001157 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001158}
1159
Tal Einatede0b6f2018-12-31 17:12:08 +02001160/*[clinic input]
1161sys.setrecursionlimit
1162
1163 limit as new_limit: int
1164 /
1165
1166Set the maximum depth of the Python interpreter stack to n.
1167
1168This limit prevents infinite recursion from causing an overflow of the C
1169stack and crashing Python. The highest possible limit is platform-
1170dependent.
1171[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001172
Tim Peterse5e065b2003-07-06 18:36:54 +00001173static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001174sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1175/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001176{
Tal Einatede0b6f2018-12-31 17:12:08 +02001177 int mark;
Victor Stinner838f2642019-06-13 22:41:23 +02001178 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001179
Victor Stinner50856d52015-10-13 00:11:21 +02001180 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001181 _PyErr_SetString(tstate, PyExc_ValueError,
1182 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return NULL;
1184 }
Victor Stinner50856d52015-10-13 00:11:21 +02001185
1186 /* Issue #25274: When the recursion depth hits the recursion limit in
1187 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1188 set to 1 and a RecursionError is raised. The overflowed flag is reset
1189 to 0 when the recursion depth goes below the low-water mark: see
1190 Py_LeaveRecursiveCall().
1191
1192 Reject too low new limit if the current recursion depth is higher than
1193 the new low-water mark. Otherwise it may not be possible anymore to
1194 reset the overflowed flag to 0. */
1195 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50856d52015-10-13 00:11:21 +02001196 if (tstate->recursion_depth >= mark) {
Victor Stinner838f2642019-06-13 22:41:23 +02001197 _PyErr_Format(tstate, PyExc_RecursionError,
1198 "cannot set the recursion limit to %i at "
1199 "the recursion depth %i: the limit is too low",
1200 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001201 return NULL;
1202 }
1203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001205 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001206}
1207
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001208/*[clinic input]
1209sys.set_coroutine_origin_tracking_depth
1210
1211 depth: int
1212
1213Enable or disable origin tracking for coroutine objects in this thread.
1214
Tal Einatede0b6f2018-12-31 17:12:08 +02001215Coroutine objects will track 'depth' frames of traceback information
1216about where they came from, available in their cr_origin attribute.
1217
1218Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001219[clinic start generated code]*/
1220
1221static PyObject *
1222sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001223/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001224{
Victor Stinner838f2642019-06-13 22:41:23 +02001225 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001226 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001227 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001228 return NULL;
1229 }
Victor Stinner838f2642019-06-13 22:41:23 +02001230 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001231 Py_RETURN_NONE;
1232}
1233
1234/*[clinic input]
1235sys.get_coroutine_origin_tracking_depth -> int
1236
1237Check status of origin tracking for coroutine objects in this thread.
1238[clinic start generated code]*/
1239
1240static int
1241sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1242/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1243{
1244 return _PyEval_GetCoroutineOriginTrackingDepth();
1245}
1246
Yury Selivanoveb636452016-09-08 22:01:51 -07001247static PyTypeObject AsyncGenHooksType;
1248
1249PyDoc_STRVAR(asyncgen_hooks_doc,
1250"asyncgen_hooks\n\
1251\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001252A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001253generators hooks. The attributes are read only.");
1254
1255static PyStructSequence_Field asyncgen_hooks_fields[] = {
1256 {"firstiter", "Hook to intercept first iteration"},
1257 {"finalizer", "Hook to intercept finalization"},
1258 {0}
1259};
1260
1261static PyStructSequence_Desc asyncgen_hooks_desc = {
1262 "asyncgen_hooks", /* name */
1263 asyncgen_hooks_doc, /* doc */
1264 asyncgen_hooks_fields , /* fields */
1265 2
1266};
1267
Yury Selivanoveb636452016-09-08 22:01:51 -07001268static PyObject *
1269sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1270{
1271 static char *keywords[] = {"firstiter", "finalizer", NULL};
1272 PyObject *firstiter = NULL;
1273 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001274 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001275
1276 if (!PyArg_ParseTupleAndKeywords(
1277 args, kw, "|OO", keywords,
1278 &firstiter, &finalizer)) {
1279 return NULL;
1280 }
1281
1282 if (finalizer && finalizer != Py_None) {
1283 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001284 _PyErr_Format(tstate, PyExc_TypeError,
1285 "callable finalizer expected, got %.50s",
1286 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001287 return NULL;
1288 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001289 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1290 return NULL;
1291 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001292 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001293 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1294 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001295 }
1296
1297 if (firstiter && firstiter != Py_None) {
1298 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001299 _PyErr_Format(tstate, PyExc_TypeError,
1300 "callable firstiter expected, got %.50s",
1301 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001302 return NULL;
1303 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001304 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1305 return NULL;
1306 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001307 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001308 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1309 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001310 }
1311
1312 Py_RETURN_NONE;
1313}
1314
1315PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001316"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001317\n\
1318Set a finalizer for async generators objects."
1319);
1320
Tal Einatede0b6f2018-12-31 17:12:08 +02001321/*[clinic input]
1322sys.get_asyncgen_hooks
1323
1324Return the installed asynchronous generators hooks.
1325
1326This returns a namedtuple of the form (firstiter, finalizer).
1327[clinic start generated code]*/
1328
Yury Selivanoveb636452016-09-08 22:01:51 -07001329static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001330sys_get_asyncgen_hooks_impl(PyObject *module)
1331/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001332{
1333 PyObject *res;
1334 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1335 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1336
1337 res = PyStructSequence_New(&AsyncGenHooksType);
1338 if (res == NULL) {
1339 return NULL;
1340 }
1341
1342 if (firstiter == NULL) {
1343 firstiter = Py_None;
1344 }
1345
1346 if (finalizer == NULL) {
1347 finalizer = Py_None;
1348 }
1349
1350 Py_INCREF(firstiter);
1351 PyStructSequence_SET_ITEM(res, 0, firstiter);
1352
1353 Py_INCREF(finalizer);
1354 PyStructSequence_SET_ITEM(res, 1, finalizer);
1355
1356 return res;
1357}
1358
Yury Selivanoveb636452016-09-08 22:01:51 -07001359
Mark Dickinsondc787d22010-05-23 13:33:13 +00001360static PyTypeObject Hash_InfoType;
1361
1362PyDoc_STRVAR(hash_info_doc,
1363"hash_info\n\
1364\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001365A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001366hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001367
1368static PyStructSequence_Field hash_info_fields[] = {
1369 {"width", "width of the type used for hashing, in bits"},
1370 {"modulus", "prime number giving the modulus on which the hash "
1371 "function is based"},
1372 {"inf", "value to be used for hash of a positive infinity"},
1373 {"nan", "value to be used for hash of a nan"},
1374 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001375 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1376 "memoryviews"},
1377 {"hash_bits", "internal output size of hash algorithm"},
1378 {"seed_bits", "seed size of hash algorithm"},
1379 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001380 {NULL, NULL}
1381};
1382
1383static PyStructSequence_Desc hash_info_desc = {
1384 "sys.hash_info",
1385 hash_info_doc,
1386 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001387 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001388};
1389
Matthias Klosed885e952010-07-06 10:53:30 +00001390static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001391get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001392{
1393 PyObject *hash_info;
1394 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001395 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001396 hash_info = PyStructSequence_New(&Hash_InfoType);
1397 if (hash_info == NULL)
1398 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001399 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001400 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001401 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001402 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001403 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001404 PyStructSequence_SET_ITEM(hash_info, field++,
1405 PyLong_FromLong(_PyHASH_INF));
1406 PyStructSequence_SET_ITEM(hash_info, field++,
1407 PyLong_FromLong(_PyHASH_NAN));
1408 PyStructSequence_SET_ITEM(hash_info, field++,
1409 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001410 PyStructSequence_SET_ITEM(hash_info, field++,
1411 PyUnicode_FromString(hashfunc->name));
1412 PyStructSequence_SET_ITEM(hash_info, field++,
1413 PyLong_FromLong(hashfunc->hash_bits));
1414 PyStructSequence_SET_ITEM(hash_info, field++,
1415 PyLong_FromLong(hashfunc->seed_bits));
1416 PyStructSequence_SET_ITEM(hash_info, field++,
1417 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001418 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001419 Py_CLEAR(hash_info);
1420 return NULL;
1421 }
1422 return hash_info;
1423}
Tal Einatede0b6f2018-12-31 17:12:08 +02001424/*[clinic input]
1425sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001426
Tal Einatede0b6f2018-12-31 17:12:08 +02001427Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001428
Tal Einatede0b6f2018-12-31 17:12:08 +02001429The recursion limit is the maximum depth of the Python interpreter
1430stack. This limit prevents infinite recursion from causing an overflow
1431of the C stack and crashing Python.
1432[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001433
1434static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001435sys_getrecursionlimit_impl(PyObject *module)
1436/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001439}
1440
Mark Hammond8696ebc2002-10-08 02:44:31 +00001441#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001442
Eric Smithf7bb5782010-01-27 00:44:57 +00001443static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1444
1445static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 {"major", "Major version number"},
1447 {"minor", "Minor version number"},
1448 {"build", "Build number"},
1449 {"platform", "Operating system platform"},
1450 {"service_pack", "Latest Service Pack installed on the system"},
1451 {"service_pack_major", "Service Pack major version number"},
1452 {"service_pack_minor", "Service Pack minor version number"},
1453 {"suite_mask", "Bit mask identifying available product suites"},
1454 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001455 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001457};
1458
1459static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001460 "sys.getwindowsversion", /* name */
1461 sys_getwindowsversion__doc__, /* doc */
1462 windows_version_fields, /* fields */
1463 5 /* For backward compatibility,
1464 only the first 5 items are accessible
1465 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001466};
1467
Steve Dower3e96f322015-03-02 08:01:10 -08001468/* Disable deprecation warnings about GetVersionEx as the result is
1469 being passed straight through to the caller, who is responsible for
1470 using it correctly. */
1471#pragma warning(push)
1472#pragma warning(disable:4996)
1473
Tal Einatede0b6f2018-12-31 17:12:08 +02001474/*[clinic input]
1475sys.getwindowsversion
1476
1477Return info about the running version of Windows as a named tuple.
1478
1479The members are named: major, minor, build, platform, service_pack,
1480service_pack_major, service_pack_minor, suite_mask, product_type and
1481platform_version. For backward compatibility, only the first 5 items
1482are available by indexing. All elements are numbers, except
1483service_pack and platform_type which are strings, and platform_version
1484which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1485workstation, 2 for a domain controller, 3 for a server.
1486Platform_version is a 3-tuple containing a version number that is
1487intended for identifying the OS rather than feature detection.
1488[clinic start generated code]*/
1489
Mark Hammond8696ebc2002-10-08 02:44:31 +00001490static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001491sys_getwindowsversion_impl(PyObject *module)
1492/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 PyObject *version;
1495 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001496 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001497 DWORD realMajor, realMinor, realBuild;
1498 HANDLE hKernel32;
1499 wchar_t kernel32_path[MAX_PATH];
1500 LPVOID verblock;
1501 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001502 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001505 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 version = PyStructSequence_New(&WindowsVersionType);
1509 if (version == NULL)
1510 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1513 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1514 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1515 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001516 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1518 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1519 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1520 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001521
Steve Dower74f4af72016-09-17 17:27:48 -07001522 realMajor = ver.dwMajorVersion;
1523 realMinor = ver.dwMinorVersion;
1524 realBuild = ver.dwBuildNumber;
1525
1526 // GetVersion will lie if we are running in a compatibility mode.
1527 // We need to read the version info from a system file resource
1528 // to accurately identify the OS version. If we fail for any reason,
1529 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001530 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001531 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001532 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001533 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1534 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1535 (verblock = PyMem_RawMalloc(verblock_size))) {
1536 VS_FIXEDFILEINFO *ffi;
1537 UINT ffi_len;
1538
1539 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1540 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1541 realMajor = HIWORD(ffi->dwProductVersionMS);
1542 realMinor = LOWORD(ffi->dwProductVersionMS);
1543 realBuild = HIWORD(ffi->dwProductVersionLS);
1544 }
1545 PyMem_RawFree(verblock);
1546 }
Segev Finer48fb7662017-06-04 20:52:27 +03001547 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1548 realMajor,
1549 realMinor,
1550 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001551 ));
1552
Victor Stinner838f2642019-06-13 22:41:23 +02001553 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001554 Py_DECREF(version);
1555 return NULL;
1556 }
Steve Dower74f4af72016-09-17 17:27:48 -07001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001559}
1560
Steve Dower3e96f322015-03-02 08:01:10 -08001561#pragma warning(pop)
1562
Tal Einatede0b6f2018-12-31 17:12:08 +02001563/*[clinic input]
1564sys._enablelegacywindowsfsencoding
1565
1566Changes the default filesystem encoding to mbcs:replace.
1567
1568This is done for consistency with earlier versions of Python. See PEP
1569529 for more information.
1570
1571This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1572environment variable before launching Python.
1573[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001574
1575static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001576sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1577/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001578{
Victor Stinner709d23d2019-05-02 14:56:30 -04001579 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001580 return NULL;
1581 }
Steve Dowercc16be82016-09-08 10:35:16 -07001582 Py_RETURN_NONE;
1583}
1584
Mark Hammond8696ebc2002-10-08 02:44:31 +00001585#endif /* MS_WINDOWS */
1586
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001587#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001588
1589/*[clinic input]
1590sys.setdlopenflags
1591
1592 flags as new_val: int
1593 /
1594
1595Set the flags used by the interpreter for dlopen calls.
1596
1597This is used, for example, when the interpreter loads extension
1598modules. Among other things, this will enable a lazy resolving of
1599symbols when importing a module, if called as sys.setdlopenflags(0).
1600To share symbols across extension modules, call as
1601sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1602modules can be found in the os module (RTLD_xxx constants, e.g.
1603os.RTLD_LAZY).
1604[clinic start generated code]*/
1605
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001606static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001607sys_setdlopenflags_impl(PyObject *module, int new_val)
1608/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001609{
Victor Stinner838f2642019-06-13 22:41:23 +02001610 PyThreadState *tstate = _PyThreadState_GET();
1611 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001612 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001613}
1614
Tal Einatede0b6f2018-12-31 17:12:08 +02001615
1616/*[clinic input]
1617sys.getdlopenflags
1618
1619Return the current value of the flags that are used for dlopen calls.
1620
1621The flag constants are defined in the os module.
1622[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001623
1624static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001625sys_getdlopenflags_impl(PyObject *module)
1626/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001627{
Victor Stinner838f2642019-06-13 22:41:23 +02001628 PyThreadState *tstate = _PyThreadState_GET();
1629 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001630}
1631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001633
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001634#ifdef USE_MALLOPT
1635/* Link with -lmalloc (or -lmpc) on an SGI */
1636#include <malloc.h>
1637
Tal Einatede0b6f2018-12-31 17:12:08 +02001638/*[clinic input]
1639sys.mdebug
1640
1641 flag: int
1642 /
1643[clinic start generated code]*/
1644
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001645static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001646sys_mdebug_impl(PyObject *module, int flag)
1647/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001651 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001652}
1653#endif /* USE_MALLOPT */
1654
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001655size_t
1656_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001660 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001661 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001662
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001664 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001665 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001666 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001667
Benjamin Petersonce798522012-01-22 11:24:29 -05001668 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001670 if (!_PyErr_Occurred(tstate)) {
1671 _PyErr_Format(tstate, PyExc_TypeError,
1672 "Type %.100s doesn't define __sizeof__",
1673 Py_TYPE(o)->tp_name);
1674 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
1676 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001677 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 Py_DECREF(method);
1679 }
1680
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001681 if (res == NULL)
1682 return (size_t)-1;
1683
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001684 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001685 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001686 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001687 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001689 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001690 _PyErr_SetString(tstate, PyExc_ValueError,
1691 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001692 return (size_t)-1;
1693 }
1694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 /* add gc_head size */
Hai Shi675d9a32020-04-15 02:11:20 +08001696 if (_PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001697 return ((size_t)size) + sizeof(PyGC_Head);
1698 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001699}
1700
1701static PyObject *
1702sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1703{
1704 static char *kwlist[] = {"object", "default", 0};
1705 size_t size;
1706 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001707 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001708
1709 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001710 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001711 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001712 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001713
1714 size = _PySys_GetSizeOf(o);
1715
Victor Stinner838f2642019-06-13 22:41:23 +02001716 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001717 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001718 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1719 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001720 Py_INCREF(dflt);
1721 return dflt;
1722 }
1723 else
1724 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001726
1727 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001728}
1729
1730PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001731"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001732\n\
1733Return the size of object in bytes.");
1734
Tal Einatede0b6f2018-12-31 17:12:08 +02001735/*[clinic input]
1736sys.getrefcount -> Py_ssize_t
1737
1738 object: object
1739 /
1740
1741Return the reference count of object.
1742
1743The count returned is generally one higher than you might expect,
1744because it includes the (temporary) reference as an argument to
1745getrefcount().
1746[clinic start generated code]*/
1747
1748static Py_ssize_t
1749sys_getrefcount_impl(PyObject *module, PyObject *object)
1750/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001751{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001752 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001753}
1754
Tim Peters4be93d02002-07-07 19:59:50 +00001755#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001756/*[clinic input]
1757sys.gettotalrefcount -> Py_ssize_t
1758[clinic start generated code]*/
1759
1760static Py_ssize_t
1761sys_gettotalrefcount_impl(PyObject *module)
1762/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001763{
Tal Einatede0b6f2018-12-31 17:12:08 +02001764 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001765}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001766#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001767
Tal Einatede0b6f2018-12-31 17:12:08 +02001768/*[clinic input]
1769sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001770
Tal Einatede0b6f2018-12-31 17:12:08 +02001771Return the number of memory blocks currently allocated.
1772[clinic start generated code]*/
1773
1774static Py_ssize_t
1775sys_getallocatedblocks_impl(PyObject *module)
1776/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001777{
Tal Einatede0b6f2018-12-31 17:12:08 +02001778 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001779}
1780
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001781
Tal Einatede0b6f2018-12-31 17:12:08 +02001782/*[clinic input]
1783sys._getframe
1784
1785 depth: int = 0
1786 /
1787
1788Return a frame object from the call stack.
1789
1790If optional integer depth is given, return the frame object that many
1791calls below the top of the stack. If that is deeper than the call
1792stack, ValueError is raised. The default for depth is zero, returning
1793the frame at the top of the call stack.
1794
1795This function should be used for internal and specialized purposes
1796only.
1797[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001798
1799static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001800sys__getframe_impl(PyObject *module, int depth)
1801/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001802{
Victor Stinner838f2642019-06-13 22:41:23 +02001803 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner70364772020-04-29 03:28:46 +02001804 PyFrameObject *f = PyThreadState_GetFrame(tstate);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001805
Victor Stinner08faf002020-03-26 18:57:32 +01001806 if (_PySys_Audit(tstate, "sys._getframe", "O", f) < 0) {
Victor Stinner70364772020-04-29 03:28:46 +02001807 Py_DECREF(f);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001808 return NULL;
1809 }
1810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 while (depth > 0 && f != NULL) {
Victor Stinner70364772020-04-29 03:28:46 +02001812 PyFrameObject *back = PyFrame_GetBack(f);
1813 Py_DECREF(f);
1814 f = back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 --depth;
1816 }
1817 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001818 _PyErr_SetString(tstate, PyExc_ValueError,
1819 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 return NULL;
1821 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001823}
1824
Tal Einatede0b6f2018-12-31 17:12:08 +02001825/*[clinic input]
1826sys._current_frames
1827
1828Return a dict mapping each thread's thread id to its current stack frame.
1829
1830This function should be used for specialized purposes only.
1831[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001832
1833static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001834sys__current_frames_impl(PyObject *module)
1835/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001838}
1839
Tal Einatede0b6f2018-12-31 17:12:08 +02001840/*[clinic input]
1841sys.call_tracing
1842
1843 func: object
1844 args as funcargs: object(subclass_of='&PyTuple_Type')
1845 /
1846
1847Call func(*args), while tracing is enabled.
1848
1849The tracing state is saved, and restored afterwards. This is intended
1850to be called from a debugger from a checkpoint, to recursively debug
1851some other code.
1852[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001853
1854static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001855sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1856/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001858 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001859}
1860
Victor Stinner048afd92016-11-28 11:59:04 +01001861
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001862#ifdef __cplusplus
1863extern "C" {
1864#endif
1865
Tal Einatede0b6f2018-12-31 17:12:08 +02001866/*[clinic input]
1867sys._debugmallocstats
1868
1869Print summary info to stderr about the state of pymalloc's structures.
1870
1871In Py_DEBUG mode, also perform some expensive internal consistency
1872checks.
1873[clinic start generated code]*/
1874
David Malcolm49526f42012-06-22 14:55:41 -04001875static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001876sys__debugmallocstats_impl(PyObject *module)
1877/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001878{
1879#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001880 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001881 fputc('\n', stderr);
1882 }
David Malcolm49526f42012-06-22 14:55:41 -04001883#endif
1884 _PyObject_DebugTypeStats(stderr);
1885
1886 Py_RETURN_NONE;
1887}
David Malcolm49526f42012-06-22 14:55:41 -04001888
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001889#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001890/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001891extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001892#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001893
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001894#ifdef DYNAMIC_EXECUTION_PROFILE
1895/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001896extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001897#endif
1898
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001899#ifdef __cplusplus
1900}
1901#endif
1902
Tal Einatede0b6f2018-12-31 17:12:08 +02001903
1904/*[clinic input]
1905sys._clear_type_cache
1906
1907Clear the internal type lookup cache.
1908[clinic start generated code]*/
1909
Christian Heimes15ebc882008-02-04 18:48:49 +00001910static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001911sys__clear_type_cache_impl(PyObject *module)
1912/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 PyType_ClearCache();
1915 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001916}
1917
Tal Einatede0b6f2018-12-31 17:12:08 +02001918/*[clinic input]
1919sys.is_finalizing
1920
1921Return True if Python is exiting.
1922[clinic start generated code]*/
1923
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001924static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001925sys_is_finalizing_impl(PyObject *module)
1926/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001927{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001928 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001929}
1930
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001931#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001932/*[clinic input]
1933sys.getandroidapilevel
1934
1935Return the build time API version of Android as an integer.
1936[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001937
1938static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001939sys_getandroidapilevel_impl(PyObject *module)
1940/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001941{
1942 return PyLong_FromLong(ANDROID_API_LEVEL);
1943}
1944#endif /* ANDROID_API_LEVEL */
1945
1946
Steve Dowerb82e17e2019-05-23 08:45:22 -07001947
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001948static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001950 SYS_ADDAUDITHOOK_METHODDEF
1951 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001952 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001953 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001954 SYS__CLEAR_TYPE_CACHE_METHODDEF
1955 SYS__CURRENT_FRAMES_METHODDEF
1956 SYS_DISPLAYHOOK_METHODDEF
1957 SYS_EXC_INFO_METHODDEF
1958 SYS_EXCEPTHOOK_METHODDEF
1959 SYS_EXIT_METHODDEF
1960 SYS_GETDEFAULTENCODING_METHODDEF
1961 SYS_GETDLOPENFLAGS_METHODDEF
1962 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001963#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001965#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001966 SYS_GETFILESYSTEMENCODING_METHODDEF
1967 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001968#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001970#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001971 SYS_GETTOTALREFCOUNT_METHODDEF
1972 SYS_GETREFCOUNT_METHODDEF
1973 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001974 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001976 SYS__GETFRAME_METHODDEF
1977 SYS_GETWINDOWSVERSION_METHODDEF
1978 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1979 SYS_INTERN_METHODDEF
1980 SYS_IS_FINALIZING_METHODDEF
1981 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001982 SYS_SETSWITCHINTERVAL_METHODDEF
1983 SYS_GETSWITCHINTERVAL_METHODDEF
1984 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001986 SYS_GETPROFILE_METHODDEF
1987 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001989 SYS_GETTRACE_METHODDEF
1990 SYS_CALL_TRACING_METHODDEF
1991 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001992 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1993 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001994 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001995 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001996 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1997 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02001998 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002000};
2001
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002002static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002003list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 PyObject *list = PyList_New(0);
2006 int i;
2007 if (list == NULL)
2008 return NULL;
2009 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2010 PyObject *name = PyUnicode_FromString(
2011 PyImport_Inittab[i].name);
2012 if (name == NULL)
2013 break;
2014 PyList_Append(list, name);
2015 Py_DECREF(name);
2016 }
2017 if (PyList_Sort(list) != 0) {
2018 Py_DECREF(list);
2019 list = NULL;
2020 }
2021 if (list) {
2022 PyObject *v = PyList_AsTuple(list);
2023 Py_DECREF(list);
2024 list = v;
2025 }
2026 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002027}
2028
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002029/* Pre-initialization support for sys.warnoptions and sys._xoptions
2030 *
2031 * Modern internal code paths:
2032 * These APIs get called after _Py_InitializeCore and get to use the
2033 * regular CPython list, dict, and unicode APIs.
2034 *
2035 * Legacy embedding code paths:
2036 * The multi-phase initialization API isn't public yet, so embedding
2037 * apps still need to be able configure sys.warnoptions and sys._xoptions
2038 * before they call Py_Initialize. To support this, we stash copies of
2039 * the supplied wchar * sequences in linked lists, and then migrate the
2040 * contents of those lists to the sys module in _PyInitializeCore.
2041 *
2042 */
2043
2044struct _preinit_entry {
2045 wchar_t *value;
2046 struct _preinit_entry *next;
2047};
2048
2049typedef struct _preinit_entry *_Py_PreInitEntry;
2050
2051static _Py_PreInitEntry _preinit_warnoptions = NULL;
2052static _Py_PreInitEntry _preinit_xoptions = NULL;
2053
2054static _Py_PreInitEntry
2055_alloc_preinit_entry(const wchar_t *value)
2056{
2057 /* To get this to work, we have to initialize the runtime implicitly */
2058 _PyRuntime_Initialize();
2059
2060 /* Force default allocator, so we can ensure that it also gets used to
2061 * destroy the linked list in _clear_preinit_entries.
2062 */
2063 PyMemAllocatorEx old_alloc;
2064 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2065
2066 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2067 if (node != NULL) {
2068 node->value = _PyMem_RawWcsdup(value);
2069 if (node->value == NULL) {
2070 PyMem_RawFree(node);
2071 node = NULL;
2072 };
2073 };
2074
2075 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2076 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002077}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002078
2079static int
2080_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2081{
2082 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2083 if (new_entry == NULL) {
2084 return -1;
2085 }
2086 /* We maintain the linked list in this order so it's easy to play back
2087 * the add commands in the same order later on in _Py_InitializeCore
2088 */
2089 _Py_PreInitEntry last_entry = *optionlist;
2090 if (last_entry == NULL) {
2091 *optionlist = new_entry;
2092 } else {
2093 while (last_entry->next != NULL) {
2094 last_entry = last_entry->next;
2095 }
2096 last_entry->next = new_entry;
2097 }
2098 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002099}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002100
2101static void
2102_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2103{
2104 _Py_PreInitEntry current = *optionlist;
2105 *optionlist = NULL;
2106 /* Deallocate the nodes and their contents using the default allocator */
2107 PyMemAllocatorEx old_alloc;
2108 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2109 while (current != NULL) {
2110 _Py_PreInitEntry next = current->next;
2111 PyMem_RawFree(current->value);
2112 PyMem_RawFree(current);
2113 current = next;
2114 }
2115 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002116}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002117
Victor Stinner120b7072019-08-23 18:03:08 +01002118
2119PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002120_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002121{
Victor Stinner120b7072019-08-23 18:03:08 +01002122 PyStatus status;
2123 _Py_PreInitEntry entry;
2124
2125 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002126 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002127 if (_PyStatus_EXCEPTION(status)) {
2128 return status;
2129 }
2130 }
2131
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002132 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002133 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002134}
2135
Victor Stinner120b7072019-08-23 18:03:08 +01002136
2137PyStatus
2138_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002139{
Victor Stinner120b7072019-08-23 18:03:08 +01002140 PyStatus status;
2141 _Py_PreInitEntry entry;
2142
2143 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2144 status = PyWideStringList_Append(&config->xoptions, entry->value);
2145 if (_PyStatus_EXCEPTION(status)) {
2146 return status;
2147 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002148 }
2149
Victor Stinner120b7072019-08-23 18:03:08 +01002150 _clear_preinit_entries(&_preinit_xoptions);
2151 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002152}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002153
Victor Stinner120b7072019-08-23 18:03:08 +01002154
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002155static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002156get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002157{
Victor Stinner838f2642019-06-13 22:41:23 +02002158 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002159 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002160 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2161 * interpreter config. When that happens, we need to properly set
2162 * the `warnoptions` reference in the main interpreter config as well.
2163 *
2164 * For Python 3.7, we shouldn't be able to get here due to the
2165 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2166 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2167 * call optional for embedding applications, thus making this
2168 * reachable again.
2169 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002170 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002171 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002172 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002173 }
2174 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002175 Py_DECREF(warnoptions);
2176 return NULL;
2177 }
2178 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002179 }
2180 return warnoptions;
2181}
Guido van Rossum23fff912000-12-15 22:02:05 +00002182
2183void
2184PySys_ResetWarnOptions(void)
2185{
Victor Stinner50b48572018-11-01 01:51:40 +01002186 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002187 if (tstate == NULL) {
2188 _clear_preinit_entries(&_preinit_warnoptions);
2189 return;
2190 }
2191
Victor Stinner838f2642019-06-13 22:41:23 +02002192 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 if (warnoptions == NULL || !PyList_Check(warnoptions))
2194 return;
2195 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002196}
2197
Victor Stinnere1b29952018-10-30 14:31:42 +01002198static int
Victor Stinner838f2642019-06-13 22:41:23 +02002199_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002200{
Victor Stinner838f2642019-06-13 22:41:23 +02002201 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002202 if (warnoptions == NULL) {
2203 return -1;
2204 }
2205 if (PyList_Append(warnoptions, option)) {
2206 return -1;
2207 }
2208 return 0;
2209}
2210
2211void
2212PySys_AddWarnOptionUnicode(PyObject *option)
2213{
Victor Stinner838f2642019-06-13 22:41:23 +02002214 PyThreadState *tstate = _PyThreadState_GET();
2215 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002216 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002217 if (tstate) {
2218 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002219 }
2220 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002221}
2222
2223void
2224PySys_AddWarnOption(const wchar_t *s)
2225{
Victor Stinner50b48572018-11-01 01:51:40 +01002226 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002227 if (tstate == NULL) {
2228 _append_preinit_entry(&_preinit_warnoptions, s);
2229 return;
2230 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002231 PyObject *unicode;
2232 unicode = PyUnicode_FromWideChar(s, -1);
2233 if (unicode == NULL)
2234 return;
2235 PySys_AddWarnOptionUnicode(unicode);
2236 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002237}
2238
Christian Heimes33fe8092008-04-13 13:53:33 +00002239int
2240PySys_HasWarnOptions(void)
2241{
Victor Stinner838f2642019-06-13 22:41:23 +02002242 PyThreadState *tstate = _PyThreadState_GET();
2243 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002244 return (warnoptions != NULL && PyList_Check(warnoptions)
2245 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002246}
2247
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002248static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002249get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002250{
Victor Stinner838f2642019-06-13 22:41:23 +02002251 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002252 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002253 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2254 * interpreter config. When that happens, we need to properly set
2255 * the `xoptions` reference in the main interpreter config as well.
2256 *
2257 * For Python 3.7, we shouldn't be able to get here due to the
2258 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2259 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2260 * call optional for embedding applications, thus making this
2261 * reachable again.
2262 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002263 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002264 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002265 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002266 }
2267 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002268 Py_DECREF(xoptions);
2269 return NULL;
2270 }
2271 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002272 }
2273 return xoptions;
2274}
2275
Victor Stinnere1b29952018-10-30 14:31:42 +01002276static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002277_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002278{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002279 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002280
Victor Stinner838f2642019-06-13 22:41:23 +02002281 PyThreadState *tstate = _PyThreadState_GET();
2282 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002284 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002285 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002286
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002287 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002288 if (!name_end) {
2289 name = PyUnicode_FromWideChar(s, -1);
2290 value = Py_True;
2291 Py_INCREF(value);
2292 }
2293 else {
2294 name = PyUnicode_FromWideChar(s, name_end - s);
2295 value = PyUnicode_FromWideChar(name_end + 1, -1);
2296 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002297 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002298 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002299 }
2300 if (PyDict_SetItem(opts, name, value) < 0) {
2301 goto error;
2302 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002303 Py_DECREF(name);
2304 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002305 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002306
2307error:
2308 Py_XDECREF(name);
2309 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002310 return -1;
2311}
2312
2313void
2314PySys_AddXOption(const wchar_t *s)
2315{
Victor Stinner50b48572018-11-01 01:51:40 +01002316 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002317 if (tstate == NULL) {
2318 _append_preinit_entry(&_preinit_xoptions, s);
2319 return;
2320 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002321 if (_PySys_AddXOptionWithError(s) < 0) {
2322 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002323 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002324 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002325}
2326
2327PyObject *
2328PySys_GetXOptions(void)
2329{
Victor Stinner838f2642019-06-13 22:41:23 +02002330 PyThreadState *tstate = _PyThreadState_GET();
2331 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002332}
2333
Guido van Rossum40552d01998-08-06 03:34:39 +00002334/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2335 Two literals concatenated works just fine. If you have a K&R compiler
2336 or other abomination that however *does* understand longer strings,
2337 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002338PyDoc_VAR(sys_doc) =
2339PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002340"This module provides access to some objects used or maintained by the\n\
2341interpreter and to functions that interact strongly with the interpreter.\n\
2342\n\
2343Dynamic objects:\n\
2344\n\
2345argv -- command line arguments; argv[0] is the script pathname if known\n\
2346path -- module search path; path[0] is the script directory, else ''\n\
2347modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002348\n\
2349displayhook -- called to show results in an interactive session\n\
2350excepthook -- called to handle any uncaught exception other than SystemExit\n\
2351 To customize printing in an interactive session or to install a custom\n\
2352 top-level exception handler, assign other functions to replace these.\n\
2353\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002354stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002355stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002356stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002357 By assigning other file objects (or objects that behave like files)\n\
2358 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002359\n\
2360last_type -- type of last uncaught exception\n\
2361last_value -- value of last uncaught exception\n\
2362last_traceback -- traceback of last uncaught exception\n\
2363 These three are only available in an interactive session after a\n\
2364 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002365"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002366)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002367/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002368PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002369"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002370Static objects:\n\
2371\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002372builtin_module_names -- tuple of module names built into this interpreter\n\
2373copyright -- copyright notice pertaining to this interpreter\n\
2374exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002375executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002376float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002377float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002378hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002379hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002380implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002381int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002382maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002383maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002384platform -- platform identifier\n\
2385prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002386thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002387version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002388version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002389"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002390)
Steve Dowercc16be82016-09-08 10:35:16 -07002391#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002392/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002393PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002394"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002395winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002396"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002397)
Steve Dowercc16be82016-09-08 10:35:16 -07002398#endif /* MS_COREDLL */
2399#ifdef MS_WINDOWS
2400/* concatenating string here */
2401PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002402"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002403"
2404)
2405#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002406PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002407"__stdin__ -- the original stdin; don't touch!\n\
2408__stdout__ -- the original stdout; don't touch!\n\
2409__stderr__ -- the original stderr; don't touch!\n\
2410__displayhook__ -- the original displayhook; don't touch!\n\
2411__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002412\n\
2413Functions:\n\
2414\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002415displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002416excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002417exc_info() -- return thread-safe information about the current exception\n\
2418exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002419getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002420getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002421getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002422getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002423getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002424gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002425setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002426setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002427setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002428settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002429"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002430)
Fred Drakeccede592000-08-14 20:59:57 +00002431/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002432
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002433
2434PyDoc_STRVAR(flags__doc__,
2435"sys.flags\n\
2436\n\
2437Flags provided through command line arguments or environment vars.");
2438
2439static PyTypeObject FlagsType;
2440
2441static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 {"inspect", "-i"},
2444 {"interactive", "-i"},
2445 {"optimize", "-O or -OO"},
2446 {"dont_write_bytecode", "-B"},
2447 {"no_user_site", "-s"},
2448 {"no_site", "-S"},
2449 {"ignore_environment", "-E"},
2450 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* {"unbuffered", "-u"}, */
2452 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002453 {"bytes_warning", "-b"},
2454 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002455 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002456 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002457 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002458 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002460};
2461
2462static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 "sys.flags", /* name */
2464 flags__doc__, /* doc */
2465 flags_fields, /* fields */
Victor Stinner1def7752020-04-23 03:03:24 +02002466 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002467};
2468
2469static PyObject*
Victor Stinner01b1cc12019-11-20 02:27:56 +01002470make_flags(PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002471{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002472 PyInterpreterState *interp = tstate->interp;
2473 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002474 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002475
Victor Stinner01b1cc12019-11-20 02:27:56 +01002476 PyObject *seq = PyStructSequence_New(&FlagsType);
2477 if (seq == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 return NULL;
Victor Stinner01b1cc12019-11-20 02:27:56 +01002479 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002480
Victor Stinner01b1cc12019-11-20 02:27:56 +01002481 int pos = 0;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002482#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002484
Victor Stinnerfbca9082018-08-30 00:50:45 +02002485 SetFlag(config->parser_debug);
2486 SetFlag(config->inspect);
2487 SetFlag(config->interactive);
2488 SetFlag(config->optimization_level);
2489 SetFlag(!config->write_bytecode);
2490 SetFlag(!config->user_site_directory);
2491 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002492 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002493 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* SetFlag(saw_unbuffered_flag); */
2495 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002496 SetFlag(config->bytes_warning);
2497 SetFlag(config->quiet);
2498 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002499 SetFlag(config->isolated);
2500 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2501 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002502#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002503
Victor Stinner838f2642019-06-13 22:41:23 +02002504 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002505 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return NULL;
2507 }
2508 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002509}
2510
Eric Smith0e5b5622009-02-06 01:32:42 +00002511PyDoc_STRVAR(version_info__doc__,
2512"sys.version_info\n\
2513\n\
2514Version information as a named tuple.");
2515
2516static PyTypeObject VersionInfoType;
2517
2518static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002519 {"major", "Major release number"},
2520 {"minor", "Minor release number"},
2521 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002522 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 {"serial", "Serial release number"},
2524 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002525};
2526
2527static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 "sys.version_info", /* name */
2529 version_info__doc__, /* doc */
2530 version_info_fields, /* fields */
2531 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002532};
2533
2534static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002535make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 PyObject *version_info;
2538 char *s;
2539 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 version_info = PyStructSequence_New(&VersionInfoType);
2542 if (version_info == NULL) {
2543 return NULL;
2544 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002546 /*
2547 * These release level checks are mutually exclusive and cover
2548 * the field, so don't get too fancy with the pre-processor!
2549 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002550#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002552#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002554#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002556#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002558#endif
2559
2560#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002562#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 SetIntItem(PY_MAJOR_VERSION);
2566 SetIntItem(PY_MINOR_VERSION);
2567 SetIntItem(PY_MICRO_VERSION);
2568 SetStrItem(s);
2569 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002570#undef SetIntItem
2571#undef SetStrItem
2572
Victor Stinner838f2642019-06-13 22:41:23 +02002573 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 Py_CLEAR(version_info);
2575 return NULL;
2576 }
2577 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002578}
2579
Brett Cannon3adc7b72012-07-09 14:22:12 -04002580/* sys.implementation values */
2581#define NAME "cpython"
2582const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002583#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2584#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002585#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002586const char *_PySys_ImplCacheTag = TAG;
2587#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002588#undef MAJOR
2589#undef MINOR
2590#undef TAG
2591
Barry Warsaw409da152012-06-03 16:18:47 -04002592static PyObject *
2593make_impl_info(PyObject *version_info)
2594{
2595 int res;
2596 PyObject *impl_info, *value, *ns;
2597
2598 impl_info = PyDict_New();
2599 if (impl_info == NULL)
2600 return NULL;
2601
2602 /* populate the dict */
2603
Brett Cannon3adc7b72012-07-09 14:22:12 -04002604 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002605 if (value == NULL)
2606 goto error;
2607 res = PyDict_SetItemString(impl_info, "name", value);
2608 Py_DECREF(value);
2609 if (res < 0)
2610 goto error;
2611
Brett Cannon3adc7b72012-07-09 14:22:12 -04002612 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002613 if (value == NULL)
2614 goto error;
2615 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2616 Py_DECREF(value);
2617 if (res < 0)
2618 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002619
2620 res = PyDict_SetItemString(impl_info, "version", version_info);
2621 if (res < 0)
2622 goto error;
2623
2624 value = PyLong_FromLong(PY_VERSION_HEX);
2625 if (value == NULL)
2626 goto error;
2627 res = PyDict_SetItemString(impl_info, "hexversion", value);
2628 Py_DECREF(value);
2629 if (res < 0)
2630 goto error;
2631
doko@ubuntu.com55532312016-06-14 08:55:19 +02002632#ifdef MULTIARCH
2633 value = PyUnicode_FromString(MULTIARCH);
2634 if (value == NULL)
2635 goto error;
2636 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2637 Py_DECREF(value);
2638 if (res < 0)
2639 goto error;
2640#endif
2641
Barry Warsaw409da152012-06-03 16:18:47 -04002642 /* dict ready */
2643
2644 ns = _PyNamespace_New(impl_info);
2645 Py_DECREF(impl_info);
2646 return ns;
2647
2648error:
2649 Py_CLEAR(impl_info);
2650 return NULL;
2651}
2652
Martin v. Löwis1a214512008-06-11 05:26:20 +00002653static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 PyModuleDef_HEAD_INIT,
2655 "sys",
2656 sys_doc,
2657 -1, /* multiple "initialization" just copies the module dict. */
2658 sys_methods,
2659 NULL,
2660 NULL,
2661 NULL,
2662 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002663};
2664
Eric Snow6b4be192017-05-22 21:36:03 -07002665/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002666#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002667 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002668 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002669 if (v == NULL) { \
2670 goto err_occurred; \
2671 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002672 res = PyDict_SetItemString(sysdict, key, v); \
2673 Py_DECREF(v); \
2674 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002675 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002676 } \
2677 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002678
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002679#define SET_SYS_FROM_STRING(key, value) \
2680 SET_SYS(key, PyUnicode_FromString(value))
2681
Victor Stinner331a6a52019-05-27 16:39:22 +02002682static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002683_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002684{
Victor Stinnerab672812019-01-23 15:04:40 +01002685 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002686 int res;
2687
Nick Coghland6009512014-11-20 21:39:37 +10002688 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002689
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002690#define COPY_SYS_ATTR(tokey, fromkey) \
2691 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002692
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002693 COPY_SYS_ATTR("__displayhook__", "displayhook");
2694 COPY_SYS_ATTR("__excepthook__", "excepthook");
2695 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2696 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2697
2698#undef COPY_SYS_ATTR
2699
2700 SET_SYS_FROM_STRING("version", Py_GetVersion());
2701 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2702 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2703 _Py_gitversion()));
2704 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2705 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2706 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2707 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2708 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2709 SET_SYS("float_info", PyFloat_GetInfo());
2710 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002711 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002712 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002713 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2714 goto type_init_failed;
2715 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002716 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002717 SET_SYS("hash_info", get_hash_info(tstate));
2718 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2719 SET_SYS("builtin_module_names", list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002720#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002721 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002722#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002723 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002724#endif
Fred Drake099325e2000-08-14 15:47:03 +00002725
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002726#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002727 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2728 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002729#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002730#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002731 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002732#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002735 if (VersionInfoType.tp_name == NULL) {
2736 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002737 &version_info_desc) < 0) {
2738 goto type_init_failed;
2739 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002740 }
Victor Stinner838f2642019-06-13 22:41:23 +02002741 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002742 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 /* prevent user from creating new instances */
2744 VersionInfoType.tp_init = NULL;
2745 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002746 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002747 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2748 _PyErr_Clear(tstate);
2749 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002750
Barry Warsaw409da152012-06-03 16:18:47 -04002751 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002752 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002755 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002756 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2757 goto type_init_failed;
2758 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002759 }
Victor Stinner43125222019-04-24 18:23:53 +02002760 /* Set flags to their default values (updated by _PySys_InitMain()) */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002761 SET_SYS("flags", make_flags(tstate));
Eric Smithf7bb5782010-01-27 00:44:57 +00002762
2763#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 /* getwindowsversion */
2765 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002766 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002767 &windows_version_desc) < 0) {
2768 goto type_init_failed;
2769 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 /* prevent user from creating new instances */
2771 WindowsVersionType.tp_init = NULL;
2772 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002773 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002774 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002775 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2776 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002777 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002778#endif
2779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002781#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002782 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002783#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002784 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002785#endif
2786
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002787 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002788
Yury Selivanoveb636452016-09-08 22:01:51 -07002789 /* initialize asyncgen_hooks */
2790 if (AsyncGenHooksType.tp_name == NULL) {
2791 if (PyStructSequence_InitType2(
2792 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002793 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002794 }
2795 }
2796
Victor Stinner838f2642019-06-13 22:41:23 +02002797 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002798 goto err_occurred;
2799 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002800 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002801
2802type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002803 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002804
2805err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002806 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002807}
2808
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002809static int
2810sys_add_xoption(PyObject *opts, const wchar_t *s)
2811{
2812 PyObject *name, *value;
2813
2814 const wchar_t *name_end = wcschr(s, L'=');
2815 if (!name_end) {
2816 name = PyUnicode_FromWideChar(s, -1);
2817 value = Py_True;
2818 Py_INCREF(value);
2819 }
2820 else {
2821 name = PyUnicode_FromWideChar(s, name_end - s);
2822 value = PyUnicode_FromWideChar(name_end + 1, -1);
2823 }
2824 if (name == NULL || value == NULL) {
2825 goto error;
2826 }
2827 if (PyDict_SetItem(opts, name, value) < 0) {
2828 goto error;
2829 }
2830 Py_DECREF(name);
2831 Py_DECREF(value);
2832 return 0;
2833
2834error:
2835 Py_XDECREF(name);
2836 Py_XDECREF(value);
2837 return -1;
2838}
2839
2840
2841static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002842sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002843{
2844 Py_ssize_t nxoption = config->xoptions.length;
2845 wchar_t * const * xoptions = config->xoptions.items;
2846 PyObject *dict = PyDict_New();
2847 if (dict == NULL) {
2848 return NULL;
2849 }
2850
2851 for (Py_ssize_t i=0; i < nxoption; i++) {
2852 const wchar_t *option = xoptions[i];
2853 if (sys_add_xoption(dict, option) < 0) {
2854 Py_DECREF(dict);
2855 return NULL;
2856 }
2857 }
2858
2859 return dict;
2860}
2861
2862
Eric Snow6b4be192017-05-22 21:36:03 -07002863int
Victor Stinner01b1cc12019-11-20 02:27:56 +01002864_PySys_InitMain(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002865{
Victor Stinner838f2642019-06-13 22:41:23 +02002866 PyObject *sysdict = tstate->interp->sysdict;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002867 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002868 int res;
2869
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002870#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002871 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002872
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002873#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002874 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002875
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002876 COPY_LIST("path", config->module_search_paths);
2877
2878 SET_SYS_FROM_WSTR("executable", config->executable);
Steve Dower9048c492019-06-29 10:34:11 -07002879 SET_SYS_FROM_WSTR("_base_executable", config->base_executable);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002880 SET_SYS_FROM_WSTR("prefix", config->prefix);
2881 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2882 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2883 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Sandro Mani8f023a22020-06-08 17:28:11 +02002884 SET_SYS_FROM_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002885
Carl Meyerb193fa92018-06-15 22:40:56 -06002886 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002887 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002888 } else {
2889 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2890 }
2891
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002892 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002893 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002894 COPY_LIST("warnoptions", config->warnoptions);
2895
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002896 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002897
Victor Stinner37cd9822018-11-16 11:55:35 +01002898#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002899#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002900
Victor Stinner8510f432020-03-10 09:53:09 +01002901
Eric Snow6b4be192017-05-22 21:36:03 -07002902 /* Set flags to their final values */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002903 SET_SYS("flags", make_flags(tstate));
Eric Snow6b4be192017-05-22 21:36:03 -07002904 /* prevent user from creating new instances */
2905 FlagsType.tp_init = NULL;
2906 FlagsType.tp_new = NULL;
2907 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2908 if (res < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02002909 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Eric Snow6b4be192017-05-22 21:36:03 -07002910 return res;
2911 }
Victor Stinner838f2642019-06-13 22:41:23 +02002912 _PyErr_Clear(tstate);
Eric Snow6b4be192017-05-22 21:36:03 -07002913 }
2914
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002915 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002916
Victor Stinner838f2642019-06-13 22:41:23 +02002917 if (get_warnoptions(tstate) == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002918 return -1;
Victor Stinner838f2642019-06-13 22:41:23 +02002919 }
Victor Stinner865de272017-06-08 13:27:47 +02002920
Victor Stinner838f2642019-06-13 22:41:23 +02002921 if (get_xoptions(tstate) == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002922 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002923
Victor Stinner838f2642019-06-13 22:41:23 +02002924 if (_PyErr_Occurred(tstate)) {
2925 goto err_occurred;
2926 }
2927
Eric Snow6b4be192017-05-22 21:36:03 -07002928 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002929
2930err_occurred:
2931 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002932}
2933
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002934#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01002935#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002936
Victor Stinnerab672812019-01-23 15:04:40 +01002937
2938/* Set up a preliminary stderr printer until we have enough
2939 infrastructure for the io module in place.
2940
2941 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002942static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002943_PySys_SetPreliminaryStderr(PyObject *sysdict)
2944{
2945 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2946 if (pstderr == NULL) {
2947 goto error;
2948 }
2949 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2950 goto error;
2951 }
2952 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2953 goto error;
2954 }
2955 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002956 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01002957
2958error:
2959 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002960 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01002961}
2962
2963
2964/* Create sys module without all attributes: _PySys_InitMain() should be called
2965 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002966PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002967_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002968{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002969 assert(!_PyErr_Occurred(tstate));
2970
Victor Stinnerb45d2592019-06-20 00:05:23 +02002971 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02002972
Victor Stinnerab672812019-01-23 15:04:40 +01002973 PyObject *modules = PyDict_New();
2974 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002975 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002976 }
2977 interp->modules = modules;
2978
2979 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2980 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002981 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01002982 }
2983
2984 PyObject *sysdict = PyModule_GetDict(sysmod);
2985 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002986 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002987 }
2988 Py_INCREF(sysdict);
2989 interp->sysdict = sysdict;
2990
2991 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002992 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002993 }
2994
Victor Stinner331a6a52019-05-27 16:39:22 +02002995 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
2996 if (_PyStatus_EXCEPTION(status)) {
2997 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01002998 }
2999
Victor Stinner01b1cc12019-11-20 02:27:56 +01003000 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003001 if (_PyStatus_EXCEPTION(status)) {
3002 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003003 }
3004
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003005 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3006 goto error;
3007 }
3008
3009 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003010
3011 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003012 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003013
3014error:
3015 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003016}
3017
3018
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003019static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003020makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003022 int i, n;
3023 const wchar_t *p;
3024 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003026 n = 1;
3027 p = path;
3028 while ((p = wcschr(p, delim)) != NULL) {
3029 n++;
3030 p++;
3031 }
3032 v = PyList_New(n);
3033 if (v == NULL)
3034 return NULL;
3035 for (i = 0; ; i++) {
3036 p = wcschr(path, delim);
3037 if (p == NULL)
3038 p = path + wcslen(path); /* End of string */
3039 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3040 if (w == NULL) {
3041 Py_DECREF(v);
3042 return NULL;
3043 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003044 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003045 if (*p == '\0')
3046 break;
3047 path = p+1;
3048 }
3049 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003050}
3051
3052void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003053PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003055 PyObject *v;
3056 if ((v = makepathobject(path, DELIM)) == NULL)
3057 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003058 PyThreadState *tstate = _PyThreadState_GET();
3059 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003060 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003061 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003062 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003063}
3064
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003065static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003066make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003067{
Victor Stinner74f65682019-03-15 15:08:05 +01003068 PyObject *list = PyList_New(argc);
3069 if (list == NULL) {
3070 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 }
Victor Stinner74f65682019-03-15 15:08:05 +01003072
3073 for (Py_ssize_t i = 0; i < argc; i++) {
3074 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3075 if (v == NULL) {
3076 Py_DECREF(list);
3077 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 }
Victor Stinner74f65682019-03-15 15:08:05 +01003079 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 }
Victor Stinner74f65682019-03-15 15:08:05 +01003081 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003082}
3083
Victor Stinner11a247d2017-12-13 21:05:57 +01003084void
3085PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003086{
Victor Stinnerc4868252019-08-23 11:04:16 +01003087 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003088 PyThreadState *tstate = _PyThreadState_GET();
3089
Victor Stinner74f65682019-03-15 15:08:05 +01003090 if (argc < 1 || argv == NULL) {
3091 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003092 argv = empty_argv;
3093 argc = 1;
3094 }
3095
3096 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003097 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003098 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003099 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02003100 if (sys_set_object_str(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003101 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003102 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003103 }
3104 Py_DECREF(av);
3105
3106 if (updatepath) {
3107 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3108 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003109 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003110 PyObject *path0 = NULL;
3111 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3112 if (path0 == NULL) {
3113 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003114 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003115
Victor Stinner838f2642019-06-13 22:41:23 +02003116 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003117 if (sys_path != NULL) {
3118 if (PyList_Insert(sys_path, 0, path0) < 0) {
3119 Py_DECREF(path0);
3120 Py_FatalError("can't prepend path0 to sys.path");
3121 }
3122 }
3123 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003124 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003125 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003126}
Guido van Rossuma890e681998-05-12 14:59:24 +00003127
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003128void
3129PySys_SetArgv(int argc, wchar_t **argv)
3130{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003131 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003132}
3133
Victor Stinner14284c22010-04-23 12:02:30 +00003134/* Reimplementation of PyFile_WriteString() no calling indirectly
3135 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3136
3137static int
Victor Stinner79766632010-08-16 17:36:42 +00003138sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003139{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003140 if (file == NULL)
3141 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003142 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003143 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003144 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003145 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003146 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003147 Py_DECREF(result);
3148 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003149}
3150
Victor Stinner79766632010-08-16 17:36:42 +00003151static int
3152sys_pyfile_write(const char *text, PyObject *file)
3153{
3154 PyObject *unicode = NULL;
3155 int err;
3156
3157 if (file == NULL)
3158 return -1;
3159
3160 unicode = PyUnicode_FromString(text);
3161 if (unicode == NULL)
3162 return -1;
3163
3164 err = sys_pyfile_write_unicode(unicode, file);
3165 Py_DECREF(unicode);
3166 return err;
3167}
Guido van Rossuma890e681998-05-12 14:59:24 +00003168
3169/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3170 Adapted from code submitted by Just van Rossum.
3171
3172 PySys_WriteStdout(format, ...)
3173 PySys_WriteStderr(format, ...)
3174
3175 The first function writes to sys.stdout; the second to sys.stderr. When
3176 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003177 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003178
Victor Stinner14284c22010-04-23 12:02:30 +00003179 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003180 signal handlers: they may raise a new exception whereas sys_write()
3181 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003182
Guido van Rossuma890e681998-05-12 14:59:24 +00003183 Both take a printf-style format string as their first argument followed
3184 by a variable length argument list determined by the format string.
3185
3186 *** WARNING ***
3187
3188 The format should limit the total size of the formatted output string to
3189 1000 bytes. In particular, this means that no unrestricted "%s" formats
3190 should occur; these should be limited using "%.<N>s where <N> is a
3191 decimal number calculated so that <N> plus the maximum size of other
3192 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3193 which can print hundreds of digits for very large numbers.
3194
3195 */
3196
3197static void
Victor Stinner09054372013-11-06 22:41:44 +01003198sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 PyObject *file;
3201 PyObject *error_type, *error_value, *error_traceback;
3202 char buffer[1001];
3203 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003204 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003205
Victor Stinner838f2642019-06-13 22:41:23 +02003206 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3207 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3209 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003210 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 fputs(buffer, fp);
3212 }
3213 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3214 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003215 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003217 }
Victor Stinner838f2642019-06-13 22:41:23 +02003218 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003219}
3220
3221void
Guido van Rossuma890e681998-05-12 14:59:24 +00003222PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003226 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003227 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003228 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003229}
3230
3231void
Guido van Rossuma890e681998-05-12 14:59:24 +00003232PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003234 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003236 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003237 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003238 va_end(va);
3239}
3240
3241static void
Victor Stinner09054372013-11-06 22:41:44 +01003242sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003243{
3244 PyObject *file, *message;
3245 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003246 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003247 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003248
Victor Stinner838f2642019-06-13 22:41:23 +02003249 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3250 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003251 message = PyUnicode_FromFormatV(format, va);
3252 if (message != NULL) {
3253 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003254 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003255 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003256 if (utf8 != NULL)
3257 fputs(utf8, fp);
3258 }
3259 Py_DECREF(message);
3260 }
Victor Stinner838f2642019-06-13 22:41:23 +02003261 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003262}
3263
3264void
3265PySys_FormatStdout(const char *format, ...)
3266{
3267 va_list va;
3268
3269 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003270 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003271 va_end(va);
3272}
3273
3274void
3275PySys_FormatStderr(const char *format, ...)
3276{
3277 va_list va;
3278
3279 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003280 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003282}