blob: 5ebeacf0b7f39936a7a6cce3c484a26425eb2ab1 [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.
692* exc_value: Exception value.
693* exc_tb: Exception traceback, can be None.
694* obj: Object causing the exception, can be None.
695[clinic start generated code]*/
696
697static PyObject *
698sys_unraisablehook(PyObject *module, PyObject *unraisable)
699/*[clinic end generated code: output=bb92838b32abaa14 input=fdbdb47fdd0bee06]*/
700{
701 return _PyErr_WriteUnraisableDefaultHook(unraisable);
702}
703
704
705/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200706sys.exit
707
708 status: object = NULL
709 /
710
711Exit the interpreter by raising SystemExit(status).
712
713If the status is omitted or None, it defaults to zero (i.e., success).
714If the status is an integer, it will be used as the system exit status.
715If it is another kind of object, it will be printed and the system
716exit status will be one (i.e., failure).
717[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000718
719static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200720sys_exit_impl(PyObject *module, PyObject *status)
721/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200724 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000725 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000726}
727
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000728
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000729
Tal Einatede0b6f2018-12-31 17:12:08 +0200730/*[clinic input]
731sys.getdefaultencoding
732
733Return the current default encoding used by the Unicode implementation.
734[clinic start generated code]*/
735
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000736static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200737sys_getdefaultencoding_impl(PyObject *module)
738/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000739{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000741}
742
Tal Einatede0b6f2018-12-31 17:12:08 +0200743/*[clinic input]
744sys.getfilesystemencoding
745
746Return the encoding used to convert Unicode filenames to OS filenames.
747[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000748
749static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200750sys_getfilesystemencoding_impl(PyObject *module)
751/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000752{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200753 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
754 const _PyCoreConfig *config = &interp->core_config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400755 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000756}
757
Tal Einatede0b6f2018-12-31 17:12:08 +0200758/*[clinic input]
759sys.getfilesystemencodeerrors
760
761Return the error mode used Unicode to OS filename conversion.
762[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000763
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000764static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200765sys_getfilesystemencodeerrors_impl(PyObject *module)
766/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700767{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200768 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
769 const _PyCoreConfig *config = &interp->core_config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400770 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700771}
772
Tal Einatede0b6f2018-12-31 17:12:08 +0200773/*[clinic input]
774sys.intern
775
776 string as s: unicode
777 /
778
779``Intern'' the given string.
780
781This enters the string in the (global) table of interned strings whose
782purpose is to speed up dictionary lookups. Return the string itself or
783the previously interned string object with the same value.
784[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700785
786static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200787sys_intern_impl(PyObject *module, PyObject *s)
788/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 if (PyUnicode_CheckExact(s)) {
791 Py_INCREF(s);
792 PyUnicode_InternInPlace(&s);
793 return s;
794 }
795 else {
796 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200797 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return NULL;
799 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000800}
801
Georg Brandl66a796e2006-12-19 20:50:34 +0000802
Fred Drake5755ce62001-06-27 19:19:46 +0000803/*
804 * Cached interned string objects used for calling the profile and
805 * trace functions. Initialized by trace_init().
806 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000807static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000808
809static int
810trace_init(void)
811{
Nick Coghlan5a851672017-09-08 10:14:16 +1000812 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200813 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000814 "c_call", "c_exception", "c_return",
815 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200816 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000817 PyObject *name;
818 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000819 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000820 if (whatstrings[i] == NULL) {
821 name = PyUnicode_InternFromString(whatnames[i]);
822 if (name == NULL)
823 return -1;
824 whatstrings[i] = name;
825 }
826 }
827 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000828}
829
830
831static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100832call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000834{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000835 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200836 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000837
Victor Stinner78da82b2016-08-20 01:22:57 +0200838 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200840 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100841
Victor Stinner78da82b2016-08-20 01:22:57 +0200842 stack[0] = (PyObject *)frame;
843 stack[1] = whatstrings[what];
844 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200847 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000848
Victor Stinner78da82b2016-08-20 01:22:57 +0200849 PyFrame_LocalsToFast(frame, 1);
850 if (result == NULL) {
851 PyTraceBack_Here(frame);
852 }
853
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000854 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000855}
856
857static int
858profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000859 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 if (arg == NULL)
864 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100865 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000866 if (result == NULL) {
867 PyEval_SetProfile(NULL, NULL);
868 return -1;
869 }
870 Py_DECREF(result);
871 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000872}
873
874static int
875trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 PyObject *callback;
879 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000880
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 if (what == PyTrace_CALL)
882 callback = self;
883 else
884 callback = frame->f_trace;
885 if (callback == NULL)
886 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100887 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000888 if (result == NULL) {
889 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200890 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 return -1;
892 }
893 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300894 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000895 }
896 else {
897 Py_DECREF(result);
898 }
899 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000900}
Fred Draked0838392001-06-16 21:02:31 +0000901
Fred Drake8b4d01d2000-05-09 19:57:01 +0000902static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000903sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000904{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 if (trace_init() == -1)
906 return NULL;
907 if (args == Py_None)
908 PyEval_SetTrace(NULL, NULL);
909 else
910 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200911 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000912}
913
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000914PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000915"settrace(function)\n\
916\n\
917Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000918function call. See the debugger chapter in the library manual."
919);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000920
Tal Einatede0b6f2018-12-31 17:12:08 +0200921/*[clinic input]
922sys.gettrace
923
924Return the global debug tracing function set with sys.settrace.
925
926See the debugger chapter in the library manual.
927[clinic start generated code]*/
928
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000929static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200930sys_gettrace_impl(PyObject *module)
931/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000932{
Victor Stinner50b48572018-11-01 01:51:40 +0100933 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 if (temp == NULL)
937 temp = Py_None;
938 Py_INCREF(temp);
939 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000940}
941
Christian Heimes9bd667a2008-01-20 15:14:11 +0000942static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000943sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 if (trace_init() == -1)
946 return NULL;
947 if (args == Py_None)
948 PyEval_SetProfile(NULL, NULL);
949 else
950 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200951 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000952}
953
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000954PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000955"setprofile(function)\n\
956\n\
957Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000958and return. See the profiler chapter in the library manual."
959);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000960
Tal Einatede0b6f2018-12-31 17:12:08 +0200961/*[clinic input]
962sys.getprofile
963
964Return the profiling function set with sys.setprofile.
965
966See the profiler chapter in the library manual.
967[clinic start generated code]*/
968
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000969static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200970sys_getprofile_impl(PyObject *module)
971/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000972{
Victor Stinner50b48572018-11-01 01:51:40 +0100973 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (temp == NULL)
977 temp = Py_None;
978 Py_INCREF(temp);
979 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000980}
981
Tal Einatede0b6f2018-12-31 17:12:08 +0200982/*[clinic input]
983sys.setcheckinterval
984
985 n: int
986 /
987
988Set the async event check interval to n instructions.
989
990This tells the Python interpreter to check for asynchronous events
991every n instructions.
992
993This also affects how often thread switches occur.
994[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000995
996static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200997sys_setcheckinterval_impl(PyObject *module, int n)
998/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1001 "sys.getcheckinterval() and sys.setcheckinterval() "
1002 "are deprecated. Use sys.setswitchinterval() "
1003 "instead.", 1) < 0)
1004 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001005
Victor Stinnercaba55b2018-08-03 15:33:52 +02001006 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +02001007 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001008 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +00001009}
1010
Tal Einatede0b6f2018-12-31 17:12:08 +02001011/*[clinic input]
1012sys.getcheckinterval
1013
1014Return the current check interval; see sys.setcheckinterval().
1015[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001016
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001017static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001018sys_getcheckinterval_impl(PyObject *module)
1019/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1022 "sys.getcheckinterval() and sys.setcheckinterval() "
1023 "are deprecated. Use sys.getswitchinterval() "
1024 "instead.", 1) < 0)
1025 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001026 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001027 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +00001028}
1029
Tal Einatede0b6f2018-12-31 17:12:08 +02001030/*[clinic input]
1031sys.setswitchinterval
1032
1033 interval: double
1034 /
1035
1036Set the ideal thread switching delay inside the Python interpreter.
1037
1038The actual frequency of switching threads can be lower if the
1039interpreter executes long sequences of uninterruptible code
1040(this is implementation-specific and workload-dependent).
1041
1042The parameter must represent the desired switching delay in seconds
1043A typical value is 0.005 (5 milliseconds).
1044[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +00001045
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001046static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001047sys_setswitchinterval_impl(PyObject *module, double interval)
1048/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001049{
Tal Einatede0b6f2018-12-31 17:12:08 +02001050 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 PyErr_SetString(PyExc_ValueError,
1052 "switch interval must be strictly positive");
1053 return NULL;
1054 }
Tal Einatede0b6f2018-12-31 17:12:08 +02001055 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001056 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001057}
1058
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001059
Tal Einatede0b6f2018-12-31 17:12:08 +02001060/*[clinic input]
1061sys.getswitchinterval -> double
1062
1063Return the current thread switch interval; see sys.setswitchinterval().
1064[clinic start generated code]*/
1065
1066static double
1067sys_getswitchinterval_impl(PyObject *module)
1068/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001069{
Tal Einatede0b6f2018-12-31 17:12:08 +02001070 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001071}
1072
Tal Einatede0b6f2018-12-31 17:12:08 +02001073/*[clinic input]
1074sys.setrecursionlimit
1075
1076 limit as new_limit: int
1077 /
1078
1079Set the maximum depth of the Python interpreter stack to n.
1080
1081This limit prevents infinite recursion from causing an overflow of the C
1082stack and crashing Python. The highest possible limit is platform-
1083dependent.
1084[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001085
Tim Peterse5e065b2003-07-06 18:36:54 +00001086static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001087sys_setrecursionlimit_impl(PyObject *module, int new_limit)
1088/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001089{
Tal Einatede0b6f2018-12-31 17:12:08 +02001090 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +02001091 PyThreadState *tstate;
1092
Victor Stinner50856d52015-10-13 00:11:21 +02001093 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +02001095 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 return NULL;
1097 }
Victor Stinner50856d52015-10-13 00:11:21 +02001098
1099 /* Issue #25274: When the recursion depth hits the recursion limit in
1100 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
1101 set to 1 and a RecursionError is raised. The overflowed flag is reset
1102 to 0 when the recursion depth goes below the low-water mark: see
1103 Py_LeaveRecursiveCall().
1104
1105 Reject too low new limit if the current recursion depth is higher than
1106 the new low-water mark. Otherwise it may not be possible anymore to
1107 reset the overflowed flag to 0. */
1108 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +01001109 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +02001110 if (tstate->recursion_depth >= mark) {
1111 PyErr_Format(PyExc_RecursionError,
1112 "cannot set the recursion limit to %i at "
1113 "the recursion depth %i: the limit is too low",
1114 new_limit, tstate->recursion_depth);
1115 return NULL;
1116 }
1117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001119 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001120}
1121
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001122/*[clinic input]
1123sys.set_coroutine_origin_tracking_depth
1124
1125 depth: int
1126
1127Enable or disable origin tracking for coroutine objects in this thread.
1128
Tal Einatede0b6f2018-12-31 17:12:08 +02001129Coroutine objects will track 'depth' frames of traceback information
1130about where they came from, available in their cr_origin attribute.
1131
1132Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001133[clinic start generated code]*/
1134
1135static PyObject *
1136sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +02001137/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001138{
1139 if (depth < 0) {
1140 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
1141 return NULL;
1142 }
1143 _PyEval_SetCoroutineOriginTrackingDepth(depth);
1144 Py_RETURN_NONE;
1145}
1146
1147/*[clinic input]
1148sys.get_coroutine_origin_tracking_depth -> int
1149
1150Check status of origin tracking for coroutine objects in this thread.
1151[clinic start generated code]*/
1152
1153static int
1154sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
1155/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
1156{
1157 return _PyEval_GetCoroutineOriginTrackingDepth();
1158}
1159
Tal Einatede0b6f2018-12-31 17:12:08 +02001160/*[clinic input]
1161sys.set_coroutine_wrapper
1162
1163 wrapper: object
1164 /
1165
1166Set a wrapper for coroutine objects.
1167[clinic start generated code]*/
1168
Yury Selivanov75445082015-05-11 22:57:16 -04001169static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001170sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
1171/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -04001172{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001173 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1174 "set_coroutine_wrapper is deprecated", 1) < 0) {
1175 return NULL;
1176 }
1177
Yury Selivanov75445082015-05-11 22:57:16 -04001178 if (wrapper != Py_None) {
1179 if (!PyCallable_Check(wrapper)) {
1180 PyErr_Format(PyExc_TypeError,
1181 "callable expected, got %.50s",
1182 Py_TYPE(wrapper)->tp_name);
1183 return NULL;
1184 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -04001185 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -04001186 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -04001187 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -04001188 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -04001189 }
Yury Selivanov75445082015-05-11 22:57:16 -04001190 Py_RETURN_NONE;
1191}
1192
Tal Einatede0b6f2018-12-31 17:12:08 +02001193/*[clinic input]
1194sys.get_coroutine_wrapper
1195
1196Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
1197[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -04001198
1199static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001200sys_get_coroutine_wrapper_impl(PyObject *module)
1201/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -04001202{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001203 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1204 "get_coroutine_wrapper is deprecated", 1) < 0) {
1205 return NULL;
1206 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -04001207 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -04001208 if (wrapper == NULL) {
1209 wrapper = Py_None;
1210 }
1211 Py_INCREF(wrapper);
1212 return wrapper;
1213}
1214
Yury Selivanov75445082015-05-11 22:57:16 -04001215
Yury Selivanoveb636452016-09-08 22:01:51 -07001216static PyTypeObject AsyncGenHooksType;
1217
1218PyDoc_STRVAR(asyncgen_hooks_doc,
1219"asyncgen_hooks\n\
1220\n\
1221A struct sequence providing information about asynhronous\n\
1222generators hooks. The attributes are read only.");
1223
1224static PyStructSequence_Field asyncgen_hooks_fields[] = {
1225 {"firstiter", "Hook to intercept first iteration"},
1226 {"finalizer", "Hook to intercept finalization"},
1227 {0}
1228};
1229
1230static PyStructSequence_Desc asyncgen_hooks_desc = {
1231 "asyncgen_hooks", /* name */
1232 asyncgen_hooks_doc, /* doc */
1233 asyncgen_hooks_fields , /* fields */
1234 2
1235};
1236
Yury Selivanoveb636452016-09-08 22:01:51 -07001237static PyObject *
1238sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
1239{
1240 static char *keywords[] = {"firstiter", "finalizer", NULL};
1241 PyObject *firstiter = NULL;
1242 PyObject *finalizer = NULL;
1243
1244 if (!PyArg_ParseTupleAndKeywords(
1245 args, kw, "|OO", keywords,
1246 &firstiter, &finalizer)) {
1247 return NULL;
1248 }
1249
1250 if (finalizer && finalizer != Py_None) {
1251 if (!PyCallable_Check(finalizer)) {
1252 PyErr_Format(PyExc_TypeError,
1253 "callable finalizer expected, got %.50s",
1254 Py_TYPE(finalizer)->tp_name);
1255 return NULL;
1256 }
1257 _PyEval_SetAsyncGenFinalizer(finalizer);
1258 }
1259 else if (finalizer == Py_None) {
1260 _PyEval_SetAsyncGenFinalizer(NULL);
1261 }
1262
1263 if (firstiter && firstiter != Py_None) {
1264 if (!PyCallable_Check(firstiter)) {
1265 PyErr_Format(PyExc_TypeError,
1266 "callable firstiter expected, got %.50s",
1267 Py_TYPE(firstiter)->tp_name);
1268 return NULL;
1269 }
1270 _PyEval_SetAsyncGenFirstiter(firstiter);
1271 }
1272 else if (firstiter == Py_None) {
1273 _PyEval_SetAsyncGenFirstiter(NULL);
1274 }
1275
1276 Py_RETURN_NONE;
1277}
1278
1279PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001280"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -07001281\n\
1282Set a finalizer for async generators objects."
1283);
1284
Tal Einatede0b6f2018-12-31 17:12:08 +02001285/*[clinic input]
1286sys.get_asyncgen_hooks
1287
1288Return the installed asynchronous generators hooks.
1289
1290This returns a namedtuple of the form (firstiter, finalizer).
1291[clinic start generated code]*/
1292
Yury Selivanoveb636452016-09-08 22:01:51 -07001293static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001294sys_get_asyncgen_hooks_impl(PyObject *module)
1295/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -07001296{
1297 PyObject *res;
1298 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
1299 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
1300
1301 res = PyStructSequence_New(&AsyncGenHooksType);
1302 if (res == NULL) {
1303 return NULL;
1304 }
1305
1306 if (firstiter == NULL) {
1307 firstiter = Py_None;
1308 }
1309
1310 if (finalizer == NULL) {
1311 finalizer = Py_None;
1312 }
1313
1314 Py_INCREF(firstiter);
1315 PyStructSequence_SET_ITEM(res, 0, firstiter);
1316
1317 Py_INCREF(finalizer);
1318 PyStructSequence_SET_ITEM(res, 1, finalizer);
1319
1320 return res;
1321}
1322
Yury Selivanoveb636452016-09-08 22:01:51 -07001323
Mark Dickinsondc787d22010-05-23 13:33:13 +00001324static PyTypeObject Hash_InfoType;
1325
1326PyDoc_STRVAR(hash_info_doc,
1327"hash_info\n\
1328\n\
1329A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001330hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001331
1332static PyStructSequence_Field hash_info_fields[] = {
1333 {"width", "width of the type used for hashing, in bits"},
1334 {"modulus", "prime number giving the modulus on which the hash "
1335 "function is based"},
1336 {"inf", "value to be used for hash of a positive infinity"},
1337 {"nan", "value to be used for hash of a nan"},
1338 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001339 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1340 "memoryviews"},
1341 {"hash_bits", "internal output size of hash algorithm"},
1342 {"seed_bits", "seed size of hash algorithm"},
1343 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001344 {NULL, NULL}
1345};
1346
1347static PyStructSequence_Desc hash_info_desc = {
1348 "sys.hash_info",
1349 hash_info_doc,
1350 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001351 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001352};
1353
Matthias Klosed885e952010-07-06 10:53:30 +00001354static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001355get_hash_info(void)
1356{
1357 PyObject *hash_info;
1358 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001359 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001360 hash_info = PyStructSequence_New(&Hash_InfoType);
1361 if (hash_info == NULL)
1362 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001363 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001364 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001365 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001366 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001367 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001368 PyStructSequence_SET_ITEM(hash_info, field++,
1369 PyLong_FromLong(_PyHASH_INF));
1370 PyStructSequence_SET_ITEM(hash_info, field++,
1371 PyLong_FromLong(_PyHASH_NAN));
1372 PyStructSequence_SET_ITEM(hash_info, field++,
1373 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001374 PyStructSequence_SET_ITEM(hash_info, field++,
1375 PyUnicode_FromString(hashfunc->name));
1376 PyStructSequence_SET_ITEM(hash_info, field++,
1377 PyLong_FromLong(hashfunc->hash_bits));
1378 PyStructSequence_SET_ITEM(hash_info, field++,
1379 PyLong_FromLong(hashfunc->seed_bits));
1380 PyStructSequence_SET_ITEM(hash_info, field++,
1381 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001382 if (PyErr_Occurred()) {
1383 Py_CLEAR(hash_info);
1384 return NULL;
1385 }
1386 return hash_info;
1387}
Tal Einatede0b6f2018-12-31 17:12:08 +02001388/*[clinic input]
1389sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001390
Tal Einatede0b6f2018-12-31 17:12:08 +02001391Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001392
Tal Einatede0b6f2018-12-31 17:12:08 +02001393The recursion limit is the maximum depth of the Python interpreter
1394stack. This limit prevents infinite recursion from causing an overflow
1395of the C stack and crashing Python.
1396[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001397
1398static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001399sys_getrecursionlimit_impl(PyObject *module)
1400/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001403}
1404
Mark Hammond8696ebc2002-10-08 02:44:31 +00001405#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001406
Eric Smithf7bb5782010-01-27 00:44:57 +00001407static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1408
1409static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 {"major", "Major version number"},
1411 {"minor", "Minor version number"},
1412 {"build", "Build number"},
1413 {"platform", "Operating system platform"},
1414 {"service_pack", "Latest Service Pack installed on the system"},
1415 {"service_pack_major", "Service Pack major version number"},
1416 {"service_pack_minor", "Service Pack minor version number"},
1417 {"suite_mask", "Bit mask identifying available product suites"},
1418 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001419 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001421};
1422
1423static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001424 "sys.getwindowsversion", /* name */
1425 sys_getwindowsversion__doc__, /* doc */
1426 windows_version_fields, /* fields */
1427 5 /* For backward compatibility,
1428 only the first 5 items are accessible
1429 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001430};
1431
Steve Dower3e96f322015-03-02 08:01:10 -08001432/* Disable deprecation warnings about GetVersionEx as the result is
1433 being passed straight through to the caller, who is responsible for
1434 using it correctly. */
1435#pragma warning(push)
1436#pragma warning(disable:4996)
1437
Tal Einatede0b6f2018-12-31 17:12:08 +02001438/*[clinic input]
1439sys.getwindowsversion
1440
1441Return info about the running version of Windows as a named tuple.
1442
1443The members are named: major, minor, build, platform, service_pack,
1444service_pack_major, service_pack_minor, suite_mask, product_type and
1445platform_version. For backward compatibility, only the first 5 items
1446are available by indexing. All elements are numbers, except
1447service_pack and platform_type which are strings, and platform_version
1448which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1449workstation, 2 for a domain controller, 3 for a server.
1450Platform_version is a 3-tuple containing a version number that is
1451intended for identifying the OS rather than feature detection.
1452[clinic start generated code]*/
1453
Mark Hammond8696ebc2002-10-08 02:44:31 +00001454static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001455sys_getwindowsversion_impl(PyObject *module)
1456/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 PyObject *version;
1459 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001460 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001461 DWORD realMajor, realMinor, realBuild;
1462 HANDLE hKernel32;
1463 wchar_t kernel32_path[MAX_PATH];
1464 LPVOID verblock;
1465 DWORD verblock_size;
1466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001468 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 version = PyStructSequence_New(&WindowsVersionType);
1472 if (version == NULL)
1473 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1476 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1477 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1478 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001479 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001480 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1481 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1482 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1483 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001484
Steve Dower74f4af72016-09-17 17:27:48 -07001485 realMajor = ver.dwMajorVersion;
1486 realMinor = ver.dwMinorVersion;
1487 realBuild = ver.dwBuildNumber;
1488
1489 // GetVersion will lie if we are running in a compatibility mode.
1490 // We need to read the version info from a system file resource
1491 // to accurately identify the OS version. If we fail for any reason,
1492 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001493 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001494 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001495 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001496 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1497 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1498 (verblock = PyMem_RawMalloc(verblock_size))) {
1499 VS_FIXEDFILEINFO *ffi;
1500 UINT ffi_len;
1501
1502 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1503 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1504 realMajor = HIWORD(ffi->dwProductVersionMS);
1505 realMinor = LOWORD(ffi->dwProductVersionMS);
1506 realBuild = HIWORD(ffi->dwProductVersionLS);
1507 }
1508 PyMem_RawFree(verblock);
1509 }
Segev Finer48fb7662017-06-04 20:52:27 +03001510 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1511 realMajor,
1512 realMinor,
1513 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001514 ));
1515
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001516 if (PyErr_Occurred()) {
1517 Py_DECREF(version);
1518 return NULL;
1519 }
Steve Dower74f4af72016-09-17 17:27:48 -07001520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001522}
1523
Steve Dower3e96f322015-03-02 08:01:10 -08001524#pragma warning(pop)
1525
Tal Einatede0b6f2018-12-31 17:12:08 +02001526/*[clinic input]
1527sys._enablelegacywindowsfsencoding
1528
1529Changes the default filesystem encoding to mbcs:replace.
1530
1531This is done for consistency with earlier versions of Python. See PEP
1532529 for more information.
1533
1534This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1535environment variable before launching Python.
1536[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001537
1538static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001539sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1540/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001541{
Victor Stinner709d23d2019-05-02 14:56:30 -04001542 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001543 return NULL;
1544 }
Steve Dowercc16be82016-09-08 10:35:16 -07001545 Py_RETURN_NONE;
1546}
1547
Mark Hammond8696ebc2002-10-08 02:44:31 +00001548#endif /* MS_WINDOWS */
1549
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001550#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001551
1552/*[clinic input]
1553sys.setdlopenflags
1554
1555 flags as new_val: int
1556 /
1557
1558Set the flags used by the interpreter for dlopen calls.
1559
1560This is used, for example, when the interpreter loads extension
1561modules. Among other things, this will enable a lazy resolving of
1562symbols when importing a module, if called as sys.setdlopenflags(0).
1563To share symbols across extension modules, call as
1564sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1565modules can be found in the os module (RTLD_xxx constants, e.g.
1566os.RTLD_LAZY).
1567[clinic start generated code]*/
1568
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001569static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001570sys_setdlopenflags_impl(PyObject *module, int new_val)
1571/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001572{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001573 PyInterpreterState *interp = _PyInterpreterState_Get();
1574 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001575 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001576}
1577
Tal Einatede0b6f2018-12-31 17:12:08 +02001578
1579/*[clinic input]
1580sys.getdlopenflags
1581
1582Return the current value of the flags that are used for dlopen calls.
1583
1584The flag constants are defined in the os module.
1585[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001586
1587static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001588sys_getdlopenflags_impl(PyObject *module)
1589/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001590{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001591 PyInterpreterState *interp = _PyInterpreterState_Get();
1592 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001593}
1594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001596
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001597#ifdef USE_MALLOPT
1598/* Link with -lmalloc (or -lmpc) on an SGI */
1599#include <malloc.h>
1600
Tal Einatede0b6f2018-12-31 17:12:08 +02001601/*[clinic input]
1602sys.mdebug
1603
1604 flag: int
1605 /
1606[clinic start generated code]*/
1607
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001608static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001609sys_mdebug_impl(PyObject *module, int flag)
1610/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001614 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001615}
1616#endif /* USE_MALLOPT */
1617
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001618size_t
1619_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001620{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001623 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 /* Make sure the type is initialized. float gets initialized late */
1626 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001627 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001628
Benjamin Petersonce798522012-01-22 11:24:29 -05001629 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 if (method == NULL) {
1631 if (!PyErr_Occurred())
1632 PyErr_Format(PyExc_TypeError,
1633 "Type %.100s doesn't define __sizeof__",
1634 Py_TYPE(o)->tp_name);
1635 }
1636 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001637 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 Py_DECREF(method);
1639 }
1640
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001641 if (res == NULL)
1642 return (size_t)-1;
1643
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001644 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001645 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001646 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001647 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001649 if (size < 0) {
1650 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1651 return (size_t)-1;
1652 }
1653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001655 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001656 return ((size_t)size) + sizeof(PyGC_Head);
1657 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001658}
1659
1660static PyObject *
1661sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1662{
1663 static char *kwlist[] = {"object", "default", 0};
1664 size_t size;
1665 PyObject *o, *dflt = NULL;
1666
1667 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1668 kwlist, &o, &dflt))
1669 return NULL;
1670
1671 size = _PySys_GetSizeOf(o);
1672
1673 if (size == (size_t)-1 && PyErr_Occurred()) {
1674 /* Has a default value been given */
1675 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1676 PyErr_Clear();
1677 Py_INCREF(dflt);
1678 return dflt;
1679 }
1680 else
1681 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001683
1684 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001685}
1686
1687PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001688"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001689\n\
1690Return the size of object in bytes.");
1691
Tal Einatede0b6f2018-12-31 17:12:08 +02001692/*[clinic input]
1693sys.getrefcount -> Py_ssize_t
1694
1695 object: object
1696 /
1697
1698Return the reference count of object.
1699
1700The count returned is generally one higher than you might expect,
1701because it includes the (temporary) reference as an argument to
1702getrefcount().
1703[clinic start generated code]*/
1704
1705static Py_ssize_t
1706sys_getrefcount_impl(PyObject *module, PyObject *object)
1707/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001708{
Tal Einatede0b6f2018-12-31 17:12:08 +02001709 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001710}
1711
Tim Peters4be93d02002-07-07 19:59:50 +00001712#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001713/*[clinic input]
1714sys.gettotalrefcount -> Py_ssize_t
1715[clinic start generated code]*/
1716
1717static Py_ssize_t
1718sys_gettotalrefcount_impl(PyObject *module)
1719/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001720{
Tal Einatede0b6f2018-12-31 17:12:08 +02001721 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001722}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001723#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001724
Tal Einatede0b6f2018-12-31 17:12:08 +02001725/*[clinic input]
1726sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001727
Tal Einatede0b6f2018-12-31 17:12:08 +02001728Return the number of memory blocks currently allocated.
1729[clinic start generated code]*/
1730
1731static Py_ssize_t
1732sys_getallocatedblocks_impl(PyObject *module)
1733/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001734{
Tal Einatede0b6f2018-12-31 17:12:08 +02001735 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001736}
1737
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001738#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001739/*[clinic input]
1740sys.getcounts
1741[clinic start generated code]*/
1742
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001743static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001744sys_getcounts_impl(PyObject *module)
1745/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001746{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001747 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001748
Pablo Galindo49c75a82018-10-28 15:02:17 +00001749 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001750}
1751#endif
1752
Tal Einatede0b6f2018-12-31 17:12:08 +02001753/*[clinic input]
1754sys._getframe
1755
1756 depth: int = 0
1757 /
1758
1759Return a frame object from the call stack.
1760
1761If optional integer depth is given, return the frame object that many
1762calls below the top of the stack. If that is deeper than the call
1763stack, ValueError is raised. The default for depth is zero, returning
1764the frame at the top of the call stack.
1765
1766This function should be used for internal and specialized purposes
1767only.
1768[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001769
1770static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001771sys__getframe_impl(PyObject *module, int depth)
1772/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001773{
Victor Stinner50b48572018-11-01 01:51:40 +01001774 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001775
Steve Dowerb82e17e2019-05-23 08:45:22 -07001776 if (PySys_Audit("sys._getframe", "O", f) < 0) {
1777 return NULL;
1778 }
1779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 while (depth > 0 && f != NULL) {
1781 f = f->f_back;
1782 --depth;
1783 }
1784 if (f == NULL) {
1785 PyErr_SetString(PyExc_ValueError,
1786 "call stack is not deep enough");
1787 return NULL;
1788 }
1789 Py_INCREF(f);
1790 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001791}
1792
Tal Einatede0b6f2018-12-31 17:12:08 +02001793/*[clinic input]
1794sys._current_frames
1795
1796Return a dict mapping each thread's thread id to its current stack frame.
1797
1798This function should be used for specialized purposes only.
1799[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001800
1801static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001802sys__current_frames_impl(PyObject *module)
1803/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001806}
1807
Tal Einatede0b6f2018-12-31 17:12:08 +02001808/*[clinic input]
1809sys.call_tracing
1810
1811 func: object
1812 args as funcargs: object(subclass_of='&PyTuple_Type')
1813 /
1814
1815Call func(*args), while tracing is enabled.
1816
1817The tracing state is saved, and restored afterwards. This is intended
1818to be called from a debugger from a checkpoint, to recursively debug
1819some other code.
1820[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001821
1822static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001823sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1824/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001827}
1828
Tal Einatede0b6f2018-12-31 17:12:08 +02001829/*[clinic input]
1830sys.callstats
1831
1832Return a tuple of function call statistics.
1833
1834A tuple is returned only if CALL_PROFILE was defined when Python was
1835built. Otherwise, this returns None.
1836
1837When enabled, this function returns detailed, implementation-specific
1838details about the number of function calls executed. The return value
1839is a 11-tuple where the entries in the tuple are counts of:
18400. all function calls
18411. calls to PyFunction_Type objects
18422. PyFunction calls that do not create an argument tuple
18433. PyFunction calls that do not create an argument tuple
1844 and bypass PyEval_EvalCodeEx()
18454. PyMethod calls
18465. PyMethod calls on bound methods
18476. PyType calls
18487. PyCFunction calls
18498. generator calls
18509. All other calls
185110. Number of stack pops performed by call_function()
1852[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001853
Victor Stinner048afd92016-11-28 11:59:04 +01001854static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001855sys_callstats_impl(PyObject *module)
1856/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001857{
1858 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1859 "sys.callstats() has been deprecated in Python 3.7 "
1860 "and will be removed in the future", 1) < 0) {
1861 return NULL;
1862 }
1863
1864 Py_RETURN_NONE;
1865}
1866
1867
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001868#ifdef __cplusplus
1869extern "C" {
1870#endif
1871
Tal Einatede0b6f2018-12-31 17:12:08 +02001872/*[clinic input]
1873sys._debugmallocstats
1874
1875Print summary info to stderr about the state of pymalloc's structures.
1876
1877In Py_DEBUG mode, also perform some expensive internal consistency
1878checks.
1879[clinic start generated code]*/
1880
David Malcolm49526f42012-06-22 14:55:41 -04001881static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001882sys__debugmallocstats_impl(PyObject *module)
1883/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001884{
1885#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001886 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001887 fputc('\n', stderr);
1888 }
David Malcolm49526f42012-06-22 14:55:41 -04001889#endif
1890 _PyObject_DebugTypeStats(stderr);
1891
1892 Py_RETURN_NONE;
1893}
David Malcolm49526f42012-06-22 14:55:41 -04001894
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001895#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001896/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001897extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001898#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001899
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001900#ifdef DYNAMIC_EXECUTION_PROFILE
1901/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001902extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001903#endif
1904
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001905#ifdef __cplusplus
1906}
1907#endif
1908
Tal Einatede0b6f2018-12-31 17:12:08 +02001909
1910/*[clinic input]
1911sys._clear_type_cache
1912
1913Clear the internal type lookup cache.
1914[clinic start generated code]*/
1915
Christian Heimes15ebc882008-02-04 18:48:49 +00001916static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001917sys__clear_type_cache_impl(PyObject *module)
1918/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyType_ClearCache();
1921 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001922}
1923
Tal Einatede0b6f2018-12-31 17:12:08 +02001924/*[clinic input]
1925sys.is_finalizing
1926
1927Return True if Python is exiting.
1928[clinic start generated code]*/
1929
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001930static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001931sys_is_finalizing_impl(PyObject *module)
1932/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001933{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001934 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001935}
1936
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001937#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001938/*[clinic input]
1939sys.getandroidapilevel
1940
1941Return the build time API version of Android as an integer.
1942[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001943
1944static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001945sys_getandroidapilevel_impl(PyObject *module)
1946/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001947{
1948 return PyLong_FromLong(ANDROID_API_LEVEL);
1949}
1950#endif /* ANDROID_API_LEVEL */
1951
1952
Steve Dowerb82e17e2019-05-23 08:45:22 -07001953
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001954static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 /* Might as well keep this in alphabetic order */
Steve Dowerb82e17e2019-05-23 08:45:22 -07001956 SYS_ADDAUDITHOOK_METHODDEF
1957 {"audit", (PyCFunction)(void(*)(void))sys_audit, METH_FASTCALL, audit_doc },
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001958 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001959 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001960 SYS_CALLSTATS_METHODDEF
1961 SYS__CLEAR_TYPE_CACHE_METHODDEF
1962 SYS__CURRENT_FRAMES_METHODDEF
1963 SYS_DISPLAYHOOK_METHODDEF
1964 SYS_EXC_INFO_METHODDEF
1965 SYS_EXCEPTHOOK_METHODDEF
1966 SYS_EXIT_METHODDEF
1967 SYS_GETDEFAULTENCODING_METHODDEF
1968 SYS_GETDLOPENFLAGS_METHODDEF
1969 SYS_GETALLOCATEDBLOCKS_METHODDEF
1970 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001971#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001973#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001974 SYS_GETFILESYSTEMENCODING_METHODDEF
1975 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001976#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001978#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001979 SYS_GETTOTALREFCOUNT_METHODDEF
1980 SYS_GETREFCOUNT_METHODDEF
1981 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001982 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001984 SYS__GETFRAME_METHODDEF
1985 SYS_GETWINDOWSVERSION_METHODDEF
1986 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1987 SYS_INTERN_METHODDEF
1988 SYS_IS_FINALIZING_METHODDEF
1989 SYS_MDEBUG_METHODDEF
1990 SYS_SETCHECKINTERVAL_METHODDEF
1991 SYS_GETCHECKINTERVAL_METHODDEF
1992 SYS_SETSWITCHINTERVAL_METHODDEF
1993 SYS_GETSWITCHINTERVAL_METHODDEF
1994 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001996 SYS_GETPROFILE_METHODDEF
1997 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001999 SYS_GETTRACE_METHODDEF
2000 SYS_CALL_TRACING_METHODDEF
2001 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08002002 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
2003 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02002004 SYS_SET_COROUTINE_WRAPPER_METHODDEF
2005 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02002006 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07002007 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02002008 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
2009 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02002010 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00002012};
2013
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002014static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00002015list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00002016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 PyObject *list = PyList_New(0);
2018 int i;
2019 if (list == NULL)
2020 return NULL;
2021 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
2022 PyObject *name = PyUnicode_FromString(
2023 PyImport_Inittab[i].name);
2024 if (name == NULL)
2025 break;
2026 PyList_Append(list, name);
2027 Py_DECREF(name);
2028 }
2029 if (PyList_Sort(list) != 0) {
2030 Py_DECREF(list);
2031 list = NULL;
2032 }
2033 if (list) {
2034 PyObject *v = PyList_AsTuple(list);
2035 Py_DECREF(list);
2036 list = v;
2037 }
2038 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00002039}
2040
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002041/* Pre-initialization support for sys.warnoptions and sys._xoptions
2042 *
2043 * Modern internal code paths:
2044 * These APIs get called after _Py_InitializeCore and get to use the
2045 * regular CPython list, dict, and unicode APIs.
2046 *
2047 * Legacy embedding code paths:
2048 * The multi-phase initialization API isn't public yet, so embedding
2049 * apps still need to be able configure sys.warnoptions and sys._xoptions
2050 * before they call Py_Initialize. To support this, we stash copies of
2051 * the supplied wchar * sequences in linked lists, and then migrate the
2052 * contents of those lists to the sys module in _PyInitializeCore.
2053 *
2054 */
2055
2056struct _preinit_entry {
2057 wchar_t *value;
2058 struct _preinit_entry *next;
2059};
2060
2061typedef struct _preinit_entry *_Py_PreInitEntry;
2062
2063static _Py_PreInitEntry _preinit_warnoptions = NULL;
2064static _Py_PreInitEntry _preinit_xoptions = NULL;
2065
2066static _Py_PreInitEntry
2067_alloc_preinit_entry(const wchar_t *value)
2068{
2069 /* To get this to work, we have to initialize the runtime implicitly */
2070 _PyRuntime_Initialize();
2071
2072 /* Force default allocator, so we can ensure that it also gets used to
2073 * destroy the linked list in _clear_preinit_entries.
2074 */
2075 PyMemAllocatorEx old_alloc;
2076 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2077
2078 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
2079 if (node != NULL) {
2080 node->value = _PyMem_RawWcsdup(value);
2081 if (node->value == NULL) {
2082 PyMem_RawFree(node);
2083 node = NULL;
2084 };
2085 };
2086
2087 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2088 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002089}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002090
2091static int
2092_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
2093{
2094 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
2095 if (new_entry == NULL) {
2096 return -1;
2097 }
2098 /* We maintain the linked list in this order so it's easy to play back
2099 * the add commands in the same order later on in _Py_InitializeCore
2100 */
2101 _Py_PreInitEntry last_entry = *optionlist;
2102 if (last_entry == NULL) {
2103 *optionlist = new_entry;
2104 } else {
2105 while (last_entry->next != NULL) {
2106 last_entry = last_entry->next;
2107 }
2108 last_entry->next = new_entry;
2109 }
2110 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002111}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002112
2113static void
2114_clear_preinit_entries(_Py_PreInitEntry *optionlist)
2115{
2116 _Py_PreInitEntry current = *optionlist;
2117 *optionlist = NULL;
2118 /* Deallocate the nodes and their contents using the default allocator */
2119 PyMemAllocatorEx old_alloc;
2120 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
2121 while (current != NULL) {
2122 _Py_PreInitEntry next = current->next;
2123 PyMem_RawFree(current->value);
2124 PyMem_RawFree(current);
2125 current = next;
2126 }
2127 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002128}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002129
2130static void
2131_clear_all_preinit_options(void)
2132{
2133 _clear_preinit_entries(&_preinit_warnoptions);
2134 _clear_preinit_entries(&_preinit_xoptions);
2135}
2136
2137static int
2138_PySys_ReadPreInitOptions(void)
2139{
2140 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01002141 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002142 if (tstate == NULL) {
2143 /* Still don't have a thread state, so something is wrong! */
2144 return -1;
2145 }
2146 _Py_PreInitEntry entry = _preinit_warnoptions;
2147 while (entry != NULL) {
2148 PySys_AddWarnOption(entry->value);
2149 entry = entry->next;
2150 }
2151 entry = _preinit_xoptions;
2152 while (entry != NULL) {
2153 PySys_AddXOption(entry->value);
2154 entry = entry->next;
2155 }
2156
2157 _clear_all_preinit_options();
2158 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06002159}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002160
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002161static PyObject *
2162get_warnoptions(void)
2163{
Eric Snowdae02762017-09-14 00:35:58 -07002164 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002165 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002166 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
2167 * interpreter config. When that happens, we need to properly set
2168 * the `warnoptions` reference in the main interpreter config as well.
2169 *
2170 * For Python 3.7, we shouldn't be able to get here due to the
2171 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2172 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2173 * call optional for embedding applications, thus making this
2174 * reachable again.
2175 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002176 warnoptions = PyList_New(0);
2177 if (warnoptions == NULL)
2178 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002179 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
2180 Py_DECREF(warnoptions);
2181 return NULL;
2182 }
2183 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002184 }
2185 return warnoptions;
2186}
Guido van Rossum23fff912000-12-15 22:02:05 +00002187
2188void
2189PySys_ResetWarnOptions(void)
2190{
Victor Stinner50b48572018-11-01 01:51:40 +01002191 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002192 if (tstate == NULL) {
2193 _clear_preinit_entries(&_preinit_warnoptions);
2194 return;
2195 }
2196
Eric Snowdae02762017-09-14 00:35:58 -07002197 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 if (warnoptions == NULL || !PyList_Check(warnoptions))
2199 return;
2200 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00002201}
2202
Victor Stinnere1b29952018-10-30 14:31:42 +01002203static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002204_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00002205{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002206 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002207 if (warnoptions == NULL) {
2208 return -1;
2209 }
2210 if (PyList_Append(warnoptions, option)) {
2211 return -1;
2212 }
2213 return 0;
2214}
2215
2216void
2217PySys_AddWarnOptionUnicode(PyObject *option)
2218{
Victor Stinnere1b29952018-10-30 14:31:42 +01002219 if (_PySys_AddWarnOptionWithError(option) < 0) {
2220 /* No return value, therefore clear error state if possible */
2221 if (_PyThreadState_UncheckedGet()) {
2222 PyErr_Clear();
2223 }
2224 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002225}
2226
2227void
2228PySys_AddWarnOption(const wchar_t *s)
2229{
Victor Stinner50b48572018-11-01 01:51:40 +01002230 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002231 if (tstate == NULL) {
2232 _append_preinit_entry(&_preinit_warnoptions, s);
2233 return;
2234 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00002235 PyObject *unicode;
2236 unicode = PyUnicode_FromWideChar(s, -1);
2237 if (unicode == NULL)
2238 return;
2239 PySys_AddWarnOptionUnicode(unicode);
2240 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00002241}
2242
Christian Heimes33fe8092008-04-13 13:53:33 +00002243int
2244PySys_HasWarnOptions(void)
2245{
Eric Snowdae02762017-09-14 00:35:58 -07002246 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02002247 return (warnoptions != NULL && PyList_Check(warnoptions)
2248 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00002249}
2250
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002251static PyObject *
2252get_xoptions(void)
2253{
Eric Snowdae02762017-09-14 00:35:58 -07002254 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002255 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002256 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
2257 * interpreter config. When that happens, we need to properly set
2258 * the `xoptions` reference in the main interpreter config as well.
2259 *
2260 * For Python 3.7, we shouldn't be able to get here due to the
2261 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
2262 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
2263 * call optional for embedding applications, thus making this
2264 * reachable again.
2265 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002266 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002267 if (xoptions == NULL)
2268 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07002269 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
2270 Py_DECREF(xoptions);
2271 return NULL;
2272 }
2273 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002274 }
2275 return xoptions;
2276}
2277
Victor Stinnere1b29952018-10-30 14:31:42 +01002278static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002279_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002280{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002281 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002282
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283 PyObject *opts = get_xoptions();
2284 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002285 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002286 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002287
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002288 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002289 if (!name_end) {
2290 name = PyUnicode_FromWideChar(s, -1);
2291 value = Py_True;
2292 Py_INCREF(value);
2293 }
2294 else {
2295 name = PyUnicode_FromWideChar(s, name_end - s);
2296 value = PyUnicode_FromWideChar(name_end + 1, -1);
2297 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002298 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002299 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002300 }
2301 if (PyDict_SetItem(opts, name, value) < 0) {
2302 goto error;
2303 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002304 Py_DECREF(name);
2305 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002306 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002307
2308error:
2309 Py_XDECREF(name);
2310 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002311 return -1;
2312}
2313
2314void
2315PySys_AddXOption(const wchar_t *s)
2316{
Victor Stinner50b48572018-11-01 01:51:40 +01002317 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002318 if (tstate == NULL) {
2319 _append_preinit_entry(&_preinit_xoptions, s);
2320 return;
2321 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002322 if (_PySys_AddXOptionWithError(s) < 0) {
2323 /* No return value, therefore clear error state if possible */
2324 if (_PyThreadState_UncheckedGet()) {
2325 PyErr_Clear();
2326 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002327 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002328}
2329
2330PyObject *
2331PySys_GetXOptions(void)
2332{
2333 return get_xoptions();
2334}
2335
Guido van Rossum40552d01998-08-06 03:34:39 +00002336/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2337 Two literals concatenated works just fine. If you have a K&R compiler
2338 or other abomination that however *does* understand longer strings,
2339 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002340PyDoc_VAR(sys_doc) =
2341PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002342"This module provides access to some objects used or maintained by the\n\
2343interpreter and to functions that interact strongly with the interpreter.\n\
2344\n\
2345Dynamic objects:\n\
2346\n\
2347argv -- command line arguments; argv[0] is the script pathname if known\n\
2348path -- module search path; path[0] is the script directory, else ''\n\
2349modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002350\n\
2351displayhook -- called to show results in an interactive session\n\
2352excepthook -- called to handle any uncaught exception other than SystemExit\n\
2353 To customize printing in an interactive session or to install a custom\n\
2354 top-level exception handler, assign other functions to replace these.\n\
2355\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002356stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002357stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002358stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002359 By assigning other file objects (or objects that behave like files)\n\
2360 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002361\n\
2362last_type -- type of last uncaught exception\n\
2363last_value -- value of last uncaught exception\n\
2364last_traceback -- traceback of last uncaught exception\n\
2365 These three are only available in an interactive session after a\n\
2366 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002367"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002368)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002369/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002370PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002371"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002372Static objects:\n\
2373\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002374builtin_module_names -- tuple of module names built into this interpreter\n\
2375copyright -- copyright notice pertaining to this interpreter\n\
2376exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002377executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002378float_info -- a struct sequence with information about the float implementation.\n\
2379float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002380hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002381hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002382implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002383int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002384maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002385maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002386platform -- platform identifier\n\
2387prefix -- prefix used to find the Python library\n\
2388thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002389version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002390version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002391"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002392)
Steve Dowercc16be82016-09-08 10:35:16 -07002393#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002394/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002395PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002396"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002397winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002398"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002399)
Steve Dowercc16be82016-09-08 10:35:16 -07002400#endif /* MS_COREDLL */
2401#ifdef MS_WINDOWS
2402/* concatenating string here */
2403PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002404"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002405"
2406)
2407#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002408PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002409"__stdin__ -- the original stdin; don't touch!\n\
2410__stdout__ -- the original stdout; don't touch!\n\
2411__stderr__ -- the original stderr; don't touch!\n\
2412__displayhook__ -- the original displayhook; don't touch!\n\
2413__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002414\n\
2415Functions:\n\
2416\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002417displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002418excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002419exc_info() -- return thread-safe information about the current exception\n\
2420exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002421getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002422getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002423getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002424getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002425getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002426gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002427setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002428setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002429setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002430setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002431settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002432"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002433)
Fred Drakeccede592000-08-14 20:59:57 +00002434/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002435
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002436
2437PyDoc_STRVAR(flags__doc__,
2438"sys.flags\n\
2439\n\
2440Flags provided through command line arguments or environment vars.");
2441
2442static PyTypeObject FlagsType;
2443
2444static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 {"inspect", "-i"},
2447 {"interactive", "-i"},
2448 {"optimize", "-O or -OO"},
2449 {"dont_write_bytecode", "-B"},
2450 {"no_user_site", "-s"},
2451 {"no_site", "-S"},
2452 {"ignore_environment", "-E"},
2453 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 /* {"unbuffered", "-u"}, */
2455 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002456 {"bytes_warning", "-b"},
2457 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002458 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002459 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002460 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002461 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002463};
2464
2465static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 "sys.flags", /* name */
2467 flags__doc__, /* doc */
2468 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002469 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002470};
2471
2472static PyObject*
Victor Stinner43125222019-04-24 18:23:53 +02002473make_flags(_PyRuntimeState *runtime, PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 int pos = 0;
2476 PyObject *seq;
Victor Stinner43125222019-04-24 18:23:53 +02002477 const _PyPreConfig *preconfig = &runtime->preconfig;
2478 const _PyCoreConfig *config = &interp->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002479
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 seq = PyStructSequence_New(&FlagsType);
2481 if (seq == NULL)
2482 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002483
2484#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002485 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002486
Victor Stinnerfbca9082018-08-30 00:50:45 +02002487 SetFlag(config->parser_debug);
2488 SetFlag(config->inspect);
2489 SetFlag(config->interactive);
2490 SetFlag(config->optimization_level);
2491 SetFlag(!config->write_bytecode);
2492 SetFlag(!config->user_site_directory);
2493 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002494 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002495 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 /* SetFlag(saw_unbuffered_flag); */
2497 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002498 SetFlag(config->bytes_warning);
2499 SetFlag(config->quiet);
2500 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002501 SetFlag(config->isolated);
2502 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2503 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002504#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002507 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002508 return NULL;
2509 }
2510 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002511}
2512
Eric Smith0e5b5622009-02-06 01:32:42 +00002513PyDoc_STRVAR(version_info__doc__,
2514"sys.version_info\n\
2515\n\
2516Version information as a named tuple.");
2517
2518static PyTypeObject VersionInfoType;
2519
2520static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002521 {"major", "Major release number"},
2522 {"minor", "Minor release number"},
2523 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002524 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002525 {"serial", "Serial release number"},
2526 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002527};
2528
2529static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 "sys.version_info", /* name */
2531 version_info__doc__, /* doc */
2532 version_info_fields, /* fields */
2533 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002534};
2535
2536static PyObject *
2537make_version_info(void)
2538{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 PyObject *version_info;
2540 char *s;
2541 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 version_info = PyStructSequence_New(&VersionInfoType);
2544 if (version_info == NULL) {
2545 return NULL;
2546 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002547
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002548 /*
2549 * These release level checks are mutually exclusive and cover
2550 * the field, so don't get too fancy with the pre-processor!
2551 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002552#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002554#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002556#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002558#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002560#endif
2561
2562#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002564#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 SetIntItem(PY_MAJOR_VERSION);
2568 SetIntItem(PY_MINOR_VERSION);
2569 SetIntItem(PY_MICRO_VERSION);
2570 SetStrItem(s);
2571 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002572#undef SetIntItem
2573#undef SetStrItem
2574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 if (PyErr_Occurred()) {
2576 Py_CLEAR(version_info);
2577 return NULL;
2578 }
2579 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002580}
2581
Brett Cannon3adc7b72012-07-09 14:22:12 -04002582/* sys.implementation values */
2583#define NAME "cpython"
2584const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002585#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2586#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002587#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002588const char *_PySys_ImplCacheTag = TAG;
2589#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002590#undef MAJOR
2591#undef MINOR
2592#undef TAG
2593
Barry Warsaw409da152012-06-03 16:18:47 -04002594static PyObject *
2595make_impl_info(PyObject *version_info)
2596{
2597 int res;
2598 PyObject *impl_info, *value, *ns;
2599
2600 impl_info = PyDict_New();
2601 if (impl_info == NULL)
2602 return NULL;
2603
2604 /* populate the dict */
2605
Brett Cannon3adc7b72012-07-09 14:22:12 -04002606 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002607 if (value == NULL)
2608 goto error;
2609 res = PyDict_SetItemString(impl_info, "name", value);
2610 Py_DECREF(value);
2611 if (res < 0)
2612 goto error;
2613
Brett Cannon3adc7b72012-07-09 14:22:12 -04002614 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002615 if (value == NULL)
2616 goto error;
2617 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2618 Py_DECREF(value);
2619 if (res < 0)
2620 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002621
2622 res = PyDict_SetItemString(impl_info, "version", version_info);
2623 if (res < 0)
2624 goto error;
2625
2626 value = PyLong_FromLong(PY_VERSION_HEX);
2627 if (value == NULL)
2628 goto error;
2629 res = PyDict_SetItemString(impl_info, "hexversion", value);
2630 Py_DECREF(value);
2631 if (res < 0)
2632 goto error;
2633
doko@ubuntu.com55532312016-06-14 08:55:19 +02002634#ifdef MULTIARCH
2635 value = PyUnicode_FromString(MULTIARCH);
2636 if (value == NULL)
2637 goto error;
2638 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2639 Py_DECREF(value);
2640 if (res < 0)
2641 goto error;
2642#endif
2643
Barry Warsaw409da152012-06-03 16:18:47 -04002644 /* dict ready */
2645
2646 ns = _PyNamespace_New(impl_info);
2647 Py_DECREF(impl_info);
2648 return ns;
2649
2650error:
2651 Py_CLEAR(impl_info);
2652 return NULL;
2653}
2654
Martin v. Löwis1a214512008-06-11 05:26:20 +00002655static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 PyModuleDef_HEAD_INIT,
2657 "sys",
2658 sys_doc,
2659 -1, /* multiple "initialization" just copies the module dict. */
2660 sys_methods,
2661 NULL,
2662 NULL,
2663 NULL,
2664 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002665};
2666
Eric Snow6b4be192017-05-22 21:36:03 -07002667/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002668#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002669 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002670 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002671 if (v == NULL) { \
2672 goto err_occurred; \
2673 } \
Victor Stinner58049602013-07-22 22:40:00 +02002674 res = PyDict_SetItemString(sysdict, key, v); \
2675 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002676 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002677 } \
2678 } while (0)
2679#define SET_SYS_FROM_STRING(key, value) \
2680 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002681 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002682 if (v == NULL) { \
2683 goto err_occurred; \
2684 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002685 res = PyDict_SetItemString(sysdict, key, v); \
2686 Py_DECREF(v); \
2687 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002688 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002689 } \
2690 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002691
Victor Stinnerab672812019-01-23 15:04:40 +01002692static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02002693_PySys_InitCore(_PyRuntimeState *runtime, PyInterpreterState *interp,
2694 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002695{
Victor Stinnerab672812019-01-23 15:04:40 +01002696 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002697 int res;
2698
Nick Coghland6009512014-11-20 21:39:37 +10002699 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002700
Victor Stinner8fea2522013-10-27 17:15:42 +01002701 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2702 PyDict_GetItemString(sysdict, "displayhook"));
2703 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2704 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002705 SET_SYS_FROM_STRING_BORROW(
2706 "__breakpointhook__",
2707 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002708 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2709 PyDict_GetItemString(sysdict, "unraisablehook"));
2710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002711 SET_SYS_FROM_STRING("version",
2712 PyUnicode_FromString(Py_GetVersion()));
2713 SET_SYS_FROM_STRING("hexversion",
2714 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002715 SET_SYS_FROM_STRING("_git",
2716 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2717 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002718 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002719 SET_SYS_FROM_STRING("api_version",
2720 PyLong_FromLong(PYTHON_API_VERSION));
2721 SET_SYS_FROM_STRING("copyright",
2722 PyUnicode_FromString(Py_GetCopyright()));
2723 SET_SYS_FROM_STRING("platform",
2724 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 SET_SYS_FROM_STRING("maxsize",
2726 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2727 SET_SYS_FROM_STRING("float_info",
2728 PyFloat_GetInfo());
2729 SET_SYS_FROM_STRING("int_info",
2730 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002731 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002732 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002733 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2734 goto type_init_failed;
2735 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002736 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002737 SET_SYS_FROM_STRING("hash_info",
2738 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002740 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 SET_SYS_FROM_STRING("builtin_module_names",
2742 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002743#if PY_BIG_ENDIAN
2744 SET_SYS_FROM_STRING("byteorder",
2745 PyUnicode_FromString("big"));
2746#else
2747 SET_SYS_FROM_STRING("byteorder",
2748 PyUnicode_FromString("little"));
2749#endif
Fred Drake099325e2000-08-14 15:47:03 +00002750
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002751#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 SET_SYS_FROM_STRING("dllhandle",
2753 PyLong_FromVoidPtr(PyWin_DLLhModule));
2754 SET_SYS_FROM_STRING("winver",
2755 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002756#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002757#ifdef ABIFLAGS
2758 SET_SYS_FROM_STRING("abiflags",
2759 PyUnicode_FromString(ABIFLAGS));
2760#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002763 if (VersionInfoType.tp_name == NULL) {
2764 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002765 &version_info_desc) < 0) {
2766 goto type_init_failed;
2767 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002768 }
Barry Warsaw409da152012-06-03 16:18:47 -04002769 version_info = make_version_info();
2770 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 /* prevent user from creating new instances */
2772 VersionInfoType.tp_init = NULL;
2773 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002774 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2775 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2776 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002777
Barry Warsaw409da152012-06-03 16:18:47 -04002778 /* implementation */
2779 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002782 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002783 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2784 goto type_init_failed;
2785 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002786 }
Victor Stinner43125222019-04-24 18:23:53 +02002787 /* Set flags to their default values (updated by _PySys_InitMain()) */
2788 SET_SYS_FROM_STRING("flags", make_flags(runtime, interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002789
2790#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002791 /* getwindowsversion */
2792 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002793 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002794 &windows_version_desc) < 0) {
2795 goto type_init_failed;
2796 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 /* prevent user from creating new instances */
2798 WindowsVersionType.tp_init = NULL;
2799 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002800 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002801 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002802 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002803 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002804 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002805#endif
2806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002807 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002808#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 SET_SYS_FROM_STRING("float_repr_style",
2810 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002811#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002812 SET_SYS_FROM_STRING("float_repr_style",
2813 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002814#endif
2815
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002816 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002817
Yury Selivanoveb636452016-09-08 22:01:51 -07002818 /* initialize asyncgen_hooks */
2819 if (AsyncGenHooksType.tp_name == NULL) {
2820 if (PyStructSequence_InitType2(
2821 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002822 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002823 }
2824 }
2825
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002826 if (PyErr_Occurred()) {
2827 goto err_occurred;
2828 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002829 return _Py_INIT_OK();
2830
2831type_init_failed:
2832 return _Py_INIT_ERR("failed to initialize a type");
2833
2834err_occurred:
2835 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002836}
2837
Eric Snow6b4be192017-05-22 21:36:03 -07002838#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002839
2840/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002841#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2842 do { \
2843 PyObject *v = (value); \
2844 if (v == NULL) \
2845 return -1; \
2846 res = PyDict_SetItemString(sysdict, key, v); \
2847 Py_DECREF(v); \
2848 if (res < 0) { \
2849 return res; \
2850 } \
2851 } while (0)
2852
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002853
2854static int
2855sys_add_xoption(PyObject *opts, const wchar_t *s)
2856{
2857 PyObject *name, *value;
2858
2859 const wchar_t *name_end = wcschr(s, L'=');
2860 if (!name_end) {
2861 name = PyUnicode_FromWideChar(s, -1);
2862 value = Py_True;
2863 Py_INCREF(value);
2864 }
2865 else {
2866 name = PyUnicode_FromWideChar(s, name_end - s);
2867 value = PyUnicode_FromWideChar(name_end + 1, -1);
2868 }
2869 if (name == NULL || value == NULL) {
2870 goto error;
2871 }
2872 if (PyDict_SetItem(opts, name, value) < 0) {
2873 goto error;
2874 }
2875 Py_DECREF(name);
2876 Py_DECREF(value);
2877 return 0;
2878
2879error:
2880 Py_XDECREF(name);
2881 Py_XDECREF(value);
2882 return -1;
2883}
2884
2885
2886static PyObject*
2887sys_create_xoptions_dict(const _PyCoreConfig *config)
2888{
2889 Py_ssize_t nxoption = config->xoptions.length;
2890 wchar_t * const * xoptions = config->xoptions.items;
2891 PyObject *dict = PyDict_New();
2892 if (dict == NULL) {
2893 return NULL;
2894 }
2895
2896 for (Py_ssize_t i=0; i < nxoption; i++) {
2897 const wchar_t *option = xoptions[i];
2898 if (sys_add_xoption(dict, option) < 0) {
2899 Py_DECREF(dict);
2900 return NULL;
2901 }
2902 }
2903
2904 return dict;
2905}
2906
2907
Eric Snow6b4be192017-05-22 21:36:03 -07002908int
Victor Stinner43125222019-04-24 18:23:53 +02002909_PySys_InitMain(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002910{
Victor Stinnerab672812019-01-23 15:04:40 +01002911 PyObject *sysdict = interp->sysdict;
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002912 const _PyCoreConfig *config = &interp->core_config;
Eric Snow6b4be192017-05-22 21:36:03 -07002913 int res;
2914
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002915#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002916 do { \
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002917 PyObject *list = _PyWstrList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002918 if (list == NULL) { \
2919 return -1; \
2920 } \
2921 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2922 Py_DECREF(list); \
2923 } while (0)
2924
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002925#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2926 do { \
2927 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2928 if (str == NULL) { \
2929 return -1; \
2930 } \
2931 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2932 Py_DECREF(str); \
2933 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002934
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002935 COPY_LIST("path", config->module_search_paths);
2936
2937 SET_SYS_FROM_WSTR("executable", config->executable);
2938 SET_SYS_FROM_WSTR("prefix", config->prefix);
2939 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2940 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2941 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002942
Carl Meyerb193fa92018-06-15 22:40:56 -06002943 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002944 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002945 } else {
2946 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2947 }
2948
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002949 COPY_LIST("argv", config->argv);
2950 COPY_LIST("warnoptions", config->warnoptions);
2951
2952 PyObject *xoptions = sys_create_xoptions_dict(config);
2953 if (xoptions == NULL) {
2954 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002955 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002956 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002957 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002958
Victor Stinner37cd9822018-11-16 11:55:35 +01002959#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002960#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002961
Eric Snow6b4be192017-05-22 21:36:03 -07002962 /* Set flags to their final values */
Victor Stinner43125222019-04-24 18:23:53 +02002963 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002964 /* prevent user from creating new instances */
2965 FlagsType.tp_init = NULL;
2966 FlagsType.tp_new = NULL;
2967 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2968 if (res < 0) {
2969 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2970 return res;
2971 }
2972 PyErr_Clear();
2973 }
2974
2975 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002976 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002977
Eric Snowdae02762017-09-14 00:35:58 -07002978 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002979 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002980
Eric Snowdae02762017-09-14 00:35:58 -07002981 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002982 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002983
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002984 /* Transfer any sys.warnoptions and sys._xoptions set directly
2985 * by an embedding application from the linked list to the module. */
2986 if (_PySys_ReadPreInitOptions() != 0)
2987 return -1;
2988
Eric Snow6b4be192017-05-22 21:36:03 -07002989 if (PyErr_Occurred())
2990 return -1;
2991 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002992
2993err_occurred:
2994 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002995}
2996
Victor Stinner41264f12017-12-15 02:05:29 +01002997#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002998#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002999
Victor Stinnerab672812019-01-23 15:04:40 +01003000
3001/* Set up a preliminary stderr printer until we have enough
3002 infrastructure for the io module in place.
3003
3004 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
3005_PyInitError
3006_PySys_SetPreliminaryStderr(PyObject *sysdict)
3007{
3008 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
3009 if (pstderr == NULL) {
3010 goto error;
3011 }
3012 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
3013 goto error;
3014 }
3015 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
3016 goto error;
3017 }
3018 Py_DECREF(pstderr);
3019 return _Py_INIT_OK();
3020
3021error:
3022 Py_XDECREF(pstderr);
3023 return _Py_INIT_ERR("can't set preliminary stderr");
3024}
3025
3026
3027/* Create sys module without all attributes: _PySys_InitMain() should be called
3028 later to add remaining attributes. */
3029_PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02003030_PySys_Create(_PyRuntimeState *runtime, PyInterpreterState *interp,
3031 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01003032{
3033 PyObject *modules = PyDict_New();
3034 if (modules == NULL) {
3035 return _Py_INIT_ERR("can't make modules dictionary");
3036 }
3037 interp->modules = modules;
3038
3039 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
3040 if (sysmod == NULL) {
3041 return _Py_INIT_ERR("failed to create a module object");
3042 }
3043
3044 PyObject *sysdict = PyModule_GetDict(sysmod);
3045 if (sysdict == NULL) {
3046 return _Py_INIT_ERR("can't initialize sys dict");
3047 }
3048 Py_INCREF(sysdict);
3049 interp->sysdict = sysdict;
3050
3051 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
3052 return _Py_INIT_ERR("can't initialize sys module");
3053 }
3054
3055 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
3056 if (_Py_INIT_FAILED(err)) {
3057 return err;
3058 }
3059
Victor Stinner43125222019-04-24 18:23:53 +02003060 err = _PySys_InitCore(runtime, interp, sysdict);
Victor Stinnerab672812019-01-23 15:04:40 +01003061 if (_Py_INIT_FAILED(err)) {
3062 return err;
3063 }
3064
3065 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
3066
3067 *sysmod_p = sysmod;
3068 return _Py_INIT_OK();
3069}
3070
3071
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003072static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00003073makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00003074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003075 int i, n;
3076 const wchar_t *p;
3077 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00003078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003079 n = 1;
3080 p = path;
3081 while ((p = wcschr(p, delim)) != NULL) {
3082 n++;
3083 p++;
3084 }
3085 v = PyList_New(n);
3086 if (v == NULL)
3087 return NULL;
3088 for (i = 0; ; i++) {
3089 p = wcschr(path, delim);
3090 if (p == NULL)
3091 p = path + wcslen(path); /* End of string */
3092 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
3093 if (w == NULL) {
3094 Py_DECREF(v);
3095 return NULL;
3096 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07003097 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003098 if (*p == '\0')
3099 break;
3100 path = p+1;
3101 }
3102 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003103}
3104
3105void
Martin v. Löwis790465f2008-04-05 20:41:37 +00003106PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003108 PyObject *v;
3109 if ((v = makepathobject(path, DELIM)) == NULL)
3110 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01003111 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003112 Py_FatalError("can't assign sys.path");
3113 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00003114}
3115
Guido van Rossum65bf9f21997-04-29 18:33:38 +00003116static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01003117make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00003118{
Victor Stinner74f65682019-03-15 15:08:05 +01003119 PyObject *list = PyList_New(argc);
3120 if (list == NULL) {
3121 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003122 }
Victor Stinner74f65682019-03-15 15:08:05 +01003123
3124 for (Py_ssize_t i = 0; i < argc; i++) {
3125 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
3126 if (v == NULL) {
3127 Py_DECREF(list);
3128 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003129 }
Victor Stinner74f65682019-03-15 15:08:05 +01003130 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003131 }
Victor Stinner74f65682019-03-15 15:08:05 +01003132 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00003133}
3134
Victor Stinner11a247d2017-12-13 21:05:57 +01003135void
3136PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01003137{
Victor Stinner74f65682019-03-15 15:08:05 +01003138 if (argc < 1 || argv == NULL) {
3139 /* Ensure at least one (empty) argument is seen */
3140 wchar_t* empty_argv[1] = {L""};
3141 argv = empty_argv;
3142 argc = 1;
3143 }
3144
3145 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01003146 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01003147 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003148 }
3149 if (PySys_SetObject("argv", av) != 0) {
3150 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01003151 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01003152 }
3153 Py_DECREF(av);
3154
3155 if (updatepath) {
3156 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
3157 If argv[0] is a symlink, use the real path. */
Victor Stinner74f65682019-03-15 15:08:05 +01003158 const _PyWstrList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01003159 PyObject *path0 = NULL;
3160 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
3161 if (path0 == NULL) {
3162 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01003163 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01003164
3165 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
3166 if (sys_path != NULL) {
3167 if (PyList_Insert(sys_path, 0, path0) < 0) {
3168 Py_DECREF(path0);
3169 Py_FatalError("can't prepend path0 to sys.path");
3170 }
3171 }
3172 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01003173 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01003174 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003175}
Guido van Rossuma890e681998-05-12 14:59:24 +00003176
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003177void
3178PySys_SetArgv(int argc, wchar_t **argv)
3179{
Christian Heimesad73a9c2013-08-10 16:36:18 +02003180 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00003181}
3182
Victor Stinner14284c22010-04-23 12:02:30 +00003183/* Reimplementation of PyFile_WriteString() no calling indirectly
3184 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
3185
3186static int
Victor Stinner79766632010-08-16 17:36:42 +00003187sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00003188{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02003189 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003190 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00003191
Victor Stinnerecccc4f2010-06-08 20:46:00 +00003192 if (file == NULL)
3193 return -1;
3194
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02003195 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003196 if (writer == NULL)
3197 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00003198
Victor Stinner7bfb42d2016-12-05 17:04:32 +01003199 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003200 if (result == NULL) {
3201 goto error;
3202 } else {
3203 err = 0;
3204 goto finally;
3205 }
Victor Stinner14284c22010-04-23 12:02:30 +00003206
3207error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003208 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00003209finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003210 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003211 Py_XDECREF(result);
3212 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00003213}
3214
Victor Stinner79766632010-08-16 17:36:42 +00003215static int
3216sys_pyfile_write(const char *text, PyObject *file)
3217{
3218 PyObject *unicode = NULL;
3219 int err;
3220
3221 if (file == NULL)
3222 return -1;
3223
3224 unicode = PyUnicode_FromString(text);
3225 if (unicode == NULL)
3226 return -1;
3227
3228 err = sys_pyfile_write_unicode(unicode, file);
3229 Py_DECREF(unicode);
3230 return err;
3231}
Guido van Rossuma890e681998-05-12 14:59:24 +00003232
3233/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
3234 Adapted from code submitted by Just van Rossum.
3235
3236 PySys_WriteStdout(format, ...)
3237 PySys_WriteStderr(format, ...)
3238
3239 The first function writes to sys.stdout; the second to sys.stderr. When
3240 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00003241 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00003242
Victor Stinner14284c22010-04-23 12:02:30 +00003243 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00003244 signal handlers: they may raise a new exception whereas sys_write()
3245 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00003246
Guido van Rossuma890e681998-05-12 14:59:24 +00003247 Both take a printf-style format string as their first argument followed
3248 by a variable length argument list determined by the format string.
3249
3250 *** WARNING ***
3251
3252 The format should limit the total size of the formatted output string to
3253 1000 bytes. In particular, this means that no unrestricted "%s" formats
3254 should occur; these should be limited using "%.<N>s where <N> is a
3255 decimal number calculated so that <N> plus the maximum size of other
3256 formatted text does not exceed 1000 bytes. Also watch out for "%f",
3257 which can print hundreds of digits for very large numbers.
3258
3259 */
3260
3261static void
Victor Stinner09054372013-11-06 22:41:44 +01003262sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00003263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003264 PyObject *file;
3265 PyObject *error_type, *error_value, *error_traceback;
3266 char buffer[1001];
3267 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00003268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003269 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003270 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003271 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
3272 if (sys_pyfile_write(buffer, file) != 0) {
3273 PyErr_Clear();
3274 fputs(buffer, fp);
3275 }
3276 if (written < 0 || (size_t)written >= sizeof(buffer)) {
3277 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00003278 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003279 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003280 }
3281 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00003282}
3283
3284void
Guido van Rossuma890e681998-05-12 14:59:24 +00003285PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003286{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003287 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003289 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003290 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003291 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003292}
3293
3294void
Guido van Rossuma890e681998-05-12 14:59:24 +00003295PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00003296{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003297 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00003298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003299 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003300 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003301 va_end(va);
3302}
3303
3304static void
Victor Stinner09054372013-11-06 22:41:44 +01003305sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00003306{
3307 PyObject *file, *message;
3308 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02003309 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00003310
3311 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003312 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00003313 message = PyUnicode_FromFormatV(format, va);
3314 if (message != NULL) {
3315 if (sys_pyfile_write_unicode(message, file) != 0) {
3316 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02003317 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003318 if (utf8 != NULL)
3319 fputs(utf8, fp);
3320 }
3321 Py_DECREF(message);
3322 }
3323 PyErr_Restore(error_type, error_value, error_traceback);
3324}
3325
3326void
3327PySys_FormatStdout(const char *format, ...)
3328{
3329 va_list va;
3330
3331 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003332 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003333 va_end(va);
3334}
3335
3336void
3337PySys_FormatStderr(const char *format, ...)
3338{
3339 va_list va;
3340
3341 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003342 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003343 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003344}