blob: 81520ea84f09cd4bbe9d89079416a4efc8df6d5e [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) {
Victor Stinner7e425412016-12-09 00:36:19 +0100133 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
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) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200182 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000183 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200184 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000185 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100186 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000187 if (outf == NULL || outf == Py_None) {
188 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
189 return NULL;
190 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000191 if (PyFile_WriteObject(o, outf, 0) != 0) {
192 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
193 /* repr(o) is not encodable to sys.stdout.encoding with
194 * sys.stdout.errors error handler (which is probably 'strict') */
195 PyErr_Clear();
196 err = sys_displayhook_unencodable(outf, o);
197 if (err)
198 return NULL;
199 }
200 else {
201 return NULL;
202 }
203 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100204 if (newline == NULL) {
205 newline = PyUnicode_FromString("\n");
206 if (newline == NULL)
207 return NULL;
208 }
209 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000210 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200211 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000212 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200213 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000214}
215
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000216PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000217"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000218"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000219"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000220);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000221
222static PyObject *
223sys_excepthook(PyObject* self, PyObject* args)
224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 PyObject *exc, *value, *tb;
226 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
227 return NULL;
228 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200229 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000230}
231
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000232PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000233"excepthook(exctype, value, traceback) -> None\n"
234"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000235"Handle an exception by displaying it with a traceback on sys.stderr.\n"
236);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000237
238static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000239sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyThreadState *tstate;
242 tstate = PyThreadState_GET();
243 return Py_BuildValue(
244 "(OOO)",
245 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
246 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
247 tstate->exc_traceback != NULL ?
248 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000249}
250
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000251PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000252"exc_info() -> (type, value, traceback)\n\
253\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000254Return information about the most recent exception caught by an except\n\
255clause in the current stack frame or in an older stack frame."
256);
257
258static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000259sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000260{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000261 PyObject *exit_code = 0;
262 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
263 return NULL;
264 /* Raise SystemExit so callers may catch it or clean up. */
265 PyErr_SetObject(PyExc_SystemExit, exit_code);
266 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267}
268
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000269PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000270"exit([status])\n\
271\n\
272Exit the interpreter by raising SystemExit(status).\n\
273If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300274If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000275If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000276exit status will be one (i.e., failure)."
277);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000278
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000279
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000280static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000281sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000282{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000284}
285
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000286PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000287"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000288\n\
289Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000290implementation."
291);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000292
293static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000294sys_getfilesystemencoding(PyObject *self)
295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 if (Py_FileSystemDefaultEncoding)
297 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200298 PyErr_SetString(PyExc_RuntimeError,
299 "filesystem encoding is not initialized");
300 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000301}
302
303PyDoc_STRVAR(getfilesystemencoding_doc,
304"getfilesystemencoding() -> string\n\
305\n\
306Return the encoding used to convert Unicode filenames in\n\
307operating system filenames."
308);
309
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000310static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700311sys_getfilesystemencodeerrors(PyObject *self)
312{
313 if (Py_FileSystemDefaultEncodeErrors)
314 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
315 PyErr_SetString(PyExc_RuntimeError,
316 "filesystem encoding is not initialized");
317 return NULL;
318}
319
320PyDoc_STRVAR(getfilesystemencodeerrors_doc,
321 "getfilesystemencodeerrors() -> string\n\
322\n\
323Return the error mode used to convert Unicode filenames in\n\
324operating system filenames."
325);
326
327static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000328sys_intern(PyObject *self, PyObject *args)
329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyObject *s;
331 if (!PyArg_ParseTuple(args, "U:intern", &s))
332 return NULL;
333 if (PyUnicode_CheckExact(s)) {
334 Py_INCREF(s);
335 PyUnicode_InternInPlace(&s);
336 return s;
337 }
338 else {
339 PyErr_Format(PyExc_TypeError,
340 "can't intern %.400s", s->ob_type->tp_name);
341 return NULL;
342 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000343}
344
345PyDoc_STRVAR(intern_doc,
346"intern(string) -> string\n\
347\n\
348``Intern'' the given string. This enters the string in the (global)\n\
349table of interned strings whose purpose is to speed up dictionary lookups.\n\
350Return the string itself or the previously interned string object with the\n\
351same value.");
352
353
Fred Drake5755ce62001-06-27 19:19:46 +0000354/*
355 * Cached interned string objects used for calling the profile and
356 * trace functions. Initialized by trace_init().
357 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000358static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000359
360static int
361trace_init(void)
362{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200363 static const char * const whatnames[7] = {
364 "call", "exception", "line", "return",
365 "c_call", "c_exception", "c_return"
366 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyObject *name;
368 int i;
369 for (i = 0; i < 7; ++i) {
370 if (whatstrings[i] == NULL) {
371 name = PyUnicode_InternFromString(whatnames[i]);
372 if (name == NULL)
373 return -1;
374 whatstrings[i] = name;
375 }
376 }
377 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000378}
379
380
381static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100382call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200386 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000387
Victor Stinner78da82b2016-08-20 01:22:57 +0200388 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200390 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100391
Victor Stinner78da82b2016-08-20 01:22:57 +0200392 stack[0] = (PyObject *)frame;
393 stack[1] = whatstrings[what];
394 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200397 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000398
Victor Stinner78da82b2016-08-20 01:22:57 +0200399 PyFrame_LocalsToFast(frame, 1);
400 if (result == NULL) {
401 PyTraceBack_Here(frame);
402 }
403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000405}
406
407static int
408profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (arg == NULL)
414 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100415 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (result == NULL) {
417 PyEval_SetProfile(NULL, NULL);
418 return -1;
419 }
420 Py_DECREF(result);
421 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000422}
423
424static int
425trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PyObject *callback;
429 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (what == PyTrace_CALL)
432 callback = self;
433 else
434 callback = frame->f_trace;
435 if (callback == NULL)
436 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100437 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (result == NULL) {
439 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200440 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return -1;
442 }
443 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300444 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 }
446 else {
447 Py_DECREF(result);
448 }
449 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000450}
Fred Draked0838392001-06-16 21:02:31 +0000451
Fred Drake8b4d01d2000-05-09 19:57:01 +0000452static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000453sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (trace_init() == -1)
456 return NULL;
457 if (args == Py_None)
458 PyEval_SetTrace(NULL, NULL);
459 else
460 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200461 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000462}
463
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000464PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000465"settrace(function)\n\
466\n\
467Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000468function call. See the debugger chapter in the library manual."
469);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000470
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000471static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000472sys_gettrace(PyObject *self, PyObject *args)
473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyThreadState *tstate = PyThreadState_GET();
475 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (temp == NULL)
478 temp = Py_None;
479 Py_INCREF(temp);
480 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000481}
482
483PyDoc_STRVAR(gettrace_doc,
484"gettrace()\n\
485\n\
486Return the global debug tracing function set with sys.settrace.\n\
487See the debugger chapter in the library manual."
488);
489
490static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000491sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (trace_init() == -1)
494 return NULL;
495 if (args == Py_None)
496 PyEval_SetProfile(NULL, NULL);
497 else
498 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200499 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000500}
501
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000502PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000503"setprofile(function)\n\
504\n\
505Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000506and return. See the profiler chapter in the library manual."
507);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000509static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000510sys_getprofile(PyObject *self, PyObject *args)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyThreadState *tstate = PyThreadState_GET();
513 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (temp == NULL)
516 temp = Py_None;
517 Py_INCREF(temp);
518 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000519}
520
521PyDoc_STRVAR(getprofile_doc,
522"getprofile()\n\
523\n\
524Return the profiling function set with sys.setprofile.\n\
525See the profiler chapter in the library manual."
526);
527
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000528static int _check_interval = 100;
529
Christian Heimes9bd667a2008-01-20 15:14:11 +0000530static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000531sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 if (PyErr_WarnEx(PyExc_DeprecationWarning,
534 "sys.getcheckinterval() and sys.setcheckinterval() "
535 "are deprecated. Use sys.setswitchinterval() "
536 "instead.", 1) < 0)
537 return NULL;
538 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
539 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200540 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000541}
542
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000543PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000544"setcheckinterval(n)\n\
545\n\
546Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000547n instructions. This also affects how often thread switches occur."
548);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000549
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000550static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000551sys_getcheckinterval(PyObject *self, PyObject *args)
552{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (PyErr_WarnEx(PyExc_DeprecationWarning,
554 "sys.getcheckinterval() and sys.setcheckinterval() "
555 "are deprecated. Use sys.getswitchinterval() "
556 "instead.", 1) < 0)
557 return NULL;
558 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000559}
560
561PyDoc_STRVAR(getcheckinterval_doc,
562"getcheckinterval() -> current check interval; see setcheckinterval()."
563);
564
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000565#ifdef WITH_THREAD
566static PyObject *
567sys_setswitchinterval(PyObject *self, PyObject *args)
568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 double d;
570 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
571 return NULL;
572 if (d <= 0.0) {
573 PyErr_SetString(PyExc_ValueError,
574 "switch interval must be strictly positive");
575 return NULL;
576 }
577 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200578 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000579}
580
581PyDoc_STRVAR(setswitchinterval_doc,
582"setswitchinterval(n)\n\
583\n\
584Set the ideal thread switching delay inside the Python interpreter\n\
585The actual frequency of switching threads can be lower if the\n\
586interpreter executes long sequences of uninterruptible code\n\
587(this is implementation-specific and workload-dependent).\n\
588\n\
589The parameter must represent the desired switching delay in seconds\n\
590A typical value is 0.005 (5 milliseconds)."
591);
592
593static PyObject *
594sys_getswitchinterval(PyObject *self, PyObject *args)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000597}
598
599PyDoc_STRVAR(getswitchinterval_doc,
600"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
601);
602
603#endif /* WITH_THREAD */
604
Tim Peterse5e065b2003-07-06 18:36:54 +0000605static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000606sys_setrecursionlimit(PyObject *self, PyObject *args)
607{
Victor Stinner50856d52015-10-13 00:11:21 +0200608 int new_limit, mark;
609 PyThreadState *tstate;
610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
612 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200613
614 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200616 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 return NULL;
618 }
Victor Stinner50856d52015-10-13 00:11:21 +0200619
620 /* Issue #25274: When the recursion depth hits the recursion limit in
621 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
622 set to 1 and a RecursionError is raised. The overflowed flag is reset
623 to 0 when the recursion depth goes below the low-water mark: see
624 Py_LeaveRecursiveCall().
625
626 Reject too low new limit if the current recursion depth is higher than
627 the new low-water mark. Otherwise it may not be possible anymore to
628 reset the overflowed flag to 0. */
629 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
630 tstate = PyThreadState_GET();
631 if (tstate->recursion_depth >= mark) {
632 PyErr_Format(PyExc_RecursionError,
633 "cannot set the recursion limit to %i at "
634 "the recursion depth %i: the limit is too low",
635 new_limit, tstate->recursion_depth);
636 return NULL;
637 }
638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000639 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200640 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000641}
642
Yury Selivanov75445082015-05-11 22:57:16 -0400643static PyObject *
644sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
645{
646 if (wrapper != Py_None) {
647 if (!PyCallable_Check(wrapper)) {
648 PyErr_Format(PyExc_TypeError,
649 "callable expected, got %.50s",
650 Py_TYPE(wrapper)->tp_name);
651 return NULL;
652 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400653 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400654 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400655 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400656 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400657 }
Yury Selivanov75445082015-05-11 22:57:16 -0400658 Py_RETURN_NONE;
659}
660
661PyDoc_STRVAR(set_coroutine_wrapper_doc,
662"set_coroutine_wrapper(wrapper)\n\
663\n\
664Set a wrapper for coroutine objects."
665);
666
667static PyObject *
668sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
669{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400670 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400671 if (wrapper == NULL) {
672 wrapper = Py_None;
673 }
674 Py_INCREF(wrapper);
675 return wrapper;
676}
677
678PyDoc_STRVAR(get_coroutine_wrapper_doc,
679"get_coroutine_wrapper()\n\
680\n\
681Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
682);
683
684
Yury Selivanoveb636452016-09-08 22:01:51 -0700685static PyTypeObject AsyncGenHooksType;
686
687PyDoc_STRVAR(asyncgen_hooks_doc,
688"asyncgen_hooks\n\
689\n\
690A struct sequence providing information about asynhronous\n\
691generators hooks. The attributes are read only.");
692
693static PyStructSequence_Field asyncgen_hooks_fields[] = {
694 {"firstiter", "Hook to intercept first iteration"},
695 {"finalizer", "Hook to intercept finalization"},
696 {0}
697};
698
699static PyStructSequence_Desc asyncgen_hooks_desc = {
700 "asyncgen_hooks", /* name */
701 asyncgen_hooks_doc, /* doc */
702 asyncgen_hooks_fields , /* fields */
703 2
704};
705
706
707static PyObject *
708sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
709{
710 static char *keywords[] = {"firstiter", "finalizer", NULL};
711 PyObject *firstiter = NULL;
712 PyObject *finalizer = NULL;
713
714 if (!PyArg_ParseTupleAndKeywords(
715 args, kw, "|OO", keywords,
716 &firstiter, &finalizer)) {
717 return NULL;
718 }
719
720 if (finalizer && finalizer != Py_None) {
721 if (!PyCallable_Check(finalizer)) {
722 PyErr_Format(PyExc_TypeError,
723 "callable finalizer expected, got %.50s",
724 Py_TYPE(finalizer)->tp_name);
725 return NULL;
726 }
727 _PyEval_SetAsyncGenFinalizer(finalizer);
728 }
729 else if (finalizer == Py_None) {
730 _PyEval_SetAsyncGenFinalizer(NULL);
731 }
732
733 if (firstiter && firstiter != Py_None) {
734 if (!PyCallable_Check(firstiter)) {
735 PyErr_Format(PyExc_TypeError,
736 "callable firstiter expected, got %.50s",
737 Py_TYPE(firstiter)->tp_name);
738 return NULL;
739 }
740 _PyEval_SetAsyncGenFirstiter(firstiter);
741 }
742 else if (firstiter == Py_None) {
743 _PyEval_SetAsyncGenFirstiter(NULL);
744 }
745
746 Py_RETURN_NONE;
747}
748
749PyDoc_STRVAR(set_asyncgen_hooks_doc,
750"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
751\n\
752Set a finalizer for async generators objects."
753);
754
755static PyObject *
756sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
757{
758 PyObject *res;
759 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
760 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
761
762 res = PyStructSequence_New(&AsyncGenHooksType);
763 if (res == NULL) {
764 return NULL;
765 }
766
767 if (firstiter == NULL) {
768 firstiter = Py_None;
769 }
770
771 if (finalizer == NULL) {
772 finalizer = Py_None;
773 }
774
775 Py_INCREF(firstiter);
776 PyStructSequence_SET_ITEM(res, 0, firstiter);
777
778 Py_INCREF(finalizer);
779 PyStructSequence_SET_ITEM(res, 1, finalizer);
780
781 return res;
782}
783
784PyDoc_STRVAR(get_asyncgen_hooks_doc,
785"get_asyncgen_hooks()\n\
786\n\
787Return a namedtuple of installed asynchronous generators hooks \
788(firstiter, finalizer)."
789);
790
791
Mark Dickinsondc787d22010-05-23 13:33:13 +0000792static PyTypeObject Hash_InfoType;
793
794PyDoc_STRVAR(hash_info_doc,
795"hash_info\n\
796\n\
797A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100798hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000799
800static PyStructSequence_Field hash_info_fields[] = {
801 {"width", "width of the type used for hashing, in bits"},
802 {"modulus", "prime number giving the modulus on which the hash "
803 "function is based"},
804 {"inf", "value to be used for hash of a positive infinity"},
805 {"nan", "value to be used for hash of a nan"},
806 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100807 {"algorithm", "name of the algorithm for hashing of str, bytes and "
808 "memoryviews"},
809 {"hash_bits", "internal output size of hash algorithm"},
810 {"seed_bits", "seed size of hash algorithm"},
811 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000812 {NULL, NULL}
813};
814
815static PyStructSequence_Desc hash_info_desc = {
816 "sys.hash_info",
817 hash_info_doc,
818 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100819 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000820};
821
Matthias Klosed885e952010-07-06 10:53:30 +0000822static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000823get_hash_info(void)
824{
825 PyObject *hash_info;
826 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100827 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000828 hash_info = PyStructSequence_New(&Hash_InfoType);
829 if (hash_info == NULL)
830 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100831 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000832 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000833 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000834 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000835 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000836 PyStructSequence_SET_ITEM(hash_info, field++,
837 PyLong_FromLong(_PyHASH_INF));
838 PyStructSequence_SET_ITEM(hash_info, field++,
839 PyLong_FromLong(_PyHASH_NAN));
840 PyStructSequence_SET_ITEM(hash_info, field++,
841 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100842 PyStructSequence_SET_ITEM(hash_info, field++,
843 PyUnicode_FromString(hashfunc->name));
844 PyStructSequence_SET_ITEM(hash_info, field++,
845 PyLong_FromLong(hashfunc->hash_bits));
846 PyStructSequence_SET_ITEM(hash_info, field++,
847 PyLong_FromLong(hashfunc->seed_bits));
848 PyStructSequence_SET_ITEM(hash_info, field++,
849 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000850 if (PyErr_Occurred()) {
851 Py_CLEAR(hash_info);
852 return NULL;
853 }
854 return hash_info;
855}
856
857
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000858PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000859"setrecursionlimit(n)\n\
860\n\
861Set the maximum depth of the Python interpreter stack to n. This\n\
862limit prevents infinite recursion from causing an overflow of the C\n\
863stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000864dependent."
865);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000866
867static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000868sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000871}
872
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000873PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000874"getrecursionlimit()\n\
875\n\
876Return the current value of the recursion limit, the maximum depth\n\
877of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000878recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000879);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000880
Mark Hammond8696ebc2002-10-08 02:44:31 +0000881#ifdef MS_WINDOWS
882PyDoc_STRVAR(getwindowsversion_doc,
883"getwindowsversion()\n\
884\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000885Return information about the running version of Windows as a named tuple.\n\
886The members are named: major, minor, build, platform, service_pack,\n\
887service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200888backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700889All elements are numbers, except service_pack and platform_type which are\n\
890strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
891Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
892server. Platform_version is a 3-tuple containing a version number that is\n\
893intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000894);
895
Eric Smithf7bb5782010-01-27 00:44:57 +0000896static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
897
898static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 {"major", "Major version number"},
900 {"minor", "Minor version number"},
901 {"build", "Build number"},
902 {"platform", "Operating system platform"},
903 {"service_pack", "Latest Service Pack installed on the system"},
904 {"service_pack_major", "Service Pack major version number"},
905 {"service_pack_minor", "Service Pack minor version number"},
906 {"suite_mask", "Bit mask identifying available product suites"},
907 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700908 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000909 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000910};
911
912static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 "sys.getwindowsversion", /* name */
914 getwindowsversion_doc, /* doc */
915 windows_version_fields, /* fields */
916 5 /* For backward compatibility,
917 only the first 5 items are accessible
918 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000919};
920
Steve Dower3e96f322015-03-02 08:01:10 -0800921/* Disable deprecation warnings about GetVersionEx as the result is
922 being passed straight through to the caller, who is responsible for
923 using it correctly. */
924#pragma warning(push)
925#pragma warning(disable:4996)
926
Mark Hammond8696ebc2002-10-08 02:44:31 +0000927static PyObject *
928sys_getwindowsversion(PyObject *self)
929{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 PyObject *version;
931 int pos = 0;
932 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700933 DWORD realMajor, realMinor, realBuild;
934 HANDLE hKernel32;
935 wchar_t kernel32_path[MAX_PATH];
936 LPVOID verblock;
937 DWORD verblock_size;
938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 ver.dwOSVersionInfoSize = sizeof(ver);
940 if (!GetVersionEx((OSVERSIONINFO*) &ver))
941 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000942
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000943 version = PyStructSequence_New(&WindowsVersionType);
944 if (version == NULL)
945 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000946
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
948 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
949 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
950 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
951 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
952 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
953 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
954 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
955 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000956
Steve Dower74f4af72016-09-17 17:27:48 -0700957 realMajor = ver.dwMajorVersion;
958 realMinor = ver.dwMinorVersion;
959 realBuild = ver.dwBuildNumber;
960
961 // GetVersion will lie if we are running in a compatibility mode.
962 // We need to read the version info from a system file resource
963 // to accurately identify the OS version. If we fail for any reason,
964 // just return whatever GetVersion said.
965 hKernel32 = GetModuleHandleW(L"kernel32.dll");
966 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
967 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
968 (verblock = PyMem_RawMalloc(verblock_size))) {
969 VS_FIXEDFILEINFO *ffi;
970 UINT ffi_len;
971
972 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
973 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
974 realMajor = HIWORD(ffi->dwProductVersionMS);
975 realMinor = LOWORD(ffi->dwProductVersionMS);
976 realBuild = HIWORD(ffi->dwProductVersionLS);
977 }
978 PyMem_RawFree(verblock);
979 }
980 PyStructSequence_SET_ITEM(version, pos++, PyTuple_Pack(3,
981 PyLong_FromLong(realMajor),
982 PyLong_FromLong(realMinor),
983 PyLong_FromLong(realBuild)
984 ));
985
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200986 if (PyErr_Occurred()) {
987 Py_DECREF(version);
988 return NULL;
989 }
Steve Dower74f4af72016-09-17 17:27:48 -0700990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000992}
993
Steve Dower3e96f322015-03-02 08:01:10 -0800994#pragma warning(pop)
995
Steve Dowercc16be82016-09-08 10:35:16 -0700996PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
997"_enablelegacywindowsfsencoding()\n\
998\n\
999Changes the default filesystem encoding to mbcs:replace for consistency\n\
1000with earlier versions of Python. See PEP 529 for more information.\n\
1001\n\
1002This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1003environment variable before launching Python."
1004);
1005
1006static PyObject *
1007sys_enablelegacywindowsfsencoding(PyObject *self)
1008{
1009 Py_FileSystemDefaultEncoding = "mbcs";
1010 Py_FileSystemDefaultEncodeErrors = "replace";
1011 Py_RETURN_NONE;
1012}
1013
Mark Hammond8696ebc2002-10-08 02:44:31 +00001014#endif /* MS_WINDOWS */
1015
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001016#ifdef HAVE_DLOPEN
1017static PyObject *
1018sys_setdlopenflags(PyObject *self, PyObject *args)
1019{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001020 int new_val;
1021 PyThreadState *tstate = PyThreadState_GET();
1022 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1023 return NULL;
1024 if (!tstate)
1025 return NULL;
1026 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001027 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001028}
1029
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001030PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001031"setdlopenflags(n) -> None\n\
1032\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001033Set the flags used by the interpreter for dlopen calls, such as when the\n\
1034interpreter loads extension modules. Among other things, this will enable\n\
1035a lazy resolving of symbols when importing a module, if called as\n\
1036sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001037sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001038can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001039
1040static PyObject *
1041sys_getdlopenflags(PyObject *self, PyObject *args)
1042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 PyThreadState *tstate = PyThreadState_GET();
1044 if (!tstate)
1045 return NULL;
1046 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001047}
1048
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001049PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001050"getdlopenflags() -> int\n\
1051\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001052Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001053The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001056
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001057#ifdef USE_MALLOPT
1058/* Link with -lmalloc (or -lmpc) on an SGI */
1059#include <malloc.h>
1060
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001061static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001062sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001063{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 int flag;
1065 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1066 return NULL;
1067 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001068 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001069}
1070#endif /* USE_MALLOPT */
1071
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001072size_t
1073_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001077 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 /* Make sure the type is initialized. float gets initialized late */
1080 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001081 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001082
Benjamin Petersonce798522012-01-22 11:24:29 -05001083 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (method == NULL) {
1085 if (!PyErr_Occurred())
1086 PyErr_Format(PyExc_TypeError,
1087 "Type %.100s doesn't define __sizeof__",
1088 Py_TYPE(o)->tp_name);
1089 }
1090 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001091 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 Py_DECREF(method);
1093 }
1094
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001095 if (res == NULL)
1096 return (size_t)-1;
1097
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001098 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001099 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001100 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001101 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001103 if (size < 0) {
1104 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1105 return (size_t)-1;
1106 }
1107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001109 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001110 return ((size_t)size) + sizeof(PyGC_Head);
1111 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001112}
1113
1114static PyObject *
1115sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1116{
1117 static char *kwlist[] = {"object", "default", 0};
1118 size_t size;
1119 PyObject *o, *dflt = NULL;
1120
1121 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1122 kwlist, &o, &dflt))
1123 return NULL;
1124
1125 size = _PySys_GetSizeOf(o);
1126
1127 if (size == (size_t)-1 && PyErr_Occurred()) {
1128 /* Has a default value been given */
1129 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1130 PyErr_Clear();
1131 Py_INCREF(dflt);
1132 return dflt;
1133 }
1134 else
1135 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001137
1138 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001139}
1140
1141PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001142"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001143\n\
1144Return the size of object in bytes.");
1145
1146static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001147sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001150}
1151
Tim Peters4be93d02002-07-07 19:59:50 +00001152#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001153static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001154sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001157}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001158#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001159
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001160PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001161"getrefcount(object) -> integer\n\
1162\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001163Return the reference count of object. The count returned is generally\n\
1164one higher than you might expect, because it includes the (temporary)\n\
1165reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001166);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001167
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001168static PyObject *
1169sys_getallocatedblocks(PyObject *self)
1170{
1171 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1172}
1173
1174PyDoc_STRVAR(getallocatedblocks_doc,
1175"getallocatedblocks() -> integer\n\
1176\n\
1177Return the number of memory blocks currently allocated, regardless of their\n\
1178size."
1179);
1180
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001181#ifdef COUNT_ALLOCS
1182static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001183sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001186
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001188}
1189#endif
1190
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001191PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001192"_getframe([depth]) -> frameobject\n\
1193\n\
1194Return a frame object from the call stack. If optional integer depth is\n\
1195given, return the frame object that many calls below the top of the stack.\n\
1196If that is deeper than the call stack, ValueError is raised. The default\n\
1197for depth is zero, returning the frame at the top of the call stack.\n\
1198\n\
1199This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001200purposes only."
1201);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001202
1203static PyObject *
1204sys_getframe(PyObject *self, PyObject *args)
1205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 PyFrameObject *f = PyThreadState_GET()->frame;
1207 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1210 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 while (depth > 0 && f != NULL) {
1213 f = f->f_back;
1214 --depth;
1215 }
1216 if (f == NULL) {
1217 PyErr_SetString(PyExc_ValueError,
1218 "call stack is not deep enough");
1219 return NULL;
1220 }
1221 Py_INCREF(f);
1222 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001223}
1224
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001225PyDoc_STRVAR(current_frames_doc,
1226"_current_frames() -> dictionary\n\
1227\n\
1228Return a dictionary mapping each current thread T's thread id to T's\n\
1229current stack frame.\n\
1230\n\
1231This function should be used for specialized purposes only."
1232);
1233
1234static PyObject *
1235sys_current_frames(PyObject *self, PyObject *noargs)
1236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001238}
1239
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001240PyDoc_STRVAR(call_tracing_doc,
1241"call_tracing(func, args) -> object\n\
1242\n\
1243Call func(*args), while tracing is enabled. The tracing state is\n\
1244saved, and restored afterwards. This is intended to be called from\n\
1245a debugger from a checkpoint, to recursively debug some other code."
1246);
1247
1248static PyObject *
1249sys_call_tracing(PyObject *self, PyObject *args)
1250{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 PyObject *func, *funcargs;
1252 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1253 return NULL;
1254 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001255}
1256
Jeremy Hylton985eba52003-02-05 23:13:00 +00001257PyDoc_STRVAR(callstats_doc,
1258"callstats() -> tuple of integers\n\
1259\n\
1260Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1261when Python was built. Otherwise, return None.\n\
1262\n\
1263When enabled, this function returns detailed, implementation-specific\n\
1264details about the number of function calls executed. The return value is\n\
1265a 11-tuple where the entries in the tuple are counts of:\n\
12660. all function calls\n\
12671. calls to PyFunction_Type objects\n\
12682. PyFunction calls that do not create an argument tuple\n\
12693. PyFunction calls that do not create an argument tuple\n\
1270 and bypass PyEval_EvalCodeEx()\n\
12714. PyMethod calls\n\
12725. PyMethod calls on bound methods\n\
12736. PyType calls\n\
12747. PyCFunction calls\n\
12758. generator calls\n\
12769. All other calls\n\
127710. Number of stack pops performed by call_function()"
1278);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001279
Victor Stinner048afd92016-11-28 11:59:04 +01001280static PyObject *
1281sys_callstats(PyObject *self)
1282{
1283 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1284 "sys.callstats() has been deprecated in Python 3.7 "
1285 "and will be removed in the future", 1) < 0) {
1286 return NULL;
1287 }
1288
1289 Py_RETURN_NONE;
1290}
1291
1292
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001293#ifdef __cplusplus
1294extern "C" {
1295#endif
1296
David Malcolm49526f42012-06-22 14:55:41 -04001297static PyObject *
1298sys_debugmallocstats(PyObject *self, PyObject *args)
1299{
1300#ifdef WITH_PYMALLOC
Victor Stinner34be8072016-03-14 12:04:26 +01001301 if (_PyMem_PymallocEnabled()) {
1302 _PyObject_DebugMallocStats(stderr);
1303 fputc('\n', stderr);
1304 }
David Malcolm49526f42012-06-22 14:55:41 -04001305#endif
1306 _PyObject_DebugTypeStats(stderr);
1307
1308 Py_RETURN_NONE;
1309}
1310PyDoc_STRVAR(debugmallocstats_doc,
1311"_debugmallocstats()\n\
1312\n\
1313Print summary info to stderr about the state of\n\
1314pymalloc's structures.\n\
1315\n\
1316In Py_DEBUG mode, also perform some expensive internal consistency\n\
1317checks.\n\
1318");
1319
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001320#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001321/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001322extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001323#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001324
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001325#ifdef DYNAMIC_EXECUTION_PROFILE
1326/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001327extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001328#endif
1329
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001330#ifdef __cplusplus
1331}
1332#endif
1333
Christian Heimes15ebc882008-02-04 18:48:49 +00001334static PyObject *
1335sys_clear_type_cache(PyObject* self, PyObject* args)
1336{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyType_ClearCache();
1338 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001339}
1340
1341PyDoc_STRVAR(sys_clear_type_cache__doc__,
1342"_clear_type_cache() -> None\n\
1343Clear the internal type lookup cache.");
1344
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001345static PyObject *
1346sys_is_finalizing(PyObject* self, PyObject* args)
1347{
1348 return PyBool_FromLong(_Py_Finalizing != NULL);
1349}
1350
1351PyDoc_STRVAR(is_finalizing_doc,
1352"is_finalizing()\n\
1353Return True if Python is exiting.");
1354
Christian Heimes15ebc882008-02-04 18:48:49 +00001355
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001356#ifdef ANDROID_API_LEVEL
1357PyDoc_STRVAR(getandroidapilevel_doc,
1358"getandroidapilevel()\n\
1359\n\
1360Return the build time API version of Android as an integer.");
1361
1362static PyObject *
1363sys_getandroidapilevel(PyObject *self)
1364{
1365 return PyLong_FromLong(ANDROID_API_LEVEL);
1366}
1367#endif /* ANDROID_API_LEVEL */
1368
1369
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001370static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001372 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 callstats_doc},
1374 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1375 sys_clear_type_cache__doc__},
1376 {"_current_frames", sys_current_frames, METH_NOARGS,
1377 current_frames_doc},
1378 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1379 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1380 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1381 {"exit", sys_exit, METH_VARARGS, exit_doc},
1382 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1383 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001384#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1386 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001387#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001388 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1389 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001390#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001392#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001393#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001395#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1397 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001398 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1399 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001400#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001402#endif
1403#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001405#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1407 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1408 getrecursionlimit_doc},
1409 {"getsizeof", (PyCFunction)sys_getsizeof,
1410 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1411 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001412#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1414 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001415 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1416 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001417#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001419 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001420#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001422#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1424 setcheckinterval_doc},
1425 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1426 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001427#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1429 setswitchinterval_doc},
1430 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1431 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001432#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001433#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1435 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001436#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1438 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1439 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1440 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 {"settrace", sys_settrace, METH_O, settrace_doc},
1442 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1443 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001444 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001445 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001446 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1447 set_coroutine_wrapper_doc},
1448 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1449 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001450 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001451 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1452 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1453 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001454#ifdef ANDROID_API_LEVEL
1455 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1456 getandroidapilevel_doc},
1457#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001459};
1460
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001461static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001462list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 PyObject *list = PyList_New(0);
1465 int i;
1466 if (list == NULL)
1467 return NULL;
1468 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1469 PyObject *name = PyUnicode_FromString(
1470 PyImport_Inittab[i].name);
1471 if (name == NULL)
1472 break;
1473 PyList_Append(list, name);
1474 Py_DECREF(name);
1475 }
1476 if (PyList_Sort(list) != 0) {
1477 Py_DECREF(list);
1478 list = NULL;
1479 }
1480 if (list) {
1481 PyObject *v = PyList_AsTuple(list);
1482 Py_DECREF(list);
1483 list = v;
1484 }
1485 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001486}
1487
Guido van Rossum23fff912000-12-15 22:02:05 +00001488static PyObject *warnoptions = NULL;
1489
1490void
1491PySys_ResetWarnOptions(void)
1492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 if (warnoptions == NULL || !PyList_Check(warnoptions))
1494 return;
1495 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001496}
1497
1498void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001499PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1502 Py_XDECREF(warnoptions);
1503 warnoptions = PyList_New(0);
1504 if (warnoptions == NULL)
1505 return;
1506 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001507 PyList_Append(warnoptions, unicode);
1508}
1509
1510void
1511PySys_AddWarnOption(const wchar_t *s)
1512{
1513 PyObject *unicode;
1514 unicode = PyUnicode_FromWideChar(s, -1);
1515 if (unicode == NULL)
1516 return;
1517 PySys_AddWarnOptionUnicode(unicode);
1518 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001519}
1520
Christian Heimes33fe8092008-04-13 13:53:33 +00001521int
1522PySys_HasWarnOptions(void)
1523{
1524 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1525}
1526
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001527static PyObject *xoptions = NULL;
1528
1529static PyObject *
1530get_xoptions(void)
1531{
1532 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1533 Py_XDECREF(xoptions);
1534 xoptions = PyDict_New();
1535 }
1536 return xoptions;
1537}
1538
1539void
1540PySys_AddXOption(const wchar_t *s)
1541{
1542 PyObject *opts;
1543 PyObject *name = NULL, *value = NULL;
1544 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001545
1546 opts = get_xoptions();
1547 if (opts == NULL)
1548 goto error;
1549
1550 name_end = wcschr(s, L'=');
1551 if (!name_end) {
1552 name = PyUnicode_FromWideChar(s, -1);
1553 value = Py_True;
1554 Py_INCREF(value);
1555 }
1556 else {
1557 name = PyUnicode_FromWideChar(s, name_end - s);
1558 value = PyUnicode_FromWideChar(name_end + 1, -1);
1559 }
1560 if (name == NULL || value == NULL)
1561 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001562 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001563 Py_DECREF(name);
1564 Py_DECREF(value);
1565 return;
1566
1567error:
1568 Py_XDECREF(name);
1569 Py_XDECREF(value);
1570 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001571 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001572 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001573 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001574}
1575
1576PyObject *
1577PySys_GetXOptions(void)
1578{
1579 return get_xoptions();
1580}
1581
Guido van Rossum40552d01998-08-06 03:34:39 +00001582/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1583 Two literals concatenated works just fine. If you have a K&R compiler
1584 or other abomination that however *does* understand longer strings,
1585 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001586PyDoc_VAR(sys_doc) =
1587PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001588"This module provides access to some objects used or maintained by the\n\
1589interpreter and to functions that interact strongly with the interpreter.\n\
1590\n\
1591Dynamic objects:\n\
1592\n\
1593argv -- command line arguments; argv[0] is the script pathname if known\n\
1594path -- module search path; path[0] is the script directory, else ''\n\
1595modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001596\n\
1597displayhook -- called to show results in an interactive session\n\
1598excepthook -- called to handle any uncaught exception other than SystemExit\n\
1599 To customize printing in an interactive session or to install a custom\n\
1600 top-level exception handler, assign other functions to replace these.\n\
1601\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001602stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001603stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001604stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001605 By assigning other file objects (or objects that behave like files)\n\
1606 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001607\n\
1608last_type -- type of last uncaught exception\n\
1609last_value -- value of last uncaught exception\n\
1610last_traceback -- traceback of last uncaught exception\n\
1611 These three are only available in an interactive session after a\n\
1612 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001613"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001614)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001615/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001616PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001617"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001618Static objects:\n\
1619\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001620builtin_module_names -- tuple of module names built into this interpreter\n\
1621copyright -- copyright notice pertaining to this interpreter\n\
1622exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001623executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001624float_info -- a struct sequence with information about the float implementation.\n\
1625float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001626hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001627hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001628implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001629int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001630maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001631maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001632platform -- platform identifier\n\
1633prefix -- prefix used to find the Python library\n\
1634thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001635version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001636version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001637"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001638)
Steve Dowercc16be82016-09-08 10:35:16 -07001639#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001640/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001641PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001642"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001643winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001644"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001645)
Steve Dowercc16be82016-09-08 10:35:16 -07001646#endif /* MS_COREDLL */
1647#ifdef MS_WINDOWS
1648/* concatenating string here */
1649PyDoc_STR(
1650"_enablelegacywindowsfsencoding -- [Windows only] \n\
1651"
1652)
1653#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001654PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001655"__stdin__ -- the original stdin; don't touch!\n\
1656__stdout__ -- the original stdout; don't touch!\n\
1657__stderr__ -- the original stderr; don't touch!\n\
1658__displayhook__ -- the original displayhook; don't touch!\n\
1659__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001660\n\
1661Functions:\n\
1662\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001663displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001664excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001665exc_info() -- return thread-safe information about the current exception\n\
1666exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001667getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001668getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001669getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001670getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001671getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001672gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001673setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001674setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001675setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001676setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001677settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001678"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001679)
Fred Drakeccede592000-08-14 20:59:57 +00001680/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001681
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001682
1683PyDoc_STRVAR(flags__doc__,
1684"sys.flags\n\
1685\n\
1686Flags provided through command line arguments or environment vars.");
1687
1688static PyTypeObject FlagsType;
1689
1690static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 {"inspect", "-i"},
1693 {"interactive", "-i"},
1694 {"optimize", "-O or -OO"},
1695 {"dont_write_bytecode", "-B"},
1696 {"no_user_site", "-s"},
1697 {"no_site", "-S"},
1698 {"ignore_environment", "-E"},
1699 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* {"unbuffered", "-u"}, */
1701 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001702 {"bytes_warning", "-b"},
1703 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001704 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001705 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001707};
1708
1709static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 "sys.flags", /* name */
1711 flags__doc__, /* doc */
1712 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001713 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001714};
1715
1716static PyObject*
1717make_flags(void)
1718{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 int pos = 0;
1720 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 seq = PyStructSequence_New(&FlagsType);
1723 if (seq == NULL)
1724 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001725
1726#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 SetFlag(Py_InspectFlag);
1731 SetFlag(Py_InteractiveFlag);
1732 SetFlag(Py_OptimizeFlag);
1733 SetFlag(Py_DontWriteBytecodeFlag);
1734 SetFlag(Py_NoUserSiteDirectory);
1735 SetFlag(Py_NoSiteFlag);
1736 SetFlag(Py_IgnoreEnvironmentFlag);
1737 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 /* SetFlag(saw_unbuffered_flag); */
1739 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001740 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001741 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001742 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001743 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001744#undef SetFlag
1745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001747 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001748 return NULL;
1749 }
1750 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001751}
1752
Eric Smith0e5b5622009-02-06 01:32:42 +00001753PyDoc_STRVAR(version_info__doc__,
1754"sys.version_info\n\
1755\n\
1756Version information as a named tuple.");
1757
1758static PyTypeObject VersionInfoType;
1759
1760static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 {"major", "Major release number"},
1762 {"minor", "Minor release number"},
1763 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001764 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 {"serial", "Serial release number"},
1766 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001767};
1768
1769static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 "sys.version_info", /* name */
1771 version_info__doc__, /* doc */
1772 version_info_fields, /* fields */
1773 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001774};
1775
1776static PyObject *
1777make_version_info(void)
1778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001779 PyObject *version_info;
1780 char *s;
1781 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 version_info = PyStructSequence_New(&VersionInfoType);
1784 if (version_info == NULL) {
1785 return NULL;
1786 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 /*
1789 * These release level checks are mutually exclusive and cover
1790 * the field, so don't get too fancy with the pre-processor!
1791 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001792#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001794#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001796#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001798#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001800#endif
1801
1802#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001804#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001806
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 SetIntItem(PY_MAJOR_VERSION);
1808 SetIntItem(PY_MINOR_VERSION);
1809 SetIntItem(PY_MICRO_VERSION);
1810 SetStrItem(s);
1811 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001812#undef SetIntItem
1813#undef SetStrItem
1814
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 if (PyErr_Occurred()) {
1816 Py_CLEAR(version_info);
1817 return NULL;
1818 }
1819 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001820}
1821
Brett Cannon3adc7b72012-07-09 14:22:12 -04001822/* sys.implementation values */
1823#define NAME "cpython"
1824const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001825#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1826#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001827#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001828const char *_PySys_ImplCacheTag = TAG;
1829#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001830#undef MAJOR
1831#undef MINOR
1832#undef TAG
1833
Barry Warsaw409da152012-06-03 16:18:47 -04001834static PyObject *
1835make_impl_info(PyObject *version_info)
1836{
1837 int res;
1838 PyObject *impl_info, *value, *ns;
1839
1840 impl_info = PyDict_New();
1841 if (impl_info == NULL)
1842 return NULL;
1843
1844 /* populate the dict */
1845
Brett Cannon3adc7b72012-07-09 14:22:12 -04001846 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001847 if (value == NULL)
1848 goto error;
1849 res = PyDict_SetItemString(impl_info, "name", value);
1850 Py_DECREF(value);
1851 if (res < 0)
1852 goto error;
1853
Brett Cannon3adc7b72012-07-09 14:22:12 -04001854 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001855 if (value == NULL)
1856 goto error;
1857 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1858 Py_DECREF(value);
1859 if (res < 0)
1860 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001861
1862 res = PyDict_SetItemString(impl_info, "version", version_info);
1863 if (res < 0)
1864 goto error;
1865
1866 value = PyLong_FromLong(PY_VERSION_HEX);
1867 if (value == NULL)
1868 goto error;
1869 res = PyDict_SetItemString(impl_info, "hexversion", value);
1870 Py_DECREF(value);
1871 if (res < 0)
1872 goto error;
1873
doko@ubuntu.com55532312016-06-14 08:55:19 +02001874#ifdef MULTIARCH
1875 value = PyUnicode_FromString(MULTIARCH);
1876 if (value == NULL)
1877 goto error;
1878 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1879 Py_DECREF(value);
1880 if (res < 0)
1881 goto error;
1882#endif
1883
Barry Warsaw409da152012-06-03 16:18:47 -04001884 /* dict ready */
1885
1886 ns = _PyNamespace_New(impl_info);
1887 Py_DECREF(impl_info);
1888 return ns;
1889
1890error:
1891 Py_CLEAR(impl_info);
1892 return NULL;
1893}
1894
Martin v. Löwis1a214512008-06-11 05:26:20 +00001895static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 PyModuleDef_HEAD_INIT,
1897 "sys",
1898 sys_doc,
1899 -1, /* multiple "initialization" just copies the module dict. */
1900 sys_methods,
1901 NULL,
1902 NULL,
1903 NULL,
1904 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001905};
1906
Guido van Rossum25ce5661997-08-02 03:10:38 +00001907PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001908_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001909{
Victor Stinner58049602013-07-22 22:40:00 +02001910 PyObject *m, *sysdict, *version_info;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001911 int res;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 m = PyModule_Create(&sysmodule);
1914 if (m == NULL)
1915 return NULL;
1916 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001917#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001918 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001919 PyObject *v = (value); \
1920 if (v == NULL) \
1921 return NULL; \
1922 res = PyDict_SetItemString(sysdict, key, v); \
1923 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001924 return NULL; \
1925 } \
1926 } while (0)
1927#define SET_SYS_FROM_STRING(key, value) \
1928 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001929 PyObject *v = (value); \
1930 if (v == NULL) \
1931 return NULL; \
1932 res = PyDict_SetItemString(sysdict, key, v); \
1933 Py_DECREF(v); \
1934 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001935 return NULL; \
1936 } \
1937 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 /* Check that stdin is not a directory
1940 Using shell redirection, you can redirect stdin to a directory,
1941 crashing the Python interpreter. Catch this common mistake here
1942 and output a useful error message. Note that under MS Windows,
1943 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001944#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001946 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001947 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 S_ISDIR(sb.st_mode)) {
1949 /* There's nothing more we can do. */
1950 /* Py_FatalError() will core dump, so just exit. */
1951 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1952 exit(EXIT_FAILURE);
1953 }
1954 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001955#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001956
Nick Coghland6009512014-11-20 21:39:37 +10001957 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001958
Victor Stinner8fea2522013-10-27 17:15:42 +01001959 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1960 PyDict_GetItemString(sysdict, "displayhook"));
1961 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1962 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 SET_SYS_FROM_STRING("version",
1964 PyUnicode_FromString(Py_GetVersion()));
1965 SET_SYS_FROM_STRING("hexversion",
1966 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001967 SET_SYS_FROM_STRING("_mercurial",
1968 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1969 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001970 SET_SYS_FROM_STRING("dont_write_bytecode",
1971 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1972 SET_SYS_FROM_STRING("api_version",
1973 PyLong_FromLong(PYTHON_API_VERSION));
1974 SET_SYS_FROM_STRING("copyright",
1975 PyUnicode_FromString(Py_GetCopyright()));
1976 SET_SYS_FROM_STRING("platform",
1977 PyUnicode_FromString(Py_GetPlatform()));
1978 SET_SYS_FROM_STRING("executable",
1979 PyUnicode_FromWideChar(
1980 Py_GetProgramFullPath(), -1));
1981 SET_SYS_FROM_STRING("prefix",
1982 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1983 SET_SYS_FROM_STRING("exec_prefix",
1984 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001985 SET_SYS_FROM_STRING("base_prefix",
1986 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1987 SET_SYS_FROM_STRING("base_exec_prefix",
1988 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 SET_SYS_FROM_STRING("maxsize",
1990 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1991 SET_SYS_FROM_STRING("float_info",
1992 PyFloat_GetInfo());
1993 SET_SYS_FROM_STRING("int_info",
1994 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001995 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001996 if (Hash_InfoType.tp_name == NULL) {
1997 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1998 return NULL;
1999 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002000 SET_SYS_FROM_STRING("hash_info",
2001 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002003 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 SET_SYS_FROM_STRING("builtin_module_names",
2005 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002006#if PY_BIG_ENDIAN
2007 SET_SYS_FROM_STRING("byteorder",
2008 PyUnicode_FromString("big"));
2009#else
2010 SET_SYS_FROM_STRING("byteorder",
2011 PyUnicode_FromString("little"));
2012#endif
Fred Drake099325e2000-08-14 15:47:03 +00002013
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002014#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 SET_SYS_FROM_STRING("dllhandle",
2016 PyLong_FromVoidPtr(PyWin_DLLhModule));
2017 SET_SYS_FROM_STRING("winver",
2018 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002019#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002020#ifdef ABIFLAGS
2021 SET_SYS_FROM_STRING("abiflags",
2022 PyUnicode_FromString(ABIFLAGS));
2023#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 if (warnoptions == NULL) {
2025 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02002026 if (warnoptions == NULL)
2027 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 }
2029 else {
2030 Py_INCREF(warnoptions);
2031 }
Victor Stinner8fea2522013-10-27 17:15:42 +01002032 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00002033
Victor Stinner8fea2522013-10-27 17:15:42 +01002034 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002035
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002037 if (VersionInfoType.tp_name == NULL) {
2038 if (PyStructSequence_InitType2(&VersionInfoType,
2039 &version_info_desc) < 0)
2040 return NULL;
2041 }
Barry Warsaw409da152012-06-03 16:18:47 -04002042 version_info = make_version_info();
2043 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* prevent user from creating new instances */
2045 VersionInfoType.tp_init = NULL;
2046 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002047 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2048 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2049 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002050
Barry Warsaw409da152012-06-03 16:18:47 -04002051 /* implementation */
2052 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2053
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002055 if (FlagsType.tp_name == 0) {
2056 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2057 return NULL;
2058 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 SET_SYS_FROM_STRING("flags", make_flags());
2060 /* prevent user from creating new instances */
2061 FlagsType.tp_init = NULL;
2062 FlagsType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002063 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2064 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2065 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002066
2067#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 /* getwindowsversion */
2069 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002070 if (PyStructSequence_InitType2(&WindowsVersionType,
2071 &windows_version_desc) < 0)
2072 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 /* prevent user from creating new instances */
2074 WindowsVersionType.tp_init = NULL;
2075 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002076 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2077 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2078 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002079#endif
2080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002082#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 SET_SYS_FROM_STRING("float_repr_style",
2084 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002085#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 SET_SYS_FROM_STRING("float_repr_style",
2087 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002088#endif
2089
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002090#ifdef WITH_THREAD
2091 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
2092#endif
2093
Yury Selivanoveb636452016-09-08 22:01:51 -07002094 /* initialize asyncgen_hooks */
2095 if (AsyncGenHooksType.tp_name == NULL) {
2096 if (PyStructSequence_InitType2(
2097 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2098 return NULL;
2099 }
2100 }
2101
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00002102#undef SET_SYS_FROM_STRING
Benjamin Peterson93813432014-03-28 18:52:45 -04002103#undef SET_SYS_FROM_STRING_BORROW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 if (PyErr_Occurred())
2105 return NULL;
2106 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002107}
2108
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002109static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002110makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002111{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 int i, n;
2113 const wchar_t *p;
2114 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002115
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 n = 1;
2117 p = path;
2118 while ((p = wcschr(p, delim)) != NULL) {
2119 n++;
2120 p++;
2121 }
2122 v = PyList_New(n);
2123 if (v == NULL)
2124 return NULL;
2125 for (i = 0; ; i++) {
2126 p = wcschr(path, delim);
2127 if (p == NULL)
2128 p = path + wcslen(path); /* End of string */
2129 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2130 if (w == NULL) {
2131 Py_DECREF(v);
2132 return NULL;
2133 }
2134 PyList_SetItem(v, i, w);
2135 if (*p == '\0')
2136 break;
2137 path = p+1;
2138 }
2139 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002140}
2141
2142void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002143PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyObject *v;
2146 if ((v = makepathobject(path, DELIM)) == NULL)
2147 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002148 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_FatalError("can't assign sys.path");
2150 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002151}
2152
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002153static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002154makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyObject *av;
2157 if (argc <= 0 || argv == NULL) {
2158 /* Ensure at least one (empty) argument is seen */
2159 static wchar_t *empty_argv[1] = {L""};
2160 argv = empty_argv;
2161 argc = 1;
2162 }
2163 av = PyList_New(argc);
2164 if (av != NULL) {
2165 int i;
2166 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 if (v == NULL) {
2169 Py_DECREF(av);
2170 av = NULL;
2171 break;
2172 }
2173 PyList_SetItem(av, i, v);
2174 }
2175 }
2176 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002177}
2178
Nick Coghland26c18a2010-08-17 13:06:11 +00002179#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2180 (argc > 0 && argv0 != NULL && \
2181 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002182
2183static void
2184sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002185{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002186 wchar_t *argv0;
2187 wchar_t *p = NULL;
2188 Py_ssize_t n = 0;
2189 PyObject *a;
2190 PyObject *path;
2191#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002192 wchar_t link[MAXPATHLEN+1];
2193 wchar_t argv0copy[2*MAXPATHLEN+1];
2194 int nr = 0;
2195#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002196#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002198#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002200#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002201
Victor Stinnerbd303c12013-11-07 23:07:29 +01002202 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002203 if (path == NULL)
2204 return;
2205
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002206 argv0 = argv[0];
2207
2208#ifdef HAVE_READLINK
2209 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2210 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2211 if (nr > 0) {
2212 /* It's a symlink */
2213 link[nr] = '\0';
2214 if (link[0] == SEP)
2215 argv0 = link; /* Link to absolute path */
2216 else if (wcschr(link, SEP) == NULL)
2217 ; /* Link without path */
2218 else {
2219 /* Must join(dirname(argv0), link) */
2220 wchar_t *q = wcsrchr(argv0, SEP);
2221 if (q == NULL)
2222 argv0 = link; /* argv0 without path */
2223 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002224 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2225 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002226 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002227 wcsncpy(q+1, link, MAXPATHLEN);
2228 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002229 argv0 = argv0copy;
2230 }
2231 }
2232 }
2233#endif /* HAVE_READLINK */
2234#if SEP == '\\' /* Special case for MS filename syntax */
2235 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2236 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002237#if defined(MS_WINDOWS)
2238 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002239 wchar_t *ptemp;
2240 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002241 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002242 fullpath,
2243 &ptemp)) {
2244 argv0 = fullpath;
2245 }
2246#endif
2247 p = wcsrchr(argv0, SEP);
2248 /* Test for alternate separator */
2249 q = wcsrchr(p ? p : argv0, '/');
2250 if (q != NULL)
2251 p = q;
2252 if (p != NULL) {
2253 n = p + 1 - argv0;
2254 if (n > 1 && p[-1] != ':')
2255 n--; /* Drop trailing separator */
2256 }
2257 }
2258#else /* All other filename syntaxes */
2259 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2260#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002261 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002262 argv0 = fullpath;
2263 }
2264#endif
2265 p = wcsrchr(argv0, SEP);
2266 }
2267 if (p != NULL) {
2268 n = p + 1 - argv0;
2269#if SEP == '/' /* Special case for Unix filename syntax */
2270 if (n > 1)
2271 n--; /* Drop trailing separator */
2272#endif /* Unix */
2273 }
2274#endif /* All others */
2275 a = PyUnicode_FromWideChar(argv0, n);
2276 if (a == NULL)
2277 Py_FatalError("no mem for sys.path insertion");
2278 if (PyList_Insert(path, 0, a) < 0)
2279 Py_FatalError("sys.path.insert(0) failed");
2280 Py_DECREF(a);
2281}
2282
2283void
2284PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002286 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 if (av == NULL)
2288 Py_FatalError("no mem for sys.argv");
2289 if (PySys_SetObject("argv", av) != 0)
2290 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002291 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002292 if (updatepath)
2293 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002294}
Guido van Rossuma890e681998-05-12 14:59:24 +00002295
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002296void
2297PySys_SetArgv(int argc, wchar_t **argv)
2298{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002299 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002300}
2301
Victor Stinner14284c22010-04-23 12:02:30 +00002302/* Reimplementation of PyFile_WriteString() no calling indirectly
2303 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2304
2305static int
Victor Stinner79766632010-08-16 17:36:42 +00002306sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002307{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002308 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002309 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002310
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002311 if (file == NULL)
2312 return -1;
2313
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002314 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 if (writer == NULL)
2316 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002317
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002318 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 if (result == NULL) {
2320 goto error;
2321 } else {
2322 err = 0;
2323 goto finally;
2324 }
Victor Stinner14284c22010-04-23 12:02:30 +00002325
2326error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002328finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 Py_XDECREF(result);
2331 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002332}
2333
Victor Stinner79766632010-08-16 17:36:42 +00002334static int
2335sys_pyfile_write(const char *text, PyObject *file)
2336{
2337 PyObject *unicode = NULL;
2338 int err;
2339
2340 if (file == NULL)
2341 return -1;
2342
2343 unicode = PyUnicode_FromString(text);
2344 if (unicode == NULL)
2345 return -1;
2346
2347 err = sys_pyfile_write_unicode(unicode, file);
2348 Py_DECREF(unicode);
2349 return err;
2350}
Guido van Rossuma890e681998-05-12 14:59:24 +00002351
2352/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2353 Adapted from code submitted by Just van Rossum.
2354
2355 PySys_WriteStdout(format, ...)
2356 PySys_WriteStderr(format, ...)
2357
2358 The first function writes to sys.stdout; the second to sys.stderr. When
2359 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002360 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002361
Victor Stinner14284c22010-04-23 12:02:30 +00002362 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002363 signal handlers: they may raise a new exception whereas sys_write()
2364 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002365
Guido van Rossuma890e681998-05-12 14:59:24 +00002366 Both take a printf-style format string as their first argument followed
2367 by a variable length argument list determined by the format string.
2368
2369 *** WARNING ***
2370
2371 The format should limit the total size of the formatted output string to
2372 1000 bytes. In particular, this means that no unrestricted "%s" formats
2373 should occur; these should be limited using "%.<N>s where <N> is a
2374 decimal number calculated so that <N> plus the maximum size of other
2375 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2376 which can print hundreds of digits for very large numbers.
2377
2378 */
2379
2380static void
Victor Stinner09054372013-11-06 22:41:44 +01002381sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyObject *file;
2384 PyObject *error_type, *error_value, *error_traceback;
2385 char buffer[1001];
2386 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002389 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2391 if (sys_pyfile_write(buffer, file) != 0) {
2392 PyErr_Clear();
2393 fputs(buffer, fp);
2394 }
2395 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2396 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002397 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 }
2400 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002401}
2402
2403void
Guido van Rossuma890e681998-05-12 14:59:24 +00002404PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002409 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002411}
2412
2413void
Guido van Rossuma890e681998-05-12 14:59:24 +00002414PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002415{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002417
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002419 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002420 va_end(va);
2421}
2422
2423static void
Victor Stinner09054372013-11-06 22:41:44 +01002424sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002425{
2426 PyObject *file, *message;
2427 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002428 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002429
2430 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002431 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002432 message = PyUnicode_FromFormatV(format, va);
2433 if (message != NULL) {
2434 if (sys_pyfile_write_unicode(message, file) != 0) {
2435 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002436 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002437 if (utf8 != NULL)
2438 fputs(utf8, fp);
2439 }
2440 Py_DECREF(message);
2441 }
2442 PyErr_Restore(error_type, error_value, error_traceback);
2443}
2444
2445void
2446PySys_FormatStdout(const char *format, ...)
2447{
2448 va_list va;
2449
2450 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002451 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002452 va_end(va);
2453}
2454
2455void
2456PySys_FormatStderr(const char *format, ...)
2457{
2458 va_list va;
2459
2460 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002461 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002463}