blob: dd127a1f7ce003acdf8464d9a427db80e397b3b5 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060018#include "internal/pystate.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000019#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000020#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020021#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossume2437a11992-03-23 18:20:18 +000023#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020024#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Mark Hammond8696ebc2002-10-08 02:44:31 +000026#ifdef MS_WINDOWS
27#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000028#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#endif /* MS_WINDOWS */
30
Guido van Rossum9b38a141996-09-11 23:12:24 +000031#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000032extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000033/* A string loaded from the DLL at startup: */
34extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000035#endif
36
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(_);
38_Py_IDENTIFIER(__sizeof__);
39_Py_IDENTIFIER(buffer);
40_Py_IDENTIFIER(builtins);
41_Py_IDENTIFIER(encoding);
42_Py_IDENTIFIER(path);
43_Py_IDENTIFIER(stdout);
44_Py_IDENTIFIER(stderr);
45_Py_IDENTIFIER(write);
46
Guido van Rossum65bf9f21997-04-29 18:33:38 +000047PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010048_PySys_GetObjectId(_Py_Identifier *key)
49{
50 PyThreadState *tstate = PyThreadState_GET();
51 PyObject *sd = tstate->interp->sysdict;
52 if (sd == NULL)
53 return NULL;
54 return _PyDict_GetItemId(sd, key);
55}
56
57PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000058PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 PyThreadState *tstate = PyThreadState_GET();
61 PyObject *sd = tstate->interp->sysdict;
62 if (sd == NULL)
63 return NULL;
64 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000065}
66
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067int
Victor Stinnerd67bd452013-11-06 22:36:40 +010068_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
69{
70 PyThreadState *tstate = PyThreadState_GET();
71 PyObject *sd = tstate->interp->sysdict;
72 if (v == NULL) {
73 if (_PyDict_GetItemId(sd, key) == NULL)
74 return 0;
75 else
76 return _PyDict_DelItemId(sd, key);
77 }
78 else
79 return _PyDict_SetItemId(sd, key, v);
80}
81
82int
Neal Norwitzf3081322007-08-25 00:32:45 +000083PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000085 PyThreadState *tstate = PyThreadState_GET();
86 PyObject *sd = tstate->interp->sysdict;
87 if (v == NULL) {
88 if (PyDict_GetItemString(sd, name) == NULL)
89 return 0;
90 else
91 return PyDict_DelItemString(sd, name);
92 }
93 else
94 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095}
96
Victor Stinner13d49ee2010-12-04 17:24:33 +000097/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
98 error handler. If sys.stdout has a buffer attribute, use
99 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
100 sys.stdout.write(redecoded).
101
102 Helper function for sys_displayhook(). */
103static int
104sys_displayhook_unencodable(PyObject *outf, PyObject *o)
105{
106 PyObject *stdout_encoding = NULL;
107 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200108 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000109 int ret;
110
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200111 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000112 if (stdout_encoding == NULL)
113 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200114 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000115 if (stdout_encoding_str == NULL)
116 goto error;
117
118 repr_str = PyObject_Repr(o);
119 if (repr_str == NULL)
120 goto error;
121 encoded = PyUnicode_AsEncodedString(repr_str,
122 stdout_encoding_str,
123 "backslashreplace");
124 Py_DECREF(repr_str);
125 if (encoded == NULL)
126 goto error;
127
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200128 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000129 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100130 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000131 Py_DECREF(buffer);
132 Py_DECREF(encoded);
133 if (result == NULL)
134 goto error;
135 Py_DECREF(result);
136 }
137 else {
138 PyErr_Clear();
139 escaped_str = PyUnicode_FromEncodedObject(encoded,
140 stdout_encoding_str,
141 "strict");
142 Py_DECREF(encoded);
143 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
144 Py_DECREF(escaped_str);
145 goto error;
146 }
147 Py_DECREF(escaped_str);
148 }
149 ret = 0;
150 goto finally;
151
152error:
153 ret = -1;
154finally:
155 Py_XDECREF(stdout_encoding);
156 return ret;
157}
158
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000159static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000160sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000162 PyObject *outf;
Eric Snow93c92f72017-09-13 23:46:04 -0700163 PyInterpreterState *interp = PyThreadState_GET()->interp;
164 PyObject *modules = interp->modules;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100165 PyObject *builtins;
166 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000167 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000168
Eric Snow93c92f72017-09-13 23:46:04 -0700169 builtins = _PyDict_GetItemId(modules, &PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000170 if (builtins == NULL) {
171 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
172 return NULL;
173 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000174
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 /* Print value except if None */
176 /* After printing, also assign to '_' */
177 /* Before, set '_' to None to avoid recursion */
178 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200179 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200181 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100183 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 if (outf == NULL || outf == Py_None) {
185 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
186 return NULL;
187 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000188 if (PyFile_WriteObject(o, outf, 0) != 0) {
189 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
190 /* repr(o) is not encodable to sys.stdout.encoding with
191 * sys.stdout.errors error handler (which is probably 'strict') */
192 PyErr_Clear();
193 err = sys_displayhook_unencodable(outf, o);
194 if (err)
195 return NULL;
196 }
197 else {
198 return NULL;
199 }
200 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100201 if (newline == NULL) {
202 newline = PyUnicode_FromString("\n");
203 if (newline == NULL)
204 return NULL;
205 }
206 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200208 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200210 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000211}
212
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000213PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000214"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000215"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000216"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000217);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000218
219static PyObject *
220sys_excepthook(PyObject* self, PyObject* args)
221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyObject *exc, *value, *tb;
223 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
224 return NULL;
225 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200226 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000227}
228
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000229PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000230"excepthook(exctype, value, traceback) -> None\n"
231"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000232"Handle an exception by displaying it with a traceback on sys.stderr.\n"
233);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000234
235static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000236sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000237{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000238 PyThreadState *tstate;
239 tstate = PyThreadState_GET();
240 return Py_BuildValue(
241 "(OOO)",
242 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
243 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
244 tstate->exc_traceback != NULL ?
245 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000246}
247
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000248PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000249"exc_info() -> (type, value, traceback)\n\
250\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000251Return information about the most recent exception caught by an except\n\
252clause in the current stack frame or in an older stack frame."
253);
254
255static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000256sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 PyObject *exit_code = 0;
259 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
260 return NULL;
261 /* Raise SystemExit so callers may catch it or clean up. */
262 PyErr_SetObject(PyExc_SystemExit, exit_code);
263 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000264}
265
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000266PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000267"exit([status])\n\
268\n\
269Exit the interpreter by raising SystemExit(status).\n\
270If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300271If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000272If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000273exit status will be one (i.e., failure)."
274);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000275
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000276
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000277static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000278sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000281}
282
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000283PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000284"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000285\n\
286Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000287implementation."
288);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000289
290static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000291sys_getfilesystemencoding(PyObject *self)
292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 if (Py_FileSystemDefaultEncoding)
294 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200295 PyErr_SetString(PyExc_RuntimeError,
296 "filesystem encoding is not initialized");
297 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000298}
299
300PyDoc_STRVAR(getfilesystemencoding_doc,
301"getfilesystemencoding() -> string\n\
302\n\
303Return the encoding used to convert Unicode filenames in\n\
304operating system filenames."
305);
306
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000307static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700308sys_getfilesystemencodeerrors(PyObject *self)
309{
310 if (Py_FileSystemDefaultEncodeErrors)
311 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
312 PyErr_SetString(PyExc_RuntimeError,
313 "filesystem encoding is not initialized");
314 return NULL;
315}
316
317PyDoc_STRVAR(getfilesystemencodeerrors_doc,
318 "getfilesystemencodeerrors() -> string\n\
319\n\
320Return the error mode used to convert Unicode filenames in\n\
321operating system filenames."
322);
323
324static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000325sys_intern(PyObject *self, PyObject *args)
326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyObject *s;
328 if (!PyArg_ParseTuple(args, "U:intern", &s))
329 return NULL;
330 if (PyUnicode_CheckExact(s)) {
331 Py_INCREF(s);
332 PyUnicode_InternInPlace(&s);
333 return s;
334 }
335 else {
336 PyErr_Format(PyExc_TypeError,
337 "can't intern %.400s", s->ob_type->tp_name);
338 return NULL;
339 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000340}
341
342PyDoc_STRVAR(intern_doc,
343"intern(string) -> string\n\
344\n\
345``Intern'' the given string. This enters the string in the (global)\n\
346table of interned strings whose purpose is to speed up dictionary lookups.\n\
347Return the string itself or the previously interned string object with the\n\
348same value.");
349
350
Fred Drake5755ce62001-06-27 19:19:46 +0000351/*
352 * Cached interned string objects used for calling the profile and
353 * trace functions. Initialized by trace_init().
354 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000355static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000356
357static int
358trace_init(void)
359{
Nick Coghlan5a851672017-09-08 10:14:16 +1000360 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200361 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000362 "c_call", "c_exception", "c_return",
363 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200364 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 PyObject *name;
366 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000367 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (whatstrings[i] == NULL) {
369 name = PyUnicode_InternFromString(whatnames[i]);
370 if (name == NULL)
371 return -1;
372 whatstrings[i] = name;
373 }
374 }
375 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000376}
377
378
379static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100380call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200384 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000385
Victor Stinner78da82b2016-08-20 01:22:57 +0200386 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200388 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100389
Victor Stinner78da82b2016-08-20 01:22:57 +0200390 stack[0] = (PyObject *)frame;
391 stack[1] = whatstrings[what];
392 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200395 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000396
Victor Stinner78da82b2016-08-20 01:22:57 +0200397 PyFrame_LocalsToFast(frame, 1);
398 if (result == NULL) {
399 PyTraceBack_Here(frame);
400 }
401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000403}
404
405static int
406profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (arg == NULL)
412 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100413 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (result == NULL) {
415 PyEval_SetProfile(NULL, NULL);
416 return -1;
417 }
418 Py_DECREF(result);
419 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000420}
421
422static int
423trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyObject *callback;
427 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 if (what == PyTrace_CALL)
430 callback = self;
431 else
432 callback = frame->f_trace;
433 if (callback == NULL)
434 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100435 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 if (result == NULL) {
437 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200438 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 return -1;
440 }
441 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300442 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 }
444 else {
445 Py_DECREF(result);
446 }
447 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000448}
Fred Draked0838392001-06-16 21:02:31 +0000449
Fred Drake8b4d01d2000-05-09 19:57:01 +0000450static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000451sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 if (trace_init() == -1)
454 return NULL;
455 if (args == Py_None)
456 PyEval_SetTrace(NULL, NULL);
457 else
458 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200459 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000460}
461
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000462PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000463"settrace(function)\n\
464\n\
465Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000466function call. See the debugger chapter in the library manual."
467);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000468
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000469static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000470sys_gettrace(PyObject *self, PyObject *args)
471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 PyThreadState *tstate = PyThreadState_GET();
473 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000474
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 if (temp == NULL)
476 temp = Py_None;
477 Py_INCREF(temp);
478 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000479}
480
481PyDoc_STRVAR(gettrace_doc,
482"gettrace()\n\
483\n\
484Return the global debug tracing function set with sys.settrace.\n\
485See the debugger chapter in the library manual."
486);
487
488static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000489sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (trace_init() == -1)
492 return NULL;
493 if (args == Py_None)
494 PyEval_SetProfile(NULL, NULL);
495 else
496 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200497 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000498}
499
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000500PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000501"setprofile(function)\n\
502\n\
503Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000504and return. See the profiler chapter in the library manual."
505);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000506
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000507static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000508sys_getprofile(PyObject *self, PyObject *args)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyThreadState *tstate = PyThreadState_GET();
511 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (temp == NULL)
514 temp = Py_None;
515 Py_INCREF(temp);
516 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000517}
518
519PyDoc_STRVAR(getprofile_doc,
520"getprofile()\n\
521\n\
522Return the profiling function set with sys.setprofile.\n\
523See the profiler chapter in the library manual."
524);
525
526static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000527sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 if (PyErr_WarnEx(PyExc_DeprecationWarning,
530 "sys.getcheckinterval() and sys.setcheckinterval() "
531 "are deprecated. Use sys.setswitchinterval() "
532 "instead.", 1) < 0)
533 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600534 PyInterpreterState *interp = PyThreadState_GET()->interp;
535 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200537 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000538}
539
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000540PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000541"setcheckinterval(n)\n\
542\n\
543Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000544n instructions. This also affects how often thread switches occur."
545);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000546
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000547static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000548sys_getcheckinterval(PyObject *self, PyObject *args)
549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (PyErr_WarnEx(PyExc_DeprecationWarning,
551 "sys.getcheckinterval() and sys.setcheckinterval() "
552 "are deprecated. Use sys.getswitchinterval() "
553 "instead.", 1) < 0)
554 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600555 PyInterpreterState *interp = PyThreadState_GET()->interp;
556 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000557}
558
559PyDoc_STRVAR(getcheckinterval_doc,
560"getcheckinterval() -> current check interval; see setcheckinterval()."
561);
562
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000563static PyObject *
564sys_setswitchinterval(PyObject *self, PyObject *args)
565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 double d;
567 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
568 return NULL;
569 if (d <= 0.0) {
570 PyErr_SetString(PyExc_ValueError,
571 "switch interval must be strictly positive");
572 return NULL;
573 }
574 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200575 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000576}
577
578PyDoc_STRVAR(setswitchinterval_doc,
579"setswitchinterval(n)\n\
580\n\
581Set the ideal thread switching delay inside the Python interpreter\n\
582The actual frequency of switching threads can be lower if the\n\
583interpreter executes long sequences of uninterruptible code\n\
584(this is implementation-specific and workload-dependent).\n\
585\n\
586The parameter must represent the desired switching delay in seconds\n\
587A typical value is 0.005 (5 milliseconds)."
588);
589
590static PyObject *
591sys_getswitchinterval(PyObject *self, PyObject *args)
592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000593 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000594}
595
596PyDoc_STRVAR(getswitchinterval_doc,
597"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
598);
599
Tim Peterse5e065b2003-07-06 18:36:54 +0000600static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000601sys_setrecursionlimit(PyObject *self, PyObject *args)
602{
Victor Stinner50856d52015-10-13 00:11:21 +0200603 int new_limit, mark;
604 PyThreadState *tstate;
605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
607 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200608
609 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200611 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 return NULL;
613 }
Victor Stinner50856d52015-10-13 00:11:21 +0200614
615 /* Issue #25274: When the recursion depth hits the recursion limit in
616 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
617 set to 1 and a RecursionError is raised. The overflowed flag is reset
618 to 0 when the recursion depth goes below the low-water mark: see
619 Py_LeaveRecursiveCall().
620
621 Reject too low new limit if the current recursion depth is higher than
622 the new low-water mark. Otherwise it may not be possible anymore to
623 reset the overflowed flag to 0. */
624 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
625 tstate = PyThreadState_GET();
626 if (tstate->recursion_depth >= mark) {
627 PyErr_Format(PyExc_RecursionError,
628 "cannot set the recursion limit to %i at "
629 "the recursion depth %i: the limit is too low",
630 new_limit, tstate->recursion_depth);
631 return NULL;
632 }
633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200635 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000636}
637
Yury Selivanov75445082015-05-11 22:57:16 -0400638static PyObject *
639sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
640{
641 if (wrapper != Py_None) {
642 if (!PyCallable_Check(wrapper)) {
643 PyErr_Format(PyExc_TypeError,
644 "callable expected, got %.50s",
645 Py_TYPE(wrapper)->tp_name);
646 return NULL;
647 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400648 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400649 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400650 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400651 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400652 }
Yury Selivanov75445082015-05-11 22:57:16 -0400653 Py_RETURN_NONE;
654}
655
656PyDoc_STRVAR(set_coroutine_wrapper_doc,
657"set_coroutine_wrapper(wrapper)\n\
658\n\
659Set a wrapper for coroutine objects."
660);
661
662static PyObject *
663sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
664{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400665 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400666 if (wrapper == NULL) {
667 wrapper = Py_None;
668 }
669 Py_INCREF(wrapper);
670 return wrapper;
671}
672
673PyDoc_STRVAR(get_coroutine_wrapper_doc,
674"get_coroutine_wrapper()\n\
675\n\
676Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
677);
678
679
Yury Selivanoveb636452016-09-08 22:01:51 -0700680static PyTypeObject AsyncGenHooksType;
681
682PyDoc_STRVAR(asyncgen_hooks_doc,
683"asyncgen_hooks\n\
684\n\
685A struct sequence providing information about asynhronous\n\
686generators hooks. The attributes are read only.");
687
688static PyStructSequence_Field asyncgen_hooks_fields[] = {
689 {"firstiter", "Hook to intercept first iteration"},
690 {"finalizer", "Hook to intercept finalization"},
691 {0}
692};
693
694static PyStructSequence_Desc asyncgen_hooks_desc = {
695 "asyncgen_hooks", /* name */
696 asyncgen_hooks_doc, /* doc */
697 asyncgen_hooks_fields , /* fields */
698 2
699};
700
701
702static PyObject *
703sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
704{
705 static char *keywords[] = {"firstiter", "finalizer", NULL};
706 PyObject *firstiter = NULL;
707 PyObject *finalizer = NULL;
708
709 if (!PyArg_ParseTupleAndKeywords(
710 args, kw, "|OO", keywords,
711 &firstiter, &finalizer)) {
712 return NULL;
713 }
714
715 if (finalizer && finalizer != Py_None) {
716 if (!PyCallable_Check(finalizer)) {
717 PyErr_Format(PyExc_TypeError,
718 "callable finalizer expected, got %.50s",
719 Py_TYPE(finalizer)->tp_name);
720 return NULL;
721 }
722 _PyEval_SetAsyncGenFinalizer(finalizer);
723 }
724 else if (finalizer == Py_None) {
725 _PyEval_SetAsyncGenFinalizer(NULL);
726 }
727
728 if (firstiter && firstiter != Py_None) {
729 if (!PyCallable_Check(firstiter)) {
730 PyErr_Format(PyExc_TypeError,
731 "callable firstiter expected, got %.50s",
732 Py_TYPE(firstiter)->tp_name);
733 return NULL;
734 }
735 _PyEval_SetAsyncGenFirstiter(firstiter);
736 }
737 else if (firstiter == Py_None) {
738 _PyEval_SetAsyncGenFirstiter(NULL);
739 }
740
741 Py_RETURN_NONE;
742}
743
744PyDoc_STRVAR(set_asyncgen_hooks_doc,
745"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
746\n\
747Set a finalizer for async generators objects."
748);
749
750static PyObject *
751sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
752{
753 PyObject *res;
754 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
755 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
756
757 res = PyStructSequence_New(&AsyncGenHooksType);
758 if (res == NULL) {
759 return NULL;
760 }
761
762 if (firstiter == NULL) {
763 firstiter = Py_None;
764 }
765
766 if (finalizer == NULL) {
767 finalizer = Py_None;
768 }
769
770 Py_INCREF(firstiter);
771 PyStructSequence_SET_ITEM(res, 0, firstiter);
772
773 Py_INCREF(finalizer);
774 PyStructSequence_SET_ITEM(res, 1, finalizer);
775
776 return res;
777}
778
779PyDoc_STRVAR(get_asyncgen_hooks_doc,
780"get_asyncgen_hooks()\n\
781\n\
782Return a namedtuple of installed asynchronous generators hooks \
783(firstiter, finalizer)."
784);
785
786
Mark Dickinsondc787d22010-05-23 13:33:13 +0000787static PyTypeObject Hash_InfoType;
788
789PyDoc_STRVAR(hash_info_doc,
790"hash_info\n\
791\n\
792A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100793hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000794
795static PyStructSequence_Field hash_info_fields[] = {
796 {"width", "width of the type used for hashing, in bits"},
797 {"modulus", "prime number giving the modulus on which the hash "
798 "function is based"},
799 {"inf", "value to be used for hash of a positive infinity"},
800 {"nan", "value to be used for hash of a nan"},
801 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100802 {"algorithm", "name of the algorithm for hashing of str, bytes and "
803 "memoryviews"},
804 {"hash_bits", "internal output size of hash algorithm"},
805 {"seed_bits", "seed size of hash algorithm"},
806 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000807 {NULL, NULL}
808};
809
810static PyStructSequence_Desc hash_info_desc = {
811 "sys.hash_info",
812 hash_info_doc,
813 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100814 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000815};
816
Matthias Klosed885e952010-07-06 10:53:30 +0000817static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000818get_hash_info(void)
819{
820 PyObject *hash_info;
821 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100822 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000823 hash_info = PyStructSequence_New(&Hash_InfoType);
824 if (hash_info == NULL)
825 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100826 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000827 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000828 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000829 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000830 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000831 PyStructSequence_SET_ITEM(hash_info, field++,
832 PyLong_FromLong(_PyHASH_INF));
833 PyStructSequence_SET_ITEM(hash_info, field++,
834 PyLong_FromLong(_PyHASH_NAN));
835 PyStructSequence_SET_ITEM(hash_info, field++,
836 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100837 PyStructSequence_SET_ITEM(hash_info, field++,
838 PyUnicode_FromString(hashfunc->name));
839 PyStructSequence_SET_ITEM(hash_info, field++,
840 PyLong_FromLong(hashfunc->hash_bits));
841 PyStructSequence_SET_ITEM(hash_info, field++,
842 PyLong_FromLong(hashfunc->seed_bits));
843 PyStructSequence_SET_ITEM(hash_info, field++,
844 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000845 if (PyErr_Occurred()) {
846 Py_CLEAR(hash_info);
847 return NULL;
848 }
849 return hash_info;
850}
851
852
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000853PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000854"setrecursionlimit(n)\n\
855\n\
856Set the maximum depth of the Python interpreter stack to n. This\n\
857limit prevents infinite recursion from causing an overflow of the C\n\
858stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000859dependent."
860);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000861
862static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000863sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000866}
867
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000868PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000869"getrecursionlimit()\n\
870\n\
871Return the current value of the recursion limit, the maximum depth\n\
872of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000873recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000874);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000875
Mark Hammond8696ebc2002-10-08 02:44:31 +0000876#ifdef MS_WINDOWS
877PyDoc_STRVAR(getwindowsversion_doc,
878"getwindowsversion()\n\
879\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000880Return information about the running version of Windows as a named tuple.\n\
881The members are named: major, minor, build, platform, service_pack,\n\
882service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200883backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700884All elements are numbers, except service_pack and platform_type which are\n\
885strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
886Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
887server. Platform_version is a 3-tuple containing a version number that is\n\
888intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000889);
890
Eric Smithf7bb5782010-01-27 00:44:57 +0000891static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
892
893static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 {"major", "Major version number"},
895 {"minor", "Minor version number"},
896 {"build", "Build number"},
897 {"platform", "Operating system platform"},
898 {"service_pack", "Latest Service Pack installed on the system"},
899 {"service_pack_major", "Service Pack major version number"},
900 {"service_pack_minor", "Service Pack minor version number"},
901 {"suite_mask", "Bit mask identifying available product suites"},
902 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700903 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000905};
906
907static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000908 "sys.getwindowsversion", /* name */
909 getwindowsversion_doc, /* doc */
910 windows_version_fields, /* fields */
911 5 /* For backward compatibility,
912 only the first 5 items are accessible
913 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000914};
915
Steve Dower3e96f322015-03-02 08:01:10 -0800916/* Disable deprecation warnings about GetVersionEx as the result is
917 being passed straight through to the caller, who is responsible for
918 using it correctly. */
919#pragma warning(push)
920#pragma warning(disable:4996)
921
Mark Hammond8696ebc2002-10-08 02:44:31 +0000922static PyObject *
923sys_getwindowsversion(PyObject *self)
924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 PyObject *version;
926 int pos = 0;
927 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700928 DWORD realMajor, realMinor, realBuild;
929 HANDLE hKernel32;
930 wchar_t kernel32_path[MAX_PATH];
931 LPVOID verblock;
932 DWORD verblock_size;
933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 ver.dwOSVersionInfoSize = sizeof(ver);
935 if (!GetVersionEx((OSVERSIONINFO*) &ver))
936 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 version = PyStructSequence_New(&WindowsVersionType);
939 if (version == NULL)
940 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000942 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
943 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
944 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
945 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
946 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
948 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
949 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
950 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000951
Steve Dower74f4af72016-09-17 17:27:48 -0700952 realMajor = ver.dwMajorVersion;
953 realMinor = ver.dwMinorVersion;
954 realBuild = ver.dwBuildNumber;
955
956 // GetVersion will lie if we are running in a compatibility mode.
957 // We need to read the version info from a system file resource
958 // to accurately identify the OS version. If we fail for any reason,
959 // just return whatever GetVersion said.
960 hKernel32 = GetModuleHandleW(L"kernel32.dll");
961 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
962 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
963 (verblock = PyMem_RawMalloc(verblock_size))) {
964 VS_FIXEDFILEINFO *ffi;
965 UINT ffi_len;
966
967 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
968 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
969 realMajor = HIWORD(ffi->dwProductVersionMS);
970 realMinor = LOWORD(ffi->dwProductVersionMS);
971 realBuild = HIWORD(ffi->dwProductVersionLS);
972 }
973 PyMem_RawFree(verblock);
974 }
Segev Finer48fb7662017-06-04 20:52:27 +0300975 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
976 realMajor,
977 realMinor,
978 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700979 ));
980
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200981 if (PyErr_Occurred()) {
982 Py_DECREF(version);
983 return NULL;
984 }
Steve Dower74f4af72016-09-17 17:27:48 -0700985
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000986 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000987}
988
Steve Dower3e96f322015-03-02 08:01:10 -0800989#pragma warning(pop)
990
Steve Dowercc16be82016-09-08 10:35:16 -0700991PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
992"_enablelegacywindowsfsencoding()\n\
993\n\
994Changes the default filesystem encoding to mbcs:replace for consistency\n\
995with earlier versions of Python. See PEP 529 for more information.\n\
996\n\
997This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
998environment variable before launching Python."
999);
1000
1001static PyObject *
1002sys_enablelegacywindowsfsencoding(PyObject *self)
1003{
1004 Py_FileSystemDefaultEncoding = "mbcs";
1005 Py_FileSystemDefaultEncodeErrors = "replace";
1006 Py_RETURN_NONE;
1007}
1008
Mark Hammond8696ebc2002-10-08 02:44:31 +00001009#endif /* MS_WINDOWS */
1010
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001011#ifdef HAVE_DLOPEN
1012static PyObject *
1013sys_setdlopenflags(PyObject *self, PyObject *args)
1014{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 int new_val;
1016 PyThreadState *tstate = PyThreadState_GET();
1017 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1018 return NULL;
1019 if (!tstate)
1020 return NULL;
1021 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001022 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001023}
1024
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001025PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001026"setdlopenflags(n) -> None\n\
1027\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001028Set the flags used by the interpreter for dlopen calls, such as when the\n\
1029interpreter loads extension modules. Among other things, this will enable\n\
1030a lazy resolving of symbols when importing a module, if called as\n\
1031sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001032sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001033can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001034
1035static PyObject *
1036sys_getdlopenflags(PyObject *self, PyObject *args)
1037{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 PyThreadState *tstate = PyThreadState_GET();
1039 if (!tstate)
1040 return NULL;
1041 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001042}
1043
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001044PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001045"getdlopenflags() -> int\n\
1046\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001047Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001048The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001051
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001052#ifdef USE_MALLOPT
1053/* Link with -lmalloc (or -lmpc) on an SGI */
1054#include <malloc.h>
1055
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001056static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001057sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001059 int flag;
1060 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1061 return NULL;
1062 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001063 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001064}
1065#endif /* USE_MALLOPT */
1066
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001067size_t
1068_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001072 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 /* Make sure the type is initialized. float gets initialized late */
1075 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001076 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001077
Benjamin Petersonce798522012-01-22 11:24:29 -05001078 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 if (method == NULL) {
1080 if (!PyErr_Occurred())
1081 PyErr_Format(PyExc_TypeError,
1082 "Type %.100s doesn't define __sizeof__",
1083 Py_TYPE(o)->tp_name);
1084 }
1085 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001086 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 Py_DECREF(method);
1088 }
1089
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001090 if (res == NULL)
1091 return (size_t)-1;
1092
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001093 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001094 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001095 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001096 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001097
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001098 if (size < 0) {
1099 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1100 return (size_t)-1;
1101 }
1102
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001103 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001104 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001105 return ((size_t)size) + sizeof(PyGC_Head);
1106 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001107}
1108
1109static PyObject *
1110sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1111{
1112 static char *kwlist[] = {"object", "default", 0};
1113 size_t size;
1114 PyObject *o, *dflt = NULL;
1115
1116 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1117 kwlist, &o, &dflt))
1118 return NULL;
1119
1120 size = _PySys_GetSizeOf(o);
1121
1122 if (size == (size_t)-1 && PyErr_Occurred()) {
1123 /* Has a default value been given */
1124 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1125 PyErr_Clear();
1126 Py_INCREF(dflt);
1127 return dflt;
1128 }
1129 else
1130 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001132
1133 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001134}
1135
1136PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001137"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001138\n\
1139Return the size of object in bytes.");
1140
1141static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001142sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001145}
1146
Tim Peters4be93d02002-07-07 19:59:50 +00001147#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001148static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001149sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001150{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001152}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001153#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001154
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001155PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001156"getrefcount(object) -> integer\n\
1157\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001158Return the reference count of object. The count returned is generally\n\
1159one higher than you might expect, because it includes the (temporary)\n\
1160reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001161);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001162
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001163static PyObject *
1164sys_getallocatedblocks(PyObject *self)
1165{
1166 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1167}
1168
1169PyDoc_STRVAR(getallocatedblocks_doc,
1170"getallocatedblocks() -> integer\n\
1171\n\
1172Return the number of memory blocks currently allocated, regardless of their\n\
1173size."
1174);
1175
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001176#ifdef COUNT_ALLOCS
1177static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001178sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001183}
1184#endif
1185
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001186PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001187"_getframe([depth]) -> frameobject\n\
1188\n\
1189Return a frame object from the call stack. If optional integer depth is\n\
1190given, return the frame object that many calls below the top of the stack.\n\
1191If that is deeper than the call stack, ValueError is raised. The default\n\
1192for depth is zero, returning the frame at the top of the call stack.\n\
1193\n\
1194This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001195purposes only."
1196);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001197
1198static PyObject *
1199sys_getframe(PyObject *self, PyObject *args)
1200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 PyFrameObject *f = PyThreadState_GET()->frame;
1202 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1205 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 while (depth > 0 && f != NULL) {
1208 f = f->f_back;
1209 --depth;
1210 }
1211 if (f == NULL) {
1212 PyErr_SetString(PyExc_ValueError,
1213 "call stack is not deep enough");
1214 return NULL;
1215 }
1216 Py_INCREF(f);
1217 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001218}
1219
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001220PyDoc_STRVAR(current_frames_doc,
1221"_current_frames() -> dictionary\n\
1222\n\
1223Return a dictionary mapping each current thread T's thread id to T's\n\
1224current stack frame.\n\
1225\n\
1226This function should be used for specialized purposes only."
1227);
1228
1229static PyObject *
1230sys_current_frames(PyObject *self, PyObject *noargs)
1231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001233}
1234
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001235PyDoc_STRVAR(call_tracing_doc,
1236"call_tracing(func, args) -> object\n\
1237\n\
1238Call func(*args), while tracing is enabled. The tracing state is\n\
1239saved, and restored afterwards. This is intended to be called from\n\
1240a debugger from a checkpoint, to recursively debug some other code."
1241);
1242
1243static PyObject *
1244sys_call_tracing(PyObject *self, PyObject *args)
1245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001246 PyObject *func, *funcargs;
1247 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1248 return NULL;
1249 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001250}
1251
Jeremy Hylton985eba52003-02-05 23:13:00 +00001252PyDoc_STRVAR(callstats_doc,
1253"callstats() -> tuple of integers\n\
1254\n\
1255Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1256when Python was built. Otherwise, return None.\n\
1257\n\
1258When enabled, this function returns detailed, implementation-specific\n\
1259details about the number of function calls executed. The return value is\n\
1260a 11-tuple where the entries in the tuple are counts of:\n\
12610. all function calls\n\
12621. calls to PyFunction_Type objects\n\
12632. PyFunction calls that do not create an argument tuple\n\
12643. PyFunction calls that do not create an argument tuple\n\
1265 and bypass PyEval_EvalCodeEx()\n\
12664. PyMethod calls\n\
12675. PyMethod calls on bound methods\n\
12686. PyType calls\n\
12697. PyCFunction calls\n\
12708. generator calls\n\
12719. All other calls\n\
127210. Number of stack pops performed by call_function()"
1273);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001274
Victor Stinner048afd92016-11-28 11:59:04 +01001275static PyObject *
1276sys_callstats(PyObject *self)
1277{
1278 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1279 "sys.callstats() has been deprecated in Python 3.7 "
1280 "and will be removed in the future", 1) < 0) {
1281 return NULL;
1282 }
1283
1284 Py_RETURN_NONE;
1285}
1286
1287
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001288#ifdef __cplusplus
1289extern "C" {
1290#endif
1291
David Malcolm49526f42012-06-22 14:55:41 -04001292static PyObject *
1293sys_debugmallocstats(PyObject *self, PyObject *args)
1294{
1295#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001296 if (_PyMem_PymallocEnabled()) {
1297 _PyObject_DebugMallocStats(stderr);
1298 fputc('\n', stderr);
1299 }
David Malcolm49526f42012-06-22 14:55:41 -04001300#endif
1301 _PyObject_DebugTypeStats(stderr);
1302
1303 Py_RETURN_NONE;
1304}
1305PyDoc_STRVAR(debugmallocstats_doc,
1306"_debugmallocstats()\n\
1307\n\
1308Print summary info to stderr about the state of\n\
1309pymalloc's structures.\n\
1310\n\
1311In Py_DEBUG mode, also perform some expensive internal consistency\n\
1312checks.\n\
1313");
1314
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001315#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001316/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001317extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001318#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001319
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001320#ifdef DYNAMIC_EXECUTION_PROFILE
1321/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001322extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001323#endif
1324
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001325#ifdef __cplusplus
1326}
1327#endif
1328
Christian Heimes15ebc882008-02-04 18:48:49 +00001329static PyObject *
1330sys_clear_type_cache(PyObject* self, PyObject* args)
1331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 PyType_ClearCache();
1333 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001334}
1335
1336PyDoc_STRVAR(sys_clear_type_cache__doc__,
1337"_clear_type_cache() -> None\n\
1338Clear the internal type lookup cache.");
1339
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001340static PyObject *
1341sys_is_finalizing(PyObject* self, PyObject* args)
1342{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001343 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001344}
1345
1346PyDoc_STRVAR(is_finalizing_doc,
1347"is_finalizing()\n\
1348Return True if Python is exiting.");
1349
Christian Heimes15ebc882008-02-04 18:48:49 +00001350
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001351#ifdef ANDROID_API_LEVEL
1352PyDoc_STRVAR(getandroidapilevel_doc,
1353"getandroidapilevel()\n\
1354\n\
1355Return the build time API version of Android as an integer.");
1356
1357static PyObject *
1358sys_getandroidapilevel(PyObject *self)
1359{
1360 return PyLong_FromLong(ANDROID_API_LEVEL);
1361}
1362#endif /* ANDROID_API_LEVEL */
1363
1364
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001365static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001367 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 callstats_doc},
1369 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1370 sys_clear_type_cache__doc__},
1371 {"_current_frames", sys_current_frames, METH_NOARGS,
1372 current_frames_doc},
1373 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1374 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1375 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1376 {"exit", sys_exit, METH_VARARGS, exit_doc},
1377 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1378 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001379#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1381 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001382#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001383 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1384 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001385#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001387#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001388#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001390#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1392 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001393 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1394 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001395#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001397#endif
1398#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001400#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1402 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1403 getrecursionlimit_doc},
1404 {"getsizeof", (PyCFunction)sys_getsizeof,
1405 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1406 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001407#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1409 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001410 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1411 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001412#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001414 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001415#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001417#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1419 setcheckinterval_doc},
1420 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1421 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1423 setswitchinterval_doc},
1424 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1425 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001426#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1428 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001429#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1431 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1432 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1433 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 {"settrace", sys_settrace, METH_O, settrace_doc},
1435 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1436 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001437 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001438 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001439 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1440 set_coroutine_wrapper_doc},
1441 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1442 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001443 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001444 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1445 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1446 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001447#ifdef ANDROID_API_LEVEL
1448 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1449 getandroidapilevel_doc},
1450#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001452};
1453
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001454static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001455list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001456{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 PyObject *list = PyList_New(0);
1458 int i;
1459 if (list == NULL)
1460 return NULL;
1461 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1462 PyObject *name = PyUnicode_FromString(
1463 PyImport_Inittab[i].name);
1464 if (name == NULL)
1465 break;
1466 PyList_Append(list, name);
1467 Py_DECREF(name);
1468 }
1469 if (PyList_Sort(list) != 0) {
1470 Py_DECREF(list);
1471 list = NULL;
1472 }
1473 if (list) {
1474 PyObject *v = PyList_AsTuple(list);
1475 Py_DECREF(list);
1476 list = v;
1477 }
1478 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001479}
1480
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001481static PyObject *
1482get_warnoptions(void)
1483{
Eric Snow93c92f72017-09-13 23:46:04 -07001484 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001485 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1486 Py_XDECREF(warnoptions);
1487 warnoptions = PyList_New(0);
1488 if (warnoptions == NULL)
1489 return NULL;
Eric Snow93c92f72017-09-13 23:46:04 -07001490 PyThreadState_GET()->interp->warnoptions = warnoptions;
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001491 }
1492 return warnoptions;
1493}
Guido van Rossum23fff912000-12-15 22:02:05 +00001494
1495void
1496PySys_ResetWarnOptions(void)
1497{
Eric Snow93c92f72017-09-13 23:46:04 -07001498 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 if (warnoptions == NULL || !PyList_Check(warnoptions))
1500 return;
1501 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001502}
1503
1504void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001505PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001506{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001507 PyObject *warnoptions = get_warnoptions();
1508 if (warnoptions == NULL)
1509 return;
Victor Stinner9ca9c252010-05-19 16:53:30 +00001510 PyList_Append(warnoptions, unicode);
1511}
1512
1513void
1514PySys_AddWarnOption(const wchar_t *s)
1515{
1516 PyObject *unicode;
1517 unicode = PyUnicode_FromWideChar(s, -1);
1518 if (unicode == NULL)
1519 return;
1520 PySys_AddWarnOptionUnicode(unicode);
1521 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001522}
1523
Christian Heimes33fe8092008-04-13 13:53:33 +00001524int
1525PySys_HasWarnOptions(void)
1526{
Eric Snow93c92f72017-09-13 23:46:04 -07001527 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Christian Heimes33fe8092008-04-13 13:53:33 +00001528 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1529}
1530
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001531static PyObject *
1532get_xoptions(void)
1533{
Eric Snow93c92f72017-09-13 23:46:04 -07001534 PyObject *xoptions = PyThreadState_GET()->interp->xoptions;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001535 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1536 Py_XDECREF(xoptions);
1537 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001538 if (xoptions == NULL)
1539 return NULL;
Eric Snow93c92f72017-09-13 23:46:04 -07001540 PyThreadState_GET()->interp->xoptions = xoptions;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001541 }
1542 return xoptions;
1543}
1544
1545void
1546PySys_AddXOption(const wchar_t *s)
1547{
1548 PyObject *opts;
1549 PyObject *name = NULL, *value = NULL;
1550 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001551
1552 opts = get_xoptions();
1553 if (opts == NULL)
1554 goto error;
1555
1556 name_end = wcschr(s, L'=');
1557 if (!name_end) {
1558 name = PyUnicode_FromWideChar(s, -1);
1559 value = Py_True;
1560 Py_INCREF(value);
1561 }
1562 else {
1563 name = PyUnicode_FromWideChar(s, name_end - s);
1564 value = PyUnicode_FromWideChar(name_end + 1, -1);
1565 }
1566 if (name == NULL || value == NULL)
1567 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001568 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001569 Py_DECREF(name);
1570 Py_DECREF(value);
1571 return;
1572
1573error:
1574 Py_XDECREF(name);
1575 Py_XDECREF(value);
1576 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001577 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001578 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001579 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001580}
1581
1582PyObject *
1583PySys_GetXOptions(void)
1584{
1585 return get_xoptions();
1586}
1587
Guido van Rossum40552d01998-08-06 03:34:39 +00001588/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1589 Two literals concatenated works just fine. If you have a K&R compiler
1590 or other abomination that however *does* understand longer strings,
1591 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001592PyDoc_VAR(sys_doc) =
1593PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001594"This module provides access to some objects used or maintained by the\n\
1595interpreter and to functions that interact strongly with the interpreter.\n\
1596\n\
1597Dynamic objects:\n\
1598\n\
1599argv -- command line arguments; argv[0] is the script pathname if known\n\
1600path -- module search path; path[0] is the script directory, else ''\n\
1601modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001602\n\
1603displayhook -- called to show results in an interactive session\n\
1604excepthook -- called to handle any uncaught exception other than SystemExit\n\
1605 To customize printing in an interactive session or to install a custom\n\
1606 top-level exception handler, assign other functions to replace these.\n\
1607\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001608stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001609stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001610stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001611 By assigning other file objects (or objects that behave like files)\n\
1612 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001613\n\
1614last_type -- type of last uncaught exception\n\
1615last_value -- value of last uncaught exception\n\
1616last_traceback -- traceback of last uncaught exception\n\
1617 These three are only available in an interactive session after a\n\
1618 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001619"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001620)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001621/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001622PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001623"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001624Static objects:\n\
1625\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001626builtin_module_names -- tuple of module names built into this interpreter\n\
1627copyright -- copyright notice pertaining to this interpreter\n\
1628exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001629executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001630float_info -- a struct sequence with information about the float implementation.\n\
1631float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001632hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001633hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001634implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001635int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001636maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001637maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001638platform -- platform identifier\n\
1639prefix -- prefix used to find the Python library\n\
1640thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001641version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001642version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001643"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001644)
Steve Dowercc16be82016-09-08 10:35:16 -07001645#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001646/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001647PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001648"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001649winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001650"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001651)
Steve Dowercc16be82016-09-08 10:35:16 -07001652#endif /* MS_COREDLL */
1653#ifdef MS_WINDOWS
1654/* concatenating string here */
1655PyDoc_STR(
1656"_enablelegacywindowsfsencoding -- [Windows only] \n\
1657"
1658)
1659#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001660PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001661"__stdin__ -- the original stdin; don't touch!\n\
1662__stdout__ -- the original stdout; don't touch!\n\
1663__stderr__ -- the original stderr; don't touch!\n\
1664__displayhook__ -- the original displayhook; don't touch!\n\
1665__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001666\n\
1667Functions:\n\
1668\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001669displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001670excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001671exc_info() -- return thread-safe information about the current exception\n\
1672exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001673getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001674getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001675getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001676getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001677getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001678gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001679setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001680setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001681setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001682setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001683settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001684"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001685)
Fred Drakeccede592000-08-14 20:59:57 +00001686/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001687
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001688
1689PyDoc_STRVAR(flags__doc__,
1690"sys.flags\n\
1691\n\
1692Flags provided through command line arguments or environment vars.");
1693
1694static PyTypeObject FlagsType;
1695
1696static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 {"inspect", "-i"},
1699 {"interactive", "-i"},
1700 {"optimize", "-O or -OO"},
1701 {"dont_write_bytecode", "-B"},
1702 {"no_user_site", "-s"},
1703 {"no_site", "-S"},
1704 {"ignore_environment", "-E"},
1705 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 /* {"unbuffered", "-u"}, */
1707 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001708 {"bytes_warning", "-b"},
1709 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001710 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001711 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001713};
1714
1715static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 "sys.flags", /* name */
1717 flags__doc__, /* doc */
1718 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001719 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001720};
1721
1722static PyObject*
1723make_flags(void)
1724{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 int pos = 0;
1726 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 seq = PyStructSequence_New(&FlagsType);
1729 if (seq == NULL)
1730 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001731
1732#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 SetFlag(Py_InspectFlag);
1737 SetFlag(Py_InteractiveFlag);
1738 SetFlag(Py_OptimizeFlag);
1739 SetFlag(Py_DontWriteBytecodeFlag);
1740 SetFlag(Py_NoUserSiteDirectory);
1741 SetFlag(Py_NoSiteFlag);
1742 SetFlag(Py_IgnoreEnvironmentFlag);
1743 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 /* SetFlag(saw_unbuffered_flag); */
1745 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001746 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001747 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001748 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001749 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001750#undef SetFlag
1751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001753 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 return NULL;
1755 }
1756 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001757}
1758
Eric Smith0e5b5622009-02-06 01:32:42 +00001759PyDoc_STRVAR(version_info__doc__,
1760"sys.version_info\n\
1761\n\
1762Version information as a named tuple.");
1763
1764static PyTypeObject VersionInfoType;
1765
1766static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 {"major", "Major release number"},
1768 {"minor", "Minor release number"},
1769 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001770 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 {"serial", "Serial release number"},
1772 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001773};
1774
1775static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 "sys.version_info", /* name */
1777 version_info__doc__, /* doc */
1778 version_info_fields, /* fields */
1779 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001780};
1781
1782static PyObject *
1783make_version_info(void)
1784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 PyObject *version_info;
1786 char *s;
1787 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 version_info = PyStructSequence_New(&VersionInfoType);
1790 if (version_info == NULL) {
1791 return NULL;
1792 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 /*
1795 * These release level checks are mutually exclusive and cover
1796 * the field, so don't get too fancy with the pre-processor!
1797 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001798#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001800#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001802#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001804#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001806#endif
1807
1808#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001810#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001812
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 SetIntItem(PY_MAJOR_VERSION);
1814 SetIntItem(PY_MINOR_VERSION);
1815 SetIntItem(PY_MICRO_VERSION);
1816 SetStrItem(s);
1817 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001818#undef SetIntItem
1819#undef SetStrItem
1820
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 if (PyErr_Occurred()) {
1822 Py_CLEAR(version_info);
1823 return NULL;
1824 }
1825 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001826}
1827
Brett Cannon3adc7b72012-07-09 14:22:12 -04001828/* sys.implementation values */
1829#define NAME "cpython"
1830const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001831#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1832#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001833#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001834const char *_PySys_ImplCacheTag = TAG;
1835#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001836#undef MAJOR
1837#undef MINOR
1838#undef TAG
1839
Barry Warsaw409da152012-06-03 16:18:47 -04001840static PyObject *
1841make_impl_info(PyObject *version_info)
1842{
1843 int res;
1844 PyObject *impl_info, *value, *ns;
1845
1846 impl_info = PyDict_New();
1847 if (impl_info == NULL)
1848 return NULL;
1849
1850 /* populate the dict */
1851
Brett Cannon3adc7b72012-07-09 14:22:12 -04001852 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001853 if (value == NULL)
1854 goto error;
1855 res = PyDict_SetItemString(impl_info, "name", value);
1856 Py_DECREF(value);
1857 if (res < 0)
1858 goto error;
1859
Brett Cannon3adc7b72012-07-09 14:22:12 -04001860 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001861 if (value == NULL)
1862 goto error;
1863 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1864 Py_DECREF(value);
1865 if (res < 0)
1866 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001867
1868 res = PyDict_SetItemString(impl_info, "version", version_info);
1869 if (res < 0)
1870 goto error;
1871
1872 value = PyLong_FromLong(PY_VERSION_HEX);
1873 if (value == NULL)
1874 goto error;
1875 res = PyDict_SetItemString(impl_info, "hexversion", value);
1876 Py_DECREF(value);
1877 if (res < 0)
1878 goto error;
1879
doko@ubuntu.com55532312016-06-14 08:55:19 +02001880#ifdef MULTIARCH
1881 value = PyUnicode_FromString(MULTIARCH);
1882 if (value == NULL)
1883 goto error;
1884 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1885 Py_DECREF(value);
1886 if (res < 0)
1887 goto error;
1888#endif
1889
Barry Warsaw409da152012-06-03 16:18:47 -04001890 /* dict ready */
1891
1892 ns = _PyNamespace_New(impl_info);
1893 Py_DECREF(impl_info);
1894 return ns;
1895
1896error:
1897 Py_CLEAR(impl_info);
1898 return NULL;
1899}
1900
Martin v. Löwis1a214512008-06-11 05:26:20 +00001901static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001902 PyModuleDef_HEAD_INIT,
1903 "sys",
1904 sys_doc,
1905 -1, /* multiple "initialization" just copies the module dict. */
1906 sys_methods,
1907 NULL,
1908 NULL,
1909 NULL,
1910 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001911};
1912
Eric Snow6b4be192017-05-22 21:36:03 -07001913/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001914#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001915 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001916 PyObject *v = (value); \
1917 if (v == NULL) \
1918 return NULL; \
1919 res = PyDict_SetItemString(sysdict, key, v); \
1920 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001921 return NULL; \
1922 } \
1923 } while (0)
1924#define SET_SYS_FROM_STRING(key, value) \
1925 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001926 PyObject *v = (value); \
1927 if (v == NULL) \
1928 return NULL; \
1929 res = PyDict_SetItemString(sysdict, key, v); \
1930 Py_DECREF(v); \
1931 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001932 return NULL; \
1933 } \
1934 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001935
Eric Snow6b4be192017-05-22 21:36:03 -07001936PyObject *
1937_PySys_BeginInit(void)
1938{
1939 PyObject *m, *sysdict, *version_info;
1940 int res;
1941
Eric Snow93c92f72017-09-13 23:46:04 -07001942 m = PyModule_Create(&sysmodule);
Eric Snow6b4be192017-05-22 21:36:03 -07001943 if (m == NULL)
1944 return NULL;
1945 sysdict = PyModule_GetDict(m);
1946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001947 /* Check that stdin is not a directory
1948 Using shell redirection, you can redirect stdin to a directory,
1949 crashing the Python interpreter. Catch this common mistake here
1950 and output a useful error message. Note that under MS Windows,
1951 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001952#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001954 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001955 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 S_ISDIR(sb.st_mode)) {
1957 /* There's nothing more we can do. */
1958 /* Py_FatalError() will core dump, so just exit. */
1959 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1960 exit(EXIT_FAILURE);
1961 }
1962 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001963#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001964
Nick Coghland6009512014-11-20 21:39:37 +10001965 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001966
Victor Stinner8fea2522013-10-27 17:15:42 +01001967 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1968 PyDict_GetItemString(sysdict, "displayhook"));
1969 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1970 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 SET_SYS_FROM_STRING("version",
1972 PyUnicode_FromString(Py_GetVersion()));
1973 SET_SYS_FROM_STRING("hexversion",
1974 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001975 SET_SYS_FROM_STRING("_git",
1976 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1977 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001978 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 SET_SYS_FROM_STRING("api_version",
1980 PyLong_FromLong(PYTHON_API_VERSION));
1981 SET_SYS_FROM_STRING("copyright",
1982 PyUnicode_FromString(Py_GetCopyright()));
1983 SET_SYS_FROM_STRING("platform",
1984 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 SET_SYS_FROM_STRING("maxsize",
1986 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1987 SET_SYS_FROM_STRING("float_info",
1988 PyFloat_GetInfo());
1989 SET_SYS_FROM_STRING("int_info",
1990 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001991 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001992 if (Hash_InfoType.tp_name == NULL) {
1993 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1994 return NULL;
1995 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001996 SET_SYS_FROM_STRING("hash_info",
1997 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001999 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 SET_SYS_FROM_STRING("builtin_module_names",
2001 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002002#if PY_BIG_ENDIAN
2003 SET_SYS_FROM_STRING("byteorder",
2004 PyUnicode_FromString("big"));
2005#else
2006 SET_SYS_FROM_STRING("byteorder",
2007 PyUnicode_FromString("little"));
2008#endif
Fred Drake099325e2000-08-14 15:47:03 +00002009
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002010#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 SET_SYS_FROM_STRING("dllhandle",
2012 PyLong_FromVoidPtr(PyWin_DLLhModule));
2013 SET_SYS_FROM_STRING("winver",
2014 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002015#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002016#ifdef ABIFLAGS
2017 SET_SYS_FROM_STRING("abiflags",
2018 PyUnicode_FromString(ABIFLAGS));
2019#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002020
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002022 if (VersionInfoType.tp_name == NULL) {
2023 if (PyStructSequence_InitType2(&VersionInfoType,
2024 &version_info_desc) < 0)
2025 return NULL;
2026 }
Barry Warsaw409da152012-06-03 16:18:47 -04002027 version_info = make_version_info();
2028 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 /* prevent user from creating new instances */
2030 VersionInfoType.tp_init = NULL;
2031 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002032 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2033 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2034 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002035
Barry Warsaw409da152012-06-03 16:18:47 -04002036 /* implementation */
2037 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002040 if (FlagsType.tp_name == 0) {
2041 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2042 return NULL;
2043 }
Eric Snow6b4be192017-05-22 21:36:03 -07002044 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002046
2047#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 /* getwindowsversion */
2049 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002050 if (PyStructSequence_InitType2(&WindowsVersionType,
2051 &windows_version_desc) < 0)
2052 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 /* prevent user from creating new instances */
2054 WindowsVersionType.tp_init = NULL;
2055 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002056 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2057 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2058 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002059#endif
2060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002062#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 SET_SYS_FROM_STRING("float_repr_style",
2064 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002065#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 SET_SYS_FROM_STRING("float_repr_style",
2067 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002068#endif
2069
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002070 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002071
Yury Selivanoveb636452016-09-08 22:01:51 -07002072 /* initialize asyncgen_hooks */
2073 if (AsyncGenHooksType.tp_name == NULL) {
2074 if (PyStructSequence_InitType2(
2075 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2076 return NULL;
2077 }
2078 }
2079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 if (PyErr_Occurred())
2081 return NULL;
2082 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002083}
2084
Eric Snow6b4be192017-05-22 21:36:03 -07002085#undef SET_SYS_FROM_STRING
2086#undef SET_SYS_FROM_STRING_BORROW
2087
2088/* Updating the sys namespace, returning integer error codes */
Eric Snow93c92f72017-09-13 23:46:04 -07002089#define SET_SYS_FROM_STRING_BORROW_INT_RESULT(key, value) \
2090 do { \
2091 PyObject *v = (value); \
2092 if (v == NULL) \
2093 return -1; \
2094 res = PyDict_SetItemString(sysdict, key, v); \
2095 if (res < 0) { \
2096 return res; \
2097 } \
2098 } while (0)
Eric Snow6b4be192017-05-22 21:36:03 -07002099#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2100 do { \
2101 PyObject *v = (value); \
2102 if (v == NULL) \
2103 return -1; \
2104 res = PyDict_SetItemString(sysdict, key, v); \
2105 Py_DECREF(v); \
2106 if (res < 0) { \
2107 return res; \
2108 } \
2109 } while (0)
2110
2111int
2112_PySys_EndInit(PyObject *sysdict)
2113{
2114 int res;
2115
2116 /* Set flags to their final values */
2117 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2118 /* prevent user from creating new instances */
2119 FlagsType.tp_init = NULL;
2120 FlagsType.tp_new = NULL;
2121 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2122 if (res < 0) {
2123 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2124 return res;
2125 }
2126 PyErr_Clear();
2127 }
2128
2129 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2130 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2131 SET_SYS_FROM_STRING_INT_RESULT("executable",
2132 PyUnicode_FromWideChar(
2133 Py_GetProgramFullPath(), -1));
2134 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2135 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2136 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2137 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2138 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2139 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2140 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2141 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2142
Eric Snow93c92f72017-09-13 23:46:04 -07002143 PyObject *warnoptions = get_warnoptions();
2144 if (warnoptions == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002145 return -1;
Eric Snow93c92f72017-09-13 23:46:04 -07002146 SET_SYS_FROM_STRING_BORROW_INT_RESULT("warnoptions", warnoptions);
Victor Stinner865de272017-06-08 13:27:47 +02002147
Eric Snow93c92f72017-09-13 23:46:04 -07002148 PyObject *xoptions = get_xoptions();
2149 if (xoptions == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002150 return -1;
Eric Snow93c92f72017-09-13 23:46:04 -07002151 SET_SYS_FROM_STRING_BORROW_INT_RESULT("_xoptions", xoptions);
Eric Snow6b4be192017-05-22 21:36:03 -07002152
2153 if (PyErr_Occurred())
2154 return -1;
2155 return 0;
2156}
2157
2158#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow93c92f72017-09-13 23:46:04 -07002159#undef SET_SYS_FROM_STRING_BORROW_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002160
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002161static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002162makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 int i, n;
2165 const wchar_t *p;
2166 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 n = 1;
2169 p = path;
2170 while ((p = wcschr(p, delim)) != NULL) {
2171 n++;
2172 p++;
2173 }
2174 v = PyList_New(n);
2175 if (v == NULL)
2176 return NULL;
2177 for (i = 0; ; i++) {
2178 p = wcschr(path, delim);
2179 if (p == NULL)
2180 p = path + wcslen(path); /* End of string */
2181 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2182 if (w == NULL) {
2183 Py_DECREF(v);
2184 return NULL;
2185 }
2186 PyList_SetItem(v, i, w);
2187 if (*p == '\0')
2188 break;
2189 path = p+1;
2190 }
2191 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002192}
2193
2194void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002195PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 PyObject *v;
2198 if ((v = makepathobject(path, DELIM)) == NULL)
2199 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002200 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 Py_FatalError("can't assign sys.path");
2202 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002203}
2204
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002205static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002206makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002207{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002208 PyObject *av;
2209 if (argc <= 0 || argv == NULL) {
2210 /* Ensure at least one (empty) argument is seen */
2211 static wchar_t *empty_argv[1] = {L""};
2212 argv = empty_argv;
2213 argc = 1;
2214 }
2215 av = PyList_New(argc);
2216 if (av != NULL) {
2217 int i;
2218 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 if (v == NULL) {
2221 Py_DECREF(av);
2222 av = NULL;
2223 break;
2224 }
2225 PyList_SetItem(av, i, v);
2226 }
2227 }
2228 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002229}
2230
Nick Coghland26c18a2010-08-17 13:06:11 +00002231#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2232 (argc > 0 && argv0 != NULL && \
2233 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002234
2235static void
2236sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002237{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002238 wchar_t *argv0;
2239 wchar_t *p = NULL;
2240 Py_ssize_t n = 0;
2241 PyObject *a;
2242 PyObject *path;
2243#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002244 wchar_t link[MAXPATHLEN+1];
2245 wchar_t argv0copy[2*MAXPATHLEN+1];
2246 int nr = 0;
2247#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002248#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002250#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002252#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002253
Victor Stinnerbd303c12013-11-07 23:07:29 +01002254 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002255 if (path == NULL)
2256 return;
2257
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002258 argv0 = argv[0];
2259
2260#ifdef HAVE_READLINK
2261 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2262 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2263 if (nr > 0) {
2264 /* It's a symlink */
2265 link[nr] = '\0';
2266 if (link[0] == SEP)
2267 argv0 = link; /* Link to absolute path */
2268 else if (wcschr(link, SEP) == NULL)
2269 ; /* Link without path */
2270 else {
2271 /* Must join(dirname(argv0), link) */
2272 wchar_t *q = wcsrchr(argv0, SEP);
2273 if (q == NULL)
2274 argv0 = link; /* argv0 without path */
2275 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002276 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2277 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002278 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002279 wcsncpy(q+1, link, MAXPATHLEN);
2280 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002281 argv0 = argv0copy;
2282 }
2283 }
2284 }
2285#endif /* HAVE_READLINK */
2286#if SEP == '\\' /* Special case for MS filename syntax */
2287 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2288 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002289#if defined(MS_WINDOWS)
2290 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002291 wchar_t *ptemp;
2292 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002293 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002294 fullpath,
2295 &ptemp)) {
2296 argv0 = fullpath;
2297 }
2298#endif
2299 p = wcsrchr(argv0, SEP);
2300 /* Test for alternate separator */
2301 q = wcsrchr(p ? p : argv0, '/');
2302 if (q != NULL)
2303 p = q;
2304 if (p != NULL) {
2305 n = p + 1 - argv0;
2306 if (n > 1 && p[-1] != ':')
2307 n--; /* Drop trailing separator */
2308 }
2309 }
2310#else /* All other filename syntaxes */
2311 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2312#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002313 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002314 argv0 = fullpath;
2315 }
2316#endif
2317 p = wcsrchr(argv0, SEP);
2318 }
2319 if (p != NULL) {
2320 n = p + 1 - argv0;
2321#if SEP == '/' /* Special case for Unix filename syntax */
2322 if (n > 1)
2323 n--; /* Drop trailing separator */
2324#endif /* Unix */
2325 }
2326#endif /* All others */
2327 a = PyUnicode_FromWideChar(argv0, n);
2328 if (a == NULL)
2329 Py_FatalError("no mem for sys.path insertion");
2330 if (PyList_Insert(path, 0, a) < 0)
2331 Py_FatalError("sys.path.insert(0) failed");
2332 Py_DECREF(a);
2333}
2334
2335void
2336PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2337{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 if (av == NULL)
2340 Py_FatalError("no mem for sys.argv");
2341 if (PySys_SetObject("argv", av) != 0)
2342 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002344 if (updatepath)
2345 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002346}
Guido van Rossuma890e681998-05-12 14:59:24 +00002347
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002348void
2349PySys_SetArgv(int argc, wchar_t **argv)
2350{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002351 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002352}
2353
Victor Stinner14284c22010-04-23 12:02:30 +00002354/* Reimplementation of PyFile_WriteString() no calling indirectly
2355 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2356
2357static int
Victor Stinner79766632010-08-16 17:36:42 +00002358sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002359{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002360 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002362
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002363 if (file == NULL)
2364 return -1;
2365
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002366 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 if (writer == NULL)
2368 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002369
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002370 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 if (result == NULL) {
2372 goto error;
2373 } else {
2374 err = 0;
2375 goto finally;
2376 }
Victor Stinner14284c22010-04-23 12:02:30 +00002377
2378error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002380finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 Py_XDECREF(result);
2383 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002384}
2385
Victor Stinner79766632010-08-16 17:36:42 +00002386static int
2387sys_pyfile_write(const char *text, PyObject *file)
2388{
2389 PyObject *unicode = NULL;
2390 int err;
2391
2392 if (file == NULL)
2393 return -1;
2394
2395 unicode = PyUnicode_FromString(text);
2396 if (unicode == NULL)
2397 return -1;
2398
2399 err = sys_pyfile_write_unicode(unicode, file);
2400 Py_DECREF(unicode);
2401 return err;
2402}
Guido van Rossuma890e681998-05-12 14:59:24 +00002403
2404/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2405 Adapted from code submitted by Just van Rossum.
2406
2407 PySys_WriteStdout(format, ...)
2408 PySys_WriteStderr(format, ...)
2409
2410 The first function writes to sys.stdout; the second to sys.stderr. When
2411 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002412 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002413
Victor Stinner14284c22010-04-23 12:02:30 +00002414 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002415 signal handlers: they may raise a new exception whereas sys_write()
2416 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002417
Guido van Rossuma890e681998-05-12 14:59:24 +00002418 Both take a printf-style format string as their first argument followed
2419 by a variable length argument list determined by the format string.
2420
2421 *** WARNING ***
2422
2423 The format should limit the total size of the formatted output string to
2424 1000 bytes. In particular, this means that no unrestricted "%s" formats
2425 should occur; these should be limited using "%.<N>s where <N> is a
2426 decimal number calculated so that <N> plus the maximum size of other
2427 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2428 which can print hundreds of digits for very large numbers.
2429
2430 */
2431
2432static void
Victor Stinner09054372013-11-06 22:41:44 +01002433sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 PyObject *file;
2436 PyObject *error_type, *error_value, *error_traceback;
2437 char buffer[1001];
2438 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002441 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2443 if (sys_pyfile_write(buffer, file) != 0) {
2444 PyErr_Clear();
2445 fputs(buffer, fp);
2446 }
2447 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2448 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002449 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 }
2452 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002453}
2454
2455void
Guido van Rossuma890e681998-05-12 14:59:24 +00002456PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002459
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002461 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002463}
2464
2465void
Guido van Rossuma890e681998-05-12 14:59:24 +00002466PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002471 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002472 va_end(va);
2473}
2474
2475static void
Victor Stinner09054372013-11-06 22:41:44 +01002476sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002477{
2478 PyObject *file, *message;
2479 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002480 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002481
2482 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002483 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002484 message = PyUnicode_FromFormatV(format, va);
2485 if (message != NULL) {
2486 if (sys_pyfile_write_unicode(message, file) != 0) {
2487 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002488 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002489 if (utf8 != NULL)
2490 fputs(utf8, fp);
2491 }
2492 Py_DECREF(message);
2493 }
2494 PyErr_Restore(error_type, error_value, error_traceback);
2495}
2496
2497void
2498PySys_FormatStdout(const char *format, ...)
2499{
2500 va_list va;
2501
2502 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002503 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002504 va_end(va);
2505}
2506
2507void
2508PySys_FormatStderr(const char *format, ...)
2509{
2510 va_list va;
2511
2512 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002513 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002515}