blob: b544f2b793ec99860ed2c5d61a8ae6d9e6ed80f1 [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"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinner331a6a52019-05-27 16:39:22 +020020#include "pycore_initconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010021#include "pycore_pylifecycle.h"
22#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010023#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010024#include "pycore_pystate.h"
Steve Dowerb82e17e2019-05-23 08:45:22 -070025#include "pycore_tupleobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020026#include "pythread.h"
Steve Dowerb82e17e2019-05-23 08:45:22 -070027#include "pydtrace.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000028
Guido van Rossume2437a11992-03-23 18:20:18 +000029#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020030#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000031
Mark Hammond8696ebc2002-10-08 02:44:31 +000032#ifdef MS_WINDOWS
33#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000034#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000035#endif /* MS_WINDOWS */
36
Guido van Rossum9b38a141996-09-11 23:12:24 +000037#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000038extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000039/* A string loaded from the DLL at startup: */
40extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000041#endif
42
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080043/*[clinic input]
44module sys
45[clinic start generated code]*/
46/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
47
48#include "clinic/sysmodule.c.h"
49
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(_);
51_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070052_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010053_Py_IDENTIFIER(buffer);
54_Py_IDENTIFIER(builtins);
55_Py_IDENTIFIER(encoding);
56_Py_IDENTIFIER(path);
57_Py_IDENTIFIER(stdout);
58_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070059_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010060_Py_IDENTIFIER(write);
61
Guido van Rossum65bf9f21997-04-29 18:33:38 +000062PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010063_PySys_GetObjectId(_Py_Identifier *key)
64{
Victor Stinnercaba55b2018-08-03 15:33:52 +020065 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
66 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010067 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020068 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010069 return _PyDict_GetItemId(sd, key);
70}
71
72PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000073PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074{
Victor Stinnercaba55b2018-08-03 15:33:52 +020075 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
76 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020078 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000079 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080}
81
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000082int
Victor Stinnerd67bd452013-11-06 22:36:40 +010083_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
84{
Victor Stinnercaba55b2018-08-03 15:33:52 +020085 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010086 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020087 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 }
90 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010091 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020092 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010093 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020094 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010095 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020096 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010097}
98
99int
Neal Norwitzf3081322007-08-25 00:32:45 +0000100PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000101{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200102 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200104 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
107 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200109 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200111 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200113 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000114}
115
Steve Dowerb82e17e2019-05-23 08:45:22 -0700116static int
117should_audit(void)
118{
119 PyThreadState *ts = _PyThreadState_GET();
120 if (!ts) {
121 return 0;
122 }
Victor Stinner0fd2c302019-06-04 03:15:09 +0200123 PyInterpreterState *is = ts ? ts->interp : NULL;
124 return _PyRuntime.audit_hook_head
Steve Dowerb82e17e2019-05-23 08:45:22 -0700125 || (is && is->audit_hooks)
126 || PyDTrace_AUDIT_ENABLED();
127}
128
129int
130PySys_Audit(const char *event, const char *argFormat, ...)
131{
132 PyObject *eventName = NULL;
133 PyObject *eventArgs = NULL;
134 PyObject *hooks = NULL;
135 PyObject *hook = NULL;
136 int res = -1;
137
138 /* N format is inappropriate, because you do not know
139 whether the reference is consumed by the call.
140 Assert rather than exception for perf reasons */
141 assert(!argFormat || !strchr(argFormat, 'N'));
142
143 /* Early exit when no hooks are registered */
144 if (!should_audit()) {
145 return 0;
146 }
147
148 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
149 PyThreadState *ts = _PyThreadState_GET();
150 PyInterpreterState *is = ts ? ts->interp : NULL;
151 int dtrace = PyDTrace_AUDIT_ENABLED();
152
153 PyObject *exc_type, *exc_value, *exc_tb;
154 if (ts) {
155 PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
156 }
157
158 /* Initialize event args now */
159 if (argFormat && argFormat[0]) {
160 va_list args;
161 va_start(args, argFormat);
Miss Islington (bot)c93d68b2019-12-09 11:22:30 -0800162 eventArgs = _Py_VaBuildValue_SizeT(argFormat, args);
Steve Dower6c794772019-06-21 09:45:13 -0700163 va_end(args);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700164 if (eventArgs && !PyTuple_Check(eventArgs)) {
165 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
166 Py_DECREF(eventArgs);
167 eventArgs = argTuple;
168 }
169 } else {
170 eventArgs = PyTuple_New(0);
171 }
172 if (!eventArgs) {
173 goto exit;
174 }
175
176 /* Call global hooks */
177 for (; e; e = e->next) {
178 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
179 goto exit;
180 }
181 }
182
183 /* Dtrace USDT point */
184 if (dtrace) {
185 PyDTrace_AUDIT(event, (void *)eventArgs);
186 }
187
188 /* Call interpreter hooks */
189 if (is && is->audit_hooks) {
190 eventName = PyUnicode_FromString(event);
191 if (!eventName) {
192 goto exit;
193 }
194
195 hooks = PyObject_GetIter(is->audit_hooks);
196 if (!hooks) {
197 goto exit;
198 }
199
200 /* Disallow tracing in hooks unless explicitly enabled */
201 ts->tracing++;
202 ts->use_tracing = 0;
203 while ((hook = PyIter_Next(hooks)) != NULL) {
Serhiy Storchaka353053d2019-09-01 14:01:05 +0300204 _Py_IDENTIFIER(__cantrace__);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700205 PyObject *o;
Serhiy Storchaka353053d2019-09-01 14:01:05 +0300206 int canTrace = _PyObject_LookupAttrId(hook, &PyId___cantrace__, &o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700207 if (o) {
208 canTrace = PyObject_IsTrue(o);
209 Py_DECREF(o);
Steve Dowerb82e17e2019-05-23 08:45:22 -0700210 }
211 if (canTrace < 0) {
212 break;
213 }
214 if (canTrace) {
215 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
216 ts->tracing--;
217 }
218 o = PyObject_CallFunctionObjArgs(hook, eventName,
219 eventArgs, NULL);
220 if (canTrace) {
221 ts->tracing++;
222 ts->use_tracing = 0;
223 }
224 if (!o) {
225 break;
226 }
227 Py_DECREF(o);
228 Py_CLEAR(hook);
229 }
230 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
231 ts->tracing--;
232 if (PyErr_Occurred()) {
233 goto exit;
234 }
235 }
236
237 res = 0;
238
239exit:
240 Py_XDECREF(hook);
241 Py_XDECREF(hooks);
242 Py_XDECREF(eventName);
243 Py_XDECREF(eventArgs);
244
245 if (ts) {
246 if (!res) {
247 PyErr_Restore(exc_type, exc_value, exc_tb);
248 } else {
249 assert(PyErr_Occurred());
250 Py_XDECREF(exc_type);
251 Py_XDECREF(exc_value);
252 Py_XDECREF(exc_tb);
253 }
254 }
255
256 return res;
257}
258
259/* We expose this function primarily for our own cleanup during
260 * finalization. In general, it should not need to be called,
261 * and as such it is not defined in any header files.
262 */
263void _PySys_ClearAuditHooks(void) {
264 /* Must be finalizing to clear hooks */
265 _PyRuntimeState *runtime = &_PyRuntime;
266 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
267 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
268 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts))
269 return;
270
271 if (Py_VerboseFlag) {
272 PySys_WriteStderr("# clear sys.audit hooks\n");
273 }
274
275 /* Hooks can abort later hooks for this event, but cannot
276 abort the clear operation itself. */
277 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
278 PyErr_Clear();
279
Victor Stinner0fd2c302019-06-04 03:15:09 +0200280 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
281 _PyRuntime.audit_hook_head = NULL;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700282 while (e) {
283 n = e->next;
284 PyMem_RawFree(e);
285 e = n;
286 }
287}
288
289int
290PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
291{
292 /* Invoke existing audit hooks to allow them an opportunity to abort. */
293 /* Cannot invoke hooks until we are initialized */
294 if (Py_IsInitialized()) {
295 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
Steve Dowerb74a6f12019-11-28 08:46:23 -0800296 if (PyErr_ExceptionMatches(PyExc_RuntimeError)) {
297 /* We do not report errors derived from RuntimeError */
Steve Dowerb82e17e2019-05-23 08:45:22 -0700298 PyErr_Clear();
299 return 0;
300 }
301 return -1;
302 }
303 }
304
Victor Stinner0fd2c302019-06-04 03:15:09 +0200305 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700306 if (!e) {
307 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
Victor Stinner0fd2c302019-06-04 03:15:09 +0200308 _PyRuntime.audit_hook_head = e;
Steve Dowerb82e17e2019-05-23 08:45:22 -0700309 } else {
310 while (e->next)
311 e = e->next;
312 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
313 sizeof(_Py_AuditHookEntry));
314 }
315
316 if (!e) {
317 if (Py_IsInitialized())
318 PyErr_NoMemory();
319 return -1;
320 }
321
322 e->next = NULL;
323 e->hookCFunction = (Py_AuditHookFunction)hook;
324 e->userData = userData;
325
326 return 0;
327}
328
329/*[clinic input]
330sys.addaudithook
331
332 hook: object
333
334Adds a new audit hook callback.
335[clinic start generated code]*/
336
337static PyObject *
338sys_addaudithook_impl(PyObject *module, PyObject *hook)
339/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
340{
341 /* Invoke existing audit hooks to allow them an opportunity to abort. */
342 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
343 if (PyErr_ExceptionMatches(PyExc_Exception)) {
344 /* We do not report errors derived from Exception */
345 PyErr_Clear();
346 Py_RETURN_NONE;
347 }
348 return NULL;
349 }
350
351 PyInterpreterState *is = _PyInterpreterState_Get();
352
353 if (is->audit_hooks == NULL) {
354 is->audit_hooks = PyList_New(0);
355 if (is->audit_hooks == NULL) {
356 return NULL;
357 }
358 }
359
360 if (PyList_Append(is->audit_hooks, hook) < 0) {
361 return NULL;
362 }
363
364 Py_RETURN_NONE;
365}
366
367PyDoc_STRVAR(audit_doc,
368"audit(event, *args)\n\
369\n\
370Passes the event to any audit hooks that are attached.");
371
372static PyObject *
373sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
374{
375 if (argc == 0) {
376 PyErr_SetString(PyExc_TypeError, "audit() missing 1 required positional argument: 'event'");
377 return NULL;
378 }
379
380 if (!should_audit()) {
381 Py_RETURN_NONE;
382 }
383
384 PyObject *auditEvent = args[0];
385 if (!auditEvent) {
386 PyErr_SetString(PyExc_TypeError, "expected str for argument 'event'");
387 return NULL;
388 }
389 if (!PyUnicode_Check(auditEvent)) {
390 PyErr_Format(PyExc_TypeError, "expected str for argument 'event', not %.200s",
391 Py_TYPE(auditEvent)->tp_name);
392 return NULL;
393 }
394 const char *event = PyUnicode_AsUTF8(auditEvent);
395 if (!event) {
396 return NULL;
397 }
398
399 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
400 if (!auditArgs) {
401 return NULL;
402 }
403
404 int res = PySys_Audit(event, "O", auditArgs);
405 Py_DECREF(auditArgs);
406
407 if (res < 0) {
408 return NULL;
409 }
410
411 Py_RETURN_NONE;
412}
413
414
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400415static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200416sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400417{
418 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300419 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400420
421 if (envar == NULL || strlen(envar) == 0) {
422 envar = "pdb.set_trace";
423 }
424 else if (!strcmp(envar, "0")) {
425 /* The breakpoint is explicitly no-op'd. */
426 Py_RETURN_NONE;
427 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300428 /* According to POSIX the string returned by getenv() might be invalidated
429 * or the string content might be overwritten by a subsequent call to
430 * getenv(). Since importing a module can performs the getenv() calls,
431 * we need to save a copy of envar. */
432 envar = _PyMem_RawStrdup(envar);
433 if (envar == NULL) {
434 PyErr_NoMemory();
435 return NULL;
436 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200437 const char *last_dot = strrchr(envar, '.');
438 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400439 PyObject *modulepath = NULL;
440
441 if (last_dot == NULL) {
442 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
443 modulepath = PyUnicode_FromString("builtins");
444 attrname = envar;
445 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200446 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400447 /* Split on the last dot; */
448 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
449 attrname = last_dot + 1;
450 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200451 else {
452 goto warn;
453 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400454 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300455 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400456 return NULL;
457 }
458
Anthony Sottiledce345c2018-11-01 10:25:05 -0700459 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400460 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400461
462 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200463 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
464 goto warn;
465 }
466 PyMem_RawFree(envar);
467 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400468 }
469
470 PyObject *hook = PyObject_GetAttrString(module, attrname);
471 Py_DECREF(module);
472
473 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200474 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
475 goto warn;
476 }
477 PyMem_RawFree(envar);
478 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400479 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300480 PyMem_RawFree(envar);
Jeroen Demeyeraacc77f2019-05-29 20:31:52 +0200481 PyObject *retval = _PyObject_Vectorcall(hook, args, nargs, keywords);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400482 Py_DECREF(hook);
483 return retval;
484
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200485 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400486 /* If any of the imports went wrong, then warn and ignore. */
487 PyErr_Clear();
488 int status = PyErr_WarnFormat(
489 PyExc_RuntimeWarning, 0,
490 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300491 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400492 if (status < 0) {
493 /* Printing the warning raised an exception. */
494 return NULL;
495 }
496 /* The warning was (probably) issued. */
497 Py_RETURN_NONE;
498}
499
500PyDoc_STRVAR(breakpointhook_doc,
501"breakpointhook(*args, **kws)\n"
502"\n"
503"This hook function is called by built-in breakpoint().\n"
504);
505
Victor Stinner13d49ee2010-12-04 17:24:33 +0000506/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
507 error handler. If sys.stdout has a buffer attribute, use
508 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
509 sys.stdout.write(redecoded).
510
511 Helper function for sys_displayhook(). */
512static int
513sys_displayhook_unencodable(PyObject *outf, PyObject *o)
514{
515 PyObject *stdout_encoding = NULL;
516 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200517 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000518 int ret;
519
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200520 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000521 if (stdout_encoding == NULL)
522 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200523 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000524 if (stdout_encoding_str == NULL)
525 goto error;
526
527 repr_str = PyObject_Repr(o);
528 if (repr_str == NULL)
529 goto error;
530 encoded = PyUnicode_AsEncodedString(repr_str,
531 stdout_encoding_str,
532 "backslashreplace");
533 Py_DECREF(repr_str);
534 if (encoded == NULL)
535 goto error;
536
Serhiy Storchaka353053d2019-09-01 14:01:05 +0300537 if (_PyObject_LookupAttrId(outf, &PyId_buffer, &buffer) < 0) {
538 Py_DECREF(encoded);
539 goto error;
540 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000541 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100542 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000543 Py_DECREF(buffer);
544 Py_DECREF(encoded);
545 if (result == NULL)
546 goto error;
547 Py_DECREF(result);
548 }
549 else {
Victor Stinner13d49ee2010-12-04 17:24:33 +0000550 escaped_str = PyUnicode_FromEncodedObject(encoded,
551 stdout_encoding_str,
552 "strict");
553 Py_DECREF(encoded);
554 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
555 Py_DECREF(escaped_str);
556 goto error;
557 }
558 Py_DECREF(escaped_str);
559 }
560 ret = 0;
561 goto finally;
562
563error:
564 ret = -1;
565finally:
566 Py_XDECREF(stdout_encoding);
567 return ret;
568}
569
Tal Einatede0b6f2018-12-31 17:12:08 +0200570/*[clinic input]
571sys.displayhook
572
573 object as o: object
574 /
575
576Print an object to sys.stdout and also save it in builtins._
577[clinic start generated code]*/
578
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000579static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200580sys_displayhook(PyObject *module, PyObject *o)
581/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000582{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100584 PyObject *builtins;
585 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000586 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000587
Eric Snow3f9eee62017-09-15 16:35:20 -0600588 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (builtins == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +0100590 if (!PyErr_Occurred()) {
591 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return NULL;
594 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600595 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 /* Print value except if None */
598 /* After printing, also assign to '_' */
599 /* Before, set '_' to None to avoid recursion */
600 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200601 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200603 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100605 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (outf == NULL || outf == Py_None) {
607 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
608 return NULL;
609 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000610 if (PyFile_WriteObject(o, outf, 0) != 0) {
611 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
612 /* repr(o) is not encodable to sys.stdout.encoding with
613 * sys.stdout.errors error handler (which is probably 'strict') */
614 PyErr_Clear();
615 err = sys_displayhook_unencodable(outf, o);
616 if (err)
617 return NULL;
618 }
619 else {
620 return NULL;
621 }
622 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100623 if (newline == NULL) {
624 newline = PyUnicode_FromString("\n");
625 if (newline == NULL)
626 return NULL;
627 }
628 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000629 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200630 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200632 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000633}
634
Tal Einatede0b6f2018-12-31 17:12:08 +0200635
636/*[clinic input]
637sys.excepthook
638
639 exctype: object
640 value: object
641 traceback: object
642 /
643
644Handle an exception by displaying it with a traceback on sys.stderr.
645[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000646
647static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200648sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
649 PyObject *traceback)
650/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000651{
Tal Einatede0b6f2018-12-31 17:12:08 +0200652 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200653 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000654}
655
Tal Einatede0b6f2018-12-31 17:12:08 +0200656
657/*[clinic input]
658sys.exc_info
659
660Return current exception information: (type, value, traceback).
661
662Return information about the most recent exception caught by an except
663clause in the current stack frame or in an older stack frame.
664[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000665
666static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200667sys_exc_info_impl(PyObject *module)
668/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000669{
Victor Stinner50b48572018-11-01 01:51:40 +0100670 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return Py_BuildValue(
672 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100673 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
674 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
675 err_info->exc_traceback != NULL ?
676 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000677}
678
Tal Einatede0b6f2018-12-31 17:12:08 +0200679
680/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200681sys.unraisablehook
682
683 unraisable: object
684 /
685
686Handle an unraisable exception.
687
688The unraisable argument has the following attributes:
689
690* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200691* exc_value: Exception value, can be None.
692* exc_traceback: Exception traceback, can be None.
693* err_msg: Error message, can be None.
694* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200695[clinic start generated code]*/
696
697static PyObject *
698sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200699/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200700{
701 return _PyErr_WriteUnraisableDefaultHook(unraisable);
702}
703
704
705/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200706sys.exit
707
Serhiy Storchakad322abb2019-09-14 13:31:50 +0300708 status: object = None
Tal Einatede0b6f2018-12-31 17:12:08 +0200709 /
710
711Exit the interpreter by raising SystemExit(status).
712
713If the status is omitted or None, it defaults to zero (i.e., success).
714If the status is an integer, it will be used as the system exit status.
715If it is another kind of object, it will be printed and the system
716exit status will be one (i.e., failure).
717[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000718
719static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200720sys_exit_impl(PyObject *module, PyObject *status)
Serhiy Storchakad322abb2019-09-14 13:31:50 +0300721/*[clinic end generated code: output=13870986c1ab2ec0 input=b86ca9497baa94f2]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200724 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726}
727
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000728
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000729
Tal Einatede0b6f2018-12-31 17:12:08 +0200730/*[clinic input]
731sys.getdefaultencoding
732
733Return the current default encoding used by the Unicode implementation.
734[clinic start generated code]*/
735
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000736static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200737sys_getdefaultencoding_impl(PyObject *module)
738/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000741}
742
Tal Einatede0b6f2018-12-31 17:12:08 +0200743/*[clinic input]
744sys.getfilesystemencoding
745
746Return the encoding used to convert Unicode filenames to OS filenames.
747[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000748
749static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200750sys_getfilesystemencoding_impl(PyObject *module)
751/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000752{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200753 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +0200754 const PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400755 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000756}
757
Tal Einatede0b6f2018-12-31 17:12:08 +0200758/*[clinic input]
759sys.getfilesystemencodeerrors
760
761Return the error mode used Unicode to OS filename conversion.
762[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000763
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000764static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200765sys_getfilesystemencodeerrors_impl(PyObject *module)
766/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700767{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200768 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
Victor Stinner331a6a52019-05-27 16:39:22 +0200769 const PyConfig *config = &interp->config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400770 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700771}
772
Tal Einatede0b6f2018-12-31 17:12:08 +0200773/*[clinic input]
774sys.intern
775
776 string as s: unicode
777 /
778
779``Intern'' the given string.
780
781This enters the string in the (global) table of interned strings whose
782purpose is to speed up dictionary lookups. Return the string itself or
783the previously interned string object with the same value.
784[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700785
786static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200787sys_intern_impl(PyObject *module, PyObject *s)
788/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (PyUnicode_CheckExact(s)) {
791 Py_INCREF(s);
792 PyUnicode_InternInPlace(&s);
793 return s;
794 }
795 else {
796 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200797 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return NULL;
799 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000800}
801
Georg Brandl66a796e2006-12-19 20:50:34 +0000802
Fred Drake5755ce62001-06-27 19:19:46 +0000803/*
804 * Cached interned string objects used for calling the profile and
805 * trace functions. Initialized by trace_init().
806 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000807static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000808
809static int
810trace_init(void)
811{
Nick Coghlan5a851672017-09-08 10:14:16 +1000812 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200813 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000814 "c_call", "c_exception", "c_return",
815 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200816 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject *name;
818 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000819 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (whatstrings[i] == NULL) {
821 name = PyUnicode_InternFromString(whatnames[i]);
822 if (name == NULL)
823 return -1;
824 whatstrings[i] = name;
825 }
826 }
827 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000828}
829
830
831static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100832call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200836 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000837
Victor Stinner78da82b2016-08-20 01:22:57 +0200838 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200840 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100841
Victor Stinner78da82b2016-08-20 01:22:57 +0200842 stack[0] = (PyObject *)frame;
843 stack[1] = whatstrings[what];
844 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200847 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000848
Victor Stinner78da82b2016-08-20 01:22:57 +0200849 PyFrame_LocalsToFast(frame, 1);
850 if (result == NULL) {
851 PyTraceBack_Here(frame);
852 }
853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000855}
856
857static int
858profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (arg == NULL)
864 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100865 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (result == NULL) {
867 PyEval_SetProfile(NULL, NULL);
868 return -1;
869 }
870 Py_DECREF(result);
871 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000872}
873
874static int
875trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyObject *callback;
879 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (what == PyTrace_CALL)
882 callback = self;
883 else
884 callback = frame->f_trace;
885 if (callback == NULL)
886 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100887 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (result == NULL) {
889 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200890 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return -1;
892 }
893 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300894 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 }
896 else {
897 Py_DECREF(result);
898 }
899 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000900}
Fred Draked0838392001-06-16 21:02:31 +0000901
Fred Drake8b4d01d2000-05-09 19:57:01 +0000902static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000903sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (trace_init() == -1)
906 return NULL;
907 if (args == Py_None)
908 PyEval_SetTrace(NULL, NULL);
909 else
910 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200911 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000912}
913
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000914PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000915"settrace(function)\n\
916\n\
917Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000918function call. See the debugger chapter in the library manual."
919);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000920
Tal Einatede0b6f2018-12-31 17:12:08 +0200921/*[clinic input]
922sys.gettrace
923
924Return the global debug tracing function set with sys.settrace.
925
926See the debugger chapter in the library manual.
927[clinic start generated code]*/
928
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000929static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200930sys_gettrace_impl(PyObject *module)
931/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000932{
Victor Stinner50b48572018-11-01 01:51:40 +0100933 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (temp == NULL)
937 temp = Py_None;
938 Py_INCREF(temp);
939 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000940}
941
Christian Heimes9bd667a2008-01-20 15:14:11 +0000942static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000943sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (trace_init() == -1)
946 return NULL;
947 if (args == Py_None)
948 PyEval_SetProfile(NULL, NULL);
949 else
950 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200951 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000952}
953
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000954PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000955"setprofile(function)\n\
956\n\
957Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000958and return. See the profiler chapter in the library manual."
959);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000960
Tal Einatede0b6f2018-12-31 17:12:08 +0200961/*[clinic input]
962sys.getprofile
963
964Return the profiling function set with sys.setprofile.
965
966See the profiler chapter in the library manual.
967[clinic start generated code]*/
968
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000969static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200970sys_getprofile_impl(PyObject *module)
971/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000972{
Victor Stinner50b48572018-11-01 01:51:40 +0100973 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (temp == NULL)
977 temp = Py_None;
978 Py_INCREF(temp);
979 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000980}
981
Tal Einatede0b6f2018-12-31 17:12:08 +0200982/*[clinic input]
983sys.setcheckinterval
984
985 n: int
986 /
987
988Set the async event check interval to n instructions.
989
990This tells the Python interpreter to check for asynchronous events
991every n instructions.
992
993This also affects how often thread switches occur.
994[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000995
996static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200997sys_setcheckinterval_impl(PyObject *module, int n)
998/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1001 "sys.getcheckinterval() and sys.setcheckinterval() "
1002 "are deprecated. Use sys.setswitchinterval() "
1003 "instead.", 1) < 0)
1004 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001005
Victor Stinnercaba55b2018-08-03 15:33:52 +02001006 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +02001007 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001008 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001009}
1010
Tal Einatede0b6f2018-12-31 17:12:08 +02001011/*[clinic input]
1012sys.getcheckinterval
1013
1014Return the current check interval; see sys.setcheckinterval().
1015[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001016
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001017static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001018sys_getcheckinterval_impl(PyObject *module)
1019/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1022 "sys.getcheckinterval() and sys.setcheckinterval() "
1023 "are deprecated. Use sys.getswitchinterval() "
1024 "instead.", 1) < 0)
1025 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001026 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001027 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001028}
1029
Tal Einatede0b6f2018-12-31 17:12:08 +02001030/*[clinic input]
1031sys.setswitchinterval
1032
1033 interval: double
1034 /
1035
1036Set the ideal thread switching delay inside the Python interpreter.
1037
1038The actual frequency of switching threads can be lower if the
1039interpreter executes long sequences of uninterruptible code
1040(this is implementation-specific and workload-dependent).
1041
1042The parameter must represent the desired switching delay in seconds
1043A typical value is 0.005 (5 milliseconds).
1044[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001045
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001046static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001047sys_setswitchinterval_impl(PyObject *module, double interval)
1048/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001049{
Tal Einatede0b6f2018-12-31 17:12:08 +02001050 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyErr_SetString(PyExc_ValueError,
1052 "switch interval must be strictly positive");
1053 return NULL;
1054 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001055 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001056 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001057}
1058
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001059
Tal Einatede0b6f2018-12-31 17:12:08 +02001060/*[clinic input]
1061sys.getswitchinterval -> double
1062
1063Return the current thread switch interval; see sys.setswitchinterval().
1064[clinic start generated code]*/
1065
1066static double
1067sys_getswitchinterval_impl(PyObject *module)
1068/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001069{
Tal Einatede0b6f2018-12-31 17:12:08 +02001070 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001071}
1072
Tal Einatede0b6f2018-12-31 17:12:08 +02001073/*[clinic input]
1074sys.setrecursionlimit
1075
1076 limit as new_limit: int
1077 /
1078
1079Set the maximum depth of the Python interpreter stack to n.
1080
1081This limit prevents infinite recursion from causing an overflow of the C
1082stack and crashing Python. The highest possible limit is platform-
1083dependent.
1084[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001085
Tim Peterse5e065b2003-07-06 18:36:54 +00001086static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001087sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1088/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001089{
Tal Einatede0b6f2018-12-31 17:12:08 +02001090 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +02001091 PyThreadState *tstate;
1092
Victor Stinner50856d52015-10-13 00:11:21 +02001093 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +02001095 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 return NULL;
1097 }
Victor Stinner50856d52015-10-13 00:11:21 +02001098
1099 /* Issue #25274: When the recursion depth hits the recursion limit in
1100 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1101 set to 1 and a RecursionError is raised. The overflowed flag is reset
1102 to 0 when the recursion depth goes below the low-water mark: see
1103 Py_LeaveRecursiveCall().
1104
1105 Reject too low new limit if the current recursion depth is higher than
1106 the new low-water mark. Otherwise it may not be possible anymore to
1107 reset the overflowed flag to 0. */
1108 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +01001109 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001110 if (tstate->recursion_depth >= mark) {
1111 PyErr_Format(PyExc_RecursionError,
1112 "cannot set the recursion limit to %i at "
1113 "the recursion depth %i: the limit is too low",
1114 new_limit, tstate->recursion_depth);
1115 return NULL;
1116 }
1117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001119 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001120}
1121
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001122/*[clinic input]
1123sys.set_coroutine_origin_tracking_depth
1124
1125 depth: int
1126
1127Enable or disable origin tracking for coroutine objects in this thread.
1128
Tal Einatede0b6f2018-12-31 17:12:08 +02001129Coroutine objects will track 'depth' frames of traceback information
1130about where they came from, available in their cr_origin attribute.
1131
1132Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001133[clinic start generated code]*/
1134
1135static PyObject *
1136sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001137/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001138{
1139 if (depth < 0) {
1140 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
1141 return NULL;
1142 }
1143 _PyEval_SetCoroutineOriginTrackingDepth(depth);
1144 Py_RETURN_NONE;
1145}
1146
1147/*[clinic input]
1148sys.get_coroutine_origin_tracking_depth -> int
1149
1150Check status of origin tracking for coroutine objects in this thread.
1151[clinic start generated code]*/
1152
1153static int
1154sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1155/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1156{
1157 return _PyEval_GetCoroutineOriginTrackingDepth();
1158}
1159
Yury Selivanoveb636452016-09-08 22:01:51 -07001160static PyTypeObject AsyncGenHooksType;
1161
1162PyDoc_STRVAR(asyncgen_hooks_doc,
1163"asyncgen_hooks\n\
1164\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +01001165A named tuple providing information about asynchronous\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001166generators hooks. The attributes are read only.");
1167
1168static PyStructSequence_Field asyncgen_hooks_fields[] = {
1169 {"firstiter", "Hook to intercept first iteration"},
1170 {"finalizer", "Hook to intercept finalization"},
1171 {0}
1172};
1173
1174static PyStructSequence_Desc asyncgen_hooks_desc = {
1175 "asyncgen_hooks", /* name */
1176 asyncgen_hooks_doc, /* doc */
1177 asyncgen_hooks_fields , /* fields */
1178 2
1179};
1180
Serhiy Storchaka87a4cd52020-03-02 09:58:48 +02001181static int
1182set_async_gen_firstiter(PyObject *firstiter)
1183{
1184 PyThreadState *tstate = _PyThreadState_GET();
1185
1186 if (PySys_Audit("sys.set_asyncgen_hook_firstiter", NULL) < 0) {
1187 return -1;
1188 }
1189
1190 Py_XINCREF(firstiter);
1191 Py_XSETREF(tstate->async_gen_firstiter, firstiter);
1192 return 0;
1193}
1194
1195void
1196_PyEval_SetAsyncGenFirstiter(PyObject *firstiter)
1197{
1198 if (set_async_gen_firstiter(firstiter) < 0) {
1199 PyErr_WriteUnraisable(NULL);
1200 }
1201}
1202
1203static int
1204set_async_gen_finalizer(PyObject *finalizer)
1205{
1206 PyThreadState *tstate = _PyThreadState_GET();
1207
1208 if (PySys_Audit("sys.set_asyncgen_hook_finalizer", NULL) < 0) {
1209 return -1;
1210 }
1211
1212 Py_XINCREF(finalizer);
1213 Py_XSETREF(tstate->async_gen_finalizer, finalizer);
1214 return 0;
1215}
1216
1217void
1218_PyEval_SetAsyncGenFinalizer(PyObject *finalizer)
1219{
1220 if (set_async_gen_finalizer(finalizer) < 0) {
1221 PyErr_WriteUnraisable(NULL);
1222 }
1223}
1224
1225
Yury Selivanoveb636452016-09-08 22:01:51 -07001226static PyObject *
1227sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1228{
1229 static char *keywords[] = {"firstiter", "finalizer", NULL};
1230 PyObject *firstiter = NULL;
1231 PyObject *finalizer = NULL;
1232
1233 if (!PyArg_ParseTupleAndKeywords(
1234 args, kw, "|OO", keywords,
1235 &firstiter, &finalizer)) {
1236 return NULL;
1237 }
1238
1239 if (finalizer && finalizer != Py_None) {
1240 if (!PyCallable_Check(finalizer)) {
1241 PyErr_Format(PyExc_TypeError,
1242 "callable finalizer expected, got %.50s",
1243 Py_TYPE(finalizer)->tp_name);
1244 return NULL;
1245 }
Serhiy Storchaka87a4cd52020-03-02 09:58:48 +02001246 if (set_async_gen_finalizer(finalizer) < 0) {
1247 return NULL;
1248 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001249 }
Serhiy Storchaka87a4cd52020-03-02 09:58:48 +02001250 else if (finalizer == Py_None && set_async_gen_finalizer(NULL) < 0) {
1251 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001252 }
1253
1254 if (firstiter && firstiter != Py_None) {
1255 if (!PyCallable_Check(firstiter)) {
1256 PyErr_Format(PyExc_TypeError,
1257 "callable firstiter expected, got %.50s",
1258 Py_TYPE(firstiter)->tp_name);
1259 return NULL;
1260 }
Serhiy Storchaka87a4cd52020-03-02 09:58:48 +02001261 if (set_async_gen_firstiter(firstiter) < 0) {
1262 return NULL;
1263 }
Yury Selivanoveb636452016-09-08 22:01:51 -07001264 }
Serhiy Storchaka87a4cd52020-03-02 09:58:48 +02001265 else if (firstiter == Py_None && set_async_gen_firstiter(NULL) < 0) {
1266 return NULL;
Yury Selivanoveb636452016-09-08 22:01:51 -07001267 }
1268
1269 Py_RETURN_NONE;
1270}
1271
1272PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001273"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001274\n\
1275Set a finalizer for async generators objects."
1276);
1277
Tal Einatede0b6f2018-12-31 17:12:08 +02001278/*[clinic input]
1279sys.get_asyncgen_hooks
1280
1281Return the installed asynchronous generators hooks.
1282
1283This returns a namedtuple of the form (firstiter, finalizer).
1284[clinic start generated code]*/
1285
Yury Selivanoveb636452016-09-08 22:01:51 -07001286static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001287sys_get_asyncgen_hooks_impl(PyObject *module)
1288/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001289{
1290 PyObject *res;
1291 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1292 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1293
1294 res = PyStructSequence_New(&AsyncGenHooksType);
1295 if (res == NULL) {
1296 return NULL;
1297 }
1298
1299 if (firstiter == NULL) {
1300 firstiter = Py_None;
1301 }
1302
1303 if (finalizer == NULL) {
1304 finalizer = Py_None;
1305 }
1306
1307 Py_INCREF(firstiter);
1308 PyStructSequence_SET_ITEM(res, 0, firstiter);
1309
1310 Py_INCREF(finalizer);
1311 PyStructSequence_SET_ITEM(res, 1, finalizer);
1312
1313 return res;
1314}
1315
Yury Selivanoveb636452016-09-08 22:01:51 -07001316
Mark Dickinsondc787d22010-05-23 13:33:13 +00001317static PyTypeObject Hash_InfoType;
1318
1319PyDoc_STRVAR(hash_info_doc,
1320"hash_info\n\
1321\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +01001322A named tuple providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001323hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001324
1325static PyStructSequence_Field hash_info_fields[] = {
1326 {"width", "width of the type used for hashing, in bits"},
1327 {"modulus", "prime number giving the modulus on which the hash "
1328 "function is based"},
1329 {"inf", "value to be used for hash of a positive infinity"},
1330 {"nan", "value to be used for hash of a nan"},
1331 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001332 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1333 "memoryviews"},
1334 {"hash_bits", "internal output size of hash algorithm"},
1335 {"seed_bits", "seed size of hash algorithm"},
1336 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001337 {NULL, NULL}
1338};
1339
1340static PyStructSequence_Desc hash_info_desc = {
1341 "sys.hash_info",
1342 hash_info_doc,
1343 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001344 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001345};
1346
Matthias Klosed885e952010-07-06 10:53:30 +00001347static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001348get_hash_info(void)
1349{
1350 PyObject *hash_info;
1351 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001352 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001353 hash_info = PyStructSequence_New(&Hash_InfoType);
1354 if (hash_info == NULL)
1355 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001356 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001357 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001358 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001359 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001360 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001361 PyStructSequence_SET_ITEM(hash_info, field++,
1362 PyLong_FromLong(_PyHASH_INF));
1363 PyStructSequence_SET_ITEM(hash_info, field++,
1364 PyLong_FromLong(_PyHASH_NAN));
1365 PyStructSequence_SET_ITEM(hash_info, field++,
1366 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001367 PyStructSequence_SET_ITEM(hash_info, field++,
1368 PyUnicode_FromString(hashfunc->name));
1369 PyStructSequence_SET_ITEM(hash_info, field++,
1370 PyLong_FromLong(hashfunc->hash_bits));
1371 PyStructSequence_SET_ITEM(hash_info, field++,
1372 PyLong_FromLong(hashfunc->seed_bits));
1373 PyStructSequence_SET_ITEM(hash_info, field++,
1374 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001375 if (PyErr_Occurred()) {
1376 Py_CLEAR(hash_info);
1377 return NULL;
1378 }
1379 return hash_info;
1380}
Tal Einatede0b6f2018-12-31 17:12:08 +02001381/*[clinic input]
1382sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001383
Tal Einatede0b6f2018-12-31 17:12:08 +02001384Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001385
Tal Einatede0b6f2018-12-31 17:12:08 +02001386The recursion limit is the maximum depth of the Python interpreter
1387stack. This limit prevents infinite recursion from causing an overflow
1388of the C stack and crashing Python.
1389[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001390
1391static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001392sys_getrecursionlimit_impl(PyObject *module)
1393/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001396}
1397
Mark Hammond8696ebc2002-10-08 02:44:31 +00001398#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001399
Eric Smithf7bb5782010-01-27 00:44:57 +00001400static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1401
1402static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 {"major", "Major version number"},
1404 {"minor", "Minor version number"},
1405 {"build", "Build number"},
1406 {"platform", "Operating system platform"},
1407 {"service_pack", "Latest Service Pack installed on the system"},
1408 {"service_pack_major", "Service Pack major version number"},
1409 {"service_pack_minor", "Service Pack minor version number"},
1410 {"suite_mask", "Bit mask identifying available product suites"},
1411 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001412 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001414};
1415
1416static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001417 "sys.getwindowsversion", /* name */
1418 sys_getwindowsversion__doc__, /* doc */
1419 windows_version_fields, /* fields */
1420 5 /* For backward compatibility,
1421 only the first 5 items are accessible
1422 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001423};
1424
Steve Dower3e96f322015-03-02 08:01:10 -08001425/* Disable deprecation warnings about GetVersionEx as the result is
1426 being passed straight through to the caller, who is responsible for
1427 using it correctly. */
1428#pragma warning(push)
1429#pragma warning(disable:4996)
1430
Tal Einatede0b6f2018-12-31 17:12:08 +02001431/*[clinic input]
1432sys.getwindowsversion
1433
1434Return info about the running version of Windows as a named tuple.
1435
1436The members are named: major, minor, build, platform, service_pack,
1437service_pack_major, service_pack_minor, suite_mask, product_type and
1438platform_version. For backward compatibility, only the first 5 items
1439are available by indexing. All elements are numbers, except
1440service_pack and platform_type which are strings, and platform_version
1441which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1442workstation, 2 for a domain controller, 3 for a server.
1443Platform_version is a 3-tuple containing a version number that is
1444intended for identifying the OS rather than feature detection.
1445[clinic start generated code]*/
1446
Mark Hammond8696ebc2002-10-08 02:44:31 +00001447static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001448sys_getwindowsversion_impl(PyObject *module)
1449/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 PyObject *version;
1452 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001453 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001454 DWORD realMajor, realMinor, realBuild;
1455 HANDLE hKernel32;
1456 wchar_t kernel32_path[MAX_PATH];
1457 LPVOID verblock;
1458 DWORD verblock_size;
1459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001461 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 version = PyStructSequence_New(&WindowsVersionType);
1465 if (version == NULL)
1466 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1469 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1470 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1471 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001472 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1474 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1475 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1476 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001477
Steve Dower74f4af72016-09-17 17:27:48 -07001478 realMajor = ver.dwMajorVersion;
1479 realMinor = ver.dwMinorVersion;
1480 realBuild = ver.dwBuildNumber;
1481
1482 // GetVersion will lie if we are running in a compatibility mode.
1483 // We need to read the version info from a system file resource
1484 // to accurately identify the OS version. If we fail for any reason,
1485 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001486 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001487 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001488 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001489 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1490 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1491 (verblock = PyMem_RawMalloc(verblock_size))) {
1492 VS_FIXEDFILEINFO *ffi;
1493 UINT ffi_len;
1494
1495 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1496 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1497 realMajor = HIWORD(ffi->dwProductVersionMS);
1498 realMinor = LOWORD(ffi->dwProductVersionMS);
1499 realBuild = HIWORD(ffi->dwProductVersionLS);
1500 }
1501 PyMem_RawFree(verblock);
1502 }
Segev Finer48fb7662017-06-04 20:52:27 +03001503 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1504 realMajor,
1505 realMinor,
1506 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001507 ));
1508
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001509 if (PyErr_Occurred()) {
1510 Py_DECREF(version);
1511 return NULL;
1512 }
Steve Dower74f4af72016-09-17 17:27:48 -07001513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001515}
1516
Steve Dower3e96f322015-03-02 08:01:10 -08001517#pragma warning(pop)
1518
Tal Einatede0b6f2018-12-31 17:12:08 +02001519/*[clinic input]
1520sys._enablelegacywindowsfsencoding
1521
1522Changes the default filesystem encoding to mbcs:replace.
1523
1524This is done for consistency with earlier versions of Python. See PEP
1525529 for more information.
1526
1527This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1528environment variable before launching Python.
1529[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001530
1531static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001532sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1533/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001534{
Victor Stinner709d23d2019-05-02 14:56:30 -04001535 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001536 return NULL;
1537 }
Steve Dowercc16be82016-09-08 10:35:16 -07001538 Py_RETURN_NONE;
1539}
1540
Mark Hammond8696ebc2002-10-08 02:44:31 +00001541#endif /* MS_WINDOWS */
1542
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001543#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001544
1545/*[clinic input]
1546sys.setdlopenflags
1547
1548 flags as new_val: int
1549 /
1550
1551Set the flags used by the interpreter for dlopen calls.
1552
1553This is used, for example, when the interpreter loads extension
1554modules. Among other things, this will enable a lazy resolving of
1555symbols when importing a module, if called as sys.setdlopenflags(0).
1556To share symbols across extension modules, call as
1557sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1558modules can be found in the os module (RTLD_xxx constants, e.g.
1559os.RTLD_LAZY).
1560[clinic start generated code]*/
1561
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001562static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001563sys_setdlopenflags_impl(PyObject *module, int new_val)
1564/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001565{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001566 PyInterpreterState *interp = _PyInterpreterState_Get();
1567 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001568 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001569}
1570
Tal Einatede0b6f2018-12-31 17:12:08 +02001571
1572/*[clinic input]
1573sys.getdlopenflags
1574
1575Return the current value of the flags that are used for dlopen calls.
1576
1577The flag constants are defined in the os module.
1578[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001579
1580static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001581sys_getdlopenflags_impl(PyObject *module)
1582/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001583{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001584 PyInterpreterState *interp = _PyInterpreterState_Get();
1585 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001586}
1587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001589
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001590#ifdef USE_MALLOPT
1591/* Link with -lmalloc (or -lmpc) on an SGI */
1592#include <malloc.h>
1593
Tal Einatede0b6f2018-12-31 17:12:08 +02001594/*[clinic input]
1595sys.mdebug
1596
1597 flag: int
1598 /
1599[clinic start generated code]*/
1600
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001601static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001602sys_mdebug_impl(PyObject *module, int flag)
1603/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001607 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001608}
1609#endif /* USE_MALLOPT */
1610
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001611size_t
1612_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001616 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 /* Make sure the type is initialized. float gets initialized late */
1619 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001620 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001621
Benjamin Petersonce798522012-01-22 11:24:29 -05001622 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 if (method == NULL) {
1624 if (!PyErr_Occurred())
1625 PyErr_Format(PyExc_TypeError,
1626 "Type %.100s doesn't define __sizeof__",
1627 Py_TYPE(o)->tp_name);
1628 }
1629 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001630 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 Py_DECREF(method);
1632 }
1633
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001634 if (res == NULL)
1635 return (size_t)-1;
1636
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001637 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001638 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001639 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001640 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001642 if (size < 0) {
1643 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1644 return (size_t)-1;
1645 }
1646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001648 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001649 return ((size_t)size) + sizeof(PyGC_Head);
1650 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001651}
1652
1653static PyObject *
1654sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1655{
1656 static char *kwlist[] = {"object", "default", 0};
1657 size_t size;
1658 PyObject *o, *dflt = NULL;
1659
1660 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1661 kwlist, &o, &dflt))
1662 return NULL;
1663
1664 size = _PySys_GetSizeOf(o);
1665
1666 if (size == (size_t)-1 && PyErr_Occurred()) {
1667 /* Has a default value been given */
1668 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1669 PyErr_Clear();
1670 Py_INCREF(dflt);
1671 return dflt;
1672 }
1673 else
1674 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001676
1677 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001678}
1679
1680PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001681"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001682\n\
1683Return the size of object in bytes.");
1684
Tal Einatede0b6f2018-12-31 17:12:08 +02001685/*[clinic input]
1686sys.getrefcount -> Py_ssize_t
1687
1688 object: object
1689 /
1690
1691Return the reference count of object.
1692
1693The count returned is generally one higher than you might expect,
1694because it includes the (temporary) reference as an argument to
1695getrefcount().
1696[clinic start generated code]*/
1697
1698static Py_ssize_t
1699sys_getrefcount_impl(PyObject *module, PyObject *object)
1700/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001701{
Tal Einatede0b6f2018-12-31 17:12:08 +02001702 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001703}
1704
Tim Peters4be93d02002-07-07 19:59:50 +00001705#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001706/*[clinic input]
1707sys.gettotalrefcount -> Py_ssize_t
1708[clinic start generated code]*/
1709
1710static Py_ssize_t
1711sys_gettotalrefcount_impl(PyObject *module)
1712/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001713{
Tal Einatede0b6f2018-12-31 17:12:08 +02001714 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001715}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001716#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001717
Tal Einatede0b6f2018-12-31 17:12:08 +02001718/*[clinic input]
1719sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001720
Tal Einatede0b6f2018-12-31 17:12:08 +02001721Return the number of memory blocks currently allocated.
1722[clinic start generated code]*/
1723
1724static Py_ssize_t
1725sys_getallocatedblocks_impl(PyObject *module)
1726/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001727{
Tal Einatede0b6f2018-12-31 17:12:08 +02001728 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001729}
1730
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001731#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001732/*[clinic input]
1733sys.getcounts
1734[clinic start generated code]*/
1735
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001736static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001737sys_getcounts_impl(PyObject *module)
1738/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001739{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001740 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001741
Pablo Galindo49c75a82018-10-28 15:02:17 +00001742 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001743}
1744#endif
1745
Tal Einatede0b6f2018-12-31 17:12:08 +02001746/*[clinic input]
1747sys._getframe
1748
1749 depth: int = 0
1750 /
1751
1752Return a frame object from the call stack.
1753
1754If optional integer depth is given, return the frame object that many
1755calls below the top of the stack. If that is deeper than the call
1756stack, ValueError is raised. The default for depth is zero, returning
1757the frame at the top of the call stack.
1758
1759This function should be used for internal and specialized purposes
1760only.
1761[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001762
1763static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001764sys__getframe_impl(PyObject *module, int depth)
1765/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001766{
Victor Stinner50b48572018-11-01 01:51:40 +01001767 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001768
Steve Dowerb82e17e2019-05-23 08:45:22 -07001769 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1770 return NULL;
1771 }
1772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 while (depth > 0 && f != NULL) {
1774 f = f->f_back;
1775 --depth;
1776 }
1777 if (f == NULL) {
1778 PyErr_SetString(PyExc_ValueError,
1779 "call stack is not deep enough");
1780 return NULL;
1781 }
1782 Py_INCREF(f);
1783 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001784}
1785
Tal Einatede0b6f2018-12-31 17:12:08 +02001786/*[clinic input]
1787sys._current_frames
1788
1789Return a dict mapping each thread's thread id to its current stack frame.
1790
1791This function should be used for specialized purposes only.
1792[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001793
1794static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001795sys__current_frames_impl(PyObject *module)
1796/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001799}
1800
Tal Einatede0b6f2018-12-31 17:12:08 +02001801/*[clinic input]
1802sys.call_tracing
1803
1804 func: object
1805 args as funcargs: object(subclass_of='&PyTuple_Type')
1806 /
1807
1808Call func(*args), while tracing is enabled.
1809
1810The tracing state is saved, and restored afterwards. This is intended
1811to be called from a debugger from a checkpoint, to recursively debug
1812some other code.
1813[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001814
1815static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001816sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1817/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001818{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001820}
1821
Tal Einatede0b6f2018-12-31 17:12:08 +02001822/*[clinic input]
1823sys.callstats
1824
1825Return a tuple of function call statistics.
1826
1827A tuple is returned only if CALL_PROFILE was defined when Python was
1828built. Otherwise, this returns None.
1829
1830When enabled, this function returns detailed, implementation-specific
1831details about the number of function calls executed. The return value
1832is a 11-tuple where the entries in the tuple are counts of:
18330. all function calls
18341. calls to PyFunction_Type objects
18352. PyFunction calls that do not create an argument tuple
18363. PyFunction calls that do not create an argument tuple
1837 and bypass PyEval_EvalCodeEx()
18384. PyMethod calls
18395. PyMethod calls on bound methods
18406. PyType calls
18417. PyCFunction calls
18428. generator calls
18439. All other calls
184410. Number of stack pops performed by call_function()
1845[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001846
Victor Stinner048afd92016-11-28 11:59:04 +01001847static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001848sys_callstats_impl(PyObject *module)
1849/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001850{
1851 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1852 "sys.callstats() has been deprecated in Python 3.7 "
1853 "and will be removed in the future", 1) < 0) {
1854 return NULL;
1855 }
1856
1857 Py_RETURN_NONE;
1858}
1859
1860
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001861#ifdef __cplusplus
1862extern "C" {
1863#endif
1864
Tal Einatede0b6f2018-12-31 17:12:08 +02001865/*[clinic input]
1866sys._debugmallocstats
1867
1868Print summary info to stderr about the state of pymalloc's structures.
1869
1870In Py_DEBUG mode, also perform some expensive internal consistency
1871checks.
1872[clinic start generated code]*/
1873
David Malcolm49526f42012-06-22 14:55:41 -04001874static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001875sys__debugmallocstats_impl(PyObject *module)
1876/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001877{
1878#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001879 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001880 fputc('\n', stderr);
1881 }
David Malcolm49526f42012-06-22 14:55:41 -04001882#endif
1883 _PyObject_DebugTypeStats(stderr);
1884
1885 Py_RETURN_NONE;
1886}
David Malcolm49526f42012-06-22 14:55:41 -04001887
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001888#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001889/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001890extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001891#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001892
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001893#ifdef DYNAMIC_EXECUTION_PROFILE
1894/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001895extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001896#endif
1897
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001898#ifdef __cplusplus
1899}
1900#endif
1901
Tal Einatede0b6f2018-12-31 17:12:08 +02001902
1903/*[clinic input]
1904sys._clear_type_cache
1905
1906Clear the internal type lookup cache.
1907[clinic start generated code]*/
1908
Christian Heimes15ebc882008-02-04 18:48:49 +00001909static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001910sys__clear_type_cache_impl(PyObject *module)
1911/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001912{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyType_ClearCache();
1914 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001915}
1916
Tal Einatede0b6f2018-12-31 17:12:08 +02001917/*[clinic input]
1918sys.is_finalizing
1919
1920Return True if Python is exiting.
1921[clinic start generated code]*/
1922
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001923static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001924sys_is_finalizing_impl(PyObject *module)
1925/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001926{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001927 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001928}
1929
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001930#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001931/*[clinic input]
1932sys.getandroidapilevel
1933
1934Return the build time API version of Android as an integer.
1935[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001936
1937static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001938sys_getandroidapilevel_impl(PyObject *module)
1939/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001940{
1941 return PyLong_FromLong(ANDROID_API_LEVEL);
1942}
1943#endif /* ANDROID_API_LEVEL */
1944
1945
Steve Dowerb82e17e2019-05-23 08:45:22 -07001946
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001947static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001949 SYS_ADDAUDITHOOK_METHODDEF
1950 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001951 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001952 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001953 SYS_CALLSTATS_METHODDEF
1954 SYS__CLEAR_TYPE_CACHE_METHODDEF
1955 SYS__CURRENT_FRAMES_METHODDEF
1956 SYS_DISPLAYHOOK_METHODDEF
1957 SYS_EXC_INFO_METHODDEF
1958 SYS_EXCEPTHOOK_METHODDEF
1959 SYS_EXIT_METHODDEF
1960 SYS_GETDEFAULTENCODING_METHODDEF
1961 SYS_GETDLOPENFLAGS_METHODDEF
1962 SYS_GETALLOCATEDBLOCKS_METHODDEF
1963 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001964#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001966#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001967 SYS_GETFILESYSTEMENCODING_METHODDEF
1968 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001969#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001971#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001972 SYS_GETTOTALREFCOUNT_METHODDEF
1973 SYS_GETREFCOUNT_METHODDEF
1974 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001975 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001976 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001977 SYS__GETFRAME_METHODDEF
1978 SYS_GETWINDOWSVERSION_METHODDEF
1979 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1980 SYS_INTERN_METHODDEF
1981 SYS_IS_FINALIZING_METHODDEF
1982 SYS_MDEBUG_METHODDEF
1983 SYS_SETCHECKINTERVAL_METHODDEF
1984 SYS_GETCHECKINTERVAL_METHODDEF
1985 SYS_SETSWITCHINTERVAL_METHODDEF
1986 SYS_GETSWITCHINTERVAL_METHODDEF
1987 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001989 SYS_GETPROFILE_METHODDEF
1990 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001991 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001992 SYS_GETTRACE_METHODDEF
1993 SYS_CALL_TRACING_METHODDEF
1994 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001995 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1996 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001997 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001998 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001999 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2000 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002001 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002003};
2004
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002005static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002006list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002007{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 PyObject *list = PyList_New(0);
2009 int i;
2010 if (list == NULL)
2011 return NULL;
2012 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2013 PyObject *name = PyUnicode_FromString(
2014 PyImport_Inittab[i].name);
2015 if (name == NULL)
2016 break;
2017 PyList_Append(list, name);
2018 Py_DECREF(name);
2019 }
2020 if (PyList_Sort(list) != 0) {
2021 Py_DECREF(list);
2022 list = NULL;
2023 }
2024 if (list) {
2025 PyObject *v = PyList_AsTuple(list);
2026 Py_DECREF(list);
2027 list = v;
2028 }
2029 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002030}
2031
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002032/* Pre-initialization support for sys.warnoptions and sys._xoptions
2033 *
2034 * Modern internal code paths:
2035 * These APIs get called after _Py_InitializeCore and get to use the
2036 * regular CPython list, dict, and unicode APIs.
2037 *
2038 * Legacy embedding code paths:
2039 * The multi-phase initialization API isn't public yet, so embedding
2040 * apps still need to be able configure sys.warnoptions and sys._xoptions
2041 * before they call Py_Initialize. To support this, we stash copies of
2042 * the supplied wchar * sequences in linked lists, and then migrate the
2043 * contents of those lists to the sys module in _PyInitializeCore.
2044 *
2045 */
2046
2047struct _preinit_entry {
2048 wchar_t *value;
2049 struct _preinit_entry *next;
2050};
2051
2052typedef struct _preinit_entry *_Py_PreInitEntry;
2053
2054static _Py_PreInitEntry _preinit_warnoptions = NULL;
2055static _Py_PreInitEntry _preinit_xoptions = NULL;
2056
2057static _Py_PreInitEntry
2058_alloc_preinit_entry(const wchar_t *value)
2059{
2060 /* To get this to work, we have to initialize the runtime implicitly */
2061 _PyRuntime_Initialize();
2062
2063 /* Force default allocator, so we can ensure that it also gets used to
2064 * destroy the linked list in _clear_preinit_entries.
2065 */
2066 PyMemAllocatorEx old_alloc;
2067 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2068
2069 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2070 if (node != NULL) {
2071 node->value = _PyMem_RawWcsdup(value);
2072 if (node->value == NULL) {
2073 PyMem_RawFree(node);
2074 node = NULL;
2075 };
2076 };
2077
2078 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2079 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002080}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002081
2082static int
2083_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2084{
2085 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2086 if (new_entry == NULL) {
2087 return -1;
2088 }
2089 /* We maintain the linked list in this order so it's easy to play back
2090 * the add commands in the same order later on in _Py_InitializeCore
2091 */
2092 _Py_PreInitEntry last_entry = *optionlist;
2093 if (last_entry == NULL) {
2094 *optionlist = new_entry;
2095 } else {
2096 while (last_entry->next != NULL) {
2097 last_entry = last_entry->next;
2098 }
2099 last_entry->next = new_entry;
2100 }
2101 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002102}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002103
2104static void
2105_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2106{
2107 _Py_PreInitEntry current = *optionlist;
2108 *optionlist = NULL;
2109 /* Deallocate the nodes and their contents using the default allocator */
2110 PyMemAllocatorEx old_alloc;
2111 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2112 while (current != NULL) {
2113 _Py_PreInitEntry next = current->next;
2114 PyMem_RawFree(current->value);
2115 PyMem_RawFree(current);
2116 current = next;
2117 }
2118 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002119}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002120
Victor Stinneraf84a882019-08-23 21:16:51 +02002121
2122PyStatus
Miss Islington (bot)c9ed9e62019-09-29 16:58:57 -07002123_PySys_ReadPreinitWarnOptions(PyWideStringList *options)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002124{
Victor Stinneraf84a882019-08-23 21:16:51 +02002125 PyStatus status;
2126 _Py_PreInitEntry entry;
2127
2128 for (entry = _preinit_warnoptions; entry != NULL; entry = entry->next) {
Miss Islington (bot)c9ed9e62019-09-29 16:58:57 -07002129 status = PyWideStringList_Append(options, entry->value);
Victor Stinneraf84a882019-08-23 21:16:51 +02002130 if (_PyStatus_EXCEPTION(status)) {
2131 return status;
2132 }
2133 }
2134
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002135 _clear_preinit_entries(&_preinit_warnoptions);
Victor Stinneraf84a882019-08-23 21:16:51 +02002136 return _PyStatus_OK();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002137}
2138
Victor Stinneraf84a882019-08-23 21:16:51 +02002139
2140PyStatus
2141_PySys_ReadPreinitXOptions(PyConfig *config)
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002142{
Victor Stinneraf84a882019-08-23 21:16:51 +02002143 PyStatus status;
2144 _Py_PreInitEntry entry;
2145
2146 for (entry = _preinit_xoptions; entry != NULL; entry = entry->next) {
2147 status = PyWideStringList_Append(&config->xoptions, entry->value);
2148 if (_PyStatus_EXCEPTION(status)) {
2149 return status;
2150 }
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002151 }
2152
Victor Stinneraf84a882019-08-23 21:16:51 +02002153 _clear_preinit_entries(&_preinit_xoptions);
2154 return _PyStatus_OK();
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002155}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002156
Victor Stinneraf84a882019-08-23 21:16:51 +02002157
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002158static PyObject *
2159get_warnoptions(void)
2160{
Eric Snowdae02762017-09-14 00:35:58 -07002161 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002162 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002163 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2164 * interpreter config. When that happens, we need to properly set
2165 * the `warnoptions` reference in the main interpreter config as well.
2166 *
2167 * For Python 3.7, we shouldn't be able to get here due to the
2168 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2169 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2170 * call optional for embedding applications, thus making this
2171 * reachable again.
2172 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002173 warnoptions = PyList_New(0);
2174 if (warnoptions == NULL)
2175 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002176 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
2177 Py_DECREF(warnoptions);
2178 return NULL;
2179 }
2180 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002181 }
2182 return warnoptions;
2183}
Guido van Rossum23fff912000-12-15 22:02:05 +00002184
2185void
2186PySys_ResetWarnOptions(void)
2187{
Victor Stinner50b48572018-11-01 01:51:40 +01002188 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002189 if (tstate == NULL) {
2190 _clear_preinit_entries(&_preinit_warnoptions);
2191 return;
2192 }
2193
Eric Snowdae02762017-09-14 00:35:58 -07002194 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (warnoptions == NULL || !PyList_Check(warnoptions))
2196 return;
2197 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002198}
2199
Victor Stinnere1b29952018-10-30 14:31:42 +01002200static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002201_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002202{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002203 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002204 if (warnoptions == NULL) {
2205 return -1;
2206 }
2207 if (PyList_Append(warnoptions, option)) {
2208 return -1;
2209 }
2210 return 0;
2211}
2212
2213void
2214PySys_AddWarnOptionUnicode(PyObject *option)
2215{
Victor Stinnere1b29952018-10-30 14:31:42 +01002216 if (_PySys_AddWarnOptionWithError(option) < 0) {
2217 /* No return value, therefore clear error state if possible */
2218 if (_PyThreadState_UncheckedGet()) {
2219 PyErr_Clear();
2220 }
2221 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002222}
2223
2224void
2225PySys_AddWarnOption(const wchar_t *s)
2226{
Victor Stinner50b48572018-11-01 01:51:40 +01002227 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002228 if (tstate == NULL) {
2229 _append_preinit_entry(&_preinit_warnoptions, s);
2230 return;
2231 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002232 PyObject *unicode;
2233 unicode = PyUnicode_FromWideChar(s, -1);
2234 if (unicode == NULL)
2235 return;
2236 PySys_AddWarnOptionUnicode(unicode);
2237 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002238}
2239
Christian Heimes33fe8092008-04-13 13:53:33 +00002240int
2241PySys_HasWarnOptions(void)
2242{
Eric Snowdae02762017-09-14 00:35:58 -07002243 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002244 return (warnoptions != NULL && PyList_Check(warnoptions)
2245 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002246}
2247
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002248static PyObject *
2249get_xoptions(void)
2250{
Eric Snowdae02762017-09-14 00:35:58 -07002251 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002252 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002253 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2254 * interpreter config. When that happens, we need to properly set
2255 * the `xoptions` reference in the main interpreter config as well.
2256 *
2257 * For Python 3.7, we shouldn't be able to get here due to the
2258 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2259 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2260 * call optional for embedding applications, thus making this
2261 * reachable again.
2262 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002263 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002264 if (xoptions == NULL)
2265 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002266 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
2267 Py_DECREF(xoptions);
2268 return NULL;
2269 }
2270 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002271 }
2272 return xoptions;
2273}
2274
Victor Stinnere1b29952018-10-30 14:31:42 +01002275static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002276_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002277{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002278 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002279
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002280 PyObject *opts = get_xoptions();
2281 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002282 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002284
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002285 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002286 if (!name_end) {
2287 name = PyUnicode_FromWideChar(s, -1);
2288 value = Py_True;
2289 Py_INCREF(value);
2290 }
2291 else {
2292 name = PyUnicode_FromWideChar(s, name_end - s);
2293 value = PyUnicode_FromWideChar(name_end + 1, -1);
2294 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002295 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002296 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002297 }
2298 if (PyDict_SetItem(opts, name, value) < 0) {
2299 goto error;
2300 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002301 Py_DECREF(name);
2302 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002303 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002304
2305error:
2306 Py_XDECREF(name);
2307 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002308 return -1;
2309}
2310
2311void
2312PySys_AddXOption(const wchar_t *s)
2313{
Victor Stinner50b48572018-11-01 01:51:40 +01002314 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002315 if (tstate == NULL) {
2316 _append_preinit_entry(&_preinit_xoptions, s);
2317 return;
2318 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002319 if (_PySys_AddXOptionWithError(s) < 0) {
2320 /* No return value, therefore clear error state if possible */
Victor Stinneraf84a882019-08-23 21:16:51 +02002321 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01002322 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002323}
2324
2325PyObject *
2326PySys_GetXOptions(void)
2327{
2328 return get_xoptions();
2329}
2330
Guido van Rossum40552d01998-08-06 03:34:39 +00002331/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2332 Two literals concatenated works just fine. If you have a K&R compiler
2333 or other abomination that however *does* understand longer strings,
2334 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002335PyDoc_VAR(sys_doc) =
2336PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002337"This module provides access to some objects used or maintained by the\n\
2338interpreter and to functions that interact strongly with the interpreter.\n\
2339\n\
2340Dynamic objects:\n\
2341\n\
2342argv -- command line arguments; argv[0] is the script pathname if known\n\
2343path -- module search path; path[0] is the script directory, else ''\n\
2344modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002345\n\
2346displayhook -- called to show results in an interactive session\n\
2347excepthook -- called to handle any uncaught exception other than SystemExit\n\
2348 To customize printing in an interactive session or to install a custom\n\
2349 top-level exception handler, assign other functions to replace these.\n\
2350\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002351stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002352stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002353stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002354 By assigning other file objects (or objects that behave like files)\n\
2355 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002356\n\
2357last_type -- type of last uncaught exception\n\
2358last_value -- value of last uncaught exception\n\
2359last_traceback -- traceback of last uncaught exception\n\
2360 These three are only available in an interactive session after a\n\
2361 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002362"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002363)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002364/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002365PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002366"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002367Static objects:\n\
2368\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002369builtin_module_names -- tuple of module names built into this interpreter\n\
2370copyright -- copyright notice pertaining to this interpreter\n\
2371exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002372executable -- absolute path of the executable binary of the Python interpreter\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +01002373float_info -- a named tuple with information about the float implementation.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002374float_repr_style -- string indicating the style of repr() output for floats\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +01002375hash_info -- a named tuple with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002376hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002377implementation -- Python implementation information.\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +01002378int_info -- a named tuple with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002379maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002380maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002381platform -- platform identifier\n\
2382prefix -- prefix used to find the Python library\n\
Paul Ganssle2bb6bf02019-09-12 03:50:29 +01002383thread_info -- a named tuple with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002384version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002385version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002386"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002387)
Steve Dowercc16be82016-09-08 10:35:16 -07002388#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002389/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002390PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002391"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002392winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002393"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002394)
Steve Dowercc16be82016-09-08 10:35:16 -07002395#endif /* MS_COREDLL */
2396#ifdef MS_WINDOWS
2397/* concatenating string here */
2398PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002399"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002400"
2401)
2402#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002403PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002404"__stdin__ -- the original stdin; don't touch!\n\
2405__stdout__ -- the original stdout; don't touch!\n\
2406__stderr__ -- the original stderr; don't touch!\n\
2407__displayhook__ -- the original displayhook; don't touch!\n\
2408__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002409\n\
2410Functions:\n\
2411\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002412displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002413excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002414exc_info() -- return thread-safe information about the current exception\n\
2415exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002416getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002417getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002418getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002419getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002420getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002421gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002422setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002423setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002424setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002425setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002426settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002427"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002428)
Fred Drakeccede592000-08-14 20:59:57 +00002429/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002430
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002431
2432PyDoc_STRVAR(flags__doc__,
2433"sys.flags\n\
2434\n\
2435Flags provided through command line arguments or environment vars.");
2436
2437static PyTypeObject FlagsType;
2438
2439static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 {"inspect", "-i"},
2442 {"interactive", "-i"},
2443 {"optimize", "-O or -OO"},
2444 {"dont_write_bytecode", "-B"},
2445 {"no_user_site", "-s"},
2446 {"no_site", "-S"},
2447 {"ignore_environment", "-E"},
2448 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* {"unbuffered", "-u"}, */
2450 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002451 {"bytes_warning", "-b"},
2452 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002453 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002454 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002455 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002456 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002458};
2459
2460static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 "sys.flags", /* name */
2462 flags__doc__, /* doc */
2463 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002464 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002465};
2466
2467static PyObject*
Victor Stinner0fd2c302019-06-04 03:15:09 +02002468make_flags(_PyRuntimeState *runtime, PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 int pos = 0;
2471 PyObject *seq;
Victor Stinner331a6a52019-05-27 16:39:22 +02002472 const PyPreConfig *preconfig = &runtime->preconfig;
2473 const PyConfig *config = &interp->config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 seq = PyStructSequence_New(&FlagsType);
2476 if (seq == NULL)
2477 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002478
2479#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002481
Victor Stinnerfbca9082018-08-30 00:50:45 +02002482 SetFlag(config->parser_debug);
2483 SetFlag(config->inspect);
2484 SetFlag(config->interactive);
2485 SetFlag(config->optimization_level);
2486 SetFlag(!config->write_bytecode);
2487 SetFlag(!config->user_site_directory);
2488 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002489 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002490 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 /* SetFlag(saw_unbuffered_flag); */
2492 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002493 SetFlag(config->bytes_warning);
2494 SetFlag(config->quiet);
2495 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002496 SetFlag(config->isolated);
2497 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2498 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002499#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002502 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002503 return NULL;
2504 }
2505 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002506}
2507
Eric Smith0e5b5622009-02-06 01:32:42 +00002508PyDoc_STRVAR(version_info__doc__,
2509"sys.version_info\n\
2510\n\
2511Version information as a named tuple.");
2512
2513static PyTypeObject VersionInfoType;
2514
2515static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002516 {"major", "Major release number"},
2517 {"minor", "Minor release number"},
2518 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002519 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002520 {"serial", "Serial release number"},
2521 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002522};
2523
2524static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 "sys.version_info", /* name */
2526 version_info__doc__, /* doc */
2527 version_info_fields, /* fields */
2528 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002529};
2530
2531static PyObject *
2532make_version_info(void)
2533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 PyObject *version_info;
2535 char *s;
2536 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002538 version_info = PyStructSequence_New(&VersionInfoType);
2539 if (version_info == NULL) {
2540 return NULL;
2541 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 /*
2544 * These release level checks are mutually exclusive and cover
2545 * the field, so don't get too fancy with the pre-processor!
2546 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002547#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002549#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002550 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002551#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002553#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002555#endif
2556
2557#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002559#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 SetIntItem(PY_MAJOR_VERSION);
2563 SetIntItem(PY_MINOR_VERSION);
2564 SetIntItem(PY_MICRO_VERSION);
2565 SetStrItem(s);
2566 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002567#undef SetIntItem
2568#undef SetStrItem
2569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 if (PyErr_Occurred()) {
2571 Py_CLEAR(version_info);
2572 return NULL;
2573 }
2574 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002575}
2576
Brett Cannon3adc7b72012-07-09 14:22:12 -04002577/* sys.implementation values */
2578#define NAME "cpython"
2579const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002580#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2581#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002582#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002583const char *_PySys_ImplCacheTag = TAG;
2584#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002585#undef MAJOR
2586#undef MINOR
2587#undef TAG
2588
Barry Warsaw409da152012-06-03 16:18:47 -04002589static PyObject *
2590make_impl_info(PyObject *version_info)
2591{
2592 int res;
2593 PyObject *impl_info, *value, *ns;
2594
2595 impl_info = PyDict_New();
2596 if (impl_info == NULL)
2597 return NULL;
2598
2599 /* populate the dict */
2600
Brett Cannon3adc7b72012-07-09 14:22:12 -04002601 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002602 if (value == NULL)
2603 goto error;
2604 res = PyDict_SetItemString(impl_info, "name", value);
2605 Py_DECREF(value);
2606 if (res < 0)
2607 goto error;
2608
Brett Cannon3adc7b72012-07-09 14:22:12 -04002609 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002610 if (value == NULL)
2611 goto error;
2612 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2613 Py_DECREF(value);
2614 if (res < 0)
2615 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002616
2617 res = PyDict_SetItemString(impl_info, "version", version_info);
2618 if (res < 0)
2619 goto error;
2620
2621 value = PyLong_FromLong(PY_VERSION_HEX);
2622 if (value == NULL)
2623 goto error;
2624 res = PyDict_SetItemString(impl_info, "hexversion", value);
2625 Py_DECREF(value);
2626 if (res < 0)
2627 goto error;
2628
doko@ubuntu.com55532312016-06-14 08:55:19 +02002629#ifdef MULTIARCH
2630 value = PyUnicode_FromString(MULTIARCH);
2631 if (value == NULL)
2632 goto error;
2633 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2634 Py_DECREF(value);
2635 if (res < 0)
2636 goto error;
2637#endif
2638
Barry Warsaw409da152012-06-03 16:18:47 -04002639 /* dict ready */
2640
2641 ns = _PyNamespace_New(impl_info);
2642 Py_DECREF(impl_info);
2643 return ns;
2644
2645error:
2646 Py_CLEAR(impl_info);
2647 return NULL;
2648}
2649
Martin v. Löwis1a214512008-06-11 05:26:20 +00002650static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002651 PyModuleDef_HEAD_INIT,
2652 "sys",
2653 sys_doc,
2654 -1, /* multiple "initialization" just copies the module dict. */
2655 sys_methods,
2656 NULL,
2657 NULL,
2658 NULL,
2659 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002660};
2661
Eric Snow6b4be192017-05-22 21:36:03 -07002662/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002663#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002664 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002665 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002666 if (v == NULL) { \
2667 goto err_occurred; \
2668 } \
Victor Stinner58049602013-07-22 22:40:00 +02002669 res = PyDict_SetItemString(sysdict, key, v); \
2670 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002671 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002672 } \
2673 } while (0)
2674#define SET_SYS_FROM_STRING(key, value) \
2675 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002676 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002677 if (v == NULL) { \
2678 goto err_occurred; \
2679 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002680 res = PyDict_SetItemString(sysdict, key, v); \
2681 Py_DECREF(v); \
2682 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002683 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002684 } \
2685 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002686
Victor Stinner331a6a52019-05-27 16:39:22 +02002687static PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +02002688_PySys_InitCore(_PyRuntimeState *runtime, PyInterpreterState *interp,
2689 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002690{
Victor Stinnerab672812019-01-23 15:04:40 +01002691 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002692 int res;
2693
Nick Coghland6009512014-11-20 21:39:37 +10002694 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002695
Victor Stinner8fea2522013-10-27 17:15:42 +01002696 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2697 PyDict_GetItemString(sysdict, "displayhook"));
2698 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2699 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002700 SET_SYS_FROM_STRING_BORROW(
2701 "__breakpointhook__",
2702 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002703 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2704 PyDict_GetItemString(sysdict, "unraisablehook"));
2705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002706 SET_SYS_FROM_STRING("version",
2707 PyUnicode_FromString(Py_GetVersion()));
2708 SET_SYS_FROM_STRING("hexversion",
2709 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002710 SET_SYS_FROM_STRING("_git",
2711 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2712 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002713 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002714 SET_SYS_FROM_STRING("api_version",
2715 PyLong_FromLong(PYTHON_API_VERSION));
2716 SET_SYS_FROM_STRING("copyright",
2717 PyUnicode_FromString(Py_GetCopyright()));
2718 SET_SYS_FROM_STRING("platform",
2719 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 SET_SYS_FROM_STRING("maxsize",
2721 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2722 SET_SYS_FROM_STRING("float_info",
2723 PyFloat_GetInfo());
2724 SET_SYS_FROM_STRING("int_info",
2725 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002726 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002727 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002728 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2729 goto type_init_failed;
2730 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002731 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002732 SET_SYS_FROM_STRING("hash_info",
2733 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002734 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002735 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 SET_SYS_FROM_STRING("builtin_module_names",
2737 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002738#if PY_BIG_ENDIAN
2739 SET_SYS_FROM_STRING("byteorder",
2740 PyUnicode_FromString("big"));
2741#else
2742 SET_SYS_FROM_STRING("byteorder",
2743 PyUnicode_FromString("little"));
2744#endif
Fred Drake099325e2000-08-14 15:47:03 +00002745
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002746#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 SET_SYS_FROM_STRING("dllhandle",
2748 PyLong_FromVoidPtr(PyWin_DLLhModule));
2749 SET_SYS_FROM_STRING("winver",
2750 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002751#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002752#ifdef ABIFLAGS
2753 SET_SYS_FROM_STRING("abiflags",
2754 PyUnicode_FromString(ABIFLAGS));
2755#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002756
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002758 if (VersionInfoType.tp_name == NULL) {
2759 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002760 &version_info_desc) < 0) {
2761 goto type_init_failed;
2762 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002763 }
Barry Warsaw409da152012-06-03 16:18:47 -04002764 version_info = make_version_info();
2765 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 /* prevent user from creating new instances */
2767 VersionInfoType.tp_init = NULL;
2768 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002769 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2770 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2771 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002772
Barry Warsaw409da152012-06-03 16:18:47 -04002773 /* implementation */
2774 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002777 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002778 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2779 goto type_init_failed;
2780 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002781 }
Victor Stinner43125222019-04-24 18:23:53 +02002782 /* Set flags to their default values (updated by _PySys_InitMain()) */
Victor Stinner0fd2c302019-06-04 03:15:09 +02002783 SET_SYS_FROM_STRING("flags", make_flags(runtime, interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002784
2785#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 /* getwindowsversion */
2787 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002788 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002789 &windows_version_desc) < 0) {
2790 goto type_init_failed;
2791 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 /* prevent user from creating new instances */
2793 WindowsVersionType.tp_init = NULL;
2794 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002795 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002796 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002797 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002798 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002799 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002800#endif
2801
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002803#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002804 SET_SYS_FROM_STRING("float_repr_style",
2805 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002806#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 SET_SYS_FROM_STRING("float_repr_style",
2808 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002809#endif
2810
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002811 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002812
Yury Selivanoveb636452016-09-08 22:01:51 -07002813 /* initialize asyncgen_hooks */
2814 if (AsyncGenHooksType.tp_name == NULL) {
2815 if (PyStructSequence_InitType2(
2816 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002817 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002818 }
2819 }
2820
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002821 if (PyErr_Occurred()) {
2822 goto err_occurred;
2823 }
Victor Stinner331a6a52019-05-27 16:39:22 +02002824 return _PyStatus_OK();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002825
2826type_init_failed:
Victor Stinner331a6a52019-05-27 16:39:22 +02002827 return _PyStatus_ERR("failed to initialize a type");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002828
2829err_occurred:
Victor Stinner331a6a52019-05-27 16:39:22 +02002830 return _PyStatus_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002831}
2832
Eric Snow6b4be192017-05-22 21:36:03 -07002833#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002834
2835/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002836#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2837 do { \
2838 PyObject *v = (value); \
2839 if (v == NULL) \
2840 return -1; \
2841 res = PyDict_SetItemString(sysdict, key, v); \
2842 Py_DECREF(v); \
2843 if (res < 0) { \
2844 return res; \
2845 } \
2846 } while (0)
2847
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002848
2849static int
2850sys_add_xoption(PyObject *opts, const wchar_t *s)
2851{
2852 PyObject *name, *value;
2853
2854 const wchar_t *name_end = wcschr(s, L'=');
2855 if (!name_end) {
2856 name = PyUnicode_FromWideChar(s, -1);
2857 value = Py_True;
2858 Py_INCREF(value);
2859 }
2860 else {
2861 name = PyUnicode_FromWideChar(s, name_end - s);
2862 value = PyUnicode_FromWideChar(name_end + 1, -1);
2863 }
2864 if (name == NULL || value == NULL) {
2865 goto error;
2866 }
2867 if (PyDict_SetItem(opts, name, value) < 0) {
2868 goto error;
2869 }
2870 Py_DECREF(name);
2871 Py_DECREF(value);
2872 return 0;
2873
2874error:
2875 Py_XDECREF(name);
2876 Py_XDECREF(value);
2877 return -1;
2878}
2879
2880
2881static PyObject*
Victor Stinner331a6a52019-05-27 16:39:22 +02002882sys_create_xoptions_dict(const PyConfig *config)
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002883{
2884 Py_ssize_t nxoption = config->xoptions.length;
2885 wchar_t * const * xoptions = config->xoptions.items;
2886 PyObject *dict = PyDict_New();
2887 if (dict == NULL) {
2888 return NULL;
2889 }
2890
2891 for (Py_ssize_t i=0; i < nxoption; i++) {
2892 const wchar_t *option = xoptions[i];
2893 if (sys_add_xoption(dict, option) < 0) {
2894 Py_DECREF(dict);
2895 return NULL;
2896 }
2897 }
2898
2899 return dict;
2900}
2901
2902
Eric Snow6b4be192017-05-22 21:36:03 -07002903int
Victor Stinner0fd2c302019-06-04 03:15:09 +02002904_PySys_InitMain(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002905{
Victor Stinnerab672812019-01-23 15:04:40 +01002906 PyObject *sysdict = interp->sysdict;
Victor Stinner331a6a52019-05-27 16:39:22 +02002907 const PyConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002908 int res;
2909
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002910#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002911 do { \
Victor Stinner331a6a52019-05-27 16:39:22 +02002912 PyObject *list = _PyWideStringList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002913 if (list == NULL) { \
2914 return -1; \
2915 } \
2916 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2917 Py_DECREF(list); \
2918 } while (0)
2919
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002920#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2921 do { \
2922 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2923 if (str == NULL) { \
2924 return -1; \
2925 } \
2926 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2927 Py_DECREF(str); \
2928 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002929
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002930 COPY_LIST("path", config->module_search_paths);
2931
2932 SET_SYS_FROM_WSTR("executable", config->executable);
Steve Dower323e7432019-06-29 14:28:59 -07002933 SET_SYS_FROM_WSTR("_base_executable", config->base_executable);
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002934 SET_SYS_FROM_WSTR("prefix", config->prefix);
2935 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2936 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2937 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002938
Carl Meyerb193fa92018-06-15 22:40:56 -06002939 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002940 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002941 } else {
2942 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2943 }
2944
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002945 COPY_LIST("argv", config->argv);
2946 COPY_LIST("warnoptions", config->warnoptions);
2947
2948 PyObject *xoptions = sys_create_xoptions_dict(config);
2949 if (xoptions == NULL) {
2950 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002951 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002952 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002953 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002954
Victor Stinner37cd9822018-11-16 11:55:35 +01002955#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002956#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002957
Eric Snow6b4be192017-05-22 21:36:03 -07002958 /* Set flags to their final values */
Victor Stinner0fd2c302019-06-04 03:15:09 +02002959 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002960 /* prevent user from creating new instances */
2961 FlagsType.tp_init = NULL;
2962 FlagsType.tp_new = NULL;
2963 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2964 if (res < 0) {
2965 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2966 return res;
2967 }
2968 PyErr_Clear();
2969 }
2970
2971 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002972 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002973
Eric Snowdae02762017-09-14 00:35:58 -07002974 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002975 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002976
Eric Snowdae02762017-09-14 00:35:58 -07002977 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002978 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002979
2980 if (PyErr_Occurred())
2981 return -1;
Victor Stinneraf84a882019-08-23 21:16:51 +02002982
Eric Snow6b4be192017-05-22 21:36:03 -07002983 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002984
2985err_occurred:
2986 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002987}
2988
Victor Stinner41264f12017-12-15 02:05:29 +01002989#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002990#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002991
Victor Stinnerab672812019-01-23 15:04:40 +01002992
2993/* Set up a preliminary stderr printer until we have enough
2994 infrastructure for the io module in place.
2995
2996 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
Victor Stinner331a6a52019-05-27 16:39:22 +02002997PyStatus
Victor Stinnerab672812019-01-23 15:04:40 +01002998_PySys_SetPreliminaryStderr(PyObject *sysdict)
2999{
3000 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3001 if (pstderr == NULL) {
3002 goto error;
3003 }
3004 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3005 goto error;
3006 }
3007 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3008 goto error;
3009 }
3010 Py_DECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003011 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003012
3013error:
3014 Py_XDECREF(pstderr);
Victor Stinner331a6a52019-05-27 16:39:22 +02003015 return _PyStatus_ERR("can't set preliminary stderr");
Victor Stinnerab672812019-01-23 15:04:40 +01003016}
3017
3018
3019/* Create sys module without all attributes: _PySys_InitMain() should be called
3020 later to add remaining attributes. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003021PyStatus
Victor Stinner0fd2c302019-06-04 03:15:09 +02003022_PySys_Create(_PyRuntimeState *runtime, PyInterpreterState *interp,
3023 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003024{
3025 PyObject *modules = PyDict_New();
3026 if (modules == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003027 return _PyStatus_ERR("can't make modules dictionary");
Victor Stinnerab672812019-01-23 15:04:40 +01003028 }
3029 interp->modules = modules;
3030
3031 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3032 if (sysmod == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003033 return _PyStatus_ERR("failed to create a module object");
Victor Stinnerab672812019-01-23 15:04:40 +01003034 }
3035
3036 PyObject *sysdict = PyModule_GetDict(sysmod);
3037 if (sysdict == NULL) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003038 return _PyStatus_ERR("can't initialize sys dict");
Victor Stinnerab672812019-01-23 15:04:40 +01003039 }
3040 Py_INCREF(sysdict);
3041 interp->sysdict = sysdict;
3042
3043 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
Victor Stinner331a6a52019-05-27 16:39:22 +02003044 return _PyStatus_ERR("can't initialize sys module");
Victor Stinnerab672812019-01-23 15:04:40 +01003045 }
3046
Victor Stinner331a6a52019-05-27 16:39:22 +02003047 PyStatus status = _PySys_SetPreliminaryStderr(sysdict);
3048 if (_PyStatus_EXCEPTION(status)) {
3049 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003050 }
3051
Victor Stinner0fd2c302019-06-04 03:15:09 +02003052 status = _PySys_InitCore(runtime, interp, sysdict);
Victor Stinner331a6a52019-05-27 16:39:22 +02003053 if (_PyStatus_EXCEPTION(status)) {
3054 return status;
Victor Stinnerab672812019-01-23 15:04:40 +01003055 }
3056
3057 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3058
3059 *sysmod_p = sysmod;
Victor Stinner331a6a52019-05-27 16:39:22 +02003060 return _PyStatus_OK();
Victor Stinnerab672812019-01-23 15:04:40 +01003061}
3062
3063
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003064static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003065makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003067 int i, n;
3068 const wchar_t *p;
3069 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003071 n = 1;
3072 p = path;
3073 while ((p = wcschr(p, delim)) != NULL) {
3074 n++;
3075 p++;
3076 }
3077 v = PyList_New(n);
3078 if (v == NULL)
3079 return NULL;
3080 for (i = 0; ; i++) {
3081 p = wcschr(path, delim);
3082 if (p == NULL)
3083 p = path + wcslen(path); /* End of string */
3084 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3085 if (w == NULL) {
3086 Py_DECREF(v);
3087 return NULL;
3088 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003089 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003090 if (*p == '\0')
3091 break;
3092 path = p+1;
3093 }
3094 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003095}
3096
3097void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003098PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003099{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003100 PyObject *v;
3101 if ((v = makepathobject(path, DELIM)) == NULL)
3102 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01003103 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003104 Py_FatalError("can't assign sys.path");
3105 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003106}
3107
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003108static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003109make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003110{
Victor Stinner74f65682019-03-15 15:08:05 +01003111 PyObject *list = PyList_New(argc);
3112 if (list == NULL) {
3113 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003114 }
Victor Stinner74f65682019-03-15 15:08:05 +01003115
3116 for (Py_ssize_t i = 0; i < argc; i++) {
3117 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3118 if (v == NULL) {
3119 Py_DECREF(list);
3120 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003121 }
Victor Stinner74f65682019-03-15 15:08:05 +01003122 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
Victor Stinner74f65682019-03-15 15:08:05 +01003124 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003125}
3126
Victor Stinner11a247d2017-12-13 21:05:57 +01003127void
3128PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003129{
Victor Stinnerca9ae942019-08-23 12:22:14 +01003130 wchar_t* empty_argv[1] = {L""};
3131
Victor Stinner74f65682019-03-15 15:08:05 +01003132 if (argc < 1 || argv == NULL) {
3133 /* Ensure at least one (empty) argument is seen */
Victor Stinner74f65682019-03-15 15:08:05 +01003134 argv = empty_argv;
3135 argc = 1;
3136 }
3137
3138 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003139 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003140 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003141 }
3142 if (PySys_SetObject("argv", av) != 0) {
3143 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003144 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003145 }
3146 Py_DECREF(av);
3147
3148 if (updatepath) {
3149 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3150 If argv[0] is a symlink, use the real path. */
Victor Stinner331a6a52019-05-27 16:39:22 +02003151 const PyWideStringList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003152 PyObject *path0 = NULL;
3153 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3154 if (path0 == NULL) {
3155 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003156 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003157
3158 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
3159 if (sys_path != NULL) {
3160 if (PyList_Insert(sys_path, 0, path0) < 0) {
3161 Py_DECREF(path0);
3162 Py_FatalError("can't prepend path0 to sys.path");
3163 }
3164 }
3165 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003166 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003167 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003168}
Guido van Rossuma890e681998-05-12 14:59:24 +00003169
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003170void
3171PySys_SetArgv(int argc, wchar_t **argv)
3172{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003173 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003174}
3175
Victor Stinner14284c22010-04-23 12:02:30 +00003176/* Reimplementation of PyFile_WriteString() no calling indirectly
3177 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3178
3179static int
Victor Stinner79766632010-08-16 17:36:42 +00003180sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003181{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003182 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003183 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003184
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003185 if (file == NULL)
3186 return -1;
3187
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003188 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003189 if (writer == NULL)
3190 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003191
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003192 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003193 if (result == NULL) {
3194 goto error;
3195 } else {
3196 err = 0;
3197 goto finally;
3198 }
Victor Stinner14284c22010-04-23 12:02:30 +00003199
3200error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003202finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003203 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003204 Py_XDECREF(result);
3205 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003206}
3207
Victor Stinner79766632010-08-16 17:36:42 +00003208static int
3209sys_pyfile_write(const char *text, PyObject *file)
3210{
3211 PyObject *unicode = NULL;
3212 int err;
3213
3214 if (file == NULL)
3215 return -1;
3216
3217 unicode = PyUnicode_FromString(text);
3218 if (unicode == NULL)
3219 return -1;
3220
3221 err = sys_pyfile_write_unicode(unicode, file);
3222 Py_DECREF(unicode);
3223 return err;
3224}
Guido van Rossuma890e681998-05-12 14:59:24 +00003225
3226/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3227 Adapted from code submitted by Just van Rossum.
3228
3229 PySys_WriteStdout(format, ...)
3230 PySys_WriteStderr(format, ...)
3231
3232 The first function writes to sys.stdout; the second to sys.stderr. When
3233 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003234 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003235
Victor Stinner14284c22010-04-23 12:02:30 +00003236 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003237 signal handlers: they may raise a new exception whereas sys_write()
3238 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003239
Guido van Rossuma890e681998-05-12 14:59:24 +00003240 Both take a printf-style format string as their first argument followed
3241 by a variable length argument list determined by the format string.
3242
3243 *** WARNING ***
3244
3245 The format should limit the total size of the formatted output string to
3246 1000 bytes. In particular, this means that no unrestricted "%s" formats
3247 should occur; these should be limited using "%.<N>s where <N> is a
3248 decimal number calculated so that <N> plus the maximum size of other
3249 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3250 which can print hundreds of digits for very large numbers.
3251
3252 */
3253
3254static void
Victor Stinner09054372013-11-06 22:41:44 +01003255sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003257 PyObject *file;
3258 PyObject *error_type, *error_value, *error_traceback;
3259 char buffer[1001];
3260 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00003261
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003262 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003263 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3265 if (sys_pyfile_write(buffer, file) != 0) {
3266 PyErr_Clear();
3267 fputs(buffer, fp);
3268 }
3269 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3270 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003271 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003273 }
3274 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003275}
3276
3277void
Guido van Rossuma890e681998-05-12 14:59:24 +00003278PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003282 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003283 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003284 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003285}
3286
3287void
Guido van Rossuma890e681998-05-12 14:59:24 +00003288PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003293 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003294 va_end(va);
3295}
3296
3297static void
Victor Stinner09054372013-11-06 22:41:44 +01003298sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003299{
3300 PyObject *file, *message;
3301 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003302 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00003303
3304 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003305 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00003306 message = PyUnicode_FromFormatV(format, va);
3307 if (message != NULL) {
3308 if (sys_pyfile_write_unicode(message, file) != 0) {
3309 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02003310 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003311 if (utf8 != NULL)
3312 fputs(utf8, fp);
3313 }
3314 Py_DECREF(message);
3315 }
3316 PyErr_Restore(error_type, error_value, error_traceback);
3317}
3318
3319void
3320PySys_FormatStdout(const char *format, ...)
3321{
3322 va_list va;
3323
3324 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003325 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003326 va_end(va);
3327}
3328
3329void
3330PySys_FormatStderr(const char *format, ...)
3331{
3332 va_list va;
3333
3334 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003335 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003336 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003337}