blob: 080c541c6df7df7cf1b1713dfb2b873d7399a2ad [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020020#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossume2437a11992-03-23 18:20:18 +000022#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020023#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000024
Mark Hammond8696ebc2002-10-08 02:44:31 +000025#ifdef MS_WINDOWS
26#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000027#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000028#endif /* MS_WINDOWS */
29
Guido van Rossum9b38a141996-09-11 23:12:24 +000030#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000031extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000032/* A string loaded from the DLL at startup: */
33extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000034#endif
35
Victor Stinnerbd303c12013-11-07 23:07:29 +010036_Py_IDENTIFIER(_);
37_Py_IDENTIFIER(__sizeof__);
38_Py_IDENTIFIER(buffer);
39_Py_IDENTIFIER(builtins);
40_Py_IDENTIFIER(encoding);
41_Py_IDENTIFIER(path);
42_Py_IDENTIFIER(stdout);
43_Py_IDENTIFIER(stderr);
44_Py_IDENTIFIER(write);
45
Guido van Rossum65bf9f21997-04-29 18:33:38 +000046PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010047_PySys_GetObjectId(_Py_Identifier *key)
48{
49 PyThreadState *tstate = PyThreadState_GET();
50 PyObject *sd = tstate->interp->sysdict;
51 if (sd == NULL)
52 return NULL;
53 return _PyDict_GetItemId(sd, key);
54}
55
56PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000057PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000059 PyThreadState *tstate = PyThreadState_GET();
60 PyObject *sd = tstate->interp->sysdict;
61 if (sd == NULL)
62 return NULL;
63 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000064}
65
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066int
Victor Stinnerd67bd452013-11-06 22:36:40 +010067_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
68{
69 PyThreadState *tstate = PyThreadState_GET();
70 PyObject *sd = tstate->interp->sysdict;
71 if (v == NULL) {
72 if (_PyDict_GetItemId(sd, key) == NULL)
73 return 0;
74 else
75 return _PyDict_DelItemId(sd, key);
76 }
77 else
78 return _PyDict_SetItemId(sd, key, v);
79}
80
81int
Neal Norwitzf3081322007-08-25 00:32:45 +000082PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000084 PyThreadState *tstate = PyThreadState_GET();
85 PyObject *sd = tstate->interp->sysdict;
86 if (v == NULL) {
87 if (PyDict_GetItemString(sd, name) == NULL)
88 return 0;
89 else
90 return PyDict_DelItemString(sd, name);
91 }
92 else
93 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000094}
95
Victor Stinner13d49ee2010-12-04 17:24:33 +000096/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
97 error handler. If sys.stdout has a buffer attribute, use
98 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
99 sys.stdout.write(redecoded).
100
101 Helper function for sys_displayhook(). */
102static int
103sys_displayhook_unencodable(PyObject *outf, PyObject *o)
104{
105 PyObject *stdout_encoding = NULL;
106 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200107 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000108 int ret;
109
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200110 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000111 if (stdout_encoding == NULL)
112 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200113 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000114 if (stdout_encoding_str == NULL)
115 goto error;
116
117 repr_str = PyObject_Repr(o);
118 if (repr_str == NULL)
119 goto error;
120 encoded = PyUnicode_AsEncodedString(repr_str,
121 stdout_encoding_str,
122 "backslashreplace");
123 Py_DECREF(repr_str);
124 if (encoded == NULL)
125 goto error;
126
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200127 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000128 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100129 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000130 Py_DECREF(buffer);
131 Py_DECREF(encoded);
132 if (result == NULL)
133 goto error;
134 Py_DECREF(result);
135 }
136 else {
137 PyErr_Clear();
138 escaped_str = PyUnicode_FromEncodedObject(encoded,
139 stdout_encoding_str,
140 "strict");
141 Py_DECREF(encoded);
142 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
143 Py_DECREF(escaped_str);
144 goto error;
145 }
146 Py_DECREF(escaped_str);
147 }
148 ret = 0;
149 goto finally;
150
151error:
152 ret = -1;
153finally:
154 Py_XDECREF(stdout_encoding);
155 return ret;
156}
157
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000158static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000159sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000160{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000161 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100162 PyObject *builtins;
163 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000164 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000165
Eric Snow86b7afd2017-09-04 17:54:09 -0600166 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000167 if (builtins == NULL) {
168 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
169 return NULL;
170 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000171
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 /* Print value except if None */
173 /* After printing, also assign to '_' */
174 /* Before, set '_' to None to avoid recursion */
175 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200176 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200178 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000179 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100180 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000181 if (outf == NULL || outf == Py_None) {
182 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
183 return NULL;
184 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000185 if (PyFile_WriteObject(o, outf, 0) != 0) {
186 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
187 /* repr(o) is not encodable to sys.stdout.encoding with
188 * sys.stdout.errors error handler (which is probably 'strict') */
189 PyErr_Clear();
190 err = sys_displayhook_unencodable(outf, o);
191 if (err)
192 return NULL;
193 }
194 else {
195 return NULL;
196 }
197 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100198 if (newline == NULL) {
199 newline = PyUnicode_FromString("\n");
200 if (newline == NULL)
201 return NULL;
202 }
203 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200205 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200207 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000208}
209
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000210PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000211"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000212"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000213"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000214);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000215
216static PyObject *
217sys_excepthook(PyObject* self, PyObject* args)
218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 PyObject *exc, *value, *tb;
220 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
221 return NULL;
222 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200223 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000224}
225
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000226PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000227"excepthook(exctype, value, traceback) -> None\n"
228"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000229"Handle an exception by displaying it with a traceback on sys.stderr.\n"
230);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000231
232static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000233sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000235 PyThreadState *tstate;
236 tstate = PyThreadState_GET();
237 return Py_BuildValue(
238 "(OOO)",
239 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
240 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
241 tstate->exc_traceback != NULL ?
242 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000243}
244
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000245PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000246"exc_info() -> (type, value, traceback)\n\
247\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000248Return information about the most recent exception caught by an except\n\
249clause in the current stack frame or in an older stack frame."
250);
251
252static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000253sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000255 PyObject *exit_code = 0;
256 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
257 return NULL;
258 /* Raise SystemExit so callers may catch it or clean up. */
259 PyErr_SetObject(PyExc_SystemExit, exit_code);
260 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000261}
262
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000263PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000264"exit([status])\n\
265\n\
266Exit the interpreter by raising SystemExit(status).\n\
267If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300268If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000269If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000270exit status will be one (i.e., failure)."
271);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000272
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000273
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000274static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000275sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000278}
279
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000280PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000281"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000282\n\
283Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000284implementation."
285);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000286
287static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000288sys_getfilesystemencoding(PyObject *self)
289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 if (Py_FileSystemDefaultEncoding)
291 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200292 PyErr_SetString(PyExc_RuntimeError,
293 "filesystem encoding is not initialized");
294 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000295}
296
297PyDoc_STRVAR(getfilesystemencoding_doc,
298"getfilesystemencoding() -> string\n\
299\n\
300Return the encoding used to convert Unicode filenames in\n\
301operating system filenames."
302);
303
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000304static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700305sys_getfilesystemencodeerrors(PyObject *self)
306{
307 if (Py_FileSystemDefaultEncodeErrors)
308 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
309 PyErr_SetString(PyExc_RuntimeError,
310 "filesystem encoding is not initialized");
311 return NULL;
312}
313
314PyDoc_STRVAR(getfilesystemencodeerrors_doc,
315 "getfilesystemencodeerrors() -> string\n\
316\n\
317Return the error mode used to convert Unicode filenames in\n\
318operating system filenames."
319);
320
321static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000322sys_intern(PyObject *self, PyObject *args)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject *s;
325 if (!PyArg_ParseTuple(args, "U:intern", &s))
326 return NULL;
327 if (PyUnicode_CheckExact(s)) {
328 Py_INCREF(s);
329 PyUnicode_InternInPlace(&s);
330 return s;
331 }
332 else {
333 PyErr_Format(PyExc_TypeError,
334 "can't intern %.400s", s->ob_type->tp_name);
335 return NULL;
336 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000337}
338
339PyDoc_STRVAR(intern_doc,
340"intern(string) -> string\n\
341\n\
342``Intern'' the given string. This enters the string in the (global)\n\
343table of interned strings whose purpose is to speed up dictionary lookups.\n\
344Return the string itself or the previously interned string object with the\n\
345same value.");
346
347
Fred Drake5755ce62001-06-27 19:19:46 +0000348/*
349 * Cached interned string objects used for calling the profile and
350 * trace functions. Initialized by trace_init().
351 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000352static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000353
354static int
355trace_init(void)
356{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200357 static const char * const whatnames[7] = {
358 "call", "exception", "line", "return",
359 "c_call", "c_exception", "c_return"
360 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyObject *name;
362 int i;
363 for (i = 0; i < 7; ++i) {
364 if (whatstrings[i] == NULL) {
365 name = PyUnicode_InternFromString(whatnames[i]);
366 if (name == NULL)
367 return -1;
368 whatstrings[i] = name;
369 }
370 }
371 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000372}
373
374
375static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100376call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200380 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000381
Victor Stinner78da82b2016-08-20 01:22:57 +0200382 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200384 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100385
Victor Stinner78da82b2016-08-20 01:22:57 +0200386 stack[0] = (PyObject *)frame;
387 stack[1] = whatstrings[what];
388 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200391 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000392
Victor Stinner78da82b2016-08-20 01:22:57 +0200393 PyFrame_LocalsToFast(frame, 1);
394 if (result == NULL) {
395 PyTraceBack_Here(frame);
396 }
397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000399}
400
401static int
402profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000403 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000404{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000405 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (arg == NULL)
408 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100409 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (result == NULL) {
411 PyEval_SetProfile(NULL, NULL);
412 return -1;
413 }
414 Py_DECREF(result);
415 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000416}
417
418static int
419trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyObject *callback;
423 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 if (what == PyTrace_CALL)
426 callback = self;
427 else
428 callback = frame->f_trace;
429 if (callback == NULL)
430 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100431 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 if (result == NULL) {
433 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200434 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 return -1;
436 }
437 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300438 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 }
440 else {
441 Py_DECREF(result);
442 }
443 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000444}
Fred Draked0838392001-06-16 21:02:31 +0000445
Fred Drake8b4d01d2000-05-09 19:57:01 +0000446static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000447sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000448{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 if (trace_init() == -1)
450 return NULL;
451 if (args == Py_None)
452 PyEval_SetTrace(NULL, NULL);
453 else
454 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200455 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000456}
457
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000458PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000459"settrace(function)\n\
460\n\
461Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000462function call. See the debugger chapter in the library manual."
463);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000464
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000465static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000466sys_gettrace(PyObject *self, PyObject *args)
467{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 PyThreadState *tstate = PyThreadState_GET();
469 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (temp == NULL)
472 temp = Py_None;
473 Py_INCREF(temp);
474 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000475}
476
477PyDoc_STRVAR(gettrace_doc,
478"gettrace()\n\
479\n\
480Return the global debug tracing function set with sys.settrace.\n\
481See the debugger chapter in the library manual."
482);
483
484static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000485sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 if (trace_init() == -1)
488 return NULL;
489 if (args == Py_None)
490 PyEval_SetProfile(NULL, NULL);
491 else
492 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200493 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000494}
495
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000496PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000497"setprofile(function)\n\
498\n\
499Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000500and return. See the profiler chapter in the library manual."
501);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000502
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000503static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000504sys_getprofile(PyObject *self, PyObject *args)
505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PyThreadState *tstate = PyThreadState_GET();
507 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (temp == NULL)
510 temp = Py_None;
511 Py_INCREF(temp);
512 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000513}
514
515PyDoc_STRVAR(getprofile_doc,
516"getprofile()\n\
517\n\
518Return the profiling function set with sys.setprofile.\n\
519See the profiler chapter in the library manual."
520);
521
522static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000523sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (PyErr_WarnEx(PyExc_DeprecationWarning,
526 "sys.getcheckinterval() and sys.setcheckinterval() "
527 "are deprecated. Use sys.setswitchinterval() "
528 "instead.", 1) < 0)
529 return NULL;
Eric Snow76d5abc2017-09-05 18:26:16 -0700530 PyInterpreterState *interp = PyThreadState_GET()->interp;
531 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200533 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000534}
535
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000536PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000537"setcheckinterval(n)\n\
538\n\
539Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000540n instructions. This also affects how often thread switches occur."
541);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000542
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000543static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000544sys_getcheckinterval(PyObject *self, PyObject *args)
545{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (PyErr_WarnEx(PyExc_DeprecationWarning,
547 "sys.getcheckinterval() and sys.setcheckinterval() "
548 "are deprecated. Use sys.getswitchinterval() "
549 "instead.", 1) < 0)
550 return NULL;
Eric Snow76d5abc2017-09-05 18:26:16 -0700551 PyInterpreterState *interp = PyThreadState_GET()->interp;
552 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000553}
554
555PyDoc_STRVAR(getcheckinterval_doc,
556"getcheckinterval() -> current check interval; see setcheckinterval()."
557);
558
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000559#ifdef WITH_THREAD
560static PyObject *
561sys_setswitchinterval(PyObject *self, PyObject *args)
562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 double d;
564 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
565 return NULL;
566 if (d <= 0.0) {
567 PyErr_SetString(PyExc_ValueError,
568 "switch interval must be strictly positive");
569 return NULL;
570 }
571 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200572 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000573}
574
575PyDoc_STRVAR(setswitchinterval_doc,
576"setswitchinterval(n)\n\
577\n\
578Set the ideal thread switching delay inside the Python interpreter\n\
579The actual frequency of switching threads can be lower if the\n\
580interpreter executes long sequences of uninterruptible code\n\
581(this is implementation-specific and workload-dependent).\n\
582\n\
583The parameter must represent the desired switching delay in seconds\n\
584A typical value is 0.005 (5 milliseconds)."
585);
586
587static PyObject *
588sys_getswitchinterval(PyObject *self, PyObject *args)
589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000591}
592
593PyDoc_STRVAR(getswitchinterval_doc,
594"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
595);
596
597#endif /* WITH_THREAD */
598
Tim Peterse5e065b2003-07-06 18:36:54 +0000599static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000600sys_setrecursionlimit(PyObject *self, PyObject *args)
601{
Victor Stinner50856d52015-10-13 00:11:21 +0200602 int new_limit, mark;
603 PyThreadState *tstate;
604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
606 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200607
608 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200610 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return NULL;
612 }
Victor Stinner50856d52015-10-13 00:11:21 +0200613
614 /* Issue #25274: When the recursion depth hits the recursion limit in
615 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
616 set to 1 and a RecursionError is raised. The overflowed flag is reset
617 to 0 when the recursion depth goes below the low-water mark: see
618 Py_LeaveRecursiveCall().
619
620 Reject too low new limit if the current recursion depth is higher than
621 the new low-water mark. Otherwise it may not be possible anymore to
622 reset the overflowed flag to 0. */
623 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
624 tstate = PyThreadState_GET();
625 if (tstate->recursion_depth >= mark) {
626 PyErr_Format(PyExc_RecursionError,
627 "cannot set the recursion limit to %i at "
628 "the recursion depth %i: the limit is too low",
629 new_limit, tstate->recursion_depth);
630 return NULL;
631 }
632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200634 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000635}
636
Yury Selivanov75445082015-05-11 22:57:16 -0400637static PyObject *
638sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
639{
640 if (wrapper != Py_None) {
641 if (!PyCallable_Check(wrapper)) {
642 PyErr_Format(PyExc_TypeError,
643 "callable expected, got %.50s",
644 Py_TYPE(wrapper)->tp_name);
645 return NULL;
646 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400647 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400648 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400649 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400650 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400651 }
Yury Selivanov75445082015-05-11 22:57:16 -0400652 Py_RETURN_NONE;
653}
654
655PyDoc_STRVAR(set_coroutine_wrapper_doc,
656"set_coroutine_wrapper(wrapper)\n\
657\n\
658Set a wrapper for coroutine objects."
659);
660
661static PyObject *
662sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
663{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400664 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400665 if (wrapper == NULL) {
666 wrapper = Py_None;
667 }
668 Py_INCREF(wrapper);
669 return wrapper;
670}
671
672PyDoc_STRVAR(get_coroutine_wrapper_doc,
673"get_coroutine_wrapper()\n\
674\n\
675Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
676);
677
678
Yury Selivanoveb636452016-09-08 22:01:51 -0700679static PyTypeObject AsyncGenHooksType;
680
681PyDoc_STRVAR(asyncgen_hooks_doc,
682"asyncgen_hooks\n\
683\n\
684A struct sequence providing information about asynhronous\n\
685generators hooks. The attributes are read only.");
686
687static PyStructSequence_Field asyncgen_hooks_fields[] = {
688 {"firstiter", "Hook to intercept first iteration"},
689 {"finalizer", "Hook to intercept finalization"},
690 {0}
691};
692
693static PyStructSequence_Desc asyncgen_hooks_desc = {
694 "asyncgen_hooks", /* name */
695 asyncgen_hooks_doc, /* doc */
696 asyncgen_hooks_fields , /* fields */
697 2
698};
699
700
701static PyObject *
702sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
703{
704 static char *keywords[] = {"firstiter", "finalizer", NULL};
705 PyObject *firstiter = NULL;
706 PyObject *finalizer = NULL;
707
708 if (!PyArg_ParseTupleAndKeywords(
709 args, kw, "|OO", keywords,
710 &firstiter, &finalizer)) {
711 return NULL;
712 }
713
714 if (finalizer && finalizer != Py_None) {
715 if (!PyCallable_Check(finalizer)) {
716 PyErr_Format(PyExc_TypeError,
717 "callable finalizer expected, got %.50s",
718 Py_TYPE(finalizer)->tp_name);
719 return NULL;
720 }
721 _PyEval_SetAsyncGenFinalizer(finalizer);
722 }
723 else if (finalizer == Py_None) {
724 _PyEval_SetAsyncGenFinalizer(NULL);
725 }
726
727 if (firstiter && firstiter != Py_None) {
728 if (!PyCallable_Check(firstiter)) {
729 PyErr_Format(PyExc_TypeError,
730 "callable firstiter expected, got %.50s",
731 Py_TYPE(firstiter)->tp_name);
732 return NULL;
733 }
734 _PyEval_SetAsyncGenFirstiter(firstiter);
735 }
736 else if (firstiter == Py_None) {
737 _PyEval_SetAsyncGenFirstiter(NULL);
738 }
739
740 Py_RETURN_NONE;
741}
742
743PyDoc_STRVAR(set_asyncgen_hooks_doc,
744"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
745\n\
746Set a finalizer for async generators objects."
747);
748
749static PyObject *
750sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
751{
752 PyObject *res;
753 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
754 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
755
756 res = PyStructSequence_New(&AsyncGenHooksType);
757 if (res == NULL) {
758 return NULL;
759 }
760
761 if (firstiter == NULL) {
762 firstiter = Py_None;
763 }
764
765 if (finalizer == NULL) {
766 finalizer = Py_None;
767 }
768
769 Py_INCREF(firstiter);
770 PyStructSequence_SET_ITEM(res, 0, firstiter);
771
772 Py_INCREF(finalizer);
773 PyStructSequence_SET_ITEM(res, 1, finalizer);
774
775 return res;
776}
777
778PyDoc_STRVAR(get_asyncgen_hooks_doc,
779"get_asyncgen_hooks()\n\
780\n\
781Return a namedtuple of installed asynchronous generators hooks \
782(firstiter, finalizer)."
783);
784
785
Mark Dickinsondc787d22010-05-23 13:33:13 +0000786static PyTypeObject Hash_InfoType;
787
788PyDoc_STRVAR(hash_info_doc,
789"hash_info\n\
790\n\
791A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100792hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000793
794static PyStructSequence_Field hash_info_fields[] = {
795 {"width", "width of the type used for hashing, in bits"},
796 {"modulus", "prime number giving the modulus on which the hash "
797 "function is based"},
798 {"inf", "value to be used for hash of a positive infinity"},
799 {"nan", "value to be used for hash of a nan"},
800 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100801 {"algorithm", "name of the algorithm for hashing of str, bytes and "
802 "memoryviews"},
803 {"hash_bits", "internal output size of hash algorithm"},
804 {"seed_bits", "seed size of hash algorithm"},
805 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000806 {NULL, NULL}
807};
808
809static PyStructSequence_Desc hash_info_desc = {
810 "sys.hash_info",
811 hash_info_doc,
812 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100813 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000814};
815
Matthias Klosed885e952010-07-06 10:53:30 +0000816static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000817get_hash_info(void)
818{
819 PyObject *hash_info;
820 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100821 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000822 hash_info = PyStructSequence_New(&Hash_InfoType);
823 if (hash_info == NULL)
824 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100825 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000826 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000827 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000828 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000829 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000830 PyStructSequence_SET_ITEM(hash_info, field++,
831 PyLong_FromLong(_PyHASH_INF));
832 PyStructSequence_SET_ITEM(hash_info, field++,
833 PyLong_FromLong(_PyHASH_NAN));
834 PyStructSequence_SET_ITEM(hash_info, field++,
835 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100836 PyStructSequence_SET_ITEM(hash_info, field++,
837 PyUnicode_FromString(hashfunc->name));
838 PyStructSequence_SET_ITEM(hash_info, field++,
839 PyLong_FromLong(hashfunc->hash_bits));
840 PyStructSequence_SET_ITEM(hash_info, field++,
841 PyLong_FromLong(hashfunc->seed_bits));
842 PyStructSequence_SET_ITEM(hash_info, field++,
843 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000844 if (PyErr_Occurred()) {
845 Py_CLEAR(hash_info);
846 return NULL;
847 }
848 return hash_info;
849}
850
851
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000852PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000853"setrecursionlimit(n)\n\
854\n\
855Set the maximum depth of the Python interpreter stack to n. This\n\
856limit prevents infinite recursion from causing an overflow of the C\n\
857stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000858dependent."
859);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000860
861static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000862sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000863{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000865}
866
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000867PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000868"getrecursionlimit()\n\
869\n\
870Return the current value of the recursion limit, the maximum depth\n\
871of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000872recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000873);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000874
Mark Hammond8696ebc2002-10-08 02:44:31 +0000875#ifdef MS_WINDOWS
876PyDoc_STRVAR(getwindowsversion_doc,
877"getwindowsversion()\n\
878\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000879Return information about the running version of Windows as a named tuple.\n\
880The members are named: major, minor, build, platform, service_pack,\n\
881service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200882backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700883All elements are numbers, except service_pack and platform_type which are\n\
884strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
885Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
886server. Platform_version is a 3-tuple containing a version number that is\n\
887intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000888);
889
Eric Smithf7bb5782010-01-27 00:44:57 +0000890static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
891
892static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000893 {"major", "Major version number"},
894 {"minor", "Minor version number"},
895 {"build", "Build number"},
896 {"platform", "Operating system platform"},
897 {"service_pack", "Latest Service Pack installed on the system"},
898 {"service_pack_major", "Service Pack major version number"},
899 {"service_pack_minor", "Service Pack minor version number"},
900 {"suite_mask", "Bit mask identifying available product suites"},
901 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700902 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000903 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000904};
905
906static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000907 "sys.getwindowsversion", /* name */
908 getwindowsversion_doc, /* doc */
909 windows_version_fields, /* fields */
910 5 /* For backward compatibility,
911 only the first 5 items are accessible
912 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000913};
914
Steve Dower3e96f322015-03-02 08:01:10 -0800915/* Disable deprecation warnings about GetVersionEx as the result is
916 being passed straight through to the caller, who is responsible for
917 using it correctly. */
918#pragma warning(push)
919#pragma warning(disable:4996)
920
Mark Hammond8696ebc2002-10-08 02:44:31 +0000921static PyObject *
922sys_getwindowsversion(PyObject *self)
923{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 PyObject *version;
925 int pos = 0;
926 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700927 DWORD realMajor, realMinor, realBuild;
928 HANDLE hKernel32;
929 wchar_t kernel32_path[MAX_PATH];
930 LPVOID verblock;
931 DWORD verblock_size;
932
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 ver.dwOSVersionInfoSize = sizeof(ver);
934 if (!GetVersionEx((OSVERSIONINFO*) &ver))
935 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000936
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000937 version = PyStructSequence_New(&WindowsVersionType);
938 if (version == NULL)
939 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000940
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
942 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
943 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
944 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
945 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
946 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
948 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
949 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000950
Steve Dower74f4af72016-09-17 17:27:48 -0700951 realMajor = ver.dwMajorVersion;
952 realMinor = ver.dwMinorVersion;
953 realBuild = ver.dwBuildNumber;
954
955 // GetVersion will lie if we are running in a compatibility mode.
956 // We need to read the version info from a system file resource
957 // to accurately identify the OS version. If we fail for any reason,
958 // just return whatever GetVersion said.
959 hKernel32 = GetModuleHandleW(L"kernel32.dll");
960 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
961 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
962 (verblock = PyMem_RawMalloc(verblock_size))) {
963 VS_FIXEDFILEINFO *ffi;
964 UINT ffi_len;
965
966 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
967 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
968 realMajor = HIWORD(ffi->dwProductVersionMS);
969 realMinor = LOWORD(ffi->dwProductVersionMS);
970 realBuild = HIWORD(ffi->dwProductVersionLS);
971 }
972 PyMem_RawFree(verblock);
973 }
Segev Finer48fb7662017-06-04 20:52:27 +0300974 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
975 realMajor,
976 realMinor,
977 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700978 ));
979
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200980 if (PyErr_Occurred()) {
981 Py_DECREF(version);
982 return NULL;
983 }
Steve Dower74f4af72016-09-17 17:27:48 -0700984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000985 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000986}
987
Steve Dower3e96f322015-03-02 08:01:10 -0800988#pragma warning(pop)
989
Steve Dowercc16be82016-09-08 10:35:16 -0700990PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
991"_enablelegacywindowsfsencoding()\n\
992\n\
993Changes the default filesystem encoding to mbcs:replace for consistency\n\
994with earlier versions of Python. See PEP 529 for more information.\n\
995\n\
996This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
997environment variable before launching Python."
998);
999
1000static PyObject *
1001sys_enablelegacywindowsfsencoding(PyObject *self)
1002{
1003 Py_FileSystemDefaultEncoding = "mbcs";
1004 Py_FileSystemDefaultEncodeErrors = "replace";
1005 Py_RETURN_NONE;
1006}
1007
Mark Hammond8696ebc2002-10-08 02:44:31 +00001008#endif /* MS_WINDOWS */
1009
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001010#ifdef HAVE_DLOPEN
1011static PyObject *
1012sys_setdlopenflags(PyObject *self, PyObject *args)
1013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 int new_val;
1015 PyThreadState *tstate = PyThreadState_GET();
1016 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1017 return NULL;
1018 if (!tstate)
1019 return NULL;
1020 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001021 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001022}
1023
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001024PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001025"setdlopenflags(n) -> None\n\
1026\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001027Set the flags used by the interpreter for dlopen calls, such as when the\n\
1028interpreter loads extension modules. Among other things, this will enable\n\
1029a lazy resolving of symbols when importing a module, if called as\n\
1030sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001031sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001032can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001033
1034static PyObject *
1035sys_getdlopenflags(PyObject *self, PyObject *args)
1036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyThreadState *tstate = PyThreadState_GET();
1038 if (!tstate)
1039 return NULL;
1040 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001041}
1042
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001043PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001044"getdlopenflags() -> int\n\
1045\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001046Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001047The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001050
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001051#ifdef USE_MALLOPT
1052/* Link with -lmalloc (or -lmpc) on an SGI */
1053#include <malloc.h>
1054
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001055static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001056sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 int flag;
1059 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1060 return NULL;
1061 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001062 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001063}
1064#endif /* USE_MALLOPT */
1065
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001066size_t
1067_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001071 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001072
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 /* Make sure the type is initialized. float gets initialized late */
1074 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001075 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001076
Benjamin Petersonce798522012-01-22 11:24:29 -05001077 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 if (method == NULL) {
1079 if (!PyErr_Occurred())
1080 PyErr_Format(PyExc_TypeError,
1081 "Type %.100s doesn't define __sizeof__",
1082 Py_TYPE(o)->tp_name);
1083 }
1084 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001085 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 Py_DECREF(method);
1087 }
1088
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001089 if (res == NULL)
1090 return (size_t)-1;
1091
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001092 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001093 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001094 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001095 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001097 if (size < 0) {
1098 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1099 return (size_t)-1;
1100 }
1101
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001102 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001103 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001104 return ((size_t)size) + sizeof(PyGC_Head);
1105 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001106}
1107
1108static PyObject *
1109sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1110{
1111 static char *kwlist[] = {"object", "default", 0};
1112 size_t size;
1113 PyObject *o, *dflt = NULL;
1114
1115 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1116 kwlist, &o, &dflt))
1117 return NULL;
1118
1119 size = _PySys_GetSizeOf(o);
1120
1121 if (size == (size_t)-1 && PyErr_Occurred()) {
1122 /* Has a default value been given */
1123 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1124 PyErr_Clear();
1125 Py_INCREF(dflt);
1126 return dflt;
1127 }
1128 else
1129 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001131
1132 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001133}
1134
1135PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001136"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001137\n\
1138Return the size of object in bytes.");
1139
1140static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001141sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001144}
1145
Tim Peters4be93d02002-07-07 19:59:50 +00001146#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001147static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001148sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001150 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001151}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001152#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001153
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001154PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001155"getrefcount(object) -> integer\n\
1156\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001157Return the reference count of object. The count returned is generally\n\
1158one higher than you might expect, because it includes the (temporary)\n\
1159reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001160);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001161
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001162static PyObject *
1163sys_getallocatedblocks(PyObject *self)
1164{
1165 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1166}
1167
1168PyDoc_STRVAR(getallocatedblocks_doc,
1169"getallocatedblocks() -> integer\n\
1170\n\
1171Return the number of memory blocks currently allocated, regardless of their\n\
1172size."
1173);
1174
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001175#ifdef COUNT_ALLOCS
1176static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001177sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001182}
1183#endif
1184
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001185PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001186"_getframe([depth]) -> frameobject\n\
1187\n\
1188Return a frame object from the call stack. If optional integer depth is\n\
1189given, return the frame object that many calls below the top of the stack.\n\
1190If that is deeper than the call stack, ValueError is raised. The default\n\
1191for depth is zero, returning the frame at the top of the call stack.\n\
1192\n\
1193This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001194purposes only."
1195);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001196
1197static PyObject *
1198sys_getframe(PyObject *self, PyObject *args)
1199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyFrameObject *f = PyThreadState_GET()->frame;
1201 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1204 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 while (depth > 0 && f != NULL) {
1207 f = f->f_back;
1208 --depth;
1209 }
1210 if (f == NULL) {
1211 PyErr_SetString(PyExc_ValueError,
1212 "call stack is not deep enough");
1213 return NULL;
1214 }
1215 Py_INCREF(f);
1216 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001217}
1218
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001219PyDoc_STRVAR(current_frames_doc,
1220"_current_frames() -> dictionary\n\
1221\n\
1222Return a dictionary mapping each current thread T's thread id to T's\n\
1223current stack frame.\n\
1224\n\
1225This function should be used for specialized purposes only."
1226);
1227
1228static PyObject *
1229sys_current_frames(PyObject *self, PyObject *noargs)
1230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001232}
1233
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001234PyDoc_STRVAR(call_tracing_doc,
1235"call_tracing(func, args) -> object\n\
1236\n\
1237Call func(*args), while tracing is enabled. The tracing state is\n\
1238saved, and restored afterwards. This is intended to be called from\n\
1239a debugger from a checkpoint, to recursively debug some other code."
1240);
1241
1242static PyObject *
1243sys_call_tracing(PyObject *self, PyObject *args)
1244{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 PyObject *func, *funcargs;
1246 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1247 return NULL;
1248 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001249}
1250
Jeremy Hylton985eba52003-02-05 23:13:00 +00001251PyDoc_STRVAR(callstats_doc,
1252"callstats() -> tuple of integers\n\
1253\n\
1254Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1255when Python was built. Otherwise, return None.\n\
1256\n\
1257When enabled, this function returns detailed, implementation-specific\n\
1258details about the number of function calls executed. The return value is\n\
1259a 11-tuple where the entries in the tuple are counts of:\n\
12600. all function calls\n\
12611. calls to PyFunction_Type objects\n\
12622. PyFunction calls that do not create an argument tuple\n\
12633. PyFunction calls that do not create an argument tuple\n\
1264 and bypass PyEval_EvalCodeEx()\n\
12654. PyMethod calls\n\
12665. PyMethod calls on bound methods\n\
12676. PyType calls\n\
12687. PyCFunction calls\n\
12698. generator calls\n\
12709. All other calls\n\
127110. Number of stack pops performed by call_function()"
1272);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001273
Victor Stinner048afd92016-11-28 11:59:04 +01001274static PyObject *
1275sys_callstats(PyObject *self)
1276{
1277 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1278 "sys.callstats() has been deprecated in Python 3.7 "
1279 "and will be removed in the future", 1) < 0) {
1280 return NULL;
1281 }
1282
1283 Py_RETURN_NONE;
1284}
1285
1286
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001287#ifdef __cplusplus
1288extern "C" {
1289#endif
1290
David Malcolm49526f42012-06-22 14:55:41 -04001291static PyObject *
1292sys_debugmallocstats(PyObject *self, PyObject *args)
1293{
1294#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001295 if (_PyMem_PymallocEnabled()) {
1296 _PyObject_DebugMallocStats(stderr);
1297 fputc('\n', stderr);
1298 }
David Malcolm49526f42012-06-22 14:55:41 -04001299#endif
1300 _PyObject_DebugTypeStats(stderr);
1301
1302 Py_RETURN_NONE;
1303}
1304PyDoc_STRVAR(debugmallocstats_doc,
1305"_debugmallocstats()\n\
1306\n\
1307Print summary info to stderr about the state of\n\
1308pymalloc's structures.\n\
1309\n\
1310In Py_DEBUG mode, also perform some expensive internal consistency\n\
1311checks.\n\
1312");
1313
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001314#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001315/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001316extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001317#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001318
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001319#ifdef DYNAMIC_EXECUTION_PROFILE
1320/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001321extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001322#endif
1323
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001324#ifdef __cplusplus
1325}
1326#endif
1327
Christian Heimes15ebc882008-02-04 18:48:49 +00001328static PyObject *
1329sys_clear_type_cache(PyObject* self, PyObject* args)
1330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 PyType_ClearCache();
1332 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001333}
1334
1335PyDoc_STRVAR(sys_clear_type_cache__doc__,
1336"_clear_type_cache() -> None\n\
1337Clear the internal type lookup cache.");
1338
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001339static PyObject *
1340sys_is_finalizing(PyObject* self, PyObject* args)
1341{
Eric Snow76d5abc2017-09-05 18:26:16 -07001342 return PyBool_FromLong(_Py_IS_FINALIZING());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001343}
1344
1345PyDoc_STRVAR(is_finalizing_doc,
1346"is_finalizing()\n\
1347Return True if Python is exiting.");
1348
Christian Heimes15ebc882008-02-04 18:48:49 +00001349
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001350#ifdef ANDROID_API_LEVEL
1351PyDoc_STRVAR(getandroidapilevel_doc,
1352"getandroidapilevel()\n\
1353\n\
1354Return the build time API version of Android as an integer.");
1355
1356static PyObject *
1357sys_getandroidapilevel(PyObject *self)
1358{
1359 return PyLong_FromLong(ANDROID_API_LEVEL);
1360}
1361#endif /* ANDROID_API_LEVEL */
1362
1363
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001364static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001366 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 callstats_doc},
1368 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1369 sys_clear_type_cache__doc__},
1370 {"_current_frames", sys_current_frames, METH_NOARGS,
1371 current_frames_doc},
1372 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1373 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1374 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1375 {"exit", sys_exit, METH_VARARGS, exit_doc},
1376 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1377 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001378#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1380 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001381#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001382 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1383 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001384#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001386#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001387#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001389#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1391 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001392 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1393 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001394#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001396#endif
1397#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001399#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1401 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1402 getrecursionlimit_doc},
1403 {"getsizeof", (PyCFunction)sys_getsizeof,
1404 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1405 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001406#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001407 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1408 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001409 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1410 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001411#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001413 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001414#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001416#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1418 setcheckinterval_doc},
1419 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1420 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001421#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1423 setswitchinterval_doc},
1424 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1425 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001426#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001427#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1429 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001430#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1432 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1433 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1434 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 {"settrace", sys_settrace, METH_O, settrace_doc},
1436 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1437 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001438 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001439 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001440 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1441 set_coroutine_wrapper_doc},
1442 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1443 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001444 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001445 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1446 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1447 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001448#ifdef ANDROID_API_LEVEL
1449 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1450 getandroidapilevel_doc},
1451#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001453};
1454
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001455static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001456list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 PyObject *list = PyList_New(0);
1459 int i;
1460 if (list == NULL)
1461 return NULL;
1462 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1463 PyObject *name = PyUnicode_FromString(
1464 PyImport_Inittab[i].name);
1465 if (name == NULL)
1466 break;
1467 PyList_Append(list, name);
1468 Py_DECREF(name);
1469 }
1470 if (PyList_Sort(list) != 0) {
1471 Py_DECREF(list);
1472 list = NULL;
1473 }
1474 if (list) {
1475 PyObject *v = PyList_AsTuple(list);
1476 Py_DECREF(list);
1477 list = v;
1478 }
1479 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001480}
1481
Eric Snow76d5abc2017-09-05 18:26:16 -07001482static PyObject *
1483get_warnoptions(void)
1484{
1485 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
1486 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1487 Py_XDECREF(warnoptions);
1488 warnoptions = PyList_New(0);
1489 if (warnoptions == NULL)
1490 return NULL;
1491 PyThreadState_GET()->interp->warnoptions = warnoptions;
1492 }
1493 return warnoptions;
1494}
Guido van Rossum23fff912000-12-15 22:02:05 +00001495
1496void
1497PySys_ResetWarnOptions(void)
1498{
Eric Snow76d5abc2017-09-05 18:26:16 -07001499 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001500 if (warnoptions == NULL || !PyList_Check(warnoptions))
1501 return;
1502 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001503}
1504
1505void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001506PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001507{
Eric Snow76d5abc2017-09-05 18:26:16 -07001508 PyObject *warnoptions = get_warnoptions();
1509 if (warnoptions == NULL)
1510 return;
Victor Stinner9ca9c252010-05-19 16:53:30 +00001511 PyList_Append(warnoptions, unicode);
1512}
1513
1514void
1515PySys_AddWarnOption(const wchar_t *s)
1516{
1517 PyObject *unicode;
1518 unicode = PyUnicode_FromWideChar(s, -1);
1519 if (unicode == NULL)
1520 return;
1521 PySys_AddWarnOptionUnicode(unicode);
1522 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001523}
1524
Christian Heimes33fe8092008-04-13 13:53:33 +00001525int
1526PySys_HasWarnOptions(void)
1527{
Eric Snow76d5abc2017-09-05 18:26:16 -07001528 PyObject *warnoptions = PyThreadState_GET()->interp->warnoptions;
Christian Heimes33fe8092008-04-13 13:53:33 +00001529 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1530}
1531
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001532static PyObject *
1533get_xoptions(void)
1534{
Eric Snow76d5abc2017-09-05 18:26:16 -07001535 PyObject *xoptions = PyThreadState_GET()->interp->xoptions;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001536 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1537 Py_XDECREF(xoptions);
1538 xoptions = PyDict_New();
Eric Snow76d5abc2017-09-05 18:26:16 -07001539 if (xoptions == NULL)
1540 return NULL;
1541 PyThreadState_GET()->interp->xoptions = xoptions;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001542 }
1543 return xoptions;
1544}
1545
1546void
1547PySys_AddXOption(const wchar_t *s)
1548{
1549 PyObject *opts;
1550 PyObject *name = NULL, *value = NULL;
1551 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001552
1553 opts = get_xoptions();
1554 if (opts == NULL)
1555 goto error;
1556
1557 name_end = wcschr(s, L'=');
1558 if (!name_end) {
1559 name = PyUnicode_FromWideChar(s, -1);
1560 value = Py_True;
1561 Py_INCREF(value);
1562 }
1563 else {
1564 name = PyUnicode_FromWideChar(s, name_end - s);
1565 value = PyUnicode_FromWideChar(name_end + 1, -1);
1566 }
1567 if (name == NULL || value == NULL)
1568 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001569 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001570 Py_DECREF(name);
1571 Py_DECREF(value);
1572 return;
1573
1574error:
1575 Py_XDECREF(name);
1576 Py_XDECREF(value);
1577 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001578 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001579 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001580 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001581}
1582
1583PyObject *
1584PySys_GetXOptions(void)
1585{
1586 return get_xoptions();
1587}
1588
Guido van Rossum40552d01998-08-06 03:34:39 +00001589/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1590 Two literals concatenated works just fine. If you have a K&R compiler
1591 or other abomination that however *does* understand longer strings,
1592 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001593PyDoc_VAR(sys_doc) =
1594PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001595"This module provides access to some objects used or maintained by the\n\
1596interpreter and to functions that interact strongly with the interpreter.\n\
1597\n\
1598Dynamic objects:\n\
1599\n\
1600argv -- command line arguments; argv[0] is the script pathname if known\n\
1601path -- module search path; path[0] is the script directory, else ''\n\
1602modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001603\n\
1604displayhook -- called to show results in an interactive session\n\
1605excepthook -- called to handle any uncaught exception other than SystemExit\n\
1606 To customize printing in an interactive session or to install a custom\n\
1607 top-level exception handler, assign other functions to replace these.\n\
1608\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001609stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001610stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001611stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001612 By assigning other file objects (or objects that behave like files)\n\
1613 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001614\n\
1615last_type -- type of last uncaught exception\n\
1616last_value -- value of last uncaught exception\n\
1617last_traceback -- traceback of last uncaught exception\n\
1618 These three are only available in an interactive session after a\n\
1619 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001620"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001621)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001622/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001623PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001624"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001625Static objects:\n\
1626\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001627builtin_module_names -- tuple of module names built into this interpreter\n\
1628copyright -- copyright notice pertaining to this interpreter\n\
1629exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001630executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001631float_info -- a struct sequence with information about the float implementation.\n\
1632float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001633hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001634hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001635implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001636int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001637maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001638maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001639platform -- platform identifier\n\
1640prefix -- prefix used to find the Python library\n\
1641thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001642version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001643version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001644"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001645)
Steve Dowercc16be82016-09-08 10:35:16 -07001646#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001647/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001648PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001649"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001650winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001651"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001652)
Steve Dowercc16be82016-09-08 10:35:16 -07001653#endif /* MS_COREDLL */
1654#ifdef MS_WINDOWS
1655/* concatenating string here */
1656PyDoc_STR(
1657"_enablelegacywindowsfsencoding -- [Windows only] \n\
1658"
1659)
1660#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001661PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001662"__stdin__ -- the original stdin; don't touch!\n\
1663__stdout__ -- the original stdout; don't touch!\n\
1664__stderr__ -- the original stderr; don't touch!\n\
1665__displayhook__ -- the original displayhook; don't touch!\n\
1666__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001667\n\
1668Functions:\n\
1669\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001670displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001671excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001672exc_info() -- return thread-safe information about the current exception\n\
1673exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001674getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001675getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001676getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001677getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001678getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001679gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001680setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001681setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001682setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001683setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001684settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001685"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001686)
Fred Drakeccede592000-08-14 20:59:57 +00001687/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001688
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001689
1690PyDoc_STRVAR(flags__doc__,
1691"sys.flags\n\
1692\n\
1693Flags provided through command line arguments or environment vars.");
1694
1695static PyTypeObject FlagsType;
1696
1697static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001698 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 {"inspect", "-i"},
1700 {"interactive", "-i"},
1701 {"optimize", "-O or -OO"},
1702 {"dont_write_bytecode", "-B"},
1703 {"no_user_site", "-s"},
1704 {"no_site", "-S"},
1705 {"ignore_environment", "-E"},
1706 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 /* {"unbuffered", "-u"}, */
1708 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001709 {"bytes_warning", "-b"},
1710 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001711 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001712 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001714};
1715
1716static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 "sys.flags", /* name */
1718 flags__doc__, /* doc */
1719 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001720 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001721};
1722
1723static PyObject*
1724make_flags(void)
1725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 int pos = 0;
1727 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 seq = PyStructSequence_New(&FlagsType);
1730 if (seq == NULL)
1731 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001732
1733#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 SetFlag(Py_InspectFlag);
1738 SetFlag(Py_InteractiveFlag);
1739 SetFlag(Py_OptimizeFlag);
1740 SetFlag(Py_DontWriteBytecodeFlag);
1741 SetFlag(Py_NoUserSiteDirectory);
1742 SetFlag(Py_NoSiteFlag);
1743 SetFlag(Py_IgnoreEnvironmentFlag);
1744 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 /* SetFlag(saw_unbuffered_flag); */
1746 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001747 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001748 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001749 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001750 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001751#undef SetFlag
1752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001754 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 return NULL;
1756 }
1757 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001758}
1759
Eric Smith0e5b5622009-02-06 01:32:42 +00001760PyDoc_STRVAR(version_info__doc__,
1761"sys.version_info\n\
1762\n\
1763Version information as a named tuple.");
1764
1765static PyTypeObject VersionInfoType;
1766
1767static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 {"major", "Major release number"},
1769 {"minor", "Minor release number"},
1770 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001771 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 {"serial", "Serial release number"},
1773 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001774};
1775
1776static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 "sys.version_info", /* name */
1778 version_info__doc__, /* doc */
1779 version_info_fields, /* fields */
1780 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001781};
1782
1783static PyObject *
1784make_version_info(void)
1785{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 PyObject *version_info;
1787 char *s;
1788 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 version_info = PyStructSequence_New(&VersionInfoType);
1791 if (version_info == NULL) {
1792 return NULL;
1793 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001794
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /*
1796 * These release level checks are mutually exclusive and cover
1797 * the field, so don't get too fancy with the pre-processor!
1798 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001799#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001801#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001803#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001805#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001807#endif
1808
1809#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001811#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 SetIntItem(PY_MAJOR_VERSION);
1815 SetIntItem(PY_MINOR_VERSION);
1816 SetIntItem(PY_MICRO_VERSION);
1817 SetStrItem(s);
1818 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001819#undef SetIntItem
1820#undef SetStrItem
1821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (PyErr_Occurred()) {
1823 Py_CLEAR(version_info);
1824 return NULL;
1825 }
1826 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001827}
1828
Brett Cannon3adc7b72012-07-09 14:22:12 -04001829/* sys.implementation values */
1830#define NAME "cpython"
1831const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001832#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1833#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001834#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001835const char *_PySys_ImplCacheTag = TAG;
1836#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001837#undef MAJOR
1838#undef MINOR
1839#undef TAG
1840
Barry Warsaw409da152012-06-03 16:18:47 -04001841static PyObject *
1842make_impl_info(PyObject *version_info)
1843{
1844 int res;
1845 PyObject *impl_info, *value, *ns;
1846
1847 impl_info = PyDict_New();
1848 if (impl_info == NULL)
1849 return NULL;
1850
1851 /* populate the dict */
1852
Brett Cannon3adc7b72012-07-09 14:22:12 -04001853 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001854 if (value == NULL)
1855 goto error;
1856 res = PyDict_SetItemString(impl_info, "name", value);
1857 Py_DECREF(value);
1858 if (res < 0)
1859 goto error;
1860
Brett Cannon3adc7b72012-07-09 14:22:12 -04001861 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001862 if (value == NULL)
1863 goto error;
1864 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1865 Py_DECREF(value);
1866 if (res < 0)
1867 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001868
1869 res = PyDict_SetItemString(impl_info, "version", version_info);
1870 if (res < 0)
1871 goto error;
1872
1873 value = PyLong_FromLong(PY_VERSION_HEX);
1874 if (value == NULL)
1875 goto error;
1876 res = PyDict_SetItemString(impl_info, "hexversion", value);
1877 Py_DECREF(value);
1878 if (res < 0)
1879 goto error;
1880
doko@ubuntu.com55532312016-06-14 08:55:19 +02001881#ifdef MULTIARCH
1882 value = PyUnicode_FromString(MULTIARCH);
1883 if (value == NULL)
1884 goto error;
1885 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1886 Py_DECREF(value);
1887 if (res < 0)
1888 goto error;
1889#endif
1890
Barry Warsaw409da152012-06-03 16:18:47 -04001891 /* dict ready */
1892
1893 ns = _PyNamespace_New(impl_info);
1894 Py_DECREF(impl_info);
1895 return ns;
1896
1897error:
1898 Py_CLEAR(impl_info);
1899 return NULL;
1900}
1901
Martin v. Löwis1a214512008-06-11 05:26:20 +00001902static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyModuleDef_HEAD_INIT,
1904 "sys",
1905 sys_doc,
1906 -1, /* multiple "initialization" just copies the module dict. */
1907 sys_methods,
1908 NULL,
1909 NULL,
1910 NULL,
1911 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001912};
1913
Eric Snow6b4be192017-05-22 21:36:03 -07001914/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001915#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001916 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001917 PyObject *v = (value); \
1918 if (v == NULL) \
1919 return NULL; \
1920 res = PyDict_SetItemString(sysdict, key, v); \
1921 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001922 return NULL; \
1923 } \
1924 } while (0)
1925#define SET_SYS_FROM_STRING(key, value) \
1926 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001927 PyObject *v = (value); \
1928 if (v == NULL) \
1929 return NULL; \
1930 res = PyDict_SetItemString(sysdict, key, v); \
1931 Py_DECREF(v); \
1932 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001933 return NULL; \
1934 } \
1935 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001936
Eric Snow6b4be192017-05-22 21:36:03 -07001937PyObject *
1938_PySys_BeginInit(void)
1939{
1940 PyObject *m, *sysdict, *version_info;
1941 int res;
1942
Eric Snow86b7afd2017-09-04 17:54:09 -06001943 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Eric Snow6b4be192017-05-22 21:36:03 -07001944 if (m == NULL)
1945 return NULL;
1946 sysdict = PyModule_GetDict(m);
1947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 /* Check that stdin is not a directory
1949 Using shell redirection, you can redirect stdin to a directory,
1950 crashing the Python interpreter. Catch this common mistake here
1951 and output a useful error message. Note that under MS Windows,
1952 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001953#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001955 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001956 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 S_ISDIR(sb.st_mode)) {
1958 /* There's nothing more we can do. */
1959 /* Py_FatalError() will core dump, so just exit. */
1960 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1961 exit(EXIT_FAILURE);
1962 }
1963 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001964#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001965
Nick Coghland6009512014-11-20 21:39:37 +10001966 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001967
Victor Stinner8fea2522013-10-27 17:15:42 +01001968 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1969 PyDict_GetItemString(sysdict, "displayhook"));
1970 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1971 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 SET_SYS_FROM_STRING("version",
1973 PyUnicode_FromString(Py_GetVersion()));
1974 SET_SYS_FROM_STRING("hexversion",
1975 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001976 SET_SYS_FROM_STRING("_git",
1977 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1978 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001979 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 SET_SYS_FROM_STRING("api_version",
1981 PyLong_FromLong(PYTHON_API_VERSION));
1982 SET_SYS_FROM_STRING("copyright",
1983 PyUnicode_FromString(Py_GetCopyright()));
1984 SET_SYS_FROM_STRING("platform",
1985 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 SET_SYS_FROM_STRING("maxsize",
1987 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1988 SET_SYS_FROM_STRING("float_info",
1989 PyFloat_GetInfo());
1990 SET_SYS_FROM_STRING("int_info",
1991 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001992 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001993 if (Hash_InfoType.tp_name == NULL) {
1994 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1995 return NULL;
1996 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001997 SET_SYS_FROM_STRING("hash_info",
1998 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002000 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 SET_SYS_FROM_STRING("builtin_module_names",
2002 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002003#if PY_BIG_ENDIAN
2004 SET_SYS_FROM_STRING("byteorder",
2005 PyUnicode_FromString("big"));
2006#else
2007 SET_SYS_FROM_STRING("byteorder",
2008 PyUnicode_FromString("little"));
2009#endif
Fred Drake099325e2000-08-14 15:47:03 +00002010
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002011#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 SET_SYS_FROM_STRING("dllhandle",
2013 PyLong_FromVoidPtr(PyWin_DLLhModule));
2014 SET_SYS_FROM_STRING("winver",
2015 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002016#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002017#ifdef ABIFLAGS
2018 SET_SYS_FROM_STRING("abiflags",
2019 PyUnicode_FromString(ABIFLAGS));
2020#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002023 if (VersionInfoType.tp_name == NULL) {
2024 if (PyStructSequence_InitType2(&VersionInfoType,
2025 &version_info_desc) < 0)
2026 return NULL;
2027 }
Barry Warsaw409da152012-06-03 16:18:47 -04002028 version_info = make_version_info();
2029 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 /* prevent user from creating new instances */
2031 VersionInfoType.tp_init = NULL;
2032 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002033 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2034 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2035 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002036
Barry Warsaw409da152012-06-03 16:18:47 -04002037 /* implementation */
2038 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002041 if (FlagsType.tp_name == 0) {
2042 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2043 return NULL;
2044 }
Eric Snow6b4be192017-05-22 21:36:03 -07002045 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002047
2048#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* getwindowsversion */
2050 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002051 if (PyStructSequence_InitType2(&WindowsVersionType,
2052 &windows_version_desc) < 0)
2053 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 /* prevent user from creating new instances */
2055 WindowsVersionType.tp_init = NULL;
2056 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002057 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2058 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2059 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002060#endif
2061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002063#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 SET_SYS_FROM_STRING("float_repr_style",
2065 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002066#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 SET_SYS_FROM_STRING("float_repr_style",
2068 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002069#endif
2070
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002071#ifdef WITH_THREAD
2072 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
2073#endif
2074
Yury Selivanoveb636452016-09-08 22:01:51 -07002075 /* initialize asyncgen_hooks */
2076 if (AsyncGenHooksType.tp_name == NULL) {
2077 if (PyStructSequence_InitType2(
2078 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2079 return NULL;
2080 }
2081 }
2082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 if (PyErr_Occurred())
2084 return NULL;
2085 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002086}
2087
Eric Snow6b4be192017-05-22 21:36:03 -07002088#undef SET_SYS_FROM_STRING
2089#undef SET_SYS_FROM_STRING_BORROW
2090
2091/* Updating the sys namespace, returning integer error codes */
2092#define SET_SYS_FROM_STRING_BORROW_INT_RESULT(key, value) \
2093 do { \
2094 PyObject *v = (value); \
2095 if (v == NULL) \
2096 return -1; \
2097 res = PyDict_SetItemString(sysdict, key, v); \
2098 if (res < 0) { \
2099 return res; \
2100 } \
2101 } while (0)
2102#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2103 do { \
2104 PyObject *v = (value); \
2105 if (v == NULL) \
2106 return -1; \
2107 res = PyDict_SetItemString(sysdict, key, v); \
2108 Py_DECREF(v); \
2109 if (res < 0) { \
2110 return res; \
2111 } \
2112 } while (0)
2113
2114int
2115_PySys_EndInit(PyObject *sysdict)
2116{
2117 int res;
2118
2119 /* Set flags to their final values */
2120 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2121 /* prevent user from creating new instances */
2122 FlagsType.tp_init = NULL;
2123 FlagsType.tp_new = NULL;
2124 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2125 if (res < 0) {
2126 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2127 return res;
2128 }
2129 PyErr_Clear();
2130 }
2131
2132 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2133 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2134 SET_SYS_FROM_STRING_INT_RESULT("executable",
2135 PyUnicode_FromWideChar(
2136 Py_GetProgramFullPath(), -1));
2137 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2138 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2139 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2140 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2141 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2142 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2143 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2144 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2145
Eric Snow76d5abc2017-09-05 18:26:16 -07002146 PyObject *warnoptions = get_warnoptions();
2147 if (warnoptions == NULL)
2148 return -1;
2149 SET_SYS_FROM_STRING_BORROW_INT_RESULT("warnoptions", warnoptions);
Victor Stinner865de272017-06-08 13:27:47 +02002150
Eric Snow76d5abc2017-09-05 18:26:16 -07002151 PyObject *xoptions = get_xoptions();
2152 if (xoptions == NULL)
2153 return -1;
2154 SET_SYS_FROM_STRING_BORROW_INT_RESULT("_xoptions", xoptions);
Eric Snow6b4be192017-05-22 21:36:03 -07002155
2156 if (PyErr_Occurred())
2157 return -1;
2158 return 0;
2159}
2160
2161#undef SET_SYS_FROM_STRING_INT_RESULT
2162#undef SET_SYS_FROM_STRING_BORROW_INT_RESULT
2163
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002164static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002165makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 int i, n;
2168 const wchar_t *p;
2169 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 n = 1;
2172 p = path;
2173 while ((p = wcschr(p, delim)) != NULL) {
2174 n++;
2175 p++;
2176 }
2177 v = PyList_New(n);
2178 if (v == NULL)
2179 return NULL;
2180 for (i = 0; ; i++) {
2181 p = wcschr(path, delim);
2182 if (p == NULL)
2183 p = path + wcslen(path); /* End of string */
2184 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2185 if (w == NULL) {
2186 Py_DECREF(v);
2187 return NULL;
2188 }
2189 PyList_SetItem(v, i, w);
2190 if (*p == '\0')
2191 break;
2192 path = p+1;
2193 }
2194 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002195}
2196
2197void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002198PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyObject *v;
2201 if ((v = makepathobject(path, DELIM)) == NULL)
2202 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002203 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 Py_FatalError("can't assign sys.path");
2205 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002206}
2207
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002208static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002209makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyObject *av;
2212 if (argc <= 0 || argv == NULL) {
2213 /* Ensure at least one (empty) argument is seen */
2214 static wchar_t *empty_argv[1] = {L""};
2215 argv = empty_argv;
2216 argc = 1;
2217 }
2218 av = PyList_New(argc);
2219 if (av != NULL) {
2220 int i;
2221 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 if (v == NULL) {
2224 Py_DECREF(av);
2225 av = NULL;
2226 break;
2227 }
2228 PyList_SetItem(av, i, v);
2229 }
2230 }
2231 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002232}
2233
Nick Coghland26c18a2010-08-17 13:06:11 +00002234#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2235 (argc > 0 && argv0 != NULL && \
2236 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002237
2238static void
2239sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002240{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002241 wchar_t *argv0;
2242 wchar_t *p = NULL;
2243 Py_ssize_t n = 0;
2244 PyObject *a;
2245 PyObject *path;
2246#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002247 wchar_t link[MAXPATHLEN+1];
2248 wchar_t argv0copy[2*MAXPATHLEN+1];
2249 int nr = 0;
2250#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002251#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002253#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002255#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002256
Victor Stinnerbd303c12013-11-07 23:07:29 +01002257 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002258 if (path == NULL)
2259 return;
2260
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002261 argv0 = argv[0];
2262
2263#ifdef HAVE_READLINK
2264 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2265 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2266 if (nr > 0) {
2267 /* It's a symlink */
2268 link[nr] = '\0';
2269 if (link[0] == SEP)
2270 argv0 = link; /* Link to absolute path */
2271 else if (wcschr(link, SEP) == NULL)
2272 ; /* Link without path */
2273 else {
2274 /* Must join(dirname(argv0), link) */
2275 wchar_t *q = wcsrchr(argv0, SEP);
2276 if (q == NULL)
2277 argv0 = link; /* argv0 without path */
2278 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002279 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2280 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002281 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002282 wcsncpy(q+1, link, MAXPATHLEN);
2283 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002284 argv0 = argv0copy;
2285 }
2286 }
2287 }
2288#endif /* HAVE_READLINK */
2289#if SEP == '\\' /* Special case for MS filename syntax */
2290 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2291 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002292#if defined(MS_WINDOWS)
2293 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002294 wchar_t *ptemp;
2295 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002296 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002297 fullpath,
2298 &ptemp)) {
2299 argv0 = fullpath;
2300 }
2301#endif
2302 p = wcsrchr(argv0, SEP);
2303 /* Test for alternate separator */
2304 q = wcsrchr(p ? p : argv0, '/');
2305 if (q != NULL)
2306 p = q;
2307 if (p != NULL) {
2308 n = p + 1 - argv0;
2309 if (n > 1 && p[-1] != ':')
2310 n--; /* Drop trailing separator */
2311 }
2312 }
2313#else /* All other filename syntaxes */
2314 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2315#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002316 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002317 argv0 = fullpath;
2318 }
2319#endif
2320 p = wcsrchr(argv0, SEP);
2321 }
2322 if (p != NULL) {
2323 n = p + 1 - argv0;
2324#if SEP == '/' /* Special case for Unix filename syntax */
2325 if (n > 1)
2326 n--; /* Drop trailing separator */
2327#endif /* Unix */
2328 }
2329#endif /* All others */
2330 a = PyUnicode_FromWideChar(argv0, n);
2331 if (a == NULL)
2332 Py_FatalError("no mem for sys.path insertion");
2333 if (PyList_Insert(path, 0, a) < 0)
2334 Py_FatalError("sys.path.insert(0) failed");
2335 Py_DECREF(a);
2336}
2337
2338void
2339PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 if (av == NULL)
2343 Py_FatalError("no mem for sys.argv");
2344 if (PySys_SetObject("argv", av) != 0)
2345 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002347 if (updatepath)
2348 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002349}
Guido van Rossuma890e681998-05-12 14:59:24 +00002350
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002351void
2352PySys_SetArgv(int argc, wchar_t **argv)
2353{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002354 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002355}
2356
Victor Stinner14284c22010-04-23 12:02:30 +00002357/* Reimplementation of PyFile_WriteString() no calling indirectly
2358 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2359
2360static int
Victor Stinner79766632010-08-16 17:36:42 +00002361sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002362{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002363 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002365
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002366 if (file == NULL)
2367 return -1;
2368
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002369 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 if (writer == NULL)
2371 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002372
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002373 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 if (result == NULL) {
2375 goto error;
2376 } else {
2377 err = 0;
2378 goto finally;
2379 }
Victor Stinner14284c22010-04-23 12:02:30 +00002380
2381error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002383finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 Py_XDECREF(result);
2386 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002387}
2388
Victor Stinner79766632010-08-16 17:36:42 +00002389static int
2390sys_pyfile_write(const char *text, PyObject *file)
2391{
2392 PyObject *unicode = NULL;
2393 int err;
2394
2395 if (file == NULL)
2396 return -1;
2397
2398 unicode = PyUnicode_FromString(text);
2399 if (unicode == NULL)
2400 return -1;
2401
2402 err = sys_pyfile_write_unicode(unicode, file);
2403 Py_DECREF(unicode);
2404 return err;
2405}
Guido van Rossuma890e681998-05-12 14:59:24 +00002406
2407/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2408 Adapted from code submitted by Just van Rossum.
2409
2410 PySys_WriteStdout(format, ...)
2411 PySys_WriteStderr(format, ...)
2412
2413 The first function writes to sys.stdout; the second to sys.stderr. When
2414 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002415 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002416
Victor Stinner14284c22010-04-23 12:02:30 +00002417 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002418 signal handlers: they may raise a new exception whereas sys_write()
2419 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002420
Guido van Rossuma890e681998-05-12 14:59:24 +00002421 Both take a printf-style format string as their first argument followed
2422 by a variable length argument list determined by the format string.
2423
2424 *** WARNING ***
2425
2426 The format should limit the total size of the formatted output string to
2427 1000 bytes. In particular, this means that no unrestricted "%s" formats
2428 should occur; these should be limited using "%.<N>s where <N> is a
2429 decimal number calculated so that <N> plus the maximum size of other
2430 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2431 which can print hundreds of digits for very large numbers.
2432
2433 */
2434
2435static void
Victor Stinner09054372013-11-06 22:41:44 +01002436sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 PyObject *file;
2439 PyObject *error_type, *error_value, *error_traceback;
2440 char buffer[1001];
2441 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002444 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2446 if (sys_pyfile_write(buffer, file) != 0) {
2447 PyErr_Clear();
2448 fputs(buffer, fp);
2449 }
2450 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2451 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002452 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 }
2455 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002456}
2457
2458void
Guido van Rossuma890e681998-05-12 14:59:24 +00002459PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002464 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002465 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002466}
2467
2468void
Guido van Rossuma890e681998-05-12 14:59:24 +00002469PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002474 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002475 va_end(va);
2476}
2477
2478static void
Victor Stinner09054372013-11-06 22:41:44 +01002479sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002480{
2481 PyObject *file, *message;
2482 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002483 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002484
2485 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002486 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002487 message = PyUnicode_FromFormatV(format, va);
2488 if (message != NULL) {
2489 if (sys_pyfile_write_unicode(message, file) != 0) {
2490 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002491 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002492 if (utf8 != NULL)
2493 fputs(utf8, fp);
2494 }
2495 Py_DECREF(message);
2496 }
2497 PyErr_Restore(error_type, error_value, error_traceback);
2498}
2499
2500void
2501PySys_FormatStdout(const char *format, ...)
2502{
2503 va_list va;
2504
2505 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002506 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002507 va_end(va);
2508}
2509
2510void
2511PySys_FormatStderr(const char *format, ...)
2512{
2513 va_list va;
2514
2515 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002516 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002517 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002518}