blob: 3ecd7fca54ab8d04fbfedceef6b01f30da14d08b [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;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100163 PyObject *builtins;
164 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000165 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000166
Eric Snow86b7afd2017-09-04 17:54:09 -0600167 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000168 if (builtins == NULL) {
169 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
170 return NULL;
171 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 /* Print value except if None */
174 /* After printing, also assign to '_' */
175 /* Before, set '_' to None to avoid recursion */
176 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200177 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200179 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000180 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100181 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 if (outf == NULL || outf == Py_None) {
183 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
184 return NULL;
185 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000186 if (PyFile_WriteObject(o, outf, 0) != 0) {
187 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
188 /* repr(o) is not encodable to sys.stdout.encoding with
189 * sys.stdout.errors error handler (which is probably 'strict') */
190 PyErr_Clear();
191 err = sys_displayhook_unencodable(outf, o);
192 if (err)
193 return NULL;
194 }
195 else {
196 return NULL;
197 }
198 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100199 if (newline == NULL) {
200 newline = PyUnicode_FromString("\n");
201 if (newline == NULL)
202 return NULL;
203 }
204 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200206 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000207 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200208 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000209}
210
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000211PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000212"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000213"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000214"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000215);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000216
217static PyObject *
218sys_excepthook(PyObject* self, PyObject* args)
219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000220 PyObject *exc, *value, *tb;
221 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
222 return NULL;
223 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200224 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000225}
226
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000227PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000228"excepthook(exctype, value, traceback) -> None\n"
229"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000230"Handle an exception by displaying it with a traceback on sys.stderr.\n"
231);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000232
233static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000234sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 PyThreadState *tstate;
237 tstate = PyThreadState_GET();
238 return Py_BuildValue(
239 "(OOO)",
240 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
241 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
242 tstate->exc_traceback != NULL ?
243 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000244}
245
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000246PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000247"exc_info() -> (type, value, traceback)\n\
248\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000249Return information about the most recent exception caught by an except\n\
250clause in the current stack frame or in an older stack frame."
251);
252
253static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000254sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 PyObject *exit_code = 0;
257 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
258 return NULL;
259 /* Raise SystemExit so callers may catch it or clean up. */
260 PyErr_SetObject(PyExc_SystemExit, exit_code);
261 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262}
263
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000264PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000265"exit([status])\n\
266\n\
267Exit the interpreter by raising SystemExit(status).\n\
268If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300269If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000270If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000271exit status will be one (i.e., failure)."
272);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000273
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000274
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000275static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000276sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000279}
280
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000281PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000282"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000283\n\
284Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000285implementation."
286);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000287
288static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000289sys_getfilesystemencoding(PyObject *self)
290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (Py_FileSystemDefaultEncoding)
292 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200293 PyErr_SetString(PyExc_RuntimeError,
294 "filesystem encoding is not initialized");
295 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000296}
297
298PyDoc_STRVAR(getfilesystemencoding_doc,
299"getfilesystemencoding() -> string\n\
300\n\
301Return the encoding used to convert Unicode filenames in\n\
302operating system filenames."
303);
304
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000305static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700306sys_getfilesystemencodeerrors(PyObject *self)
307{
308 if (Py_FileSystemDefaultEncodeErrors)
309 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
310 PyErr_SetString(PyExc_RuntimeError,
311 "filesystem encoding is not initialized");
312 return NULL;
313}
314
315PyDoc_STRVAR(getfilesystemencodeerrors_doc,
316 "getfilesystemencodeerrors() -> string\n\
317\n\
318Return the error mode used to convert Unicode filenames in\n\
319operating system filenames."
320);
321
322static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000323sys_intern(PyObject *self, PyObject *args)
324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 PyObject *s;
326 if (!PyArg_ParseTuple(args, "U:intern", &s))
327 return NULL;
328 if (PyUnicode_CheckExact(s)) {
329 Py_INCREF(s);
330 PyUnicode_InternInPlace(&s);
331 return s;
332 }
333 else {
334 PyErr_Format(PyExc_TypeError,
335 "can't intern %.400s", s->ob_type->tp_name);
336 return NULL;
337 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000338}
339
340PyDoc_STRVAR(intern_doc,
341"intern(string) -> string\n\
342\n\
343``Intern'' the given string. This enters the string in the (global)\n\
344table of interned strings whose purpose is to speed up dictionary lookups.\n\
345Return the string itself or the previously interned string object with the\n\
346same value.");
347
348
Fred Drake5755ce62001-06-27 19:19:46 +0000349/*
350 * Cached interned string objects used for calling the profile and
351 * trace functions. Initialized by trace_init().
352 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000353static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000354
355static int
356trace_init(void)
357{
Nick Coghlan5a851672017-09-08 10:14:16 +1000358 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200359 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000360 "c_call", "c_exception", "c_return",
361 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200362 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000363 PyObject *name;
364 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000365 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 if (whatstrings[i] == NULL) {
367 name = PyUnicode_InternFromString(whatnames[i]);
368 if (name == NULL)
369 return -1;
370 whatstrings[i] = name;
371 }
372 }
373 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000374}
375
376
377static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100378call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200382 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000383
Victor Stinner78da82b2016-08-20 01:22:57 +0200384 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200386 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100387
Victor Stinner78da82b2016-08-20 01:22:57 +0200388 stack[0] = (PyObject *)frame;
389 stack[1] = whatstrings[what];
390 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200393 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000394
Victor Stinner78da82b2016-08-20 01:22:57 +0200395 PyFrame_LocalsToFast(frame, 1);
396 if (result == NULL) {
397 PyTraceBack_Here(frame);
398 }
399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000400 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000401}
402
403static int
404profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (arg == NULL)
410 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100411 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (result == NULL) {
413 PyEval_SetProfile(NULL, NULL);
414 return -1;
415 }
416 Py_DECREF(result);
417 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000418}
419
420static int
421trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000423{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 PyObject *callback;
425 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 if (what == PyTrace_CALL)
428 callback = self;
429 else
430 callback = frame->f_trace;
431 if (callback == NULL)
432 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100433 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (result == NULL) {
435 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200436 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 return -1;
438 }
439 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300440 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 }
442 else {
443 Py_DECREF(result);
444 }
445 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000446}
Fred Draked0838392001-06-16 21:02:31 +0000447
Fred Drake8b4d01d2000-05-09 19:57:01 +0000448static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000449sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (trace_init() == -1)
452 return NULL;
453 if (args == Py_None)
454 PyEval_SetTrace(NULL, NULL);
455 else
456 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200457 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000458}
459
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000460PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000461"settrace(function)\n\
462\n\
463Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000464function call. See the debugger chapter in the library manual."
465);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000466
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000467static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000468sys_gettrace(PyObject *self, PyObject *args)
469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyThreadState *tstate = PyThreadState_GET();
471 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (temp == NULL)
474 temp = Py_None;
475 Py_INCREF(temp);
476 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000477}
478
479PyDoc_STRVAR(gettrace_doc,
480"gettrace()\n\
481\n\
482Return the global debug tracing function set with sys.settrace.\n\
483See the debugger chapter in the library manual."
484);
485
486static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000487sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (trace_init() == -1)
490 return NULL;
491 if (args == Py_None)
492 PyEval_SetProfile(NULL, NULL);
493 else
494 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200495 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000496}
497
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000498PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000499"setprofile(function)\n\
500\n\
501Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000502and return. See the profiler chapter in the library manual."
503);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000504
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000505static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000506sys_getprofile(PyObject *self, PyObject *args)
507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyThreadState *tstate = PyThreadState_GET();
509 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (temp == NULL)
512 temp = Py_None;
513 Py_INCREF(temp);
514 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000515}
516
517PyDoc_STRVAR(getprofile_doc,
518"getprofile()\n\
519\n\
520Return the profiling function set with sys.setprofile.\n\
521See the profiler chapter in the library manual."
522);
523
524static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000525sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (PyErr_WarnEx(PyExc_DeprecationWarning,
528 "sys.getcheckinterval() and sys.setcheckinterval() "
529 "are deprecated. Use sys.setswitchinterval() "
530 "instead.", 1) < 0)
531 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600532 PyInterpreterState *interp = PyThreadState_GET()->interp;
533 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200535 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000536}
537
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000538PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000539"setcheckinterval(n)\n\
540\n\
541Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000542n instructions. This also affects how often thread switches occur."
543);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000544
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000545static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000546sys_getcheckinterval(PyObject *self, PyObject *args)
547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (PyErr_WarnEx(PyExc_DeprecationWarning,
549 "sys.getcheckinterval() and sys.setcheckinterval() "
550 "are deprecated. Use sys.getswitchinterval() "
551 "instead.", 1) < 0)
552 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600553 PyInterpreterState *interp = PyThreadState_GET()->interp;
554 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000555}
556
557PyDoc_STRVAR(getcheckinterval_doc,
558"getcheckinterval() -> current check interval; see setcheckinterval()."
559);
560
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000561static PyObject *
562sys_setswitchinterval(PyObject *self, PyObject *args)
563{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 double d;
565 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
566 return NULL;
567 if (d <= 0.0) {
568 PyErr_SetString(PyExc_ValueError,
569 "switch interval must be strictly positive");
570 return NULL;
571 }
572 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200573 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000574}
575
576PyDoc_STRVAR(setswitchinterval_doc,
577"setswitchinterval(n)\n\
578\n\
579Set the ideal thread switching delay inside the Python interpreter\n\
580The actual frequency of switching threads can be lower if the\n\
581interpreter executes long sequences of uninterruptible code\n\
582(this is implementation-specific and workload-dependent).\n\
583\n\
584The parameter must represent the desired switching delay in seconds\n\
585A typical value is 0.005 (5 milliseconds)."
586);
587
588static PyObject *
589sys_getswitchinterval(PyObject *self, PyObject *args)
590{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000592}
593
594PyDoc_STRVAR(getswitchinterval_doc,
595"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
596);
597
Tim Peterse5e065b2003-07-06 18:36:54 +0000598static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000599sys_setrecursionlimit(PyObject *self, PyObject *args)
600{
Victor Stinner50856d52015-10-13 00:11:21 +0200601 int new_limit, mark;
602 PyThreadState *tstate;
603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
605 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200606
607 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200609 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000610 return NULL;
611 }
Victor Stinner50856d52015-10-13 00:11:21 +0200612
613 /* Issue #25274: When the recursion depth hits the recursion limit in
614 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
615 set to 1 and a RecursionError is raised. The overflowed flag is reset
616 to 0 when the recursion depth goes below the low-water mark: see
617 Py_LeaveRecursiveCall().
618
619 Reject too low new limit if the current recursion depth is higher than
620 the new low-water mark. Otherwise it may not be possible anymore to
621 reset the overflowed flag to 0. */
622 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
623 tstate = PyThreadState_GET();
624 if (tstate->recursion_depth >= mark) {
625 PyErr_Format(PyExc_RecursionError,
626 "cannot set the recursion limit to %i at "
627 "the recursion depth %i: the limit is too low",
628 new_limit, tstate->recursion_depth);
629 return NULL;
630 }
631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200633 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000634}
635
Yury Selivanov75445082015-05-11 22:57:16 -0400636static PyObject *
637sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
638{
639 if (wrapper != Py_None) {
640 if (!PyCallable_Check(wrapper)) {
641 PyErr_Format(PyExc_TypeError,
642 "callable expected, got %.50s",
643 Py_TYPE(wrapper)->tp_name);
644 return NULL;
645 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400646 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400647 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400648 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400649 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400650 }
Yury Selivanov75445082015-05-11 22:57:16 -0400651 Py_RETURN_NONE;
652}
653
654PyDoc_STRVAR(set_coroutine_wrapper_doc,
655"set_coroutine_wrapper(wrapper)\n\
656\n\
657Set a wrapper for coroutine objects."
658);
659
660static PyObject *
661sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
662{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400663 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400664 if (wrapper == NULL) {
665 wrapper = Py_None;
666 }
667 Py_INCREF(wrapper);
668 return wrapper;
669}
670
671PyDoc_STRVAR(get_coroutine_wrapper_doc,
672"get_coroutine_wrapper()\n\
673\n\
674Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
675);
676
677
Yury Selivanoveb636452016-09-08 22:01:51 -0700678static PyTypeObject AsyncGenHooksType;
679
680PyDoc_STRVAR(asyncgen_hooks_doc,
681"asyncgen_hooks\n\
682\n\
683A struct sequence providing information about asynhronous\n\
684generators hooks. The attributes are read only.");
685
686static PyStructSequence_Field asyncgen_hooks_fields[] = {
687 {"firstiter", "Hook to intercept first iteration"},
688 {"finalizer", "Hook to intercept finalization"},
689 {0}
690};
691
692static PyStructSequence_Desc asyncgen_hooks_desc = {
693 "asyncgen_hooks", /* name */
694 asyncgen_hooks_doc, /* doc */
695 asyncgen_hooks_fields , /* fields */
696 2
697};
698
699
700static PyObject *
701sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
702{
703 static char *keywords[] = {"firstiter", "finalizer", NULL};
704 PyObject *firstiter = NULL;
705 PyObject *finalizer = NULL;
706
707 if (!PyArg_ParseTupleAndKeywords(
708 args, kw, "|OO", keywords,
709 &firstiter, &finalizer)) {
710 return NULL;
711 }
712
713 if (finalizer && finalizer != Py_None) {
714 if (!PyCallable_Check(finalizer)) {
715 PyErr_Format(PyExc_TypeError,
716 "callable finalizer expected, got %.50s",
717 Py_TYPE(finalizer)->tp_name);
718 return NULL;
719 }
720 _PyEval_SetAsyncGenFinalizer(finalizer);
721 }
722 else if (finalizer == Py_None) {
723 _PyEval_SetAsyncGenFinalizer(NULL);
724 }
725
726 if (firstiter && firstiter != Py_None) {
727 if (!PyCallable_Check(firstiter)) {
728 PyErr_Format(PyExc_TypeError,
729 "callable firstiter expected, got %.50s",
730 Py_TYPE(firstiter)->tp_name);
731 return NULL;
732 }
733 _PyEval_SetAsyncGenFirstiter(firstiter);
734 }
735 else if (firstiter == Py_None) {
736 _PyEval_SetAsyncGenFirstiter(NULL);
737 }
738
739 Py_RETURN_NONE;
740}
741
742PyDoc_STRVAR(set_asyncgen_hooks_doc,
743"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
744\n\
745Set a finalizer for async generators objects."
746);
747
748static PyObject *
749sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
750{
751 PyObject *res;
752 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
753 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
754
755 res = PyStructSequence_New(&AsyncGenHooksType);
756 if (res == NULL) {
757 return NULL;
758 }
759
760 if (firstiter == NULL) {
761 firstiter = Py_None;
762 }
763
764 if (finalizer == NULL) {
765 finalizer = Py_None;
766 }
767
768 Py_INCREF(firstiter);
769 PyStructSequence_SET_ITEM(res, 0, firstiter);
770
771 Py_INCREF(finalizer);
772 PyStructSequence_SET_ITEM(res, 1, finalizer);
773
774 return res;
775}
776
777PyDoc_STRVAR(get_asyncgen_hooks_doc,
778"get_asyncgen_hooks()\n\
779\n\
780Return a namedtuple of installed asynchronous generators hooks \
781(firstiter, finalizer)."
782);
783
784
Mark Dickinsondc787d22010-05-23 13:33:13 +0000785static PyTypeObject Hash_InfoType;
786
787PyDoc_STRVAR(hash_info_doc,
788"hash_info\n\
789\n\
790A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100791hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000792
793static PyStructSequence_Field hash_info_fields[] = {
794 {"width", "width of the type used for hashing, in bits"},
795 {"modulus", "prime number giving the modulus on which the hash "
796 "function is based"},
797 {"inf", "value to be used for hash of a positive infinity"},
798 {"nan", "value to be used for hash of a nan"},
799 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100800 {"algorithm", "name of the algorithm for hashing of str, bytes and "
801 "memoryviews"},
802 {"hash_bits", "internal output size of hash algorithm"},
803 {"seed_bits", "seed size of hash algorithm"},
804 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000805 {NULL, NULL}
806};
807
808static PyStructSequence_Desc hash_info_desc = {
809 "sys.hash_info",
810 hash_info_doc,
811 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100812 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000813};
814
Matthias Klosed885e952010-07-06 10:53:30 +0000815static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000816get_hash_info(void)
817{
818 PyObject *hash_info;
819 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100820 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000821 hash_info = PyStructSequence_New(&Hash_InfoType);
822 if (hash_info == NULL)
823 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100824 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000825 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000826 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000827 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000828 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000829 PyStructSequence_SET_ITEM(hash_info, field++,
830 PyLong_FromLong(_PyHASH_INF));
831 PyStructSequence_SET_ITEM(hash_info, field++,
832 PyLong_FromLong(_PyHASH_NAN));
833 PyStructSequence_SET_ITEM(hash_info, field++,
834 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100835 PyStructSequence_SET_ITEM(hash_info, field++,
836 PyUnicode_FromString(hashfunc->name));
837 PyStructSequence_SET_ITEM(hash_info, field++,
838 PyLong_FromLong(hashfunc->hash_bits));
839 PyStructSequence_SET_ITEM(hash_info, field++,
840 PyLong_FromLong(hashfunc->seed_bits));
841 PyStructSequence_SET_ITEM(hash_info, field++,
842 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000843 if (PyErr_Occurred()) {
844 Py_CLEAR(hash_info);
845 return NULL;
846 }
847 return hash_info;
848}
849
850
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000851PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000852"setrecursionlimit(n)\n\
853\n\
854Set the maximum depth of the Python interpreter stack to n. This\n\
855limit prevents infinite recursion from causing an overflow of the C\n\
856stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000857dependent."
858);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000859
860static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000861sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000862{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000864}
865
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000866PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000867"getrecursionlimit()\n\
868\n\
869Return the current value of the recursion limit, the maximum depth\n\
870of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000871recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000872);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000873
Mark Hammond8696ebc2002-10-08 02:44:31 +0000874#ifdef MS_WINDOWS
875PyDoc_STRVAR(getwindowsversion_doc,
876"getwindowsversion()\n\
877\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000878Return information about the running version of Windows as a named tuple.\n\
879The members are named: major, minor, build, platform, service_pack,\n\
880service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200881backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700882All elements are numbers, except service_pack and platform_type which are\n\
883strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
884Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
885server. Platform_version is a 3-tuple containing a version number that is\n\
886intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000887);
888
Eric Smithf7bb5782010-01-27 00:44:57 +0000889static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
890
891static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 {"major", "Major version number"},
893 {"minor", "Minor version number"},
894 {"build", "Build number"},
895 {"platform", "Operating system platform"},
896 {"service_pack", "Latest Service Pack installed on the system"},
897 {"service_pack_major", "Service Pack major version number"},
898 {"service_pack_minor", "Service Pack minor version number"},
899 {"suite_mask", "Bit mask identifying available product suites"},
900 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700901 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000902 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000903};
904
905static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 "sys.getwindowsversion", /* name */
907 getwindowsversion_doc, /* doc */
908 windows_version_fields, /* fields */
909 5 /* For backward compatibility,
910 only the first 5 items are accessible
911 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000912};
913
Steve Dower3e96f322015-03-02 08:01:10 -0800914/* Disable deprecation warnings about GetVersionEx as the result is
915 being passed straight through to the caller, who is responsible for
916 using it correctly. */
917#pragma warning(push)
918#pragma warning(disable:4996)
919
Mark Hammond8696ebc2002-10-08 02:44:31 +0000920static PyObject *
921sys_getwindowsversion(PyObject *self)
922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000923 PyObject *version;
924 int pos = 0;
925 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700926 DWORD realMajor, realMinor, realBuild;
927 HANDLE hKernel32;
928 wchar_t kernel32_path[MAX_PATH];
929 LPVOID verblock;
930 DWORD verblock_size;
931
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 ver.dwOSVersionInfoSize = sizeof(ver);
933 if (!GetVersionEx((OSVERSIONINFO*) &ver))
934 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 version = PyStructSequence_New(&WindowsVersionType);
937 if (version == NULL)
938 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
941 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
942 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
943 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
944 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
945 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
946 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
948 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000949
Steve Dower74f4af72016-09-17 17:27:48 -0700950 realMajor = ver.dwMajorVersion;
951 realMinor = ver.dwMinorVersion;
952 realBuild = ver.dwBuildNumber;
953
954 // GetVersion will lie if we are running in a compatibility mode.
955 // We need to read the version info from a system file resource
956 // to accurately identify the OS version. If we fail for any reason,
957 // just return whatever GetVersion said.
958 hKernel32 = GetModuleHandleW(L"kernel32.dll");
959 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
960 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
961 (verblock = PyMem_RawMalloc(verblock_size))) {
962 VS_FIXEDFILEINFO *ffi;
963 UINT ffi_len;
964
965 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
966 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
967 realMajor = HIWORD(ffi->dwProductVersionMS);
968 realMinor = LOWORD(ffi->dwProductVersionMS);
969 realBuild = HIWORD(ffi->dwProductVersionLS);
970 }
971 PyMem_RawFree(verblock);
972 }
Segev Finer48fb7662017-06-04 20:52:27 +0300973 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
974 realMajor,
975 realMinor,
976 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700977 ));
978
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200979 if (PyErr_Occurred()) {
980 Py_DECREF(version);
981 return NULL;
982 }
Steve Dower74f4af72016-09-17 17:27:48 -0700983
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000985}
986
Steve Dower3e96f322015-03-02 08:01:10 -0800987#pragma warning(pop)
988
Steve Dowercc16be82016-09-08 10:35:16 -0700989PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
990"_enablelegacywindowsfsencoding()\n\
991\n\
992Changes the default filesystem encoding to mbcs:replace for consistency\n\
993with earlier versions of Python. See PEP 529 for more information.\n\
994\n\
995This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
996environment variable before launching Python."
997);
998
999static PyObject *
1000sys_enablelegacywindowsfsencoding(PyObject *self)
1001{
1002 Py_FileSystemDefaultEncoding = "mbcs";
1003 Py_FileSystemDefaultEncodeErrors = "replace";
1004 Py_RETURN_NONE;
1005}
1006
Mark Hammond8696ebc2002-10-08 02:44:31 +00001007#endif /* MS_WINDOWS */
1008
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001009#ifdef HAVE_DLOPEN
1010static PyObject *
1011sys_setdlopenflags(PyObject *self, PyObject *args)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 int new_val;
1014 PyThreadState *tstate = PyThreadState_GET();
1015 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1016 return NULL;
1017 if (!tstate)
1018 return NULL;
1019 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001020 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001021}
1022
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001023PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001024"setdlopenflags(n) -> None\n\
1025\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001026Set the flags used by the interpreter for dlopen calls, such as when the\n\
1027interpreter loads extension modules. Among other things, this will enable\n\
1028a lazy resolving of symbols when importing a module, if called as\n\
1029sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001030sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001031can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001032
1033static PyObject *
1034sys_getdlopenflags(PyObject *self, PyObject *args)
1035{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 PyThreadState *tstate = PyThreadState_GET();
1037 if (!tstate)
1038 return NULL;
1039 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001040}
1041
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001042PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001043"getdlopenflags() -> int\n\
1044\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001045Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001046The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001049
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001050#ifdef USE_MALLOPT
1051/* Link with -lmalloc (or -lmpc) on an SGI */
1052#include <malloc.h>
1053
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001054static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001055sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001056{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 int flag;
1058 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1059 return NULL;
1060 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001061 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001062}
1063#endif /* USE_MALLOPT */
1064
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001065size_t
1066_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001067{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001070 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 /* Make sure the type is initialized. float gets initialized late */
1073 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001074 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001075
Benjamin Petersonce798522012-01-22 11:24:29 -05001076 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 if (method == NULL) {
1078 if (!PyErr_Occurred())
1079 PyErr_Format(PyExc_TypeError,
1080 "Type %.100s doesn't define __sizeof__",
1081 Py_TYPE(o)->tp_name);
1082 }
1083 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001084 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 Py_DECREF(method);
1086 }
1087
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001088 if (res == NULL)
1089 return (size_t)-1;
1090
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001091 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001092 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001093 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001094 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001096 if (size < 0) {
1097 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1098 return (size_t)-1;
1099 }
1100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001102 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001103 return ((size_t)size) + sizeof(PyGC_Head);
1104 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001105}
1106
1107static PyObject *
1108sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1109{
1110 static char *kwlist[] = {"object", "default", 0};
1111 size_t size;
1112 PyObject *o, *dflt = NULL;
1113
1114 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1115 kwlist, &o, &dflt))
1116 return NULL;
1117
1118 size = _PySys_GetSizeOf(o);
1119
1120 if (size == (size_t)-1 && PyErr_Occurred()) {
1121 /* Has a default value been given */
1122 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1123 PyErr_Clear();
1124 Py_INCREF(dflt);
1125 return dflt;
1126 }
1127 else
1128 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001130
1131 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001132}
1133
1134PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001135"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001136\n\
1137Return the size of object in bytes.");
1138
1139static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001140sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001143}
1144
Tim Peters4be93d02002-07-07 19:59:50 +00001145#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001146static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001147sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001150}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001151#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001152
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001153PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001154"getrefcount(object) -> integer\n\
1155\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001156Return the reference count of object. The count returned is generally\n\
1157one higher than you might expect, because it includes the (temporary)\n\
1158reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001159);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001160
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001161static PyObject *
1162sys_getallocatedblocks(PyObject *self)
1163{
1164 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1165}
1166
1167PyDoc_STRVAR(getallocatedblocks_doc,
1168"getallocatedblocks() -> integer\n\
1169\n\
1170Return the number of memory blocks currently allocated, regardless of their\n\
1171size."
1172);
1173
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001174#ifdef COUNT_ALLOCS
1175static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001176sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001181}
1182#endif
1183
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001184PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001185"_getframe([depth]) -> frameobject\n\
1186\n\
1187Return a frame object from the call stack. If optional integer depth is\n\
1188given, return the frame object that many calls below the top of the stack.\n\
1189If that is deeper than the call stack, ValueError is raised. The default\n\
1190for depth is zero, returning the frame at the top of the call stack.\n\
1191\n\
1192This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001193purposes only."
1194);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001195
1196static PyObject *
1197sys_getframe(PyObject *self, PyObject *args)
1198{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyFrameObject *f = PyThreadState_GET()->frame;
1200 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1203 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001204
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001205 while (depth > 0 && f != NULL) {
1206 f = f->f_back;
1207 --depth;
1208 }
1209 if (f == NULL) {
1210 PyErr_SetString(PyExc_ValueError,
1211 "call stack is not deep enough");
1212 return NULL;
1213 }
1214 Py_INCREF(f);
1215 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001216}
1217
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001218PyDoc_STRVAR(current_frames_doc,
1219"_current_frames() -> dictionary\n\
1220\n\
1221Return a dictionary mapping each current thread T's thread id to T's\n\
1222current stack frame.\n\
1223\n\
1224This function should be used for specialized purposes only."
1225);
1226
1227static PyObject *
1228sys_current_frames(PyObject *self, PyObject *noargs)
1229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001231}
1232
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001233PyDoc_STRVAR(call_tracing_doc,
1234"call_tracing(func, args) -> object\n\
1235\n\
1236Call func(*args), while tracing is enabled. The tracing state is\n\
1237saved, and restored afterwards. This is intended to be called from\n\
1238a debugger from a checkpoint, to recursively debug some other code."
1239);
1240
1241static PyObject *
1242sys_call_tracing(PyObject *self, PyObject *args)
1243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 PyObject *func, *funcargs;
1245 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1246 return NULL;
1247 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001248}
1249
Jeremy Hylton985eba52003-02-05 23:13:00 +00001250PyDoc_STRVAR(callstats_doc,
1251"callstats() -> tuple of integers\n\
1252\n\
1253Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1254when Python was built. Otherwise, return None.\n\
1255\n\
1256When enabled, this function returns detailed, implementation-specific\n\
1257details about the number of function calls executed. The return value is\n\
1258a 11-tuple where the entries in the tuple are counts of:\n\
12590. all function calls\n\
12601. calls to PyFunction_Type objects\n\
12612. PyFunction calls that do not create an argument tuple\n\
12623. PyFunction calls that do not create an argument tuple\n\
1263 and bypass PyEval_EvalCodeEx()\n\
12644. PyMethod calls\n\
12655. PyMethod calls on bound methods\n\
12666. PyType calls\n\
12677. PyCFunction calls\n\
12688. generator calls\n\
12699. All other calls\n\
127010. Number of stack pops performed by call_function()"
1271);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001272
Victor Stinner048afd92016-11-28 11:59:04 +01001273static PyObject *
1274sys_callstats(PyObject *self)
1275{
1276 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1277 "sys.callstats() has been deprecated in Python 3.7 "
1278 "and will be removed in the future", 1) < 0) {
1279 return NULL;
1280 }
1281
1282 Py_RETURN_NONE;
1283}
1284
1285
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001286#ifdef __cplusplus
1287extern "C" {
1288#endif
1289
David Malcolm49526f42012-06-22 14:55:41 -04001290static PyObject *
1291sys_debugmallocstats(PyObject *self, PyObject *args)
1292{
1293#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001294 if (_PyMem_PymallocEnabled()) {
1295 _PyObject_DebugMallocStats(stderr);
1296 fputc('\n', stderr);
1297 }
David Malcolm49526f42012-06-22 14:55:41 -04001298#endif
1299 _PyObject_DebugTypeStats(stderr);
1300
1301 Py_RETURN_NONE;
1302}
1303PyDoc_STRVAR(debugmallocstats_doc,
1304"_debugmallocstats()\n\
1305\n\
1306Print summary info to stderr about the state of\n\
1307pymalloc's structures.\n\
1308\n\
1309In Py_DEBUG mode, also perform some expensive internal consistency\n\
1310checks.\n\
1311");
1312
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001313#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001314/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001315extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001316#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001317
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001318#ifdef DYNAMIC_EXECUTION_PROFILE
1319/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001320extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001321#endif
1322
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001323#ifdef __cplusplus
1324}
1325#endif
1326
Christian Heimes15ebc882008-02-04 18:48:49 +00001327static PyObject *
1328sys_clear_type_cache(PyObject* self, PyObject* args)
1329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 PyType_ClearCache();
1331 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001332}
1333
1334PyDoc_STRVAR(sys_clear_type_cache__doc__,
1335"_clear_type_cache() -> None\n\
1336Clear the internal type lookup cache.");
1337
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001338static PyObject *
1339sys_is_finalizing(PyObject* self, PyObject* args)
1340{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001341 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001342}
1343
1344PyDoc_STRVAR(is_finalizing_doc,
1345"is_finalizing()\n\
1346Return True if Python is exiting.");
1347
Christian Heimes15ebc882008-02-04 18:48:49 +00001348
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001349#ifdef ANDROID_API_LEVEL
1350PyDoc_STRVAR(getandroidapilevel_doc,
1351"getandroidapilevel()\n\
1352\n\
1353Return the build time API version of Android as an integer.");
1354
1355static PyObject *
1356sys_getandroidapilevel(PyObject *self)
1357{
1358 return PyLong_FromLong(ANDROID_API_LEVEL);
1359}
1360#endif /* ANDROID_API_LEVEL */
1361
1362
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001363static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001365 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001366 callstats_doc},
1367 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1368 sys_clear_type_cache__doc__},
1369 {"_current_frames", sys_current_frames, METH_NOARGS,
1370 current_frames_doc},
1371 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1372 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1373 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1374 {"exit", sys_exit, METH_VARARGS, exit_doc},
1375 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1376 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001377#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1379 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001380#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001381 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1382 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001383#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001385#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001386#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001388#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1390 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001391 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1392 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001393#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001395#endif
1396#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001398#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1400 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1401 getrecursionlimit_doc},
1402 {"getsizeof", (PyCFunction)sys_getsizeof,
1403 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1404 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001405#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1407 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001408 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1409 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001410#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001412 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001413#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001415#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1417 setcheckinterval_doc},
1418 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1419 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1421 setswitchinterval_doc},
1422 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1423 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001424#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1426 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001427#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1429 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1430 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1431 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 {"settrace", sys_settrace, METH_O, settrace_doc},
1433 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1434 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001435 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001436 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001437 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1438 set_coroutine_wrapper_doc},
1439 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1440 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001441 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001442 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1443 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1444 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001445#ifdef ANDROID_API_LEVEL
1446 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1447 getandroidapilevel_doc},
1448#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001449 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001450};
1451
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001452static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001453list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyObject *list = PyList_New(0);
1456 int i;
1457 if (list == NULL)
1458 return NULL;
1459 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1460 PyObject *name = PyUnicode_FromString(
1461 PyImport_Inittab[i].name);
1462 if (name == NULL)
1463 break;
1464 PyList_Append(list, name);
1465 Py_DECREF(name);
1466 }
1467 if (PyList_Sort(list) != 0) {
1468 Py_DECREF(list);
1469 list = NULL;
1470 }
1471 if (list) {
1472 PyObject *v = PyList_AsTuple(list);
1473 Py_DECREF(list);
1474 list = v;
1475 }
1476 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001477}
1478
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001479static PyObject *
1480get_warnoptions(void)
1481{
1482 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
1483 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1484 Py_XDECREF(warnoptions);
1485 warnoptions = PyList_New(0);
1486 if (warnoptions == NULL)
1487 return NULL;
1488 PyThreadState_GET()->interp->warnoptions = warnoptions;
1489 }
1490 return warnoptions;
1491}
Guido van Rossum23fff912000-12-15 22:02:05 +00001492
1493void
1494PySys_ResetWarnOptions(void)
1495{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001496 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 if (warnoptions == NULL || !PyList_Check(warnoptions))
1498 return;
1499 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001500}
1501
1502void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001503PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001504{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001505 PyObject *warnoptions = get_warnoptions();
1506 if (warnoptions == NULL)
1507 return;
Victor Stinner9ca9c252010-05-19 16:53:30 +00001508 PyList_Append(warnoptions, unicode);
1509}
1510
1511void
1512PySys_AddWarnOption(const wchar_t *s)
1513{
1514 PyObject *unicode;
1515 unicode = PyUnicode_FromWideChar(s, -1);
1516 if (unicode == NULL)
1517 return;
1518 PySys_AddWarnOptionUnicode(unicode);
1519 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001520}
1521
Christian Heimes33fe8092008-04-13 13:53:33 +00001522int
1523PySys_HasWarnOptions(void)
1524{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001525 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Christian Heimes33fe8092008-04-13 13:53:33 +00001526 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1527}
1528
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001529static PyObject *
1530get_xoptions(void)
1531{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001532 PyObject *xoptions = PyThreadState_GET()->interp->xoptions;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001533 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1534 Py_XDECREF(xoptions);
1535 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001536 if (xoptions == NULL)
1537 return NULL;
1538 PyThreadState_GET()->interp->xoptions = xoptions;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001539 }
1540 return xoptions;
1541}
1542
1543void
1544PySys_AddXOption(const wchar_t *s)
1545{
1546 PyObject *opts;
1547 PyObject *name = NULL, *value = NULL;
1548 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001549
1550 opts = get_xoptions();
1551 if (opts == NULL)
1552 goto error;
1553
1554 name_end = wcschr(s, L'=');
1555 if (!name_end) {
1556 name = PyUnicode_FromWideChar(s, -1);
1557 value = Py_True;
1558 Py_INCREF(value);
1559 }
1560 else {
1561 name = PyUnicode_FromWideChar(s, name_end - s);
1562 value = PyUnicode_FromWideChar(name_end + 1, -1);
1563 }
1564 if (name == NULL || value == NULL)
1565 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001566 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001567 Py_DECREF(name);
1568 Py_DECREF(value);
1569 return;
1570
1571error:
1572 Py_XDECREF(name);
1573 Py_XDECREF(value);
1574 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001575 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001576 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001577 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001578}
1579
1580PyObject *
1581PySys_GetXOptions(void)
1582{
1583 return get_xoptions();
1584}
1585
Guido van Rossum40552d01998-08-06 03:34:39 +00001586/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1587 Two literals concatenated works just fine. If you have a K&R compiler
1588 or other abomination that however *does* understand longer strings,
1589 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001590PyDoc_VAR(sys_doc) =
1591PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001592"This module provides access to some objects used or maintained by the\n\
1593interpreter and to functions that interact strongly with the interpreter.\n\
1594\n\
1595Dynamic objects:\n\
1596\n\
1597argv -- command line arguments; argv[0] is the script pathname if known\n\
1598path -- module search path; path[0] is the script directory, else ''\n\
1599modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001600\n\
1601displayhook -- called to show results in an interactive session\n\
1602excepthook -- called to handle any uncaught exception other than SystemExit\n\
1603 To customize printing in an interactive session or to install a custom\n\
1604 top-level exception handler, assign other functions to replace these.\n\
1605\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001606stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001607stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001608stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001609 By assigning other file objects (or objects that behave like files)\n\
1610 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001611\n\
1612last_type -- type of last uncaught exception\n\
1613last_value -- value of last uncaught exception\n\
1614last_traceback -- traceback of last uncaught exception\n\
1615 These three are only available in an interactive session after a\n\
1616 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001617"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001618)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001619/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001620PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001621"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001622Static objects:\n\
1623\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001624builtin_module_names -- tuple of module names built into this interpreter\n\
1625copyright -- copyright notice pertaining to this interpreter\n\
1626exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001627executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001628float_info -- a struct sequence with information about the float implementation.\n\
1629float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001630hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001631hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001632implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001633int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001634maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001635maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001636platform -- platform identifier\n\
1637prefix -- prefix used to find the Python library\n\
1638thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001639version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001640version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001641"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001642)
Steve Dowercc16be82016-09-08 10:35:16 -07001643#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001644/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001645PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001646"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001647winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001648"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001649)
Steve Dowercc16be82016-09-08 10:35:16 -07001650#endif /* MS_COREDLL */
1651#ifdef MS_WINDOWS
1652/* concatenating string here */
1653PyDoc_STR(
1654"_enablelegacywindowsfsencoding -- [Windows only] \n\
1655"
1656)
1657#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001658PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001659"__stdin__ -- the original stdin; don't touch!\n\
1660__stdout__ -- the original stdout; don't touch!\n\
1661__stderr__ -- the original stderr; don't touch!\n\
1662__displayhook__ -- the original displayhook; don't touch!\n\
1663__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001664\n\
1665Functions:\n\
1666\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001667displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001668excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001669exc_info() -- return thread-safe information about the current exception\n\
1670exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001671getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001672getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001673getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001674getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001675getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001676gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001677setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001678setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001679setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001680setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001681settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001682"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001683)
Fred Drakeccede592000-08-14 20:59:57 +00001684/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001685
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001686
1687PyDoc_STRVAR(flags__doc__,
1688"sys.flags\n\
1689\n\
1690Flags provided through command line arguments or environment vars.");
1691
1692static PyTypeObject FlagsType;
1693
1694static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 {"inspect", "-i"},
1697 {"interactive", "-i"},
1698 {"optimize", "-O or -OO"},
1699 {"dont_write_bytecode", "-B"},
1700 {"no_user_site", "-s"},
1701 {"no_site", "-S"},
1702 {"ignore_environment", "-E"},
1703 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 /* {"unbuffered", "-u"}, */
1705 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001706 {"bytes_warning", "-b"},
1707 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001708 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001709 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001711};
1712
1713static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 "sys.flags", /* name */
1715 flags__doc__, /* doc */
1716 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001717 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001718};
1719
1720static PyObject*
1721make_flags(void)
1722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 int pos = 0;
1724 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 seq = PyStructSequence_New(&FlagsType);
1727 if (seq == NULL)
1728 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001729
1730#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001733 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 SetFlag(Py_InspectFlag);
1735 SetFlag(Py_InteractiveFlag);
1736 SetFlag(Py_OptimizeFlag);
1737 SetFlag(Py_DontWriteBytecodeFlag);
1738 SetFlag(Py_NoUserSiteDirectory);
1739 SetFlag(Py_NoSiteFlag);
1740 SetFlag(Py_IgnoreEnvironmentFlag);
1741 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 /* SetFlag(saw_unbuffered_flag); */
1743 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001744 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001745 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001746 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001747 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001748#undef SetFlag
1749
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001751 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 return NULL;
1753 }
1754 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001755}
1756
Eric Smith0e5b5622009-02-06 01:32:42 +00001757PyDoc_STRVAR(version_info__doc__,
1758"sys.version_info\n\
1759\n\
1760Version information as a named tuple.");
1761
1762static PyTypeObject VersionInfoType;
1763
1764static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 {"major", "Major release number"},
1766 {"minor", "Minor release number"},
1767 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001768 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 {"serial", "Serial release number"},
1770 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001771};
1772
1773static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 "sys.version_info", /* name */
1775 version_info__doc__, /* doc */
1776 version_info_fields, /* fields */
1777 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001778};
1779
1780static PyObject *
1781make_version_info(void)
1782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyObject *version_info;
1784 char *s;
1785 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 version_info = PyStructSequence_New(&VersionInfoType);
1788 if (version_info == NULL) {
1789 return NULL;
1790 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 /*
1793 * These release level checks are mutually exclusive and cover
1794 * the field, so don't get too fancy with the pre-processor!
1795 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001796#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001798#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001800#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001802#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001804#endif
1805
1806#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001808#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 SetIntItem(PY_MAJOR_VERSION);
1812 SetIntItem(PY_MINOR_VERSION);
1813 SetIntItem(PY_MICRO_VERSION);
1814 SetStrItem(s);
1815 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001816#undef SetIntItem
1817#undef SetStrItem
1818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 if (PyErr_Occurred()) {
1820 Py_CLEAR(version_info);
1821 return NULL;
1822 }
1823 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001824}
1825
Brett Cannon3adc7b72012-07-09 14:22:12 -04001826/* sys.implementation values */
1827#define NAME "cpython"
1828const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001829#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1830#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001831#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001832const char *_PySys_ImplCacheTag = TAG;
1833#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001834#undef MAJOR
1835#undef MINOR
1836#undef TAG
1837
Barry Warsaw409da152012-06-03 16:18:47 -04001838static PyObject *
1839make_impl_info(PyObject *version_info)
1840{
1841 int res;
1842 PyObject *impl_info, *value, *ns;
1843
1844 impl_info = PyDict_New();
1845 if (impl_info == NULL)
1846 return NULL;
1847
1848 /* populate the dict */
1849
Brett Cannon3adc7b72012-07-09 14:22:12 -04001850 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001851 if (value == NULL)
1852 goto error;
1853 res = PyDict_SetItemString(impl_info, "name", value);
1854 Py_DECREF(value);
1855 if (res < 0)
1856 goto error;
1857
Brett Cannon3adc7b72012-07-09 14:22:12 -04001858 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001859 if (value == NULL)
1860 goto error;
1861 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1862 Py_DECREF(value);
1863 if (res < 0)
1864 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001865
1866 res = PyDict_SetItemString(impl_info, "version", version_info);
1867 if (res < 0)
1868 goto error;
1869
1870 value = PyLong_FromLong(PY_VERSION_HEX);
1871 if (value == NULL)
1872 goto error;
1873 res = PyDict_SetItemString(impl_info, "hexversion", value);
1874 Py_DECREF(value);
1875 if (res < 0)
1876 goto error;
1877
doko@ubuntu.com55532312016-06-14 08:55:19 +02001878#ifdef MULTIARCH
1879 value = PyUnicode_FromString(MULTIARCH);
1880 if (value == NULL)
1881 goto error;
1882 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1883 Py_DECREF(value);
1884 if (res < 0)
1885 goto error;
1886#endif
1887
Barry Warsaw409da152012-06-03 16:18:47 -04001888 /* dict ready */
1889
1890 ns = _PyNamespace_New(impl_info);
1891 Py_DECREF(impl_info);
1892 return ns;
1893
1894error:
1895 Py_CLEAR(impl_info);
1896 return NULL;
1897}
1898
Martin v. Löwis1a214512008-06-11 05:26:20 +00001899static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001900 PyModuleDef_HEAD_INIT,
1901 "sys",
1902 sys_doc,
1903 -1, /* multiple "initialization" just copies the module dict. */
1904 sys_methods,
1905 NULL,
1906 NULL,
1907 NULL,
1908 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001909};
1910
Eric Snow6b4be192017-05-22 21:36:03 -07001911/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001912#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001913 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001914 PyObject *v = (value); \
1915 if (v == NULL) \
1916 return NULL; \
1917 res = PyDict_SetItemString(sysdict, key, v); \
1918 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001919 return NULL; \
1920 } \
1921 } while (0)
1922#define SET_SYS_FROM_STRING(key, value) \
1923 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001924 PyObject *v = (value); \
1925 if (v == NULL) \
1926 return NULL; \
1927 res = PyDict_SetItemString(sysdict, key, v); \
1928 Py_DECREF(v); \
1929 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001930 return NULL; \
1931 } \
1932 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001933
Eric Snow6b4be192017-05-22 21:36:03 -07001934PyObject *
1935_PySys_BeginInit(void)
1936{
1937 PyObject *m, *sysdict, *version_info;
1938 int res;
1939
Eric Snow86b7afd2017-09-04 17:54:09 -06001940 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Eric Snow6b4be192017-05-22 21:36:03 -07001941 if (m == NULL)
1942 return NULL;
1943 sysdict = PyModule_GetDict(m);
1944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 /* Check that stdin is not a directory
1946 Using shell redirection, you can redirect stdin to a directory,
1947 crashing the Python interpreter. Catch this common mistake here
1948 and output a useful error message. Note that under MS Windows,
1949 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001950#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001951 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001952 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001953 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 S_ISDIR(sb.st_mode)) {
1955 /* There's nothing more we can do. */
1956 /* Py_FatalError() will core dump, so just exit. */
1957 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1958 exit(EXIT_FAILURE);
1959 }
1960 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001961#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001962
Nick Coghland6009512014-11-20 21:39:37 +10001963 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001964
Victor Stinner8fea2522013-10-27 17:15:42 +01001965 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1966 PyDict_GetItemString(sysdict, "displayhook"));
1967 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1968 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 SET_SYS_FROM_STRING("version",
1970 PyUnicode_FromString(Py_GetVersion()));
1971 SET_SYS_FROM_STRING("hexversion",
1972 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001973 SET_SYS_FROM_STRING("_git",
1974 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1975 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001976 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 SET_SYS_FROM_STRING("api_version",
1978 PyLong_FromLong(PYTHON_API_VERSION));
1979 SET_SYS_FROM_STRING("copyright",
1980 PyUnicode_FromString(Py_GetCopyright()));
1981 SET_SYS_FROM_STRING("platform",
1982 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 SET_SYS_FROM_STRING("maxsize",
1984 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1985 SET_SYS_FROM_STRING("float_info",
1986 PyFloat_GetInfo());
1987 SET_SYS_FROM_STRING("int_info",
1988 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001989 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001990 if (Hash_InfoType.tp_name == NULL) {
1991 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1992 return NULL;
1993 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001994 SET_SYS_FROM_STRING("hash_info",
1995 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001997 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001998 SET_SYS_FROM_STRING("builtin_module_names",
1999 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002000#if PY_BIG_ENDIAN
2001 SET_SYS_FROM_STRING("byteorder",
2002 PyUnicode_FromString("big"));
2003#else
2004 SET_SYS_FROM_STRING("byteorder",
2005 PyUnicode_FromString("little"));
2006#endif
Fred Drake099325e2000-08-14 15:47:03 +00002007
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002008#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 SET_SYS_FROM_STRING("dllhandle",
2010 PyLong_FromVoidPtr(PyWin_DLLhModule));
2011 SET_SYS_FROM_STRING("winver",
2012 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002013#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002014#ifdef ABIFLAGS
2015 SET_SYS_FROM_STRING("abiflags",
2016 PyUnicode_FromString(ABIFLAGS));
2017#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002018
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002020 if (VersionInfoType.tp_name == NULL) {
2021 if (PyStructSequence_InitType2(&VersionInfoType,
2022 &version_info_desc) < 0)
2023 return NULL;
2024 }
Barry Warsaw409da152012-06-03 16:18:47 -04002025 version_info = make_version_info();
2026 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* prevent user from creating new instances */
2028 VersionInfoType.tp_init = NULL;
2029 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002030 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2031 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2032 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002033
Barry Warsaw409da152012-06-03 16:18:47 -04002034 /* implementation */
2035 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002038 if (FlagsType.tp_name == 0) {
2039 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2040 return NULL;
2041 }
Eric Snow6b4be192017-05-22 21:36:03 -07002042 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002044
2045#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* getwindowsversion */
2047 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002048 if (PyStructSequence_InitType2(&WindowsVersionType,
2049 &windows_version_desc) < 0)
2050 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 /* prevent user from creating new instances */
2052 WindowsVersionType.tp_init = NULL;
2053 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002054 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2055 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2056 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002057#endif
2058
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002060#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 SET_SYS_FROM_STRING("float_repr_style",
2062 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002063#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 SET_SYS_FROM_STRING("float_repr_style",
2065 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002066#endif
2067
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002068 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002069
Yury Selivanoveb636452016-09-08 22:01:51 -07002070 /* initialize asyncgen_hooks */
2071 if (AsyncGenHooksType.tp_name == NULL) {
2072 if (PyStructSequence_InitType2(
2073 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2074 return NULL;
2075 }
2076 }
2077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 if (PyErr_Occurred())
2079 return NULL;
2080 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002081}
2082
Eric Snow6b4be192017-05-22 21:36:03 -07002083#undef SET_SYS_FROM_STRING
2084#undef SET_SYS_FROM_STRING_BORROW
2085
2086/* Updating the sys namespace, returning integer error codes */
2087#define SET_SYS_FROM_STRING_BORROW_INT_RESULT(key, value) \
2088 do { \
2089 PyObject *v = (value); \
2090 if (v == NULL) \
2091 return -1; \
2092 res = PyDict_SetItemString(sysdict, key, v); \
2093 if (res < 0) { \
2094 return res; \
2095 } \
2096 } while (0)
2097#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2098 do { \
2099 PyObject *v = (value); \
2100 if (v == NULL) \
2101 return -1; \
2102 res = PyDict_SetItemString(sysdict, key, v); \
2103 Py_DECREF(v); \
2104 if (res < 0) { \
2105 return res; \
2106 } \
2107 } while (0)
2108
2109int
2110_PySys_EndInit(PyObject *sysdict)
2111{
2112 int res;
2113
2114 /* Set flags to their final values */
2115 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2116 /* prevent user from creating new instances */
2117 FlagsType.tp_init = NULL;
2118 FlagsType.tp_new = NULL;
2119 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2120 if (res < 0) {
2121 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2122 return res;
2123 }
2124 PyErr_Clear();
2125 }
2126
2127 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2128 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2129 SET_SYS_FROM_STRING_INT_RESULT("executable",
2130 PyUnicode_FromWideChar(
2131 Py_GetProgramFullPath(), -1));
2132 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2133 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2134 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2135 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2136 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2137 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2138 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2139 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2140
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002141 PyObject *warnoptions = get_warnoptions();
2142 if (warnoptions == NULL)
2143 return -1;
2144 SET_SYS_FROM_STRING_BORROW_INT_RESULT("warnoptions", warnoptions);
Victor Stinner865de272017-06-08 13:27:47 +02002145
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002146 PyObject *xoptions = get_xoptions();
2147 if (xoptions == NULL)
2148 return -1;
2149 SET_SYS_FROM_STRING_BORROW_INT_RESULT("_xoptions", xoptions);
Eric Snow6b4be192017-05-22 21:36:03 -07002150
2151 if (PyErr_Occurred())
2152 return -1;
2153 return 0;
2154}
2155
2156#undef SET_SYS_FROM_STRING_INT_RESULT
2157#undef SET_SYS_FROM_STRING_BORROW_INT_RESULT
2158
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002159static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002160makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 int i, n;
2163 const wchar_t *p;
2164 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 n = 1;
2167 p = path;
2168 while ((p = wcschr(p, delim)) != NULL) {
2169 n++;
2170 p++;
2171 }
2172 v = PyList_New(n);
2173 if (v == NULL)
2174 return NULL;
2175 for (i = 0; ; i++) {
2176 p = wcschr(path, delim);
2177 if (p == NULL)
2178 p = path + wcslen(path); /* End of string */
2179 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2180 if (w == NULL) {
2181 Py_DECREF(v);
2182 return NULL;
2183 }
2184 PyList_SetItem(v, i, w);
2185 if (*p == '\0')
2186 break;
2187 path = p+1;
2188 }
2189 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002190}
2191
2192void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002193PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 PyObject *v;
2196 if ((v = makepathobject(path, DELIM)) == NULL)
2197 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002198 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 Py_FatalError("can't assign sys.path");
2200 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002201}
2202
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002203static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002204makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 PyObject *av;
2207 if (argc <= 0 || argv == NULL) {
2208 /* Ensure at least one (empty) argument is seen */
2209 static wchar_t *empty_argv[1] = {L""};
2210 argv = empty_argv;
2211 argc = 1;
2212 }
2213 av = PyList_New(argc);
2214 if (av != NULL) {
2215 int i;
2216 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 if (v == NULL) {
2219 Py_DECREF(av);
2220 av = NULL;
2221 break;
2222 }
2223 PyList_SetItem(av, i, v);
2224 }
2225 }
2226 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002227}
2228
Nick Coghland26c18a2010-08-17 13:06:11 +00002229#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2230 (argc > 0 && argv0 != NULL && \
2231 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002232
2233static void
2234sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002235{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002236 wchar_t *argv0;
2237 wchar_t *p = NULL;
2238 Py_ssize_t n = 0;
2239 PyObject *a;
2240 PyObject *path;
2241#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002242 wchar_t link[MAXPATHLEN+1];
2243 wchar_t argv0copy[2*MAXPATHLEN+1];
2244 int nr = 0;
2245#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002246#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002248#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002250#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002251
Victor Stinnerbd303c12013-11-07 23:07:29 +01002252 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002253 if (path == NULL)
2254 return;
2255
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002256 argv0 = argv[0];
2257
2258#ifdef HAVE_READLINK
2259 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2260 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2261 if (nr > 0) {
2262 /* It's a symlink */
2263 link[nr] = '\0';
2264 if (link[0] == SEP)
2265 argv0 = link; /* Link to absolute path */
2266 else if (wcschr(link, SEP) == NULL)
2267 ; /* Link without path */
2268 else {
2269 /* Must join(dirname(argv0), link) */
2270 wchar_t *q = wcsrchr(argv0, SEP);
2271 if (q == NULL)
2272 argv0 = link; /* argv0 without path */
2273 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002274 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2275 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002276 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002277 wcsncpy(q+1, link, MAXPATHLEN);
2278 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002279 argv0 = argv0copy;
2280 }
2281 }
2282 }
2283#endif /* HAVE_READLINK */
2284#if SEP == '\\' /* Special case for MS filename syntax */
2285 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2286 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002287#if defined(MS_WINDOWS)
2288 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002289 wchar_t *ptemp;
2290 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002291 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002292 fullpath,
2293 &ptemp)) {
2294 argv0 = fullpath;
2295 }
2296#endif
2297 p = wcsrchr(argv0, SEP);
2298 /* Test for alternate separator */
2299 q = wcsrchr(p ? p : argv0, '/');
2300 if (q != NULL)
2301 p = q;
2302 if (p != NULL) {
2303 n = p + 1 - argv0;
2304 if (n > 1 && p[-1] != ':')
2305 n--; /* Drop trailing separator */
2306 }
2307 }
2308#else /* All other filename syntaxes */
2309 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2310#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002311 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002312 argv0 = fullpath;
2313 }
2314#endif
2315 p = wcsrchr(argv0, SEP);
2316 }
2317 if (p != NULL) {
2318 n = p + 1 - argv0;
2319#if SEP == '/' /* Special case for Unix filename syntax */
2320 if (n > 1)
2321 n--; /* Drop trailing separator */
2322#endif /* Unix */
2323 }
2324#endif /* All others */
2325 a = PyUnicode_FromWideChar(argv0, n);
2326 if (a == NULL)
2327 Py_FatalError("no mem for sys.path insertion");
2328 if (PyList_Insert(path, 0, a) < 0)
2329 Py_FatalError("sys.path.insert(0) failed");
2330 Py_DECREF(a);
2331}
2332
2333void
2334PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2335{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 if (av == NULL)
2338 Py_FatalError("no mem for sys.argv");
2339 if (PySys_SetObject("argv", av) != 0)
2340 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002342 if (updatepath)
2343 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002344}
Guido van Rossuma890e681998-05-12 14:59:24 +00002345
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002346void
2347PySys_SetArgv(int argc, wchar_t **argv)
2348{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002349 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002350}
2351
Victor Stinner14284c22010-04-23 12:02:30 +00002352/* Reimplementation of PyFile_WriteString() no calling indirectly
2353 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2354
2355static int
Victor Stinner79766632010-08-16 17:36:42 +00002356sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002357{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002358 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002360
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002361 if (file == NULL)
2362 return -1;
2363
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002364 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 if (writer == NULL)
2366 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002367
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002368 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 if (result == NULL) {
2370 goto error;
2371 } else {
2372 err = 0;
2373 goto finally;
2374 }
Victor Stinner14284c22010-04-23 12:02:30 +00002375
2376error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002378finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 Py_XDECREF(result);
2381 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002382}
2383
Victor Stinner79766632010-08-16 17:36:42 +00002384static int
2385sys_pyfile_write(const char *text, PyObject *file)
2386{
2387 PyObject *unicode = NULL;
2388 int err;
2389
2390 if (file == NULL)
2391 return -1;
2392
2393 unicode = PyUnicode_FromString(text);
2394 if (unicode == NULL)
2395 return -1;
2396
2397 err = sys_pyfile_write_unicode(unicode, file);
2398 Py_DECREF(unicode);
2399 return err;
2400}
Guido van Rossuma890e681998-05-12 14:59:24 +00002401
2402/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2403 Adapted from code submitted by Just van Rossum.
2404
2405 PySys_WriteStdout(format, ...)
2406 PySys_WriteStderr(format, ...)
2407
2408 The first function writes to sys.stdout; the second to sys.stderr. When
2409 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002410 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002411
Victor Stinner14284c22010-04-23 12:02:30 +00002412 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002413 signal handlers: they may raise a new exception whereas sys_write()
2414 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002415
Guido van Rossuma890e681998-05-12 14:59:24 +00002416 Both take a printf-style format string as their first argument followed
2417 by a variable length argument list determined by the format string.
2418
2419 *** WARNING ***
2420
2421 The format should limit the total size of the formatted output string to
2422 1000 bytes. In particular, this means that no unrestricted "%s" formats
2423 should occur; these should be limited using "%.<N>s where <N> is a
2424 decimal number calculated so that <N> plus the maximum size of other
2425 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2426 which can print hundreds of digits for very large numbers.
2427
2428 */
2429
2430static void
Victor Stinner09054372013-11-06 22:41:44 +01002431sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 PyObject *file;
2434 PyObject *error_type, *error_value, *error_traceback;
2435 char buffer[1001];
2436 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002439 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2441 if (sys_pyfile_write(buffer, file) != 0) {
2442 PyErr_Clear();
2443 fputs(buffer, fp);
2444 }
2445 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2446 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002447 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 }
2450 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002451}
2452
2453void
Guido van Rossuma890e681998-05-12 14:59:24 +00002454PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002457
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002459 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002461}
2462
2463void
Guido van Rossuma890e681998-05-12 14:59:24 +00002464PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002465{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002469 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002470 va_end(va);
2471}
2472
2473static void
Victor Stinner09054372013-11-06 22:41:44 +01002474sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002475{
2476 PyObject *file, *message;
2477 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002478 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002479
2480 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002481 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002482 message = PyUnicode_FromFormatV(format, va);
2483 if (message != NULL) {
2484 if (sys_pyfile_write_unicode(message, file) != 0) {
2485 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002486 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002487 if (utf8 != NULL)
2488 fputs(utf8, fp);
2489 }
2490 Py_DECREF(message);
2491 }
2492 PyErr_Restore(error_type, error_value, error_traceback);
2493}
2494
2495void
2496PySys_FormatStdout(const char *format, ...)
2497{
2498 va_list va;
2499
2500 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002501 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002502 va_end(va);
2503}
2504
2505void
2506PySys_FormatStderr(const char *format, ...)
2507{
2508 va_list va;
2509
2510 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002511 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002513}