blob: b80d37df42c8080cf2e293e61c97c5dba9332a5d [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
Victor Stinneraf1d64d2020-11-04 17:34:34 +010087static PyObject *
88_PySys_GetObject(PyThreadState *tstate, const char *name)
89{
90 PyObject *sysdict = tstate->interp->sysdict;
91 if (sysdict == NULL) {
92 return NULL;
93 }
94 return _PyDict_GetItemStringWithError(sysdict, name);
95}
96
Victor Stinner838f2642019-06-13 22:41:23 +020097PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000098PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099{
Victor Stinner838f2642019-06-13 22:41:23 +0200100 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100101
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200102 PyObject *exc_type, *exc_value, *exc_tb;
103 _PyErr_Fetch(tstate, &exc_type, &exc_value, &exc_tb);
Victor Stinneraf1d64d2020-11-04 17:34:34 +0100104 PyObject *value = _PySys_GetObject(tstate, name);
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200105 /* XXX Suppress a new exception if it was raised and restore
106 * the old one. */
107 _PyErr_Restore(tstate, exc_type, exc_value, exc_tb);
108 return value;
109}
110
111static int
112sys_set_object(PyThreadState *tstate, PyObject *key, PyObject *v)
113{
114 if (key == NULL) {
115 return -1;
116 }
117 PyObject *sd = tstate->interp->sysdict;
118 if (v == NULL) {
119 v = _PyDict_Pop(sd, key, Py_None);
120 if (v == NULL) {
121 return -1;
122 }
123 Py_DECREF(v);
124 return 0;
125 }
126 else {
127 return PyDict_SetItem(sd, key, v);
128 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000129}
130
Victor Stinner838f2642019-06-13 22:41:23 +0200131static int
132sys_set_object_id(PyThreadState *tstate, _Py_Identifier *key, PyObject *v)
Victor Stinnerd67bd452013-11-06 22:36:40 +0100133{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200134 return sys_set_object(tstate, _PyUnicode_FromId(key), v);
Victor Stinnerd67bd452013-11-06 22:36:40 +0100135}
136
137int
Victor Stinner838f2642019-06-13 22:41:23 +0200138_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000139{
Victor Stinner838f2642019-06-13 22:41:23 +0200140 PyThreadState *tstate = _PyThreadState_GET();
141 return sys_set_object_id(tstate, key, v);
142}
143
144static int
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200145sys_set_object_str(PyThreadState *tstate, const char *name, PyObject *v)
Victor Stinner838f2642019-06-13 22:41:23 +0200146{
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200147 PyObject *key = v ? PyUnicode_InternFromString(name)
148 : PyUnicode_FromString(name);
149 int r = sys_set_object(tstate, key, v);
150 Py_XDECREF(key);
151 return r;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152}
153
Victor Stinner838f2642019-06-13 22:41:23 +0200154int
155PySys_SetObject(const char *name, PyObject *v)
Steve Dowerb82e17e2019-05-23 08:45:22 -0700156{
Victor Stinner838f2642019-06-13 22:41:23 +0200157 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +0200158 return sys_set_object_str(tstate, name, v);
Victor Stinner838f2642019-06-13 22:41:23 +0200159}
160
Victor Stinner08faf002020-03-26 18:57:32 +0100161
Victor Stinner838f2642019-06-13 22:41:23 +0200162static int
Victor Stinner08faf002020-03-26 18:57:32 +0100163should_audit(PyInterpreterState *is)
Victor Stinner838f2642019-06-13 22:41:23 +0200164{
Victor Stinner08faf002020-03-26 18:57:32 +0100165 /* tstate->interp cannot be NULL, but test it just in case
166 for extra safety */
167 assert(is != NULL);
168 if (!is) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700169 return 0;
170 }
Victor Stinner08faf002020-03-26 18:57:32 +0100171 return (is->runtime->audit_hook_head
172 || is->audit_hooks
173 || PyDTrace_AUDIT_ENABLED());
Steve Dowerb82e17e2019-05-23 08:45:22 -0700174}
175
Steve Dowerb82e17e2019-05-23 08:45:22 -0700176
Victor Stinner08faf002020-03-26 18:57:32 +0100177static int
178sys_audit_tstate(PyThreadState *ts, const char *event,
179 const char *argFormat, va_list vargs)
180{
Steve Dowerb82e17e2019-05-23 08:45:22 -0700181 /* N format is inappropriate, because you do not know
182 whether the reference is consumed by the call.
183 Assert rather than exception for perf reasons */
184 assert(!argFormat || !strchr(argFormat, 'N'));
185
Victor Stinner08faf002020-03-26 18:57:32 +0100186 if (!ts) {
187 /* Audit hooks cannot be called with a NULL thread state */
Steve Dowerb82e17e2019-05-23 08:45:22 -0700188 return 0;
189 }
190
Victor Stinner08faf002020-03-26 18:57:32 +0100191 /* The current implementation cannot be called if tstate is not
192 the current Python thread state. */
193 assert(ts == _PyThreadState_GET());
194
195 /* Early exit when no hooks are registered */
196 PyInterpreterState *is = ts->interp;
197 if (!should_audit(is)) {
198 return 0;
199 }
200
201 PyObject *eventName = NULL;
202 PyObject *eventArgs = NULL;
203 PyObject *hooks = NULL;
204 PyObject *hook = NULL;
205 int res = -1;
206
Steve Dowerb82e17e2019-05-23 08:45:22 -0700207 int dtrace = PyDTrace_AUDIT_ENABLED();
208
209 PyObject *exc_type, *exc_value, *exc_tb;
Victor Stinner08faf002020-03-26 18:57:32 +0100210 _PyErr_Fetch(ts, &exc_type, &exc_value, &exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700211
212 /* Initialize event args now */
213 if (argFormat && argFormat[0]) {
Victor Stinner08faf002020-03-26 18:57:32 +0100214 eventArgs = _Py_VaBuildValue_SizeT(argFormat, vargs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700215 if (eventArgs && !PyTuple_Check(eventArgs)) {
216 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
217 Py_DECREF(eventArgs);
218 eventArgs = argTuple;
219 }
Victor Stinner08faf002020-03-26 18:57:32 +0100220 }
221 else {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700222 eventArgs = PyTuple_New(0);
223 }
224 if (!eventArgs) {
225 goto exit;
226 }
227
228 /* Call global hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100229 _Py_AuditHookEntry *e = is->runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700230 for (; e; e = e->next) {
231 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
232 goto exit;
233 }
234 }
235
236 /* Dtrace USDT point */
237 if (dtrace) {
Andy Lestere6be9b52020-02-11 20:28:35 -0600238 PyDTrace_AUDIT(event, (void *)eventArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700239 }
240
241 /* Call interpreter hooks */
Victor Stinner08faf002020-03-26 18:57:32 +0100242 if (is->audit_hooks) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700243 eventName = PyUnicode_FromString(event);
244 if (!eventName) {
245 goto exit;
246 }
247
248 hooks = PyObject_GetIter(is->audit_hooks);
249 if (!hooks) {
250 goto exit;
251 }
252
253 /* Disallow tracing in hooks unless explicitly enabled */
254 ts->tracing++;
255 ts->use_tracing = 0;
256 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300257 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700258 PyObject *o;
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300259 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700260 if (o) {
261 canTrace = PyObject_IsTrue(o);
262 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700263 }
264 if (canTrace < 0) {
265 break;
266 }
267 if (canTrace) {
268 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
269 ts->tracing--;
270 }
Victor Stinner08faf002020-03-26 18:57:32 +0100271 PyObject* args[2] = {eventName, eventArgs};
272 o = _PyObject_FastCallTstate(ts, hook, args, 2);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700273 if (canTrace) {
274 ts->tracing++;
275 ts->use_tracing = 0;
276 }
277 if (!o) {
278 break;
279 }
280 Py_DECREF(o);
281 Py_CLEAR(hook);
282 }
283 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
284 ts->tracing--;
Victor Stinner838f2642019-06-13 22:41:23 +0200285 if (_PyErr_Occurred(ts)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700286 goto exit;
287 }
288 }
289
290 res = 0;
291
292exit:
293 Py_XDECREF(hook);
294 Py_XDECREF(hooks);
295 Py_XDECREF(eventName);
296 Py_XDECREF(eventArgs);
297
Victor Stinner08faf002020-03-26 18:57:32 +0100298 if (!res) {
299 _PyErr_Restore(ts, exc_type, exc_value, exc_tb);
300 }
301 else {
302 assert(_PyErr_Occurred(ts));
303 Py_XDECREF(exc_type);
304 Py_XDECREF(exc_value);
305 Py_XDECREF(exc_tb);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700306 }
307
308 return res;
309}
310
Victor Stinner08faf002020-03-26 18:57:32 +0100311int
312_PySys_Audit(PyThreadState *tstate, const char *event,
313 const char *argFormat, ...)
314{
315 va_list vargs;
316#ifdef HAVE_STDARG_PROTOTYPES
317 va_start(vargs, argFormat);
318#else
319 va_start(vargs);
320#endif
321 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
322 va_end(vargs);
323 return res;
324}
325
326int
327PySys_Audit(const char *event, const char *argFormat, ...)
328{
329 PyThreadState *tstate = _PyThreadState_GET();
330 va_list vargs;
331#ifdef HAVE_STDARG_PROTOTYPES
332 va_start(vargs, argFormat);
333#else
334 va_start(vargs);
335#endif
336 int res = sys_audit_tstate(tstate, event, argFormat, vargs);
337 va_end(vargs);
338 return res;
339}
340
Steve Dowerb82e17e2019-05-23 08:45:22 -0700341/* We expose this function primarily for our own cleanup during
342 * finalization. In general, it should not need to be called,
Victor Stinner08faf002020-03-26 18:57:32 +0100343 * and as such the function is not exported.
344 *
345 * Must be finalizing to clear hooks */
Victor Stinner838f2642019-06-13 22:41:23 +0200346void
Victor Stinner08faf002020-03-26 18:57:32 +0100347_PySys_ClearAuditHooks(PyThreadState *ts)
Victor Stinner838f2642019-06-13 22:41:23 +0200348{
Victor Stinner08faf002020-03-26 18:57:32 +0100349 assert(ts != NULL);
350 if (!ts) {
351 return;
352 }
353
354 _PyRuntimeState *runtime = ts->interp->runtime;
Victor Stinner7b3c2522020-03-07 00:24:23 +0100355 PyThreadState *finalizing = _PyRuntimeState_GetFinalizing(runtime);
Victor Stinner08faf002020-03-26 18:57:32 +0100356 assert(finalizing == ts);
357 if (finalizing != ts) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700358 return;
Victor Stinner838f2642019-06-13 22:41:23 +0200359 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700360
Victor Stinnerda7933e2020-04-13 03:04:28 +0200361 const PyConfig *config = _PyInterpreterState_GetConfig(ts->interp);
Victor Stinner838f2642019-06-13 22:41:23 +0200362 if (config->verbose) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700363 PySys_WriteStderr("# clear sys.audit hooks\n");
364 }
365
366 /* Hooks can abort later hooks for this event, but cannot
367 abort the clear operation itself. */
Victor Stinner08faf002020-03-26 18:57:32 +0100368 _PySys_Audit(ts, "cpython._PySys_ClearAuditHooks", NULL);
Victor Stinner838f2642019-06-13 22:41:23 +0200369 _PyErr_Clear(ts);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700370
Victor Stinner08faf002020-03-26 18:57:32 +0100371 _Py_AuditHookEntry *e = runtime->audit_hook_head, *n;
372 runtime->audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700373 while (e) {
374 n = e->next;
375 PyMem_RawFree(e);
376 e = n;
377 }
378}
379
380int
381PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
382{
Victor Stinner08faf002020-03-26 18:57:32 +0100383 /* tstate can be NULL, so access directly _PyRuntime:
384 PySys_AddAuditHook() can be called before Python is initialized. */
Victor Stinner838f2642019-06-13 22:41:23 +0200385 _PyRuntimeState *runtime = &_PyRuntime;
Victor Stinner08faf002020-03-26 18:57:32 +0100386 PyThreadState *tstate;
387 if (runtime->initialized) {
388 tstate = _PyRuntimeState_GetThreadState(runtime);
389 }
390 else {
391 tstate = NULL;
392 }
Victor Stinner838f2642019-06-13 22:41:23 +0200393
Steve Dowerb82e17e2019-05-23 08:45:22 -0700394 /* Invoke existing audit hooks to allow them an opportunity to abort. */
395 /* Cannot invoke hooks until we are initialized */
Victor Stinner08faf002020-03-26 18:57:32 +0100396 if (tstate != NULL) {
397 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Steve Dowerbea33f52019-11-28 08:46:11 -0800398 if (_PyErr_ExceptionMatches(tstate, PyExc_RuntimeError)) {
399 /* We do not report errors derived from RuntimeError */
Victor Stinner838f2642019-06-13 22:41:23 +0200400 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700401 return 0;
402 }
403 return -1;
404 }
405 }
406
Victor Stinner08faf002020-03-26 18:57:32 +0100407 _Py_AuditHookEntry *e = runtime->audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700408 if (!e) {
409 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner08faf002020-03-26 18:57:32 +0100410 runtime->audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700411 } else {
Victor Stinner838f2642019-06-13 22:41:23 +0200412 while (e->next) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700413 e = e->next;
Victor Stinner838f2642019-06-13 22:41:23 +0200414 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700415 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
416 sizeof(_Py_AuditHookEntry));
417 }
418
419 if (!e) {
Victor Stinner08faf002020-03-26 18:57:32 +0100420 if (tstate != NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200421 _PyErr_NoMemory(tstate);
422 }
Steve Dowerb82e17e2019-05-23 08:45:22 -0700423 return -1;
424 }
425
426 e->next = NULL;
427 e->hookCFunction = (Py_AuditHookFunction)hook;
428 e->userData = userData;
429
430 return 0;
431}
432
433/*[clinic input]
434sys.addaudithook
435
436 hook: object
437
438Adds a new audit hook callback.
439[clinic start generated code]*/
440
441static PyObject *
442sys_addaudithook_impl(PyObject *module, PyObject *hook)
443/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
444{
Victor Stinner838f2642019-06-13 22:41:23 +0200445 PyThreadState *tstate = _PyThreadState_GET();
446
Steve Dowerb82e17e2019-05-23 08:45:22 -0700447 /* Invoke existing audit hooks to allow them an opportunity to abort. */
Victor Stinner08faf002020-03-26 18:57:32 +0100448 if (_PySys_Audit(tstate, "sys.addaudithook", NULL) < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200449 if (_PyErr_ExceptionMatches(tstate, PyExc_Exception)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700450 /* We do not report errors derived from Exception */
Victor Stinner838f2642019-06-13 22:41:23 +0200451 _PyErr_Clear(tstate);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700452 Py_RETURN_NONE;
453 }
454 return NULL;
455 }
456
Victor Stinner838f2642019-06-13 22:41:23 +0200457 PyInterpreterState *is = tstate->interp;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700458 if (is->audit_hooks == NULL) {
459 is->audit_hooks = PyList_New(0);
460 if (is->audit_hooks == NULL) {
461 return NULL;
462 }
463 }
464
465 if (PyList_Append(is->audit_hooks, hook) < 0) {
466 return NULL;
467 }
468
469 Py_RETURN_NONE;
470}
471
472PyDoc_STRVAR(audit_doc,
473"audit(event, *args)\n\
474\n\
475Passes the event to any audit hooks that are attached.");
476
477static PyObject *
478sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
479{
Victor Stinner838f2642019-06-13 22:41:23 +0200480 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner3026cad2020-06-01 16:02:40 +0200481 _Py_EnsureTstateNotNULL(tstate);
Victor Stinner838f2642019-06-13 22:41:23 +0200482
Steve Dowerb82e17e2019-05-23 08:45:22 -0700483 if (argc == 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200484 _PyErr_SetString(tstate, PyExc_TypeError,
485 "audit() missing 1 required positional argument: "
486 "'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700487 return NULL;
488 }
489
Victor Stinner08faf002020-03-26 18:57:32 +0100490 if (!should_audit(tstate->interp)) {
Steve Dowerb82e17e2019-05-23 08:45:22 -0700491 Py_RETURN_NONE;
492 }
493
494 PyObject *auditEvent = args[0];
495 if (!auditEvent) {
Victor Stinner838f2642019-06-13 22:41:23 +0200496 _PyErr_SetString(tstate, PyExc_TypeError,
497 "expected str for argument 'event'");
Steve Dowerb82e17e2019-05-23 08:45:22 -0700498 return NULL;
499 }
500 if (!PyUnicode_Check(auditEvent)) {
Victor Stinner838f2642019-06-13 22:41:23 +0200501 _PyErr_Format(tstate, PyExc_TypeError,
502 "expected str for argument 'event', not %.200s",
503 Py_TYPE(auditEvent)->tp_name);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700504 return NULL;
505 }
506 const char *event = PyUnicode_AsUTF8(auditEvent);
507 if (!event) {
508 return NULL;
509 }
510
511 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
512 if (!auditArgs) {
513 return NULL;
514 }
515
Victor Stinner08faf002020-03-26 18:57:32 +0100516 int res = _PySys_Audit(tstate, event, "O", auditArgs);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700517 Py_DECREF(auditArgs);
518
519 if (res < 0) {
520 return NULL;
521 }
522
523 Py_RETURN_NONE;
524}
525
526
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400527static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200528sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400529{
Victor Stinner838f2642019-06-13 22:41:23 +0200530 PyThreadState *tstate = _PyThreadState_GET();
531 assert(!_PyErr_Occurred(tstate));
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300532 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400533
534 if (envar == NULL || strlen(envar) == 0) {
535 envar = "pdb.set_trace";
536 }
537 else if (!strcmp(envar, "0")) {
538 /* The breakpoint is explicitly no-op'd. */
539 Py_RETURN_NONE;
540 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300541 /* According to POSIX the string returned by getenv() might be invalidated
542 * or the string content might be overwritten by a subsequent call to
543 * getenv(). Since importing a module can performs the getenv() calls,
544 * we need to save a copy of envar. */
545 envar = _PyMem_RawStrdup(envar);
546 if (envar == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200547 _PyErr_NoMemory(tstate);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300548 return NULL;
549 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200550 const char *last_dot = strrchr(envar, '.');
551 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400552 PyObject *modulepath = NULL;
553
554 if (last_dot == NULL) {
555 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
556 modulepath = PyUnicode_FromString("builtins");
557 attrname = envar;
558 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200559 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400560 /* Split on the last dot; */
561 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
562 attrname = last_dot + 1;
563 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200564 else {
565 goto warn;
566 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400567 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300568 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400569 return NULL;
570 }
571
Anthony Sottiledce345c2018-11-01 10:25:05 -0700572 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400573 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400574
575 if (module == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200576 if (_PyErr_ExceptionMatches(tstate, PyExc_ImportError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200577 goto warn;
578 }
579 PyMem_RawFree(envar);
580 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400581 }
582
583 PyObject *hook = PyObject_GetAttrString(module, attrname);
584 Py_DECREF(module);
585
586 if (hook == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200587 if (_PyErr_ExceptionMatches(tstate, PyExc_AttributeError)) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200588 goto warn;
589 }
590 PyMem_RawFree(envar);
591 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400592 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300593 PyMem_RawFree(envar);
Petr Viktorinffd97532020-02-11 17:46:57 +0100594 PyObject *retval = PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400595 Py_DECREF(hook);
596 return retval;
597
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200598 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400599 /* If any of the imports went wrong, then warn and ignore. */
Victor Stinner838f2642019-06-13 22:41:23 +0200600 _PyErr_Clear(tstate);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400601 int status = PyErr_WarnFormat(
602 PyExc_RuntimeWarning, 0,
603 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300604 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400605 if (status < 0) {
606 /* Printing the warning raised an exception. */
607 return NULL;
608 }
609 /* The warning was (probably) issued. */
610 Py_RETURN_NONE;
611}
612
613PyDoc_STRVAR(breakpointhook_doc,
614"breakpointhook(*args, **kws)\n"
615"\n"
616"This hook function is called by built-in breakpoint().\n"
617);
618
Victor Stinner13d49ee2010-12-04 17:24:33 +0000619/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
620 error handler. If sys.stdout has a buffer attribute, use
621 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
622 sys.stdout.write(redecoded).
623
624 Helper function for sys_displayhook(). */
625static int
Andy Lesterda4d6562020-03-05 22:34:36 -0600626sys_displayhook_unencodable(PyObject *outf, PyObject *o)
Victor Stinner13d49ee2010-12-04 17:24:33 +0000627{
628 PyObject *stdout_encoding = NULL;
629 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200630 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000631 int ret;
632
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200633 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000634 if (stdout_encoding == NULL)
635 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200636 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000637 if (stdout_encoding_str == NULL)
638 goto error;
639
640 repr_str = PyObject_Repr(o);
641 if (repr_str == NULL)
642 goto error;
643 encoded = PyUnicode_AsEncodedString(repr_str,
644 stdout_encoding_str,
645 "backslashreplace");
646 Py_DECREF(repr_str);
647 if (encoded == NULL)
648 goto error;
649
Serhiy Storchaka41c57b32019-09-01 12:03:39 +0300650 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
651 Py_DECREF(encoded);
652 goto error;
653 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000654 if (buffer) {
Jeroen Demeyer59ad1102019-07-11 10:59:05 +0200655 result = _PyObject_CallMethodIdOneArg(buffer, &PyId_write, encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000656 Py_DECREF(buffer);
657 Py_DECREF(encoded);
658 if (result == NULL)
659 goto error;
660 Py_DECREF(result);
661 }
662 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000663 escaped_str = PyUnicode_FromEncodedObject(encoded,
664 stdout_encoding_str,
665 "strict");
666 Py_DECREF(encoded);
667 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
668 Py_DECREF(escaped_str);
669 goto error;
670 }
671 Py_DECREF(escaped_str);
672 }
673 ret = 0;
674 goto finally;
675
676error:
677 ret = -1;
678finally:
679 Py_XDECREF(stdout_encoding);
680 return ret;
681}
682
Tal Einatede0b6f2018-12-31 17:12:08 +0200683/*[clinic input]
684sys.displayhook
685
686 object as o: object
687 /
688
689Print an object to sys.stdout and also save it in builtins._
690[clinic start generated code]*/
691
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000692static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200693sys_displayhook(PyObject *module, PyObject *o)
694/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100697 PyObject *builtins;
698 static PyObject *newline = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200699 PyThreadState *tstate = _PyThreadState_GET();
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000700
Eric Snow3f9eee62017-09-15 16:35:20 -0600701 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000702 if (builtins == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +0200703 if (!_PyErr_Occurred(tstate)) {
704 _PyErr_SetString(tstate, PyExc_RuntimeError,
705 "lost builtins module");
Stefan Krah027b09c2019-03-25 21:50:58 +0100706 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return NULL;
708 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600709 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 /* Print value except if None */
712 /* After printing, also assign to '_' */
713 /* Before, set '_' to None to avoid recursion */
714 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200715 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200717 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200719 outf = sys_get_object_id(tstate, &PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 if (outf == NULL || outf == Py_None) {
Victor Stinner838f2642019-06-13 22:41:23 +0200721 _PyErr_SetString(tstate, PyExc_RuntimeError, "lost sys.stdout");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 return NULL;
723 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000724 if (PyFile_WriteObject(o, outf, 0) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +0200725 if (_PyErr_ExceptionMatches(tstate, PyExc_UnicodeEncodeError)) {
Andy Lesterda4d6562020-03-05 22:34:36 -0600726 int err;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000727 /* repr(o) is not encodable to sys.stdout.encoding with
728 * sys.stdout.errors error handler (which is probably 'strict') */
Victor Stinner838f2642019-06-13 22:41:23 +0200729 _PyErr_Clear(tstate);
Andy Lesterda4d6562020-03-05 22:34:36 -0600730 err = sys_displayhook_unencodable(outf, o);
Victor Stinner838f2642019-06-13 22:41:23 +0200731 if (err) {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000732 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +0200733 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000734 }
735 else {
736 return NULL;
737 }
738 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100739 if (newline == NULL) {
740 newline = PyUnicode_FromString("\n");
741 if (newline == NULL)
742 return NULL;
743 }
744 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200746 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200748 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000749}
750
Tal Einatede0b6f2018-12-31 17:12:08 +0200751
752/*[clinic input]
753sys.excepthook
754
755 exctype: object
756 value: object
757 traceback: object
758 /
759
760Handle an exception by displaying it with a traceback on sys.stderr.
761[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000762
763static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200764sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
765 PyObject *traceback)
766/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000767{
Tal Einatede0b6f2018-12-31 17:12:08 +0200768 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200769 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000770}
771
Tal Einatede0b6f2018-12-31 17:12:08 +0200772
773/*[clinic input]
774sys.exc_info
775
776Return current exception information: (type, value, traceback).
777
778Return information about the most recent exception caught by an except
779clause in the current stack frame or in an older stack frame.
780[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000781
782static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200783sys_exc_info_impl(PyObject *module)
784/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000785{
Victor Stinner50b48572018-11-01 01:51:40 +0100786 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 return Py_BuildValue(
788 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100789 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
790 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
791 err_info->exc_traceback != NULL ?
792 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000793}
794
Tal Einatede0b6f2018-12-31 17:12:08 +0200795
796/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200797sys.unraisablehook
798
799 unraisable: object
800 /
801
802Handle an unraisable exception.
803
804The unraisable argument has the following attributes:
805
806* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200807* exc_value: Exception value, can be None.
808* exc_traceback: Exception traceback, can be None.
809* err_msg: Error message, can be None.
810* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200811[clinic start generated code]*/
812
813static PyObject *
814sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200815/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200816{
817 return _PyErr_WriteUnraisableDefaultHook(unraisable);
818}
819
820
821/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200822sys.exit
823
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300824 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200825 /
826
827Exit the interpreter by raising SystemExit(status).
828
829If the status is omitted or None, it defaults to zero (i.e., success).
830If the status is an integer, it will be used as the system exit status.
831If it is another kind of object, it will be printed and the system
832exit status will be one (i.e., failure).
833[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000834
835static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200836sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchaka279f4462019-09-14 12:24:05 +0300837/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 /* Raise SystemExit so callers may catch it or clean up. */
Victor Stinner838f2642019-06-13 22:41:23 +0200840 PyThreadState *tstate = _PyThreadState_GET();
841 _PyErr_SetObject(tstate, PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000842 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000843}
844
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000845
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000846
Tal Einatede0b6f2018-12-31 17:12:08 +0200847/*[clinic input]
848sys.getdefaultencoding
849
850Return the current default encoding used by the Unicode implementation.
851[clinic start generated code]*/
852
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000853static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200854sys_getdefaultencoding_impl(PyObject *module)
855/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000858}
859
Tal Einatede0b6f2018-12-31 17:12:08 +0200860/*[clinic input]
861sys.getfilesystemencoding
862
863Return the encoding used to convert Unicode filenames to OS filenames.
864[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000865
866static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200867sys_getfilesystemencoding_impl(PyObject *module)
868/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000869{
Victor Stinner81a7be32020-04-14 15:14:01 +0200870 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200871 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400872 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000873}
874
Tal Einatede0b6f2018-12-31 17:12:08 +0200875/*[clinic input]
876sys.getfilesystemencodeerrors
877
878Return the error mode used Unicode to OS filename conversion.
879[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000880
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000881static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200882sys_getfilesystemencodeerrors_impl(PyObject *module)
883/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700884{
Victor Stinner81a7be32020-04-14 15:14:01 +0200885 PyInterpreterState *interp = _PyInterpreterState_GET();
Victor Stinnerda7933e2020-04-13 03:04:28 +0200886 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Victor Stinner709d23d2019-05-02 14:56:30 -0400887 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700888}
889
Tal Einatede0b6f2018-12-31 17:12:08 +0200890/*[clinic input]
891sys.intern
892
893 string as s: unicode
894 /
895
896``Intern'' the given string.
897
898This enters the string in the (global) table of interned strings whose
899purpose is to speed up dictionary lookups. Return the string itself or
900the previously interned string object with the same value.
901[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700902
903static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200904sys_intern_impl(PyObject *module, PyObject *s)
905/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000906{
Victor Stinner838f2642019-06-13 22:41:23 +0200907 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 if (PyUnicode_CheckExact(s)) {
909 Py_INCREF(s);
910 PyUnicode_InternInPlace(&s);
911 return s;
912 }
913 else {
Victor Stinner838f2642019-06-13 22:41:23 +0200914 _PyErr_Format(tstate, PyExc_TypeError,
Victor Stinnera102ed72020-02-07 02:24:48 +0100915 "can't intern %.400s", Py_TYPE(s)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return NULL;
917 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000918}
919
Georg Brandl66a796e2006-12-19 20:50:34 +0000920
Fred Drake5755ce62001-06-27 19:19:46 +0000921/*
922 * Cached interned string objects used for calling the profile and
923 * trace functions. Initialized by trace_init().
924 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000925static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000926
927static int
928trace_init(void)
929{
Nick Coghlan5a851672017-09-08 10:14:16 +1000930 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200931 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000932 "c_call", "c_exception", "c_return",
933 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200934 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *name;
936 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000937 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 if (whatstrings[i] == NULL) {
939 name = PyUnicode_InternFromString(whatnames[i]);
940 if (name == NULL)
941 return -1;
942 whatstrings[i] = name;
943 }
944 }
945 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000946}
947
948
949static PyObject *
Victor Stinner309d7cc2020-03-13 16:39:12 +0100950call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000952{
Victor Stinner78da82b2016-08-20 01:22:57 +0200953 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000954 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200955 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100956
Victor Stinner838f2642019-06-13 22:41:23 +0200957 PyObject *stack[3];
Victor Stinner78da82b2016-08-20 01:22:57 +0200958 stack[0] = (PyObject *)frame;
959 stack[1] = whatstrings[what];
960 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000961
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000962 /* call the Python-level function */
Victor Stinner309d7cc2020-03-13 16:39:12 +0100963 PyObject *result = _PyObject_FastCallTstate(tstate, callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000964
Victor Stinner78da82b2016-08-20 01:22:57 +0200965 PyFrame_LocalsToFast(frame, 1);
966 if (result == NULL) {
967 PyTraceBack_Here(frame);
968 }
969
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000971}
972
973static int
974profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000976{
Victor Stinner309d7cc2020-03-13 16:39:12 +0100977 if (arg == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 arg = Py_None;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100979 }
980
981 PyThreadState *tstate = _PyThreadState_GET();
982 PyObject *result = call_trampoline(tstate, self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +0100984 _PyEval_SetProfile(tstate, NULL, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return -1;
986 }
Victor Stinner309d7cc2020-03-13 16:39:12 +0100987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 Py_DECREF(result);
989 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000990}
991
992static int
993trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 PyObject *callback;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100997 if (what == PyTrace_CALL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 callback = self;
Victor Stinner309d7cc2020-03-13 16:39:12 +0100999 }
1000 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 callback = frame->f_trace;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001002 }
1003 if (callback == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 return 0;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001005 }
1006
1007 PyThreadState *tstate = _PyThreadState_GET();
1008 PyObject *result = call_trampoline(tstate, callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 if (result == NULL) {
Victor Stinner309d7cc2020-03-13 16:39:12 +01001010 _PyEval_SetTrace(tstate, NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +02001011 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 return -1;
1013 }
Victor Stinner309d7cc2020-03-13 16:39:12 +01001014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +03001016 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 }
1018 else {
1019 Py_DECREF(result);
1020 }
1021 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +00001022}
Fred Draked0838392001-06-16 21:02:31 +00001023
Fred Drake8b4d01d2000-05-09 19:57:01 +00001024static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001025sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001026{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001027 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001029 }
1030
1031 PyThreadState *tstate = _PyThreadState_GET();
1032 if (args == Py_None) {
1033 if (_PyEval_SetTrace(tstate, NULL, NULL) < 0) {
1034 return NULL;
1035 }
1036 }
1037 else {
1038 if (_PyEval_SetTrace(tstate, trace_trampoline, args) < 0) {
1039 return NULL;
1040 }
1041 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001042 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001043}
1044
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001045PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001046"settrace(function)\n\
1047\n\
1048Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001049function call. See the debugger chapter in the library manual."
1050);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001051
Tal Einatede0b6f2018-12-31 17:12:08 +02001052/*[clinic input]
1053sys.gettrace
1054
1055Return the global debug tracing function set with sys.settrace.
1056
1057See the debugger chapter in the library manual.
1058[clinic start generated code]*/
1059
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001060static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001061sys_gettrace_impl(PyObject *module)
1062/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001063{
Victor Stinner50b48572018-11-01 01:51:40 +01001064 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001066
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 if (temp == NULL)
1068 temp = Py_None;
1069 Py_INCREF(temp);
1070 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001071}
1072
Christian Heimes9bd667a2008-01-20 15:14:11 +00001073static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001074sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +00001075{
Victor Stinner309d7cc2020-03-13 16:39:12 +01001076 if (trace_init() == -1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 return NULL;
Victor Stinner309d7cc2020-03-13 16:39:12 +01001078 }
1079
1080 PyThreadState *tstate = _PyThreadState_GET();
1081 if (args == Py_None) {
1082 if (_PyEval_SetProfile(tstate, NULL, NULL) < 0) {
1083 return NULL;
1084 }
1085 }
1086 else {
1087 if (_PyEval_SetProfile(tstate, profile_trampoline, args) < 0) {
1088 return NULL;
1089 }
1090 }
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001091 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +00001092}
1093
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001094PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001095"setprofile(function)\n\
1096\n\
1097Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001098and return. See the profiler chapter in the library manual."
1099);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001100
Tal Einatede0b6f2018-12-31 17:12:08 +02001101/*[clinic input]
1102sys.getprofile
1103
1104Return the profiling function set with sys.setprofile.
1105
1106See the profiler chapter in the library manual.
1107[clinic start generated code]*/
1108
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001109static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001110sys_getprofile_impl(PyObject *module)
1111/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +00001112{
Victor Stinner50b48572018-11-01 01:51:40 +01001113 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 if (temp == NULL)
1117 temp = Py_None;
1118 Py_INCREF(temp);
1119 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +00001120}
1121
Tim Peterse5e065b2003-07-06 18:36:54 +00001122
Tal Einatede0b6f2018-12-31 17:12:08 +02001123/*[clinic input]
1124sys.setswitchinterval
1125
1126 interval: double
1127 /
1128
1129Set the ideal thread switching delay inside the Python interpreter.
1130
1131The actual frequency of switching threads can be lower if the
1132interpreter executes long sequences of uninterruptible code
1133(this is implementation-specific and workload-dependent).
1134
1135The parameter must represent the desired switching delay in seconds
1136A typical value is 0.005 (5 milliseconds).
1137[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001138
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001139static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001140sys_setswitchinterval_impl(PyObject *module, double interval)
1141/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001142{
Victor Stinner838f2642019-06-13 22:41:23 +02001143 PyThreadState *tstate = _PyThreadState_GET();
Tal Einatede0b6f2018-12-31 17:12:08 +02001144 if (interval <= 0.0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001145 _PyErr_SetString(tstate, PyExc_ValueError,
1146 "switch interval must be strictly positive");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return NULL;
1148 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001149 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001150 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001151}
1152
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001153
Tal Einatede0b6f2018-12-31 17:12:08 +02001154/*[clinic input]
1155sys.getswitchinterval -> double
1156
1157Return the current thread switch interval; see sys.setswitchinterval().
1158[clinic start generated code]*/
1159
1160static double
1161sys_getswitchinterval_impl(PyObject *module)
1162/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001163{
Tal Einatede0b6f2018-12-31 17:12:08 +02001164 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001165}
1166
Tal Einatede0b6f2018-12-31 17:12:08 +02001167/*[clinic input]
1168sys.setrecursionlimit
1169
1170 limit as new_limit: int
1171 /
1172
1173Set the maximum depth of the Python interpreter stack to n.
1174
1175This limit prevents infinite recursion from causing an overflow of the C
1176stack and crashing Python. The highest possible limit is platform-
1177dependent.
1178[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001179
Tim Peterse5e065b2003-07-06 18:36:54 +00001180static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001181sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1182/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001183{
Victor Stinner838f2642019-06-13 22:41:23 +02001184 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001185
Victor Stinner50856d52015-10-13 00:11:21 +02001186 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001187 _PyErr_SetString(tstate, PyExc_ValueError,
1188 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 return NULL;
1190 }
Victor Stinner50856d52015-10-13 00:11:21 +02001191
1192 /* Issue #25274: When the recursion depth hits the recursion limit in
1193 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1194 set to 1 and a RecursionError is raised. The overflowed flag is reset
1195 to 0 when the recursion depth goes below the low-water mark: see
1196 Py_LeaveRecursiveCall().
1197
1198 Reject too low new limit if the current recursion depth is higher than
1199 the new low-water mark. Otherwise it may not be possible anymore to
1200 reset the overflowed flag to 0. */
Mark Shannon4e7a69b2020-12-02 13:30:55 +00001201 if (tstate->recursion_depth >= new_limit) {
Victor Stinner838f2642019-06-13 22:41:23 +02001202 _PyErr_Format(tstate, PyExc_RecursionError,
1203 "cannot set the recursion limit to %i at "
1204 "the recursion depth %i: the limit is too low",
1205 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001206 return NULL;
1207 }
1208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001210 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001211}
1212
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001213/*[clinic input]
1214sys.set_coroutine_origin_tracking_depth
1215
1216 depth: int
1217
1218Enable or disable origin tracking for coroutine objects in this thread.
1219
Tal Einatede0b6f2018-12-31 17:12:08 +02001220Coroutine objects will track 'depth' frames of traceback information
1221about where they came from, available in their cr_origin attribute.
1222
1223Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001224[clinic start generated code]*/
1225
1226static PyObject *
1227sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001228/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001229{
Victor Stinner838f2642019-06-13 22:41:23 +02001230 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001231 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001232 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001233 return NULL;
1234 }
Victor Stinner838f2642019-06-13 22:41:23 +02001235 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001236 Py_RETURN_NONE;
1237}
1238
1239/*[clinic input]
1240sys.get_coroutine_origin_tracking_depth -> int
1241
1242Check status of origin tracking for coroutine objects in this thread.
1243[clinic start generated code]*/
1244
1245static int
1246sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1247/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1248{
1249 return _PyEval_GetCoroutineOriginTrackingDepth();
1250}
1251
Yury Selivanoveb636452016-09-08 22:01:51 -07001252static PyTypeObject AsyncGenHooksType;
1253
1254PyDoc_STRVAR(asyncgen_hooks_doc,
1255"asyncgen_hooks\n\
1256\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001257A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001258generators hooks. The attributes are read only.");
1259
1260static PyStructSequence_Field asyncgen_hooks_fields[] = {
1261 {"firstiter", "Hook to intercept first iteration"},
1262 {"finalizer", "Hook to intercept finalization"},
1263 {0}
1264};
1265
1266static PyStructSequence_Desc asyncgen_hooks_desc = {
1267 "asyncgen_hooks", /* name */
1268 asyncgen_hooks_doc, /* doc */
1269 asyncgen_hooks_fields , /* fields */
1270 2
1271};
1272
Yury Selivanoveb636452016-09-08 22:01:51 -07001273static PyObject *
1274sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1275{
1276 static char *keywords[] = {"firstiter", "finalizer", NULL};
1277 PyObject *firstiter = NULL;
1278 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001279 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001280
1281 if (!PyArg_ParseTupleAndKeywords(
1282 args, kw, "|OO", keywords,
1283 &firstiter, &finalizer)) {
1284 return NULL;
1285 }
1286
1287 if (finalizer && finalizer != Py_None) {
1288 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001289 _PyErr_Format(tstate, PyExc_TypeError,
1290 "callable finalizer expected, got %.50s",
1291 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001292 return NULL;
1293 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001294 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1295 return NULL;
1296 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001297 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001298 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1299 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001300 }
1301
1302 if (firstiter && firstiter != Py_None) {
1303 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001304 _PyErr_Format(tstate, PyExc_TypeError,
1305 "callable firstiter expected, got %.50s",
1306 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001307 return NULL;
1308 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001309 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1310 return NULL;
1311 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001312 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001313 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1314 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001315 }
1316
1317 Py_RETURN_NONE;
1318}
1319
1320PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001321"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001322\n\
1323Set a finalizer for async generators objects."
1324);
1325
Tal Einatede0b6f2018-12-31 17:12:08 +02001326/*[clinic input]
1327sys.get_asyncgen_hooks
1328
1329Return the installed asynchronous generators hooks.
1330
1331This returns a namedtuple of the form (firstiter, finalizer).
1332[clinic start generated code]*/
1333
Yury Selivanoveb636452016-09-08 22:01:51 -07001334static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001335sys_get_asyncgen_hooks_impl(PyObject *module)
1336/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001337{
1338 PyObject *res;
1339 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1340 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1341
1342 res = PyStructSequence_New(&AsyncGenHooksType);
1343 if (res == NULL) {
1344 return NULL;
1345 }
1346
1347 if (firstiter == NULL) {
1348 firstiter = Py_None;
1349 }
1350
1351 if (finalizer == NULL) {
1352 finalizer = Py_None;
1353 }
1354
1355 Py_INCREF(firstiter);
1356 PyStructSequence_SET_ITEM(res, 0, firstiter);
1357
1358 Py_INCREF(finalizer);
1359 PyStructSequence_SET_ITEM(res, 1, finalizer);
1360
1361 return res;
1362}
1363
Yury Selivanoveb636452016-09-08 22:01:51 -07001364
Mark Dickinsondc787d22010-05-23 13:33:13 +00001365static PyTypeObject Hash_InfoType;
1366
1367PyDoc_STRVAR(hash_info_doc,
1368"hash_info\n\
1369\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001370A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001371hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001372
1373static PyStructSequence_Field hash_info_fields[] = {
1374 {"width", "width of the type used for hashing, in bits"},
1375 {"modulus", "prime number giving the modulus on which the hash "
1376 "function is based"},
1377 {"inf", "value to be used for hash of a positive infinity"},
1378 {"nan", "value to be used for hash of a nan"},
1379 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001380 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1381 "memoryviews"},
1382 {"hash_bits", "internal output size of hash algorithm"},
1383 {"seed_bits", "seed size of hash algorithm"},
1384 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001385 {NULL, NULL}
1386};
1387
1388static PyStructSequence_Desc hash_info_desc = {
1389 "sys.hash_info",
1390 hash_info_doc,
1391 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001392 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001393};
1394
Matthias Klosed885e952010-07-06 10:53:30 +00001395static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001396get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001397{
1398 PyObject *hash_info;
1399 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001400 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001401 hash_info = PyStructSequence_New(&Hash_InfoType);
1402 if (hash_info == NULL)
1403 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001404 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001405 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001406 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001407 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001408 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001409 PyStructSequence_SET_ITEM(hash_info, field++,
1410 PyLong_FromLong(_PyHASH_INF));
1411 PyStructSequence_SET_ITEM(hash_info, field++,
1412 PyLong_FromLong(_PyHASH_NAN));
1413 PyStructSequence_SET_ITEM(hash_info, field++,
1414 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001415 PyStructSequence_SET_ITEM(hash_info, field++,
1416 PyUnicode_FromString(hashfunc->name));
1417 PyStructSequence_SET_ITEM(hash_info, field++,
1418 PyLong_FromLong(hashfunc->hash_bits));
1419 PyStructSequence_SET_ITEM(hash_info, field++,
1420 PyLong_FromLong(hashfunc->seed_bits));
1421 PyStructSequence_SET_ITEM(hash_info, field++,
1422 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001423 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001424 Py_CLEAR(hash_info);
1425 return NULL;
1426 }
1427 return hash_info;
1428}
Tal Einatede0b6f2018-12-31 17:12:08 +02001429/*[clinic input]
1430sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001431
Tal Einatede0b6f2018-12-31 17:12:08 +02001432Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001433
Tal Einatede0b6f2018-12-31 17:12:08 +02001434The recursion limit is the maximum depth of the Python interpreter
1435stack. This limit prevents infinite recursion from causing an overflow
1436of the C stack and crashing Python.
1437[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001438
1439static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001440sys_getrecursionlimit_impl(PyObject *module)
1441/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001444}
1445
Mark Hammond8696ebc2002-10-08 02:44:31 +00001446#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001447
Eric Smithf7bb5782010-01-27 00:44:57 +00001448static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1449
1450static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 {"major", "Major version number"},
1452 {"minor", "Minor version number"},
1453 {"build", "Build number"},
1454 {"platform", "Operating system platform"},
1455 {"service_pack", "Latest Service Pack installed on the system"},
1456 {"service_pack_major", "Service Pack major version number"},
1457 {"service_pack_minor", "Service Pack minor version number"},
1458 {"suite_mask", "Bit mask identifying available product suites"},
1459 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001460 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001462};
1463
1464static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001465 "sys.getwindowsversion", /* name */
1466 sys_getwindowsversion__doc__, /* doc */
1467 windows_version_fields, /* fields */
1468 5 /* For backward compatibility,
1469 only the first 5 items are accessible
1470 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001471};
1472
Steve Dower3e96f322015-03-02 08:01:10 -08001473/* Disable deprecation warnings about GetVersionEx as the result is
1474 being passed straight through to the caller, who is responsible for
1475 using it correctly. */
1476#pragma warning(push)
1477#pragma warning(disable:4996)
1478
Tal Einatede0b6f2018-12-31 17:12:08 +02001479/*[clinic input]
1480sys.getwindowsversion
1481
1482Return info about the running version of Windows as a named tuple.
1483
1484The members are named: major, minor, build, platform, service_pack,
1485service_pack_major, service_pack_minor, suite_mask, product_type and
1486platform_version. For backward compatibility, only the first 5 items
1487are available by indexing. All elements are numbers, except
1488service_pack and platform_type which are strings, and platform_version
1489which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1490workstation, 2 for a domain controller, 3 for a server.
1491Platform_version is a 3-tuple containing a version number that is
1492intended for identifying the OS rather than feature detection.
1493[clinic start generated code]*/
1494
Mark Hammond8696ebc2002-10-08 02:44:31 +00001495static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001496sys_getwindowsversion_impl(PyObject *module)
1497/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyObject *version;
1500 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001501 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001502 DWORD realMajor, realMinor, realBuild;
1503 HANDLE hKernel32;
1504 wchar_t kernel32_path[MAX_PATH];
1505 LPVOID verblock;
1506 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001507 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001510 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 version = PyStructSequence_New(&WindowsVersionType);
1514 if (version == NULL)
1515 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1518 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1519 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1520 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001521 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1523 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1524 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1525 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001526
Steve Dower74f4af72016-09-17 17:27:48 -07001527 realMajor = ver.dwMajorVersion;
1528 realMinor = ver.dwMinorVersion;
1529 realBuild = ver.dwBuildNumber;
1530
1531 // GetVersion will lie if we are running in a compatibility mode.
1532 // We need to read the version info from a system file resource
1533 // to accurately identify the OS version. If we fail for any reason,
1534 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001535 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001536 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001537 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001538 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1539 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1540 (verblock = PyMem_RawMalloc(verblock_size))) {
1541 VS_FIXEDFILEINFO *ffi;
1542 UINT ffi_len;
1543
1544 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1545 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1546 realMajor = HIWORD(ffi->dwProductVersionMS);
1547 realMinor = LOWORD(ffi->dwProductVersionMS);
1548 realBuild = HIWORD(ffi->dwProductVersionLS);
1549 }
1550 PyMem_RawFree(verblock);
1551 }
Segev Finer48fb7662017-06-04 20:52:27 +03001552 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1553 realMajor,
1554 realMinor,
1555 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001556 ));
1557
Victor Stinner838f2642019-06-13 22:41:23 +02001558 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001559 Py_DECREF(version);
1560 return NULL;
1561 }
Steve Dower74f4af72016-09-17 17:27:48 -07001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001564}
1565
Steve Dower3e96f322015-03-02 08:01:10 -08001566#pragma warning(pop)
1567
Tal Einatede0b6f2018-12-31 17:12:08 +02001568/*[clinic input]
1569sys._enablelegacywindowsfsencoding
1570
1571Changes the default filesystem encoding to mbcs:replace.
1572
1573This is done for consistency with earlier versions of Python. See PEP
1574529 for more information.
1575
1576This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1577environment variable before launching Python.
1578[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001579
1580static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001581sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1582/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001583{
Victor Stinner709d23d2019-05-02 14:56:30 -04001584 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001585 return NULL;
1586 }
Steve Dowercc16be82016-09-08 10:35:16 -07001587 Py_RETURN_NONE;
1588}
1589
Mark Hammond8696ebc2002-10-08 02:44:31 +00001590#endif /* MS_WINDOWS */
1591
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001592#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001593
1594/*[clinic input]
1595sys.setdlopenflags
1596
1597 flags as new_val: int
1598 /
1599
1600Set the flags used by the interpreter for dlopen calls.
1601
1602This is used, for example, when the interpreter loads extension
1603modules. Among other things, this will enable a lazy resolving of
1604symbols when importing a module, if called as sys.setdlopenflags(0).
1605To share symbols across extension modules, call as
1606sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1607modules can be found in the os module (RTLD_xxx constants, e.g.
1608os.RTLD_LAZY).
1609[clinic start generated code]*/
1610
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001611static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001612sys_setdlopenflags_impl(PyObject *module, int new_val)
1613/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001614{
Victor Stinner838f2642019-06-13 22:41:23 +02001615 PyThreadState *tstate = _PyThreadState_GET();
1616 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001617 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001618}
1619
Tal Einatede0b6f2018-12-31 17:12:08 +02001620
1621/*[clinic input]
1622sys.getdlopenflags
1623
1624Return the current value of the flags that are used for dlopen calls.
1625
1626The flag constants are defined in the os module.
1627[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001628
1629static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001630sys_getdlopenflags_impl(PyObject *module)
1631/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001632{
Victor Stinner838f2642019-06-13 22:41:23 +02001633 PyThreadState *tstate = _PyThreadState_GET();
1634 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001635}
1636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001638
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001639#ifdef USE_MALLOPT
1640/* Link with -lmalloc (or -lmpc) on an SGI */
1641#include <malloc.h>
1642
Tal Einatede0b6f2018-12-31 17:12:08 +02001643/*[clinic input]
1644sys.mdebug
1645
1646 flag: int
1647 /
1648[clinic start generated code]*/
1649
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001650static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001651sys_mdebug_impl(PyObject *module, int flag)
1652/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001653{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001656 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001657}
1658#endif /* USE_MALLOPT */
1659
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001660size_t
1661_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001665 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001666 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001667
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001669 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001670 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001671 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001672
Benjamin Petersonce798522012-01-22 11:24:29 -05001673 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001675 if (!_PyErr_Occurred(tstate)) {
1676 _PyErr_Format(tstate, PyExc_TypeError,
1677 "Type %.100s doesn't define __sizeof__",
1678 Py_TYPE(o)->tp_name);
1679 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 }
1681 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001682 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 Py_DECREF(method);
1684 }
1685
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001686 if (res == NULL)
1687 return (size_t)-1;
1688
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001689 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001690 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001691 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001692 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001694 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001695 _PyErr_SetString(tstate, PyExc_ValueError,
1696 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001697 return (size_t)-1;
1698 }
1699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* add gc_head size */
Hai Shi675d9a32020-04-15 02:11:20 +08001701 if (_PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001702 return ((size_t)size) + sizeof(PyGC_Head);
1703 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001704}
1705
1706static PyObject *
1707sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1708{
1709 static char *kwlist[] = {"object", "default", 0};
1710 size_t size;
1711 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001712 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001713
1714 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001715 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001716 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001717 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001718
1719 size = _PySys_GetSizeOf(o);
1720
Victor Stinner838f2642019-06-13 22:41:23 +02001721 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001722 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001723 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1724 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001725 Py_INCREF(dflt);
1726 return dflt;
1727 }
1728 else
1729 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001731
1732 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001733}
1734
1735PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001736"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001737\n\
1738Return the size of object in bytes.");
1739
Tal Einatede0b6f2018-12-31 17:12:08 +02001740/*[clinic input]
1741sys.getrefcount -> Py_ssize_t
1742
1743 object: object
1744 /
1745
1746Return the reference count of object.
1747
1748The count returned is generally one higher than you might expect,
1749because it includes the (temporary) reference as an argument to
1750getrefcount().
1751[clinic start generated code]*/
1752
1753static Py_ssize_t
1754sys_getrefcount_impl(PyObject *module, PyObject *object)
1755/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001756{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001757 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001758}
1759
Tim Peters4be93d02002-07-07 19:59:50 +00001760#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001761/*[clinic input]
1762sys.gettotalrefcount -> Py_ssize_t
1763[clinic start generated code]*/
1764
1765static Py_ssize_t
1766sys_gettotalrefcount_impl(PyObject *module)
1767/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001768{
Tal Einatede0b6f2018-12-31 17:12:08 +02001769 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001770}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001771#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001772
Tal Einatede0b6f2018-12-31 17:12:08 +02001773/*[clinic input]
1774sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001775
Tal Einatede0b6f2018-12-31 17:12:08 +02001776Return the number of memory blocks currently allocated.
1777[clinic start generated code]*/
1778
1779static Py_ssize_t
1780sys_getallocatedblocks_impl(PyObject *module)
1781/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001782{
Tal Einatede0b6f2018-12-31 17:12:08 +02001783 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001784}
1785
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001786
Tal Einatede0b6f2018-12-31 17:12:08 +02001787/*[clinic input]
1788sys._getframe
1789
1790 depth: int = 0
1791 /
1792
1793Return a frame object from the call stack.
1794
1795If optional integer depth is given, return the frame object that many
1796calls below the top of the stack. If that is deeper than the call
1797stack, ValueError is raised. The default for depth is zero, returning
1798the frame at the top of the call stack.
1799
1800This function should be used for internal and specialized purposes
1801only.
1802[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001803
1804static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001805sys__getframe_impl(PyObject *module, int depth)
1806/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001807{
Victor Stinner838f2642019-06-13 22:41:23 +02001808 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner70364772020-04-29 03:28:46 +02001809 PyFrameObject *f = PyThreadState_GetFrame(tstate);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001810
Victor Stinner08faf002020-03-26 18:57:32 +01001811 if (_PySys_Audit(tstate, "sys._getframe", "O", f) < 0) {
Victor Stinner70364772020-04-29 03:28:46 +02001812 Py_DECREF(f);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001813 return NULL;
1814 }
1815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 while (depth > 0 && f != NULL) {
Victor Stinner70364772020-04-29 03:28:46 +02001817 PyFrameObject *back = PyFrame_GetBack(f);
1818 Py_DECREF(f);
1819 f = back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 --depth;
1821 }
1822 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001823 _PyErr_SetString(tstate, PyExc_ValueError,
1824 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001825 return NULL;
1826 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001828}
1829
Tal Einatede0b6f2018-12-31 17:12:08 +02001830/*[clinic input]
1831sys._current_frames
1832
1833Return a dict mapping each thread's thread id to its current stack frame.
1834
1835This function should be used for specialized purposes only.
1836[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001837
1838static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001839sys__current_frames_impl(PyObject *module)
1840/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001841{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001843}
1844
Tal Einatede0b6f2018-12-31 17:12:08 +02001845/*[clinic input]
Julien Danjou64366fa2020-11-02 15:16:25 +01001846sys._current_exceptions
1847
1848Return a dict mapping each thread's identifier to its current raised exception.
1849
1850This function should be used for specialized purposes only.
1851[clinic start generated code]*/
1852
1853static PyObject *
1854sys__current_exceptions_impl(PyObject *module)
1855/*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
1856{
1857 return _PyThread_CurrentExceptions();
1858}
1859
1860/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +02001861sys.call_tracing
1862
1863 func: object
1864 args as funcargs: object(subclass_of='&PyTuple_Type')
1865 /
1866
1867Call func(*args), while tracing is enabled.
1868
1869The tracing state is saved, and restored afterwards. This is intended
1870to be called from a debugger from a checkpoint, to recursively debug
1871some other code.
1872[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001873
1874static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001875sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1876/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001879}
1880
Victor Stinner048afd92016-11-28 11:59:04 +01001881
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001882#ifdef __cplusplus
1883extern "C" {
1884#endif
1885
Tal Einatede0b6f2018-12-31 17:12:08 +02001886/*[clinic input]
1887sys._debugmallocstats
1888
1889Print summary info to stderr about the state of pymalloc's structures.
1890
1891In Py_DEBUG mode, also perform some expensive internal consistency
1892checks.
1893[clinic start generated code]*/
1894
David Malcolm49526f42012-06-22 14:55:41 -04001895static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001896sys__debugmallocstats_impl(PyObject *module)
1897/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001898{
1899#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001900 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001901 fputc('\n', stderr);
1902 }
David Malcolm49526f42012-06-22 14:55:41 -04001903#endif
1904 _PyObject_DebugTypeStats(stderr);
1905
1906 Py_RETURN_NONE;
1907}
David Malcolm49526f42012-06-22 14:55:41 -04001908
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001909#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001910/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001911extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001912#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001913
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001914#ifdef DYNAMIC_EXECUTION_PROFILE
1915/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001916extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001917#endif
1918
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001919#ifdef __cplusplus
1920}
1921#endif
1922
Tal Einatede0b6f2018-12-31 17:12:08 +02001923
1924/*[clinic input]
1925sys._clear_type_cache
1926
1927Clear the internal type lookup cache.
1928[clinic start generated code]*/
1929
Christian Heimes15ebc882008-02-04 18:48:49 +00001930static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001931sys__clear_type_cache_impl(PyObject *module)
1932/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001934 PyType_ClearCache();
1935 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001936}
1937
Tal Einatede0b6f2018-12-31 17:12:08 +02001938/*[clinic input]
1939sys.is_finalizing
1940
1941Return True if Python is exiting.
1942[clinic start generated code]*/
1943
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001944static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001945sys_is_finalizing_impl(PyObject *module)
1946/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001947{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001948 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001949}
1950
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001951#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001952/*[clinic input]
1953sys.getandroidapilevel
1954
1955Return the build time API version of Android as an integer.
1956[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001957
1958static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001959sys_getandroidapilevel_impl(PyObject *module)
1960/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001961{
1962 return PyLong_FromLong(ANDROID_API_LEVEL);
1963}
1964#endif /* ANDROID_API_LEVEL */
1965
1966
Steve Dowerb82e17e2019-05-23 08:45:22 -07001967
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001968static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001970 SYS_ADDAUDITHOOK_METHODDEF
1971 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001972 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001973 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001974 SYS__CLEAR_TYPE_CACHE_METHODDEF
1975 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001976 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001977 SYS_DISPLAYHOOK_METHODDEF
1978 SYS_EXC_INFO_METHODDEF
1979 SYS_EXCEPTHOOK_METHODDEF
1980 SYS_EXIT_METHODDEF
1981 SYS_GETDEFAULTENCODING_METHODDEF
1982 SYS_GETDLOPENFLAGS_METHODDEF
1983 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001984#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001986#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001987 SYS_GETFILESYSTEMENCODING_METHODDEF
1988 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001989#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001991#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001992 SYS_GETTOTALREFCOUNT_METHODDEF
1993 SYS_GETREFCOUNT_METHODDEF
1994 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001995 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001997 SYS__GETFRAME_METHODDEF
1998 SYS_GETWINDOWSVERSION_METHODDEF
1999 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
2000 SYS_INTERN_METHODDEF
2001 SYS_IS_FINALIZING_METHODDEF
2002 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002003 SYS_SETSWITCHINTERVAL_METHODDEF
2004 SYS_GETSWITCHINTERVAL_METHODDEF
2005 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002007 SYS_GETPROFILE_METHODDEF
2008 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002010 SYS_GETTRACE_METHODDEF
2011 SYS_CALL_TRACING_METHODDEF
2012 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002013 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2014 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002015 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002016 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002017 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2018 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002019 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002021};
2022
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002023static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002024list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 PyObject *list = PyList_New(0);
2027 int i;
2028 if (list == NULL)
2029 return NULL;
2030 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2031 PyObject *name = PyUnicode_FromString(
2032 PyImport_Inittab[i].name);
2033 if (name == NULL)
2034 break;
2035 PyList_Append(list, name);
2036 Py_DECREF(name);
2037 }
2038 if (PyList_Sort(list) != 0) {
2039 Py_DECREF(list);
2040 list = NULL;
2041 }
2042 if (list) {
2043 PyObject *v = PyList_AsTuple(list);
2044 Py_DECREF(list);
2045 list = v;
2046 }
2047 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002048}
2049
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002050/* Pre-initialization support for sys.warnoptions and sys._xoptions
2051 *
2052 * Modern internal code paths:
2053 * These APIs get called after _Py_InitializeCore and get to use the
2054 * regular CPython list, dict, and unicode APIs.
2055 *
2056 * Legacy embedding code paths:
2057 * The multi-phase initialization API isn't public yet, so embedding
2058 * apps still need to be able configure sys.warnoptions and sys._xoptions
2059 * before they call Py_Initialize. To support this, we stash copies of
2060 * the supplied wchar * sequences in linked lists, and then migrate the
2061 * contents of those lists to the sys module in _PyInitializeCore.
2062 *
2063 */
2064
2065struct _preinit_entry {
2066 wchar_t *value;
2067 struct _preinit_entry *next;
2068};
2069
2070typedef struct _preinit_entry *_Py_PreInitEntry;
2071
2072static _Py_PreInitEntry _preinit_warnoptions = NULL;
2073static _Py_PreInitEntry _preinit_xoptions = NULL;
2074
2075static _Py_PreInitEntry
2076_alloc_preinit_entry(const wchar_t *value)
2077{
2078 /* To get this to work, we have to initialize the runtime implicitly */
2079 _PyRuntime_Initialize();
2080
2081 /* Force default allocator, so we can ensure that it also gets used to
2082 * destroy the linked list in _clear_preinit_entries.
2083 */
2084 PyMemAllocatorEx old_alloc;
2085 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2086
2087 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2088 if (node != NULL) {
2089 node->value = _PyMem_RawWcsdup(value);
2090 if (node->value == NULL) {
2091 PyMem_RawFree(node);
2092 node = NULL;
2093 };
2094 };
2095
2096 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2097 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002098}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002099
2100static int
2101_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2102{
2103 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2104 if (new_entry == NULL) {
2105 return -1;
2106 }
2107 /* We maintain the linked list in this order so it's easy to play back
2108 * the add commands in the same order later on in _Py_InitializeCore
2109 */
2110 _Py_PreInitEntry last_entry = *optionlist;
2111 if (last_entry == NULL) {
2112 *optionlist = new_entry;
2113 } else {
2114 while (last_entry->next != NULL) {
2115 last_entry = last_entry->next;
2116 }
2117 last_entry->next = new_entry;
2118 }
2119 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002120}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002121
2122static void
2123_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2124{
2125 _Py_PreInitEntry current = *optionlist;
2126 *optionlist = NULL;
2127 /* Deallocate the nodes and their contents using the default allocator */
2128 PyMemAllocatorEx old_alloc;
2129 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2130 while (current != NULL) {
2131 _Py_PreInitEntry next = current->next;
2132 PyMem_RawFree(current->value);
2133 PyMem_RawFree(current);
2134 current = next;
2135 }
2136 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002137}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002138
Victor Stinner120b7072019-08-23 18:03:08 +01002139
2140PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002141_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002142{
Victor Stinner120b7072019-08-23 18:03:08 +01002143 PyStatus status;
2144 _Py_PreInitEntry entry;
2145
2146 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002147 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002148 if (_PyStatus_EXCEPTION(status)) {
2149 return status;
2150 }
2151 }
2152
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002153 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002154 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002155}
2156
Victor Stinner120b7072019-08-23 18:03:08 +01002157
2158PyStatus
2159_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002160{
Victor Stinner120b7072019-08-23 18:03:08 +01002161 PyStatus status;
2162 _Py_PreInitEntry entry;
2163
2164 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2165 status = PyWideStringList_Append(&config->xoptions, entry->value);
2166 if (_PyStatus_EXCEPTION(status)) {
2167 return status;
2168 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002169 }
2170
Victor Stinner120b7072019-08-23 18:03:08 +01002171 _clear_preinit_entries(&_preinit_xoptions);
2172 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002173}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002174
Victor Stinner120b7072019-08-23 18:03:08 +01002175
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002176static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002177get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002178{
Victor Stinner838f2642019-06-13 22:41:23 +02002179 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002180 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002181 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2182 * interpreter config. When that happens, we need to properly set
2183 * the `warnoptions` reference in the main interpreter config as well.
2184 *
2185 * For Python 3.7, we shouldn't be able to get here due to the
2186 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2187 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2188 * call optional for embedding applications, thus making this
2189 * reachable again.
2190 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002191 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002192 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002193 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002194 }
2195 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002196 Py_DECREF(warnoptions);
2197 return NULL;
2198 }
2199 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002200 }
2201 return warnoptions;
2202}
Guido van Rossum23fff912000-12-15 22:02:05 +00002203
2204void
2205PySys_ResetWarnOptions(void)
2206{
Victor Stinner50b48572018-11-01 01:51:40 +01002207 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002208 if (tstate == NULL) {
2209 _clear_preinit_entries(&_preinit_warnoptions);
2210 return;
2211 }
2212
Victor Stinner838f2642019-06-13 22:41:23 +02002213 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 if (warnoptions == NULL || !PyList_Check(warnoptions))
2215 return;
2216 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002217}
2218
Victor Stinnere1b29952018-10-30 14:31:42 +01002219static int
Victor Stinner838f2642019-06-13 22:41:23 +02002220_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002221{
Victor Stinner838f2642019-06-13 22:41:23 +02002222 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002223 if (warnoptions == NULL) {
2224 return -1;
2225 }
2226 if (PyList_Append(warnoptions, option)) {
2227 return -1;
2228 }
2229 return 0;
2230}
2231
2232void
2233PySys_AddWarnOptionUnicode(PyObject *option)
2234{
Victor Stinner838f2642019-06-13 22:41:23 +02002235 PyThreadState *tstate = _PyThreadState_GET();
2236 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002237 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002238 if (tstate) {
2239 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002240 }
2241 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002242}
2243
2244void
2245PySys_AddWarnOption(const wchar_t *s)
2246{
Victor Stinner50b48572018-11-01 01:51:40 +01002247 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002248 if (tstate == NULL) {
2249 _append_preinit_entry(&_preinit_warnoptions, s);
2250 return;
2251 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002252 PyObject *unicode;
2253 unicode = PyUnicode_FromWideChar(s, -1);
2254 if (unicode == NULL)
2255 return;
2256 PySys_AddWarnOptionUnicode(unicode);
2257 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002258}
2259
Christian Heimes33fe8092008-04-13 13:53:33 +00002260int
2261PySys_HasWarnOptions(void)
2262{
Victor Stinner838f2642019-06-13 22:41:23 +02002263 PyThreadState *tstate = _PyThreadState_GET();
2264 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002265 return (warnoptions != NULL && PyList_Check(warnoptions)
2266 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002267}
2268
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002269static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002270get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002271{
Victor Stinner838f2642019-06-13 22:41:23 +02002272 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002273 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002274 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2275 * interpreter config. When that happens, we need to properly set
2276 * the `xoptions` reference in the main interpreter config as well.
2277 *
2278 * For Python 3.7, we shouldn't be able to get here due to the
2279 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2280 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2281 * call optional for embedding applications, thus making this
2282 * reachable again.
2283 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002284 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002285 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002286 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002287 }
2288 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002289 Py_DECREF(xoptions);
2290 return NULL;
2291 }
2292 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002293 }
2294 return xoptions;
2295}
2296
Victor Stinnere1b29952018-10-30 14:31:42 +01002297static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002298_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002299{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002300 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002301
Victor Stinner838f2642019-06-13 22:41:23 +02002302 PyThreadState *tstate = _PyThreadState_GET();
2303 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002304 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002305 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002306 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002307
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002308 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002309 if (!name_end) {
2310 name = PyUnicode_FromWideChar(s, -1);
2311 value = Py_True;
2312 Py_INCREF(value);
2313 }
2314 else {
2315 name = PyUnicode_FromWideChar(s, name_end - s);
2316 value = PyUnicode_FromWideChar(name_end + 1, -1);
2317 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002318 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002319 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002320 }
2321 if (PyDict_SetItem(opts, name, value) < 0) {
2322 goto error;
2323 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002324 Py_DECREF(name);
2325 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002326 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002327
2328error:
2329 Py_XDECREF(name);
2330 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002331 return -1;
2332}
2333
2334void
2335PySys_AddXOption(const wchar_t *s)
2336{
Victor Stinner50b48572018-11-01 01:51:40 +01002337 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002338 if (tstate == NULL) {
2339 _append_preinit_entry(&_preinit_xoptions, s);
2340 return;
2341 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002342 if (_PySys_AddXOptionWithError(s) < 0) {
2343 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002344 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002345 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002346}
2347
2348PyObject *
2349PySys_GetXOptions(void)
2350{
Victor Stinner838f2642019-06-13 22:41:23 +02002351 PyThreadState *tstate = _PyThreadState_GET();
2352 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002353}
2354
Guido van Rossum40552d01998-08-06 03:34:39 +00002355/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2356 Two literals concatenated works just fine. If you have a K&R compiler
2357 or other abomination that however *does* understand longer strings,
2358 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002359PyDoc_VAR(sys_doc) =
2360PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002361"This module provides access to some objects used or maintained by the\n\
2362interpreter and to functions that interact strongly with the interpreter.\n\
2363\n\
2364Dynamic objects:\n\
2365\n\
2366argv -- command line arguments; argv[0] is the script pathname if known\n\
2367path -- module search path; path[0] is the script directory, else ''\n\
2368modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002369\n\
2370displayhook -- called to show results in an interactive session\n\
2371excepthook -- called to handle any uncaught exception other than SystemExit\n\
2372 To customize printing in an interactive session or to install a custom\n\
2373 top-level exception handler, assign other functions to replace these.\n\
2374\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002375stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002376stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002377stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002378 By assigning other file objects (or objects that behave like files)\n\
2379 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002380\n\
2381last_type -- type of last uncaught exception\n\
2382last_value -- value of last uncaught exception\n\
2383last_traceback -- traceback of last uncaught exception\n\
2384 These three are only available in an interactive session after a\n\
2385 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002386"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002387)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002388/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002389PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002390"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002391Static objects:\n\
2392\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002393builtin_module_names -- tuple of module names built into this interpreter\n\
2394copyright -- copyright notice pertaining to this interpreter\n\
2395exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002396executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002397float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002398float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002399hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002400hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002401implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002402int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002403maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002404maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002405platform -- platform identifier\n\
2406prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002407thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002408version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002409version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002410"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002411)
Steve Dowercc16be82016-09-08 10:35:16 -07002412#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002413/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002414PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002415"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002416winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002417"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002418)
Steve Dowercc16be82016-09-08 10:35:16 -07002419#endif /* MS_COREDLL */
2420#ifdef MS_WINDOWS
2421/* concatenating string here */
2422PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002423"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002424"
2425)
2426#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002427PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002428"__stdin__ -- the original stdin; don't touch!\n\
2429__stdout__ -- the original stdout; don't touch!\n\
2430__stderr__ -- the original stderr; don't touch!\n\
2431__displayhook__ -- the original displayhook; don't touch!\n\
2432__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002433\n\
2434Functions:\n\
2435\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002436displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002437excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002438exc_info() -- return thread-safe information about the current exception\n\
2439exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002440getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002441getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002442getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002443getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002444getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002445gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002446setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002447setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002448setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002449settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002450"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002451)
Fred Drakeccede592000-08-14 20:59:57 +00002452/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002453
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002454
2455PyDoc_STRVAR(flags__doc__,
2456"sys.flags\n\
2457\n\
2458Flags provided through command line arguments or environment vars.");
2459
2460static PyTypeObject FlagsType;
2461
2462static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 {"inspect", "-i"},
2465 {"interactive", "-i"},
2466 {"optimize", "-O or -OO"},
2467 {"dont_write_bytecode", "-B"},
2468 {"no_user_site", "-s"},
2469 {"no_site", "-S"},
2470 {"ignore_environment", "-E"},
2471 {"verbose", "-v"},
Georg Brandl8aa7e992010-12-28 18:30:18 +00002472 {"bytes_warning", "-b"},
2473 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002474 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002475 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002476 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002477 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002479};
2480
2481static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 "sys.flags", /* name */
2483 flags__doc__, /* doc */
2484 flags_fields, /* fields */
Victor Stinner1def7752020-04-23 03:03:24 +02002485 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002486};
2487
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002488static int
2489set_flags_from_config(PyObject *flags, PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002490{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002491 PyInterpreterState *interp = tstate->interp;
2492 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002493 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002494
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002495 // _PySys_UpdateConfig() modifies sys.flags in-place:
2496 // Py_XDECREF() is needed in this case.
2497 Py_ssize_t pos = 0;
2498#define SetFlagObj(expr) \
2499 do { \
2500 PyObject *value = (expr); \
2501 if (value == NULL) { \
2502 return -1; \
2503 } \
2504 Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
2505 PyStructSequence_SET_ITEM(flags, pos, value); \
2506 pos++; \
2507 } while (0)
2508#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002509
Victor Stinnerfbca9082018-08-30 00:50:45 +02002510 SetFlag(config->parser_debug);
2511 SetFlag(config->inspect);
2512 SetFlag(config->interactive);
2513 SetFlag(config->optimization_level);
2514 SetFlag(!config->write_bytecode);
2515 SetFlag(!config->user_site_directory);
2516 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002517 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002518 SetFlag(config->verbose);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002519 SetFlag(config->bytes_warning);
2520 SetFlag(config->quiet);
2521 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002522 SetFlag(config->isolated);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002523 SetFlagObj(PyBool_FromLong(config->dev_mode));
Victor Stinner20004952019-03-26 02:31:11 +01002524 SetFlag(preconfig->utf8_mode);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002525#undef SetFlagObj
Victor Stinner91106cd2017-12-13 12:29:09 +01002526#undef SetFlag
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002527 return 0;
2528}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002529
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002530
2531static PyObject*
2532make_flags(PyThreadState *tstate)
2533{
2534 PyObject *flags = PyStructSequence_New(&FlagsType);
2535 if (flags == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 return NULL;
2537 }
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002538
2539 if (set_flags_from_config(flags, tstate) < 0) {
2540 Py_DECREF(flags);
2541 return NULL;
2542 }
2543 return flags;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002544}
2545
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002546
Eric Smith0e5b5622009-02-06 01:32:42 +00002547PyDoc_STRVAR(version_info__doc__,
2548"sys.version_info\n\
2549\n\
2550Version information as a named tuple.");
2551
2552static PyTypeObject VersionInfoType;
2553
2554static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 {"major", "Major release number"},
2556 {"minor", "Minor release number"},
2557 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002558 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 {"serial", "Serial release number"},
2560 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002561};
2562
2563static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 "sys.version_info", /* name */
2565 version_info__doc__, /* doc */
2566 version_info_fields, /* fields */
2567 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002568};
2569
2570static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002571make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 PyObject *version_info;
2574 char *s;
2575 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002577 version_info = PyStructSequence_New(&VersionInfoType);
2578 if (version_info == NULL) {
2579 return NULL;
2580 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 /*
2583 * These release level checks are mutually exclusive and cover
2584 * the field, so don't get too fancy with the pre-processor!
2585 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002586#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002587 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002588#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002590#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002592#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002594#endif
2595
2596#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002598#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 SetIntItem(PY_MAJOR_VERSION);
2602 SetIntItem(PY_MINOR_VERSION);
2603 SetIntItem(PY_MICRO_VERSION);
2604 SetStrItem(s);
2605 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002606#undef SetIntItem
2607#undef SetStrItem
2608
Victor Stinner838f2642019-06-13 22:41:23 +02002609 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 Py_CLEAR(version_info);
2611 return NULL;
2612 }
2613 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002614}
2615
Brett Cannon3adc7b72012-07-09 14:22:12 -04002616/* sys.implementation values */
2617#define NAME "cpython"
2618const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002619#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2620#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002621#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002622const char *_PySys_ImplCacheTag = TAG;
2623#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002624#undef MAJOR
2625#undef MINOR
2626#undef TAG
2627
Barry Warsaw409da152012-06-03 16:18:47 -04002628static PyObject *
2629make_impl_info(PyObject *version_info)
2630{
2631 int res;
2632 PyObject *impl_info, *value, *ns;
2633
2634 impl_info = PyDict_New();
2635 if (impl_info == NULL)
2636 return NULL;
2637
2638 /* populate the dict */
2639
Brett Cannon3adc7b72012-07-09 14:22:12 -04002640 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002641 if (value == NULL)
2642 goto error;
2643 res = PyDict_SetItemString(impl_info, "name", value);
2644 Py_DECREF(value);
2645 if (res < 0)
2646 goto error;
2647
Brett Cannon3adc7b72012-07-09 14:22:12 -04002648 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002649 if (value == NULL)
2650 goto error;
2651 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2652 Py_DECREF(value);
2653 if (res < 0)
2654 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002655
2656 res = PyDict_SetItemString(impl_info, "version", version_info);
2657 if (res < 0)
2658 goto error;
2659
2660 value = PyLong_FromLong(PY_VERSION_HEX);
2661 if (value == NULL)
2662 goto error;
2663 res = PyDict_SetItemString(impl_info, "hexversion", value);
2664 Py_DECREF(value);
2665 if (res < 0)
2666 goto error;
2667
doko@ubuntu.com55532312016-06-14 08:55:19 +02002668#ifdef MULTIARCH
2669 value = PyUnicode_FromString(MULTIARCH);
2670 if (value == NULL)
2671 goto error;
2672 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2673 Py_DECREF(value);
2674 if (res < 0)
2675 goto error;
2676#endif
2677
Barry Warsaw409da152012-06-03 16:18:47 -04002678 /* dict ready */
2679
2680 ns = _PyNamespace_New(impl_info);
2681 Py_DECREF(impl_info);
2682 return ns;
2683
2684error:
2685 Py_CLEAR(impl_info);
2686 return NULL;
2687}
2688
Martin v. Löwis1a214512008-06-11 05:26:20 +00002689static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 PyModuleDef_HEAD_INIT,
2691 "sys",
2692 sys_doc,
2693 -1, /* multiple "initialization" just copies the module dict. */
2694 sys_methods,
2695 NULL,
2696 NULL,
2697 NULL,
2698 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002699};
2700
Eric Snow6b4be192017-05-22 21:36:03 -07002701/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002702#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002703 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002704 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002705 if (v == NULL) { \
2706 goto err_occurred; \
2707 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002708 res = PyDict_SetItemString(sysdict, key, v); \
2709 Py_DECREF(v); \
2710 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002711 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002712 } \
2713 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002714
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002715#define SET_SYS_FROM_STRING(key, value) \
2716 SET_SYS(key, PyUnicode_FromString(value))
2717
Victor Stinner331a6a52019-05-27 16:39:22 +02002718static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002719_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002720{
Victor Stinnerab672812019-01-23 15:04:40 +01002721 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002722 int res;
2723
Nick Coghland6009512014-11-20 21:39:37 +10002724 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002725
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002726#define COPY_SYS_ATTR(tokey, fromkey) \
2727 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002728
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002729 COPY_SYS_ATTR("__displayhook__", "displayhook");
2730 COPY_SYS_ATTR("__excepthook__", "excepthook");
2731 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2732 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2733
2734#undef COPY_SYS_ATTR
2735
2736 SET_SYS_FROM_STRING("version", Py_GetVersion());
2737 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2738 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2739 _Py_gitversion()));
2740 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2741 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2742 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2743 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2744 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2745 SET_SYS("float_info", PyFloat_GetInfo());
2746 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002747 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002748 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002749 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2750 goto type_init_failed;
2751 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002752 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002753 SET_SYS("hash_info", get_hash_info(tstate));
2754 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2755 SET_SYS("builtin_module_names", list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002756#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002757 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002758#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002759 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002760#endif
Fred Drake099325e2000-08-14 15:47:03 +00002761
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002762#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002763 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2764 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002765#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002766#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002767 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002768#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002769
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002771 if (VersionInfoType.tp_name == NULL) {
2772 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002773 &version_info_desc) < 0) {
2774 goto type_init_failed;
2775 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002776 }
Victor Stinner838f2642019-06-13 22:41:23 +02002777 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002778 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 /* prevent user from creating new instances */
2780 VersionInfoType.tp_init = NULL;
2781 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002782 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002783 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2784 _PyErr_Clear(tstate);
2785 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002786
Barry Warsaw409da152012-06-03 16:18:47 -04002787 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002788 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002789
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002790 // sys.flags: updated in-place later by _PySys_UpdateConfig()
Victor Stinner1c8f0592013-07-22 22:24:54 +02002791 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002792 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2793 goto type_init_failed;
2794 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002795 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002796 SET_SYS("flags", make_flags(tstate));
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002797 /* prevent user from creating new instances */
2798 FlagsType.tp_init = NULL;
2799 FlagsType.tp_new = NULL;
2800 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2801 if (res < 0) {
2802 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2803 goto err_occurred;
2804 }
2805 _PyErr_Clear(tstate);
2806 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002807
2808#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 /* getwindowsversion */
2810 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002811 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002812 &windows_version_desc) < 0) {
2813 goto type_init_failed;
2814 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002815 /* prevent user from creating new instances */
2816 WindowsVersionType.tp_init = NULL;
2817 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002818 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002819 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002820 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2821 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002822 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002823#endif
2824
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002826#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002827 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002828#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002829 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002830#endif
2831
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002832 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002833
Yury Selivanoveb636452016-09-08 22:01:51 -07002834 /* initialize asyncgen_hooks */
2835 if (AsyncGenHooksType.tp_name == NULL) {
2836 if (PyStructSequence_InitType2(
2837 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002838 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002839 }
2840 }
2841
Victor Stinneref75a622020-11-12 15:14:13 +01002842 /* adding sys.path_hooks and sys.path_importer_cache */
2843 SET_SYS("meta_path", PyList_New(0));
2844 SET_SYS("path_importer_cache", PyDict_New());
2845 SET_SYS("path_hooks", PyList_New(0));
2846
Victor Stinner838f2642019-06-13 22:41:23 +02002847 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002848 goto err_occurred;
2849 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002850 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002851
2852type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002853 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002854
2855err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002856 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002857}
2858
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002859static int
2860sys_add_xoption(PyObject *opts, const wchar_t *s)
2861{
2862 PyObject *name, *value;
2863
2864 const wchar_t *name_end = wcschr(s, L'=');
2865 if (!name_end) {
2866 name = PyUnicode_FromWideChar(s, -1);
2867 value = Py_True;
2868 Py_INCREF(value);
2869 }
2870 else {
2871 name = PyUnicode_FromWideChar(s, name_end - s);
2872 value = PyUnicode_FromWideChar(name_end + 1, -1);
2873 }
2874 if (name == NULL || value == NULL) {
2875 goto error;
2876 }
2877 if (PyDict_SetItem(opts, name, value) < 0) {
2878 goto error;
2879 }
2880 Py_DECREF(name);
2881 Py_DECREF(value);
2882 return 0;
2883
2884error:
2885 Py_XDECREF(name);
2886 Py_XDECREF(value);
2887 return -1;
2888}
2889
2890
2891static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002892sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002893{
2894 Py_ssize_t nxoption = config->xoptions.length;
2895 wchar_t * const * xoptions = config->xoptions.items;
2896 PyObject *dict = PyDict_New();
2897 if (dict == NULL) {
2898 return NULL;
2899 }
2900
2901 for (Py_ssize_t i=0; i < nxoption; i++) {
2902 const wchar_t *option = xoptions[i];
2903 if (sys_add_xoption(dict, option) < 0) {
2904 Py_DECREF(dict);
2905 return NULL;
2906 }
2907 }
2908
2909 return dict;
2910}
2911
2912
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002913// Update sys attributes for a new PyConfig configuration.
2914// This function also adds attributes that _PySys_InitCore() didn't add.
Eric Snow6b4be192017-05-22 21:36:03 -07002915int
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002916_PySys_UpdateConfig(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002917{
Victor Stinner838f2642019-06-13 22:41:23 +02002918 PyObject *sysdict = tstate->interp->sysdict;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002919 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002920 int res;
2921
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002922#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002923 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002924
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002925#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002926 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002927
Victor Stinner9e1b8282020-11-10 13:21:52 +01002928#define COPY_WSTR(SYS_ATTR, WSTR) \
2929 if (WSTR != NULL) { \
2930 SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
2931 }
2932
Victor Stinnerf3cb8142020-11-05 18:12:33 +01002933 if (config->module_search_paths_set) {
2934 COPY_LIST("path", config->module_search_paths);
2935 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002936
Victor Stinner9e1b8282020-11-10 13:21:52 +01002937 COPY_WSTR("executable", config->executable);
2938 COPY_WSTR("_base_executable", config->base_executable);
2939 COPY_WSTR("prefix", config->prefix);
2940 COPY_WSTR("base_prefix", config->base_prefix);
2941 COPY_WSTR("exec_prefix", config->exec_prefix);
2942 COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
2943 COPY_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002944
Carl Meyerb193fa92018-06-15 22:40:56 -06002945 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002946 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002947 } else {
2948 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2949 }
2950
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002951 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002952 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002953 COPY_LIST("warnoptions", config->warnoptions);
2954
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002955 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002956
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002957#undef SET_SYS_FROM_WSTR
Victor Stinner9e1b8282020-11-10 13:21:52 +01002958#undef COPY_LIST
2959#undef COPY_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002960
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002961 // sys.flags
2962 PyObject *flags = _PySys_GetObject(tstate, "flags"); // borrowed ref
2963 if (flags == NULL) {
2964 return -1;
2965 }
2966 if (set_flags_from_config(flags, tstate) < 0) {
2967 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002968 }
2969
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002970 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002971
Victor Stinner838f2642019-06-13 22:41:23 +02002972 if (_PyErr_Occurred(tstate)) {
2973 goto err_occurred;
2974 }
2975
Eric Snow6b4be192017-05-22 21:36:03 -07002976 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002977
2978err_occurred:
2979 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002980}
2981
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002982#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01002983#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002984
Victor Stinnerab672812019-01-23 15:04:40 +01002985
2986/* Set up a preliminary stderr printer until we have enough
2987 infrastructure for the io module in place.
2988
2989 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002990static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002991_PySys_SetPreliminaryStderr(PyObject *sysdict)
2992{
2993 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2994 if (pstderr == NULL) {
2995 goto error;
2996 }
2997 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2998 goto error;
2999 }
3000 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3001 goto error;
3002 }
3003 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003004 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003005
3006error:
3007 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003008 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003009}
3010
3011
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003012/* Create sys module without all attributes.
3013 _PySys_UpdateConfig() should be called later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003014PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01003015_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003016{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003017 assert(!_PyErr_Occurred(tstate));
3018
Victor Stinnerb45d2592019-06-20 00:05:23 +02003019 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003020
Victor Stinnerab672812019-01-23 15:04:40 +01003021 PyObject *modules = PyDict_New();
3022 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003023 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003024 }
3025 interp->modules = modules;
3026
3027 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3028 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003029 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003030 }
3031
3032 PyObject *sysdict = PyModule_GetDict(sysmod);
3033 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003034 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003035 }
3036 Py_INCREF(sysdict);
3037 interp->sysdict = sysdict;
3038
3039 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003040 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003041 }
3042
Victor Stinner331a6a52019-05-27 16:39:22 +02003043 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3044 if (_PyStatus_EXCEPTION(status)) {
3045 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003046 }
3047
Victor Stinner01b1cc12019-11-20 02:27:56 +01003048 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003049 if (_PyStatus_EXCEPTION(status)) {
3050 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003051 }
3052
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003053 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3054 goto error;
3055 }
3056
3057 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003058
3059 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003060 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003061
3062error:
3063 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003064}
3065
3066
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003067static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003068makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003070 int i, n;
3071 const wchar_t *p;
3072 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003074 n = 1;
3075 p = path;
3076 while ((p = wcschr(p, delim)) != NULL) {
3077 n++;
3078 p++;
3079 }
3080 v = PyList_New(n);
3081 if (v == NULL)
3082 return NULL;
3083 for (i = 0; ; i++) {
3084 p = wcschr(path, delim);
3085 if (p == NULL)
3086 p = path + wcslen(path); /* End of string */
3087 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3088 if (w == NULL) {
3089 Py_DECREF(v);
3090 return NULL;
3091 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003092 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003093 if (*p == '\0')
3094 break;
3095 path = p+1;
3096 }
3097 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003098}
3099
3100void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003101PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003103 PyObject *v;
3104 if ((v = makepathobject(path, DELIM)) == NULL)
3105 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003106 PyThreadState *tstate = _PyThreadState_GET();
3107 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003111}
3112
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003113static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003114make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003115{
Victor Stinner74f65682019-03-15 15:08:05 +01003116 PyObject *list = PyList_New(argc);
3117 if (list == NULL) {
3118 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003119 }
Victor Stinner74f65682019-03-15 15:08:05 +01003120
3121 for (Py_ssize_t i = 0; i < argc; i++) {
3122 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3123 if (v == NULL) {
3124 Py_DECREF(list);
3125 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003126 }
Victor Stinner74f65682019-03-15 15:08:05 +01003127 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
Victor Stinner74f65682019-03-15 15:08:05 +01003129 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003130}
3131
Victor Stinner11a247d2017-12-13 21:05:57 +01003132void
3133PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003134{
Victor Stinnerc4868252019-08-23 11:04:16 +01003135 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003136 PyThreadState *tstate = _PyThreadState_GET();
3137
Victor Stinner74f65682019-03-15 15:08:05 +01003138 if (argc < 1 || argv == NULL) {
3139 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003140 argv = empty_argv;
3141 argc = 1;
3142 }
3143
3144 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003145 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003146 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003147 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02003148 if (sys_set_object_str(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003149 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003150 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003151 }
3152 Py_DECREF(av);
3153
3154 if (updatepath) {
3155 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3156 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003157 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003158 PyObject *path0 = NULL;
3159 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3160 if (path0 == NULL) {
3161 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003162 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003163
Victor Stinner838f2642019-06-13 22:41:23 +02003164 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003165 if (sys_path != NULL) {
3166 if (PyList_Insert(sys_path, 0, path0) < 0) {
3167 Py_DECREF(path0);
3168 Py_FatalError("can't prepend path0 to sys.path");
3169 }
3170 }
3171 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003172 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003173 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003174}
Guido van Rossuma890e681998-05-12 14:59:24 +00003175
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003176void
3177PySys_SetArgv(int argc, wchar_t **argv)
3178{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003179 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003180}
3181
Victor Stinner14284c22010-04-23 12:02:30 +00003182/* Reimplementation of PyFile_WriteString() no calling indirectly
3183 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3184
3185static int
Victor Stinner79766632010-08-16 17:36:42 +00003186sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003187{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003188 if (file == NULL)
3189 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003190 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003191 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003192 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003193 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003195 Py_DECREF(result);
3196 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003197}
3198
Victor Stinner79766632010-08-16 17:36:42 +00003199static int
3200sys_pyfile_write(const char *text, PyObject *file)
3201{
3202 PyObject *unicode = NULL;
3203 int err;
3204
3205 if (file == NULL)
3206 return -1;
3207
3208 unicode = PyUnicode_FromString(text);
3209 if (unicode == NULL)
3210 return -1;
3211
3212 err = sys_pyfile_write_unicode(unicode, file);
3213 Py_DECREF(unicode);
3214 return err;
3215}
Guido van Rossuma890e681998-05-12 14:59:24 +00003216
3217/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3218 Adapted from code submitted by Just van Rossum.
3219
3220 PySys_WriteStdout(format, ...)
3221 PySys_WriteStderr(format, ...)
3222
3223 The first function writes to sys.stdout; the second to sys.stderr. When
3224 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003225 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003226
Victor Stinner14284c22010-04-23 12:02:30 +00003227 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003228 signal handlers: they may raise a new exception whereas sys_write()
3229 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003230
Guido van Rossuma890e681998-05-12 14:59:24 +00003231 Both take a printf-style format string as their first argument followed
3232 by a variable length argument list determined by the format string.
3233
3234 *** WARNING ***
3235
3236 The format should limit the total size of the formatted output string to
3237 1000 bytes. In particular, this means that no unrestricted "%s" formats
3238 should occur; these should be limited using "%.<N>s where <N> is a
3239 decimal number calculated so that <N> plus the maximum size of other
3240 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3241 which can print hundreds of digits for very large numbers.
3242
3243 */
3244
3245static void
Victor Stinner09054372013-11-06 22:41:44 +01003246sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003248 PyObject *file;
3249 PyObject *error_type, *error_value, *error_traceback;
3250 char buffer[1001];
3251 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003252 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003253
Victor Stinner838f2642019-06-13 22:41:23 +02003254 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3255 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003256 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3257 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003258 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003259 fputs(buffer, fp);
3260 }
3261 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3262 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003263 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 }
Victor Stinner838f2642019-06-13 22:41:23 +02003266 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003267}
3268
3269void
Guido van Rossuma890e681998-05-12 14:59:24 +00003270PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003273
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003275 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003277}
3278
3279void
Guido van Rossuma890e681998-05-12 14:59:24 +00003280PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003285 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003286 va_end(va);
3287}
3288
3289static void
Victor Stinner09054372013-11-06 22:41:44 +01003290sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003291{
3292 PyObject *file, *message;
3293 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003294 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003295 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003296
Victor Stinner838f2642019-06-13 22:41:23 +02003297 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3298 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003299 message = PyUnicode_FromFormatV(format, va);
3300 if (message != NULL) {
3301 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003302 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003303 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003304 if (utf8 != NULL)
3305 fputs(utf8, fp);
3306 }
3307 Py_DECREF(message);
3308 }
Victor Stinner838f2642019-06-13 22:41:23 +02003309 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003310}
3311
3312void
3313PySys_FormatStdout(const char *format, ...)
3314{
3315 va_list va;
3316
3317 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003318 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003319 va_end(va);
3320}
3321
3322void
3323PySys_FormatStderr(const char *format, ...)
3324{
3325 va_list va;
3326
3327 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003328 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003329 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003330}