blob: f05b33a9aacf1de1f93b3db2f23302740410ebef [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{
Tal Einatede0b6f2018-12-31 17:12:08 +02001184 int mark;
Victor Stinner838f2642019-06-13 22:41:23 +02001185 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001186
Victor Stinner50856d52015-10-13 00:11:21 +02001187 if (new_limit < 1) {
Victor Stinner838f2642019-06-13 22:41:23 +02001188 _PyErr_SetString(tstate, PyExc_ValueError,
1189 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 return NULL;
1191 }
Victor Stinner50856d52015-10-13 00:11:21 +02001192
1193 /* Issue #25274: When the recursion depth hits the recursion limit in
1194 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1195 set to 1 and a RecursionError is raised. The overflowed flag is reset
1196 to 0 when the recursion depth goes below the low-water mark: see
1197 Py_LeaveRecursiveCall().
1198
1199 Reject too low new limit if the current recursion depth is higher than
1200 the new low-water mark. Otherwise it may not be possible anymore to
1201 reset the overflowed flag to 0. */
1202 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50856d52015-10-13 00:11:21 +02001203 if (tstate->recursion_depth >= mark) {
Victor Stinner838f2642019-06-13 22:41:23 +02001204 _PyErr_Format(tstate, PyExc_RecursionError,
1205 "cannot set the recursion limit to %i at "
1206 "the recursion depth %i: the limit is too low",
1207 new_limit, tstate->recursion_depth);
Victor Stinner50856d52015-10-13 00:11:21 +02001208 return NULL;
1209 }
1210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001212 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001213}
1214
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001215/*[clinic input]
1216sys.set_coroutine_origin_tracking_depth
1217
1218 depth: int
1219
1220Enable or disable origin tracking for coroutine objects in this thread.
1221
Tal Einatede0b6f2018-12-31 17:12:08 +02001222Coroutine objects will track 'depth' frames of traceback information
1223about where they came from, available in their cr_origin attribute.
1224
1225Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001226[clinic start generated code]*/
1227
1228static PyObject *
1229sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001230/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001231{
Victor Stinner838f2642019-06-13 22:41:23 +02001232 PyThreadState *tstate = _PyThreadState_GET();
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001233 if (depth < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001234 _PyErr_SetString(tstate, PyExc_ValueError, "depth must be >= 0");
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001235 return NULL;
1236 }
Victor Stinner838f2642019-06-13 22:41:23 +02001237 _PyEval_SetCoroutineOriginTrackingDepth(tstate, depth);
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001238 Py_RETURN_NONE;
1239}
1240
1241/*[clinic input]
1242sys.get_coroutine_origin_tracking_depth -> int
1243
1244Check status of origin tracking for coroutine objects in this thread.
1245[clinic start generated code]*/
1246
1247static int
1248sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1249/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1250{
1251 return _PyEval_GetCoroutineOriginTrackingDepth();
1252}
1253
Yury Selivanoveb636452016-09-08 22:01:51 -07001254static PyTypeObject AsyncGenHooksType;
1255
1256PyDoc_STRVAR(asyncgen_hooks_doc,
1257"asyncgen_hooks\n\
1258\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001259A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001260generators hooks. The attributes are read only.");
1261
1262static PyStructSequence_Field asyncgen_hooks_fields[] = {
1263 {"firstiter", "Hook to intercept first iteration"},
1264 {"finalizer", "Hook to intercept finalization"},
1265 {0}
1266};
1267
1268static PyStructSequence_Desc asyncgen_hooks_desc = {
1269 "asyncgen_hooks", /* name */
1270 asyncgen_hooks_doc, /* doc */
1271 asyncgen_hooks_fields , /* fields */
1272 2
1273};
1274
Yury Selivanoveb636452016-09-08 22:01:51 -07001275static PyObject *
1276sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1277{
1278 static char *keywords[] = {"firstiter", "finalizer", NULL};
1279 PyObject *firstiter = NULL;
1280 PyObject *finalizer = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001281 PyThreadState *tstate = _PyThreadState_GET();
Yury Selivanoveb636452016-09-08 22:01:51 -07001282
1283 if (!PyArg_ParseTupleAndKeywords(
1284 args, kw, "|OO", keywords,
1285 &firstiter, &finalizer)) {
1286 return NULL;
1287 }
1288
1289 if (finalizer && finalizer != Py_None) {
1290 if (!PyCallable_Check(finalizer)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001291 _PyErr_Format(tstate, PyExc_TypeError,
1292 "callable finalizer expected, got %.50s",
1293 Py_TYPE(finalizer)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001294 return NULL;
1295 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001296 if (_PyEval_SetAsyncGenFinalizer(finalizer) < 0) {
1297 return NULL;
1298 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001299 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001300 else if (finalizer == Py_None && _PyEval_SetAsyncGenFinalizer(NULL) < 0) {
1301 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001302 }
1303
1304 if (firstiter && firstiter != Py_None) {
1305 if (!PyCallable_Check(firstiter)) {
Victor Stinner838f2642019-06-13 22:41:23 +02001306 _PyErr_Format(tstate, PyExc_TypeError,
1307 "callable firstiter expected, got %.50s",
1308 Py_TYPE(firstiter)->tp_name);
Yury Selivanoveb636452016-09-08 22:01:51 -07001309 return NULL;
1310 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001311 if (_PyEval_SetAsyncGenFirstiter(firstiter) < 0) {
1312 return NULL;
1313 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001314 }
Zackery Spytz79ceccd2020-03-26 06:11:13 -06001315 else if (firstiter == Py_None && _PyEval_SetAsyncGenFirstiter(NULL) < 0) {
1316 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001317 }
1318
1319 Py_RETURN_NONE;
1320}
1321
1322PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001323"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001324\n\
1325Set a finalizer for async generators objects."
1326);
1327
Tal Einatede0b6f2018-12-31 17:12:08 +02001328/*[clinic input]
1329sys.get_asyncgen_hooks
1330
1331Return the installed asynchronous generators hooks.
1332
1333This returns a namedtuple of the form (firstiter, finalizer).
1334[clinic start generated code]*/
1335
Yury Selivanoveb636452016-09-08 22:01:51 -07001336static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001337sys_get_asyncgen_hooks_impl(PyObject *module)
1338/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001339{
1340 PyObject *res;
1341 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1342 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1343
1344 res = PyStructSequence_New(&AsyncGenHooksType);
1345 if (res == NULL) {
1346 return NULL;
1347 }
1348
1349 if (firstiter == NULL) {
1350 firstiter = Py_None;
1351 }
1352
1353 if (finalizer == NULL) {
1354 finalizer = Py_None;
1355 }
1356
1357 Py_INCREF(firstiter);
1358 PyStructSequence_SET_ITEM(res, 0, firstiter);
1359
1360 Py_INCREF(finalizer);
1361 PyStructSequence_SET_ITEM(res, 1, finalizer);
1362
1363 return res;
1364}
1365
Yury Selivanoveb636452016-09-08 22:01:51 -07001366
Mark Dickinsondc787d22010-05-23 13:33:13 +00001367static PyTypeObject Hash_InfoType;
1368
1369PyDoc_STRVAR(hash_info_doc,
1370"hash_info\n\
1371\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07001372A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001373hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001374
1375static PyStructSequence_Field hash_info_fields[] = {
1376 {"width", "width of the type used for hashing, in bits"},
1377 {"modulus", "prime number giving the modulus on which the hash "
1378 "function is based"},
1379 {"inf", "value to be used for hash of a positive infinity"},
1380 {"nan", "value to be used for hash of a nan"},
1381 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001382 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1383 "memoryviews"},
1384 {"hash_bits", "internal output size of hash algorithm"},
1385 {"seed_bits", "seed size of hash algorithm"},
1386 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001387 {NULL, NULL}
1388};
1389
1390static PyStructSequence_Desc hash_info_desc = {
1391 "sys.hash_info",
1392 hash_info_doc,
1393 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001394 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001395};
1396
Matthias Klosed885e952010-07-06 10:53:30 +00001397static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02001398get_hash_info(PyThreadState *tstate)
Mark Dickinsondc787d22010-05-23 13:33:13 +00001399{
1400 PyObject *hash_info;
1401 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001402 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001403 hash_info = PyStructSequence_New(&Hash_InfoType);
1404 if (hash_info == NULL)
1405 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001406 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001407 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001408 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001409 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001410 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001411 PyStructSequence_SET_ITEM(hash_info, field++,
1412 PyLong_FromLong(_PyHASH_INF));
1413 PyStructSequence_SET_ITEM(hash_info, field++,
1414 PyLong_FromLong(_PyHASH_NAN));
1415 PyStructSequence_SET_ITEM(hash_info, field++,
1416 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001417 PyStructSequence_SET_ITEM(hash_info, field++,
1418 PyUnicode_FromString(hashfunc->name));
1419 PyStructSequence_SET_ITEM(hash_info, field++,
1420 PyLong_FromLong(hashfunc->hash_bits));
1421 PyStructSequence_SET_ITEM(hash_info, field++,
1422 PyLong_FromLong(hashfunc->seed_bits));
1423 PyStructSequence_SET_ITEM(hash_info, field++,
1424 PyLong_FromLong(Py_HASH_CUTOFF));
Victor Stinner838f2642019-06-13 22:41:23 +02001425 if (_PyErr_Occurred(tstate)) {
Mark Dickinsondc787d22010-05-23 13:33:13 +00001426 Py_CLEAR(hash_info);
1427 return NULL;
1428 }
1429 return hash_info;
1430}
Tal Einatede0b6f2018-12-31 17:12:08 +02001431/*[clinic input]
1432sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001433
Tal Einatede0b6f2018-12-31 17:12:08 +02001434Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001435
Tal Einatede0b6f2018-12-31 17:12:08 +02001436The recursion limit is the maximum depth of the Python interpreter
1437stack. This limit prevents infinite recursion from causing an overflow
1438of the C stack and crashing Python.
1439[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001440
1441static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001442sys_getrecursionlimit_impl(PyObject *module)
1443/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001444{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001446}
1447
Mark Hammond8696ebc2002-10-08 02:44:31 +00001448#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001449
Eric Smithf7bb5782010-01-27 00:44:57 +00001450static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1451
1452static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 {"major", "Major version number"},
1454 {"minor", "Minor version number"},
1455 {"build", "Build number"},
1456 {"platform", "Operating system platform"},
1457 {"service_pack", "Latest Service Pack installed on the system"},
1458 {"service_pack_major", "Service Pack major version number"},
1459 {"service_pack_minor", "Service Pack minor version number"},
1460 {"suite_mask", "Bit mask identifying available product suites"},
1461 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001462 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001464};
1465
1466static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001467 "sys.getwindowsversion", /* name */
1468 sys_getwindowsversion__doc__, /* doc */
1469 windows_version_fields, /* fields */
1470 5 /* For backward compatibility,
1471 only the first 5 items are accessible
1472 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001473};
1474
Steve Dower3e96f322015-03-02 08:01:10 -08001475/* Disable deprecation warnings about GetVersionEx as the result is
1476 being passed straight through to the caller, who is responsible for
1477 using it correctly. */
1478#pragma warning(push)
1479#pragma warning(disable:4996)
1480
Tal Einatede0b6f2018-12-31 17:12:08 +02001481/*[clinic input]
1482sys.getwindowsversion
1483
1484Return info about the running version of Windows as a named tuple.
1485
1486The members are named: major, minor, build, platform, service_pack,
1487service_pack_major, service_pack_minor, suite_mask, product_type and
1488platform_version. For backward compatibility, only the first 5 items
1489are available by indexing. All elements are numbers, except
1490service_pack and platform_type which are strings, and platform_version
1491which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1492workstation, 2 for a domain controller, 3 for a server.
1493Platform_version is a 3-tuple containing a version number that is
1494intended for identifying the OS rather than feature detection.
1495[clinic start generated code]*/
1496
Mark Hammond8696ebc2002-10-08 02:44:31 +00001497static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001498sys_getwindowsversion_impl(PyObject *module)
1499/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 PyObject *version;
1502 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001503 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001504 DWORD realMajor, realMinor, realBuild;
1505 HANDLE hKernel32;
1506 wchar_t kernel32_path[MAX_PATH];
1507 LPVOID verblock;
1508 DWORD verblock_size;
Victor Stinner838f2642019-06-13 22:41:23 +02001509 PyThreadState *tstate = _PyThreadState_GET();
Steve Dower74f4af72016-09-17 17:27:48 -07001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001512 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 version = PyStructSequence_New(&WindowsVersionType);
1516 if (version == NULL)
1517 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1520 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1521 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1522 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001523 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1525 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1526 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1527 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001528
Steve Dower74f4af72016-09-17 17:27:48 -07001529 realMajor = ver.dwMajorVersion;
1530 realMinor = ver.dwMinorVersion;
1531 realBuild = ver.dwBuildNumber;
1532
1533 // GetVersion will lie if we are running in a compatibility mode.
1534 // We need to read the version info from a system file resource
1535 // to accurately identify the OS version. If we fail for any reason,
1536 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001537 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001538 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001539 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001540 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1541 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1542 (verblock = PyMem_RawMalloc(verblock_size))) {
1543 VS_FIXEDFILEINFO *ffi;
1544 UINT ffi_len;
1545
1546 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1547 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1548 realMajor = HIWORD(ffi->dwProductVersionMS);
1549 realMinor = LOWORD(ffi->dwProductVersionMS);
1550 realBuild = HIWORD(ffi->dwProductVersionLS);
1551 }
1552 PyMem_RawFree(verblock);
1553 }
Segev Finer48fb7662017-06-04 20:52:27 +03001554 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1555 realMajor,
1556 realMinor,
1557 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001558 ));
1559
Victor Stinner838f2642019-06-13 22:41:23 +02001560 if (_PyErr_Occurred(tstate)) {
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001561 Py_DECREF(version);
1562 return NULL;
1563 }
Steve Dower74f4af72016-09-17 17:27:48 -07001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001566}
1567
Steve Dower3e96f322015-03-02 08:01:10 -08001568#pragma warning(pop)
1569
Tal Einatede0b6f2018-12-31 17:12:08 +02001570/*[clinic input]
1571sys._enablelegacywindowsfsencoding
1572
1573Changes the default filesystem encoding to mbcs:replace.
1574
1575This is done for consistency with earlier versions of Python. See PEP
1576529 for more information.
1577
1578This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1579environment variable before launching Python.
1580[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001581
1582static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001583sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1584/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001585{
Victor Stinner709d23d2019-05-02 14:56:30 -04001586 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001587 return NULL;
1588 }
Steve Dowercc16be82016-09-08 10:35:16 -07001589 Py_RETURN_NONE;
1590}
1591
Mark Hammond8696ebc2002-10-08 02:44:31 +00001592#endif /* MS_WINDOWS */
1593
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001594#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001595
1596/*[clinic input]
1597sys.setdlopenflags
1598
1599 flags as new_val: int
1600 /
1601
1602Set the flags used by the interpreter for dlopen calls.
1603
1604This is used, for example, when the interpreter loads extension
1605modules. Among other things, this will enable a lazy resolving of
1606symbols when importing a module, if called as sys.setdlopenflags(0).
1607To share symbols across extension modules, call as
1608sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1609modules can be found in the os module (RTLD_xxx constants, e.g.
1610os.RTLD_LAZY).
1611[clinic start generated code]*/
1612
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001613static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001614sys_setdlopenflags_impl(PyObject *module, int new_val)
1615/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001616{
Victor Stinner838f2642019-06-13 22:41:23 +02001617 PyThreadState *tstate = _PyThreadState_GET();
1618 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001619 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001620}
1621
Tal Einatede0b6f2018-12-31 17:12:08 +02001622
1623/*[clinic input]
1624sys.getdlopenflags
1625
1626Return the current value of the flags that are used for dlopen calls.
1627
1628The flag constants are defined in the os module.
1629[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001630
1631static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001632sys_getdlopenflags_impl(PyObject *module)
1633/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001634{
Victor Stinner838f2642019-06-13 22:41:23 +02001635 PyThreadState *tstate = _PyThreadState_GET();
1636 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001637}
1638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001640
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001641#ifdef USE_MALLOPT
1642/* Link with -lmalloc (or -lmpc) on an SGI */
1643#include <malloc.h>
1644
Tal Einatede0b6f2018-12-31 17:12:08 +02001645/*[clinic input]
1646sys.mdebug
1647
1648 flag: int
1649 /
1650[clinic start generated code]*/
1651
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001652static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001653sys_mdebug_impl(PyObject *module, int flag)
1654/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001658 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001659}
1660#endif /* USE_MALLOPT */
1661
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001662size_t
1663_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001667 Py_ssize_t size;
Victor Stinner838f2642019-06-13 22:41:23 +02001668 PyThreadState *tstate = _PyThreadState_GET();
Benjamin Petersona5758c02009-05-09 18:15:04 +00001669
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 /* Make sure the type is initialized. float gets initialized late */
Victor Stinner838f2642019-06-13 22:41:23 +02001671 if (PyType_Ready(Py_TYPE(o)) < 0) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001672 return (size_t)-1;
Victor Stinner838f2642019-06-13 22:41:23 +02001673 }
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001674
Benjamin Petersonce798522012-01-22 11:24:29 -05001675 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 if (method == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001677 if (!_PyErr_Occurred(tstate)) {
1678 _PyErr_Format(tstate, PyExc_TypeError,
1679 "Type %.100s doesn't define __sizeof__",
1680 Py_TYPE(o)->tp_name);
1681 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 }
1683 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001684 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 Py_DECREF(method);
1686 }
1687
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001688 if (res == NULL)
1689 return (size_t)-1;
1690
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001691 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001692 Py_DECREF(res);
Victor Stinner838f2642019-06-13 22:41:23 +02001693 if (size == -1 && _PyErr_Occurred(tstate))
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001694 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001696 if (size < 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02001697 _PyErr_SetString(tstate, PyExc_ValueError,
1698 "__sizeof__() should return >= 0");
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001699 return (size_t)-1;
1700 }
1701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* add gc_head size */
Hai Shi675d9a32020-04-15 02:11:20 +08001703 if (_PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001704 return ((size_t)size) + sizeof(PyGC_Head);
1705 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001706}
1707
1708static PyObject *
1709sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1710{
1711 static char *kwlist[] = {"object", "default", 0};
1712 size_t size;
1713 PyObject *o, *dflt = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001714 PyThreadState *tstate = _PyThreadState_GET();
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001715
1716 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
Victor Stinner838f2642019-06-13 22:41:23 +02001717 kwlist, &o, &dflt)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001718 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02001719 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001720
1721 size = _PySys_GetSizeOf(o);
1722
Victor Stinner838f2642019-06-13 22:41:23 +02001723 if (size == (size_t)-1 && _PyErr_Occurred(tstate)) {
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001724 /* Has a default value been given */
Victor Stinner838f2642019-06-13 22:41:23 +02001725 if (dflt != NULL && _PyErr_ExceptionMatches(tstate, PyExc_TypeError)) {
1726 _PyErr_Clear(tstate);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001727 Py_INCREF(dflt);
1728 return dflt;
1729 }
1730 else
1731 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001733
1734 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001735}
1736
1737PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001738"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001739\n\
1740Return the size of object in bytes.");
1741
Tal Einatede0b6f2018-12-31 17:12:08 +02001742/*[clinic input]
1743sys.getrefcount -> Py_ssize_t
1744
1745 object: object
1746 /
1747
1748Return the reference count of object.
1749
1750The count returned is generally one higher than you might expect,
1751because it includes the (temporary) reference as an argument to
1752getrefcount().
1753[clinic start generated code]*/
1754
1755static Py_ssize_t
1756sys_getrefcount_impl(PyObject *module, PyObject *object)
1757/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001758{
Victor Stinnera93c51e2020-02-07 00:38:59 +01001759 return Py_REFCNT(object);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001760}
1761
Tim Peters4be93d02002-07-07 19:59:50 +00001762#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001763/*[clinic input]
1764sys.gettotalrefcount -> Py_ssize_t
1765[clinic start generated code]*/
1766
1767static Py_ssize_t
1768sys_gettotalrefcount_impl(PyObject *module)
1769/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001770{
Tal Einatede0b6f2018-12-31 17:12:08 +02001771 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001772}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001773#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001774
Tal Einatede0b6f2018-12-31 17:12:08 +02001775/*[clinic input]
1776sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001777
Tal Einatede0b6f2018-12-31 17:12:08 +02001778Return the number of memory blocks currently allocated.
1779[clinic start generated code]*/
1780
1781static Py_ssize_t
1782sys_getallocatedblocks_impl(PyObject *module)
1783/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001784{
Tal Einatede0b6f2018-12-31 17:12:08 +02001785 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001786}
1787
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001788
Tal Einatede0b6f2018-12-31 17:12:08 +02001789/*[clinic input]
1790sys._getframe
1791
1792 depth: int = 0
1793 /
1794
1795Return a frame object from the call stack.
1796
1797If optional integer depth is given, return the frame object that many
1798calls below the top of the stack. If that is deeper than the call
1799stack, ValueError is raised. The default for depth is zero, returning
1800the frame at the top of the call stack.
1801
1802This function should be used for internal and specialized purposes
1803only.
1804[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001805
1806static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001807sys__getframe_impl(PyObject *module, int depth)
1808/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001809{
Victor Stinner838f2642019-06-13 22:41:23 +02001810 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner70364772020-04-29 03:28:46 +02001811 PyFrameObject *f = PyThreadState_GetFrame(tstate);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001812
Victor Stinner08faf002020-03-26 18:57:32 +01001813 if (_PySys_Audit(tstate, "sys._getframe", "O", f) < 0) {
Victor Stinner70364772020-04-29 03:28:46 +02001814 Py_DECREF(f);
Steve Dowerb82e17e2019-05-23 08:45:22 -07001815 return NULL;
1816 }
1817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 while (depth > 0 && f != NULL) {
Victor Stinner70364772020-04-29 03:28:46 +02001819 PyFrameObject *back = PyFrame_GetBack(f);
1820 Py_DECREF(f);
1821 f = back;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 --depth;
1823 }
1824 if (f == NULL) {
Victor Stinner838f2642019-06-13 22:41:23 +02001825 _PyErr_SetString(tstate, PyExc_ValueError,
1826 "call stack is not deep enough");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return NULL;
1828 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001830}
1831
Tal Einatede0b6f2018-12-31 17:12:08 +02001832/*[clinic input]
1833sys._current_frames
1834
1835Return a dict mapping each thread's thread id to its current stack frame.
1836
1837This function should be used for specialized purposes only.
1838[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001839
1840static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001841sys__current_frames_impl(PyObject *module)
1842/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001845}
1846
Tal Einatede0b6f2018-12-31 17:12:08 +02001847/*[clinic input]
Julien Danjou64366fa2020-11-02 15:16:25 +01001848sys._current_exceptions
1849
1850Return a dict mapping each thread's identifier to its current raised exception.
1851
1852This function should be used for specialized purposes only.
1853[clinic start generated code]*/
1854
1855static PyObject *
1856sys__current_exceptions_impl(PyObject *module)
1857/*[clinic end generated code: output=2ccfd838c746f0ba input=0e91818fbf2edc1f]*/
1858{
1859 return _PyThread_CurrentExceptions();
1860}
1861
1862/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +02001863sys.call_tracing
1864
1865 func: object
1866 args as funcargs: object(subclass_of='&PyTuple_Type')
1867 /
1868
1869Call func(*args), while tracing is enabled.
1870
1871The tracing state is saved, and restored afterwards. This is intended
1872to be called from a debugger from a checkpoint, to recursively debug
1873some other code.
1874[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001875
1876static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001877sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1878/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001879{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001881}
1882
Victor Stinner048afd92016-11-28 11:59:04 +01001883
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001884#ifdef __cplusplus
1885extern "C" {
1886#endif
1887
Tal Einatede0b6f2018-12-31 17:12:08 +02001888/*[clinic input]
1889sys._debugmallocstats
1890
1891Print summary info to stderr about the state of pymalloc's structures.
1892
1893In Py_DEBUG mode, also perform some expensive internal consistency
1894checks.
1895[clinic start generated code]*/
1896
David Malcolm49526f42012-06-22 14:55:41 -04001897static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001898sys__debugmallocstats_impl(PyObject *module)
1899/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001900{
1901#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001902 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001903 fputc('\n', stderr);
1904 }
David Malcolm49526f42012-06-22 14:55:41 -04001905#endif
1906 _PyObject_DebugTypeStats(stderr);
1907
1908 Py_RETURN_NONE;
1909}
David Malcolm49526f42012-06-22 14:55:41 -04001910
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001911#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001912/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001913extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001914#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001915
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001916#ifdef DYNAMIC_EXECUTION_PROFILE
1917/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001918extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001919#endif
1920
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001921#ifdef __cplusplus
1922}
1923#endif
1924
Tal Einatede0b6f2018-12-31 17:12:08 +02001925
1926/*[clinic input]
1927sys._clear_type_cache
1928
1929Clear the internal type lookup cache.
1930[clinic start generated code]*/
1931
Christian Heimes15ebc882008-02-04 18:48:49 +00001932static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001933sys__clear_type_cache_impl(PyObject *module)
1934/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 PyType_ClearCache();
1937 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001938}
1939
Tal Einatede0b6f2018-12-31 17:12:08 +02001940/*[clinic input]
1941sys.is_finalizing
1942
1943Return True if Python is exiting.
1944[clinic start generated code]*/
1945
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001946static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001947sys_is_finalizing_impl(PyObject *module)
1948/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001949{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001950 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001951}
1952
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001953#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001954/*[clinic input]
1955sys.getandroidapilevel
1956
1957Return the build time API version of Android as an integer.
1958[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001959
1960static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001961sys_getandroidapilevel_impl(PyObject *module)
1962/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001963{
1964 return PyLong_FromLong(ANDROID_API_LEVEL);
1965}
1966#endif /* ANDROID_API_LEVEL */
1967
1968
Steve Dowerb82e17e2019-05-23 08:45:22 -07001969
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001970static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001972 SYS_ADDAUDITHOOK_METHODDEF
1973 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001974 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001975 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001976 SYS__CLEAR_TYPE_CACHE_METHODDEF
1977 SYS__CURRENT_FRAMES_METHODDEF
Julien Danjou64366fa2020-11-02 15:16:25 +01001978 SYS__CURRENT_EXCEPTIONS_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001979 SYS_DISPLAYHOOK_METHODDEF
1980 SYS_EXC_INFO_METHODDEF
1981 SYS_EXCEPTHOOK_METHODDEF
1982 SYS_EXIT_METHODDEF
1983 SYS_GETDEFAULTENCODING_METHODDEF
1984 SYS_GETDLOPENFLAGS_METHODDEF
1985 SYS_GETALLOCATEDBLOCKS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001986#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001987 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001988#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001989 SYS_GETFILESYSTEMENCODING_METHODDEF
1990 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001991#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001992 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001993#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001994 SYS_GETTOTALREFCOUNT_METHODDEF
1995 SYS_GETREFCOUNT_METHODDEF
1996 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001997 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001999 SYS__GETFRAME_METHODDEF
2000 SYS_GETWINDOWSVERSION_METHODDEF
2001 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
2002 SYS_INTERN_METHODDEF
2003 SYS_IS_FINALIZING_METHODDEF
2004 SYS_MDEBUG_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002005 SYS_SETSWITCHINTERVAL_METHODDEF
2006 SYS_GETSWITCHINTERVAL_METHODDEF
2007 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002009 SYS_GETPROFILE_METHODDEF
2010 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002012 SYS_GETTRACE_METHODDEF
2013 SYS_CALL_TRACING_METHODDEF
2014 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002015 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2016 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002017 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002018 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002019 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2020 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002021 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002023};
2024
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002025static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002026list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 PyObject *list = PyList_New(0);
2029 int i;
2030 if (list == NULL)
2031 return NULL;
2032 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2033 PyObject *name = PyUnicode_FromString(
2034 PyImport_Inittab[i].name);
2035 if (name == NULL)
2036 break;
2037 PyList_Append(list, name);
2038 Py_DECREF(name);
2039 }
2040 if (PyList_Sort(list) != 0) {
2041 Py_DECREF(list);
2042 list = NULL;
2043 }
2044 if (list) {
2045 PyObject *v = PyList_AsTuple(list);
2046 Py_DECREF(list);
2047 list = v;
2048 }
2049 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002050}
2051
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002052/* Pre-initialization support for sys.warnoptions and sys._xoptions
2053 *
2054 * Modern internal code paths:
2055 * These APIs get called after _Py_InitializeCore and get to use the
2056 * regular CPython list, dict, and unicode APIs.
2057 *
2058 * Legacy embedding code paths:
2059 * The multi-phase initialization API isn't public yet, so embedding
2060 * apps still need to be able configure sys.warnoptions and sys._xoptions
2061 * before they call Py_Initialize. To support this, we stash copies of
2062 * the supplied wchar * sequences in linked lists, and then migrate the
2063 * contents of those lists to the sys module in _PyInitializeCore.
2064 *
2065 */
2066
2067struct _preinit_entry {
2068 wchar_t *value;
2069 struct _preinit_entry *next;
2070};
2071
2072typedef struct _preinit_entry *_Py_PreInitEntry;
2073
2074static _Py_PreInitEntry _preinit_warnoptions = NULL;
2075static _Py_PreInitEntry _preinit_xoptions = NULL;
2076
2077static _Py_PreInitEntry
2078_alloc_preinit_entry(const wchar_t *value)
2079{
2080 /* To get this to work, we have to initialize the runtime implicitly */
2081 _PyRuntime_Initialize();
2082
2083 /* Force default allocator, so we can ensure that it also gets used to
2084 * destroy the linked list in _clear_preinit_entries.
2085 */
2086 PyMemAllocatorEx old_alloc;
2087 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2088
2089 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2090 if (node != NULL) {
2091 node->value = _PyMem_RawWcsdup(value);
2092 if (node->value == NULL) {
2093 PyMem_RawFree(node);
2094 node = NULL;
2095 };
2096 };
2097
2098 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2099 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002100}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002101
2102static int
2103_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2104{
2105 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2106 if (new_entry == NULL) {
2107 return -1;
2108 }
2109 /* We maintain the linked list in this order so it's easy to play back
2110 * the add commands in the same order later on in _Py_InitializeCore
2111 */
2112 _Py_PreInitEntry last_entry = *optionlist;
2113 if (last_entry == NULL) {
2114 *optionlist = new_entry;
2115 } else {
2116 while (last_entry->next != NULL) {
2117 last_entry = last_entry->next;
2118 }
2119 last_entry->next = new_entry;
2120 }
2121 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002122}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002123
2124static void
2125_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2126{
2127 _Py_PreInitEntry current = *optionlist;
2128 *optionlist = NULL;
2129 /* Deallocate the nodes and their contents using the default allocator */
2130 PyMemAllocatorEx old_alloc;
2131 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2132 while (current != NULL) {
2133 _Py_PreInitEntry next = current->next;
2134 PyMem_RawFree(current->value);
2135 PyMem_RawFree(current);
2136 current = next;
2137 }
2138 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002139}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002140
Victor Stinner120b7072019-08-23 18:03:08 +01002141
2142PyStatus
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002143_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002144{
Victor Stinner120b7072019-08-23 18:03:08 +01002145 PyStatus status;
2146 _Py_PreInitEntry entry;
2147
2148 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Victor Stinnerfb4ae152019-09-30 01:40:17 +02002149 status = PyWideStringList_Append(options, entry->value);
Victor Stinner120b7072019-08-23 18:03:08 +01002150 if (_PyStatus_EXCEPTION(status)) {
2151 return status;
2152 }
2153 }
2154
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002155 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinner120b7072019-08-23 18:03:08 +01002156 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002157}
2158
Victor Stinner120b7072019-08-23 18:03:08 +01002159
2160PyStatus
2161_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002162{
Victor Stinner120b7072019-08-23 18:03:08 +01002163 PyStatus status;
2164 _Py_PreInitEntry entry;
2165
2166 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2167 status = PyWideStringList_Append(&config->xoptions, entry->value);
2168 if (_PyStatus_EXCEPTION(status)) {
2169 return status;
2170 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002171 }
2172
Victor Stinner120b7072019-08-23 18:03:08 +01002173 _clear_preinit_entries(&_preinit_xoptions);
2174 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002175}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002176
Victor Stinner120b7072019-08-23 18:03:08 +01002177
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002178static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002179get_warnoptions(PyThreadState *tstate)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002180{
Victor Stinner838f2642019-06-13 22:41:23 +02002181 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002182 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002183 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2184 * interpreter config. When that happens, we need to properly set
2185 * the `warnoptions` reference in the main interpreter config as well.
2186 *
2187 * For Python 3.7, we shouldn't be able to get here due to the
2188 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2189 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2190 * call optional for embedding applications, thus making this
2191 * reachable again.
2192 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002193 warnoptions = PyList_New(0);
Victor Stinner838f2642019-06-13 22:41:23 +02002194 if (warnoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002195 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002196 }
2197 if (sys_set_object_id(tstate, &PyId_warnoptions, warnoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002198 Py_DECREF(warnoptions);
2199 return NULL;
2200 }
2201 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002202 }
2203 return warnoptions;
2204}
Guido van Rossum23fff912000-12-15 22:02:05 +00002205
2206void
2207PySys_ResetWarnOptions(void)
2208{
Victor Stinner50b48572018-11-01 01:51:40 +01002209 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002210 if (tstate == NULL) {
2211 _clear_preinit_entries(&_preinit_warnoptions);
2212 return;
2213 }
2214
Victor Stinner838f2642019-06-13 22:41:23 +02002215 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (warnoptions == NULL || !PyList_Check(warnoptions))
2217 return;
2218 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002219}
2220
Victor Stinnere1b29952018-10-30 14:31:42 +01002221static int
Victor Stinner838f2642019-06-13 22:41:23 +02002222_PySys_AddWarnOptionWithError(PyThreadState *tstate, PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002223{
Victor Stinner838f2642019-06-13 22:41:23 +02002224 PyObject *warnoptions = get_warnoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002225 if (warnoptions == NULL) {
2226 return -1;
2227 }
2228 if (PyList_Append(warnoptions, option)) {
2229 return -1;
2230 }
2231 return 0;
2232}
2233
2234void
2235PySys_AddWarnOptionUnicode(PyObject *option)
2236{
Victor Stinner838f2642019-06-13 22:41:23 +02002237 PyThreadState *tstate = _PyThreadState_GET();
2238 if (_PySys_AddWarnOptionWithError(tstate, option) < 0) {
Victor Stinnere1b29952018-10-30 14:31:42 +01002239 /* No return value, therefore clear error state if possible */
Victor Stinner838f2642019-06-13 22:41:23 +02002240 if (tstate) {
2241 _PyErr_Clear(tstate);
Victor Stinnere1b29952018-10-30 14:31:42 +01002242 }
2243 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002244}
2245
2246void
2247PySys_AddWarnOption(const wchar_t *s)
2248{
Victor Stinner50b48572018-11-01 01:51:40 +01002249 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002250 if (tstate == NULL) {
2251 _append_preinit_entry(&_preinit_warnoptions, s);
2252 return;
2253 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002254 PyObject *unicode;
2255 unicode = PyUnicode_FromWideChar(s, -1);
2256 if (unicode == NULL)
2257 return;
2258 PySys_AddWarnOptionUnicode(unicode);
2259 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002260}
2261
Christian Heimes33fe8092008-04-13 13:53:33 +00002262int
2263PySys_HasWarnOptions(void)
2264{
Victor Stinner838f2642019-06-13 22:41:23 +02002265 PyThreadState *tstate = _PyThreadState_GET();
2266 PyObject *warnoptions = sys_get_object_id(tstate, &PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002267 return (warnoptions != NULL && PyList_Check(warnoptions)
2268 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002269}
2270
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002271static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002272get_xoptions(PyThreadState *tstate)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002273{
Victor Stinner838f2642019-06-13 22:41:23 +02002274 PyObject *xoptions = sys_get_object_id(tstate, &PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002275 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002276 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2277 * interpreter config. When that happens, we need to properly set
2278 * the `xoptions` reference in the main interpreter config as well.
2279 *
2280 * For Python 3.7, we shouldn't be able to get here due to the
2281 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2282 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2283 * call optional for embedding applications, thus making this
2284 * reachable again.
2285 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002286 xoptions = PyDict_New();
Victor Stinner838f2642019-06-13 22:41:23 +02002287 if (xoptions == NULL) {
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002288 return NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002289 }
2290 if (sys_set_object_id(tstate, &PyId__xoptions, xoptions)) {
Eric Snowdae02762017-09-14 00:35:58 -07002291 Py_DECREF(xoptions);
2292 return NULL;
2293 }
2294 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002295 }
2296 return xoptions;
2297}
2298
Victor Stinnere1b29952018-10-30 14:31:42 +01002299static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002300_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002301{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002302 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002303
Victor Stinner838f2642019-06-13 22:41:23 +02002304 PyThreadState *tstate = _PyThreadState_GET();
2305 PyObject *opts = get_xoptions(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002306 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002307 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002308 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002309
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002310 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002311 if (!name_end) {
2312 name = PyUnicode_FromWideChar(s, -1);
2313 value = Py_True;
2314 Py_INCREF(value);
2315 }
2316 else {
2317 name = PyUnicode_FromWideChar(s, name_end - s);
2318 value = PyUnicode_FromWideChar(name_end + 1, -1);
2319 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002320 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002321 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002322 }
2323 if (PyDict_SetItem(opts, name, value) < 0) {
2324 goto error;
2325 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002326 Py_DECREF(name);
2327 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002328 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002329
2330error:
2331 Py_XDECREF(name);
2332 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002333 return -1;
2334}
2335
2336void
2337PySys_AddXOption(const wchar_t *s)
2338{
Victor Stinner50b48572018-11-01 01:51:40 +01002339 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002340 if (tstate == NULL) {
2341 _append_preinit_entry(&_preinit_xoptions, s);
2342 return;
2343 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002344 if (_PySys_AddXOptionWithError(s) < 0) {
2345 /* No return value, therefore clear error state if possible */
Victor Stinner120b7072019-08-23 18:03:08 +01002346 _PyErr_Clear(tstate);
Victor Stinner0cae6092016-11-11 01:43:56 +01002347 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002348}
2349
2350PyObject *
2351PySys_GetXOptions(void)
2352{
Victor Stinner838f2642019-06-13 22:41:23 +02002353 PyThreadState *tstate = _PyThreadState_GET();
2354 return get_xoptions(tstate);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002355}
2356
Guido van Rossum40552d01998-08-06 03:34:39 +00002357/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2358 Two literals concatenated works just fine. If you have a K&R compiler
2359 or other abomination that however *does* understand longer strings,
2360 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002361PyDoc_VAR(sys_doc) =
2362PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002363"This module provides access to some objects used or maintained by the\n\
2364interpreter and to functions that interact strongly with the interpreter.\n\
2365\n\
2366Dynamic objects:\n\
2367\n\
2368argv -- command line arguments; argv[0] is the script pathname if known\n\
2369path -- module search path; path[0] is the script directory, else ''\n\
2370modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002371\n\
2372displayhook -- called to show results in an interactive session\n\
2373excepthook -- called to handle any uncaught exception other than SystemExit\n\
2374 To customize printing in an interactive session or to install a custom\n\
2375 top-level exception handler, assign other functions to replace these.\n\
2376\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002377stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002378stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002379stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002380 By assigning other file objects (or objects that behave like files)\n\
2381 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002382\n\
2383last_type -- type of last uncaught exception\n\
2384last_value -- value of last uncaught exception\n\
2385last_traceback -- traceback of last uncaught exception\n\
2386 These three are only available in an interactive session after a\n\
2387 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002388"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002389)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002390/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002391PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002392"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002393Static objects:\n\
2394\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002395builtin_module_names -- tuple of module names built into this interpreter\n\
2396copyright -- copyright notice pertaining to this interpreter\n\
2397exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002398executable -- absolute path of the executable binary of the Python interpreter\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002399float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002400float_repr_style -- string indicating the style of repr() output for floats\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002401hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002402hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002403implementation -- Python implementation information.\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002404int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002405maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002406maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002407platform -- platform identifier\n\
2408prefix -- prefix used to find the Python library\n\
Raymond Hettinger71170742019-09-11 07:17:32 -07002409thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002410version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002411version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002412"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002413)
Steve Dowercc16be82016-09-08 10:35:16 -07002414#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002415/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002416PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002417"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002418winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002419"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002420)
Steve Dowercc16be82016-09-08 10:35:16 -07002421#endif /* MS_COREDLL */
2422#ifdef MS_WINDOWS
2423/* concatenating string here */
2424PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002425"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002426"
2427)
2428#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002429PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002430"__stdin__ -- the original stdin; don't touch!\n\
2431__stdout__ -- the original stdout; don't touch!\n\
2432__stderr__ -- the original stderr; don't touch!\n\
2433__displayhook__ -- the original displayhook; don't touch!\n\
2434__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002435\n\
2436Functions:\n\
2437\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002438displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002439excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002440exc_info() -- return thread-safe information about the current exception\n\
2441exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002442getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002443getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002444getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002445getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002446getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002447gettrace() -- get the global debug tracing function\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002448setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002449setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002450setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002451settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002452"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002453)
Fred Drakeccede592000-08-14 20:59:57 +00002454/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002455
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002456
2457PyDoc_STRVAR(flags__doc__,
2458"sys.flags\n\
2459\n\
2460Flags provided through command line arguments or environment vars.");
2461
2462static PyTypeObject FlagsType;
2463
2464static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 {"inspect", "-i"},
2467 {"interactive", "-i"},
2468 {"optimize", "-O or -OO"},
2469 {"dont_write_bytecode", "-B"},
2470 {"no_user_site", "-s"},
2471 {"no_site", "-S"},
2472 {"ignore_environment", "-E"},
2473 {"verbose", "-v"},
Georg Brandl8aa7e992010-12-28 18:30:18 +00002474 {"bytes_warning", "-b"},
2475 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002476 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002477 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002478 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002479 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002481};
2482
2483static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 "sys.flags", /* name */
2485 flags__doc__, /* doc */
2486 flags_fields, /* fields */
Victor Stinner1def7752020-04-23 03:03:24 +02002487 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002488};
2489
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002490static int
2491set_flags_from_config(PyObject *flags, PyThreadState *tstate)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002492{
Victor Stinner01b1cc12019-11-20 02:27:56 +01002493 PyInterpreterState *interp = tstate->interp;
2494 const PyPreConfig *preconfig = &interp->runtime->preconfig;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002495 const PyConfig *config = _PyInterpreterState_GetConfig(interp);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002496
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002497 // _PySys_UpdateConfig() modifies sys.flags in-place:
2498 // Py_XDECREF() is needed in this case.
2499 Py_ssize_t pos = 0;
2500#define SetFlagObj(expr) \
2501 do { \
2502 PyObject *value = (expr); \
2503 if (value == NULL) { \
2504 return -1; \
2505 } \
2506 Py_XDECREF(PyStructSequence_GET_ITEM(flags, pos)); \
2507 PyStructSequence_SET_ITEM(flags, pos, value); \
2508 pos++; \
2509 } while (0)
2510#define SetFlag(expr) SetFlagObj(PyLong_FromLong(expr))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002511
Victor Stinnerfbca9082018-08-30 00:50:45 +02002512 SetFlag(config->parser_debug);
2513 SetFlag(config->inspect);
2514 SetFlag(config->interactive);
2515 SetFlag(config->optimization_level);
2516 SetFlag(!config->write_bytecode);
2517 SetFlag(!config->user_site_directory);
2518 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002519 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002520 SetFlag(config->verbose);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002521 SetFlag(config->bytes_warning);
2522 SetFlag(config->quiet);
2523 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002524 SetFlag(config->isolated);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002525 SetFlagObj(PyBool_FromLong(config->dev_mode));
Victor Stinner20004952019-03-26 02:31:11 +01002526 SetFlag(preconfig->utf8_mode);
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002527#undef SetFlagObj
Victor Stinner91106cd2017-12-13 12:29:09 +01002528#undef SetFlag
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002529 return 0;
2530}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002531
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002532
2533static PyObject*
2534make_flags(PyThreadState *tstate)
2535{
2536 PyObject *flags = PyStructSequence_New(&FlagsType);
2537 if (flags == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 return NULL;
2539 }
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002540
2541 if (set_flags_from_config(flags, tstate) < 0) {
2542 Py_DECREF(flags);
2543 return NULL;
2544 }
2545 return flags;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002546}
2547
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002548
Eric Smith0e5b5622009-02-06 01:32:42 +00002549PyDoc_STRVAR(version_info__doc__,
2550"sys.version_info\n\
2551\n\
2552Version information as a named tuple.");
2553
2554static PyTypeObject VersionInfoType;
2555
2556static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 {"major", "Major release number"},
2558 {"minor", "Minor release number"},
2559 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002560 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 {"serial", "Serial release number"},
2562 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002563};
2564
2565static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 "sys.version_info", /* name */
2567 version_info__doc__, /* doc */
2568 version_info_fields, /* fields */
2569 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002570};
2571
2572static PyObject *
Victor Stinner838f2642019-06-13 22:41:23 +02002573make_version_info(PyThreadState *tstate)
Eric Smith0e5b5622009-02-06 01:32:42 +00002574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 PyObject *version_info;
2576 char *s;
2577 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 version_info = PyStructSequence_New(&VersionInfoType);
2580 if (version_info == NULL) {
2581 return NULL;
2582 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002583
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002584 /*
2585 * These release level checks are mutually exclusive and cover
2586 * the field, so don't get too fancy with the pre-processor!
2587 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002588#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002590#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002592#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002594#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002595 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002596#endif
2597
2598#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002600#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002603 SetIntItem(PY_MAJOR_VERSION);
2604 SetIntItem(PY_MINOR_VERSION);
2605 SetIntItem(PY_MICRO_VERSION);
2606 SetStrItem(s);
2607 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002608#undef SetIntItem
2609#undef SetStrItem
2610
Victor Stinner838f2642019-06-13 22:41:23 +02002611 if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Py_CLEAR(version_info);
2613 return NULL;
2614 }
2615 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002616}
2617
Brett Cannon3adc7b72012-07-09 14:22:12 -04002618/* sys.implementation values */
2619#define NAME "cpython"
2620const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002621#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2622#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002623#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002624const char *_PySys_ImplCacheTag = TAG;
2625#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002626#undef MAJOR
2627#undef MINOR
2628#undef TAG
2629
Barry Warsaw409da152012-06-03 16:18:47 -04002630static PyObject *
2631make_impl_info(PyObject *version_info)
2632{
2633 int res;
2634 PyObject *impl_info, *value, *ns;
2635
2636 impl_info = PyDict_New();
2637 if (impl_info == NULL)
2638 return NULL;
2639
2640 /* populate the dict */
2641
Brett Cannon3adc7b72012-07-09 14:22:12 -04002642 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002643 if (value == NULL)
2644 goto error;
2645 res = PyDict_SetItemString(impl_info, "name", value);
2646 Py_DECREF(value);
2647 if (res < 0)
2648 goto error;
2649
Brett Cannon3adc7b72012-07-09 14:22:12 -04002650 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002651 if (value == NULL)
2652 goto error;
2653 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2654 Py_DECREF(value);
2655 if (res < 0)
2656 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002657
2658 res = PyDict_SetItemString(impl_info, "version", version_info);
2659 if (res < 0)
2660 goto error;
2661
2662 value = PyLong_FromLong(PY_VERSION_HEX);
2663 if (value == NULL)
2664 goto error;
2665 res = PyDict_SetItemString(impl_info, "hexversion", value);
2666 Py_DECREF(value);
2667 if (res < 0)
2668 goto error;
2669
doko@ubuntu.com55532312016-06-14 08:55:19 +02002670#ifdef MULTIARCH
2671 value = PyUnicode_FromString(MULTIARCH);
2672 if (value == NULL)
2673 goto error;
2674 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2675 Py_DECREF(value);
2676 if (res < 0)
2677 goto error;
2678#endif
2679
Barry Warsaw409da152012-06-03 16:18:47 -04002680 /* dict ready */
2681
2682 ns = _PyNamespace_New(impl_info);
2683 Py_DECREF(impl_info);
2684 return ns;
2685
2686error:
2687 Py_CLEAR(impl_info);
2688 return NULL;
2689}
2690
Martin v. Löwis1a214512008-06-11 05:26:20 +00002691static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyModuleDef_HEAD_INIT,
2693 "sys",
2694 sys_doc,
2695 -1, /* multiple "initialization" just copies the module dict. */
2696 sys_methods,
2697 NULL,
2698 NULL,
2699 NULL,
2700 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002701};
2702
Eric Snow6b4be192017-05-22 21:36:03 -07002703/* Updating the sys namespace, returning NULL pointer on error */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002704#define SET_SYS(key, value) \
Victor Stinner8fea2522013-10-27 17:15:42 +01002705 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002706 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002707 if (v == NULL) { \
2708 goto err_occurred; \
2709 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002710 res = PyDict_SetItemString(sysdict, key, v); \
2711 Py_DECREF(v); \
2712 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002713 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002714 } \
2715 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002716
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002717#define SET_SYS_FROM_STRING(key, value) \
2718 SET_SYS(key, PyUnicode_FromString(value))
2719
Victor Stinner331a6a52019-05-27 16:39:22 +02002720static PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01002721_PySys_InitCore(PyThreadState *tstate, PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002722{
Victor Stinnerab672812019-01-23 15:04:40 +01002723 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002724 int res;
2725
Nick Coghland6009512014-11-20 21:39:37 +10002726 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002727
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002728#define COPY_SYS_ATTR(tokey, fromkey) \
2729 SET_SYS(tokey, PyMapping_GetItemString(sysdict, fromkey))
Victor Stinneref9d9b62019-05-22 11:28:22 +02002730
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002731 COPY_SYS_ATTR("__displayhook__", "displayhook");
2732 COPY_SYS_ATTR("__excepthook__", "excepthook");
2733 COPY_SYS_ATTR("__breakpointhook__", "breakpointhook");
2734 COPY_SYS_ATTR("__unraisablehook__", "unraisablehook");
2735
2736#undef COPY_SYS_ATTR
2737
2738 SET_SYS_FROM_STRING("version", Py_GetVersion());
2739 SET_SYS("hexversion", PyLong_FromLong(PY_VERSION_HEX));
2740 SET_SYS("_git", Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2741 _Py_gitversion()));
2742 SET_SYS_FROM_STRING("_framework", _PYTHONFRAMEWORK);
2743 SET_SYS("api_version", PyLong_FromLong(PYTHON_API_VERSION));
2744 SET_SYS_FROM_STRING("copyright", Py_GetCopyright());
2745 SET_SYS_FROM_STRING("platform", Py_GetPlatform());
2746 SET_SYS("maxsize", PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2747 SET_SYS("float_info", PyFloat_GetInfo());
2748 SET_SYS("int_info", PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002749 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002750 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002751 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2752 goto type_init_failed;
2753 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002754 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002755 SET_SYS("hash_info", get_hash_info(tstate));
2756 SET_SYS("maxunicode", PyLong_FromLong(0x10FFFF));
2757 SET_SYS("builtin_module_names", list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002758#if PY_BIG_ENDIAN
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002759 SET_SYS_FROM_STRING("byteorder", "big");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002760#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002761 SET_SYS_FROM_STRING("byteorder", "little");
Christian Heimes743e0cd2012-10-17 23:52:17 +02002762#endif
Fred Drake099325e2000-08-14 15:47:03 +00002763
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002764#ifdef MS_COREDLL
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002765 SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
2766 SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
Guido van Rossumc606fe11996-04-09 02:37:57 +00002767#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002768#ifdef ABIFLAGS
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002769 SET_SYS_FROM_STRING("abiflags", ABIFLAGS);
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002770#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002773 if (VersionInfoType.tp_name == NULL) {
2774 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002775 &version_info_desc) < 0) {
2776 goto type_init_failed;
2777 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002778 }
Victor Stinner838f2642019-06-13 22:41:23 +02002779 version_info = make_version_info(tstate);
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002780 SET_SYS("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 /* prevent user from creating new instances */
2782 VersionInfoType.tp_init = NULL;
2783 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002784 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002785 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2786 _PyErr_Clear(tstate);
2787 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002788
Barry Warsaw409da152012-06-03 16:18:47 -04002789 /* implementation */
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002790 SET_SYS("implementation", make_impl_info(version_info));
Barry Warsaw409da152012-06-03 16:18:47 -04002791
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002792 // sys.flags: updated in-place later by _PySys_UpdateConfig()
Victor Stinner1c8f0592013-07-22 22:24:54 +02002793 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002794 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2795 goto type_init_failed;
2796 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002797 }
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002798 SET_SYS("flags", make_flags(tstate));
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002799 /* prevent user from creating new instances */
2800 FlagsType.tp_init = NULL;
2801 FlagsType.tp_new = NULL;
2802 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2803 if (res < 0) {
2804 if (!_PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2805 goto err_occurred;
2806 }
2807 _PyErr_Clear(tstate);
2808 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002809
2810#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 /* getwindowsversion */
2812 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002813 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002814 &windows_version_desc) < 0) {
2815 goto type_init_failed;
2816 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002817 /* prevent user from creating new instances */
2818 WindowsVersionType.tp_init = NULL;
2819 WindowsVersionType.tp_new = NULL;
Victor Stinner838f2642019-06-13 22:41:23 +02002820 assert(!_PyErr_Occurred(tstate));
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002821 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinner838f2642019-06-13 22:41:23 +02002822 if (res < 0 && _PyErr_ExceptionMatches(tstate, PyExc_KeyError)) {
2823 _PyErr_Clear(tstate);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002824 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002825#endif
2826
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002827 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002828#ifndef PY_NO_SHORT_FLOAT_REPR
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002829 SET_SYS_FROM_STRING("float_repr_style", "short");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002830#else
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002831 SET_SYS_FROM_STRING("float_repr_style", "legacy");
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002832#endif
2833
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002834 SET_SYS("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002835
Yury Selivanoveb636452016-09-08 22:01:51 -07002836 /* initialize asyncgen_hooks */
2837 if (AsyncGenHooksType.tp_name == NULL) {
2838 if (PyStructSequence_InitType2(
2839 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002840 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002841 }
2842 }
2843
Victor Stinneref75a622020-11-12 15:14:13 +01002844 /* adding sys.path_hooks and sys.path_importer_cache */
2845 SET_SYS("meta_path", PyList_New(0));
2846 SET_SYS("path_importer_cache", PyDict_New());
2847 SET_SYS("path_hooks", PyList_New(0));
2848
Victor Stinner838f2642019-06-13 22:41:23 +02002849 if (_PyErr_Occurred(tstate)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002850 goto err_occurred;
2851 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002852 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002853
2854type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002855 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002856
2857err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002858 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002859}
2860
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002861static int
2862sys_add_xoption(PyObject *opts, const wchar_t *s)
2863{
2864 PyObject *name, *value;
2865
2866 const wchar_t *name_end = wcschr(s, L'=');
2867 if (!name_end) {
2868 name = PyUnicode_FromWideChar(s, -1);
2869 value = Py_True;
2870 Py_INCREF(value);
2871 }
2872 else {
2873 name = PyUnicode_FromWideChar(s, name_end - s);
2874 value = PyUnicode_FromWideChar(name_end + 1, -1);
2875 }
2876 if (name == NULL || value == NULL) {
2877 goto error;
2878 }
2879 if (PyDict_SetItem(opts, name, value) < 0) {
2880 goto error;
2881 }
2882 Py_DECREF(name);
2883 Py_DECREF(value);
2884 return 0;
2885
2886error:
2887 Py_XDECREF(name);
2888 Py_XDECREF(value);
2889 return -1;
2890}
2891
2892
2893static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002894sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002895{
2896 Py_ssize_t nxoption = config->xoptions.length;
2897 wchar_t * const * xoptions = config->xoptions.items;
2898 PyObject *dict = PyDict_New();
2899 if (dict == NULL) {
2900 return NULL;
2901 }
2902
2903 for (Py_ssize_t i=0; i < nxoption; i++) {
2904 const wchar_t *option = xoptions[i];
2905 if (sys_add_xoption(dict, option) < 0) {
2906 Py_DECREF(dict);
2907 return NULL;
2908 }
2909 }
2910
2911 return dict;
2912}
2913
2914
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002915// Update sys attributes for a new PyConfig configuration.
2916// This function also adds attributes that _PySys_InitCore() didn't add.
Eric Snow6b4be192017-05-22 21:36:03 -07002917int
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002918_PySys_UpdateConfig(PyThreadState *tstate)
Eric Snow6b4be192017-05-22 21:36:03 -07002919{
Victor Stinner838f2642019-06-13 22:41:23 +02002920 PyObject *sysdict = tstate->interp->sysdict;
Victor Stinnerda7933e2020-04-13 03:04:28 +02002921 const PyConfig *config = _PyInterpreterState_GetConfig(tstate->interp);
Eric Snow6b4be192017-05-22 21:36:03 -07002922 int res;
2923
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002924#define COPY_LIST(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002925 SET_SYS(KEY, _PyWideStringList_AsList(&(VALUE)));
Victor Stinner37cd9822018-11-16 11:55:35 +01002926
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002927#define SET_SYS_FROM_WSTR(KEY, VALUE) \
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002928 SET_SYS(KEY, PyUnicode_FromWideChar(VALUE, -1));
Victor Stinner37cd9822018-11-16 11:55:35 +01002929
Victor Stinner9e1b8282020-11-10 13:21:52 +01002930#define COPY_WSTR(SYS_ATTR, WSTR) \
2931 if (WSTR != NULL) { \
2932 SET_SYS_FROM_WSTR(SYS_ATTR, WSTR); \
2933 }
2934
Victor Stinnerf3cb8142020-11-05 18:12:33 +01002935 if (config->module_search_paths_set) {
2936 COPY_LIST("path", config->module_search_paths);
2937 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002938
Victor Stinner9e1b8282020-11-10 13:21:52 +01002939 COPY_WSTR("executable", config->executable);
2940 COPY_WSTR("_base_executable", config->base_executable);
2941 COPY_WSTR("prefix", config->prefix);
2942 COPY_WSTR("base_prefix", config->base_prefix);
2943 COPY_WSTR("exec_prefix", config->exec_prefix);
2944 COPY_WSTR("base_exec_prefix", config->base_exec_prefix);
2945 COPY_WSTR("platlibdir", config->platlibdir);
Victor Stinner41264f12017-12-15 02:05:29 +01002946
Carl Meyerb193fa92018-06-15 22:40:56 -06002947 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002948 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002949 } else {
2950 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2951 }
2952
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002953 COPY_LIST("argv", config->argv);
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02002954 COPY_LIST("orig_argv", config->orig_argv);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002955 COPY_LIST("warnoptions", config->warnoptions);
2956
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002957 SET_SYS("_xoptions", sys_create_xoptions_dict(config));
Victor Stinner41264f12017-12-15 02:05:29 +01002958
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002959#undef SET_SYS_FROM_WSTR
Victor Stinner9e1b8282020-11-10 13:21:52 +01002960#undef COPY_LIST
2961#undef COPY_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002962
Victor Stinneraf1d64d2020-11-04 17:34:34 +01002963 // sys.flags
2964 PyObject *flags = _PySys_GetObject(tstate, "flags"); // borrowed ref
2965 if (flags == NULL) {
2966 return -1;
2967 }
2968 if (set_flags_from_config(flags, tstate) < 0) {
2969 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002970 }
2971
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002972 SET_SYS("dont_write_bytecode", PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002973
Victor Stinner838f2642019-06-13 22:41:23 +02002974 if (_PyErr_Occurred(tstate)) {
2975 goto err_occurred;
2976 }
2977
Eric Snow6b4be192017-05-22 21:36:03 -07002978 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002979
2980err_occurred:
2981 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002982}
2983
Serhiy Storchakafa1d83d2020-10-11 15:30:43 +03002984#undef SET_SYS
Victor Stinner8510f432020-03-10 09:53:09 +01002985#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002986
Victor Stinnerab672812019-01-23 15:04:40 +01002987
2988/* Set up a preliminary stderr printer until we have enough
2989 infrastructure for the io module in place.
2990
2991 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner81fe5bd2019-12-06 02:43:30 +01002992static PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002993_PySys_SetPreliminaryStderr(PyObject *sysdict)
2994{
2995 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2996 if (pstderr == NULL) {
2997 goto error;
2998 }
2999 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3000 goto error;
3001 }
3002 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3003 goto error;
3004 }
3005 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003006 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003007
3008error:
3009 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003010 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003011}
3012
3013
Victor Stinneraf1d64d2020-11-04 17:34:34 +01003014/* Create sys module without all attributes.
3015 _PySys_UpdateConfig() should be called later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003016PyStatus
Victor Stinner01b1cc12019-11-20 02:27:56 +01003017_PySys_Create(PyThreadState *tstate, PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003018{
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003019 assert(!_PyErr_Occurred(tstate));
3020
Victor Stinnerb45d2592019-06-20 00:05:23 +02003021 PyInterpreterState *interp = tstate->interp;
Victor Stinner838f2642019-06-13 22:41:23 +02003022
Victor Stinnerab672812019-01-23 15:04:40 +01003023 PyObject *modules = PyDict_New();
3024 if (modules == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003025 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003026 }
3027 interp->modules = modules;
3028
3029 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3030 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003031 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003032 }
3033
3034 PyObject *sysdict = PyModule_GetDict(sysmod);
3035 if (sysdict == NULL) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003036 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003037 }
3038 Py_INCREF(sysdict);
3039 interp->sysdict = sysdict;
3040
3041 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003042 goto error;
Victor Stinnerab672812019-01-23 15:04:40 +01003043 }
3044
Victor Stinner331a6a52019-05-27 16:39:22 +02003045 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3046 if (_PyStatus_EXCEPTION(status)) {
3047 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003048 }
3049
Victor Stinner01b1cc12019-11-20 02:27:56 +01003050 status = _PySys_InitCore(tstate, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003051 if (_PyStatus_EXCEPTION(status)) {
3052 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003053 }
3054
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003055 if (_PyImport_FixupBuiltin(sysmod, "sys", interp->modules) < 0) {
3056 goto error;
3057 }
3058
3059 assert(!_PyErr_Occurred(tstate));
Victor Stinnerab672812019-01-23 15:04:40 +01003060
3061 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003062 return _PyStatus_OK();
Victor Stinner81fe5bd2019-12-06 02:43:30 +01003063
3064error:
3065 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003066}
3067
3068
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003069static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003070makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003072 int i, n;
3073 const wchar_t *p;
3074 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 n = 1;
3077 p = path;
3078 while ((p = wcschr(p, delim)) != NULL) {
3079 n++;
3080 p++;
3081 }
3082 v = PyList_New(n);
3083 if (v == NULL)
3084 return NULL;
3085 for (i = 0; ; i++) {
3086 p = wcschr(path, delim);
3087 if (p == NULL)
3088 p = path + wcslen(path); /* End of string */
3089 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3090 if (w == NULL) {
3091 Py_DECREF(v);
3092 return NULL;
3093 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003094 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003095 if (*p == '\0')
3096 break;
3097 path = p+1;
3098 }
3099 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003100}
3101
3102void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003103PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003105 PyObject *v;
3106 if ((v = makepathobject(path, DELIM)) == NULL)
3107 Py_FatalError("can't create sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003108 PyThreadState *tstate = _PyThreadState_GET();
3109 if (sys_set_object_id(tstate, &PyId_path, v) != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003110 Py_FatalError("can't assign sys.path");
Victor Stinner838f2642019-06-13 22:41:23 +02003111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003113}
3114
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003115static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003116make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003117{
Victor Stinner74f65682019-03-15 15:08:05 +01003118 PyObject *list = PyList_New(argc);
3119 if (list == NULL) {
3120 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 }
Victor Stinner74f65682019-03-15 15:08:05 +01003122
3123 for (Py_ssize_t i = 0; i < argc; i++) {
3124 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3125 if (v == NULL) {
3126 Py_DECREF(list);
3127 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003128 }
Victor Stinner74f65682019-03-15 15:08:05 +01003129 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 }
Victor Stinner74f65682019-03-15 15:08:05 +01003131 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003132}
3133
Victor Stinner11a247d2017-12-13 21:05:57 +01003134void
3135PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003136{
Victor Stinnerc4868252019-08-23 11:04:16 +01003137 wchar_t* empty_argv[1] = {L""};
Victor Stinner838f2642019-06-13 22:41:23 +02003138 PyThreadState *tstate = _PyThreadState_GET();
3139
Victor Stinner74f65682019-03-15 15:08:05 +01003140 if (argc < 1 || argv == NULL) {
3141 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003142 argv = empty_argv;
3143 argc = 1;
3144 }
3145
3146 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003147 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003148 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003149 }
Serhiy Storchakafb5db7e2020-10-26 08:43:39 +02003150 if (sys_set_object_str(tstate, "argv", av) != 0) {
Victor Stinnerd5dda982017-12-13 17:31:16 +01003151 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003152 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003153 }
3154 Py_DECREF(av);
3155
3156 if (updatepath) {
3157 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3158 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003159 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003160 PyObject *path0 = NULL;
3161 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3162 if (path0 == NULL) {
3163 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003164 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003165
Victor Stinner838f2642019-06-13 22:41:23 +02003166 PyObject *sys_path = sys_get_object_id(tstate, &PyId_path);
Victor Stinnerdcf61712019-03-19 16:09:27 +01003167 if (sys_path != NULL) {
3168 if (PyList_Insert(sys_path, 0, path0) < 0) {
3169 Py_DECREF(path0);
3170 Py_FatalError("can't prepend path0 to sys.path");
3171 }
3172 }
3173 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003174 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003175 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003176}
Guido van Rossuma890e681998-05-12 14:59:24 +00003177
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003178void
3179PySys_SetArgv(int argc, wchar_t **argv)
3180{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003181 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003182}
3183
Victor Stinner14284c22010-04-23 12:02:30 +00003184/* Reimplementation of PyFile_WriteString() no calling indirectly
3185 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3186
3187static int
Victor Stinner79766632010-08-16 17:36:42 +00003188sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003189{
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003190 if (file == NULL)
3191 return -1;
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003192 assert(unicode != NULL);
Jeroen Demeyer59ad1102019-07-11 10:59:05 +02003193 PyObject *result = _PyObject_CallMethodIdOneArg(file, &PyId_write, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003194 if (result == NULL) {
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003195 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 }
Jeroen Demeyerb1263d52019-06-28 11:49:00 +02003197 Py_DECREF(result);
3198 return 0;
Victor Stinner14284c22010-04-23 12:02:30 +00003199}
3200
Victor Stinner79766632010-08-16 17:36:42 +00003201static int
3202sys_pyfile_write(const char *text, PyObject *file)
3203{
3204 PyObject *unicode = NULL;
3205 int err;
3206
3207 if (file == NULL)
3208 return -1;
3209
3210 unicode = PyUnicode_FromString(text);
3211 if (unicode == NULL)
3212 return -1;
3213
3214 err = sys_pyfile_write_unicode(unicode, file);
3215 Py_DECREF(unicode);
3216 return err;
3217}
Guido van Rossuma890e681998-05-12 14:59:24 +00003218
3219/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3220 Adapted from code submitted by Just van Rossum.
3221
3222 PySys_WriteStdout(format, ...)
3223 PySys_WriteStderr(format, ...)
3224
3225 The first function writes to sys.stdout; the second to sys.stderr. When
3226 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003227 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003228
Victor Stinner14284c22010-04-23 12:02:30 +00003229 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003230 signal handlers: they may raise a new exception whereas sys_write()
3231 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003232
Guido van Rossuma890e681998-05-12 14:59:24 +00003233 Both take a printf-style format string as their first argument followed
3234 by a variable length argument list determined by the format string.
3235
3236 *** WARNING ***
3237
3238 The format should limit the total size of the formatted output string to
3239 1000 bytes. In particular, this means that no unrestricted "%s" formats
3240 should occur; these should be limited using "%.<N>s where <N> is a
3241 decimal number calculated so that <N> plus the maximum size of other
3242 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3243 which can print hundreds of digits for very large numbers.
3244
3245 */
3246
3247static void
Victor Stinner09054372013-11-06 22:41:44 +01003248sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003250 PyObject *file;
3251 PyObject *error_type, *error_value, *error_traceback;
3252 char buffer[1001];
3253 int written;
Victor Stinner838f2642019-06-13 22:41:23 +02003254 PyThreadState *tstate = _PyThreadState_GET();
Guido van Rossuma890e681998-05-12 14:59:24 +00003255
Victor Stinner838f2642019-06-13 22:41:23 +02003256 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3257 file = sys_get_object_id(tstate, key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003258 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3259 if (sys_pyfile_write(buffer, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003260 _PyErr_Clear(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003261 fputs(buffer, fp);
3262 }
3263 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3264 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003265 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003266 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003267 }
Victor Stinner838f2642019-06-13 22:41:23 +02003268 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003269}
3270
3271void
Guido van Rossuma890e681998-05-12 14:59:24 +00003272PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003274 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003276 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003277 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003278 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003279}
3280
3281void
Guido van Rossuma890e681998-05-12 14:59:24 +00003282PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003286 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003287 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003288 va_end(va);
3289}
3290
3291static void
Victor Stinner09054372013-11-06 22:41:44 +01003292sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003293{
3294 PyObject *file, *message;
3295 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003296 const char *utf8;
Victor Stinner838f2642019-06-13 22:41:23 +02003297 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner79766632010-08-16 17:36:42 +00003298
Victor Stinner838f2642019-06-13 22:41:23 +02003299 _PyErr_Fetch(tstate, &error_type, &error_value, &error_traceback);
3300 file = sys_get_object_id(tstate, key);
Victor Stinner79766632010-08-16 17:36:42 +00003301 message = PyUnicode_FromFormatV(format, va);
3302 if (message != NULL) {
3303 if (sys_pyfile_write_unicode(message, file) != 0) {
Victor Stinner838f2642019-06-13 22:41:23 +02003304 _PyErr_Clear(tstate);
Serhiy Storchaka06515832016-11-20 09:13:07 +02003305 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003306 if (utf8 != NULL)
3307 fputs(utf8, fp);
3308 }
3309 Py_DECREF(message);
3310 }
Victor Stinner838f2642019-06-13 22:41:23 +02003311 _PyErr_Restore(tstate, error_type, error_value, error_traceback);
Victor Stinner79766632010-08-16 17:36:42 +00003312}
3313
3314void
3315PySys_FormatStdout(const char *format, ...)
3316{
3317 va_list va;
3318
3319 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003320 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003321 va_end(va);
3322}
3323
3324void
3325PySys_FormatStderr(const char *format, ...)
3326{
3327 va_list va;
3328
3329 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003330 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003331 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003332}