blob: d463683df1df072fbf95b60bb7205f81a54bd046 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060018#include "internal/pystate.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000019#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000020#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020021#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossume2437a11992-03-23 18:20:18 +000023#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020024#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Mark Hammond8696ebc2002-10-08 02:44:31 +000026#ifdef MS_WINDOWS
27#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000028#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#endif /* MS_WINDOWS */
30
Guido van Rossum9b38a141996-09-11 23:12:24 +000031#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000032extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000033/* A string loaded from the DLL at startup: */
34extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000035#endif
36
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(_);
38_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070039_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010040_Py_IDENTIFIER(buffer);
41_Py_IDENTIFIER(builtins);
42_Py_IDENTIFIER(encoding);
43_Py_IDENTIFIER(path);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070046_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(write);
48
Guido van Rossum65bf9f21997-04-29 18:33:38 +000049PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010050_PySys_GetObjectId(_Py_Identifier *key)
51{
52 PyThreadState *tstate = PyThreadState_GET();
53 PyObject *sd = tstate->interp->sysdict;
54 if (sd == NULL)
55 return NULL;
56 return _PyDict_GetItemId(sd, key);
57}
58
59PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000060PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyThreadState *tstate = PyThreadState_GET();
63 PyObject *sd = tstate->interp->sysdict;
64 if (sd == NULL)
65 return NULL;
66 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067}
68
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069int
Victor Stinnerd67bd452013-11-06 22:36:40 +010070_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
71{
72 PyThreadState *tstate = PyThreadState_GET();
73 PyObject *sd = tstate->interp->sysdict;
74 if (v == NULL) {
75 if (_PyDict_GetItemId(sd, key) == NULL)
76 return 0;
77 else
78 return _PyDict_DelItemId(sd, key);
79 }
80 else
81 return _PyDict_SetItemId(sd, key, v);
82}
83
84int
Neal Norwitzf3081322007-08-25 00:32:45 +000085PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 PyThreadState *tstate = PyThreadState_GET();
88 PyObject *sd = tstate->interp->sysdict;
89 if (v == NULL) {
90 if (PyDict_GetItemString(sd, name) == NULL)
91 return 0;
92 else
93 return PyDict_DelItemString(sd, name);
94 }
95 else
96 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000097}
98
Victor Stinner13d49ee2010-12-04 17:24:33 +000099/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
100 error handler. If sys.stdout has a buffer attribute, use
101 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
102 sys.stdout.write(redecoded).
103
104 Helper function for sys_displayhook(). */
105static int
106sys_displayhook_unencodable(PyObject *outf, PyObject *o)
107{
108 PyObject *stdout_encoding = NULL;
109 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200110 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000111 int ret;
112
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200113 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000114 if (stdout_encoding == NULL)
115 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200116 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000117 if (stdout_encoding_str == NULL)
118 goto error;
119
120 repr_str = PyObject_Repr(o);
121 if (repr_str == NULL)
122 goto error;
123 encoded = PyUnicode_AsEncodedString(repr_str,
124 stdout_encoding_str,
125 "backslashreplace");
126 Py_DECREF(repr_str);
127 if (encoded == NULL)
128 goto error;
129
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200130 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000131 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100132 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000133 Py_DECREF(buffer);
134 Py_DECREF(encoded);
135 if (result == NULL)
136 goto error;
137 Py_DECREF(result);
138 }
139 else {
140 PyErr_Clear();
141 escaped_str = PyUnicode_FromEncodedObject(encoded,
142 stdout_encoding_str,
143 "strict");
144 Py_DECREF(encoded);
145 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
146 Py_DECREF(escaped_str);
147 goto error;
148 }
149 Py_DECREF(escaped_str);
150 }
151 ret = 0;
152 goto finally;
153
154error:
155 ret = -1;
156finally:
157 Py_XDECREF(stdout_encoding);
158 return ret;
159}
160
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000161static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000162sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000164 PyObject *outf;
Eric Snowd393c1b2017-09-14 12:18:12 -0600165 PyObject *modules = PyImport_GetModuleDict();
166 if (modules == NULL)
167 return NULL;
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
Eric Snow93c92f72017-09-13 23:46:04 -0700172 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 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000358static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000359
360static int
361trace_init(void)
362{
Nick Coghlan5a851672017-09-08 10:14:16 +1000363 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200364 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000365 "c_call", "c_exception", "c_return",
366 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200367 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 PyObject *name;
369 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000370 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 if (whatstrings[i] == NULL) {
372 name = PyUnicode_InternFromString(whatnames[i]);
373 if (name == NULL)
374 return -1;
375 whatstrings[i] = name;
376 }
377 }
378 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000379}
380
381
382static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100383call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200387 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000388
Victor Stinner78da82b2016-08-20 01:22:57 +0200389 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200391 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100392
Victor Stinner78da82b2016-08-20 01:22:57 +0200393 stack[0] = (PyObject *)frame;
394 stack[1] = whatstrings[what];
395 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000396
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200398 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000399
Victor Stinner78da82b2016-08-20 01:22:57 +0200400 PyFrame_LocalsToFast(frame, 1);
401 if (result == NULL) {
402 PyTraceBack_Here(frame);
403 }
404
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000406}
407
408static int
409profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 if (arg == NULL)
415 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100416 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (result == NULL) {
418 PyEval_SetProfile(NULL, NULL);
419 return -1;
420 }
421 Py_DECREF(result);
422 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000423}
424
425static int
426trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 PyObject *callback;
430 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (what == PyTrace_CALL)
433 callback = self;
434 else
435 callback = frame->f_trace;
436 if (callback == NULL)
437 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100438 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 if (result == NULL) {
440 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200441 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 return -1;
443 }
444 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300445 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000446 }
447 else {
448 Py_DECREF(result);
449 }
450 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000451}
Fred Draked0838392001-06-16 21:02:31 +0000452
Fred Drake8b4d01d2000-05-09 19:57:01 +0000453static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000454sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (trace_init() == -1)
457 return NULL;
458 if (args == Py_None)
459 PyEval_SetTrace(NULL, NULL);
460 else
461 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200462 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000463}
464
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000465PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000466"settrace(function)\n\
467\n\
468Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000469function call. See the debugger chapter in the library manual."
470);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000471
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000472static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000473sys_gettrace(PyObject *self, PyObject *args)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyThreadState *tstate = PyThreadState_GET();
476 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000477
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (temp == NULL)
479 temp = Py_None;
480 Py_INCREF(temp);
481 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000482}
483
484PyDoc_STRVAR(gettrace_doc,
485"gettrace()\n\
486\n\
487Return the global debug tracing function set with sys.settrace.\n\
488See the debugger chapter in the library manual."
489);
490
491static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000492sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 if (trace_init() == -1)
495 return NULL;
496 if (args == Py_None)
497 PyEval_SetProfile(NULL, NULL);
498 else
499 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200500 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000501}
502
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000503PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000504"setprofile(function)\n\
505\n\
506Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000507and return. See the profiler chapter in the library manual."
508);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000509
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000510static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000511sys_getprofile(PyObject *self, PyObject *args)
512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyThreadState *tstate = PyThreadState_GET();
514 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (temp == NULL)
517 temp = Py_None;
518 Py_INCREF(temp);
519 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000520}
521
522PyDoc_STRVAR(getprofile_doc,
523"getprofile()\n\
524\n\
525Return the profiling function set with sys.setprofile.\n\
526See the profiler chapter in the library manual."
527);
528
529static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000530sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (PyErr_WarnEx(PyExc_DeprecationWarning,
533 "sys.getcheckinterval() and sys.setcheckinterval() "
534 "are deprecated. Use sys.setswitchinterval() "
535 "instead.", 1) < 0)
536 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600537 PyInterpreterState *interp = PyThreadState_GET()->interp;
538 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 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;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600558 PyInterpreterState *interp = PyThreadState_GET()->interp;
559 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000560}
561
562PyDoc_STRVAR(getcheckinterval_doc,
563"getcheckinterval() -> current check interval; see setcheckinterval()."
564);
565
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000566static 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
Tim Peterse5e065b2003-07-06 18:36:54 +0000603static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000604sys_setrecursionlimit(PyObject *self, PyObject *args)
605{
Victor Stinner50856d52015-10-13 00:11:21 +0200606 int new_limit, mark;
607 PyThreadState *tstate;
608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
610 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200611
612 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200614 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000615 return NULL;
616 }
Victor Stinner50856d52015-10-13 00:11:21 +0200617
618 /* Issue #25274: When the recursion depth hits the recursion limit in
619 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
620 set to 1 and a RecursionError is raised. The overflowed flag is reset
621 to 0 when the recursion depth goes below the low-water mark: see
622 Py_LeaveRecursiveCall().
623
624 Reject too low new limit if the current recursion depth is higher than
625 the new low-water mark. Otherwise it may not be possible anymore to
626 reset the overflowed flag to 0. */
627 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
628 tstate = PyThreadState_GET();
629 if (tstate->recursion_depth >= mark) {
630 PyErr_Format(PyExc_RecursionError,
631 "cannot set the recursion limit to %i at "
632 "the recursion depth %i: the limit is too low",
633 new_limit, tstate->recursion_depth);
634 return NULL;
635 }
636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200638 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000639}
640
Yury Selivanov75445082015-05-11 22:57:16 -0400641static PyObject *
642sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
643{
644 if (wrapper != Py_None) {
645 if (!PyCallable_Check(wrapper)) {
646 PyErr_Format(PyExc_TypeError,
647 "callable expected, got %.50s",
648 Py_TYPE(wrapper)->tp_name);
649 return NULL;
650 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400651 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400652 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400653 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400654 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400655 }
Yury Selivanov75445082015-05-11 22:57:16 -0400656 Py_RETURN_NONE;
657}
658
659PyDoc_STRVAR(set_coroutine_wrapper_doc,
660"set_coroutine_wrapper(wrapper)\n\
661\n\
662Set a wrapper for coroutine objects."
663);
664
665static PyObject *
666sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
667{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400668 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400669 if (wrapper == NULL) {
670 wrapper = Py_None;
671 }
672 Py_INCREF(wrapper);
673 return wrapper;
674}
675
676PyDoc_STRVAR(get_coroutine_wrapper_doc,
677"get_coroutine_wrapper()\n\
678\n\
679Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
680);
681
682
Yury Selivanoveb636452016-09-08 22:01:51 -0700683static PyTypeObject AsyncGenHooksType;
684
685PyDoc_STRVAR(asyncgen_hooks_doc,
686"asyncgen_hooks\n\
687\n\
688A struct sequence providing information about asynhronous\n\
689generators hooks. The attributes are read only.");
690
691static PyStructSequence_Field asyncgen_hooks_fields[] = {
692 {"firstiter", "Hook to intercept first iteration"},
693 {"finalizer", "Hook to intercept finalization"},
694 {0}
695};
696
697static PyStructSequence_Desc asyncgen_hooks_desc = {
698 "asyncgen_hooks", /* name */
699 asyncgen_hooks_doc, /* doc */
700 asyncgen_hooks_fields , /* fields */
701 2
702};
703
704
705static PyObject *
706sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
707{
708 static char *keywords[] = {"firstiter", "finalizer", NULL};
709 PyObject *firstiter = NULL;
710 PyObject *finalizer = NULL;
711
712 if (!PyArg_ParseTupleAndKeywords(
713 args, kw, "|OO", keywords,
714 &firstiter, &finalizer)) {
715 return NULL;
716 }
717
718 if (finalizer && finalizer != Py_None) {
719 if (!PyCallable_Check(finalizer)) {
720 PyErr_Format(PyExc_TypeError,
721 "callable finalizer expected, got %.50s",
722 Py_TYPE(finalizer)->tp_name);
723 return NULL;
724 }
725 _PyEval_SetAsyncGenFinalizer(finalizer);
726 }
727 else if (finalizer == Py_None) {
728 _PyEval_SetAsyncGenFinalizer(NULL);
729 }
730
731 if (firstiter && firstiter != Py_None) {
732 if (!PyCallable_Check(firstiter)) {
733 PyErr_Format(PyExc_TypeError,
734 "callable firstiter expected, got %.50s",
735 Py_TYPE(firstiter)->tp_name);
736 return NULL;
737 }
738 _PyEval_SetAsyncGenFirstiter(firstiter);
739 }
740 else if (firstiter == Py_None) {
741 _PyEval_SetAsyncGenFirstiter(NULL);
742 }
743
744 Py_RETURN_NONE;
745}
746
747PyDoc_STRVAR(set_asyncgen_hooks_doc,
748"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
749\n\
750Set a finalizer for async generators objects."
751);
752
753static PyObject *
754sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
755{
756 PyObject *res;
757 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
758 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
759
760 res = PyStructSequence_New(&AsyncGenHooksType);
761 if (res == NULL) {
762 return NULL;
763 }
764
765 if (firstiter == NULL) {
766 firstiter = Py_None;
767 }
768
769 if (finalizer == NULL) {
770 finalizer = Py_None;
771 }
772
773 Py_INCREF(firstiter);
774 PyStructSequence_SET_ITEM(res, 0, firstiter);
775
776 Py_INCREF(finalizer);
777 PyStructSequence_SET_ITEM(res, 1, finalizer);
778
779 return res;
780}
781
782PyDoc_STRVAR(get_asyncgen_hooks_doc,
783"get_asyncgen_hooks()\n\
784\n\
785Return a namedtuple of installed asynchronous generators hooks \
786(firstiter, finalizer)."
787);
788
789
Mark Dickinsondc787d22010-05-23 13:33:13 +0000790static PyTypeObject Hash_InfoType;
791
792PyDoc_STRVAR(hash_info_doc,
793"hash_info\n\
794\n\
795A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100796hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000797
798static PyStructSequence_Field hash_info_fields[] = {
799 {"width", "width of the type used for hashing, in bits"},
800 {"modulus", "prime number giving the modulus on which the hash "
801 "function is based"},
802 {"inf", "value to be used for hash of a positive infinity"},
803 {"nan", "value to be used for hash of a nan"},
804 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100805 {"algorithm", "name of the algorithm for hashing of str, bytes and "
806 "memoryviews"},
807 {"hash_bits", "internal output size of hash algorithm"},
808 {"seed_bits", "seed size of hash algorithm"},
809 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000810 {NULL, NULL}
811};
812
813static PyStructSequence_Desc hash_info_desc = {
814 "sys.hash_info",
815 hash_info_doc,
816 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100817 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000818};
819
Matthias Klosed885e952010-07-06 10:53:30 +0000820static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000821get_hash_info(void)
822{
823 PyObject *hash_info;
824 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100825 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000826 hash_info = PyStructSequence_New(&Hash_InfoType);
827 if (hash_info == NULL)
828 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100829 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000830 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000831 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000832 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000833 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000834 PyStructSequence_SET_ITEM(hash_info, field++,
835 PyLong_FromLong(_PyHASH_INF));
836 PyStructSequence_SET_ITEM(hash_info, field++,
837 PyLong_FromLong(_PyHASH_NAN));
838 PyStructSequence_SET_ITEM(hash_info, field++,
839 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100840 PyStructSequence_SET_ITEM(hash_info, field++,
841 PyUnicode_FromString(hashfunc->name));
842 PyStructSequence_SET_ITEM(hash_info, field++,
843 PyLong_FromLong(hashfunc->hash_bits));
844 PyStructSequence_SET_ITEM(hash_info, field++,
845 PyLong_FromLong(hashfunc->seed_bits));
846 PyStructSequence_SET_ITEM(hash_info, field++,
847 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000848 if (PyErr_Occurred()) {
849 Py_CLEAR(hash_info);
850 return NULL;
851 }
852 return hash_info;
853}
854
855
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000856PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000857"setrecursionlimit(n)\n\
858\n\
859Set the maximum depth of the Python interpreter stack to n. This\n\
860limit prevents infinite recursion from causing an overflow of the C\n\
861stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000862dependent."
863);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000864
865static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000866sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000867{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000869}
870
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000871PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000872"getrecursionlimit()\n\
873\n\
874Return the current value of the recursion limit, the maximum depth\n\
875of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000876recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000877);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000878
Mark Hammond8696ebc2002-10-08 02:44:31 +0000879#ifdef MS_WINDOWS
880PyDoc_STRVAR(getwindowsversion_doc,
881"getwindowsversion()\n\
882\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000883Return information about the running version of Windows as a named tuple.\n\
884The members are named: major, minor, build, platform, service_pack,\n\
885service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200886backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700887All elements are numbers, except service_pack and platform_type which are\n\
888strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
889Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
890server. Platform_version is a 3-tuple containing a version number that is\n\
891intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000892);
893
Eric Smithf7bb5782010-01-27 00:44:57 +0000894static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
895
896static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 {"major", "Major version number"},
898 {"minor", "Minor version number"},
899 {"build", "Build number"},
900 {"platform", "Operating system platform"},
901 {"service_pack", "Latest Service Pack installed on the system"},
902 {"service_pack_major", "Service Pack major version number"},
903 {"service_pack_minor", "Service Pack minor version number"},
904 {"suite_mask", "Bit mask identifying available product suites"},
905 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700906 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000908};
909
910static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911 "sys.getwindowsversion", /* name */
912 getwindowsversion_doc, /* doc */
913 windows_version_fields, /* fields */
914 5 /* For backward compatibility,
915 only the first 5 items are accessible
916 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000917};
918
Steve Dower3e96f322015-03-02 08:01:10 -0800919/* Disable deprecation warnings about GetVersionEx as the result is
920 being passed straight through to the caller, who is responsible for
921 using it correctly. */
922#pragma warning(push)
923#pragma warning(disable:4996)
924
Mark Hammond8696ebc2002-10-08 02:44:31 +0000925static PyObject *
926sys_getwindowsversion(PyObject *self)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyObject *version;
929 int pos = 0;
930 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700931 DWORD realMajor, realMinor, realBuild;
932 HANDLE hKernel32;
933 wchar_t kernel32_path[MAX_PATH];
934 LPVOID verblock;
935 DWORD verblock_size;
936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 ver.dwOSVersionInfoSize = sizeof(ver);
938 if (!GetVersionEx((OSVERSIONINFO*) &ver))
939 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 version = PyStructSequence_New(&WindowsVersionType);
942 if (version == NULL)
943 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000944
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
946 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
948 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
949 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
950 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
951 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
952 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
953 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000954
Steve Dower74f4af72016-09-17 17:27:48 -0700955 realMajor = ver.dwMajorVersion;
956 realMinor = ver.dwMinorVersion;
957 realBuild = ver.dwBuildNumber;
958
959 // GetVersion will lie if we are running in a compatibility mode.
960 // We need to read the version info from a system file resource
961 // to accurately identify the OS version. If we fail for any reason,
962 // just return whatever GetVersion said.
963 hKernel32 = GetModuleHandleW(L"kernel32.dll");
964 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
965 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
966 (verblock = PyMem_RawMalloc(verblock_size))) {
967 VS_FIXEDFILEINFO *ffi;
968 UINT ffi_len;
969
970 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
971 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
972 realMajor = HIWORD(ffi->dwProductVersionMS);
973 realMinor = LOWORD(ffi->dwProductVersionMS);
974 realBuild = HIWORD(ffi->dwProductVersionLS);
975 }
976 PyMem_RawFree(verblock);
977 }
Segev Finer48fb7662017-06-04 20:52:27 +0300978 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
979 realMajor,
980 realMinor,
981 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700982 ));
983
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200984 if (PyErr_Occurred()) {
985 Py_DECREF(version);
986 return NULL;
987 }
Steve Dower74f4af72016-09-17 17:27:48 -0700988
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000989 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000990}
991
Steve Dower3e96f322015-03-02 08:01:10 -0800992#pragma warning(pop)
993
Steve Dowercc16be82016-09-08 10:35:16 -0700994PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
995"_enablelegacywindowsfsencoding()\n\
996\n\
997Changes the default filesystem encoding to mbcs:replace for consistency\n\
998with earlier versions of Python. See PEP 529 for more information.\n\
999\n\
1000This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1001environment variable before launching Python."
1002);
1003
1004static PyObject *
1005sys_enablelegacywindowsfsencoding(PyObject *self)
1006{
1007 Py_FileSystemDefaultEncoding = "mbcs";
1008 Py_FileSystemDefaultEncodeErrors = "replace";
1009 Py_RETURN_NONE;
1010}
1011
Mark Hammond8696ebc2002-10-08 02:44:31 +00001012#endif /* MS_WINDOWS */
1013
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001014#ifdef HAVE_DLOPEN
1015static PyObject *
1016sys_setdlopenflags(PyObject *self, PyObject *args)
1017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 int new_val;
1019 PyThreadState *tstate = PyThreadState_GET();
1020 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1021 return NULL;
1022 if (!tstate)
1023 return NULL;
1024 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001025 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001026}
1027
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001028PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001029"setdlopenflags(n) -> None\n\
1030\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001031Set the flags used by the interpreter for dlopen calls, such as when the\n\
1032interpreter loads extension modules. Among other things, this will enable\n\
1033a lazy resolving of symbols when importing a module, if called as\n\
1034sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001035sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001036can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001037
1038static PyObject *
1039sys_getdlopenflags(PyObject *self, PyObject *args)
1040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 PyThreadState *tstate = PyThreadState_GET();
1042 if (!tstate)
1043 return NULL;
1044 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001045}
1046
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001047PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001048"getdlopenflags() -> int\n\
1049\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001050Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001051The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001054
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001055#ifdef USE_MALLOPT
1056/* Link with -lmalloc (or -lmpc) on an SGI */
1057#include <malloc.h>
1058
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001059static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001060sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 int flag;
1063 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1064 return NULL;
1065 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001066 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001067}
1068#endif /* USE_MALLOPT */
1069
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001070size_t
1071_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001075 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001076
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 /* Make sure the type is initialized. float gets initialized late */
1078 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001079 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001080
Benjamin Petersonce798522012-01-22 11:24:29 -05001081 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 if (method == NULL) {
1083 if (!PyErr_Occurred())
1084 PyErr_Format(PyExc_TypeError,
1085 "Type %.100s doesn't define __sizeof__",
1086 Py_TYPE(o)->tp_name);
1087 }
1088 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001089 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 Py_DECREF(method);
1091 }
1092
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001093 if (res == NULL)
1094 return (size_t)-1;
1095
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001096 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001097 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001098 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001099 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001101 if (size < 0) {
1102 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1103 return (size_t)-1;
1104 }
1105
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001107 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001108 return ((size_t)size) + sizeof(PyGC_Head);
1109 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001110}
1111
1112static PyObject *
1113sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1114{
1115 static char *kwlist[] = {"object", "default", 0};
1116 size_t size;
1117 PyObject *o, *dflt = NULL;
1118
1119 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1120 kwlist, &o, &dflt))
1121 return NULL;
1122
1123 size = _PySys_GetSizeOf(o);
1124
1125 if (size == (size_t)-1 && PyErr_Occurred()) {
1126 /* Has a default value been given */
1127 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1128 PyErr_Clear();
1129 Py_INCREF(dflt);
1130 return dflt;
1131 }
1132 else
1133 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001135
1136 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001137}
1138
1139PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001140"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001141\n\
1142Return the size of object in bytes.");
1143
1144static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001145sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001148}
1149
Tim Peters4be93d02002-07-07 19:59:50 +00001150#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001151static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001152sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001155}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001156#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001157
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001158PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001159"getrefcount(object) -> integer\n\
1160\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001161Return the reference count of object. The count returned is generally\n\
1162one higher than you might expect, because it includes the (temporary)\n\
1163reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001164);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001165
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001166static PyObject *
1167sys_getallocatedblocks(PyObject *self)
1168{
1169 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1170}
1171
1172PyDoc_STRVAR(getallocatedblocks_doc,
1173"getallocatedblocks() -> integer\n\
1174\n\
1175Return the number of memory blocks currently allocated, regardless of their\n\
1176size."
1177);
1178
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001179#ifdef COUNT_ALLOCS
1180static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001181sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001186}
1187#endif
1188
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001189PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001190"_getframe([depth]) -> frameobject\n\
1191\n\
1192Return a frame object from the call stack. If optional integer depth is\n\
1193given, return the frame object that many calls below the top of the stack.\n\
1194If that is deeper than the call stack, ValueError is raised. The default\n\
1195for depth is zero, returning the frame at the top of the call stack.\n\
1196\n\
1197This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001198purposes only."
1199);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001200
1201static PyObject *
1202sys_getframe(PyObject *self, PyObject *args)
1203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 PyFrameObject *f = PyThreadState_GET()->frame;
1205 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1208 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001210 while (depth > 0 && f != NULL) {
1211 f = f->f_back;
1212 --depth;
1213 }
1214 if (f == NULL) {
1215 PyErr_SetString(PyExc_ValueError,
1216 "call stack is not deep enough");
1217 return NULL;
1218 }
1219 Py_INCREF(f);
1220 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001221}
1222
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001223PyDoc_STRVAR(current_frames_doc,
1224"_current_frames() -> dictionary\n\
1225\n\
1226Return a dictionary mapping each current thread T's thread id to T's\n\
1227current stack frame.\n\
1228\n\
1229This function should be used for specialized purposes only."
1230);
1231
1232static PyObject *
1233sys_current_frames(PyObject *self, PyObject *noargs)
1234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001236}
1237
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001238PyDoc_STRVAR(call_tracing_doc,
1239"call_tracing(func, args) -> object\n\
1240\n\
1241Call func(*args), while tracing is enabled. The tracing state is\n\
1242saved, and restored afterwards. This is intended to be called from\n\
1243a debugger from a checkpoint, to recursively debug some other code."
1244);
1245
1246static PyObject *
1247sys_call_tracing(PyObject *self, PyObject *args)
1248{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 PyObject *func, *funcargs;
1250 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1251 return NULL;
1252 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001253}
1254
Jeremy Hylton985eba52003-02-05 23:13:00 +00001255PyDoc_STRVAR(callstats_doc,
1256"callstats() -> tuple of integers\n\
1257\n\
1258Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1259when Python was built. Otherwise, return None.\n\
1260\n\
1261When enabled, this function returns detailed, implementation-specific\n\
1262details about the number of function calls executed. The return value is\n\
1263a 11-tuple where the entries in the tuple are counts of:\n\
12640. all function calls\n\
12651. calls to PyFunction_Type objects\n\
12662. PyFunction calls that do not create an argument tuple\n\
12673. PyFunction calls that do not create an argument tuple\n\
1268 and bypass PyEval_EvalCodeEx()\n\
12694. PyMethod calls\n\
12705. PyMethod calls on bound methods\n\
12716. PyType calls\n\
12727. PyCFunction calls\n\
12738. generator calls\n\
12749. All other calls\n\
127510. Number of stack pops performed by call_function()"
1276);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001277
Victor Stinner048afd92016-11-28 11:59:04 +01001278static PyObject *
1279sys_callstats(PyObject *self)
1280{
1281 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1282 "sys.callstats() has been deprecated in Python 3.7 "
1283 "and will be removed in the future", 1) < 0) {
1284 return NULL;
1285 }
1286
1287 Py_RETURN_NONE;
1288}
1289
1290
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001291#ifdef __cplusplus
1292extern "C" {
1293#endif
1294
David Malcolm49526f42012-06-22 14:55:41 -04001295static PyObject *
1296sys_debugmallocstats(PyObject *self, PyObject *args)
1297{
1298#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001299 if (_PyMem_PymallocEnabled()) {
1300 _PyObject_DebugMallocStats(stderr);
1301 fputc('\n', stderr);
1302 }
David Malcolm49526f42012-06-22 14:55:41 -04001303#endif
1304 _PyObject_DebugTypeStats(stderr);
1305
1306 Py_RETURN_NONE;
1307}
1308PyDoc_STRVAR(debugmallocstats_doc,
1309"_debugmallocstats()\n\
1310\n\
1311Print summary info to stderr about the state of\n\
1312pymalloc's structures.\n\
1313\n\
1314In Py_DEBUG mode, also perform some expensive internal consistency\n\
1315checks.\n\
1316");
1317
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001318#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001319/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001320extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001321#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001322
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001323#ifdef DYNAMIC_EXECUTION_PROFILE
1324/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001325extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001326#endif
1327
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001328#ifdef __cplusplus
1329}
1330#endif
1331
Christian Heimes15ebc882008-02-04 18:48:49 +00001332static PyObject *
1333sys_clear_type_cache(PyObject* self, PyObject* args)
1334{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 PyType_ClearCache();
1336 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001337}
1338
1339PyDoc_STRVAR(sys_clear_type_cache__doc__,
1340"_clear_type_cache() -> None\n\
1341Clear the internal type lookup cache.");
1342
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001343static PyObject *
1344sys_is_finalizing(PyObject* self, PyObject* args)
1345{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001346 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001347}
1348
1349PyDoc_STRVAR(is_finalizing_doc,
1350"is_finalizing()\n\
1351Return True if Python is exiting.");
1352
Christian Heimes15ebc882008-02-04 18:48:49 +00001353
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001354#ifdef ANDROID_API_LEVEL
1355PyDoc_STRVAR(getandroidapilevel_doc,
1356"getandroidapilevel()\n\
1357\n\
1358Return the build time API version of Android as an integer.");
1359
1360static PyObject *
1361sys_getandroidapilevel(PyObject *self)
1362{
1363 return PyLong_FromLong(ANDROID_API_LEVEL);
1364}
1365#endif /* ANDROID_API_LEVEL */
1366
1367
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001368static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001370 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 callstats_doc},
1372 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1373 sys_clear_type_cache__doc__},
1374 {"_current_frames", sys_current_frames, METH_NOARGS,
1375 current_frames_doc},
1376 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1377 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1378 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1379 {"exit", sys_exit, METH_VARARGS, exit_doc},
1380 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1381 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001382#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1384 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001385#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001386 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1387 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001388#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001390#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001391#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001393#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1395 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001396 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1397 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001398#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001399 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001400#endif
1401#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001403#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1405 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1406 getrecursionlimit_doc},
1407 {"getsizeof", (PyCFunction)sys_getsizeof,
1408 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1409 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001410#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001411 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1412 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001413 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1414 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001415#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001417 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001418#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001420#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1422 setcheckinterval_doc},
1423 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1424 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1426 setswitchinterval_doc},
1427 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1428 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001429#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1431 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001432#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1434 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1435 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1436 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001437 {"settrace", sys_settrace, METH_O, settrace_doc},
1438 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1439 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001440 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001441 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001442 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1443 set_coroutine_wrapper_doc},
1444 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1445 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001446 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001447 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1448 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1449 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001450#ifdef ANDROID_API_LEVEL
1451 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1452 getandroidapilevel_doc},
1453#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001455};
1456
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001457static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001458list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001460 PyObject *list = PyList_New(0);
1461 int i;
1462 if (list == NULL)
1463 return NULL;
1464 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1465 PyObject *name = PyUnicode_FromString(
1466 PyImport_Inittab[i].name);
1467 if (name == NULL)
1468 break;
1469 PyList_Append(list, name);
1470 Py_DECREF(name);
1471 }
1472 if (PyList_Sort(list) != 0) {
1473 Py_DECREF(list);
1474 list = NULL;
1475 }
1476 if (list) {
1477 PyObject *v = PyList_AsTuple(list);
1478 Py_DECREF(list);
1479 list = v;
1480 }
1481 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001482}
1483
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001484static PyObject *
1485get_warnoptions(void)
1486{
Eric Snowdae02762017-09-14 00:35:58 -07001487 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001488 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1489 Py_XDECREF(warnoptions);
1490 warnoptions = PyList_New(0);
1491 if (warnoptions == NULL)
1492 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001493 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1494 Py_DECREF(warnoptions);
1495 return NULL;
1496 }
1497 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001498 }
1499 return warnoptions;
1500}
Guido van Rossum23fff912000-12-15 22:02:05 +00001501
1502void
1503PySys_ResetWarnOptions(void)
1504{
Eric Snowdae02762017-09-14 00:35:58 -07001505 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 if (warnoptions == NULL || !PyList_Check(warnoptions))
1507 return;
1508 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001509}
1510
1511void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001512PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001513{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001514 PyObject *warnoptions = get_warnoptions();
1515 if (warnoptions == NULL)
1516 return;
Victor Stinner9ca9c252010-05-19 16:53:30 +00001517 PyList_Append(warnoptions, unicode);
1518}
1519
1520void
1521PySys_AddWarnOption(const wchar_t *s)
1522{
1523 PyObject *unicode;
1524 unicode = PyUnicode_FromWideChar(s, -1);
1525 if (unicode == NULL)
1526 return;
1527 PySys_AddWarnOptionUnicode(unicode);
1528 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001529}
1530
Christian Heimes33fe8092008-04-13 13:53:33 +00001531int
1532PySys_HasWarnOptions(void)
1533{
Eric Snowdae02762017-09-14 00:35:58 -07001534 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001535 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1536}
1537
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001538static PyObject *
1539get_xoptions(void)
1540{
Eric Snowdae02762017-09-14 00:35:58 -07001541 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001542 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1543 Py_XDECREF(xoptions);
1544 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001545 if (xoptions == NULL)
1546 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001547 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1548 Py_DECREF(xoptions);
1549 return NULL;
1550 }
1551 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001552 }
1553 return xoptions;
1554}
1555
1556void
1557PySys_AddXOption(const wchar_t *s)
1558{
1559 PyObject *opts;
1560 PyObject *name = NULL, *value = NULL;
1561 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001562
1563 opts = get_xoptions();
1564 if (opts == NULL)
1565 goto error;
1566
1567 name_end = wcschr(s, L'=');
1568 if (!name_end) {
1569 name = PyUnicode_FromWideChar(s, -1);
1570 value = Py_True;
1571 Py_INCREF(value);
1572 }
1573 else {
1574 name = PyUnicode_FromWideChar(s, name_end - s);
1575 value = PyUnicode_FromWideChar(name_end + 1, -1);
1576 }
1577 if (name == NULL || value == NULL)
1578 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001579 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001580 Py_DECREF(name);
1581 Py_DECREF(value);
1582 return;
1583
1584error:
1585 Py_XDECREF(name);
1586 Py_XDECREF(value);
1587 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001588 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001589 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001590 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001591}
1592
1593PyObject *
1594PySys_GetXOptions(void)
1595{
1596 return get_xoptions();
1597}
1598
Guido van Rossum40552d01998-08-06 03:34:39 +00001599/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1600 Two literals concatenated works just fine. If you have a K&R compiler
1601 or other abomination that however *does* understand longer strings,
1602 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001603PyDoc_VAR(sys_doc) =
1604PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001605"This module provides access to some objects used or maintained by the\n\
1606interpreter and to functions that interact strongly with the interpreter.\n\
1607\n\
1608Dynamic objects:\n\
1609\n\
1610argv -- command line arguments; argv[0] is the script pathname if known\n\
1611path -- module search path; path[0] is the script directory, else ''\n\
1612modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001613\n\
1614displayhook -- called to show results in an interactive session\n\
1615excepthook -- called to handle any uncaught exception other than SystemExit\n\
1616 To customize printing in an interactive session or to install a custom\n\
1617 top-level exception handler, assign other functions to replace these.\n\
1618\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001619stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001620stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001621stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001622 By assigning other file objects (or objects that behave like files)\n\
1623 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001624\n\
1625last_type -- type of last uncaught exception\n\
1626last_value -- value of last uncaught exception\n\
1627last_traceback -- traceback of last uncaught exception\n\
1628 These three are only available in an interactive session after a\n\
1629 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001630"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001631)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001632/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001633PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001634"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001635Static objects:\n\
1636\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001637builtin_module_names -- tuple of module names built into this interpreter\n\
1638copyright -- copyright notice pertaining to this interpreter\n\
1639exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001640executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001641float_info -- a struct sequence with information about the float implementation.\n\
1642float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001643hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001644hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001645implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001646int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001647maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001648maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001649platform -- platform identifier\n\
1650prefix -- prefix used to find the Python library\n\
1651thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001652version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001653version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001654"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001655)
Steve Dowercc16be82016-09-08 10:35:16 -07001656#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001657/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001658PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001659"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001660winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001661"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001662)
Steve Dowercc16be82016-09-08 10:35:16 -07001663#endif /* MS_COREDLL */
1664#ifdef MS_WINDOWS
1665/* concatenating string here */
1666PyDoc_STR(
1667"_enablelegacywindowsfsencoding -- [Windows only] \n\
1668"
1669)
1670#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001671PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001672"__stdin__ -- the original stdin; don't touch!\n\
1673__stdout__ -- the original stdout; don't touch!\n\
1674__stderr__ -- the original stderr; don't touch!\n\
1675__displayhook__ -- the original displayhook; don't touch!\n\
1676__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001677\n\
1678Functions:\n\
1679\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001680displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001681excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001682exc_info() -- return thread-safe information about the current exception\n\
1683exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001684getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001685getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001686getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001687getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001688getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001689gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001690setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001691setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001692setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001693setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001694settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001695"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001696)
Fred Drakeccede592000-08-14 20:59:57 +00001697/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001698
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001699
1700PyDoc_STRVAR(flags__doc__,
1701"sys.flags\n\
1702\n\
1703Flags provided through command line arguments or environment vars.");
1704
1705static PyTypeObject FlagsType;
1706
1707static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 {"inspect", "-i"},
1710 {"interactive", "-i"},
1711 {"optimize", "-O or -OO"},
1712 {"dont_write_bytecode", "-B"},
1713 {"no_user_site", "-s"},
1714 {"no_site", "-S"},
1715 {"ignore_environment", "-E"},
1716 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 /* {"unbuffered", "-u"}, */
1718 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001719 {"bytes_warning", "-b"},
1720 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001721 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001722 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001724};
1725
1726static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 "sys.flags", /* name */
1728 flags__doc__, /* doc */
1729 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001730 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001731};
1732
1733static PyObject*
1734make_flags(void)
1735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 int pos = 0;
1737 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001738
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 seq = PyStructSequence_New(&FlagsType);
1740 if (seq == NULL)
1741 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001742
1743#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001747 SetFlag(Py_InspectFlag);
1748 SetFlag(Py_InteractiveFlag);
1749 SetFlag(Py_OptimizeFlag);
1750 SetFlag(Py_DontWriteBytecodeFlag);
1751 SetFlag(Py_NoUserSiteDirectory);
1752 SetFlag(Py_NoSiteFlag);
1753 SetFlag(Py_IgnoreEnvironmentFlag);
1754 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 /* SetFlag(saw_unbuffered_flag); */
1756 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001757 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001758 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001759 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001760 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001761#undef SetFlag
1762
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001763 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001764 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001765 return NULL;
1766 }
1767 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001768}
1769
Eric Smith0e5b5622009-02-06 01:32:42 +00001770PyDoc_STRVAR(version_info__doc__,
1771"sys.version_info\n\
1772\n\
1773Version information as a named tuple.");
1774
1775static PyTypeObject VersionInfoType;
1776
1777static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 {"major", "Major release number"},
1779 {"minor", "Minor release number"},
1780 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001781 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 {"serial", "Serial release number"},
1783 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001784};
1785
1786static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 "sys.version_info", /* name */
1788 version_info__doc__, /* doc */
1789 version_info_fields, /* fields */
1790 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001791};
1792
1793static PyObject *
1794make_version_info(void)
1795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 PyObject *version_info;
1797 char *s;
1798 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001799
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 version_info = PyStructSequence_New(&VersionInfoType);
1801 if (version_info == NULL) {
1802 return NULL;
1803 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 /*
1806 * These release level checks are mutually exclusive and cover
1807 * the field, so don't get too fancy with the pre-processor!
1808 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001809#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001811#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001813#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001815#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001817#endif
1818
1819#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001821#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001823
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 SetIntItem(PY_MAJOR_VERSION);
1825 SetIntItem(PY_MINOR_VERSION);
1826 SetIntItem(PY_MICRO_VERSION);
1827 SetStrItem(s);
1828 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001829#undef SetIntItem
1830#undef SetStrItem
1831
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 if (PyErr_Occurred()) {
1833 Py_CLEAR(version_info);
1834 return NULL;
1835 }
1836 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001837}
1838
Brett Cannon3adc7b72012-07-09 14:22:12 -04001839/* sys.implementation values */
1840#define NAME "cpython"
1841const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001842#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1843#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001844#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001845const char *_PySys_ImplCacheTag = TAG;
1846#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001847#undef MAJOR
1848#undef MINOR
1849#undef TAG
1850
Barry Warsaw409da152012-06-03 16:18:47 -04001851static PyObject *
1852make_impl_info(PyObject *version_info)
1853{
1854 int res;
1855 PyObject *impl_info, *value, *ns;
1856
1857 impl_info = PyDict_New();
1858 if (impl_info == NULL)
1859 return NULL;
1860
1861 /* populate the dict */
1862
Brett Cannon3adc7b72012-07-09 14:22:12 -04001863 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001864 if (value == NULL)
1865 goto error;
1866 res = PyDict_SetItemString(impl_info, "name", value);
1867 Py_DECREF(value);
1868 if (res < 0)
1869 goto error;
1870
Brett Cannon3adc7b72012-07-09 14:22:12 -04001871 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001872 if (value == NULL)
1873 goto error;
1874 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1875 Py_DECREF(value);
1876 if (res < 0)
1877 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001878
1879 res = PyDict_SetItemString(impl_info, "version", version_info);
1880 if (res < 0)
1881 goto error;
1882
1883 value = PyLong_FromLong(PY_VERSION_HEX);
1884 if (value == NULL)
1885 goto error;
1886 res = PyDict_SetItemString(impl_info, "hexversion", value);
1887 Py_DECREF(value);
1888 if (res < 0)
1889 goto error;
1890
doko@ubuntu.com55532312016-06-14 08:55:19 +02001891#ifdef MULTIARCH
1892 value = PyUnicode_FromString(MULTIARCH);
1893 if (value == NULL)
1894 goto error;
1895 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1896 Py_DECREF(value);
1897 if (res < 0)
1898 goto error;
1899#endif
1900
Barry Warsaw409da152012-06-03 16:18:47 -04001901 /* dict ready */
1902
1903 ns = _PyNamespace_New(impl_info);
1904 Py_DECREF(impl_info);
1905 return ns;
1906
1907error:
1908 Py_CLEAR(impl_info);
1909 return NULL;
1910}
1911
Martin v. Löwis1a214512008-06-11 05:26:20 +00001912static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 PyModuleDef_HEAD_INIT,
1914 "sys",
1915 sys_doc,
1916 -1, /* multiple "initialization" just copies the module dict. */
1917 sys_methods,
1918 NULL,
1919 NULL,
1920 NULL,
1921 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001922};
1923
Eric Snow6b4be192017-05-22 21:36:03 -07001924/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001925#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001926 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001927 PyObject *v = (value); \
1928 if (v == NULL) \
1929 return NULL; \
1930 res = PyDict_SetItemString(sysdict, key, v); \
1931 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001932 return NULL; \
1933 } \
1934 } while (0)
1935#define SET_SYS_FROM_STRING(key, value) \
1936 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001937 PyObject *v = (value); \
1938 if (v == NULL) \
1939 return NULL; \
1940 res = PyDict_SetItemString(sysdict, key, v); \
1941 Py_DECREF(v); \
1942 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001943 return NULL; \
1944 } \
1945 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001946
Eric Snow6b4be192017-05-22 21:36:03 -07001947PyObject *
1948_PySys_BeginInit(void)
1949{
1950 PyObject *m, *sysdict, *version_info;
1951 int res;
1952
Eric Snowd393c1b2017-09-14 12:18:12 -06001953 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Eric Snow6b4be192017-05-22 21:36:03 -07001954 if (m == NULL)
1955 return NULL;
1956 sysdict = PyModule_GetDict(m);
1957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 /* Check that stdin is not a directory
1959 Using shell redirection, you can redirect stdin to a directory,
1960 crashing the Python interpreter. Catch this common mistake here
1961 and output a useful error message. Note that under MS Windows,
1962 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001963#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001964 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001965 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001966 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 S_ISDIR(sb.st_mode)) {
1968 /* There's nothing more we can do. */
1969 /* Py_FatalError() will core dump, so just exit. */
1970 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1971 exit(EXIT_FAILURE);
1972 }
1973 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001974#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001975
Nick Coghland6009512014-11-20 21:39:37 +10001976 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001977
Victor Stinner8fea2522013-10-27 17:15:42 +01001978 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1979 PyDict_GetItemString(sysdict, "displayhook"));
1980 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1981 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 SET_SYS_FROM_STRING("version",
1983 PyUnicode_FromString(Py_GetVersion()));
1984 SET_SYS_FROM_STRING("hexversion",
1985 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001986 SET_SYS_FROM_STRING("_git",
1987 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1988 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001989 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001990 SET_SYS_FROM_STRING("api_version",
1991 PyLong_FromLong(PYTHON_API_VERSION));
1992 SET_SYS_FROM_STRING("copyright",
1993 PyUnicode_FromString(Py_GetCopyright()));
1994 SET_SYS_FROM_STRING("platform",
1995 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 SET_SYS_FROM_STRING("maxsize",
1997 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1998 SET_SYS_FROM_STRING("float_info",
1999 PyFloat_GetInfo());
2000 SET_SYS_FROM_STRING("int_info",
2001 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002002 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002003 if (Hash_InfoType.tp_name == NULL) {
2004 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
2005 return NULL;
2006 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002007 SET_SYS_FROM_STRING("hash_info",
2008 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002010 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 SET_SYS_FROM_STRING("builtin_module_names",
2012 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002013#if PY_BIG_ENDIAN
2014 SET_SYS_FROM_STRING("byteorder",
2015 PyUnicode_FromString("big"));
2016#else
2017 SET_SYS_FROM_STRING("byteorder",
2018 PyUnicode_FromString("little"));
2019#endif
Fred Drake099325e2000-08-14 15:47:03 +00002020
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002021#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 SET_SYS_FROM_STRING("dllhandle",
2023 PyLong_FromVoidPtr(PyWin_DLLhModule));
2024 SET_SYS_FROM_STRING("winver",
2025 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002026#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002027#ifdef ABIFLAGS
2028 SET_SYS_FROM_STRING("abiflags",
2029 PyUnicode_FromString(ABIFLAGS));
2030#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002031
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002033 if (VersionInfoType.tp_name == NULL) {
2034 if (PyStructSequence_InitType2(&VersionInfoType,
2035 &version_info_desc) < 0)
2036 return NULL;
2037 }
Barry Warsaw409da152012-06-03 16:18:47 -04002038 version_info = make_version_info();
2039 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* prevent user from creating new instances */
2041 VersionInfoType.tp_init = NULL;
2042 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002043 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2044 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2045 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002046
Barry Warsaw409da152012-06-03 16:18:47 -04002047 /* implementation */
2048 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2049
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002051 if (FlagsType.tp_name == 0) {
2052 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2053 return NULL;
2054 }
Eric Snow6b4be192017-05-22 21:36:03 -07002055 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002057
2058#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 /* getwindowsversion */
2060 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002061 if (PyStructSequence_InitType2(&WindowsVersionType,
2062 &windows_version_desc) < 0)
2063 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* prevent user from creating new instances */
2065 WindowsVersionType.tp_init = NULL;
2066 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002067 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2068 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2069 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002070#endif
2071
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002073#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 SET_SYS_FROM_STRING("float_repr_style",
2075 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002076#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 SET_SYS_FROM_STRING("float_repr_style",
2078 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002079#endif
2080
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002081 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002082
Yury Selivanoveb636452016-09-08 22:01:51 -07002083 /* initialize asyncgen_hooks */
2084 if (AsyncGenHooksType.tp_name == NULL) {
2085 if (PyStructSequence_InitType2(
2086 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2087 return NULL;
2088 }
2089 }
2090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 if (PyErr_Occurred())
2092 return NULL;
2093 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002094}
2095
Eric Snow6b4be192017-05-22 21:36:03 -07002096#undef SET_SYS_FROM_STRING
2097#undef SET_SYS_FROM_STRING_BORROW
2098
2099/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002100#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2101 do { \
2102 PyObject *v = (value); \
2103 if (v == NULL) \
2104 return -1; \
2105 res = PyDict_SetItemString(sysdict, key, v); \
2106 Py_DECREF(v); \
2107 if (res < 0) { \
2108 return res; \
2109 } \
2110 } while (0)
2111
2112int
2113_PySys_EndInit(PyObject *sysdict)
2114{
2115 int res;
2116
2117 /* Set flags to their final values */
2118 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2119 /* prevent user from creating new instances */
2120 FlagsType.tp_init = NULL;
2121 FlagsType.tp_new = NULL;
2122 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2123 if (res < 0) {
2124 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2125 return res;
2126 }
2127 PyErr_Clear();
2128 }
2129
2130 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2131 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2132 SET_SYS_FROM_STRING_INT_RESULT("executable",
2133 PyUnicode_FromWideChar(
2134 Py_GetProgramFullPath(), -1));
2135 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2136 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2137 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2138 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2139 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2140 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2141 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2142 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2143
Eric Snowdae02762017-09-14 00:35:58 -07002144 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002145 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002146
Eric Snowdae02762017-09-14 00:35:58 -07002147 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002148 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002149
2150 if (PyErr_Occurred())
2151 return -1;
2152 return 0;
2153}
2154
2155#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002156
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002157static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002158makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 int i, n;
2161 const wchar_t *p;
2162 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 n = 1;
2165 p = path;
2166 while ((p = wcschr(p, delim)) != NULL) {
2167 n++;
2168 p++;
2169 }
2170 v = PyList_New(n);
2171 if (v == NULL)
2172 return NULL;
2173 for (i = 0; ; i++) {
2174 p = wcschr(path, delim);
2175 if (p == NULL)
2176 p = path + wcslen(path); /* End of string */
2177 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2178 if (w == NULL) {
2179 Py_DECREF(v);
2180 return NULL;
2181 }
2182 PyList_SetItem(v, i, w);
2183 if (*p == '\0')
2184 break;
2185 path = p+1;
2186 }
2187 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002188}
2189
2190void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002191PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 PyObject *v;
2194 if ((v = makepathobject(path, DELIM)) == NULL)
2195 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002196 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 Py_FatalError("can't assign sys.path");
2198 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002199}
2200
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002201static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002202makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyObject *av;
2205 if (argc <= 0 || argv == NULL) {
2206 /* Ensure at least one (empty) argument is seen */
2207 static wchar_t *empty_argv[1] = {L""};
2208 argv = empty_argv;
2209 argc = 1;
2210 }
2211 av = PyList_New(argc);
2212 if (av != NULL) {
2213 int i;
2214 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 if (v == NULL) {
2217 Py_DECREF(av);
2218 av = NULL;
2219 break;
2220 }
2221 PyList_SetItem(av, i, v);
2222 }
2223 }
2224 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002225}
2226
Nick Coghland26c18a2010-08-17 13:06:11 +00002227#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2228 (argc > 0 && argv0 != NULL && \
2229 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002230
2231static void
2232sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002233{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002234 wchar_t *argv0;
2235 wchar_t *p = NULL;
2236 Py_ssize_t n = 0;
2237 PyObject *a;
2238 PyObject *path;
2239#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002240 wchar_t link[MAXPATHLEN+1];
2241 wchar_t argv0copy[2*MAXPATHLEN+1];
2242 int nr = 0;
2243#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002244#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002246#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002248#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002249
Victor Stinnerbd303c12013-11-07 23:07:29 +01002250 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002251 if (path == NULL)
2252 return;
2253
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002254 argv0 = argv[0];
2255
2256#ifdef HAVE_READLINK
2257 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2258 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2259 if (nr > 0) {
2260 /* It's a symlink */
2261 link[nr] = '\0';
2262 if (link[0] == SEP)
2263 argv0 = link; /* Link to absolute path */
2264 else if (wcschr(link, SEP) == NULL)
2265 ; /* Link without path */
2266 else {
2267 /* Must join(dirname(argv0), link) */
2268 wchar_t *q = wcsrchr(argv0, SEP);
2269 if (q == NULL)
2270 argv0 = link; /* argv0 without path */
2271 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002272 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2273 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002274 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002275 wcsncpy(q+1, link, MAXPATHLEN);
2276 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002277 argv0 = argv0copy;
2278 }
2279 }
2280 }
2281#endif /* HAVE_READLINK */
2282#if SEP == '\\' /* Special case for MS filename syntax */
2283 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2284 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002285#if defined(MS_WINDOWS)
2286 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002287 wchar_t *ptemp;
2288 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002289 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002290 fullpath,
2291 &ptemp)) {
2292 argv0 = fullpath;
2293 }
2294#endif
2295 p = wcsrchr(argv0, SEP);
2296 /* Test for alternate separator */
2297 q = wcsrchr(p ? p : argv0, '/');
2298 if (q != NULL)
2299 p = q;
2300 if (p != NULL) {
2301 n = p + 1 - argv0;
2302 if (n > 1 && p[-1] != ':')
2303 n--; /* Drop trailing separator */
2304 }
2305 }
2306#else /* All other filename syntaxes */
2307 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2308#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002309 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002310 argv0 = fullpath;
2311 }
2312#endif
2313 p = wcsrchr(argv0, SEP);
2314 }
2315 if (p != NULL) {
2316 n = p + 1 - argv0;
2317#if SEP == '/' /* Special case for Unix filename syntax */
2318 if (n > 1)
2319 n--; /* Drop trailing separator */
2320#endif /* Unix */
2321 }
2322#endif /* All others */
2323 a = PyUnicode_FromWideChar(argv0, n);
2324 if (a == NULL)
2325 Py_FatalError("no mem for sys.path insertion");
2326 if (PyList_Insert(path, 0, a) < 0)
2327 Py_FatalError("sys.path.insert(0) failed");
2328 Py_DECREF(a);
2329}
2330
2331void
2332PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 if (av == NULL)
2336 Py_FatalError("no mem for sys.argv");
2337 if (PySys_SetObject("argv", av) != 0)
2338 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002340 if (updatepath)
2341 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002342}
Guido van Rossuma890e681998-05-12 14:59:24 +00002343
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002344void
2345PySys_SetArgv(int argc, wchar_t **argv)
2346{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002347 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002348}
2349
Victor Stinner14284c22010-04-23 12:02:30 +00002350/* Reimplementation of PyFile_WriteString() no calling indirectly
2351 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2352
2353static int
Victor Stinner79766632010-08-16 17:36:42 +00002354sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002355{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002356 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002358
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002359 if (file == NULL)
2360 return -1;
2361
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002362 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (writer == NULL)
2364 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002365
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002366 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 if (result == NULL) {
2368 goto error;
2369 } else {
2370 err = 0;
2371 goto finally;
2372 }
Victor Stinner14284c22010-04-23 12:02:30 +00002373
2374error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002375 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002376finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 Py_XDECREF(result);
2379 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002380}
2381
Victor Stinner79766632010-08-16 17:36:42 +00002382static int
2383sys_pyfile_write(const char *text, PyObject *file)
2384{
2385 PyObject *unicode = NULL;
2386 int err;
2387
2388 if (file == NULL)
2389 return -1;
2390
2391 unicode = PyUnicode_FromString(text);
2392 if (unicode == NULL)
2393 return -1;
2394
2395 err = sys_pyfile_write_unicode(unicode, file);
2396 Py_DECREF(unicode);
2397 return err;
2398}
Guido van Rossuma890e681998-05-12 14:59:24 +00002399
2400/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2401 Adapted from code submitted by Just van Rossum.
2402
2403 PySys_WriteStdout(format, ...)
2404 PySys_WriteStderr(format, ...)
2405
2406 The first function writes to sys.stdout; the second to sys.stderr. When
2407 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002408 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002409
Victor Stinner14284c22010-04-23 12:02:30 +00002410 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002411 signal handlers: they may raise a new exception whereas sys_write()
2412 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002413
Guido van Rossuma890e681998-05-12 14:59:24 +00002414 Both take a printf-style format string as their first argument followed
2415 by a variable length argument list determined by the format string.
2416
2417 *** WARNING ***
2418
2419 The format should limit the total size of the formatted output string to
2420 1000 bytes. In particular, this means that no unrestricted "%s" formats
2421 should occur; these should be limited using "%.<N>s where <N> is a
2422 decimal number calculated so that <N> plus the maximum size of other
2423 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2424 which can print hundreds of digits for very large numbers.
2425
2426 */
2427
2428static void
Victor Stinner09054372013-11-06 22:41:44 +01002429sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002431 PyObject *file;
2432 PyObject *error_type, *error_value, *error_traceback;
2433 char buffer[1001];
2434 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002435
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002437 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2439 if (sys_pyfile_write(buffer, file) != 0) {
2440 PyErr_Clear();
2441 fputs(buffer, fp);
2442 }
2443 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2444 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002445 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 }
2448 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002449}
2450
2451void
Guido van Rossuma890e681998-05-12 14:59:24 +00002452PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002457 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002459}
2460
2461void
Guido van Rossuma890e681998-05-12 14:59:24 +00002462PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002465
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002467 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002468 va_end(va);
2469}
2470
2471static void
Victor Stinner09054372013-11-06 22:41:44 +01002472sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002473{
2474 PyObject *file, *message;
2475 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002476 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002477
2478 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002479 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002480 message = PyUnicode_FromFormatV(format, va);
2481 if (message != NULL) {
2482 if (sys_pyfile_write_unicode(message, file) != 0) {
2483 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002484 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002485 if (utf8 != NULL)
2486 fputs(utf8, fp);
2487 }
2488 Py_DECREF(message);
2489 }
2490 PyErr_Restore(error_type, error_value, error_traceback);
2491}
2492
2493void
2494PySys_FormatStdout(const char *format, ...)
2495{
2496 va_list va;
2497
2498 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002499 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002500 va_end(va);
2501}
2502
2503void
2504PySys_FormatStderr(const char *format, ...)
2505{
2506 va_list va;
2507
2508 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002509 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002511}