blob: 79068304ab77b0c00d5d7902d2d0abff487b1ff5 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020020#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossume2437a11992-03-23 18:20:18 +000022#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020023#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000024
Mark Hammond8696ebc2002-10-08 02:44:31 +000025#ifdef MS_WINDOWS
26#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000027#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000028#endif /* MS_WINDOWS */
29
Guido van Rossum9b38a141996-09-11 23:12:24 +000030#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000031extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000032/* A string loaded from the DLL at startup: */
33extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000034#endif
35
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000036#ifdef HAVE_LANGINFO_H
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000037#include <langinfo.h>
38#endif
39
Victor Stinnerbd303c12013-11-07 23:07:29 +010040_Py_IDENTIFIER(_);
41_Py_IDENTIFIER(__sizeof__);
42_Py_IDENTIFIER(buffer);
43_Py_IDENTIFIER(builtins);
44_Py_IDENTIFIER(encoding);
45_Py_IDENTIFIER(path);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
48_Py_IDENTIFIER(write);
49
Guido van Rossum65bf9f21997-04-29 18:33:38 +000050PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010051_PySys_GetObjectId(_Py_Identifier *key)
52{
53 PyThreadState *tstate = PyThreadState_GET();
54 PyObject *sd = tstate->interp->sysdict;
55 if (sd == NULL)
56 return NULL;
57 return _PyDict_GetItemId(sd, key);
58}
59
60PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000061PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyThreadState *tstate = PyThreadState_GET();
64 PyObject *sd = tstate->interp->sysdict;
65 if (sd == NULL)
66 return NULL;
67 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068}
69
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070int
Victor Stinnerd67bd452013-11-06 22:36:40 +010071_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
72{
73 PyThreadState *tstate = PyThreadState_GET();
74 PyObject *sd = tstate->interp->sysdict;
75 if (v == NULL) {
76 if (_PyDict_GetItemId(sd, key) == NULL)
77 return 0;
78 else
79 return _PyDict_DelItemId(sd, key);
80 }
81 else
82 return _PyDict_SetItemId(sd, key, v);
83}
84
85int
Neal Norwitzf3081322007-08-25 00:32:45 +000086PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 PyThreadState *tstate = PyThreadState_GET();
89 PyObject *sd = tstate->interp->sysdict;
90 if (v == NULL) {
91 if (PyDict_GetItemString(sd, name) == NULL)
92 return 0;
93 else
94 return PyDict_DelItemString(sd, name);
95 }
96 else
97 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098}
99
Victor Stinner13d49ee2010-12-04 17:24:33 +0000100/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
101 error handler. If sys.stdout has a buffer attribute, use
102 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
103 sys.stdout.write(redecoded).
104
105 Helper function for sys_displayhook(). */
106static int
107sys_displayhook_unencodable(PyObject *outf, PyObject *o)
108{
109 PyObject *stdout_encoding = NULL;
110 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200111 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000112 int ret;
113
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200114 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000115 if (stdout_encoding == NULL)
116 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200117 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000118 if (stdout_encoding_str == NULL)
119 goto error;
120
121 repr_str = PyObject_Repr(o);
122 if (repr_str == NULL)
123 goto error;
124 encoded = PyUnicode_AsEncodedString(repr_str,
125 stdout_encoding_str,
126 "backslashreplace");
127 Py_DECREF(repr_str);
128 if (encoded == NULL)
129 goto error;
130
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200131 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000132 if (buffer) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200133 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000134 Py_DECREF(buffer);
135 Py_DECREF(encoded);
136 if (result == NULL)
137 goto error;
138 Py_DECREF(result);
139 }
140 else {
141 PyErr_Clear();
142 escaped_str = PyUnicode_FromEncodedObject(encoded,
143 stdout_encoding_str,
144 "strict");
145 Py_DECREF(encoded);
146 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
147 Py_DECREF(escaped_str);
148 goto error;
149 }
150 Py_DECREF(escaped_str);
151 }
152 ret = 0;
153 goto finally;
154
155error:
156 ret = -1;
157finally:
158 Py_XDECREF(stdout_encoding);
159 return ret;
160}
161
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000162static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000163sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 PyObject *outf;
166 PyInterpreterState *interp = PyThreadState_GET()->interp;
167 PyObject *modules = interp->modules;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100168 PyObject *builtins;
169 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000170 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000171
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100172 builtins = _PyDict_GetItemId(modules, &PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 if (builtins == NULL) {
174 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
175 return NULL;
176 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* Print value except if None */
179 /* After printing, also assign to '_' */
180 /* Before, set '_' to None to avoid recursion */
181 if (o == Py_None) {
182 Py_INCREF(Py_None);
183 return Py_None;
184 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200185 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100187 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (outf == NULL || outf == Py_None) {
189 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
190 return NULL;
191 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000192 if (PyFile_WriteObject(o, outf, 0) != 0) {
193 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
194 /* repr(o) is not encodable to sys.stdout.encoding with
195 * sys.stdout.errors error handler (which is probably 'strict') */
196 PyErr_Clear();
197 err = sys_displayhook_unencodable(outf, o);
198 if (err)
199 return NULL;
200 }
201 else {
202 return NULL;
203 }
204 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100205 if (newline == NULL) {
206 newline = PyUnicode_FromString("\n");
207 if (newline == NULL)
208 return NULL;
209 }
210 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200212 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return NULL;
214 Py_INCREF(Py_None);
215 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000216}
217
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000218PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000219"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000220"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000221"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000222);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000223
224static PyObject *
225sys_excepthook(PyObject* self, PyObject* args)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 PyObject *exc, *value, *tb;
228 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
229 return NULL;
230 PyErr_Display(exc, value, tb);
231 Py_INCREF(Py_None);
232 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000233}
234
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000235PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000236"excepthook(exctype, value, traceback) -> None\n"
237"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000238"Handle an exception by displaying it with a traceback on sys.stderr.\n"
239);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000240
241static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000242sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 PyThreadState *tstate;
245 tstate = PyThreadState_GET();
246 return Py_BuildValue(
247 "(OOO)",
248 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
249 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
250 tstate->exc_traceback != NULL ?
251 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000252}
253
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000254PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000255"exc_info() -> (type, value, traceback)\n\
256\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000257Return information about the most recent exception caught by an except\n\
258clause in the current stack frame or in an older stack frame."
259);
260
261static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000262sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 PyObject *exit_code = 0;
265 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
266 return NULL;
267 /* Raise SystemExit so callers may catch it or clean up. */
268 PyErr_SetObject(PyExc_SystemExit, exit_code);
269 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270}
271
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000272PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000273"exit([status])\n\
274\n\
275Exit the interpreter by raising SystemExit(status).\n\
276If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300277If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000278If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000279exit status will be one (i.e., failure)."
280);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000281
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000282
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000283static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000284sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000287}
288
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000289PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000290"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000291\n\
292Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000293implementation."
294);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000295
296static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000297sys_getfilesystemencoding(PyObject *self)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (Py_FileSystemDefaultEncoding)
300 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200301 PyErr_SetString(PyExc_RuntimeError,
302 "filesystem encoding is not initialized");
303 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000304}
305
306PyDoc_STRVAR(getfilesystemencoding_doc,
307"getfilesystemencoding() -> string\n\
308\n\
309Return the encoding used to convert Unicode filenames in\n\
310operating system filenames."
311);
312
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000313static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700314sys_getfilesystemencodeerrors(PyObject *self)
315{
316 if (Py_FileSystemDefaultEncodeErrors)
317 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
318 PyErr_SetString(PyExc_RuntimeError,
319 "filesystem encoding is not initialized");
320 return NULL;
321}
322
323PyDoc_STRVAR(getfilesystemencodeerrors_doc,
324 "getfilesystemencodeerrors() -> string\n\
325\n\
326Return the error mode used to convert Unicode filenames in\n\
327operating system filenames."
328);
329
330static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000331sys_intern(PyObject *self, PyObject *args)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *s;
334 if (!PyArg_ParseTuple(args, "U:intern", &s))
335 return NULL;
336 if (PyUnicode_CheckExact(s)) {
337 Py_INCREF(s);
338 PyUnicode_InternInPlace(&s);
339 return s;
340 }
341 else {
342 PyErr_Format(PyExc_TypeError,
343 "can't intern %.400s", s->ob_type->tp_name);
344 return NULL;
345 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000346}
347
348PyDoc_STRVAR(intern_doc,
349"intern(string) -> string\n\
350\n\
351``Intern'' the given string. This enters the string in the (global)\n\
352table of interned strings whose purpose is to speed up dictionary lookups.\n\
353Return the string itself or the previously interned string object with the\n\
354same value.");
355
356
Fred Drake5755ce62001-06-27 19:19:46 +0000357/*
358 * Cached interned string objects used for calling the profile and
359 * trace functions. Initialized by trace_init().
360 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000361static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000362
363static int
364trace_init(void)
365{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200366 static const char * const whatnames[7] = {
367 "call", "exception", "line", "return",
368 "c_call", "c_exception", "c_return"
369 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *name;
371 int i;
372 for (i = 0; i < 7; ++i) {
373 if (whatstrings[i] == NULL) {
374 name = PyUnicode_InternFromString(whatnames[i]);
375 if (name == NULL)
376 return -1;
377 whatstrings[i] = name;
378 }
379 }
380 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000381}
382
383
384static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100385call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200389 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000390
Victor Stinner78da82b2016-08-20 01:22:57 +0200391 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200393 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100394
Victor Stinner78da82b2016-08-20 01:22:57 +0200395 stack[0] = (PyObject *)frame;
396 stack[1] = whatstrings[what];
397 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200400 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000401
Victor Stinner78da82b2016-08-20 01:22:57 +0200402 PyFrame_LocalsToFast(frame, 1);
403 if (result == NULL) {
404 PyTraceBack_Here(frame);
405 }
406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000408}
409
410static int
411profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (arg == NULL)
417 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100418 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (result == NULL) {
420 PyEval_SetProfile(NULL, NULL);
421 return -1;
422 }
423 Py_DECREF(result);
424 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000425}
426
427static int
428trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *callback;
432 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (what == PyTrace_CALL)
435 callback = self;
436 else
437 callback = frame->f_trace;
438 if (callback == NULL)
439 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100440 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (result == NULL) {
442 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200443 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return -1;
445 }
446 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300447 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 }
449 else {
450 Py_DECREF(result);
451 }
452 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000453}
Fred Draked0838392001-06-16 21:02:31 +0000454
Fred Drake8b4d01d2000-05-09 19:57:01 +0000455static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000456sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (trace_init() == -1)
459 return NULL;
460 if (args == Py_None)
461 PyEval_SetTrace(NULL, NULL);
462 else
463 PyEval_SetTrace(trace_trampoline, args);
464 Py_INCREF(Py_None);
465 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000466}
467
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000468PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000469"settrace(function)\n\
470\n\
471Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000472function call. See the debugger chapter in the library manual."
473);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000474
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000475static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000476sys_gettrace(PyObject *self, PyObject *args)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyThreadState *tstate = PyThreadState_GET();
479 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (temp == NULL)
482 temp = Py_None;
483 Py_INCREF(temp);
484 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000485}
486
487PyDoc_STRVAR(gettrace_doc,
488"gettrace()\n\
489\n\
490Return the global debug tracing function set with sys.settrace.\n\
491See the debugger chapter in the library manual."
492);
493
494static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000495sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (trace_init() == -1)
498 return NULL;
499 if (args == Py_None)
500 PyEval_SetProfile(NULL, NULL);
501 else
502 PyEval_SetProfile(profile_trampoline, args);
503 Py_INCREF(Py_None);
504 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000505}
506
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000507PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508"setprofile(function)\n\
509\n\
510Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000511and return. See the profiler chapter in the library manual."
512);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000513
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000514static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000515sys_getprofile(PyObject *self, PyObject *args)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyThreadState *tstate = PyThreadState_GET();
518 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (temp == NULL)
521 temp = Py_None;
522 Py_INCREF(temp);
523 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000524}
525
526PyDoc_STRVAR(getprofile_doc,
527"getprofile()\n\
528\n\
529Return the profiling function set with sys.setprofile.\n\
530See the profiler chapter in the library manual."
531);
532
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000533static int _check_interval = 100;
534
Christian Heimes9bd667a2008-01-20 15:14:11 +0000535static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (PyErr_WarnEx(PyExc_DeprecationWarning,
539 "sys.getcheckinterval() and sys.setcheckinterval() "
540 "are deprecated. Use sys.setswitchinterval() "
541 "instead.", 1) < 0)
542 return NULL;
543 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
544 return NULL;
545 Py_INCREF(Py_None);
546 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000547}
548
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000549PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000550"setcheckinterval(n)\n\
551\n\
552Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000553n instructions. This also affects how often thread switches occur."
554);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000555
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000556static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000557sys_getcheckinterval(PyObject *self, PyObject *args)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (PyErr_WarnEx(PyExc_DeprecationWarning,
560 "sys.getcheckinterval() and sys.setcheckinterval() "
561 "are deprecated. Use sys.getswitchinterval() "
562 "instead.", 1) < 0)
563 return NULL;
564 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000565}
566
567PyDoc_STRVAR(getcheckinterval_doc,
568"getcheckinterval() -> current check interval; see setcheckinterval()."
569);
570
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000571#ifdef WITH_THREAD
572static PyObject *
573sys_setswitchinterval(PyObject *self, PyObject *args)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double d;
576 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
577 return NULL;
578 if (d <= 0.0) {
579 PyErr_SetString(PyExc_ValueError,
580 "switch interval must be strictly positive");
581 return NULL;
582 }
583 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
584 Py_INCREF(Py_None);
585 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000586}
587
588PyDoc_STRVAR(setswitchinterval_doc,
589"setswitchinterval(n)\n\
590\n\
591Set the ideal thread switching delay inside the Python interpreter\n\
592The actual frequency of switching threads can be lower if the\n\
593interpreter executes long sequences of uninterruptible code\n\
594(this is implementation-specific and workload-dependent).\n\
595\n\
596The parameter must represent the desired switching delay in seconds\n\
597A typical value is 0.005 (5 milliseconds)."
598);
599
600static PyObject *
601sys_getswitchinterval(PyObject *self, PyObject *args)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000604}
605
606PyDoc_STRVAR(getswitchinterval_doc,
607"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
608);
609
610#endif /* WITH_THREAD */
611
Tim Peterse5e065b2003-07-06 18:36:54 +0000612static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000613sys_setrecursionlimit(PyObject *self, PyObject *args)
614{
Victor Stinner50856d52015-10-13 00:11:21 +0200615 int new_limit, mark;
616 PyThreadState *tstate;
617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
619 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200620
621 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000622 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200623 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 return NULL;
625 }
Victor Stinner50856d52015-10-13 00:11:21 +0200626
627 /* Issue #25274: When the recursion depth hits the recursion limit in
628 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
629 set to 1 and a RecursionError is raised. The overflowed flag is reset
630 to 0 when the recursion depth goes below the low-water mark: see
631 Py_LeaveRecursiveCall().
632
633 Reject too low new limit if the current recursion depth is higher than
634 the new low-water mark. Otherwise it may not be possible anymore to
635 reset the overflowed flag to 0. */
636 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
637 tstate = PyThreadState_GET();
638 if (tstate->recursion_depth >= mark) {
639 PyErr_Format(PyExc_RecursionError,
640 "cannot set the recursion limit to %i at "
641 "the recursion depth %i: the limit is too low",
642 new_limit, tstate->recursion_depth);
643 return NULL;
644 }
645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 Py_SetRecursionLimit(new_limit);
647 Py_INCREF(Py_None);
648 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000649}
650
Yury Selivanov75445082015-05-11 22:57:16 -0400651static PyObject *
652sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
653{
654 if (wrapper != Py_None) {
655 if (!PyCallable_Check(wrapper)) {
656 PyErr_Format(PyExc_TypeError,
657 "callable expected, got %.50s",
658 Py_TYPE(wrapper)->tp_name);
659 return NULL;
660 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400661 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400662 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400663 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400664 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400665 }
Yury Selivanov75445082015-05-11 22:57:16 -0400666 Py_RETURN_NONE;
667}
668
669PyDoc_STRVAR(set_coroutine_wrapper_doc,
670"set_coroutine_wrapper(wrapper)\n\
671\n\
672Set a wrapper for coroutine objects."
673);
674
675static PyObject *
676sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
677{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400678 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400679 if (wrapper == NULL) {
680 wrapper = Py_None;
681 }
682 Py_INCREF(wrapper);
683 return wrapper;
684}
685
686PyDoc_STRVAR(get_coroutine_wrapper_doc,
687"get_coroutine_wrapper()\n\
688\n\
689Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
690);
691
692
Yury Selivanoveb636452016-09-08 22:01:51 -0700693static PyTypeObject AsyncGenHooksType;
694
695PyDoc_STRVAR(asyncgen_hooks_doc,
696"asyncgen_hooks\n\
697\n\
698A struct sequence providing information about asynhronous\n\
699generators hooks. The attributes are read only.");
700
701static PyStructSequence_Field asyncgen_hooks_fields[] = {
702 {"firstiter", "Hook to intercept first iteration"},
703 {"finalizer", "Hook to intercept finalization"},
704 {0}
705};
706
707static PyStructSequence_Desc asyncgen_hooks_desc = {
708 "asyncgen_hooks", /* name */
709 asyncgen_hooks_doc, /* doc */
710 asyncgen_hooks_fields , /* fields */
711 2
712};
713
714
715static PyObject *
716sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
717{
718 static char *keywords[] = {"firstiter", "finalizer", NULL};
719 PyObject *firstiter = NULL;
720 PyObject *finalizer = NULL;
721
722 if (!PyArg_ParseTupleAndKeywords(
723 args, kw, "|OO", keywords,
724 &firstiter, &finalizer)) {
725 return NULL;
726 }
727
728 if (finalizer && finalizer != Py_None) {
729 if (!PyCallable_Check(finalizer)) {
730 PyErr_Format(PyExc_TypeError,
731 "callable finalizer expected, got %.50s",
732 Py_TYPE(finalizer)->tp_name);
733 return NULL;
734 }
735 _PyEval_SetAsyncGenFinalizer(finalizer);
736 }
737 else if (finalizer == Py_None) {
738 _PyEval_SetAsyncGenFinalizer(NULL);
739 }
740
741 if (firstiter && firstiter != Py_None) {
742 if (!PyCallable_Check(firstiter)) {
743 PyErr_Format(PyExc_TypeError,
744 "callable firstiter expected, got %.50s",
745 Py_TYPE(firstiter)->tp_name);
746 return NULL;
747 }
748 _PyEval_SetAsyncGenFirstiter(firstiter);
749 }
750 else if (firstiter == Py_None) {
751 _PyEval_SetAsyncGenFirstiter(NULL);
752 }
753
754 Py_RETURN_NONE;
755}
756
757PyDoc_STRVAR(set_asyncgen_hooks_doc,
758"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
759\n\
760Set a finalizer for async generators objects."
761);
762
763static PyObject *
764sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
765{
766 PyObject *res;
767 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
768 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
769
770 res = PyStructSequence_New(&AsyncGenHooksType);
771 if (res == NULL) {
772 return NULL;
773 }
774
775 if (firstiter == NULL) {
776 firstiter = Py_None;
777 }
778
779 if (finalizer == NULL) {
780 finalizer = Py_None;
781 }
782
783 Py_INCREF(firstiter);
784 PyStructSequence_SET_ITEM(res, 0, firstiter);
785
786 Py_INCREF(finalizer);
787 PyStructSequence_SET_ITEM(res, 1, finalizer);
788
789 return res;
790}
791
792PyDoc_STRVAR(get_asyncgen_hooks_doc,
793"get_asyncgen_hooks()\n\
794\n\
795Return a namedtuple of installed asynchronous generators hooks \
796(firstiter, finalizer)."
797);
798
799
Mark Dickinsondc787d22010-05-23 13:33:13 +0000800static PyTypeObject Hash_InfoType;
801
802PyDoc_STRVAR(hash_info_doc,
803"hash_info\n\
804\n\
805A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100806hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000807
808static PyStructSequence_Field hash_info_fields[] = {
809 {"width", "width of the type used for hashing, in bits"},
810 {"modulus", "prime number giving the modulus on which the hash "
811 "function is based"},
812 {"inf", "value to be used for hash of a positive infinity"},
813 {"nan", "value to be used for hash of a nan"},
814 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100815 {"algorithm", "name of the algorithm for hashing of str, bytes and "
816 "memoryviews"},
817 {"hash_bits", "internal output size of hash algorithm"},
818 {"seed_bits", "seed size of hash algorithm"},
819 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000820 {NULL, NULL}
821};
822
823static PyStructSequence_Desc hash_info_desc = {
824 "sys.hash_info",
825 hash_info_doc,
826 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100827 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000828};
829
Matthias Klosed885e952010-07-06 10:53:30 +0000830static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000831get_hash_info(void)
832{
833 PyObject *hash_info;
834 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100835 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000836 hash_info = PyStructSequence_New(&Hash_InfoType);
837 if (hash_info == NULL)
838 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100839 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000840 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000841 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000842 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000843 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000844 PyStructSequence_SET_ITEM(hash_info, field++,
845 PyLong_FromLong(_PyHASH_INF));
846 PyStructSequence_SET_ITEM(hash_info, field++,
847 PyLong_FromLong(_PyHASH_NAN));
848 PyStructSequence_SET_ITEM(hash_info, field++,
849 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100850 PyStructSequence_SET_ITEM(hash_info, field++,
851 PyUnicode_FromString(hashfunc->name));
852 PyStructSequence_SET_ITEM(hash_info, field++,
853 PyLong_FromLong(hashfunc->hash_bits));
854 PyStructSequence_SET_ITEM(hash_info, field++,
855 PyLong_FromLong(hashfunc->seed_bits));
856 PyStructSequence_SET_ITEM(hash_info, field++,
857 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000858 if (PyErr_Occurred()) {
859 Py_CLEAR(hash_info);
860 return NULL;
861 }
862 return hash_info;
863}
864
865
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000866PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000867"setrecursionlimit(n)\n\
868\n\
869Set the maximum depth of the Python interpreter stack to n. This\n\
870limit prevents infinite recursion from causing an overflow of the C\n\
871stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000872dependent."
873);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000874
875static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000876sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000879}
880
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000881PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000882"getrecursionlimit()\n\
883\n\
884Return the current value of the recursion limit, the maximum depth\n\
885of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000886recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000887);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000888
Mark Hammond8696ebc2002-10-08 02:44:31 +0000889#ifdef MS_WINDOWS
890PyDoc_STRVAR(getwindowsversion_doc,
891"getwindowsversion()\n\
892\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000893Return information about the running version of Windows as a named tuple.\n\
894The members are named: major, minor, build, platform, service_pack,\n\
895service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200896backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700897All elements are numbers, except service_pack and platform_type which are\n\
898strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
899Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
900server. Platform_version is a 3-tuple containing a version number that is\n\
901intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000902);
903
Eric Smithf7bb5782010-01-27 00:44:57 +0000904static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
905
906static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 {"major", "Major version number"},
908 {"minor", "Minor version number"},
909 {"build", "Build number"},
910 {"platform", "Operating system platform"},
911 {"service_pack", "Latest Service Pack installed on the system"},
912 {"service_pack_major", "Service Pack major version number"},
913 {"service_pack_minor", "Service Pack minor version number"},
914 {"suite_mask", "Bit mask identifying available product suites"},
915 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700916 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000917 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000918};
919
920static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 "sys.getwindowsversion", /* name */
922 getwindowsversion_doc, /* doc */
923 windows_version_fields, /* fields */
924 5 /* For backward compatibility,
925 only the first 5 items are accessible
926 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000927};
928
Steve Dower3e96f322015-03-02 08:01:10 -0800929/* Disable deprecation warnings about GetVersionEx as the result is
930 being passed straight through to the caller, who is responsible for
931 using it correctly. */
932#pragma warning(push)
933#pragma warning(disable:4996)
934
Mark Hammond8696ebc2002-10-08 02:44:31 +0000935static PyObject *
936sys_getwindowsversion(PyObject *self)
937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyObject *version;
939 int pos = 0;
940 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700941 DWORD realMajor, realMinor, realBuild;
942 HANDLE hKernel32;
943 wchar_t kernel32_path[MAX_PATH];
944 LPVOID verblock;
945 DWORD verblock_size;
946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 ver.dwOSVersionInfoSize = sizeof(ver);
948 if (!GetVersionEx((OSVERSIONINFO*) &ver))
949 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000950
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000951 version = PyStructSequence_New(&WindowsVersionType);
952 if (version == NULL)
953 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000954
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
956 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
957 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
958 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
959 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
960 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
961 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
962 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
963 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000964
Steve Dower74f4af72016-09-17 17:27:48 -0700965 realMajor = ver.dwMajorVersion;
966 realMinor = ver.dwMinorVersion;
967 realBuild = ver.dwBuildNumber;
968
969 // GetVersion will lie if we are running in a compatibility mode.
970 // We need to read the version info from a system file resource
971 // to accurately identify the OS version. If we fail for any reason,
972 // just return whatever GetVersion said.
973 hKernel32 = GetModuleHandleW(L"kernel32.dll");
974 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
975 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
976 (verblock = PyMem_RawMalloc(verblock_size))) {
977 VS_FIXEDFILEINFO *ffi;
978 UINT ffi_len;
979
980 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
981 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
982 realMajor = HIWORD(ffi->dwProductVersionMS);
983 realMinor = LOWORD(ffi->dwProductVersionMS);
984 realBuild = HIWORD(ffi->dwProductVersionLS);
985 }
986 PyMem_RawFree(verblock);
987 }
988 PyStructSequence_SET_ITEM(version, pos++, PyTuple_Pack(3,
989 PyLong_FromLong(realMajor),
990 PyLong_FromLong(realMinor),
991 PyLong_FromLong(realBuild)
992 ));
993
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200994 if (PyErr_Occurred()) {
995 Py_DECREF(version);
996 return NULL;
997 }
Steve Dower74f4af72016-09-17 17:27:48 -0700998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001000}
1001
Steve Dower3e96f322015-03-02 08:01:10 -08001002#pragma warning(pop)
1003
Steve Dowercc16be82016-09-08 10:35:16 -07001004PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1005"_enablelegacywindowsfsencoding()\n\
1006\n\
1007Changes the default filesystem encoding to mbcs:replace for consistency\n\
1008with earlier versions of Python. See PEP 529 for more information.\n\
1009\n\
1010This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1011environment variable before launching Python."
1012);
1013
1014static PyObject *
1015sys_enablelegacywindowsfsencoding(PyObject *self)
1016{
1017 Py_FileSystemDefaultEncoding = "mbcs";
1018 Py_FileSystemDefaultEncodeErrors = "replace";
1019 Py_RETURN_NONE;
1020}
1021
Mark Hammond8696ebc2002-10-08 02:44:31 +00001022#endif /* MS_WINDOWS */
1023
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001024#ifdef HAVE_DLOPEN
1025static PyObject *
1026sys_setdlopenflags(PyObject *self, PyObject *args)
1027{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 int new_val;
1029 PyThreadState *tstate = PyThreadState_GET();
1030 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1031 return NULL;
1032 if (!tstate)
1033 return NULL;
1034 tstate->interp->dlopenflags = new_val;
1035 Py_INCREF(Py_None);
1036 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001037}
1038
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001039PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001040"setdlopenflags(n) -> None\n\
1041\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001042Set the flags used by the interpreter for dlopen calls, such as when the\n\
1043interpreter loads extension modules. Among other things, this will enable\n\
1044a lazy resolving of symbols when importing a module, if called as\n\
1045sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001046sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001047can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001048
1049static PyObject *
1050sys_getdlopenflags(PyObject *self, PyObject *args)
1051{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 PyThreadState *tstate = PyThreadState_GET();
1053 if (!tstate)
1054 return NULL;
1055 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001056}
1057
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001058PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001059"getdlopenflags() -> int\n\
1060\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001061Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001062The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001065
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001066#ifdef USE_MALLOPT
1067/* Link with -lmalloc (or -lmpc) on an SGI */
1068#include <malloc.h>
1069
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001070static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001071sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 int flag;
1074 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1075 return NULL;
1076 mallopt(M_DEBUG, flag);
1077 Py_INCREF(Py_None);
1078 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001079}
1080#endif /* USE_MALLOPT */
1081
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001082size_t
1083_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001087 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 /* Make sure the type is initialized. float gets initialized late */
1090 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001091 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001092
Benjamin Petersonce798522012-01-22 11:24:29 -05001093 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 if (method == NULL) {
1095 if (!PyErr_Occurred())
1096 PyErr_Format(PyExc_TypeError,
1097 "Type %.100s doesn't define __sizeof__",
1098 Py_TYPE(o)->tp_name);
1099 }
1100 else {
1101 res = PyObject_CallFunctionObjArgs(method, NULL);
1102 Py_DECREF(method);
1103 }
1104
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001105 if (res == NULL)
1106 return (size_t)-1;
1107
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001108 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001109 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001110 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001111 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001112
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001113 if (size < 0) {
1114 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1115 return (size_t)-1;
1116 }
1117
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001118 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001119 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001120 return ((size_t)size) + sizeof(PyGC_Head);
1121 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001122}
1123
1124static PyObject *
1125sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1126{
1127 static char *kwlist[] = {"object", "default", 0};
1128 size_t size;
1129 PyObject *o, *dflt = NULL;
1130
1131 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1132 kwlist, &o, &dflt))
1133 return NULL;
1134
1135 size = _PySys_GetSizeOf(o);
1136
1137 if (size == (size_t)-1 && PyErr_Occurred()) {
1138 /* Has a default value been given */
1139 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1140 PyErr_Clear();
1141 Py_INCREF(dflt);
1142 return dflt;
1143 }
1144 else
1145 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001147
1148 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001149}
1150
1151PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001152"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001153\n\
1154Return the size of object in bytes.");
1155
1156static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001157sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001160}
1161
Tim Peters4be93d02002-07-07 19:59:50 +00001162#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001163static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001164sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001167}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001168#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001169
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001170PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001171"getrefcount(object) -> integer\n\
1172\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001173Return the reference count of object. The count returned is generally\n\
1174one higher than you might expect, because it includes the (temporary)\n\
1175reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001176);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001177
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001178static PyObject *
1179sys_getallocatedblocks(PyObject *self)
1180{
1181 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1182}
1183
1184PyDoc_STRVAR(getallocatedblocks_doc,
1185"getallocatedblocks() -> integer\n\
1186\n\
1187Return the number of memory blocks currently allocated, regardless of their\n\
1188size."
1189);
1190
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001191#ifdef COUNT_ALLOCS
1192static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001193sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001198}
1199#endif
1200
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001201PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001202"_getframe([depth]) -> frameobject\n\
1203\n\
1204Return a frame object from the call stack. If optional integer depth is\n\
1205given, return the frame object that many calls below the top of the stack.\n\
1206If that is deeper than the call stack, ValueError is raised. The default\n\
1207for depth is zero, returning the frame at the top of the call stack.\n\
1208\n\
1209This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001210purposes only."
1211);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001212
1213static PyObject *
1214sys_getframe(PyObject *self, PyObject *args)
1215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyFrameObject *f = PyThreadState_GET()->frame;
1217 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1220 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 while (depth > 0 && f != NULL) {
1223 f = f->f_back;
1224 --depth;
1225 }
1226 if (f == NULL) {
1227 PyErr_SetString(PyExc_ValueError,
1228 "call stack is not deep enough");
1229 return NULL;
1230 }
1231 Py_INCREF(f);
1232 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001233}
1234
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001235PyDoc_STRVAR(current_frames_doc,
1236"_current_frames() -> dictionary\n\
1237\n\
1238Return a dictionary mapping each current thread T's thread id to T's\n\
1239current stack frame.\n\
1240\n\
1241This function should be used for specialized purposes only."
1242);
1243
1244static PyObject *
1245sys_current_frames(PyObject *self, PyObject *noargs)
1246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001248}
1249
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001250PyDoc_STRVAR(call_tracing_doc,
1251"call_tracing(func, args) -> object\n\
1252\n\
1253Call func(*args), while tracing is enabled. The tracing state is\n\
1254saved, and restored afterwards. This is intended to be called from\n\
1255a debugger from a checkpoint, to recursively debug some other code."
1256);
1257
1258static PyObject *
1259sys_call_tracing(PyObject *self, PyObject *args)
1260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 PyObject *func, *funcargs;
1262 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1263 return NULL;
1264 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001265}
1266
Jeremy Hylton985eba52003-02-05 23:13:00 +00001267PyDoc_STRVAR(callstats_doc,
1268"callstats() -> tuple of integers\n\
1269\n\
1270Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1271when Python was built. Otherwise, return None.\n\
1272\n\
1273When enabled, this function returns detailed, implementation-specific\n\
1274details about the number of function calls executed. The return value is\n\
1275a 11-tuple where the entries in the tuple are counts of:\n\
12760. all function calls\n\
12771. calls to PyFunction_Type objects\n\
12782. PyFunction calls that do not create an argument tuple\n\
12793. PyFunction calls that do not create an argument tuple\n\
1280 and bypass PyEval_EvalCodeEx()\n\
12814. PyMethod calls\n\
12825. PyMethod calls on bound methods\n\
12836. PyType calls\n\
12847. PyCFunction calls\n\
12858. generator calls\n\
12869. All other calls\n\
128710. Number of stack pops performed by call_function()"
1288);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001289
Victor Stinner048afd92016-11-28 11:59:04 +01001290static PyObject *
1291sys_callstats(PyObject *self)
1292{
1293 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1294 "sys.callstats() has been deprecated in Python 3.7 "
1295 "and will be removed in the future", 1) < 0) {
1296 return NULL;
1297 }
1298
1299 Py_RETURN_NONE;
1300}
1301
1302
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001303#ifdef __cplusplus
1304extern "C" {
1305#endif
1306
David Malcolm49526f42012-06-22 14:55:41 -04001307static PyObject *
1308sys_debugmallocstats(PyObject *self, PyObject *args)
1309{
1310#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001311 if (_PyMem_PymallocEnabled()) {
1312 _PyObject_DebugMallocStats(stderr);
1313 fputc('\n', stderr);
1314 }
David Malcolm49526f42012-06-22 14:55:41 -04001315#endif
1316 _PyObject_DebugTypeStats(stderr);
1317
1318 Py_RETURN_NONE;
1319}
1320PyDoc_STRVAR(debugmallocstats_doc,
1321"_debugmallocstats()\n\
1322\n\
1323Print summary info to stderr about the state of\n\
1324pymalloc's structures.\n\
1325\n\
1326In Py_DEBUG mode, also perform some expensive internal consistency\n\
1327checks.\n\
1328");
1329
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001330#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001331/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001332extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001333#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001334
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001335#ifdef DYNAMIC_EXECUTION_PROFILE
1336/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001337extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001338#endif
1339
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001340#ifdef __cplusplus
1341}
1342#endif
1343
Christian Heimes15ebc882008-02-04 18:48:49 +00001344static PyObject *
1345sys_clear_type_cache(PyObject* self, PyObject* args)
1346{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 PyType_ClearCache();
1348 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001349}
1350
1351PyDoc_STRVAR(sys_clear_type_cache__doc__,
1352"_clear_type_cache() -> None\n\
1353Clear the internal type lookup cache.");
1354
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001355static PyObject *
1356sys_is_finalizing(PyObject* self, PyObject* args)
1357{
1358 return PyBool_FromLong(_Py_Finalizing != NULL);
1359}
1360
1361PyDoc_STRVAR(is_finalizing_doc,
1362"is_finalizing()\n\
1363Return True if Python is exiting.");
1364
Christian Heimes15ebc882008-02-04 18:48:49 +00001365
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001366static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001368 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 callstats_doc},
1370 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1371 sys_clear_type_cache__doc__},
1372 {"_current_frames", sys_current_frames, METH_NOARGS,
1373 current_frames_doc},
1374 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1375 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1376 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1377 {"exit", sys_exit, METH_VARARGS, exit_doc},
1378 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1379 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001380#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001381 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1382 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001383#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001384 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1385 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001386#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001388#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001389#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001391#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1393 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001394 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1395 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001396#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001398#endif
1399#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001401#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1403 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1404 getrecursionlimit_doc},
1405 {"getsizeof", (PyCFunction)sys_getsizeof,
1406 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1407 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001408#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1410 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001411 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1412 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001413#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001415 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001416#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001418#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1420 setcheckinterval_doc},
1421 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1422 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001423#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1425 setswitchinterval_doc},
1426 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1427 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001428#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001429#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1431 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001432#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1434 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1435 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1436 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 {"settrace", sys_settrace, METH_O, settrace_doc},
1438 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1439 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001440 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001441 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001442 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1443 set_coroutine_wrapper_doc},
1444 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1445 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001446 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001447 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1448 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1449 get_asyncgen_hooks_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001451};
1452
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001453static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001454list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyObject *list = PyList_New(0);
1457 int i;
1458 if (list == NULL)
1459 return NULL;
1460 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1461 PyObject *name = PyUnicode_FromString(
1462 PyImport_Inittab[i].name);
1463 if (name == NULL)
1464 break;
1465 PyList_Append(list, name);
1466 Py_DECREF(name);
1467 }
1468 if (PyList_Sort(list) != 0) {
1469 Py_DECREF(list);
1470 list = NULL;
1471 }
1472 if (list) {
1473 PyObject *v = PyList_AsTuple(list);
1474 Py_DECREF(list);
1475 list = v;
1476 }
1477 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001478}
1479
Guido van Rossum23fff912000-12-15 22:02:05 +00001480static PyObject *warnoptions = NULL;
1481
1482void
1483PySys_ResetWarnOptions(void)
1484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 if (warnoptions == NULL || !PyList_Check(warnoptions))
1486 return;
1487 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001488}
1489
1490void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001491PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1494 Py_XDECREF(warnoptions);
1495 warnoptions = PyList_New(0);
1496 if (warnoptions == NULL)
1497 return;
1498 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001499 PyList_Append(warnoptions, unicode);
1500}
1501
1502void
1503PySys_AddWarnOption(const wchar_t *s)
1504{
1505 PyObject *unicode;
1506 unicode = PyUnicode_FromWideChar(s, -1);
1507 if (unicode == NULL)
1508 return;
1509 PySys_AddWarnOptionUnicode(unicode);
1510 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001511}
1512
Christian Heimes33fe8092008-04-13 13:53:33 +00001513int
1514PySys_HasWarnOptions(void)
1515{
1516 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1517}
1518
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001519static PyObject *xoptions = NULL;
1520
1521static PyObject *
1522get_xoptions(void)
1523{
1524 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1525 Py_XDECREF(xoptions);
1526 xoptions = PyDict_New();
1527 }
1528 return xoptions;
1529}
1530
1531void
1532PySys_AddXOption(const wchar_t *s)
1533{
1534 PyObject *opts;
1535 PyObject *name = NULL, *value = NULL;
1536 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001537
1538 opts = get_xoptions();
1539 if (opts == NULL)
1540 goto error;
1541
1542 name_end = wcschr(s, L'=');
1543 if (!name_end) {
1544 name = PyUnicode_FromWideChar(s, -1);
1545 value = Py_True;
1546 Py_INCREF(value);
1547 }
1548 else {
1549 name = PyUnicode_FromWideChar(s, name_end - s);
1550 value = PyUnicode_FromWideChar(name_end + 1, -1);
1551 }
1552 if (name == NULL || value == NULL)
1553 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001554 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001555 Py_DECREF(name);
1556 Py_DECREF(value);
1557 return;
1558
1559error:
1560 Py_XDECREF(name);
1561 Py_XDECREF(value);
1562 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001563 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001564 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001565 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001566}
1567
1568PyObject *
1569PySys_GetXOptions(void)
1570{
1571 return get_xoptions();
1572}
1573
Guido van Rossum40552d01998-08-06 03:34:39 +00001574/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1575 Two literals concatenated works just fine. If you have a K&R compiler
1576 or other abomination that however *does* understand longer strings,
1577 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001578PyDoc_VAR(sys_doc) =
1579PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001580"This module provides access to some objects used or maintained by the\n\
1581interpreter and to functions that interact strongly with the interpreter.\n\
1582\n\
1583Dynamic objects:\n\
1584\n\
1585argv -- command line arguments; argv[0] is the script pathname if known\n\
1586path -- module search path; path[0] is the script directory, else ''\n\
1587modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001588\n\
1589displayhook -- called to show results in an interactive session\n\
1590excepthook -- called to handle any uncaught exception other than SystemExit\n\
1591 To customize printing in an interactive session or to install a custom\n\
1592 top-level exception handler, assign other functions to replace these.\n\
1593\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001594stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001595stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001596stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001597 By assigning other file objects (or objects that behave like files)\n\
1598 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001599\n\
1600last_type -- type of last uncaught exception\n\
1601last_value -- value of last uncaught exception\n\
1602last_traceback -- traceback of last uncaught exception\n\
1603 These three are only available in an interactive session after a\n\
1604 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001605"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001606)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001607/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001608PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001609"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001610Static objects:\n\
1611\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001612builtin_module_names -- tuple of module names built into this interpreter\n\
1613copyright -- copyright notice pertaining to this interpreter\n\
1614exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001615executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001616float_info -- a struct sequence with information about the float implementation.\n\
1617float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001618hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001619hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001620implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001621int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001622maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001623maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001624platform -- platform identifier\n\
1625prefix -- prefix used to find the Python library\n\
1626thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001627version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001628version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001629"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001630)
Steve Dowercc16be82016-09-08 10:35:16 -07001631#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001632/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001633PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001634"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001635winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001636"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001637)
Steve Dowercc16be82016-09-08 10:35:16 -07001638#endif /* MS_COREDLL */
1639#ifdef MS_WINDOWS
1640/* concatenating string here */
1641PyDoc_STR(
1642"_enablelegacywindowsfsencoding -- [Windows only] \n\
1643"
1644)
1645#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001646PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001647"__stdin__ -- the original stdin; don't touch!\n\
1648__stdout__ -- the original stdout; don't touch!\n\
1649__stderr__ -- the original stderr; don't touch!\n\
1650__displayhook__ -- the original displayhook; don't touch!\n\
1651__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001652\n\
1653Functions:\n\
1654\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001655displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001656excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001657exc_info() -- return thread-safe information about the current exception\n\
1658exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001659getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001660getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001661getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001662getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001663getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001664gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001665setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001666setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001667setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001668setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001669settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001670"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001671)
Fred Drakeccede592000-08-14 20:59:57 +00001672/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001673
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001674
1675PyDoc_STRVAR(flags__doc__,
1676"sys.flags\n\
1677\n\
1678Flags provided through command line arguments or environment vars.");
1679
1680static PyTypeObject FlagsType;
1681
1682static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 {"inspect", "-i"},
1685 {"interactive", "-i"},
1686 {"optimize", "-O or -OO"},
1687 {"dont_write_bytecode", "-B"},
1688 {"no_user_site", "-s"},
1689 {"no_site", "-S"},
1690 {"ignore_environment", "-E"},
1691 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* {"unbuffered", "-u"}, */
1693 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001694 {"bytes_warning", "-b"},
1695 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001696 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001697 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001699};
1700
1701static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 "sys.flags", /* name */
1703 flags__doc__, /* doc */
1704 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001705 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001706};
1707
1708static PyObject*
1709make_flags(void)
1710{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 int pos = 0;
1712 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 seq = PyStructSequence_New(&FlagsType);
1715 if (seq == NULL)
1716 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001717
1718#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 SetFlag(Py_InspectFlag);
1723 SetFlag(Py_InteractiveFlag);
1724 SetFlag(Py_OptimizeFlag);
1725 SetFlag(Py_DontWriteBytecodeFlag);
1726 SetFlag(Py_NoUserSiteDirectory);
1727 SetFlag(Py_NoSiteFlag);
1728 SetFlag(Py_IgnoreEnvironmentFlag);
1729 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 /* SetFlag(saw_unbuffered_flag); */
1731 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001732 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001733 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001734 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001735 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001736#undef SetFlag
1737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001739 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 return NULL;
1741 }
1742 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001743}
1744
Eric Smith0e5b5622009-02-06 01:32:42 +00001745PyDoc_STRVAR(version_info__doc__,
1746"sys.version_info\n\
1747\n\
1748Version information as a named tuple.");
1749
1750static PyTypeObject VersionInfoType;
1751
1752static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 {"major", "Major release number"},
1754 {"minor", "Minor release number"},
1755 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001756 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001757 {"serial", "Serial release number"},
1758 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001759};
1760
1761static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 "sys.version_info", /* name */
1763 version_info__doc__, /* doc */
1764 version_info_fields, /* fields */
1765 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001766};
1767
1768static PyObject *
1769make_version_info(void)
1770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 PyObject *version_info;
1772 char *s;
1773 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001774
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001775 version_info = PyStructSequence_New(&VersionInfoType);
1776 if (version_info == NULL) {
1777 return NULL;
1778 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /*
1781 * These release level checks are mutually exclusive and cover
1782 * the field, so don't get too fancy with the pre-processor!
1783 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001784#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001786#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001788#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001790#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001792#endif
1793
1794#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001796#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 SetIntItem(PY_MAJOR_VERSION);
1800 SetIntItem(PY_MINOR_VERSION);
1801 SetIntItem(PY_MICRO_VERSION);
1802 SetStrItem(s);
1803 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001804#undef SetIntItem
1805#undef SetStrItem
1806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (PyErr_Occurred()) {
1808 Py_CLEAR(version_info);
1809 return NULL;
1810 }
1811 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001812}
1813
Brett Cannon3adc7b72012-07-09 14:22:12 -04001814/* sys.implementation values */
1815#define NAME "cpython"
1816const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001817#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1818#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001819#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001820const char *_PySys_ImplCacheTag = TAG;
1821#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001822#undef MAJOR
1823#undef MINOR
1824#undef TAG
1825
Barry Warsaw409da152012-06-03 16:18:47 -04001826static PyObject *
1827make_impl_info(PyObject *version_info)
1828{
1829 int res;
1830 PyObject *impl_info, *value, *ns;
1831
1832 impl_info = PyDict_New();
1833 if (impl_info == NULL)
1834 return NULL;
1835
1836 /* populate the dict */
1837
Brett Cannon3adc7b72012-07-09 14:22:12 -04001838 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001839 if (value == NULL)
1840 goto error;
1841 res = PyDict_SetItemString(impl_info, "name", value);
1842 Py_DECREF(value);
1843 if (res < 0)
1844 goto error;
1845
Brett Cannon3adc7b72012-07-09 14:22:12 -04001846 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001847 if (value == NULL)
1848 goto error;
1849 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1850 Py_DECREF(value);
1851 if (res < 0)
1852 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001853
1854 res = PyDict_SetItemString(impl_info, "version", version_info);
1855 if (res < 0)
1856 goto error;
1857
1858 value = PyLong_FromLong(PY_VERSION_HEX);
1859 if (value == NULL)
1860 goto error;
1861 res = PyDict_SetItemString(impl_info, "hexversion", value);
1862 Py_DECREF(value);
1863 if (res < 0)
1864 goto error;
1865
doko@ubuntu.com55532312016-06-14 08:55:19 +02001866#ifdef MULTIARCH
1867 value = PyUnicode_FromString(MULTIARCH);
1868 if (value == NULL)
1869 goto error;
1870 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1871 Py_DECREF(value);
1872 if (res < 0)
1873 goto error;
1874#endif
1875
Barry Warsaw409da152012-06-03 16:18:47 -04001876 /* dict ready */
1877
1878 ns = _PyNamespace_New(impl_info);
1879 Py_DECREF(impl_info);
1880 return ns;
1881
1882error:
1883 Py_CLEAR(impl_info);
1884 return NULL;
1885}
1886
Martin v. Löwis1a214512008-06-11 05:26:20 +00001887static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 PyModuleDef_HEAD_INIT,
1889 "sys",
1890 sys_doc,
1891 -1, /* multiple "initialization" just copies the module dict. */
1892 sys_methods,
1893 NULL,
1894 NULL,
1895 NULL,
1896 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001897};
1898
Guido van Rossum25ce5661997-08-02 03:10:38 +00001899PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001900_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001901{
Victor Stinner58049602013-07-22 22:40:00 +02001902 PyObject *m, *sysdict, *version_info;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001903 int res;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 m = PyModule_Create(&sysmodule);
1906 if (m == NULL)
1907 return NULL;
1908 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001909#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001910 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001911 PyObject *v = (value); \
1912 if (v == NULL) \
1913 return NULL; \
1914 res = PyDict_SetItemString(sysdict, key, v); \
1915 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001916 return NULL; \
1917 } \
1918 } while (0)
1919#define SET_SYS_FROM_STRING(key, value) \
1920 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001921 PyObject *v = (value); \
1922 if (v == NULL) \
1923 return NULL; \
1924 res = PyDict_SetItemString(sysdict, key, v); \
1925 Py_DECREF(v); \
1926 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001927 return NULL; \
1928 } \
1929 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 /* Check that stdin is not a directory
1932 Using shell redirection, you can redirect stdin to a directory,
1933 crashing the Python interpreter. Catch this common mistake here
1934 and output a useful error message. Note that under MS Windows,
1935 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001936#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001938 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001939 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 S_ISDIR(sb.st_mode)) {
1941 /* There's nothing more we can do. */
1942 /* Py_FatalError() will core dump, so just exit. */
1943 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1944 exit(EXIT_FAILURE);
1945 }
1946 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001947#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001948
Nick Coghland6009512014-11-20 21:39:37 +10001949 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001950
Victor Stinner8fea2522013-10-27 17:15:42 +01001951 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1952 PyDict_GetItemString(sysdict, "displayhook"));
1953 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1954 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 SET_SYS_FROM_STRING("version",
1956 PyUnicode_FromString(Py_GetVersion()));
1957 SET_SYS_FROM_STRING("hexversion",
1958 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001959 SET_SYS_FROM_STRING("_mercurial",
1960 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1961 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 SET_SYS_FROM_STRING("dont_write_bytecode",
1963 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1964 SET_SYS_FROM_STRING("api_version",
1965 PyLong_FromLong(PYTHON_API_VERSION));
1966 SET_SYS_FROM_STRING("copyright",
1967 PyUnicode_FromString(Py_GetCopyright()));
1968 SET_SYS_FROM_STRING("platform",
1969 PyUnicode_FromString(Py_GetPlatform()));
1970 SET_SYS_FROM_STRING("executable",
1971 PyUnicode_FromWideChar(
1972 Py_GetProgramFullPath(), -1));
1973 SET_SYS_FROM_STRING("prefix",
1974 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1975 SET_SYS_FROM_STRING("exec_prefix",
1976 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001977 SET_SYS_FROM_STRING("base_prefix",
1978 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1979 SET_SYS_FROM_STRING("base_exec_prefix",
1980 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 SET_SYS_FROM_STRING("maxsize",
1982 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1983 SET_SYS_FROM_STRING("float_info",
1984 PyFloat_GetInfo());
1985 SET_SYS_FROM_STRING("int_info",
1986 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001987 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001988 if (Hash_InfoType.tp_name == NULL) {
1989 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1990 return NULL;
1991 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001992 SET_SYS_FROM_STRING("hash_info",
1993 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001995 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 SET_SYS_FROM_STRING("builtin_module_names",
1997 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001998#if PY_BIG_ENDIAN
1999 SET_SYS_FROM_STRING("byteorder",
2000 PyUnicode_FromString("big"));
2001#else
2002 SET_SYS_FROM_STRING("byteorder",
2003 PyUnicode_FromString("little"));
2004#endif
Fred Drake099325e2000-08-14 15:47:03 +00002005
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002006#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 SET_SYS_FROM_STRING("dllhandle",
2008 PyLong_FromVoidPtr(PyWin_DLLhModule));
2009 SET_SYS_FROM_STRING("winver",
2010 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002011#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002012#ifdef ABIFLAGS
2013 SET_SYS_FROM_STRING("abiflags",
2014 PyUnicode_FromString(ABIFLAGS));
2015#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002016 if (warnoptions == NULL) {
2017 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02002018 if (warnoptions == NULL)
2019 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002020 }
2021 else {
2022 Py_INCREF(warnoptions);
2023 }
Victor Stinner8fea2522013-10-27 17:15:42 +01002024 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00002025
Victor Stinner8fea2522013-10-27 17:15:42 +01002026 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002027
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002029 if (VersionInfoType.tp_name == NULL) {
2030 if (PyStructSequence_InitType2(&VersionInfoType,
2031 &version_info_desc) < 0)
2032 return NULL;
2033 }
Barry Warsaw409da152012-06-03 16:18:47 -04002034 version_info = make_version_info();
2035 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* prevent user from creating new instances */
2037 VersionInfoType.tp_init = NULL;
2038 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002039 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2040 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2041 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002042
Barry Warsaw409da152012-06-03 16:18:47 -04002043 /* implementation */
2044 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002047 if (FlagsType.tp_name == 0) {
2048 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2049 return NULL;
2050 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 SET_SYS_FROM_STRING("flags", make_flags());
2052 /* prevent user from creating new instances */
2053 FlagsType.tp_init = NULL;
2054 FlagsType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002055 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2056 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2057 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002058
2059#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* getwindowsversion */
2061 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002062 if (PyStructSequence_InitType2(&WindowsVersionType,
2063 &windows_version_desc) < 0)
2064 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 /* prevent user from creating new instances */
2066 WindowsVersionType.tp_init = NULL;
2067 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002068 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2069 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2070 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002071#endif
2072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002074#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 SET_SYS_FROM_STRING("float_repr_style",
2076 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002077#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 SET_SYS_FROM_STRING("float_repr_style",
2079 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002080#endif
2081
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002082#ifdef WITH_THREAD
2083 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
2084#endif
2085
Yury Selivanoveb636452016-09-08 22:01:51 -07002086 /* initialize asyncgen_hooks */
2087 if (AsyncGenHooksType.tp_name == NULL) {
2088 if (PyStructSequence_InitType2(
2089 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2090 return NULL;
2091 }
2092 }
2093
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00002094#undef SET_SYS_FROM_STRING
Benjamin Peterson93813432014-03-28 18:52:45 -04002095#undef SET_SYS_FROM_STRING_BORROW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002096 if (PyErr_Occurred())
2097 return NULL;
2098 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002099}
2100
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002101static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002102makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 int i, n;
2105 const wchar_t *p;
2106 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 n = 1;
2109 p = path;
2110 while ((p = wcschr(p, delim)) != NULL) {
2111 n++;
2112 p++;
2113 }
2114 v = PyList_New(n);
2115 if (v == NULL)
2116 return NULL;
2117 for (i = 0; ; i++) {
2118 p = wcschr(path, delim);
2119 if (p == NULL)
2120 p = path + wcslen(path); /* End of string */
2121 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2122 if (w == NULL) {
2123 Py_DECREF(v);
2124 return NULL;
2125 }
2126 PyList_SetItem(v, i, w);
2127 if (*p == '\0')
2128 break;
2129 path = p+1;
2130 }
2131 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002132}
2133
2134void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002135PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *v;
2138 if ((v = makepathobject(path, DELIM)) == NULL)
2139 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002140 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 Py_FatalError("can't assign sys.path");
2142 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002143}
2144
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002145static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002146makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyObject *av;
2149 if (argc <= 0 || argv == NULL) {
2150 /* Ensure at least one (empty) argument is seen */
2151 static wchar_t *empty_argv[1] = {L""};
2152 argv = empty_argv;
2153 argc = 1;
2154 }
2155 av = PyList_New(argc);
2156 if (av != NULL) {
2157 int i;
2158 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 if (v == NULL) {
2161 Py_DECREF(av);
2162 av = NULL;
2163 break;
2164 }
2165 PyList_SetItem(av, i, v);
2166 }
2167 }
2168 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002169}
2170
Nick Coghland26c18a2010-08-17 13:06:11 +00002171#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2172 (argc > 0 && argv0 != NULL && \
2173 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002174
2175static void
2176sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002177{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002178 wchar_t *argv0;
2179 wchar_t *p = NULL;
2180 Py_ssize_t n = 0;
2181 PyObject *a;
2182 PyObject *path;
2183#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002184 wchar_t link[MAXPATHLEN+1];
2185 wchar_t argv0copy[2*MAXPATHLEN+1];
2186 int nr = 0;
2187#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002188#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002190#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002192#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002193
Victor Stinnerbd303c12013-11-07 23:07:29 +01002194 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002195 if (path == NULL)
2196 return;
2197
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002198 argv0 = argv[0];
2199
2200#ifdef HAVE_READLINK
2201 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2202 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2203 if (nr > 0) {
2204 /* It's a symlink */
2205 link[nr] = '\0';
2206 if (link[0] == SEP)
2207 argv0 = link; /* Link to absolute path */
2208 else if (wcschr(link, SEP) == NULL)
2209 ; /* Link without path */
2210 else {
2211 /* Must join(dirname(argv0), link) */
2212 wchar_t *q = wcsrchr(argv0, SEP);
2213 if (q == NULL)
2214 argv0 = link; /* argv0 without path */
2215 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002216 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2217 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002218 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002219 wcsncpy(q+1, link, MAXPATHLEN);
2220 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002221 argv0 = argv0copy;
2222 }
2223 }
2224 }
2225#endif /* HAVE_READLINK */
2226#if SEP == '\\' /* Special case for MS filename syntax */
2227 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2228 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002229#if defined(MS_WINDOWS)
2230 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002231 wchar_t *ptemp;
2232 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002233 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002234 fullpath,
2235 &ptemp)) {
2236 argv0 = fullpath;
2237 }
2238#endif
2239 p = wcsrchr(argv0, SEP);
2240 /* Test for alternate separator */
2241 q = wcsrchr(p ? p : argv0, '/');
2242 if (q != NULL)
2243 p = q;
2244 if (p != NULL) {
2245 n = p + 1 - argv0;
2246 if (n > 1 && p[-1] != ':')
2247 n--; /* Drop trailing separator */
2248 }
2249 }
2250#else /* All other filename syntaxes */
2251 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2252#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002253 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002254 argv0 = fullpath;
2255 }
2256#endif
2257 p = wcsrchr(argv0, SEP);
2258 }
2259 if (p != NULL) {
2260 n = p + 1 - argv0;
2261#if SEP == '/' /* Special case for Unix filename syntax */
2262 if (n > 1)
2263 n--; /* Drop trailing separator */
2264#endif /* Unix */
2265 }
2266#endif /* All others */
2267 a = PyUnicode_FromWideChar(argv0, n);
2268 if (a == NULL)
2269 Py_FatalError("no mem for sys.path insertion");
2270 if (PyList_Insert(path, 0, a) < 0)
2271 Py_FatalError("sys.path.insert(0) failed");
2272 Py_DECREF(a);
2273}
2274
2275void
2276PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 if (av == NULL)
2280 Py_FatalError("no mem for sys.argv");
2281 if (PySys_SetObject("argv", av) != 0)
2282 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002284 if (updatepath)
2285 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002286}
Guido van Rossuma890e681998-05-12 14:59:24 +00002287
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002288void
2289PySys_SetArgv(int argc, wchar_t **argv)
2290{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002291 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002292}
2293
Victor Stinner14284c22010-04-23 12:02:30 +00002294/* Reimplementation of PyFile_WriteString() no calling indirectly
2295 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2296
2297static int
Victor Stinner79766632010-08-16 17:36:42 +00002298sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002299{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002300 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002302
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002303 if (file == NULL)
2304 return -1;
2305
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002306 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002307 if (writer == NULL)
2308 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002309
Victor Stinner559bb6a2016-08-22 22:48:54 +02002310 result = _PyObject_CallArg1(writer, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 if (result == NULL) {
2312 goto error;
2313 } else {
2314 err = 0;
2315 goto finally;
2316 }
Victor Stinner14284c22010-04-23 12:02:30 +00002317
2318error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002320finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 Py_XDECREF(result);
2323 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002324}
2325
Victor Stinner79766632010-08-16 17:36:42 +00002326static int
2327sys_pyfile_write(const char *text, PyObject *file)
2328{
2329 PyObject *unicode = NULL;
2330 int err;
2331
2332 if (file == NULL)
2333 return -1;
2334
2335 unicode = PyUnicode_FromString(text);
2336 if (unicode == NULL)
2337 return -1;
2338
2339 err = sys_pyfile_write_unicode(unicode, file);
2340 Py_DECREF(unicode);
2341 return err;
2342}
Guido van Rossuma890e681998-05-12 14:59:24 +00002343
2344/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2345 Adapted from code submitted by Just van Rossum.
2346
2347 PySys_WriteStdout(format, ...)
2348 PySys_WriteStderr(format, ...)
2349
2350 The first function writes to sys.stdout; the second to sys.stderr. When
2351 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002352 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002353
Victor Stinner14284c22010-04-23 12:02:30 +00002354 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002355 signal handlers: they may raise a new exception whereas sys_write()
2356 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002357
Guido van Rossuma890e681998-05-12 14:59:24 +00002358 Both take a printf-style format string as their first argument followed
2359 by a variable length argument list determined by the format string.
2360
2361 *** WARNING ***
2362
2363 The format should limit the total size of the formatted output string to
2364 1000 bytes. In particular, this means that no unrestricted "%s" formats
2365 should occur; these should be limited using "%.<N>s where <N> is a
2366 decimal number calculated so that <N> plus the maximum size of other
2367 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2368 which can print hundreds of digits for very large numbers.
2369
2370 */
2371
2372static void
Victor Stinner09054372013-11-06 22:41:44 +01002373sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 PyObject *file;
2376 PyObject *error_type, *error_value, *error_traceback;
2377 char buffer[1001];
2378 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002381 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2383 if (sys_pyfile_write(buffer, file) != 0) {
2384 PyErr_Clear();
2385 fputs(buffer, fp);
2386 }
2387 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2388 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002389 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 }
2392 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002393}
2394
2395void
Guido van Rossuma890e681998-05-12 14:59:24 +00002396PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002401 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002403}
2404
2405void
Guido van Rossuma890e681998-05-12 14:59:24 +00002406PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002411 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002412 va_end(va);
2413}
2414
2415static void
Victor Stinner09054372013-11-06 22:41:44 +01002416sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002417{
2418 PyObject *file, *message;
2419 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002420 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002421
2422 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002423 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002424 message = PyUnicode_FromFormatV(format, va);
2425 if (message != NULL) {
2426 if (sys_pyfile_write_unicode(message, file) != 0) {
2427 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002428 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002429 if (utf8 != NULL)
2430 fputs(utf8, fp);
2431 }
2432 Py_DECREF(message);
2433 }
2434 PyErr_Restore(error_type, error_value, error_traceback);
2435}
2436
2437void
2438PySys_FormatStdout(const char *format, ...)
2439{
2440 va_list va;
2441
2442 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002443 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002444 va_end(va);
2445}
2446
2447void
2448PySys_FormatStderr(const char *format, ...)
2449{
2450 va_list va;
2451
2452 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002453 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002455}