blob: 08a1a2995e004e676ff99bdfb9e95065eddf5774 [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 Stinner8b9dbc02019-03-27 01:36:16 +010020#include "pycore_coreconfig.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 }
123 PyInterpreterState *is = ts ? ts->interp : NULL;
124 return _PyRuntime.audit_hook_head
125 || (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);
162 eventArgs = Py_VaBuildValue(argFormat, args);
163 if (eventArgs && !PyTuple_Check(eventArgs)) {
164 PyObject *argTuple = PyTuple_Pack(1, eventArgs);
165 Py_DECREF(eventArgs);
166 eventArgs = argTuple;
167 }
168 } else {
169 eventArgs = PyTuple_New(0);
170 }
171 if (!eventArgs) {
172 goto exit;
173 }
174
175 /* Call global hooks */
176 for (; e; e = e->next) {
177 if (e->hookCFunction(event, eventArgs, e->userData) < 0) {
178 goto exit;
179 }
180 }
181
182 /* Dtrace USDT point */
183 if (dtrace) {
184 PyDTrace_AUDIT(event, (void *)eventArgs);
185 }
186
187 /* Call interpreter hooks */
188 if (is && is->audit_hooks) {
189 eventName = PyUnicode_FromString(event);
190 if (!eventName) {
191 goto exit;
192 }
193
194 hooks = PyObject_GetIter(is->audit_hooks);
195 if (!hooks) {
196 goto exit;
197 }
198
199 /* Disallow tracing in hooks unless explicitly enabled */
200 ts->tracing++;
201 ts->use_tracing = 0;
202 while ((hook = PyIter_Next(hooks)) != NULL) {
203 PyObject *o;
204 int canTrace = -1;
205 o = PyObject_GetAttrString(hook, "__cantrace__");
206 if (o) {
207 canTrace = PyObject_IsTrue(o);
208 Py_DECREF(o);
209 } else if (PyErr_Occurred() &&
210 PyErr_ExceptionMatches(PyExc_AttributeError)) {
211 PyErr_Clear();
212 canTrace = 0;
213 }
214 if (canTrace < 0) {
215 break;
216 }
217 if (canTrace) {
218 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
219 ts->tracing--;
220 }
221 o = PyObject_CallFunctionObjArgs(hook, eventName,
222 eventArgs, NULL);
223 if (canTrace) {
224 ts->tracing++;
225 ts->use_tracing = 0;
226 }
227 if (!o) {
228 break;
229 }
230 Py_DECREF(o);
231 Py_CLEAR(hook);
232 }
233 ts->use_tracing = (ts->c_tracefunc || ts->c_profilefunc);
234 ts->tracing--;
235 if (PyErr_Occurred()) {
236 goto exit;
237 }
238 }
239
240 res = 0;
241
242exit:
243 Py_XDECREF(hook);
244 Py_XDECREF(hooks);
245 Py_XDECREF(eventName);
246 Py_XDECREF(eventArgs);
247
248 if (ts) {
249 if (!res) {
250 PyErr_Restore(exc_type, exc_value, exc_tb);
251 } else {
252 assert(PyErr_Occurred());
253 Py_XDECREF(exc_type);
254 Py_XDECREF(exc_value);
255 Py_XDECREF(exc_tb);
256 }
257 }
258
259 return res;
260}
261
262/* We expose this function primarily for our own cleanup during
263 * finalization. In general, it should not need to be called,
264 * and as such it is not defined in any header files.
265 */
266void _PySys_ClearAuditHooks(void) {
267 /* Must be finalizing to clear hooks */
268 _PyRuntimeState *runtime = &_PyRuntime;
269 PyThreadState *ts = _PyRuntimeState_GetThreadState(runtime);
270 assert(!ts || _Py_CURRENTLY_FINALIZING(runtime, ts));
271 if (!ts || !_Py_CURRENTLY_FINALIZING(runtime, ts))
272 return;
273
274 if (Py_VerboseFlag) {
275 PySys_WriteStderr("# clear sys.audit hooks\n");
276 }
277
278 /* Hooks can abort later hooks for this event, but cannot
279 abort the clear operation itself. */
280 PySys_Audit("cpython._PySys_ClearAuditHooks", NULL);
281 PyErr_Clear();
282
283 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head, *n;
284 _PyRuntime.audit_hook_head = NULL;
285 while (e) {
286 n = e->next;
287 PyMem_RawFree(e);
288 e = n;
289 }
290}
291
292int
293PySys_AddAuditHook(Py_AuditHookFunction hook, void *userData)
294{
295 /* Invoke existing audit hooks to allow them an opportunity to abort. */
296 /* Cannot invoke hooks until we are initialized */
297 if (Py_IsInitialized()) {
298 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
299 if (PyErr_ExceptionMatches(PyExc_Exception)) {
300 /* We do not report errors derived from Exception */
301 PyErr_Clear();
302 return 0;
303 }
304 return -1;
305 }
306 }
307
308 _Py_AuditHookEntry *e = _PyRuntime.audit_hook_head;
309 if (!e) {
310 e = (_Py_AuditHookEntry*)PyMem_RawMalloc(sizeof(_Py_AuditHookEntry));
311 _PyRuntime.audit_hook_head = e;
312 } else {
313 while (e->next)
314 e = e->next;
315 e = e->next = (_Py_AuditHookEntry*)PyMem_RawMalloc(
316 sizeof(_Py_AuditHookEntry));
317 }
318
319 if (!e) {
320 if (Py_IsInitialized())
321 PyErr_NoMemory();
322 return -1;
323 }
324
325 e->next = NULL;
326 e->hookCFunction = (Py_AuditHookFunction)hook;
327 e->userData = userData;
328
329 return 0;
330}
331
332/*[clinic input]
333sys.addaudithook
334
335 hook: object
336
337Adds a new audit hook callback.
338[clinic start generated code]*/
339
340static PyObject *
341sys_addaudithook_impl(PyObject *module, PyObject *hook)
342/*[clinic end generated code: output=4f9c17aaeb02f44e input=0f3e191217a45e34]*/
343{
344 /* Invoke existing audit hooks to allow them an opportunity to abort. */
345 if (PySys_Audit("sys.addaudithook", NULL) < 0) {
346 if (PyErr_ExceptionMatches(PyExc_Exception)) {
347 /* We do not report errors derived from Exception */
348 PyErr_Clear();
349 Py_RETURN_NONE;
350 }
351 return NULL;
352 }
353
354 PyInterpreterState *is = _PyInterpreterState_Get();
355
356 if (is->audit_hooks == NULL) {
357 is->audit_hooks = PyList_New(0);
358 if (is->audit_hooks == NULL) {
359 return NULL;
360 }
361 }
362
363 if (PyList_Append(is->audit_hooks, hook) < 0) {
364 return NULL;
365 }
366
367 Py_RETURN_NONE;
368}
369
370PyDoc_STRVAR(audit_doc,
371"audit(event, *args)\n\
372\n\
373Passes the event to any audit hooks that are attached.");
374
375static PyObject *
376sys_audit(PyObject *self, PyObject *const *args, Py_ssize_t argc)
377{
378 if (argc == 0) {
379 PyErr_SetString(PyExc_TypeError, "audit() missing 1 required positional argument: 'event'");
380 return NULL;
381 }
382
383 if (!should_audit()) {
384 Py_RETURN_NONE;
385 }
386
387 PyObject *auditEvent = args[0];
388 if (!auditEvent) {
389 PyErr_SetString(PyExc_TypeError, "expected str for argument 'event'");
390 return NULL;
391 }
392 if (!PyUnicode_Check(auditEvent)) {
393 PyErr_Format(PyExc_TypeError, "expected str for argument 'event', not %.200s",
394 Py_TYPE(auditEvent)->tp_name);
395 return NULL;
396 }
397 const char *event = PyUnicode_AsUTF8(auditEvent);
398 if (!event) {
399 return NULL;
400 }
401
402 PyObject *auditArgs = _PyTuple_FromArray(args + 1, argc - 1);
403 if (!auditArgs) {
404 return NULL;
405 }
406
407 int res = PySys_Audit(event, "O", auditArgs);
408 Py_DECREF(auditArgs);
409
410 if (res < 0) {
411 return NULL;
412 }
413
414 Py_RETURN_NONE;
415}
416
417
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400418static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200419sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400420{
421 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300422 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400423
424 if (envar == NULL || strlen(envar) == 0) {
425 envar = "pdb.set_trace";
426 }
427 else if (!strcmp(envar, "0")) {
428 /* The breakpoint is explicitly no-op'd. */
429 Py_RETURN_NONE;
430 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300431 /* According to POSIX the string returned by getenv() might be invalidated
432 * or the string content might be overwritten by a subsequent call to
433 * getenv(). Since importing a module can performs the getenv() calls,
434 * we need to save a copy of envar. */
435 envar = _PyMem_RawStrdup(envar);
436 if (envar == NULL) {
437 PyErr_NoMemory();
438 return NULL;
439 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200440 const char *last_dot = strrchr(envar, '.');
441 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400442 PyObject *modulepath = NULL;
443
444 if (last_dot == NULL) {
445 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
446 modulepath = PyUnicode_FromString("builtins");
447 attrname = envar;
448 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200449 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400450 /* Split on the last dot; */
451 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
452 attrname = last_dot + 1;
453 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200454 else {
455 goto warn;
456 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400457 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300458 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400459 return NULL;
460 }
461
Anthony Sottiledce345c2018-11-01 10:25:05 -0700462 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400463 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400464
465 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200466 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
467 goto warn;
468 }
469 PyMem_RawFree(envar);
470 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400471 }
472
473 PyObject *hook = PyObject_GetAttrString(module, attrname);
474 Py_DECREF(module);
475
476 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200477 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
478 goto warn;
479 }
480 PyMem_RawFree(envar);
481 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400482 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300483 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400484 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
485 Py_DECREF(hook);
486 return retval;
487
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200488 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400489 /* If any of the imports went wrong, then warn and ignore. */
490 PyErr_Clear();
491 int status = PyErr_WarnFormat(
492 PyExc_RuntimeWarning, 0,
493 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300494 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400495 if (status < 0) {
496 /* Printing the warning raised an exception. */
497 return NULL;
498 }
499 /* The warning was (probably) issued. */
500 Py_RETURN_NONE;
501}
502
503PyDoc_STRVAR(breakpointhook_doc,
504"breakpointhook(*args, **kws)\n"
505"\n"
506"This hook function is called by built-in breakpoint().\n"
507);
508
Victor Stinner13d49ee2010-12-04 17:24:33 +0000509/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
510 error handler. If sys.stdout has a buffer attribute, use
511 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
512 sys.stdout.write(redecoded).
513
514 Helper function for sys_displayhook(). */
515static int
516sys_displayhook_unencodable(PyObject *outf, PyObject *o)
517{
518 PyObject *stdout_encoding = NULL;
519 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200520 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000521 int ret;
522
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200523 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000524 if (stdout_encoding == NULL)
525 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200526 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000527 if (stdout_encoding_str == NULL)
528 goto error;
529
530 repr_str = PyObject_Repr(o);
531 if (repr_str == NULL)
532 goto error;
533 encoded = PyUnicode_AsEncodedString(repr_str,
534 stdout_encoding_str,
535 "backslashreplace");
536 Py_DECREF(repr_str);
537 if (encoded == NULL)
538 goto error;
539
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200540 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
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 {
550 PyErr_Clear();
551 escaped_str = PyUnicode_FromEncodedObject(encoded,
552 stdout_encoding_str,
553 "strict");
554 Py_DECREF(encoded);
555 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
556 Py_DECREF(escaped_str);
557 goto error;
558 }
559 Py_DECREF(escaped_str);
560 }
561 ret = 0;
562 goto finally;
563
564error:
565 ret = -1;
566finally:
567 Py_XDECREF(stdout_encoding);
568 return ret;
569}
570
Tal Einatede0b6f2018-12-31 17:12:08 +0200571/*[clinic input]
572sys.displayhook
573
574 object as o: object
575 /
576
577Print an object to sys.stdout and also save it in builtins._
578[clinic start generated code]*/
579
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000580static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200581sys_displayhook(PyObject *module, PyObject *o)
582/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000583{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100585 PyObject *builtins;
586 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000587 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000588
Eric Snow3f9eee62017-09-15 16:35:20 -0600589 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (builtins == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +0100591 if (!PyErr_Occurred()) {
592 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
593 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 return NULL;
595 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600596 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 /* Print value except if None */
599 /* After printing, also assign to '_' */
600 /* Before, set '_' to None to avoid recursion */
601 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200602 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200604 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100606 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (outf == NULL || outf == Py_None) {
608 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
609 return NULL;
610 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000611 if (PyFile_WriteObject(o, outf, 0) != 0) {
612 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
613 /* repr(o) is not encodable to sys.stdout.encoding with
614 * sys.stdout.errors error handler (which is probably 'strict') */
615 PyErr_Clear();
616 err = sys_displayhook_unencodable(outf, o);
617 if (err)
618 return NULL;
619 }
620 else {
621 return NULL;
622 }
623 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100624 if (newline == NULL) {
625 newline = PyUnicode_FromString("\n");
626 if (newline == NULL)
627 return NULL;
628 }
629 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200631 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200633 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000634}
635
Tal Einatede0b6f2018-12-31 17:12:08 +0200636
637/*[clinic input]
638sys.excepthook
639
640 exctype: object
641 value: object
642 traceback: object
643 /
644
645Handle an exception by displaying it with a traceback on sys.stderr.
646[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000647
648static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200649sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
650 PyObject *traceback)
651/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000652{
Tal Einatede0b6f2018-12-31 17:12:08 +0200653 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200654 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000655}
656
Tal Einatede0b6f2018-12-31 17:12:08 +0200657
658/*[clinic input]
659sys.exc_info
660
661Return current exception information: (type, value, traceback).
662
663Return information about the most recent exception caught by an except
664clause in the current stack frame or in an older stack frame.
665[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000666
667static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200668sys_exc_info_impl(PyObject *module)
669/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000670{
Victor Stinner50b48572018-11-01 01:51:40 +0100671 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return Py_BuildValue(
673 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100674 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
675 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
676 err_info->exc_traceback != NULL ?
677 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000678}
679
Tal Einatede0b6f2018-12-31 17:12:08 +0200680
681/*[clinic input]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200682sys.unraisablehook
683
684 unraisable: object
685 /
686
687Handle an unraisable exception.
688
689The unraisable argument has the following attributes:
690
691* exc_type: Exception type.
Victor Stinner71c52e32019-05-27 08:57:14 +0200692* exc_value: Exception value, can be None.
693* exc_traceback: Exception traceback, can be None.
694* err_msg: Error message, can be None.
695* object: Object causing the exception, can be None.
Victor Stinneref9d9b62019-05-22 11:28:22 +0200696[clinic start generated code]*/
697
698static PyObject *
699sys_unraisablehook(PyObject *module, PyObject *unraisable)
Victor Stinner71c52e32019-05-27 08:57:14 +0200700/*[clinic end generated code: output=bb92838b32abaa14 input=ec3af148294af8d3]*/
Victor Stinneref9d9b62019-05-22 11:28:22 +0200701{
702 return _PyErr_WriteUnraisableDefaultHook(unraisable);
703}
704
705
706/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200707sys.exit
708
709 status: object = NULL
710 /
711
712Exit the interpreter by raising SystemExit(status).
713
714If the status is omitted or None, it defaults to zero (i.e., success).
715If the status is an integer, it will be used as the system exit status.
716If it is another kind of object, it will be printed and the system
717exit status will be one (i.e., failure).
718[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000719
720static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200721sys_exit_impl(PyObject *module, PyObject *status)
722/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200725 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000727}
728
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000729
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000730
Tal Einatede0b6f2018-12-31 17:12:08 +0200731/*[clinic input]
732sys.getdefaultencoding
733
734Return the current default encoding used by the Unicode implementation.
735[clinic start generated code]*/
736
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000737static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200738sys_getdefaultencoding_impl(PyObject *module)
739/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000740{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000741 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000742}
743
Tal Einatede0b6f2018-12-31 17:12:08 +0200744/*[clinic input]
745sys.getfilesystemencoding
746
747Return the encoding used to convert Unicode filenames to OS filenames.
748[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000749
750static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200751sys_getfilesystemencoding_impl(PyObject *module)
752/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000753{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200754 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
755 const _PyCoreConfig *config = &interp->core_config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400756 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000757}
758
Tal Einatede0b6f2018-12-31 17:12:08 +0200759/*[clinic input]
760sys.getfilesystemencodeerrors
761
762Return the error mode used Unicode to OS filename conversion.
763[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000764
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000765static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200766sys_getfilesystemencodeerrors_impl(PyObject *module)
767/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700768{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200769 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
770 const _PyCoreConfig *config = &interp->core_config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400771 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700772}
773
Tal Einatede0b6f2018-12-31 17:12:08 +0200774/*[clinic input]
775sys.intern
776
777 string as s: unicode
778 /
779
780``Intern'' the given string.
781
782This enters the string in the (global) table of interned strings whose
783purpose is to speed up dictionary lookups. Return the string itself or
784the previously interned string object with the same value.
785[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700786
787static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200788sys_intern_impl(PyObject *module, PyObject *s)
789/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000790{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791 if (PyUnicode_CheckExact(s)) {
792 Py_INCREF(s);
793 PyUnicode_InternInPlace(&s);
794 return s;
795 }
796 else {
797 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200798 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000799 return NULL;
800 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000801}
802
Georg Brandl66a796e2006-12-19 20:50:34 +0000803
Fred Drake5755ce62001-06-27 19:19:46 +0000804/*
805 * Cached interned string objects used for calling the profile and
806 * trace functions. Initialized by trace_init().
807 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000808static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000809
810static int
811trace_init(void)
812{
Nick Coghlan5a851672017-09-08 10:14:16 +1000813 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200814 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000815 "c_call", "c_exception", "c_return",
816 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200817 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 PyObject *name;
819 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000820 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 if (whatstrings[i] == NULL) {
822 name = PyUnicode_InternFromString(whatnames[i]);
823 if (name == NULL)
824 return -1;
825 whatstrings[i] = name;
826 }
827 }
828 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000829}
830
831
832static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100833call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200837 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000838
Victor Stinner78da82b2016-08-20 01:22:57 +0200839 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200841 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100842
Victor Stinner78da82b2016-08-20 01:22:57 +0200843 stack[0] = (PyObject *)frame;
844 stack[1] = whatstrings[what];
845 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000847 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200848 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000849
Victor Stinner78da82b2016-08-20 01:22:57 +0200850 PyFrame_LocalsToFast(frame, 1);
851 if (result == NULL) {
852 PyTraceBack_Here(frame);
853 }
854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000855 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000856}
857
858static int
859profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (arg == NULL)
865 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100866 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 if (result == NULL) {
868 PyEval_SetProfile(NULL, NULL);
869 return -1;
870 }
871 Py_DECREF(result);
872 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000873}
874
875static int
876trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000877 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000878{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000879 PyObject *callback;
880 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 if (what == PyTrace_CALL)
883 callback = self;
884 else
885 callback = frame->f_trace;
886 if (callback == NULL)
887 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100888 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 if (result == NULL) {
890 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200891 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return -1;
893 }
894 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300895 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 }
897 else {
898 Py_DECREF(result);
899 }
900 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000901}
Fred Draked0838392001-06-16 21:02:31 +0000902
Fred Drake8b4d01d2000-05-09 19:57:01 +0000903static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000904sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000905{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 if (trace_init() == -1)
907 return NULL;
908 if (args == Py_None)
909 PyEval_SetTrace(NULL, NULL);
910 else
911 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200912 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000913}
914
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000915PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000916"settrace(function)\n\
917\n\
918Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000919function call. See the debugger chapter in the library manual."
920);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000921
Tal Einatede0b6f2018-12-31 17:12:08 +0200922/*[clinic input]
923sys.gettrace
924
925Return the global debug tracing function set with sys.settrace.
926
927See the debugger chapter in the library manual.
928[clinic start generated code]*/
929
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000930static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200931sys_gettrace_impl(PyObject *module)
932/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000933{
Victor Stinner50b48572018-11-01 01:51:40 +0100934 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 if (temp == NULL)
938 temp = Py_None;
939 Py_INCREF(temp);
940 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000941}
942
Christian Heimes9bd667a2008-01-20 15:14:11 +0000943static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000944sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946 if (trace_init() == -1)
947 return NULL;
948 if (args == Py_None)
949 PyEval_SetProfile(NULL, NULL);
950 else
951 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200952 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000953}
954
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000955PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000956"setprofile(function)\n\
957\n\
958Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000959and return. See the profiler chapter in the library manual."
960);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000961
Tal Einatede0b6f2018-12-31 17:12:08 +0200962/*[clinic input]
963sys.getprofile
964
965Return the profiling function set with sys.setprofile.
966
967See the profiler chapter in the library manual.
968[clinic start generated code]*/
969
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000970static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200971sys_getprofile_impl(PyObject *module)
972/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000973{
Victor Stinner50b48572018-11-01 01:51:40 +0100974 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000975 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000977 if (temp == NULL)
978 temp = Py_None;
979 Py_INCREF(temp);
980 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000981}
982
Tal Einatede0b6f2018-12-31 17:12:08 +0200983/*[clinic input]
984sys.setcheckinterval
985
986 n: int
987 /
988
989Set the async event check interval to n instructions.
990
991This tells the Python interpreter to check for asynchronous events
992every n instructions.
993
994This also affects how often thread switches occur.
995[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000996
997static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200998sys_setcheckinterval_impl(PyObject *module, int n)
999/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1002 "sys.getcheckinterval() and sys.setcheckinterval() "
1003 "are deprecated. Use sys.setswitchinterval() "
1004 "instead.", 1) < 0)
1005 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001006
Victor Stinnercaba55b2018-08-03 15:33:52 +02001007 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +02001008 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001009 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001010}
1011
Tal Einatede0b6f2018-12-31 17:12:08 +02001012/*[clinic input]
1013sys.getcheckinterval
1014
1015Return the current check interval; see sys.setcheckinterval().
1016[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001017
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001018static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001019sys_getcheckinterval_impl(PyObject *module)
1020/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001021{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1023 "sys.getcheckinterval() and sys.setcheckinterval() "
1024 "are deprecated. Use sys.getswitchinterval() "
1025 "instead.", 1) < 0)
1026 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001027 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001028 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001029}
1030
Tal Einatede0b6f2018-12-31 17:12:08 +02001031/*[clinic input]
1032sys.setswitchinterval
1033
1034 interval: double
1035 /
1036
1037Set the ideal thread switching delay inside the Python interpreter.
1038
1039The actual frequency of switching threads can be lower if the
1040interpreter executes long sequences of uninterruptible code
1041(this is implementation-specific and workload-dependent).
1042
1043The parameter must represent the desired switching delay in seconds
1044A typical value is 0.005 (5 milliseconds).
1045[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001046
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001047static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001048sys_setswitchinterval_impl(PyObject *module, double interval)
1049/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001050{
Tal Einatede0b6f2018-12-31 17:12:08 +02001051 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyErr_SetString(PyExc_ValueError,
1053 "switch interval must be strictly positive");
1054 return NULL;
1055 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001056 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001057 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001058}
1059
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001060
Tal Einatede0b6f2018-12-31 17:12:08 +02001061/*[clinic input]
1062sys.getswitchinterval -> double
1063
1064Return the current thread switch interval; see sys.setswitchinterval().
1065[clinic start generated code]*/
1066
1067static double
1068sys_getswitchinterval_impl(PyObject *module)
1069/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001070{
Tal Einatede0b6f2018-12-31 17:12:08 +02001071 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001072}
1073
Tal Einatede0b6f2018-12-31 17:12:08 +02001074/*[clinic input]
1075sys.setrecursionlimit
1076
1077 limit as new_limit: int
1078 /
1079
1080Set the maximum depth of the Python interpreter stack to n.
1081
1082This limit prevents infinite recursion from causing an overflow of the C
1083stack and crashing Python. The highest possible limit is platform-
1084dependent.
1085[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001086
Tim Peterse5e065b2003-07-06 18:36:54 +00001087static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001088sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1089/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001090{
Tal Einatede0b6f2018-12-31 17:12:08 +02001091 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +02001092 PyThreadState *tstate;
1093
Victor Stinner50856d52015-10-13 00:11:21 +02001094 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +02001096 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097 return NULL;
1098 }
Victor Stinner50856d52015-10-13 00:11:21 +02001099
1100 /* Issue #25274: When the recursion depth hits the recursion limit in
1101 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1102 set to 1 and a RecursionError is raised. The overflowed flag is reset
1103 to 0 when the recursion depth goes below the low-water mark: see
1104 Py_LeaveRecursiveCall().
1105
1106 Reject too low new limit if the current recursion depth is higher than
1107 the new low-water mark. Otherwise it may not be possible anymore to
1108 reset the overflowed flag to 0. */
1109 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +01001110 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001111 if (tstate->recursion_depth >= mark) {
1112 PyErr_Format(PyExc_RecursionError,
1113 "cannot set the recursion limit to %i at "
1114 "the recursion depth %i: the limit is too low",
1115 new_limit, tstate->recursion_depth);
1116 return NULL;
1117 }
1118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001119 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001120 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001121}
1122
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001123/*[clinic input]
1124sys.set_coroutine_origin_tracking_depth
1125
1126 depth: int
1127
1128Enable or disable origin tracking for coroutine objects in this thread.
1129
Tal Einatede0b6f2018-12-31 17:12:08 +02001130Coroutine objects will track 'depth' frames of traceback information
1131about where they came from, available in their cr_origin attribute.
1132
1133Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001134[clinic start generated code]*/
1135
1136static PyObject *
1137sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001138/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001139{
1140 if (depth < 0) {
1141 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
1142 return NULL;
1143 }
1144 _PyEval_SetCoroutineOriginTrackingDepth(depth);
1145 Py_RETURN_NONE;
1146}
1147
1148/*[clinic input]
1149sys.get_coroutine_origin_tracking_depth -> int
1150
1151Check status of origin tracking for coroutine objects in this thread.
1152[clinic start generated code]*/
1153
1154static int
1155sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1156/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1157{
1158 return _PyEval_GetCoroutineOriginTrackingDepth();
1159}
1160
Tal Einatede0b6f2018-12-31 17:12:08 +02001161/*[clinic input]
1162sys.set_coroutine_wrapper
1163
1164 wrapper: object
1165 /
1166
1167Set a wrapper for coroutine objects.
1168[clinic start generated code]*/
1169
Yury Selivanov75445082015-05-11 22:57:16 -04001170static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001171sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
1172/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -04001173{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001174 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1175 "set_coroutine_wrapper is deprecated", 1) < 0) {
1176 return NULL;
1177 }
1178
Yury Selivanov75445082015-05-11 22:57:16 -04001179 if (wrapper != Py_None) {
1180 if (!PyCallable_Check(wrapper)) {
1181 PyErr_Format(PyExc_TypeError,
1182 "callable expected, got %.50s",
1183 Py_TYPE(wrapper)->tp_name);
1184 return NULL;
1185 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -04001186 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -04001187 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -04001188 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -04001189 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -04001190 }
Yury Selivanov75445082015-05-11 22:57:16 -04001191 Py_RETURN_NONE;
1192}
1193
Tal Einatede0b6f2018-12-31 17:12:08 +02001194/*[clinic input]
1195sys.get_coroutine_wrapper
1196
1197Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
1198[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -04001199
1200static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001201sys_get_coroutine_wrapper_impl(PyObject *module)
1202/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -04001203{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001204 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1205 "get_coroutine_wrapper is deprecated", 1) < 0) {
1206 return NULL;
1207 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -04001208 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -04001209 if (wrapper == NULL) {
1210 wrapper = Py_None;
1211 }
1212 Py_INCREF(wrapper);
1213 return wrapper;
1214}
1215
Yury Selivanov75445082015-05-11 22:57:16 -04001216
Yury Selivanoveb636452016-09-08 22:01:51 -07001217static PyTypeObject AsyncGenHooksType;
1218
1219PyDoc_STRVAR(asyncgen_hooks_doc,
1220"asyncgen_hooks\n\
1221\n\
1222A struct sequence providing information about asynhronous\n\
1223generators hooks. The attributes are read only.");
1224
1225static PyStructSequence_Field asyncgen_hooks_fields[] = {
1226 {"firstiter", "Hook to intercept first iteration"},
1227 {"finalizer", "Hook to intercept finalization"},
1228 {0}
1229};
1230
1231static PyStructSequence_Desc asyncgen_hooks_desc = {
1232 "asyncgen_hooks", /* name */
1233 asyncgen_hooks_doc, /* doc */
1234 asyncgen_hooks_fields , /* fields */
1235 2
1236};
1237
Yury Selivanoveb636452016-09-08 22:01:51 -07001238static PyObject *
1239sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1240{
1241 static char *keywords[] = {"firstiter", "finalizer", NULL};
1242 PyObject *firstiter = NULL;
1243 PyObject *finalizer = NULL;
1244
1245 if (!PyArg_ParseTupleAndKeywords(
1246 args, kw, "|OO", keywords,
1247 &firstiter, &finalizer)) {
1248 return NULL;
1249 }
1250
1251 if (finalizer && finalizer != Py_None) {
1252 if (!PyCallable_Check(finalizer)) {
1253 PyErr_Format(PyExc_TypeError,
1254 "callable finalizer expected, got %.50s",
1255 Py_TYPE(finalizer)->tp_name);
1256 return NULL;
1257 }
1258 _PyEval_SetAsyncGenFinalizer(finalizer);
1259 }
1260 else if (finalizer == Py_None) {
1261 _PyEval_SetAsyncGenFinalizer(NULL);
1262 }
1263
1264 if (firstiter && firstiter != Py_None) {
1265 if (!PyCallable_Check(firstiter)) {
1266 PyErr_Format(PyExc_TypeError,
1267 "callable firstiter expected, got %.50s",
1268 Py_TYPE(firstiter)->tp_name);
1269 return NULL;
1270 }
1271 _PyEval_SetAsyncGenFirstiter(firstiter);
1272 }
1273 else if (firstiter == Py_None) {
1274 _PyEval_SetAsyncGenFirstiter(NULL);
1275 }
1276
1277 Py_RETURN_NONE;
1278}
1279
1280PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001281"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001282\n\
1283Set a finalizer for async generators objects."
1284);
1285
Tal Einatede0b6f2018-12-31 17:12:08 +02001286/*[clinic input]
1287sys.get_asyncgen_hooks
1288
1289Return the installed asynchronous generators hooks.
1290
1291This returns a namedtuple of the form (firstiter, finalizer).
1292[clinic start generated code]*/
1293
Yury Selivanoveb636452016-09-08 22:01:51 -07001294static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001295sys_get_asyncgen_hooks_impl(PyObject *module)
1296/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001297{
1298 PyObject *res;
1299 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1300 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1301
1302 res = PyStructSequence_New(&AsyncGenHooksType);
1303 if (res == NULL) {
1304 return NULL;
1305 }
1306
1307 if (firstiter == NULL) {
1308 firstiter = Py_None;
1309 }
1310
1311 if (finalizer == NULL) {
1312 finalizer = Py_None;
1313 }
1314
1315 Py_INCREF(firstiter);
1316 PyStructSequence_SET_ITEM(res, 0, firstiter);
1317
1318 Py_INCREF(finalizer);
1319 PyStructSequence_SET_ITEM(res, 1, finalizer);
1320
1321 return res;
1322}
1323
Yury Selivanoveb636452016-09-08 22:01:51 -07001324
Mark Dickinsondc787d22010-05-23 13:33:13 +00001325static PyTypeObject Hash_InfoType;
1326
1327PyDoc_STRVAR(hash_info_doc,
1328"hash_info\n\
1329\n\
1330A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001331hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001332
1333static PyStructSequence_Field hash_info_fields[] = {
1334 {"width", "width of the type used for hashing, in bits"},
1335 {"modulus", "prime number giving the modulus on which the hash "
1336 "function is based"},
1337 {"inf", "value to be used for hash of a positive infinity"},
1338 {"nan", "value to be used for hash of a nan"},
1339 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001340 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1341 "memoryviews"},
1342 {"hash_bits", "internal output size of hash algorithm"},
1343 {"seed_bits", "seed size of hash algorithm"},
1344 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001345 {NULL, NULL}
1346};
1347
1348static PyStructSequence_Desc hash_info_desc = {
1349 "sys.hash_info",
1350 hash_info_doc,
1351 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001352 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001353};
1354
Matthias Klosed885e952010-07-06 10:53:30 +00001355static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001356get_hash_info(void)
1357{
1358 PyObject *hash_info;
1359 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001360 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001361 hash_info = PyStructSequence_New(&Hash_InfoType);
1362 if (hash_info == NULL)
1363 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001364 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001365 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001366 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001367 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001368 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001369 PyStructSequence_SET_ITEM(hash_info, field++,
1370 PyLong_FromLong(_PyHASH_INF));
1371 PyStructSequence_SET_ITEM(hash_info, field++,
1372 PyLong_FromLong(_PyHASH_NAN));
1373 PyStructSequence_SET_ITEM(hash_info, field++,
1374 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001375 PyStructSequence_SET_ITEM(hash_info, field++,
1376 PyUnicode_FromString(hashfunc->name));
1377 PyStructSequence_SET_ITEM(hash_info, field++,
1378 PyLong_FromLong(hashfunc->hash_bits));
1379 PyStructSequence_SET_ITEM(hash_info, field++,
1380 PyLong_FromLong(hashfunc->seed_bits));
1381 PyStructSequence_SET_ITEM(hash_info, field++,
1382 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001383 if (PyErr_Occurred()) {
1384 Py_CLEAR(hash_info);
1385 return NULL;
1386 }
1387 return hash_info;
1388}
Tal Einatede0b6f2018-12-31 17:12:08 +02001389/*[clinic input]
1390sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001391
Tal Einatede0b6f2018-12-31 17:12:08 +02001392Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001393
Tal Einatede0b6f2018-12-31 17:12:08 +02001394The recursion limit is the maximum depth of the Python interpreter
1395stack. This limit prevents infinite recursion from causing an overflow
1396of the C stack and crashing Python.
1397[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001398
1399static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001400sys_getrecursionlimit_impl(PyObject *module)
1401/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001402{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001404}
1405
Mark Hammond8696ebc2002-10-08 02:44:31 +00001406#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001407
Eric Smithf7bb5782010-01-27 00:44:57 +00001408static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1409
1410static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 {"major", "Major version number"},
1412 {"minor", "Minor version number"},
1413 {"build", "Build number"},
1414 {"platform", "Operating system platform"},
1415 {"service_pack", "Latest Service Pack installed on the system"},
1416 {"service_pack_major", "Service Pack major version number"},
1417 {"service_pack_minor", "Service Pack minor version number"},
1418 {"suite_mask", "Bit mask identifying available product suites"},
1419 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001420 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001422};
1423
1424static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001425 "sys.getwindowsversion", /* name */
1426 sys_getwindowsversion__doc__, /* doc */
1427 windows_version_fields, /* fields */
1428 5 /* For backward compatibility,
1429 only the first 5 items are accessible
1430 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001431};
1432
Steve Dower3e96f322015-03-02 08:01:10 -08001433/* Disable deprecation warnings about GetVersionEx as the result is
1434 being passed straight through to the caller, who is responsible for
1435 using it correctly. */
1436#pragma warning(push)
1437#pragma warning(disable:4996)
1438
Tal Einatede0b6f2018-12-31 17:12:08 +02001439/*[clinic input]
1440sys.getwindowsversion
1441
1442Return info about the running version of Windows as a named tuple.
1443
1444The members are named: major, minor, build, platform, service_pack,
1445service_pack_major, service_pack_minor, suite_mask, product_type and
1446platform_version. For backward compatibility, only the first 5 items
1447are available by indexing. All elements are numbers, except
1448service_pack and platform_type which are strings, and platform_version
1449which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1450workstation, 2 for a domain controller, 3 for a server.
1451Platform_version is a 3-tuple containing a version number that is
1452intended for identifying the OS rather than feature detection.
1453[clinic start generated code]*/
1454
Mark Hammond8696ebc2002-10-08 02:44:31 +00001455static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001456sys_getwindowsversion_impl(PyObject *module)
1457/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyObject *version;
1460 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001461 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001462 DWORD realMajor, realMinor, realBuild;
1463 HANDLE hKernel32;
1464 wchar_t kernel32_path[MAX_PATH];
1465 LPVOID verblock;
1466 DWORD verblock_size;
1467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001469 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 version = PyStructSequence_New(&WindowsVersionType);
1473 if (version == NULL)
1474 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1477 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1478 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1479 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001480 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1482 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1483 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1484 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001485
Steve Dower74f4af72016-09-17 17:27:48 -07001486 realMajor = ver.dwMajorVersion;
1487 realMinor = ver.dwMinorVersion;
1488 realBuild = ver.dwBuildNumber;
1489
1490 // GetVersion will lie if we are running in a compatibility mode.
1491 // We need to read the version info from a system file resource
1492 // to accurately identify the OS version. If we fail for any reason,
1493 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001494 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001495 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001496 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001497 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1498 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1499 (verblock = PyMem_RawMalloc(verblock_size))) {
1500 VS_FIXEDFILEINFO *ffi;
1501 UINT ffi_len;
1502
1503 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1504 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1505 realMajor = HIWORD(ffi->dwProductVersionMS);
1506 realMinor = LOWORD(ffi->dwProductVersionMS);
1507 realBuild = HIWORD(ffi->dwProductVersionLS);
1508 }
1509 PyMem_RawFree(verblock);
1510 }
Segev Finer48fb7662017-06-04 20:52:27 +03001511 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1512 realMajor,
1513 realMinor,
1514 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001515 ));
1516
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001517 if (PyErr_Occurred()) {
1518 Py_DECREF(version);
1519 return NULL;
1520 }
Steve Dower74f4af72016-09-17 17:27:48 -07001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001523}
1524
Steve Dower3e96f322015-03-02 08:01:10 -08001525#pragma warning(pop)
1526
Tal Einatede0b6f2018-12-31 17:12:08 +02001527/*[clinic input]
1528sys._enablelegacywindowsfsencoding
1529
1530Changes the default filesystem encoding to mbcs:replace.
1531
1532This is done for consistency with earlier versions of Python. See PEP
1533529 for more information.
1534
1535This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1536environment variable before launching Python.
1537[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001538
1539static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001540sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1541/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001542{
Victor Stinner709d23d2019-05-02 14:56:30 -04001543 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001544 return NULL;
1545 }
Steve Dowercc16be82016-09-08 10:35:16 -07001546 Py_RETURN_NONE;
1547}
1548
Mark Hammond8696ebc2002-10-08 02:44:31 +00001549#endif /* MS_WINDOWS */
1550
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001551#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001552
1553/*[clinic input]
1554sys.setdlopenflags
1555
1556 flags as new_val: int
1557 /
1558
1559Set the flags used by the interpreter for dlopen calls.
1560
1561This is used, for example, when the interpreter loads extension
1562modules. Among other things, this will enable a lazy resolving of
1563symbols when importing a module, if called as sys.setdlopenflags(0).
1564To share symbols across extension modules, call as
1565sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1566modules can be found in the os module (RTLD_xxx constants, e.g.
1567os.RTLD_LAZY).
1568[clinic start generated code]*/
1569
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001570static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001571sys_setdlopenflags_impl(PyObject *module, int new_val)
1572/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001573{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001574 PyInterpreterState *interp = _PyInterpreterState_Get();
1575 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001576 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001577}
1578
Tal Einatede0b6f2018-12-31 17:12:08 +02001579
1580/*[clinic input]
1581sys.getdlopenflags
1582
1583Return the current value of the flags that are used for dlopen calls.
1584
1585The flag constants are defined in the os module.
1586[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001587
1588static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001589sys_getdlopenflags_impl(PyObject *module)
1590/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001591{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001592 PyInterpreterState *interp = _PyInterpreterState_Get();
1593 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001594}
1595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001597
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001598#ifdef USE_MALLOPT
1599/* Link with -lmalloc (or -lmpc) on an SGI */
1600#include <malloc.h>
1601
Tal Einatede0b6f2018-12-31 17:12:08 +02001602/*[clinic input]
1603sys.mdebug
1604
1605 flag: int
1606 /
1607[clinic start generated code]*/
1608
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001609static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001610sys_mdebug_impl(PyObject *module, int flag)
1611/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001615 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001616}
1617#endif /* USE_MALLOPT */
1618
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001619size_t
1620_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001621{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001624 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 /* Make sure the type is initialized. float gets initialized late */
1627 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001628 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001629
Benjamin Petersonce798522012-01-22 11:24:29 -05001630 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (method == NULL) {
1632 if (!PyErr_Occurred())
1633 PyErr_Format(PyExc_TypeError,
1634 "Type %.100s doesn't define __sizeof__",
1635 Py_TYPE(o)->tp_name);
1636 }
1637 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001638 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 Py_DECREF(method);
1640 }
1641
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001642 if (res == NULL)
1643 return (size_t)-1;
1644
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001645 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001646 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001647 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001648 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001650 if (size < 0) {
1651 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1652 return (size_t)-1;
1653 }
1654
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001656 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001657 return ((size_t)size) + sizeof(PyGC_Head);
1658 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001659}
1660
1661static PyObject *
1662sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1663{
1664 static char *kwlist[] = {"object", "default", 0};
1665 size_t size;
1666 PyObject *o, *dflt = NULL;
1667
1668 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1669 kwlist, &o, &dflt))
1670 return NULL;
1671
1672 size = _PySys_GetSizeOf(o);
1673
1674 if (size == (size_t)-1 && PyErr_Occurred()) {
1675 /* Has a default value been given */
1676 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1677 PyErr_Clear();
1678 Py_INCREF(dflt);
1679 return dflt;
1680 }
1681 else
1682 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001684
1685 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001686}
1687
1688PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001689"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001690\n\
1691Return the size of object in bytes.");
1692
Tal Einatede0b6f2018-12-31 17:12:08 +02001693/*[clinic input]
1694sys.getrefcount -> Py_ssize_t
1695
1696 object: object
1697 /
1698
1699Return the reference count of object.
1700
1701The count returned is generally one higher than you might expect,
1702because it includes the (temporary) reference as an argument to
1703getrefcount().
1704[clinic start generated code]*/
1705
1706static Py_ssize_t
1707sys_getrefcount_impl(PyObject *module, PyObject *object)
1708/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001709{
Tal Einatede0b6f2018-12-31 17:12:08 +02001710 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001711}
1712
Tim Peters4be93d02002-07-07 19:59:50 +00001713#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001714/*[clinic input]
1715sys.gettotalrefcount -> Py_ssize_t
1716[clinic start generated code]*/
1717
1718static Py_ssize_t
1719sys_gettotalrefcount_impl(PyObject *module)
1720/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001721{
Tal Einatede0b6f2018-12-31 17:12:08 +02001722 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001723}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001724#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001725
Tal Einatede0b6f2018-12-31 17:12:08 +02001726/*[clinic input]
1727sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001728
Tal Einatede0b6f2018-12-31 17:12:08 +02001729Return the number of memory blocks currently allocated.
1730[clinic start generated code]*/
1731
1732static Py_ssize_t
1733sys_getallocatedblocks_impl(PyObject *module)
1734/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001735{
Tal Einatede0b6f2018-12-31 17:12:08 +02001736 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001737}
1738
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001739#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001740/*[clinic input]
1741sys.getcounts
1742[clinic start generated code]*/
1743
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001744static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001745sys_getcounts_impl(PyObject *module)
1746/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001747{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001748 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001749
Pablo Galindo49c75a82018-10-28 15:02:17 +00001750 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001751}
1752#endif
1753
Tal Einatede0b6f2018-12-31 17:12:08 +02001754/*[clinic input]
1755sys._getframe
1756
1757 depth: int = 0
1758 /
1759
1760Return a frame object from the call stack.
1761
1762If optional integer depth is given, return the frame object that many
1763calls below the top of the stack. If that is deeper than the call
1764stack, ValueError is raised. The default for depth is zero, returning
1765the frame at the top of the call stack.
1766
1767This function should be used for internal and specialized purposes
1768only.
1769[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001770
1771static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001772sys__getframe_impl(PyObject *module, int depth)
1773/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001774{
Victor Stinner50b48572018-11-01 01:51:40 +01001775 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001776
Steve Dowerb82e17e2019-05-23 08:45:22 -07001777 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1778 return NULL;
1779 }
1780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 while (depth > 0 && f != NULL) {
1782 f = f->f_back;
1783 --depth;
1784 }
1785 if (f == NULL) {
1786 PyErr_SetString(PyExc_ValueError,
1787 "call stack is not deep enough");
1788 return NULL;
1789 }
1790 Py_INCREF(f);
1791 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001792}
1793
Tal Einatede0b6f2018-12-31 17:12:08 +02001794/*[clinic input]
1795sys._current_frames
1796
1797Return a dict mapping each thread's thread id to its current stack frame.
1798
1799This function should be used for specialized purposes only.
1800[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001801
1802static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001803sys__current_frames_impl(PyObject *module)
1804/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001805{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001807}
1808
Tal Einatede0b6f2018-12-31 17:12:08 +02001809/*[clinic input]
1810sys.call_tracing
1811
1812 func: object
1813 args as funcargs: object(subclass_of='&PyTuple_Type')
1814 /
1815
1816Call func(*args), while tracing is enabled.
1817
1818The tracing state is saved, and restored afterwards. This is intended
1819to be called from a debugger from a checkpoint, to recursively debug
1820some other code.
1821[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001822
1823static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001824sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1825/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001826{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001827 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001828}
1829
Tal Einatede0b6f2018-12-31 17:12:08 +02001830/*[clinic input]
1831sys.callstats
1832
1833Return a tuple of function call statistics.
1834
1835A tuple is returned only if CALL_PROFILE was defined when Python was
1836built. Otherwise, this returns None.
1837
1838When enabled, this function returns detailed, implementation-specific
1839details about the number of function calls executed. The return value
1840is a 11-tuple where the entries in the tuple are counts of:
18410. all function calls
18421. calls to PyFunction_Type objects
18432. PyFunction calls that do not create an argument tuple
18443. PyFunction calls that do not create an argument tuple
1845 and bypass PyEval_EvalCodeEx()
18464. PyMethod calls
18475. PyMethod calls on bound methods
18486. PyType calls
18497. PyCFunction calls
18508. generator calls
18519. All other calls
185210. Number of stack pops performed by call_function()
1853[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001854
Victor Stinner048afd92016-11-28 11:59:04 +01001855static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001856sys_callstats_impl(PyObject *module)
1857/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001858{
1859 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1860 "sys.callstats() has been deprecated in Python 3.7 "
1861 "and will be removed in the future", 1) < 0) {
1862 return NULL;
1863 }
1864
1865 Py_RETURN_NONE;
1866}
1867
1868
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001869#ifdef __cplusplus
1870extern "C" {
1871#endif
1872
Tal Einatede0b6f2018-12-31 17:12:08 +02001873/*[clinic input]
1874sys._debugmallocstats
1875
1876Print summary info to stderr about the state of pymalloc's structures.
1877
1878In Py_DEBUG mode, also perform some expensive internal consistency
1879checks.
1880[clinic start generated code]*/
1881
David Malcolm49526f42012-06-22 14:55:41 -04001882static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001883sys__debugmallocstats_impl(PyObject *module)
1884/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001885{
1886#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001887 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001888 fputc('\n', stderr);
1889 }
David Malcolm49526f42012-06-22 14:55:41 -04001890#endif
1891 _PyObject_DebugTypeStats(stderr);
1892
1893 Py_RETURN_NONE;
1894}
David Malcolm49526f42012-06-22 14:55:41 -04001895
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001896#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001897/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001898extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001899#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001900
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001901#ifdef DYNAMIC_EXECUTION_PROFILE
1902/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001903extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001904#endif
1905
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001906#ifdef __cplusplus
1907}
1908#endif
1909
Tal Einatede0b6f2018-12-31 17:12:08 +02001910
1911/*[clinic input]
1912sys._clear_type_cache
1913
1914Clear the internal type lookup cache.
1915[clinic start generated code]*/
1916
Christian Heimes15ebc882008-02-04 18:48:49 +00001917static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001918sys__clear_type_cache_impl(PyObject *module)
1919/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 PyType_ClearCache();
1922 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001923}
1924
Tal Einatede0b6f2018-12-31 17:12:08 +02001925/*[clinic input]
1926sys.is_finalizing
1927
1928Return True if Python is exiting.
1929[clinic start generated code]*/
1930
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001931static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001932sys_is_finalizing_impl(PyObject *module)
1933/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001934{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001935 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001936}
1937
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001938#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001939/*[clinic input]
1940sys.getandroidapilevel
1941
1942Return the build time API version of Android as an integer.
1943[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001944
1945static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001946sys_getandroidapilevel_impl(PyObject *module)
1947/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001948{
1949 return PyLong_FromLong(ANDROID_API_LEVEL);
1950}
1951#endif /* ANDROID_API_LEVEL */
1952
1953
Steve Dowerb82e17e2019-05-23 08:45:22 -07001954
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001955static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001957 SYS_ADDAUDITHOOK_METHODDEF
1958 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001959 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001960 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001961 SYS_CALLSTATS_METHODDEF
1962 SYS__CLEAR_TYPE_CACHE_METHODDEF
1963 SYS__CURRENT_FRAMES_METHODDEF
1964 SYS_DISPLAYHOOK_METHODDEF
1965 SYS_EXC_INFO_METHODDEF
1966 SYS_EXCEPTHOOK_METHODDEF
1967 SYS_EXIT_METHODDEF
1968 SYS_GETDEFAULTENCODING_METHODDEF
1969 SYS_GETDLOPENFLAGS_METHODDEF
1970 SYS_GETALLOCATEDBLOCKS_METHODDEF
1971 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001972#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001974#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001975 SYS_GETFILESYSTEMENCODING_METHODDEF
1976 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001977#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001978 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001979#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001980 SYS_GETTOTALREFCOUNT_METHODDEF
1981 SYS_GETREFCOUNT_METHODDEF
1982 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001983 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001985 SYS__GETFRAME_METHODDEF
1986 SYS_GETWINDOWSVERSION_METHODDEF
1987 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1988 SYS_INTERN_METHODDEF
1989 SYS_IS_FINALIZING_METHODDEF
1990 SYS_MDEBUG_METHODDEF
1991 SYS_SETCHECKINTERVAL_METHODDEF
1992 SYS_GETCHECKINTERVAL_METHODDEF
1993 SYS_SETSWITCHINTERVAL_METHODDEF
1994 SYS_GETSWITCHINTERVAL_METHODDEF
1995 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001997 SYS_GETPROFILE_METHODDEF
1998 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002000 SYS_GETTRACE_METHODDEF
2001 SYS_CALL_TRACING_METHODDEF
2002 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002003 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2004 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002005 SYS_SET_COROUTINE_WRAPPER_METHODDEF
2006 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002007 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002008 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002009 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2010 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002011 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002013};
2014
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002015static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002016list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 PyObject *list = PyList_New(0);
2019 int i;
2020 if (list == NULL)
2021 return NULL;
2022 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2023 PyObject *name = PyUnicode_FromString(
2024 PyImport_Inittab[i].name);
2025 if (name == NULL)
2026 break;
2027 PyList_Append(list, name);
2028 Py_DECREF(name);
2029 }
2030 if (PyList_Sort(list) != 0) {
2031 Py_DECREF(list);
2032 list = NULL;
2033 }
2034 if (list) {
2035 PyObject *v = PyList_AsTuple(list);
2036 Py_DECREF(list);
2037 list = v;
2038 }
2039 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002040}
2041
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002042/* Pre-initialization support for sys.warnoptions and sys._xoptions
2043 *
2044 * Modern internal code paths:
2045 * These APIs get called after _Py_InitializeCore and get to use the
2046 * regular CPython list, dict, and unicode APIs.
2047 *
2048 * Legacy embedding code paths:
2049 * The multi-phase initialization API isn't public yet, so embedding
2050 * apps still need to be able configure sys.warnoptions and sys._xoptions
2051 * before they call Py_Initialize. To support this, we stash copies of
2052 * the supplied wchar * sequences in linked lists, and then migrate the
2053 * contents of those lists to the sys module in _PyInitializeCore.
2054 *
2055 */
2056
2057struct _preinit_entry {
2058 wchar_t *value;
2059 struct _preinit_entry *next;
2060};
2061
2062typedef struct _preinit_entry *_Py_PreInitEntry;
2063
2064static _Py_PreInitEntry _preinit_warnoptions = NULL;
2065static _Py_PreInitEntry _preinit_xoptions = NULL;
2066
2067static _Py_PreInitEntry
2068_alloc_preinit_entry(const wchar_t *value)
2069{
2070 /* To get this to work, we have to initialize the runtime implicitly */
2071 _PyRuntime_Initialize();
2072
2073 /* Force default allocator, so we can ensure that it also gets used to
2074 * destroy the linked list in _clear_preinit_entries.
2075 */
2076 PyMemAllocatorEx old_alloc;
2077 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2078
2079 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2080 if (node != NULL) {
2081 node->value = _PyMem_RawWcsdup(value);
2082 if (node->value == NULL) {
2083 PyMem_RawFree(node);
2084 node = NULL;
2085 };
2086 };
2087
2088 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2089 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002090}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002091
2092static int
2093_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2094{
2095 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2096 if (new_entry == NULL) {
2097 return -1;
2098 }
2099 /* We maintain the linked list in this order so it's easy to play back
2100 * the add commands in the same order later on in _Py_InitializeCore
2101 */
2102 _Py_PreInitEntry last_entry = *optionlist;
2103 if (last_entry == NULL) {
2104 *optionlist = new_entry;
2105 } else {
2106 while (last_entry->next != NULL) {
2107 last_entry = last_entry->next;
2108 }
2109 last_entry->next = new_entry;
2110 }
2111 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002112}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002113
2114static void
2115_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2116{
2117 _Py_PreInitEntry current = *optionlist;
2118 *optionlist = NULL;
2119 /* Deallocate the nodes and their contents using the default allocator */
2120 PyMemAllocatorEx old_alloc;
2121 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2122 while (current != NULL) {
2123 _Py_PreInitEntry next = current->next;
2124 PyMem_RawFree(current->value);
2125 PyMem_RawFree(current);
2126 current = next;
2127 }
2128 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002129}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002130
2131static void
2132_clear_all_preinit_options(void)
2133{
2134 _clear_preinit_entries(&_preinit_warnoptions);
2135 _clear_preinit_entries(&_preinit_xoptions);
2136}
2137
2138static int
2139_PySys_ReadPreInitOptions(void)
2140{
2141 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01002142 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002143 if (tstate == NULL) {
2144 /* Still don't have a thread state, so something is wrong! */
2145 return -1;
2146 }
2147 _Py_PreInitEntry entry = _preinit_warnoptions;
2148 while (entry != NULL) {
2149 PySys_AddWarnOption(entry->value);
2150 entry = entry->next;
2151 }
2152 entry = _preinit_xoptions;
2153 while (entry != NULL) {
2154 PySys_AddXOption(entry->value);
2155 entry = entry->next;
2156 }
2157
2158 _clear_all_preinit_options();
2159 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002160}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002161
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002162static PyObject *
2163get_warnoptions(void)
2164{
Eric Snowdae02762017-09-14 00:35:58 -07002165 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002166 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002167 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2168 * interpreter config. When that happens, we need to properly set
2169 * the `warnoptions` reference in the main interpreter config as well.
2170 *
2171 * For Python 3.7, we shouldn't be able to get here due to the
2172 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2173 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2174 * call optional for embedding applications, thus making this
2175 * reachable again.
2176 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002177 warnoptions = PyList_New(0);
2178 if (warnoptions == NULL)
2179 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002180 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
2181 Py_DECREF(warnoptions);
2182 return NULL;
2183 }
2184 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002185 }
2186 return warnoptions;
2187}
Guido van Rossum23fff912000-12-15 22:02:05 +00002188
2189void
2190PySys_ResetWarnOptions(void)
2191{
Victor Stinner50b48572018-11-01 01:51:40 +01002192 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002193 if (tstate == NULL) {
2194 _clear_preinit_entries(&_preinit_warnoptions);
2195 return;
2196 }
2197
Eric Snowdae02762017-09-14 00:35:58 -07002198 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 if (warnoptions == NULL || !PyList_Check(warnoptions))
2200 return;
2201 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002202}
2203
Victor Stinnere1b29952018-10-30 14:31:42 +01002204static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002205_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002206{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002207 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002208 if (warnoptions == NULL) {
2209 return -1;
2210 }
2211 if (PyList_Append(warnoptions, option)) {
2212 return -1;
2213 }
2214 return 0;
2215}
2216
2217void
2218PySys_AddWarnOptionUnicode(PyObject *option)
2219{
Victor Stinnere1b29952018-10-30 14:31:42 +01002220 if (_PySys_AddWarnOptionWithError(option) < 0) {
2221 /* No return value, therefore clear error state if possible */
2222 if (_PyThreadState_UncheckedGet()) {
2223 PyErr_Clear();
2224 }
2225 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002226}
2227
2228void
2229PySys_AddWarnOption(const wchar_t *s)
2230{
Victor Stinner50b48572018-11-01 01:51:40 +01002231 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002232 if (tstate == NULL) {
2233 _append_preinit_entry(&_preinit_warnoptions, s);
2234 return;
2235 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002236 PyObject *unicode;
2237 unicode = PyUnicode_FromWideChar(s, -1);
2238 if (unicode == NULL)
2239 return;
2240 PySys_AddWarnOptionUnicode(unicode);
2241 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002242}
2243
Christian Heimes33fe8092008-04-13 13:53:33 +00002244int
2245PySys_HasWarnOptions(void)
2246{
Eric Snowdae02762017-09-14 00:35:58 -07002247 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002248 return (warnoptions != NULL && PyList_Check(warnoptions)
2249 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002250}
2251
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002252static PyObject *
2253get_xoptions(void)
2254{
Eric Snowdae02762017-09-14 00:35:58 -07002255 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002256 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002257 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2258 * interpreter config. When that happens, we need to properly set
2259 * the `xoptions` reference in the main interpreter config as well.
2260 *
2261 * For Python 3.7, we shouldn't be able to get here due to the
2262 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2263 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2264 * call optional for embedding applications, thus making this
2265 * reachable again.
2266 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002267 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002268 if (xoptions == NULL)
2269 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002270 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
2271 Py_DECREF(xoptions);
2272 return NULL;
2273 }
2274 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002275 }
2276 return xoptions;
2277}
2278
Victor Stinnere1b29952018-10-30 14:31:42 +01002279static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002280_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002281{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002282 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002283
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002284 PyObject *opts = get_xoptions();
2285 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002286 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002287 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002288
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002290 if (!name_end) {
2291 name = PyUnicode_FromWideChar(s, -1);
2292 value = Py_True;
2293 Py_INCREF(value);
2294 }
2295 else {
2296 name = PyUnicode_FromWideChar(s, name_end - s);
2297 value = PyUnicode_FromWideChar(name_end + 1, -1);
2298 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002299 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002300 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002301 }
2302 if (PyDict_SetItem(opts, name, value) < 0) {
2303 goto error;
2304 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002305 Py_DECREF(name);
2306 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002307 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002308
2309error:
2310 Py_XDECREF(name);
2311 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002312 return -1;
2313}
2314
2315void
2316PySys_AddXOption(const wchar_t *s)
2317{
Victor Stinner50b48572018-11-01 01:51:40 +01002318 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002319 if (tstate == NULL) {
2320 _append_preinit_entry(&_preinit_xoptions, s);
2321 return;
2322 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002323 if (_PySys_AddXOptionWithError(s) < 0) {
2324 /* No return value, therefore clear error state if possible */
2325 if (_PyThreadState_UncheckedGet()) {
2326 PyErr_Clear();
2327 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002328 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002329}
2330
2331PyObject *
2332PySys_GetXOptions(void)
2333{
2334 return get_xoptions();
2335}
2336
Guido van Rossum40552d01998-08-06 03:34:39 +00002337/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2338 Two literals concatenated works just fine. If you have a K&R compiler
2339 or other abomination that however *does* understand longer strings,
2340 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002341PyDoc_VAR(sys_doc) =
2342PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002343"This module provides access to some objects used or maintained by the\n\
2344interpreter and to functions that interact strongly with the interpreter.\n\
2345\n\
2346Dynamic objects:\n\
2347\n\
2348argv -- command line arguments; argv[0] is the script pathname if known\n\
2349path -- module search path; path[0] is the script directory, else ''\n\
2350modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002351\n\
2352displayhook -- called to show results in an interactive session\n\
2353excepthook -- called to handle any uncaught exception other than SystemExit\n\
2354 To customize printing in an interactive session or to install a custom\n\
2355 top-level exception handler, assign other functions to replace these.\n\
2356\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002357stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002358stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002359stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002360 By assigning other file objects (or objects that behave like files)\n\
2361 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002362\n\
2363last_type -- type of last uncaught exception\n\
2364last_value -- value of last uncaught exception\n\
2365last_traceback -- traceback of last uncaught exception\n\
2366 These three are only available in an interactive session after a\n\
2367 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002368"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002369)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002370/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002371PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002372"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002373Static objects:\n\
2374\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002375builtin_module_names -- tuple of module names built into this interpreter\n\
2376copyright -- copyright notice pertaining to this interpreter\n\
2377exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002378executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002379float_info -- a struct sequence with information about the float implementation.\n\
2380float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002381hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002382hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002383implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002384int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002385maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002386maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002387platform -- platform identifier\n\
2388prefix -- prefix used to find the Python library\n\
2389thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002390version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002391version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002392"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002393)
Steve Dowercc16be82016-09-08 10:35:16 -07002394#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002395/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002396PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002397"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002398winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002399"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002400)
Steve Dowercc16be82016-09-08 10:35:16 -07002401#endif /* MS_COREDLL */
2402#ifdef MS_WINDOWS
2403/* concatenating string here */
2404PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002405"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002406"
2407)
2408#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002409PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002410"__stdin__ -- the original stdin; don't touch!\n\
2411__stdout__ -- the original stdout; don't touch!\n\
2412__stderr__ -- the original stderr; don't touch!\n\
2413__displayhook__ -- the original displayhook; don't touch!\n\
2414__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002415\n\
2416Functions:\n\
2417\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002418displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002419excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002420exc_info() -- return thread-safe information about the current exception\n\
2421exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002422getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002423getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002424getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002425getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002426getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002427gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002428setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002429setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002430setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002431setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002432settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002433"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002434)
Fred Drakeccede592000-08-14 20:59:57 +00002435/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002436
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002437
2438PyDoc_STRVAR(flags__doc__,
2439"sys.flags\n\
2440\n\
2441Flags provided through command line arguments or environment vars.");
2442
2443static PyTypeObject FlagsType;
2444
2445static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 {"inspect", "-i"},
2448 {"interactive", "-i"},
2449 {"optimize", "-O or -OO"},
2450 {"dont_write_bytecode", "-B"},
2451 {"no_user_site", "-s"},
2452 {"no_site", "-S"},
2453 {"ignore_environment", "-E"},
2454 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 /* {"unbuffered", "-u"}, */
2456 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002457 {"bytes_warning", "-b"},
2458 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002459 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002460 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002461 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002462 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002464};
2465
2466static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002467 "sys.flags", /* name */
2468 flags__doc__, /* doc */
2469 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002470 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002471};
2472
2473static PyObject*
Victor Stinner43125222019-04-24 18:23:53 +02002474make_flags(_PyRuntimeState *runtime, PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 int pos = 0;
2477 PyObject *seq;
Victor Stinner43125222019-04-24 18:23:53 +02002478 const _PyPreConfig *preconfig = &runtime->preconfig;
2479 const _PyCoreConfig *config = &interp->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 seq = PyStructSequence_New(&FlagsType);
2482 if (seq == NULL)
2483 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002484
2485#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002487
Victor Stinnerfbca9082018-08-30 00:50:45 +02002488 SetFlag(config->parser_debug);
2489 SetFlag(config->inspect);
2490 SetFlag(config->interactive);
2491 SetFlag(config->optimization_level);
2492 SetFlag(!config->write_bytecode);
2493 SetFlag(!config->user_site_directory);
2494 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002495 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002496 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002497 /* SetFlag(saw_unbuffered_flag); */
2498 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002499 SetFlag(config->bytes_warning);
2500 SetFlag(config->quiet);
2501 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002502 SetFlag(config->isolated);
2503 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2504 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002505#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002507 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002508 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 return NULL;
2510 }
2511 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002512}
2513
Eric Smith0e5b5622009-02-06 01:32:42 +00002514PyDoc_STRVAR(version_info__doc__,
2515"sys.version_info\n\
2516\n\
2517Version information as a named tuple.");
2518
2519static PyTypeObject VersionInfoType;
2520
2521static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 {"major", "Major release number"},
2523 {"minor", "Minor release number"},
2524 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002525 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 {"serial", "Serial release number"},
2527 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002528};
2529
2530static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 "sys.version_info", /* name */
2532 version_info__doc__, /* doc */
2533 version_info_fields, /* fields */
2534 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002535};
2536
2537static PyObject *
2538make_version_info(void)
2539{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002540 PyObject *version_info;
2541 char *s;
2542 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002544 version_info = PyStructSequence_New(&VersionInfoType);
2545 if (version_info == NULL) {
2546 return NULL;
2547 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002549 /*
2550 * These release level checks are mutually exclusive and cover
2551 * the field, so don't get too fancy with the pre-processor!
2552 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002553#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002555#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002556 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002557#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002559#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002561#endif
2562
2563#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002565#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 SetIntItem(PY_MAJOR_VERSION);
2569 SetIntItem(PY_MINOR_VERSION);
2570 SetIntItem(PY_MICRO_VERSION);
2571 SetStrItem(s);
2572 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002573#undef SetIntItem
2574#undef SetStrItem
2575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002576 if (PyErr_Occurred()) {
2577 Py_CLEAR(version_info);
2578 return NULL;
2579 }
2580 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002581}
2582
Brett Cannon3adc7b72012-07-09 14:22:12 -04002583/* sys.implementation values */
2584#define NAME "cpython"
2585const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002586#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2587#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002588#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002589const char *_PySys_ImplCacheTag = TAG;
2590#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002591#undef MAJOR
2592#undef MINOR
2593#undef TAG
2594
Barry Warsaw409da152012-06-03 16:18:47 -04002595static PyObject *
2596make_impl_info(PyObject *version_info)
2597{
2598 int res;
2599 PyObject *impl_info, *value, *ns;
2600
2601 impl_info = PyDict_New();
2602 if (impl_info == NULL)
2603 return NULL;
2604
2605 /* populate the dict */
2606
Brett Cannon3adc7b72012-07-09 14:22:12 -04002607 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002608 if (value == NULL)
2609 goto error;
2610 res = PyDict_SetItemString(impl_info, "name", value);
2611 Py_DECREF(value);
2612 if (res < 0)
2613 goto error;
2614
Brett Cannon3adc7b72012-07-09 14:22:12 -04002615 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002616 if (value == NULL)
2617 goto error;
2618 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2619 Py_DECREF(value);
2620 if (res < 0)
2621 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002622
2623 res = PyDict_SetItemString(impl_info, "version", version_info);
2624 if (res < 0)
2625 goto error;
2626
2627 value = PyLong_FromLong(PY_VERSION_HEX);
2628 if (value == NULL)
2629 goto error;
2630 res = PyDict_SetItemString(impl_info, "hexversion", value);
2631 Py_DECREF(value);
2632 if (res < 0)
2633 goto error;
2634
doko@ubuntu.com55532312016-06-14 08:55:19 +02002635#ifdef MULTIARCH
2636 value = PyUnicode_FromString(MULTIARCH);
2637 if (value == NULL)
2638 goto error;
2639 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2640 Py_DECREF(value);
2641 if (res < 0)
2642 goto error;
2643#endif
2644
Barry Warsaw409da152012-06-03 16:18:47 -04002645 /* dict ready */
2646
2647 ns = _PyNamespace_New(impl_info);
2648 Py_DECREF(impl_info);
2649 return ns;
2650
2651error:
2652 Py_CLEAR(impl_info);
2653 return NULL;
2654}
2655
Martin v. Löwis1a214512008-06-11 05:26:20 +00002656static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 PyModuleDef_HEAD_INIT,
2658 "sys",
2659 sys_doc,
2660 -1, /* multiple "initialization" just copies the module dict. */
2661 sys_methods,
2662 NULL,
2663 NULL,
2664 NULL,
2665 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002666};
2667
Eric Snow6b4be192017-05-22 21:36:03 -07002668/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002669#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002670 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002671 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002672 if (v == NULL) { \
2673 goto err_occurred; \
2674 } \
Victor Stinner58049602013-07-22 22:40:00 +02002675 res = PyDict_SetItemString(sysdict, key, v); \
2676 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002677 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002678 } \
2679 } while (0)
2680#define SET_SYS_FROM_STRING(key, value) \
2681 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002682 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002683 if (v == NULL) { \
2684 goto err_occurred; \
2685 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002686 res = PyDict_SetItemString(sysdict, key, v); \
2687 Py_DECREF(v); \
2688 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002689 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002690 } \
2691 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002692
Victor Stinnerab672812019-01-23 15:04:40 +01002693static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02002694_PySys_InitCore(_PyRuntimeState *runtime, PyInterpreterState *interp,
2695 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002696{
Victor Stinnerab672812019-01-23 15:04:40 +01002697 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002698 int res;
2699
Nick Coghland6009512014-11-20 21:39:37 +10002700 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002701
Victor Stinner8fea2522013-10-27 17:15:42 +01002702 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2703 PyDict_GetItemString(sysdict, "displayhook"));
2704 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2705 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002706 SET_SYS_FROM_STRING_BORROW(
2707 "__breakpointhook__",
2708 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002709 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2710 PyDict_GetItemString(sysdict, "unraisablehook"));
2711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 SET_SYS_FROM_STRING("version",
2713 PyUnicode_FromString(Py_GetVersion()));
2714 SET_SYS_FROM_STRING("hexversion",
2715 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002716 SET_SYS_FROM_STRING("_git",
2717 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2718 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002719 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 SET_SYS_FROM_STRING("api_version",
2721 PyLong_FromLong(PYTHON_API_VERSION));
2722 SET_SYS_FROM_STRING("copyright",
2723 PyUnicode_FromString(Py_GetCopyright()));
2724 SET_SYS_FROM_STRING("platform",
2725 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 SET_SYS_FROM_STRING("maxsize",
2727 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2728 SET_SYS_FROM_STRING("float_info",
2729 PyFloat_GetInfo());
2730 SET_SYS_FROM_STRING("int_info",
2731 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002732 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002733 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002734 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2735 goto type_init_failed;
2736 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002737 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002738 SET_SYS_FROM_STRING("hash_info",
2739 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002741 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 SET_SYS_FROM_STRING("builtin_module_names",
2743 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002744#if PY_BIG_ENDIAN
2745 SET_SYS_FROM_STRING("byteorder",
2746 PyUnicode_FromString("big"));
2747#else
2748 SET_SYS_FROM_STRING("byteorder",
2749 PyUnicode_FromString("little"));
2750#endif
Fred Drake099325e2000-08-14 15:47:03 +00002751
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002752#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 SET_SYS_FROM_STRING("dllhandle",
2754 PyLong_FromVoidPtr(PyWin_DLLhModule));
2755 SET_SYS_FROM_STRING("winver",
2756 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002757#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002758#ifdef ABIFLAGS
2759 SET_SYS_FROM_STRING("abiflags",
2760 PyUnicode_FromString(ABIFLAGS));
2761#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002764 if (VersionInfoType.tp_name == NULL) {
2765 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002766 &version_info_desc) < 0) {
2767 goto type_init_failed;
2768 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002769 }
Barry Warsaw409da152012-06-03 16:18:47 -04002770 version_info = make_version_info();
2771 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 /* prevent user from creating new instances */
2773 VersionInfoType.tp_init = NULL;
2774 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002775 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2776 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2777 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002778
Barry Warsaw409da152012-06-03 16:18:47 -04002779 /* implementation */
2780 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002783 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002784 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2785 goto type_init_failed;
2786 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002787 }
Victor Stinner43125222019-04-24 18:23:53 +02002788 /* Set flags to their default values (updated by _PySys_InitMain()) */
2789 SET_SYS_FROM_STRING("flags", make_flags(runtime, interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002790
2791#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 /* getwindowsversion */
2793 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002794 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002795 &windows_version_desc) < 0) {
2796 goto type_init_failed;
2797 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 /* prevent user from creating new instances */
2799 WindowsVersionType.tp_init = NULL;
2800 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002801 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002802 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002803 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002804 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002805 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002806#endif
2807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002808 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002809#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 SET_SYS_FROM_STRING("float_repr_style",
2811 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002812#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002813 SET_SYS_FROM_STRING("float_repr_style",
2814 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002815#endif
2816
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002817 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002818
Yury Selivanoveb636452016-09-08 22:01:51 -07002819 /* initialize asyncgen_hooks */
2820 if (AsyncGenHooksType.tp_name == NULL) {
2821 if (PyStructSequence_InitType2(
2822 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002823 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002824 }
2825 }
2826
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002827 if (PyErr_Occurred()) {
2828 goto err_occurred;
2829 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002830 return _Py_INIT_OK();
2831
2832type_init_failed:
2833 return _Py_INIT_ERR("failed to initialize a type");
2834
2835err_occurred:
2836 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002837}
2838
Eric Snow6b4be192017-05-22 21:36:03 -07002839#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002840
2841/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002842#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2843 do { \
2844 PyObject *v = (value); \
2845 if (v == NULL) \
2846 return -1; \
2847 res = PyDict_SetItemString(sysdict, key, v); \
2848 Py_DECREF(v); \
2849 if (res < 0) { \
2850 return res; \
2851 } \
2852 } while (0)
2853
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002854
2855static int
2856sys_add_xoption(PyObject *opts, const wchar_t *s)
2857{
2858 PyObject *name, *value;
2859
2860 const wchar_t *name_end = wcschr(s, L'=');
2861 if (!name_end) {
2862 name = PyUnicode_FromWideChar(s, -1);
2863 value = Py_True;
2864 Py_INCREF(value);
2865 }
2866 else {
2867 name = PyUnicode_FromWideChar(s, name_end - s);
2868 value = PyUnicode_FromWideChar(name_end + 1, -1);
2869 }
2870 if (name == NULL || value == NULL) {
2871 goto error;
2872 }
2873 if (PyDict_SetItem(opts, name, value) < 0) {
2874 goto error;
2875 }
2876 Py_DECREF(name);
2877 Py_DECREF(value);
2878 return 0;
2879
2880error:
2881 Py_XDECREF(name);
2882 Py_XDECREF(value);
2883 return -1;
2884}
2885
2886
2887static PyObject*
2888sys_create_xoptions_dict(const _PyCoreConfig *config)
2889{
2890 Py_ssize_t nxoption = config->xoptions.length;
2891 wchar_t * const * xoptions = config->xoptions.items;
2892 PyObject *dict = PyDict_New();
2893 if (dict == NULL) {
2894 return NULL;
2895 }
2896
2897 for (Py_ssize_t i=0; i < nxoption; i++) {
2898 const wchar_t *option = xoptions[i];
2899 if (sys_add_xoption(dict, option) < 0) {
2900 Py_DECREF(dict);
2901 return NULL;
2902 }
2903 }
2904
2905 return dict;
2906}
2907
2908
Eric Snow6b4be192017-05-22 21:36:03 -07002909int
Victor Stinner43125222019-04-24 18:23:53 +02002910_PySys_InitMain(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002911{
Victor Stinnerab672812019-01-23 15:04:40 +01002912 PyObject *sysdict = interp->sysdict;
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002913 const _PyCoreConfig *config = &interp->core_config;
Eric Snow6b4be192017-05-22 21:36:03 -07002914 int res;
2915
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002916#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002917 do { \
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002918 PyObject *list = _PyWstrList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002919 if (list == NULL) { \
2920 return -1; \
2921 } \
2922 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2923 Py_DECREF(list); \
2924 } while (0)
2925
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002926#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2927 do { \
2928 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2929 if (str == NULL) { \
2930 return -1; \
2931 } \
2932 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2933 Py_DECREF(str); \
2934 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002935
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002936 COPY_LIST("path", config->module_search_paths);
2937
2938 SET_SYS_FROM_WSTR("executable", config->executable);
2939 SET_SYS_FROM_WSTR("prefix", config->prefix);
2940 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2941 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2942 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002943
Carl Meyerb193fa92018-06-15 22:40:56 -06002944 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002945 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002946 } else {
2947 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2948 }
2949
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002950 COPY_LIST("argv", config->argv);
2951 COPY_LIST("warnoptions", config->warnoptions);
2952
2953 PyObject *xoptions = sys_create_xoptions_dict(config);
2954 if (xoptions == NULL) {
2955 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002956 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002957 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002958 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002959
Victor Stinner37cd9822018-11-16 11:55:35 +01002960#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002961#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002962
Eric Snow6b4be192017-05-22 21:36:03 -07002963 /* Set flags to their final values */
Victor Stinner43125222019-04-24 18:23:53 +02002964 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002965 /* prevent user from creating new instances */
2966 FlagsType.tp_init = NULL;
2967 FlagsType.tp_new = NULL;
2968 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2969 if (res < 0) {
2970 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2971 return res;
2972 }
2973 PyErr_Clear();
2974 }
2975
2976 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002977 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002978
Eric Snowdae02762017-09-14 00:35:58 -07002979 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002980 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002981
Eric Snowdae02762017-09-14 00:35:58 -07002982 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002983 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002984
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002985 /* Transfer any sys.warnoptions and sys._xoptions set directly
2986 * by an embedding application from the linked list to the module. */
2987 if (_PySys_ReadPreInitOptions() != 0)
2988 return -1;
2989
Eric Snow6b4be192017-05-22 21:36:03 -07002990 if (PyErr_Occurred())
2991 return -1;
2992 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002993
2994err_occurred:
2995 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002996}
2997
Victor Stinner41264f12017-12-15 02:05:29 +01002998#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002999#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07003000
Victor Stinnerab672812019-01-23 15:04:40 +01003001
3002/* Set up a preliminary stderr printer until we have enough
3003 infrastructure for the io module in place.
3004
3005 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
3006_PyInitError
3007_PySys_SetPreliminaryStderr(PyObject *sysdict)
3008{
3009 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3010 if (pstderr == NULL) {
3011 goto error;
3012 }
3013 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3014 goto error;
3015 }
3016 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3017 goto error;
3018 }
3019 Py_DECREF(pstderr);
3020 return _Py_INIT_OK();
3021
3022error:
3023 Py_XDECREF(pstderr);
3024 return _Py_INIT_ERR("can't set preliminary stderr");
3025}
3026
3027
3028/* Create sys module without all attributes: _PySys_InitMain() should be called
3029 later to add remaining attributes. */
3030_PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02003031_PySys_Create(_PyRuntimeState *runtime, PyInterpreterState *interp,
3032 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003033{
3034 PyObject *modules = PyDict_New();
3035 if (modules == NULL) {
3036 return _Py_INIT_ERR("can't make modules dictionary");
3037 }
3038 interp->modules = modules;
3039
3040 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3041 if (sysmod == NULL) {
3042 return _Py_INIT_ERR("failed to create a module object");
3043 }
3044
3045 PyObject *sysdict = PyModule_GetDict(sysmod);
3046 if (sysdict == NULL) {
3047 return _Py_INIT_ERR("can't initialize sys dict");
3048 }
3049 Py_INCREF(sysdict);
3050 interp->sysdict = sysdict;
3051
3052 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
3053 return _Py_INIT_ERR("can't initialize sys module");
3054 }
3055
3056 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
3057 if (_Py_INIT_FAILED(err)) {
3058 return err;
3059 }
3060
Victor Stinner43125222019-04-24 18:23:53 +02003061 err = _PySys_InitCore(runtime, interp, sysdict);
Victor Stinnerab672812019-01-23 15:04:40 +01003062 if (_Py_INIT_FAILED(err)) {
3063 return err;
3064 }
3065
3066 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3067
3068 *sysmod_p = sysmod;
3069 return _Py_INIT_OK();
3070}
3071
3072
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003073static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003074makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003076 int i, n;
3077 const wchar_t *p;
3078 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003080 n = 1;
3081 p = path;
3082 while ((p = wcschr(p, delim)) != NULL) {
3083 n++;
3084 p++;
3085 }
3086 v = PyList_New(n);
3087 if (v == NULL)
3088 return NULL;
3089 for (i = 0; ; i++) {
3090 p = wcschr(path, delim);
3091 if (p == NULL)
3092 p = path + wcslen(path); /* End of string */
3093 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3094 if (w == NULL) {
3095 Py_DECREF(v);
3096 return NULL;
3097 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003098 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003099 if (*p == '\0')
3100 break;
3101 path = p+1;
3102 }
3103 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003104}
3105
3106void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003107PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003108{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003109 PyObject *v;
3110 if ((v = makepathobject(path, DELIM)) == NULL)
3111 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01003112 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003113 Py_FatalError("can't assign sys.path");
3114 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003115}
3116
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003117static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003118make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003119{
Victor Stinner74f65682019-03-15 15:08:05 +01003120 PyObject *list = PyList_New(argc);
3121 if (list == NULL) {
3122 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003123 }
Victor Stinner74f65682019-03-15 15:08:05 +01003124
3125 for (Py_ssize_t i = 0; i < argc; i++) {
3126 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3127 if (v == NULL) {
3128 Py_DECREF(list);
3129 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003130 }
Victor Stinner74f65682019-03-15 15:08:05 +01003131 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003132 }
Victor Stinner74f65682019-03-15 15:08:05 +01003133 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003134}
3135
Victor Stinner11a247d2017-12-13 21:05:57 +01003136void
3137PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003138{
Victor Stinner74f65682019-03-15 15:08:05 +01003139 if (argc < 1 || argv == NULL) {
3140 /* Ensure at least one (empty) argument is seen */
3141 wchar_t* empty_argv[1] = {L""};
3142 argv = empty_argv;
3143 argc = 1;
3144 }
3145
3146 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003147 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003148 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003149 }
3150 if (PySys_SetObject("argv", av) != 0) {
3151 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003152 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003153 }
3154 Py_DECREF(av);
3155
3156 if (updatepath) {
3157 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3158 If argv[0] is a symlink, use the real path. */
Victor Stinner74f65682019-03-15 15:08:05 +01003159 const _PyWstrList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003160 PyObject *path0 = NULL;
3161 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3162 if (path0 == NULL) {
3163 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003164 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003165
3166 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
3167 if (sys_path != NULL) {
3168 if (PyList_Insert(sys_path, 0, path0) < 0) {
3169 Py_DECREF(path0);
3170 Py_FatalError("can't prepend path0 to sys.path");
3171 }
3172 }
3173 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003174 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003175 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003176}
Guido van Rossuma890e681998-05-12 14:59:24 +00003177
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003178void
3179PySys_SetArgv(int argc, wchar_t **argv)
3180{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003181 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003182}
3183
Victor Stinner14284c22010-04-23 12:02:30 +00003184/* Reimplementation of PyFile_WriteString() no calling indirectly
3185 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3186
3187static int
Victor Stinner79766632010-08-16 17:36:42 +00003188sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003189{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003190 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003191 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003192
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003193 if (file == NULL)
3194 return -1;
3195
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003196 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003197 if (writer == NULL)
3198 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003199
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003200 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003201 if (result == NULL) {
3202 goto error;
3203 } else {
3204 err = 0;
3205 goto finally;
3206 }
Victor Stinner14284c22010-04-23 12:02:30 +00003207
3208error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003209 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003210finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003212 Py_XDECREF(result);
3213 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003214}
3215
Victor Stinner79766632010-08-16 17:36:42 +00003216static int
3217sys_pyfile_write(const char *text, PyObject *file)
3218{
3219 PyObject *unicode = NULL;
3220 int err;
3221
3222 if (file == NULL)
3223 return -1;
3224
3225 unicode = PyUnicode_FromString(text);
3226 if (unicode == NULL)
3227 return -1;
3228
3229 err = sys_pyfile_write_unicode(unicode, file);
3230 Py_DECREF(unicode);
3231 return err;
3232}
Guido van Rossuma890e681998-05-12 14:59:24 +00003233
3234/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3235 Adapted from code submitted by Just van Rossum.
3236
3237 PySys_WriteStdout(format, ...)
3238 PySys_WriteStderr(format, ...)
3239
3240 The first function writes to sys.stdout; the second to sys.stderr. When
3241 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003242 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003243
Victor Stinner14284c22010-04-23 12:02:30 +00003244 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003245 signal handlers: they may raise a new exception whereas sys_write()
3246 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003247
Guido van Rossuma890e681998-05-12 14:59:24 +00003248 Both take a printf-style format string as their first argument followed
3249 by a variable length argument list determined by the format string.
3250
3251 *** WARNING ***
3252
3253 The format should limit the total size of the formatted output string to
3254 1000 bytes. In particular, this means that no unrestricted "%s" formats
3255 should occur; these should be limited using "%.<N>s where <N> is a
3256 decimal number calculated so that <N> plus the maximum size of other
3257 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3258 which can print hundreds of digits for very large numbers.
3259
3260 */
3261
3262static void
Victor Stinner09054372013-11-06 22:41:44 +01003263sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003265 PyObject *file;
3266 PyObject *error_type, *error_value, *error_traceback;
3267 char buffer[1001];
3268 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00003269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003270 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003271 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003272 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3273 if (sys_pyfile_write(buffer, file) != 0) {
3274 PyErr_Clear();
3275 fputs(buffer, fp);
3276 }
3277 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3278 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003279 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003281 }
3282 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003283}
3284
3285void
Guido van Rossuma890e681998-05-12 14:59:24 +00003286PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003287{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003288 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003290 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003291 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003292 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003293}
3294
3295void
Guido van Rossuma890e681998-05-12 14:59:24 +00003296PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003298 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003300 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003301 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003302 va_end(va);
3303}
3304
3305static void
Victor Stinner09054372013-11-06 22:41:44 +01003306sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003307{
3308 PyObject *file, *message;
3309 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003310 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00003311
3312 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003313 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00003314 message = PyUnicode_FromFormatV(format, va);
3315 if (message != NULL) {
3316 if (sys_pyfile_write_unicode(message, file) != 0) {
3317 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02003318 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003319 if (utf8 != NULL)
3320 fputs(utf8, fp);
3321 }
3322 Py_DECREF(message);
3323 }
3324 PyErr_Restore(error_type, error_value, error_traceback);
3325}
3326
3327void
3328PySys_FormatStdout(const char *format, ...)
3329{
3330 va_list va;
3331
3332 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003333 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003334 va_end(va);
3335}
3336
3337void
3338PySys_FormatStderr(const char *format, ...)
3339{
3340 va_list va;
3341
3342 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003343 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003344 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003345}