blob: 9e13d49417dbc9f7090742198f66817f91f32a98 [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 Snow93c92f72017-09-13 23:46:04 -0700165 PyInterpreterState *interp = PyThreadState_GET()->interp;
166 PyObject *modules = interp->modules;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100167 PyObject *builtins;
168 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000169 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000170
Eric Snow93c92f72017-09-13 23:46:04 -0700171 builtins = _PyDict_GetItemId(modules, &PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 if (builtins == NULL) {
173 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
174 return NULL;
175 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 /* Print value except if None */
178 /* After printing, also assign to '_' */
179 /* Before, set '_' to None to avoid recursion */
180 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200181 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200183 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000184 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100185 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 if (outf == NULL || outf == Py_None) {
187 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
188 return NULL;
189 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000190 if (PyFile_WriteObject(o, outf, 0) != 0) {
191 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
192 /* repr(o) is not encodable to sys.stdout.encoding with
193 * sys.stdout.errors error handler (which is probably 'strict') */
194 PyErr_Clear();
195 err = sys_displayhook_unencodable(outf, o);
196 if (err)
197 return NULL;
198 }
199 else {
200 return NULL;
201 }
202 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100203 if (newline == NULL) {
204 newline = PyUnicode_FromString("\n");
205 if (newline == NULL)
206 return NULL;
207 }
208 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200210 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200212 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000213}
214
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000215PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000216"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000217"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000218"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000219);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000220
221static PyObject *
222sys_excepthook(PyObject* self, PyObject* args)
223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000224 PyObject *exc, *value, *tb;
225 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
226 return NULL;
227 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200228 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000229}
230
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000231PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000232"excepthook(exctype, value, traceback) -> None\n"
233"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000234"Handle an exception by displaying it with a traceback on sys.stderr.\n"
235);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000236
237static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000238sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000239{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000240 PyThreadState *tstate;
241 tstate = PyThreadState_GET();
242 return Py_BuildValue(
243 "(OOO)",
244 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
245 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
246 tstate->exc_traceback != NULL ?
247 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000248}
249
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000250PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000251"exc_info() -> (type, value, traceback)\n\
252\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000253Return information about the most recent exception caught by an except\n\
254clause in the current stack frame or in an older stack frame."
255);
256
257static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000258sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 PyObject *exit_code = 0;
261 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
262 return NULL;
263 /* Raise SystemExit so callers may catch it or clean up. */
264 PyErr_SetObject(PyExc_SystemExit, exit_code);
265 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000266}
267
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000268PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000269"exit([status])\n\
270\n\
271Exit the interpreter by raising SystemExit(status).\n\
272If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300273If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000274If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000275exit status will be one (i.e., failure)."
276);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000277
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000278
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000279static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000280sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000283}
284
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000285PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000286"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000287\n\
288Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000289implementation."
290);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000291
292static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000293sys_getfilesystemencoding(PyObject *self)
294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (Py_FileSystemDefaultEncoding)
296 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200297 PyErr_SetString(PyExc_RuntimeError,
298 "filesystem encoding is not initialized");
299 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000300}
301
302PyDoc_STRVAR(getfilesystemencoding_doc,
303"getfilesystemencoding() -> string\n\
304\n\
305Return the encoding used to convert Unicode filenames in\n\
306operating system filenames."
307);
308
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000309static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700310sys_getfilesystemencodeerrors(PyObject *self)
311{
312 if (Py_FileSystemDefaultEncodeErrors)
313 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
314 PyErr_SetString(PyExc_RuntimeError,
315 "filesystem encoding is not initialized");
316 return NULL;
317}
318
319PyDoc_STRVAR(getfilesystemencodeerrors_doc,
320 "getfilesystemencodeerrors() -> string\n\
321\n\
322Return the error mode used to convert Unicode filenames in\n\
323operating system filenames."
324);
325
326static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000327sys_intern(PyObject *self, PyObject *args)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject *s;
330 if (!PyArg_ParseTuple(args, "U:intern", &s))
331 return NULL;
332 if (PyUnicode_CheckExact(s)) {
333 Py_INCREF(s);
334 PyUnicode_InternInPlace(&s);
335 return s;
336 }
337 else {
338 PyErr_Format(PyExc_TypeError,
339 "can't intern %.400s", s->ob_type->tp_name);
340 return NULL;
341 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000342}
343
344PyDoc_STRVAR(intern_doc,
345"intern(string) -> string\n\
346\n\
347``Intern'' the given string. This enters the string in the (global)\n\
348table of interned strings whose purpose is to speed up dictionary lookups.\n\
349Return the string itself or the previously interned string object with the\n\
350same value.");
351
352
Fred Drake5755ce62001-06-27 19:19:46 +0000353/*
354 * Cached interned string objects used for calling the profile and
355 * trace functions. Initialized by trace_init().
356 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000357static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000358
359static int
360trace_init(void)
361{
Nick Coghlan5a851672017-09-08 10:14:16 +1000362 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200363 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000364 "c_call", "c_exception", "c_return",
365 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200366 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyObject *name;
368 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000369 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 if (whatstrings[i] == NULL) {
371 name = PyUnicode_InternFromString(whatnames[i]);
372 if (name == NULL)
373 return -1;
374 whatstrings[i] = name;
375 }
376 }
377 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000378}
379
380
381static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100382call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000384{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000385 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200386 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000387
Victor Stinner78da82b2016-08-20 01:22:57 +0200388 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200390 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100391
Victor Stinner78da82b2016-08-20 01:22:57 +0200392 stack[0] = (PyObject *)frame;
393 stack[1] = whatstrings[what];
394 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200397 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000398
Victor Stinner78da82b2016-08-20 01:22:57 +0200399 PyFrame_LocalsToFast(frame, 1);
400 if (result == NULL) {
401 PyTraceBack_Here(frame);
402 }
403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000405}
406
407static int
408profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000412
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (arg == NULL)
414 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100415 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (result == NULL) {
417 PyEval_SetProfile(NULL, NULL);
418 return -1;
419 }
420 Py_DECREF(result);
421 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000422}
423
424static int
425trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PyObject *callback;
429 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000430
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (what == PyTrace_CALL)
432 callback = self;
433 else
434 callback = frame->f_trace;
435 if (callback == NULL)
436 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100437 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (result == NULL) {
439 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200440 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 return -1;
442 }
443 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300444 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000445 }
446 else {
447 Py_DECREF(result);
448 }
449 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000450}
Fred Draked0838392001-06-16 21:02:31 +0000451
Fred Drake8b4d01d2000-05-09 19:57:01 +0000452static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000453sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000454{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 if (trace_init() == -1)
456 return NULL;
457 if (args == Py_None)
458 PyEval_SetTrace(NULL, NULL);
459 else
460 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200461 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000462}
463
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000464PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000465"settrace(function)\n\
466\n\
467Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000468function call. See the debugger chapter in the library manual."
469);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000470
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000471static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000472sys_gettrace(PyObject *self, PyObject *args)
473{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 PyThreadState *tstate = PyThreadState_GET();
475 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (temp == NULL)
478 temp = Py_None;
479 Py_INCREF(temp);
480 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000481}
482
483PyDoc_STRVAR(gettrace_doc,
484"gettrace()\n\
485\n\
486Return the global debug tracing function set with sys.settrace.\n\
487See the debugger chapter in the library manual."
488);
489
490static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000491sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (trace_init() == -1)
494 return NULL;
495 if (args == Py_None)
496 PyEval_SetProfile(NULL, NULL);
497 else
498 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200499 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000500}
501
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000502PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000503"setprofile(function)\n\
504\n\
505Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000506and return. See the profiler chapter in the library manual."
507);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000509static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000510sys_getprofile(PyObject *self, PyObject *args)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 PyThreadState *tstate = PyThreadState_GET();
513 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (temp == NULL)
516 temp = Py_None;
517 Py_INCREF(temp);
518 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000519}
520
521PyDoc_STRVAR(getprofile_doc,
522"getprofile()\n\
523\n\
524Return the profiling function set with sys.setprofile.\n\
525See the profiler chapter in the library manual."
526);
527
528static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000529sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (PyErr_WarnEx(PyExc_DeprecationWarning,
532 "sys.getcheckinterval() and sys.setcheckinterval() "
533 "are deprecated. Use sys.setswitchinterval() "
534 "instead.", 1) < 0)
535 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600536 PyInterpreterState *interp = PyThreadState_GET()->interp;
537 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200539 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000540}
541
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000542PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000543"setcheckinterval(n)\n\
544\n\
545Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000546n instructions. This also affects how often thread switches occur."
547);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000548
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000549static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000550sys_getcheckinterval(PyObject *self, PyObject *args)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (PyErr_WarnEx(PyExc_DeprecationWarning,
553 "sys.getcheckinterval() and sys.setcheckinterval() "
554 "are deprecated. Use sys.getswitchinterval() "
555 "instead.", 1) < 0)
556 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600557 PyInterpreterState *interp = PyThreadState_GET()->interp;
558 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000559}
560
561PyDoc_STRVAR(getcheckinterval_doc,
562"getcheckinterval() -> current check interval; see setcheckinterval()."
563);
564
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000565static PyObject *
566sys_setswitchinterval(PyObject *self, PyObject *args)
567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 double d;
569 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
570 return NULL;
571 if (d <= 0.0) {
572 PyErr_SetString(PyExc_ValueError,
573 "switch interval must be strictly positive");
574 return NULL;
575 }
576 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200577 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000578}
579
580PyDoc_STRVAR(setswitchinterval_doc,
581"setswitchinterval(n)\n\
582\n\
583Set the ideal thread switching delay inside the Python interpreter\n\
584The actual frequency of switching threads can be lower if the\n\
585interpreter executes long sequences of uninterruptible code\n\
586(this is implementation-specific and workload-dependent).\n\
587\n\
588The parameter must represent the desired switching delay in seconds\n\
589A typical value is 0.005 (5 milliseconds)."
590);
591
592static PyObject *
593sys_getswitchinterval(PyObject *self, PyObject *args)
594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000596}
597
598PyDoc_STRVAR(getswitchinterval_doc,
599"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
600);
601
Tim Peterse5e065b2003-07-06 18:36:54 +0000602static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000603sys_setrecursionlimit(PyObject *self, PyObject *args)
604{
Victor Stinner50856d52015-10-13 00:11:21 +0200605 int new_limit, mark;
606 PyThreadState *tstate;
607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
609 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200610
611 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200613 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 return NULL;
615 }
Victor Stinner50856d52015-10-13 00:11:21 +0200616
617 /* Issue #25274: When the recursion depth hits the recursion limit in
618 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
619 set to 1 and a RecursionError is raised. The overflowed flag is reset
620 to 0 when the recursion depth goes below the low-water mark: see
621 Py_LeaveRecursiveCall().
622
623 Reject too low new limit if the current recursion depth is higher than
624 the new low-water mark. Otherwise it may not be possible anymore to
625 reset the overflowed flag to 0. */
626 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
627 tstate = PyThreadState_GET();
628 if (tstate->recursion_depth >= mark) {
629 PyErr_Format(PyExc_RecursionError,
630 "cannot set the recursion limit to %i at "
631 "the recursion depth %i: the limit is too low",
632 new_limit, tstate->recursion_depth);
633 return NULL;
634 }
635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200637 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000638}
639
Yury Selivanov75445082015-05-11 22:57:16 -0400640static PyObject *
641sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
642{
643 if (wrapper != Py_None) {
644 if (!PyCallable_Check(wrapper)) {
645 PyErr_Format(PyExc_TypeError,
646 "callable expected, got %.50s",
647 Py_TYPE(wrapper)->tp_name);
648 return NULL;
649 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400650 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400651 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400652 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400653 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400654 }
Yury Selivanov75445082015-05-11 22:57:16 -0400655 Py_RETURN_NONE;
656}
657
658PyDoc_STRVAR(set_coroutine_wrapper_doc,
659"set_coroutine_wrapper(wrapper)\n\
660\n\
661Set a wrapper for coroutine objects."
662);
663
664static PyObject *
665sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
666{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400667 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400668 if (wrapper == NULL) {
669 wrapper = Py_None;
670 }
671 Py_INCREF(wrapper);
672 return wrapper;
673}
674
675PyDoc_STRVAR(get_coroutine_wrapper_doc,
676"get_coroutine_wrapper()\n\
677\n\
678Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
679);
680
681
Yury Selivanoveb636452016-09-08 22:01:51 -0700682static PyTypeObject AsyncGenHooksType;
683
684PyDoc_STRVAR(asyncgen_hooks_doc,
685"asyncgen_hooks\n\
686\n\
687A struct sequence providing information about asynhronous\n\
688generators hooks. The attributes are read only.");
689
690static PyStructSequence_Field asyncgen_hooks_fields[] = {
691 {"firstiter", "Hook to intercept first iteration"},
692 {"finalizer", "Hook to intercept finalization"},
693 {0}
694};
695
696static PyStructSequence_Desc asyncgen_hooks_desc = {
697 "asyncgen_hooks", /* name */
698 asyncgen_hooks_doc, /* doc */
699 asyncgen_hooks_fields , /* fields */
700 2
701};
702
703
704static PyObject *
705sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
706{
707 static char *keywords[] = {"firstiter", "finalizer", NULL};
708 PyObject *firstiter = NULL;
709 PyObject *finalizer = NULL;
710
711 if (!PyArg_ParseTupleAndKeywords(
712 args, kw, "|OO", keywords,
713 &firstiter, &finalizer)) {
714 return NULL;
715 }
716
717 if (finalizer && finalizer != Py_None) {
718 if (!PyCallable_Check(finalizer)) {
719 PyErr_Format(PyExc_TypeError,
720 "callable finalizer expected, got %.50s",
721 Py_TYPE(finalizer)->tp_name);
722 return NULL;
723 }
724 _PyEval_SetAsyncGenFinalizer(finalizer);
725 }
726 else if (finalizer == Py_None) {
727 _PyEval_SetAsyncGenFinalizer(NULL);
728 }
729
730 if (firstiter && firstiter != Py_None) {
731 if (!PyCallable_Check(firstiter)) {
732 PyErr_Format(PyExc_TypeError,
733 "callable firstiter expected, got %.50s",
734 Py_TYPE(firstiter)->tp_name);
735 return NULL;
736 }
737 _PyEval_SetAsyncGenFirstiter(firstiter);
738 }
739 else if (firstiter == Py_None) {
740 _PyEval_SetAsyncGenFirstiter(NULL);
741 }
742
743 Py_RETURN_NONE;
744}
745
746PyDoc_STRVAR(set_asyncgen_hooks_doc,
747"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
748\n\
749Set a finalizer for async generators objects."
750);
751
752static PyObject *
753sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
754{
755 PyObject *res;
756 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
757 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
758
759 res = PyStructSequence_New(&AsyncGenHooksType);
760 if (res == NULL) {
761 return NULL;
762 }
763
764 if (firstiter == NULL) {
765 firstiter = Py_None;
766 }
767
768 if (finalizer == NULL) {
769 finalizer = Py_None;
770 }
771
772 Py_INCREF(firstiter);
773 PyStructSequence_SET_ITEM(res, 0, firstiter);
774
775 Py_INCREF(finalizer);
776 PyStructSequence_SET_ITEM(res, 1, finalizer);
777
778 return res;
779}
780
781PyDoc_STRVAR(get_asyncgen_hooks_doc,
782"get_asyncgen_hooks()\n\
783\n\
784Return a namedtuple of installed asynchronous generators hooks \
785(firstiter, finalizer)."
786);
787
788
Mark Dickinsondc787d22010-05-23 13:33:13 +0000789static PyTypeObject Hash_InfoType;
790
791PyDoc_STRVAR(hash_info_doc,
792"hash_info\n\
793\n\
794A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100795hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000796
797static PyStructSequence_Field hash_info_fields[] = {
798 {"width", "width of the type used for hashing, in bits"},
799 {"modulus", "prime number giving the modulus on which the hash "
800 "function is based"},
801 {"inf", "value to be used for hash of a positive infinity"},
802 {"nan", "value to be used for hash of a nan"},
803 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100804 {"algorithm", "name of the algorithm for hashing of str, bytes and "
805 "memoryviews"},
806 {"hash_bits", "internal output size of hash algorithm"},
807 {"seed_bits", "seed size of hash algorithm"},
808 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000809 {NULL, NULL}
810};
811
812static PyStructSequence_Desc hash_info_desc = {
813 "sys.hash_info",
814 hash_info_doc,
815 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100816 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000817};
818
Matthias Klosed885e952010-07-06 10:53:30 +0000819static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000820get_hash_info(void)
821{
822 PyObject *hash_info;
823 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100824 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000825 hash_info = PyStructSequence_New(&Hash_InfoType);
826 if (hash_info == NULL)
827 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100828 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000829 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000830 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000831 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000832 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000833 PyStructSequence_SET_ITEM(hash_info, field++,
834 PyLong_FromLong(_PyHASH_INF));
835 PyStructSequence_SET_ITEM(hash_info, field++,
836 PyLong_FromLong(_PyHASH_NAN));
837 PyStructSequence_SET_ITEM(hash_info, field++,
838 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100839 PyStructSequence_SET_ITEM(hash_info, field++,
840 PyUnicode_FromString(hashfunc->name));
841 PyStructSequence_SET_ITEM(hash_info, field++,
842 PyLong_FromLong(hashfunc->hash_bits));
843 PyStructSequence_SET_ITEM(hash_info, field++,
844 PyLong_FromLong(hashfunc->seed_bits));
845 PyStructSequence_SET_ITEM(hash_info, field++,
846 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000847 if (PyErr_Occurred()) {
848 Py_CLEAR(hash_info);
849 return NULL;
850 }
851 return hash_info;
852}
853
854
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000855PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000856"setrecursionlimit(n)\n\
857\n\
858Set the maximum depth of the Python interpreter stack to n. This\n\
859limit prevents infinite recursion from causing an overflow of the C\n\
860stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000861dependent."
862);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000863
864static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000865sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000868}
869
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000870PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000871"getrecursionlimit()\n\
872\n\
873Return the current value of the recursion limit, the maximum depth\n\
874of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000875recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000876);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000877
Mark Hammond8696ebc2002-10-08 02:44:31 +0000878#ifdef MS_WINDOWS
879PyDoc_STRVAR(getwindowsversion_doc,
880"getwindowsversion()\n\
881\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000882Return information about the running version of Windows as a named tuple.\n\
883The members are named: major, minor, build, platform, service_pack,\n\
884service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200885backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700886All elements are numbers, except service_pack and platform_type which are\n\
887strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
888Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
889server. Platform_version is a 3-tuple containing a version number that is\n\
890intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000891);
892
Eric Smithf7bb5782010-01-27 00:44:57 +0000893static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
894
895static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 {"major", "Major version number"},
897 {"minor", "Minor version number"},
898 {"build", "Build number"},
899 {"platform", "Operating system platform"},
900 {"service_pack", "Latest Service Pack installed on the system"},
901 {"service_pack_major", "Service Pack major version number"},
902 {"service_pack_minor", "Service Pack minor version number"},
903 {"suite_mask", "Bit mask identifying available product suites"},
904 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700905 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000906 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000907};
908
909static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 "sys.getwindowsversion", /* name */
911 getwindowsversion_doc, /* doc */
912 windows_version_fields, /* fields */
913 5 /* For backward compatibility,
914 only the first 5 items are accessible
915 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000916};
917
Steve Dower3e96f322015-03-02 08:01:10 -0800918/* Disable deprecation warnings about GetVersionEx as the result is
919 being passed straight through to the caller, who is responsible for
920 using it correctly. */
921#pragma warning(push)
922#pragma warning(disable:4996)
923
Mark Hammond8696ebc2002-10-08 02:44:31 +0000924static PyObject *
925sys_getwindowsversion(PyObject *self)
926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000927 PyObject *version;
928 int pos = 0;
929 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700930 DWORD realMajor, realMinor, realBuild;
931 HANDLE hKernel32;
932 wchar_t kernel32_path[MAX_PATH];
933 LPVOID verblock;
934 DWORD verblock_size;
935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 ver.dwOSVersionInfoSize = sizeof(ver);
937 if (!GetVersionEx((OSVERSIONINFO*) &ver))
938 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 version = PyStructSequence_New(&WindowsVersionType);
941 if (version == NULL)
942 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
945 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
946 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
948 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
949 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
950 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
951 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
952 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000953
Steve Dower74f4af72016-09-17 17:27:48 -0700954 realMajor = ver.dwMajorVersion;
955 realMinor = ver.dwMinorVersion;
956 realBuild = ver.dwBuildNumber;
957
958 // GetVersion will lie if we are running in a compatibility mode.
959 // We need to read the version info from a system file resource
960 // to accurately identify the OS version. If we fail for any reason,
961 // just return whatever GetVersion said.
962 hKernel32 = GetModuleHandleW(L"kernel32.dll");
963 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
964 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
965 (verblock = PyMem_RawMalloc(verblock_size))) {
966 VS_FIXEDFILEINFO *ffi;
967 UINT ffi_len;
968
969 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
970 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
971 realMajor = HIWORD(ffi->dwProductVersionMS);
972 realMinor = LOWORD(ffi->dwProductVersionMS);
973 realBuild = HIWORD(ffi->dwProductVersionLS);
974 }
975 PyMem_RawFree(verblock);
976 }
Segev Finer48fb7662017-06-04 20:52:27 +0300977 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
978 realMajor,
979 realMinor,
980 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700981 ));
982
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200983 if (PyErr_Occurred()) {
984 Py_DECREF(version);
985 return NULL;
986 }
Steve Dower74f4af72016-09-17 17:27:48 -0700987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000989}
990
Steve Dower3e96f322015-03-02 08:01:10 -0800991#pragma warning(pop)
992
Steve Dowercc16be82016-09-08 10:35:16 -0700993PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
994"_enablelegacywindowsfsencoding()\n\
995\n\
996Changes the default filesystem encoding to mbcs:replace for consistency\n\
997with earlier versions of Python. See PEP 529 for more information.\n\
998\n\
999This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1000environment variable before launching Python."
1001);
1002
1003static PyObject *
1004sys_enablelegacywindowsfsencoding(PyObject *self)
1005{
1006 Py_FileSystemDefaultEncoding = "mbcs";
1007 Py_FileSystemDefaultEncodeErrors = "replace";
1008 Py_RETURN_NONE;
1009}
1010
Mark Hammond8696ebc2002-10-08 02:44:31 +00001011#endif /* MS_WINDOWS */
1012
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001013#ifdef HAVE_DLOPEN
1014static PyObject *
1015sys_setdlopenflags(PyObject *self, PyObject *args)
1016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 int new_val;
1018 PyThreadState *tstate = PyThreadState_GET();
1019 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1020 return NULL;
1021 if (!tstate)
1022 return NULL;
1023 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001024 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001025}
1026
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001027PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001028"setdlopenflags(n) -> None\n\
1029\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001030Set the flags used by the interpreter for dlopen calls, such as when the\n\
1031interpreter loads extension modules. Among other things, this will enable\n\
1032a lazy resolving of symbols when importing a module, if called as\n\
1033sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001034sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001035can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001036
1037static PyObject *
1038sys_getdlopenflags(PyObject *self, PyObject *args)
1039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyThreadState *tstate = PyThreadState_GET();
1041 if (!tstate)
1042 return NULL;
1043 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001044}
1045
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001046PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001047"getdlopenflags() -> int\n\
1048\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001049Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001050The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001053
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001054#ifdef USE_MALLOPT
1055/* Link with -lmalloc (or -lmpc) on an SGI */
1056#include <malloc.h>
1057
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001058static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001059sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001060{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 int flag;
1062 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1063 return NULL;
1064 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001065 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001066}
1067#endif /* USE_MALLOPT */
1068
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001069size_t
1070_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001074 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 /* Make sure the type is initialized. float gets initialized late */
1077 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001078 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001079
Benjamin Petersonce798522012-01-22 11:24:29 -05001080 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 if (method == NULL) {
1082 if (!PyErr_Occurred())
1083 PyErr_Format(PyExc_TypeError,
1084 "Type %.100s doesn't define __sizeof__",
1085 Py_TYPE(o)->tp_name);
1086 }
1087 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001088 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 Py_DECREF(method);
1090 }
1091
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001092 if (res == NULL)
1093 return (size_t)-1;
1094
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001095 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001096 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001097 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001098 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001100 if (size < 0) {
1101 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1102 return (size_t)-1;
1103 }
1104
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001105 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001106 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001107 return ((size_t)size) + sizeof(PyGC_Head);
1108 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001109}
1110
1111static PyObject *
1112sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1113{
1114 static char *kwlist[] = {"object", "default", 0};
1115 size_t size;
1116 PyObject *o, *dflt = NULL;
1117
1118 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1119 kwlist, &o, &dflt))
1120 return NULL;
1121
1122 size = _PySys_GetSizeOf(o);
1123
1124 if (size == (size_t)-1 && PyErr_Occurred()) {
1125 /* Has a default value been given */
1126 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1127 PyErr_Clear();
1128 Py_INCREF(dflt);
1129 return dflt;
1130 }
1131 else
1132 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001134
1135 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001136}
1137
1138PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001139"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001140\n\
1141Return the size of object in bytes.");
1142
1143static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001144sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001147}
1148
Tim Peters4be93d02002-07-07 19:59:50 +00001149#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001150static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001151sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001153 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001154}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001155#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001156
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001157PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001158"getrefcount(object) -> integer\n\
1159\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001160Return the reference count of object. The count returned is generally\n\
1161one higher than you might expect, because it includes the (temporary)\n\
1162reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001163);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001164
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001165static PyObject *
1166sys_getallocatedblocks(PyObject *self)
1167{
1168 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1169}
1170
1171PyDoc_STRVAR(getallocatedblocks_doc,
1172"getallocatedblocks() -> integer\n\
1173\n\
1174Return the number of memory blocks currently allocated, regardless of their\n\
1175size."
1176);
1177
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001178#ifdef COUNT_ALLOCS
1179static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001180sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001185}
1186#endif
1187
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001188PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001189"_getframe([depth]) -> frameobject\n\
1190\n\
1191Return a frame object from the call stack. If optional integer depth is\n\
1192given, return the frame object that many calls below the top of the stack.\n\
1193If that is deeper than the call stack, ValueError is raised. The default\n\
1194for depth is zero, returning the frame at the top of the call stack.\n\
1195\n\
1196This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001197purposes only."
1198);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001199
1200static PyObject *
1201sys_getframe(PyObject *self, PyObject *args)
1202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 PyFrameObject *f = PyThreadState_GET()->frame;
1204 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1207 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001208
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001209 while (depth > 0 && f != NULL) {
1210 f = f->f_back;
1211 --depth;
1212 }
1213 if (f == NULL) {
1214 PyErr_SetString(PyExc_ValueError,
1215 "call stack is not deep enough");
1216 return NULL;
1217 }
1218 Py_INCREF(f);
1219 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001220}
1221
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001222PyDoc_STRVAR(current_frames_doc,
1223"_current_frames() -> dictionary\n\
1224\n\
1225Return a dictionary mapping each current thread T's thread id to T's\n\
1226current stack frame.\n\
1227\n\
1228This function should be used for specialized purposes only."
1229);
1230
1231static PyObject *
1232sys_current_frames(PyObject *self, PyObject *noargs)
1233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001235}
1236
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001237PyDoc_STRVAR(call_tracing_doc,
1238"call_tracing(func, args) -> object\n\
1239\n\
1240Call func(*args), while tracing is enabled. The tracing state is\n\
1241saved, and restored afterwards. This is intended to be called from\n\
1242a debugger from a checkpoint, to recursively debug some other code."
1243);
1244
1245static PyObject *
1246sys_call_tracing(PyObject *self, PyObject *args)
1247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 PyObject *func, *funcargs;
1249 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1250 return NULL;
1251 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001252}
1253
Jeremy Hylton985eba52003-02-05 23:13:00 +00001254PyDoc_STRVAR(callstats_doc,
1255"callstats() -> tuple of integers\n\
1256\n\
1257Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1258when Python was built. Otherwise, return None.\n\
1259\n\
1260When enabled, this function returns detailed, implementation-specific\n\
1261details about the number of function calls executed. The return value is\n\
1262a 11-tuple where the entries in the tuple are counts of:\n\
12630. all function calls\n\
12641. calls to PyFunction_Type objects\n\
12652. PyFunction calls that do not create an argument tuple\n\
12663. PyFunction calls that do not create an argument tuple\n\
1267 and bypass PyEval_EvalCodeEx()\n\
12684. PyMethod calls\n\
12695. PyMethod calls on bound methods\n\
12706. PyType calls\n\
12717. PyCFunction calls\n\
12728. generator calls\n\
12739. All other calls\n\
127410. Number of stack pops performed by call_function()"
1275);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001276
Victor Stinner048afd92016-11-28 11:59:04 +01001277static PyObject *
1278sys_callstats(PyObject *self)
1279{
1280 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1281 "sys.callstats() has been deprecated in Python 3.7 "
1282 "and will be removed in the future", 1) < 0) {
1283 return NULL;
1284 }
1285
1286 Py_RETURN_NONE;
1287}
1288
1289
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001290#ifdef __cplusplus
1291extern "C" {
1292#endif
1293
David Malcolm49526f42012-06-22 14:55:41 -04001294static PyObject *
1295sys_debugmallocstats(PyObject *self, PyObject *args)
1296{
1297#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001298 if (_PyMem_PymallocEnabled()) {
1299 _PyObject_DebugMallocStats(stderr);
1300 fputc('\n', stderr);
1301 }
David Malcolm49526f42012-06-22 14:55:41 -04001302#endif
1303 _PyObject_DebugTypeStats(stderr);
1304
1305 Py_RETURN_NONE;
1306}
1307PyDoc_STRVAR(debugmallocstats_doc,
1308"_debugmallocstats()\n\
1309\n\
1310Print summary info to stderr about the state of\n\
1311pymalloc's structures.\n\
1312\n\
1313In Py_DEBUG mode, also perform some expensive internal consistency\n\
1314checks.\n\
1315");
1316
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001317#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001318/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001319extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001320#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001321
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001322#ifdef DYNAMIC_EXECUTION_PROFILE
1323/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001324extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001325#endif
1326
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001327#ifdef __cplusplus
1328}
1329#endif
1330
Christian Heimes15ebc882008-02-04 18:48:49 +00001331static PyObject *
1332sys_clear_type_cache(PyObject* self, PyObject* args)
1333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 PyType_ClearCache();
1335 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001336}
1337
1338PyDoc_STRVAR(sys_clear_type_cache__doc__,
1339"_clear_type_cache() -> None\n\
1340Clear the internal type lookup cache.");
1341
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001342static PyObject *
1343sys_is_finalizing(PyObject* self, PyObject* args)
1344{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001345 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001346}
1347
1348PyDoc_STRVAR(is_finalizing_doc,
1349"is_finalizing()\n\
1350Return True if Python is exiting.");
1351
Christian Heimes15ebc882008-02-04 18:48:49 +00001352
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001353#ifdef ANDROID_API_LEVEL
1354PyDoc_STRVAR(getandroidapilevel_doc,
1355"getandroidapilevel()\n\
1356\n\
1357Return the build time API version of Android as an integer.");
1358
1359static PyObject *
1360sys_getandroidapilevel(PyObject *self)
1361{
1362 return PyLong_FromLong(ANDROID_API_LEVEL);
1363}
1364#endif /* ANDROID_API_LEVEL */
1365
1366
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001367static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001369 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 callstats_doc},
1371 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1372 sys_clear_type_cache__doc__},
1373 {"_current_frames", sys_current_frames, METH_NOARGS,
1374 current_frames_doc},
1375 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1376 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1377 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1378 {"exit", sys_exit, METH_VARARGS, exit_doc},
1379 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1380 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001381#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1383 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001384#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001385 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1386 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001387#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001389#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001390#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001392#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1394 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001395 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1396 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001397#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001399#endif
1400#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001402#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1404 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1405 getrecursionlimit_doc},
1406 {"getsizeof", (PyCFunction)sys_getsizeof,
1407 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1408 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001409#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1411 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001412 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1413 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001414#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001416 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001417#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001419#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1421 setcheckinterval_doc},
1422 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1423 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1425 setswitchinterval_doc},
1426 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1427 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001428#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1430 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001431#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1433 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1434 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1435 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 {"settrace", sys_settrace, METH_O, settrace_doc},
1437 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1438 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001439 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001440 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001441 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1442 set_coroutine_wrapper_doc},
1443 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1444 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001445 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001446 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1447 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1448 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001449#ifdef ANDROID_API_LEVEL
1450 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1451 getandroidapilevel_doc},
1452#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001454};
1455
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001456static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001457list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyObject *list = PyList_New(0);
1460 int i;
1461 if (list == NULL)
1462 return NULL;
1463 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1464 PyObject *name = PyUnicode_FromString(
1465 PyImport_Inittab[i].name);
1466 if (name == NULL)
1467 break;
1468 PyList_Append(list, name);
1469 Py_DECREF(name);
1470 }
1471 if (PyList_Sort(list) != 0) {
1472 Py_DECREF(list);
1473 list = NULL;
1474 }
1475 if (list) {
1476 PyObject *v = PyList_AsTuple(list);
1477 Py_DECREF(list);
1478 list = v;
1479 }
1480 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001481}
1482
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001483static PyObject *
1484get_warnoptions(void)
1485{
Eric Snowdae02762017-09-14 00:35:58 -07001486 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001487 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1488 Py_XDECREF(warnoptions);
1489 warnoptions = PyList_New(0);
1490 if (warnoptions == NULL)
1491 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001492 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1493 Py_DECREF(warnoptions);
1494 return NULL;
1495 }
1496 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001497 }
1498 return warnoptions;
1499}
Guido van Rossum23fff912000-12-15 22:02:05 +00001500
1501void
1502PySys_ResetWarnOptions(void)
1503{
Eric Snowdae02762017-09-14 00:35:58 -07001504 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 if (warnoptions == NULL || !PyList_Check(warnoptions))
1506 return;
1507 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001508}
1509
1510void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001511PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001512{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001513 PyObject *warnoptions = get_warnoptions();
1514 if (warnoptions == NULL)
1515 return;
Victor Stinner9ca9c252010-05-19 16:53:30 +00001516 PyList_Append(warnoptions, unicode);
1517}
1518
1519void
1520PySys_AddWarnOption(const wchar_t *s)
1521{
1522 PyObject *unicode;
1523 unicode = PyUnicode_FromWideChar(s, -1);
1524 if (unicode == NULL)
1525 return;
1526 PySys_AddWarnOptionUnicode(unicode);
1527 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001528}
1529
Christian Heimes33fe8092008-04-13 13:53:33 +00001530int
1531PySys_HasWarnOptions(void)
1532{
Eric Snowdae02762017-09-14 00:35:58 -07001533 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001534 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1535}
1536
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001537static PyObject *
1538get_xoptions(void)
1539{
Eric Snowdae02762017-09-14 00:35:58 -07001540 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001541 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1542 Py_XDECREF(xoptions);
1543 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001544 if (xoptions == NULL)
1545 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001546 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1547 Py_DECREF(xoptions);
1548 return NULL;
1549 }
1550 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001551 }
1552 return xoptions;
1553}
1554
1555void
1556PySys_AddXOption(const wchar_t *s)
1557{
1558 PyObject *opts;
1559 PyObject *name = NULL, *value = NULL;
1560 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001561
1562 opts = get_xoptions();
1563 if (opts == NULL)
1564 goto error;
1565
1566 name_end = wcschr(s, L'=');
1567 if (!name_end) {
1568 name = PyUnicode_FromWideChar(s, -1);
1569 value = Py_True;
1570 Py_INCREF(value);
1571 }
1572 else {
1573 name = PyUnicode_FromWideChar(s, name_end - s);
1574 value = PyUnicode_FromWideChar(name_end + 1, -1);
1575 }
1576 if (name == NULL || value == NULL)
1577 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001578 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001579 Py_DECREF(name);
1580 Py_DECREF(value);
1581 return;
1582
1583error:
1584 Py_XDECREF(name);
1585 Py_XDECREF(value);
1586 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001587 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001588 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001589 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001590}
1591
1592PyObject *
1593PySys_GetXOptions(void)
1594{
1595 return get_xoptions();
1596}
1597
Guido van Rossum40552d01998-08-06 03:34:39 +00001598/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1599 Two literals concatenated works just fine. If you have a K&R compiler
1600 or other abomination that however *does* understand longer strings,
1601 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001602PyDoc_VAR(sys_doc) =
1603PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001604"This module provides access to some objects used or maintained by the\n\
1605interpreter and to functions that interact strongly with the interpreter.\n\
1606\n\
1607Dynamic objects:\n\
1608\n\
1609argv -- command line arguments; argv[0] is the script pathname if known\n\
1610path -- module search path; path[0] is the script directory, else ''\n\
1611modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001612\n\
1613displayhook -- called to show results in an interactive session\n\
1614excepthook -- called to handle any uncaught exception other than SystemExit\n\
1615 To customize printing in an interactive session or to install a custom\n\
1616 top-level exception handler, assign other functions to replace these.\n\
1617\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001618stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001619stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001620stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001621 By assigning other file objects (or objects that behave like files)\n\
1622 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001623\n\
1624last_type -- type of last uncaught exception\n\
1625last_value -- value of last uncaught exception\n\
1626last_traceback -- traceback of last uncaught exception\n\
1627 These three are only available in an interactive session after a\n\
1628 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001629"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001630)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001631/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001632PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001633"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001634Static objects:\n\
1635\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001636builtin_module_names -- tuple of module names built into this interpreter\n\
1637copyright -- copyright notice pertaining to this interpreter\n\
1638exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001639executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001640float_info -- a struct sequence with information about the float implementation.\n\
1641float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001642hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001643hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001644implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001645int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001646maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001647maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001648platform -- platform identifier\n\
1649prefix -- prefix used to find the Python library\n\
1650thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001651version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001652version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001653"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001654)
Steve Dowercc16be82016-09-08 10:35:16 -07001655#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001656/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001657PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001658"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001659winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001660"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001661)
Steve Dowercc16be82016-09-08 10:35:16 -07001662#endif /* MS_COREDLL */
1663#ifdef MS_WINDOWS
1664/* concatenating string here */
1665PyDoc_STR(
1666"_enablelegacywindowsfsencoding -- [Windows only] \n\
1667"
1668)
1669#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001670PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001671"__stdin__ -- the original stdin; don't touch!\n\
1672__stdout__ -- the original stdout; don't touch!\n\
1673__stderr__ -- the original stderr; don't touch!\n\
1674__displayhook__ -- the original displayhook; don't touch!\n\
1675__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001676\n\
1677Functions:\n\
1678\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001679displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001680excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001681exc_info() -- return thread-safe information about the current exception\n\
1682exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001683getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001684getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001685getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001686getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001687getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001688gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001689setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001690setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001691setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001692setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001693settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001694"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001695)
Fred Drakeccede592000-08-14 20:59:57 +00001696/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001697
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001698
1699PyDoc_STRVAR(flags__doc__,
1700"sys.flags\n\
1701\n\
1702Flags provided through command line arguments or environment vars.");
1703
1704static PyTypeObject FlagsType;
1705
1706static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 {"inspect", "-i"},
1709 {"interactive", "-i"},
1710 {"optimize", "-O or -OO"},
1711 {"dont_write_bytecode", "-B"},
1712 {"no_user_site", "-s"},
1713 {"no_site", "-S"},
1714 {"ignore_environment", "-E"},
1715 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 /* {"unbuffered", "-u"}, */
1717 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001718 {"bytes_warning", "-b"},
1719 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001720 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001721 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001723};
1724
1725static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 "sys.flags", /* name */
1727 flags__doc__, /* doc */
1728 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001729 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001730};
1731
1732static PyObject*
1733make_flags(void)
1734{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 int pos = 0;
1736 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 seq = PyStructSequence_New(&FlagsType);
1739 if (seq == NULL)
1740 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001741
1742#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 SetFlag(Py_InspectFlag);
1747 SetFlag(Py_InteractiveFlag);
1748 SetFlag(Py_OptimizeFlag);
1749 SetFlag(Py_DontWriteBytecodeFlag);
1750 SetFlag(Py_NoUserSiteDirectory);
1751 SetFlag(Py_NoSiteFlag);
1752 SetFlag(Py_IgnoreEnvironmentFlag);
1753 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 /* SetFlag(saw_unbuffered_flag); */
1755 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001756 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001757 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001758 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001759 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001760#undef SetFlag
1761
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001763 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 return NULL;
1765 }
1766 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001767}
1768
Eric Smith0e5b5622009-02-06 01:32:42 +00001769PyDoc_STRVAR(version_info__doc__,
1770"sys.version_info\n\
1771\n\
1772Version information as a named tuple.");
1773
1774static PyTypeObject VersionInfoType;
1775
1776static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 {"major", "Major release number"},
1778 {"minor", "Minor release number"},
1779 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001780 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 {"serial", "Serial release number"},
1782 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001783};
1784
1785static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 "sys.version_info", /* name */
1787 version_info__doc__, /* doc */
1788 version_info_fields, /* fields */
1789 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001790};
1791
1792static PyObject *
1793make_version_info(void)
1794{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyObject *version_info;
1796 char *s;
1797 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001798
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 version_info = PyStructSequence_New(&VersionInfoType);
1800 if (version_info == NULL) {
1801 return NULL;
1802 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 /*
1805 * These release level checks are mutually exclusive and cover
1806 * the field, so don't get too fancy with the pre-processor!
1807 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001808#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001810#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001812#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001813 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001814#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001816#endif
1817
1818#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001820#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001823 SetIntItem(PY_MAJOR_VERSION);
1824 SetIntItem(PY_MINOR_VERSION);
1825 SetIntItem(PY_MICRO_VERSION);
1826 SetStrItem(s);
1827 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001828#undef SetIntItem
1829#undef SetStrItem
1830
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 if (PyErr_Occurred()) {
1832 Py_CLEAR(version_info);
1833 return NULL;
1834 }
1835 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001836}
1837
Brett Cannon3adc7b72012-07-09 14:22:12 -04001838/* sys.implementation values */
1839#define NAME "cpython"
1840const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001841#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1842#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001843#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001844const char *_PySys_ImplCacheTag = TAG;
1845#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001846#undef MAJOR
1847#undef MINOR
1848#undef TAG
1849
Barry Warsaw409da152012-06-03 16:18:47 -04001850static PyObject *
1851make_impl_info(PyObject *version_info)
1852{
1853 int res;
1854 PyObject *impl_info, *value, *ns;
1855
1856 impl_info = PyDict_New();
1857 if (impl_info == NULL)
1858 return NULL;
1859
1860 /* populate the dict */
1861
Brett Cannon3adc7b72012-07-09 14:22:12 -04001862 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001863 if (value == NULL)
1864 goto error;
1865 res = PyDict_SetItemString(impl_info, "name", value);
1866 Py_DECREF(value);
1867 if (res < 0)
1868 goto error;
1869
Brett Cannon3adc7b72012-07-09 14:22:12 -04001870 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001871 if (value == NULL)
1872 goto error;
1873 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1874 Py_DECREF(value);
1875 if (res < 0)
1876 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001877
1878 res = PyDict_SetItemString(impl_info, "version", version_info);
1879 if (res < 0)
1880 goto error;
1881
1882 value = PyLong_FromLong(PY_VERSION_HEX);
1883 if (value == NULL)
1884 goto error;
1885 res = PyDict_SetItemString(impl_info, "hexversion", value);
1886 Py_DECREF(value);
1887 if (res < 0)
1888 goto error;
1889
doko@ubuntu.com55532312016-06-14 08:55:19 +02001890#ifdef MULTIARCH
1891 value = PyUnicode_FromString(MULTIARCH);
1892 if (value == NULL)
1893 goto error;
1894 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1895 Py_DECREF(value);
1896 if (res < 0)
1897 goto error;
1898#endif
1899
Barry Warsaw409da152012-06-03 16:18:47 -04001900 /* dict ready */
1901
1902 ns = _PyNamespace_New(impl_info);
1903 Py_DECREF(impl_info);
1904 return ns;
1905
1906error:
1907 Py_CLEAR(impl_info);
1908 return NULL;
1909}
1910
Martin v. Löwis1a214512008-06-11 05:26:20 +00001911static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 PyModuleDef_HEAD_INIT,
1913 "sys",
1914 sys_doc,
1915 -1, /* multiple "initialization" just copies the module dict. */
1916 sys_methods,
1917 NULL,
1918 NULL,
1919 NULL,
1920 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001921};
1922
Eric Snow6b4be192017-05-22 21:36:03 -07001923/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001924#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001925 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001926 PyObject *v = (value); \
1927 if (v == NULL) \
1928 return NULL; \
1929 res = PyDict_SetItemString(sysdict, key, v); \
1930 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001931 return NULL; \
1932 } \
1933 } while (0)
1934#define SET_SYS_FROM_STRING(key, value) \
1935 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001936 PyObject *v = (value); \
1937 if (v == NULL) \
1938 return NULL; \
1939 res = PyDict_SetItemString(sysdict, key, v); \
1940 Py_DECREF(v); \
1941 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001942 return NULL; \
1943 } \
1944 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001945
Eric Snow6b4be192017-05-22 21:36:03 -07001946PyObject *
1947_PySys_BeginInit(void)
1948{
1949 PyObject *m, *sysdict, *version_info;
1950 int res;
1951
Eric Snow93c92f72017-09-13 23:46:04 -07001952 m = PyModule_Create(&sysmodule);
Eric Snow6b4be192017-05-22 21:36:03 -07001953 if (m == NULL)
1954 return NULL;
1955 sysdict = PyModule_GetDict(m);
1956
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 /* Check that stdin is not a directory
1958 Using shell redirection, you can redirect stdin to a directory,
1959 crashing the Python interpreter. Catch this common mistake here
1960 and output a useful error message. Note that under MS Windows,
1961 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001962#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001964 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001965 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001966 S_ISDIR(sb.st_mode)) {
1967 /* There's nothing more we can do. */
1968 /* Py_FatalError() will core dump, so just exit. */
1969 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1970 exit(EXIT_FAILURE);
1971 }
1972 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001973#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001974
Nick Coghland6009512014-11-20 21:39:37 +10001975 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001976
Victor Stinner8fea2522013-10-27 17:15:42 +01001977 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1978 PyDict_GetItemString(sysdict, "displayhook"));
1979 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1980 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 SET_SYS_FROM_STRING("version",
1982 PyUnicode_FromString(Py_GetVersion()));
1983 SET_SYS_FROM_STRING("hexversion",
1984 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001985 SET_SYS_FROM_STRING("_git",
1986 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1987 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001988 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001989 SET_SYS_FROM_STRING("api_version",
1990 PyLong_FromLong(PYTHON_API_VERSION));
1991 SET_SYS_FROM_STRING("copyright",
1992 PyUnicode_FromString(Py_GetCopyright()));
1993 SET_SYS_FROM_STRING("platform",
1994 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 SET_SYS_FROM_STRING("maxsize",
1996 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1997 SET_SYS_FROM_STRING("float_info",
1998 PyFloat_GetInfo());
1999 SET_SYS_FROM_STRING("int_info",
2000 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002001 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002002 if (Hash_InfoType.tp_name == NULL) {
2003 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
2004 return NULL;
2005 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002006 SET_SYS_FROM_STRING("hash_info",
2007 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002009 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 SET_SYS_FROM_STRING("builtin_module_names",
2011 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002012#if PY_BIG_ENDIAN
2013 SET_SYS_FROM_STRING("byteorder",
2014 PyUnicode_FromString("big"));
2015#else
2016 SET_SYS_FROM_STRING("byteorder",
2017 PyUnicode_FromString("little"));
2018#endif
Fred Drake099325e2000-08-14 15:47:03 +00002019
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002020#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002021 SET_SYS_FROM_STRING("dllhandle",
2022 PyLong_FromVoidPtr(PyWin_DLLhModule));
2023 SET_SYS_FROM_STRING("winver",
2024 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002025#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002026#ifdef ABIFLAGS
2027 SET_SYS_FROM_STRING("abiflags",
2028 PyUnicode_FromString(ABIFLAGS));
2029#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002032 if (VersionInfoType.tp_name == NULL) {
2033 if (PyStructSequence_InitType2(&VersionInfoType,
2034 &version_info_desc) < 0)
2035 return NULL;
2036 }
Barry Warsaw409da152012-06-03 16:18:47 -04002037 version_info = make_version_info();
2038 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* prevent user from creating new instances */
2040 VersionInfoType.tp_init = NULL;
2041 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002042 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2043 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2044 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002045
Barry Warsaw409da152012-06-03 16:18:47 -04002046 /* implementation */
2047 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002050 if (FlagsType.tp_name == 0) {
2051 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2052 return NULL;
2053 }
Eric Snow6b4be192017-05-22 21:36:03 -07002054 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002056
2057#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 /* getwindowsversion */
2059 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002060 if (PyStructSequence_InitType2(&WindowsVersionType,
2061 &windows_version_desc) < 0)
2062 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 /* prevent user from creating new instances */
2064 WindowsVersionType.tp_init = NULL;
2065 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002066 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2067 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2068 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002069#endif
2070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002072#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 SET_SYS_FROM_STRING("float_repr_style",
2074 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002075#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 SET_SYS_FROM_STRING("float_repr_style",
2077 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002078#endif
2079
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002080 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002081
Yury Selivanoveb636452016-09-08 22:01:51 -07002082 /* initialize asyncgen_hooks */
2083 if (AsyncGenHooksType.tp_name == NULL) {
2084 if (PyStructSequence_InitType2(
2085 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2086 return NULL;
2087 }
2088 }
2089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (PyErr_Occurred())
2091 return NULL;
2092 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002093}
2094
Eric Snow6b4be192017-05-22 21:36:03 -07002095#undef SET_SYS_FROM_STRING
2096#undef SET_SYS_FROM_STRING_BORROW
2097
2098/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002099#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2100 do { \
2101 PyObject *v = (value); \
2102 if (v == NULL) \
2103 return -1; \
2104 res = PyDict_SetItemString(sysdict, key, v); \
2105 Py_DECREF(v); \
2106 if (res < 0) { \
2107 return res; \
2108 } \
2109 } while (0)
2110
2111int
2112_PySys_EndInit(PyObject *sysdict)
2113{
2114 int res;
2115
2116 /* Set flags to their final values */
2117 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2118 /* prevent user from creating new instances */
2119 FlagsType.tp_init = NULL;
2120 FlagsType.tp_new = NULL;
2121 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2122 if (res < 0) {
2123 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2124 return res;
2125 }
2126 PyErr_Clear();
2127 }
2128
2129 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2130 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2131 SET_SYS_FROM_STRING_INT_RESULT("executable",
2132 PyUnicode_FromWideChar(
2133 Py_GetProgramFullPath(), -1));
2134 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2135 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2136 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2137 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2138 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2139 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2140 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2141 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2142
Eric Snowdae02762017-09-14 00:35:58 -07002143 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002144 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002145
Eric Snowdae02762017-09-14 00:35:58 -07002146 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002147 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002148
2149 if (PyErr_Occurred())
2150 return -1;
2151 return 0;
2152}
2153
2154#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002155
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002156static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002157makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 int i, n;
2160 const wchar_t *p;
2161 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 n = 1;
2164 p = path;
2165 while ((p = wcschr(p, delim)) != NULL) {
2166 n++;
2167 p++;
2168 }
2169 v = PyList_New(n);
2170 if (v == NULL)
2171 return NULL;
2172 for (i = 0; ; i++) {
2173 p = wcschr(path, delim);
2174 if (p == NULL)
2175 p = path + wcslen(path); /* End of string */
2176 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2177 if (w == NULL) {
2178 Py_DECREF(v);
2179 return NULL;
2180 }
2181 PyList_SetItem(v, i, w);
2182 if (*p == '\0')
2183 break;
2184 path = p+1;
2185 }
2186 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002187}
2188
2189void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002190PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 PyObject *v;
2193 if ((v = makepathobject(path, DELIM)) == NULL)
2194 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002195 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002196 Py_FatalError("can't assign sys.path");
2197 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002198}
2199
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002200static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002201makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 PyObject *av;
2204 if (argc <= 0 || argv == NULL) {
2205 /* Ensure at least one (empty) argument is seen */
2206 static wchar_t *empty_argv[1] = {L""};
2207 argv = empty_argv;
2208 argc = 1;
2209 }
2210 av = PyList_New(argc);
2211 if (av != NULL) {
2212 int i;
2213 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 if (v == NULL) {
2216 Py_DECREF(av);
2217 av = NULL;
2218 break;
2219 }
2220 PyList_SetItem(av, i, v);
2221 }
2222 }
2223 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002224}
2225
Nick Coghland26c18a2010-08-17 13:06:11 +00002226#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2227 (argc > 0 && argv0 != NULL && \
2228 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002229
2230static void
2231sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002232{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002233 wchar_t *argv0;
2234 wchar_t *p = NULL;
2235 Py_ssize_t n = 0;
2236 PyObject *a;
2237 PyObject *path;
2238#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002239 wchar_t link[MAXPATHLEN+1];
2240 wchar_t argv0copy[2*MAXPATHLEN+1];
2241 int nr = 0;
2242#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002243#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002245#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002247#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002248
Victor Stinnerbd303c12013-11-07 23:07:29 +01002249 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002250 if (path == NULL)
2251 return;
2252
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002253 argv0 = argv[0];
2254
2255#ifdef HAVE_READLINK
2256 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2257 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2258 if (nr > 0) {
2259 /* It's a symlink */
2260 link[nr] = '\0';
2261 if (link[0] == SEP)
2262 argv0 = link; /* Link to absolute path */
2263 else if (wcschr(link, SEP) == NULL)
2264 ; /* Link without path */
2265 else {
2266 /* Must join(dirname(argv0), link) */
2267 wchar_t *q = wcsrchr(argv0, SEP);
2268 if (q == NULL)
2269 argv0 = link; /* argv0 without path */
2270 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002271 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2272 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002273 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002274 wcsncpy(q+1, link, MAXPATHLEN);
2275 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002276 argv0 = argv0copy;
2277 }
2278 }
2279 }
2280#endif /* HAVE_READLINK */
2281#if SEP == '\\' /* Special case for MS filename syntax */
2282 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2283 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002284#if defined(MS_WINDOWS)
2285 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002286 wchar_t *ptemp;
2287 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002288 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002289 fullpath,
2290 &ptemp)) {
2291 argv0 = fullpath;
2292 }
2293#endif
2294 p = wcsrchr(argv0, SEP);
2295 /* Test for alternate separator */
2296 q = wcsrchr(p ? p : argv0, '/');
2297 if (q != NULL)
2298 p = q;
2299 if (p != NULL) {
2300 n = p + 1 - argv0;
2301 if (n > 1 && p[-1] != ':')
2302 n--; /* Drop trailing separator */
2303 }
2304 }
2305#else /* All other filename syntaxes */
2306 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2307#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002308 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002309 argv0 = fullpath;
2310 }
2311#endif
2312 p = wcsrchr(argv0, SEP);
2313 }
2314 if (p != NULL) {
2315 n = p + 1 - argv0;
2316#if SEP == '/' /* Special case for Unix filename syntax */
2317 if (n > 1)
2318 n--; /* Drop trailing separator */
2319#endif /* Unix */
2320 }
2321#endif /* All others */
2322 a = PyUnicode_FromWideChar(argv0, n);
2323 if (a == NULL)
2324 Py_FatalError("no mem for sys.path insertion");
2325 if (PyList_Insert(path, 0, a) < 0)
2326 Py_FatalError("sys.path.insert(0) failed");
2327 Py_DECREF(a);
2328}
2329
2330void
2331PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (av == NULL)
2335 Py_FatalError("no mem for sys.argv");
2336 if (PySys_SetObject("argv", av) != 0)
2337 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002339 if (updatepath)
2340 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002341}
Guido van Rossuma890e681998-05-12 14:59:24 +00002342
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002343void
2344PySys_SetArgv(int argc, wchar_t **argv)
2345{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002346 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002347}
2348
Victor Stinner14284c22010-04-23 12:02:30 +00002349/* Reimplementation of PyFile_WriteString() no calling indirectly
2350 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2351
2352static int
Victor Stinner79766632010-08-16 17:36:42 +00002353sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002354{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002355 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002357
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002358 if (file == NULL)
2359 return -1;
2360
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002361 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 if (writer == NULL)
2363 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002364
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002365 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 if (result == NULL) {
2367 goto error;
2368 } else {
2369 err = 0;
2370 goto finally;
2371 }
Victor Stinner14284c22010-04-23 12:02:30 +00002372
2373error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002375finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002376 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 Py_XDECREF(result);
2378 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002379}
2380
Victor Stinner79766632010-08-16 17:36:42 +00002381static int
2382sys_pyfile_write(const char *text, PyObject *file)
2383{
2384 PyObject *unicode = NULL;
2385 int err;
2386
2387 if (file == NULL)
2388 return -1;
2389
2390 unicode = PyUnicode_FromString(text);
2391 if (unicode == NULL)
2392 return -1;
2393
2394 err = sys_pyfile_write_unicode(unicode, file);
2395 Py_DECREF(unicode);
2396 return err;
2397}
Guido van Rossuma890e681998-05-12 14:59:24 +00002398
2399/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2400 Adapted from code submitted by Just van Rossum.
2401
2402 PySys_WriteStdout(format, ...)
2403 PySys_WriteStderr(format, ...)
2404
2405 The first function writes to sys.stdout; the second to sys.stderr. When
2406 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002407 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002408
Victor Stinner14284c22010-04-23 12:02:30 +00002409 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002410 signal handlers: they may raise a new exception whereas sys_write()
2411 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002412
Guido van Rossuma890e681998-05-12 14:59:24 +00002413 Both take a printf-style format string as their first argument followed
2414 by a variable length argument list determined by the format string.
2415
2416 *** WARNING ***
2417
2418 The format should limit the total size of the formatted output string to
2419 1000 bytes. In particular, this means that no unrestricted "%s" formats
2420 should occur; these should be limited using "%.<N>s where <N> is a
2421 decimal number calculated so that <N> plus the maximum size of other
2422 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2423 which can print hundreds of digits for very large numbers.
2424
2425 */
2426
2427static void
Victor Stinner09054372013-11-06 22:41:44 +01002428sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002429{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 PyObject *file;
2431 PyObject *error_type, *error_value, *error_traceback;
2432 char buffer[1001];
2433 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002436 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2438 if (sys_pyfile_write(buffer, file) != 0) {
2439 PyErr_Clear();
2440 fputs(buffer, fp);
2441 }
2442 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2443 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002444 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 }
2447 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002448}
2449
2450void
Guido van Rossuma890e681998-05-12 14:59:24 +00002451PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002456 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002457 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002458}
2459
2460void
Guido van Rossuma890e681998-05-12 14:59:24 +00002461PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002462{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002464
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002466 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002467 va_end(va);
2468}
2469
2470static void
Victor Stinner09054372013-11-06 22:41:44 +01002471sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002472{
2473 PyObject *file, *message;
2474 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002475 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002476
2477 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002478 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002479 message = PyUnicode_FromFormatV(format, va);
2480 if (message != NULL) {
2481 if (sys_pyfile_write_unicode(message, file) != 0) {
2482 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002483 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002484 if (utf8 != NULL)
2485 fputs(utf8, fp);
2486 }
2487 Py_DECREF(message);
2488 }
2489 PyErr_Restore(error_type, error_value, error_traceback);
2490}
2491
2492void
2493PySys_FormatStdout(const char *format, ...)
2494{
2495 va_list va;
2496
2497 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002498 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002499 va_end(va);
2500}
2501
2502void
2503PySys_FormatStderr(const char *format, ...)
2504{
2505 va_list va;
2506
2507 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002508 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002509 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002510}