blob: 945e639ca57560097b15c178bfa6dc70d1737b31 [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]
Julien Danjou64366fa2020-11-02 15:16:25 +01001841sys._current_exceptions
1842
1843Return a dict mapping each thread's identifier to its current raised exception.
1844
1845This function should be used for specialized purposes only.
1846[clinic start generated code]*/
1847
1848static PyObject *
1849sys__current_exceptions_impl(PyObject *module)
1850/*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
1851{
1852 return _PyThread_CurrentExceptions();
1853}
1854
1855/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +02001856sys.call_tracing
1857
1858 func: object
1859 args as funcargs: object(subclass_of='&PyTuple_Type')
1860 /
1861
1862Call func(*args), while tracing is enabled.
1863
1864The tracing state is saved, and restored afterwards. This is intended
1865to be called from a debugger from a checkpoint, to recursively debug
1866some other code.
1867[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001868
1869static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001870sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1871/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001872{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001874}
1875
Victor Stinner048afd92016-11-28 11:59:04 +01001876
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001877#ifdef __cplusplus
1878extern "C" {
1879#endif
1880
Tal Einatede0b6f2018-12-31 17:12:08 +02001881/*[clinic input]
1882sys._debugmallocstats
1883
1884Print summary info to stderr about the state of pymalloc's structures.
1885
1886In Py_DEBUG mode, also perform some expensive internal consistency
1887checks.
1888[clinic start generated code]*/
1889
David Malcolm49526f42012-06-22 14:55:41 -04001890static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001891sys__debugmallocstats_impl(PyObject *module)
1892/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001893{
1894#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001895 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001896 fputc('\n', stderr);
1897 }
David Malcolm49526f42012-06-22 14:55:41 -04001898#endif
1899 _PyObject_DebugTypeStats(stderr);
1900
1901 Py_RETURN_NONE;
1902}
David Malcolm49526f42012-06-22 14:55:41 -04001903
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001904#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001905/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001906extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001907#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001908
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001909#ifdef DYNAMIC_EXECUTION_PROFILE
1910/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001911extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001912#endif
1913
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001914#ifdef __cplusplus
1915}
1916#endif
1917
Tal Einatede0b6f2018-12-31 17:12:08 +02001918
1919/*[clinic input]
1920sys._clear_type_cache
1921
1922Clear the internal type lookup cache.
1923[clinic start generated code]*/
1924
Christian Heimes15ebc882008-02-04 18:48:49 +00001925static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001926sys__clear_type_cache_impl(PyObject *module)
1927/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001928{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001929 PyType_ClearCache();
1930 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001931}
1932
Tal Einatede0b6f2018-12-31 17:12:08 +02001933/*[clinic input]
1934sys.is_finalizing
1935
1936Return True if Python is exiting.
1937[clinic start generated code]*/
1938
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001939static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001940sys_is_finalizing_impl(PyObject *module)
1941/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001942{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001943 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001944}
1945
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001946#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001947/*[clinic input]
1948sys.getandroidapilevel
1949
1950Return the build time API version of Android as an integer.
1951[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001952
1953static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001954sys_getandroidapilevel_impl(PyObject *module)
1955/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001956{
1957 return PyLong_FromLong(ANDROID_API_LEVEL);
1958}
1959#endif /* ANDROID_API_LEVEL */
1960
1961
Steve Dowerb82e17e2019-05-23 08:45:22 -07001962
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001963static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001965 SYS_ADDAUDITHOOK_METHODDEF
1966 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001967 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001968 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001969 SYS__CLEAR_TYPE_CACHE_METHODDEF
1970 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001971 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001972 SYS_DISPLAYHOOK_METHODDEF
1973 SYS_EXC_INFO_METHODDEF
1974 SYS_EXCEPTHOOK_METHODDEF
1975 SYS_EXIT_METHODDEF
1976 SYS_GETDEFAULTENCODING_METHODDEF
1977 SYS_GETDLOPENFLAGS_METHODDEF
1978 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001979#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001981#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001982 SYS_GETFILESYSTEMENCODING_METHODDEF
1983 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001984#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001986#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001987 SYS_GETTOTALREFCOUNT_METHODDEF
1988 SYS_GETREFCOUNT_METHODDEF
1989 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001990 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001992 SYS__GETFRAME_METHODDEF
1993 SYS_GETWINDOWSVERSION_METHODDEF
1994 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1995 SYS_INTERN_METHODDEF
1996 SYS_IS_FINALIZING_METHODDEF
1997 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001998 SYS_SETSWITCHINTERVAL_METHODDEF
1999 SYS_GETSWITCHINTERVAL_METHODDEF
2000 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002002 SYS_GETPROFILE_METHODDEF
2003 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002005 SYS_GETTRACE_METHODDEF
2006 SYS_CALL_TRACING_METHODDEF
2007 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002008 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2009 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002010 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002011 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002012 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2013 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002014 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002016};
2017
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002018static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002019list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 PyObject *list = PyList_New(0);
2022 int i;
2023 if (list == NULL)
2024 return NULL;
2025 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2026 PyObject *name = PyUnicode_FromString(
2027 PyImport_Inittab[i].name);
2028 if (name == NULL)
2029 break;
2030 PyList_Append(list, name);
2031 Py_DECREF(name);
2032 }
2033 if (PyList_Sort(list) != 0) {
2034 Py_DECREF(list);
2035 list = NULL;
2036 }
2037 if (list) {
2038 PyObject *v = PyList_AsTuple(list);
2039 Py_DECREF(list);
2040 list = v;
2041 }
2042 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002043}
2044
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002045/* Pre-initialization support for sys.warnoptions and sys._xoptions
2046 *
2047 * Modern internal code paths:
2048 * These APIs get called after _Py_InitializeCore and get to use the
2049 * regular CPython list, dict, and unicode APIs.
2050 *
2051 * Legacy embedding code paths:
2052 * The multi-phase initialization API isn't public yet, so embedding
2053 * apps still need to be able configure sys.warnoptions and sys._xoptions
2054 * before they call Py_Initialize. To support this, we stash copies of
2055 * the supplied wchar * sequences in linked lists, and then migrate the
2056 * contents of those lists to the sys module in _PyInitializeCore.
2057 *
2058 */
2059
2060struct _preinit_entry {
2061 wchar_t *value;
2062 struct _preinit_entry *next;
2063};
2064
2065typedef struct _preinit_entry *_Py_PreInitEntry;
2066
2067static _Py_PreInitEntry _preinit_warnoptions = NULL;
2068static _Py_PreInitEntry _preinit_xoptions = NULL;
2069
2070static _Py_PreInitEntry
2071_alloc_preinit_entry(const wchar_t *value)
2072{
2073 /* To get this to work, we have to initialize the runtime implicitly */
2074 _PyRuntime_Initialize();
2075
2076 /* Force default allocator, so we can ensure that it also gets used to
2077 * destroy the linked list in _clear_preinit_entries.
2078 */
2079 PyMemAllocatorEx old_alloc;
2080 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2081
2082 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2083 if (node != NULL) {
2084 node->value = _PyMem_RawWcsdup(value);
2085 if (node->value == NULL) {
2086 PyMem_RawFree(node);
2087 node = NULL;
2088 };
2089 };
2090
2091 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2092 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002093}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002094
2095static int
2096_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2097{
2098 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2099 if (new_entry == NULL) {
2100 return -1;
2101 }
2102 /* We maintain the linked list in this order so it's easy to play back
2103 * the add commands in the same order later on in _Py_InitializeCore
2104 */
2105 _Py_PreInitEntry last_entry = *optionlist;
2106 if (last_entry == NULL) {
2107 *optionlist = new_entry;
2108 } else {
2109 while (last_entry->next != NULL) {
2110 last_entry = last_entry->next;
2111 }
2112 last_entry->next = new_entry;
2113 }
2114 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002115}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002116
2117static void
2118_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2119{
2120 _Py_PreInitEntry current = *optionlist;
2121 *optionlist = NULL;
2122 /* Deallocate the nodes and their contents using the default allocator */
2123 PyMemAllocatorEx old_alloc;
2124 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2125 while (current != NULL) {
2126 _Py_PreInitEntry next = current->next;
2127 PyMem_RawFree(current->value);
2128 PyMem_RawFree(current);
2129 current = next;
2130 }
2131 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002132}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002133
Victor Stinner120b7072019-08-23 18:03:08 +01002134
2135PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002136_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002137{
Victor Stinner120b7072019-08-23 18:03:08 +01002138 PyStatus status;
2139 _Py_PreInitEntry entry;
2140
2141 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002142 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002143 if (_PyStatus_EXCEPTION(status)) {
2144 return status;
2145 }
2146 }
2147
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002148 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002149 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002150}
2151
Victor Stinner120b7072019-08-23 18:03:08 +01002152
2153PyStatus
2154_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002155{
Victor Stinner120b7072019-08-23 18:03:08 +01002156 PyStatus status;
2157 _Py_PreInitEntry entry;
2158
2159 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2160 status = PyWideStringList_Append(&config->xoptions, entry->value);
2161 if (_PyStatus_EXCEPTION(status)) {
2162 return status;
2163 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002164 }
2165
Victor Stinner120b7072019-08-23 18:03:08 +01002166 _clear_preinit_entries(&_preinit_xoptions);
2167 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002168}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002169
Victor Stinner120b7072019-08-23 18:03:08 +01002170
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002171static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002172get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002173{
Victor Stinner838f2642019-06-13 22:41:23 +02002174 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002175 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002176 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2177 * interpreter config. When that happens, we need to properly set
2178 * the `warnoptions` reference in the main interpreter config as well.
2179 *
2180 * For Python 3.7, we shouldn't be able to get here due to the
2181 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2182 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2183 * call optional for embedding applications, thus making this
2184 * reachable again.
2185 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002186 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002187 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002188 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002189 }
2190 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002191 Py_DECREF(warnoptions);
2192 return NULL;
2193 }
2194 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002195 }
2196 return warnoptions;
2197}
Guido van Rossum23fff912000-12-15 22:02:05 +00002198
2199void
2200PySys_ResetWarnOptions(void)
2201{
Victor Stinner50b48572018-11-01 01:51:40 +01002202 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002203 if (tstate == NULL) {
2204 _clear_preinit_entries(&_preinit_warnoptions);
2205 return;
2206 }
2207
Victor Stinner838f2642019-06-13 22:41:23 +02002208 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 if (warnoptions == NULL || !PyList_Check(warnoptions))
2210 return;
2211 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002212}
2213
Victor Stinnere1b29952018-10-30 14:31:42 +01002214static int
Victor Stinner838f2642019-06-13 22:41:23 +02002215_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002216{
Victor Stinner838f2642019-06-13 22:41:23 +02002217 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002218 if (warnoptions == NULL) {
2219 return -1;
2220 }
2221 if (PyList_Append(warnoptions, option)) {
2222 return -1;
2223 }
2224 return 0;
2225}
2226
2227void
2228PySys_AddWarnOptionUnicode(PyObject *option)
2229{
Victor Stinner838f2642019-06-13 22:41:23 +02002230 PyThreadState *tstate = _PyThreadState_GET();
2231 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002232 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002233 if (tstate) {
2234 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002235 }
2236 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002237}
2238
2239void
2240PySys_AddWarnOption(const wchar_t *s)
2241{
Victor Stinner50b48572018-11-01 01:51:40 +01002242 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002243 if (tstate == NULL) {
2244 _append_preinit_entry(&_preinit_warnoptions, s);
2245 return;
2246 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002247 PyObject *unicode;
2248 unicode = PyUnicode_FromWideChar(s, -1);
2249 if (unicode == NULL)
2250 return;
2251 PySys_AddWarnOptionUnicode(unicode);
2252 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002253}
2254
Christian Heimes33fe8092008-04-13 13:53:33 +00002255int
2256PySys_HasWarnOptions(void)
2257{
Victor Stinner838f2642019-06-13 22:41:23 +02002258 PyThreadState *tstate = _PyThreadState_GET();
2259 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002260 return (warnoptions != NULL && PyList_Check(warnoptions)
2261 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002262}
2263
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002264static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002265get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002266{
Victor Stinner838f2642019-06-13 22:41:23 +02002267 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002268 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002269 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2270 * interpreter config. When that happens, we need to properly set
2271 * the `xoptions` reference in the main interpreter config as well.
2272 *
2273 * For Python 3.7, we shouldn't be able to get here due to the
2274 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2275 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2276 * call optional for embedding applications, thus making this
2277 * reachable again.
2278 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002279 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002280 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002281 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002282 }
2283 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002284 Py_DECREF(xoptions);
2285 return NULL;
2286 }
2287 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002288 }
2289 return xoptions;
2290}
2291
Victor Stinnere1b29952018-10-30 14:31:42 +01002292static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002294{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002295 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002296
Victor Stinner838f2642019-06-13 22:41:23 +02002297 PyThreadState *tstate = _PyThreadState_GET();
2298 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002299 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002300 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002301 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002302
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002303 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002304 if (!name_end) {
2305 name = PyUnicode_FromWideChar(s, -1);
2306 value = Py_True;
2307 Py_INCREF(value);
2308 }
2309 else {
2310 name = PyUnicode_FromWideChar(s, name_end - s);
2311 value = PyUnicode_FromWideChar(name_end + 1, -1);
2312 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002313 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002314 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002315 }
2316 if (PyDict_SetItem(opts, name, value) < 0) {
2317 goto error;
2318 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002319 Py_DECREF(name);
2320 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002321 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002322
2323error:
2324 Py_XDECREF(name);
2325 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002326 return -1;
2327}
2328
2329void
2330PySys_AddXOption(const wchar_t *s)
2331{
Victor Stinner50b48572018-11-01 01:51:40 +01002332 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002333 if (tstate == NULL) {
2334 _append_preinit_entry(&_preinit_xoptions, s);
2335 return;
2336 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002337 if (_PySys_AddXOptionWithError(s) < 0) {
2338 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002339 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002340 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002341}
2342
2343PyObject *
2344PySys_GetXOptions(void)
2345{
Victor Stinner838f2642019-06-13 22:41:23 +02002346 PyThreadState *tstate = _PyThreadState_GET();
2347 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002348}
2349
Guido van Rossum40552d01998-08-06 03:34:39 +00002350/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2351 Two literals concatenated works just fine. If you have a K&R compiler
2352 or other abomination that however *does* understand longer strings,
2353 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002354PyDoc_VAR(sys_doc) =
2355PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002356"This module provides access to some objects used or maintained by the\n\
2357interpreter and to functions that interact strongly with the interpreter.\n\
2358\n\
2359Dynamic objects:\n\
2360\n\
2361argv -- command line arguments; argv[0] is the script pathname if known\n\
2362path -- module search path; path[0] is the script directory, else ''\n\
2363modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002364\n\
2365displayhook -- called to show results in an interactive session\n\
2366excepthook -- called to handle any uncaught exception other than SystemExit\n\
2367 To customize printing in an interactive session or to install a custom\n\
2368 top-level exception handler, assign other functions to replace these.\n\
2369\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002370stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002371stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002372stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002373 By assigning other file objects (or objects that behave like files)\n\
2374 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002375\n\
2376last_type -- type of last uncaught exception\n\
2377last_value -- value of last uncaught exception\n\
2378last_traceback -- traceback of last uncaught exception\n\
2379 These three are only available in an interactive session after a\n\
2380 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002381"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002382)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002383/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002384PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002385"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002386Static objects:\n\
2387\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002388builtin_module_names -- tuple of module names built into this interpreter\n\
2389copyright -- copyright notice pertaining to this interpreter\n\
2390exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002391executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002392float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002393float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002394hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002395hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002396implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002397int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002398maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002399maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002400platform -- platform identifier\n\
2401prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002402thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002403version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002404version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002405"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002406)
Steve Dowercc16be82016-09-08 10:35:16 -07002407#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002408/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002409PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002410"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002411winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002412"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002413)
Steve Dowercc16be82016-09-08 10:35:16 -07002414#endif /* MS_COREDLL */
2415#ifdef MS_WINDOWS
2416/* concatenating string here */
2417PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002418"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002419"
2420)
2421#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002422PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002423"__stdin__ -- the original stdin; don't touch!\n\
2424__stdout__ -- the original stdout; don't touch!\n\
2425__stderr__ -- the original stderr; don't touch!\n\
2426__displayhook__ -- the original displayhook; don't touch!\n\
2427__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002428\n\
2429Functions:\n\
2430\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002431displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002432excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002433exc_info() -- return thread-safe information about the current exception\n\
2434exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002435getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002436getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002437getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002438getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002439getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002440gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002441setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002442setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002443setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002444settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002445"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002446)
Fred Drakeccede592000-08-14 20:59:57 +00002447/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002448
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002449
2450PyDoc_STRVAR(flags__doc__,
2451"sys.flags\n\
2452\n\
2453Flags provided through command line arguments or environment vars.");
2454
2455static PyTypeObject FlagsType;
2456
2457static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002459 {"inspect", "-i"},
2460 {"interactive", "-i"},
2461 {"optimize", "-O or -OO"},
2462 {"dont_write_bytecode", "-B"},
2463 {"no_user_site", "-s"},
2464 {"no_site", "-S"},
2465 {"ignore_environment", "-E"},
2466 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 /* {"unbuffered", "-u"}, */
2468 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002469 {"bytes_warning", "-b"},
2470 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002471 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002472 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002473 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002474 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002476};
2477
2478static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002479 "sys.flags", /* name */
2480 flags__doc__, /* doc */
2481 flags_fields, /* fields */
Victor Stinner1def7752020-04-23 03:03:24 +02002482 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002483};
2484
2485static PyObject*
Victor Stinner01b1cc12019-11-20 02:27:56 +01002486make_flags(PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002487{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002488 PyInterpreterState *interp = tstate->interp;
2489 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002490 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002491
Victor Stinner01b1cc12019-11-20 02:27:56 +01002492 PyObject *seq = PyStructSequence_New(&FlagsType);
2493 if (seq == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 return NULL;
Victor Stinner01b1cc12019-11-20 02:27:56 +01002495 }
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002496
Victor Stinner01b1cc12019-11-20 02:27:56 +01002497 int pos = 0;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002498#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002500
Victor Stinnerfbca9082018-08-30 00:50:45 +02002501 SetFlag(config->parser_debug);
2502 SetFlag(config->inspect);
2503 SetFlag(config->interactive);
2504 SetFlag(config->optimization_level);
2505 SetFlag(!config->write_bytecode);
2506 SetFlag(!config->user_site_directory);
2507 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002508 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002509 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 /* SetFlag(saw_unbuffered_flag); */
2511 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002512 SetFlag(config->bytes_warning);
2513 SetFlag(config->quiet);
2514 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002515 SetFlag(config->isolated);
2516 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2517 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002518#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002519
Victor Stinner838f2642019-06-13 22:41:23 +02002520 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002521 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 return NULL;
2523 }
2524 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002525}
2526
Eric Smith0e5b5622009-02-06 01:32:42 +00002527PyDoc_STRVAR(version_info__doc__,
2528"sys.version_info\n\
2529\n\
2530Version information as a named tuple.");
2531
2532static PyTypeObject VersionInfoType;
2533
2534static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 {"major", "Major release number"},
2536 {"minor", "Minor release number"},
2537 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002538 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 {"serial", "Serial release number"},
2540 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002541};
2542
2543static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 "sys.version_info", /* name */
2545 version_info__doc__, /* doc */
2546 version_info_fields, /* fields */
2547 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002548};
2549
2550static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002551make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 PyObject *version_info;
2554 char *s;
2555 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 version_info = PyStructSequence_New(&VersionInfoType);
2558 if (version_info == NULL) {
2559 return NULL;
2560 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 /*
2563 * These release level checks are mutually exclusive and cover
2564 * the field, so don't get too fancy with the pre-processor!
2565 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002566#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002568#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002570#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002572#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002574#endif
2575
2576#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002578#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 SetIntItem(PY_MAJOR_VERSION);
2582 SetIntItem(PY_MINOR_VERSION);
2583 SetIntItem(PY_MICRO_VERSION);
2584 SetStrItem(s);
2585 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002586#undef SetIntItem
2587#undef SetStrItem
2588
Victor Stinner838f2642019-06-13 22:41:23 +02002589 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 Py_CLEAR(version_info);
2591 return NULL;
2592 }
2593 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002594}
2595
Brett Cannon3adc7b72012-07-09 14:22:12 -04002596/* sys.implementation values */
2597#define NAME "cpython"
2598const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002599#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2600#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002601#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002602const char *_PySys_ImplCacheTag = TAG;
2603#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002604#undef MAJOR
2605#undef MINOR
2606#undef TAG
2607
Barry Warsaw409da152012-06-03 16:18:47 -04002608static PyObject *
2609make_impl_info(PyObject *version_info)
2610{
2611 int res;
2612 PyObject *impl_info, *value, *ns;
2613
2614 impl_info = PyDict_New();
2615 if (impl_info == NULL)
2616 return NULL;
2617
2618 /* populate the dict */
2619
Brett Cannon3adc7b72012-07-09 14:22:12 -04002620 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002621 if (value == NULL)
2622 goto error;
2623 res = PyDict_SetItemString(impl_info, "name", value);
2624 Py_DECREF(value);
2625 if (res < 0)
2626 goto error;
2627
Brett Cannon3adc7b72012-07-09 14:22:12 -04002628 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002629 if (value == NULL)
2630 goto error;
2631 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2632 Py_DECREF(value);
2633 if (res < 0)
2634 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002635
2636 res = PyDict_SetItemString(impl_info, "version", version_info);
2637 if (res < 0)
2638 goto error;
2639
2640 value = PyLong_FromLong(PY_VERSION_HEX);
2641 if (value == NULL)
2642 goto error;
2643 res = PyDict_SetItemString(impl_info, "hexversion", value);
2644 Py_DECREF(value);
2645 if (res < 0)
2646 goto error;
2647
doko@ubuntu.com55532312016-06-14 08:55:19 +02002648#ifdef MULTIARCH
2649 value = PyUnicode_FromString(MULTIARCH);
2650 if (value == NULL)
2651 goto error;
2652 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2653 Py_DECREF(value);
2654 if (res < 0)
2655 goto error;
2656#endif
2657
Barry Warsaw409da152012-06-03 16:18:47 -04002658 /* dict ready */
2659
2660 ns = _PyNamespace_New(impl_info);
2661 Py_DECREF(impl_info);
2662 return ns;
2663
2664error:
2665 Py_CLEAR(impl_info);
2666 return NULL;
2667}
2668
Martin v. Löwis1a214512008-06-11 05:26:20 +00002669static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 PyModuleDef_HEAD_INIT,
2671 "sys",
2672 sys_doc,
2673 -1, /* multiple "initialization" just copies the module dict. */
2674 sys_methods,
2675 NULL,
2676 NULL,
2677 NULL,
2678 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002679};
2680
Eric Snow6b4be192017-05-22 21:36:03 -07002681/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002682#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002683 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002684 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002685 if (v == NULL) { \
2686 goto err_occurred; \
2687 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002688 res = PyDict_SetItemString(sysdict, key, v); \
2689 Py_DECREF(v); \
2690 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002691 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002692 } \
2693 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002694
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002695#define SET_SYS_FROM_STRING(key, value) \
2696 SET_SYS(key, PyUnicode_FromString(value))
2697
Victor Stinner331a6a52019-05-27 16:39:22 +02002698static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002699_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002700{
Victor Stinnerab672812019-01-23 15:04:40 +01002701 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002702 int res;
2703
Nick Coghland6009512014-11-20 21:39:37 +10002704 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002705
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002706#define COPY_SYS_ATTR(tokey, fromkey) \
2707 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002708
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002709 COPY_SYS_ATTR("__displayhook__", "displayhook");
2710 COPY_SYS_ATTR("__excepthook__", "excepthook");
2711 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2712 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2713
2714#undef COPY_SYS_ATTR
2715
2716 SET_SYS_FROM_STRING("version", Py_GetVersion());
2717 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2718 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2719 _Py_gitversion()));
2720 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2721 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2722 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2723 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2724 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2725 SET_SYS("float_info", PyFloat_GetInfo());
2726 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002727 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002728 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002729 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2730 goto type_init_failed;
2731 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002732 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002733 SET_SYS("hash_info", get_hash_info(tstate));
2734 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2735 SET_SYS("builtin_module_names", list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002736#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002737 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002738#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002739 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002740#endif
Fred Drake099325e2000-08-14 15:47:03 +00002741
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002742#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002743 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2744 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002745#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002746#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002747 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002748#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002751 if (VersionInfoType.tp_name == NULL) {
2752 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002753 &version_info_desc) < 0) {
2754 goto type_init_failed;
2755 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002756 }
Victor Stinner838f2642019-06-13 22:41:23 +02002757 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002758 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 /* prevent user from creating new instances */
2760 VersionInfoType.tp_init = NULL;
2761 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002762 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002763 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2764 _PyErr_Clear(tstate);
2765 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002766
Barry Warsaw409da152012-06-03 16:18:47 -04002767 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002768 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002771 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002772 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2773 goto type_init_failed;
2774 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002775 }
Victor Stinner43125222019-04-24 18:23:53 +02002776 /* Set flags to their default values (updated by _PySys_InitMain()) */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002777 SET_SYS("flags", make_flags(tstate));
Eric Smithf7bb5782010-01-27 00:44:57 +00002778
2779#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 /* getwindowsversion */
2781 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002782 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002783 &windows_version_desc) < 0) {
2784 goto type_init_failed;
2785 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 /* prevent user from creating new instances */
2787 WindowsVersionType.tp_init = NULL;
2788 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002789 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002790 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002791 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2792 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002793 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002794#endif
2795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002797#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002798 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002799#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002800 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002801#endif
2802
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002803 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002804
Yury Selivanoveb636452016-09-08 22:01:51 -07002805 /* initialize asyncgen_hooks */
2806 if (AsyncGenHooksType.tp_name == NULL) {
2807 if (PyStructSequence_InitType2(
2808 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002809 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002810 }
2811 }
2812
Victor Stinner838f2642019-06-13 22:41:23 +02002813 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002814 goto err_occurred;
2815 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002816 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002817
2818type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002819 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002820
2821err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002822 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002823}
2824
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002825static int
2826sys_add_xoption(PyObject *opts, const wchar_t *s)
2827{
2828 PyObject *name, *value;
2829
2830 const wchar_t *name_end = wcschr(s, L'=');
2831 if (!name_end) {
2832 name = PyUnicode_FromWideChar(s, -1);
2833 value = Py_True;
2834 Py_INCREF(value);
2835 }
2836 else {
2837 name = PyUnicode_FromWideChar(s, name_end - s);
2838 value = PyUnicode_FromWideChar(name_end + 1, -1);
2839 }
2840 if (name == NULL || value == NULL) {
2841 goto error;
2842 }
2843 if (PyDict_SetItem(opts, name, value) < 0) {
2844 goto error;
2845 }
2846 Py_DECREF(name);
2847 Py_DECREF(value);
2848 return 0;
2849
2850error:
2851 Py_XDECREF(name);
2852 Py_XDECREF(value);
2853 return -1;
2854}
2855
2856
2857static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002858sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002859{
2860 Py_ssize_t nxoption = config->xoptions.length;
2861 wchar_t * const * xoptions = config->xoptions.items;
2862 PyObject *dict = PyDict_New();
2863 if (dict == NULL) {
2864 return NULL;
2865 }
2866
2867 for (Py_ssize_t i=0; i < nxoption; i++) {
2868 const wchar_t *option = xoptions[i];
2869 if (sys_add_xoption(dict, option) < 0) {
2870 Py_DECREF(dict);
2871 return NULL;
2872 }
2873 }
2874
2875 return dict;
2876}
2877
2878
Eric Snow6b4be192017-05-22 21:36:03 -07002879int
Victor Stinner01b1cc12019-11-20 02:27:56 +01002880_PySys_InitMain(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002881{
Victor Stinner838f2642019-06-13 22:41:23 +02002882 PyObject *sysdict = tstate->interp->sysdict;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002883 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002884 int res;
2885
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002886#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002887 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002888
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002889#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002890 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002891
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002892 COPY_LIST("path", config->module_search_paths);
2893
2894 SET_SYS_FROM_WSTR("executable", config->executable);
Steve Dower9048c492019-06-29 10:34:11 -07002895 SET_SYS_FROM_WSTR("_base_executable", config->base_executable);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002896 SET_SYS_FROM_WSTR("prefix", config->prefix);
2897 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2898 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2899 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Sandro Mani8f023a22020-06-08 17:28:11 +02002900 SET_SYS_FROM_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002901
Carl Meyerb193fa92018-06-15 22:40:56 -06002902 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002903 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002904 } else {
2905 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2906 }
2907
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002908 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002909 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002910 COPY_LIST("warnoptions", config->warnoptions);
2911
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002912 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002913
Victor Stinner37cd9822018-11-16 11:55:35 +01002914#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002915#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002916
Victor Stinner8510f432020-03-10 09:53:09 +01002917
Eric Snow6b4be192017-05-22 21:36:03 -07002918 /* Set flags to their final values */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002919 SET_SYS("flags", make_flags(tstate));
Eric Snow6b4be192017-05-22 21:36:03 -07002920 /* prevent user from creating new instances */
2921 FlagsType.tp_init = NULL;
2922 FlagsType.tp_new = NULL;
2923 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2924 if (res < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02002925 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
Eric Snow6b4be192017-05-22 21:36:03 -07002926 return res;
2927 }
Victor Stinner838f2642019-06-13 22:41:23 +02002928 _PyErr_Clear(tstate);
Eric Snow6b4be192017-05-22 21:36:03 -07002929 }
2930
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002931 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002932
Victor Stinner838f2642019-06-13 22:41:23 +02002933 if (get_warnoptions(tstate) == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002934 return -1;
Victor Stinner838f2642019-06-13 22:41:23 +02002935 }
Victor Stinner865de272017-06-08 13:27:47 +02002936
Victor Stinner838f2642019-06-13 22:41:23 +02002937 if (get_xoptions(tstate) == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002938 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002939
Victor Stinner838f2642019-06-13 22:41:23 +02002940 if (_PyErr_Occurred(tstate)) {
2941 goto err_occurred;
2942 }
2943
Eric Snow6b4be192017-05-22 21:36:03 -07002944 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002945
2946err_occurred:
2947 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002948}
2949
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002950#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01002951#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002952
Victor Stinnerab672812019-01-23 15:04:40 +01002953
2954/* Set up a preliminary stderr printer until we have enough
2955 infrastructure for the io module in place.
2956
2957 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002958static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002959_PySys_SetPreliminaryStderr(PyObject *sysdict)
2960{
2961 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2962 if (pstderr == NULL) {
2963 goto error;
2964 }
2965 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2966 goto error;
2967 }
2968 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2969 goto error;
2970 }
2971 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002972 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01002973
2974error:
2975 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02002976 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01002977}
2978
2979
2980/* Create sys module without all attributes: _PySys_InitMain() should be called
2981 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002982PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002983_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002984{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002985 assert(!_PyErr_Occurred(tstate));
2986
Victor Stinnerb45d2592019-06-20 00:05:23 +02002987 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02002988
Victor Stinnerab672812019-01-23 15:04:40 +01002989 PyObject *modules = PyDict_New();
2990 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002991 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01002992 }
2993 interp->modules = modules;
2994
2995 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2996 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02002997 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01002998 }
2999
3000 PyObject *sysdict = PyModule_GetDict(sysmod);
3001 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003002 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003003 }
3004 Py_INCREF(sysdict);
3005 interp->sysdict = sysdict;
3006
3007 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003008 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003009 }
3010
Victor Stinner331a6a52019-05-27 16:39:22 +02003011 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3012 if (_PyStatus_EXCEPTION(status)) {
3013 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003014 }
3015
Victor Stinner01b1cc12019-11-20 02:27:56 +01003016 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003017 if (_PyStatus_EXCEPTION(status)) {
3018 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003019 }
3020
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003021 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3022 goto error;
3023 }
3024
3025 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003026
3027 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003028 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003029
3030error:
3031 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003032}
3033
3034
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003035static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003036makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003038 int i, n;
3039 const wchar_t *p;
3040 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003041
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003042 n = 1;
3043 p = path;
3044 while ((p = wcschr(p, delim)) != NULL) {
3045 n++;
3046 p++;
3047 }
3048 v = PyList_New(n);
3049 if (v == NULL)
3050 return NULL;
3051 for (i = 0; ; i++) {
3052 p = wcschr(path, delim);
3053 if (p == NULL)
3054 p = path + wcslen(path); /* End of string */
3055 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3056 if (w == NULL) {
3057 Py_DECREF(v);
3058 return NULL;
3059 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003060 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003061 if (*p == '\0')
3062 break;
3063 path = p+1;
3064 }
3065 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003066}
3067
3068void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003069PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 PyObject *v;
3072 if ((v = makepathobject(path, DELIM)) == NULL)
3073 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003074 PyThreadState *tstate = _PyThreadState_GET();
3075 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003077 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003078 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003079}
3080
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003081static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003082make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003083{
Victor Stinner74f65682019-03-15 15:08:05 +01003084 PyObject *list = PyList_New(argc);
3085 if (list == NULL) {
3086 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003087 }
Victor Stinner74f65682019-03-15 15:08:05 +01003088
3089 for (Py_ssize_t i = 0; i < argc; i++) {
3090 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3091 if (v == NULL) {
3092 Py_DECREF(list);
3093 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003094 }
Victor Stinner74f65682019-03-15 15:08:05 +01003095 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003096 }
Victor Stinner74f65682019-03-15 15:08:05 +01003097 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003098}
3099
Victor Stinner11a247d2017-12-13 21:05:57 +01003100void
3101PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003102{
Victor Stinnerc4868252019-08-23 11:04:16 +01003103 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003104 PyThreadState *tstate = _PyThreadState_GET();
3105
Victor Stinner74f65682019-03-15 15:08:05 +01003106 if (argc < 1 || argv == NULL) {
3107 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003108 argv = empty_argv;
3109 argc = 1;
3110 }
3111
3112 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003113 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003114 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003115 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02003116 if (sys_set_object_str(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003117 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003118 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003119 }
3120 Py_DECREF(av);
3121
3122 if (updatepath) {
3123 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3124 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003125 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003126 PyObject *path0 = NULL;
3127 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3128 if (path0 == NULL) {
3129 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003130 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003131
Victor Stinner838f2642019-06-13 22:41:23 +02003132 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003133 if (sys_path != NULL) {
3134 if (PyList_Insert(sys_path, 0, path0) < 0) {
3135 Py_DECREF(path0);
3136 Py_FatalError("can't prepend path0 to sys.path");
3137 }
3138 }
3139 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003140 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003141 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003142}
Guido van Rossuma890e681998-05-12 14:59:24 +00003143
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003144void
3145PySys_SetArgv(int argc, wchar_t **argv)
3146{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003147 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003148}
3149
Victor Stinner14284c22010-04-23 12:02:30 +00003150/* Reimplementation of PyFile_WriteString() no calling indirectly
3151 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3152
3153static int
Victor Stinner79766632010-08-16 17:36:42 +00003154sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003155{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003156 if (file == NULL)
3157 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003158 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003159 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003160 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003161 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003162 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003163 Py_DECREF(result);
3164 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003165}
3166
Victor Stinner79766632010-08-16 17:36:42 +00003167static int
3168sys_pyfile_write(const char *text, PyObject *file)
3169{
3170 PyObject *unicode = NULL;
3171 int err;
3172
3173 if (file == NULL)
3174 return -1;
3175
3176 unicode = PyUnicode_FromString(text);
3177 if (unicode == NULL)
3178 return -1;
3179
3180 err = sys_pyfile_write_unicode(unicode, file);
3181 Py_DECREF(unicode);
3182 return err;
3183}
Guido van Rossuma890e681998-05-12 14:59:24 +00003184
3185/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3186 Adapted from code submitted by Just van Rossum.
3187
3188 PySys_WriteStdout(format, ...)
3189 PySys_WriteStderr(format, ...)
3190
3191 The first function writes to sys.stdout; the second to sys.stderr. When
3192 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003193 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003194
Victor Stinner14284c22010-04-23 12:02:30 +00003195 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003196 signal handlers: they may raise a new exception whereas sys_write()
3197 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003198
Guido van Rossuma890e681998-05-12 14:59:24 +00003199 Both take a printf-style format string as their first argument followed
3200 by a variable length argument list determined by the format string.
3201
3202 *** WARNING ***
3203
3204 The format should limit the total size of the formatted output string to
3205 1000 bytes. In particular, this means that no unrestricted "%s" formats
3206 should occur; these should be limited using "%.<N>s where <N> is a
3207 decimal number calculated so that <N> plus the maximum size of other
3208 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3209 which can print hundreds of digits for very large numbers.
3210
3211 */
3212
3213static void
Victor Stinner09054372013-11-06 22:41:44 +01003214sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003216 PyObject *file;
3217 PyObject *error_type, *error_value, *error_traceback;
3218 char buffer[1001];
3219 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003220 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003221
Victor Stinner838f2642019-06-13 22:41:23 +02003222 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3223 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003224 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3225 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003226 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003227 fputs(buffer, fp);
3228 }
3229 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3230 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003231 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003232 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003233 }
Victor Stinner838f2642019-06-13 22:41:23 +02003234 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003235}
3236
3237void
Guido van Rossuma890e681998-05-12 14:59:24 +00003238PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003240 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003241
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003242 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003243 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003244 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003245}
3246
3247void
Guido van Rossuma890e681998-05-12 14:59:24 +00003248PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003252 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003253 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003254 va_end(va);
3255}
3256
3257static void
Victor Stinner09054372013-11-06 22:41:44 +01003258sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003259{
3260 PyObject *file, *message;
3261 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003262 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003263 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003264
Victor Stinner838f2642019-06-13 22:41:23 +02003265 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3266 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003267 message = PyUnicode_FromFormatV(format, va);
3268 if (message != NULL) {
3269 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003270 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003271 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003272 if (utf8 != NULL)
3273 fputs(utf8, fp);
3274 }
3275 Py_DECREF(message);
3276 }
Victor Stinner838f2642019-06-13 22:41:23 +02003277 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003278}
3279
3280void
3281PySys_FormatStdout(const char *format, ...)
3282{
3283 va_list va;
3284
3285 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003286 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003287 va_end(va);
3288}
3289
3290void
3291PySys_FormatStderr(const char *format, ...)
3292{
3293 va_list va;
3294
3295 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003296 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003298}