blob: 852babbed78964a3309e45ab5c6051348d340d20 [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
Eric Snow05351c12017-09-05 21:43:08 -0700522static int _check_interval = 100;
523
Christian Heimes9bd667a2008-01-20 15:14:11 +0000524static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000525sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (PyErr_WarnEx(PyExc_DeprecationWarning,
528 "sys.getcheckinterval() and sys.setcheckinterval() "
529 "are deprecated. Use sys.setswitchinterval() "
530 "instead.", 1) < 0)
531 return NULL;
Eric Snow05351c12017-09-05 21:43:08 -0700532 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200534 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000535}
536
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000537PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000538"setcheckinterval(n)\n\
539\n\
540Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000541n instructions. This also affects how often thread switches occur."
542);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000543
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000544static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000545sys_getcheckinterval(PyObject *self, PyObject *args)
546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 if (PyErr_WarnEx(PyExc_DeprecationWarning,
548 "sys.getcheckinterval() and sys.setcheckinterval() "
549 "are deprecated. Use sys.getswitchinterval() "
550 "instead.", 1) < 0)
551 return NULL;
Eric Snow05351c12017-09-05 21:43:08 -0700552 return PyLong_FromLong(_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 Snow05351c12017-09-05 21:43:08 -07001342 return PyBool_FromLong(_Py_Finalizing != NULL);
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 Snow05351c12017-09-05 21:43:08 -07001482static PyObject *warnoptions = NULL;
Guido van Rossum23fff912000-12-15 22:02:05 +00001483
1484void
1485PySys_ResetWarnOptions(void)
1486{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001487 if (warnoptions == NULL || !PyList_Check(warnoptions))
1488 return;
1489 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001490}
1491
1492void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001493PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001494{
Eric Snow05351c12017-09-05 21:43:08 -07001495 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1496 Py_XDECREF(warnoptions);
1497 warnoptions = PyList_New(0);
1498 if (warnoptions == NULL)
1499 return;
1500 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001501 PyList_Append(warnoptions, unicode);
1502}
1503
1504void
1505PySys_AddWarnOption(const wchar_t *s)
1506{
1507 PyObject *unicode;
1508 unicode = PyUnicode_FromWideChar(s, -1);
1509 if (unicode == NULL)
1510 return;
1511 PySys_AddWarnOptionUnicode(unicode);
1512 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001513}
1514
Christian Heimes33fe8092008-04-13 13:53:33 +00001515int
1516PySys_HasWarnOptions(void)
1517{
1518 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1519}
1520
Eric Snow05351c12017-09-05 21:43:08 -07001521static PyObject *xoptions = NULL;
1522
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001523static PyObject *
1524get_xoptions(void)
1525{
1526 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1527 Py_XDECREF(xoptions);
1528 xoptions = PyDict_New();
1529 }
1530 return xoptions;
1531}
1532
1533void
1534PySys_AddXOption(const wchar_t *s)
1535{
1536 PyObject *opts;
1537 PyObject *name = NULL, *value = NULL;
1538 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001539
1540 opts = get_xoptions();
1541 if (opts == NULL)
1542 goto error;
1543
1544 name_end = wcschr(s, L'=');
1545 if (!name_end) {
1546 name = PyUnicode_FromWideChar(s, -1);
1547 value = Py_True;
1548 Py_INCREF(value);
1549 }
1550 else {
1551 name = PyUnicode_FromWideChar(s, name_end - s);
1552 value = PyUnicode_FromWideChar(name_end + 1, -1);
1553 }
1554 if (name == NULL || value == NULL)
1555 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001556 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001557 Py_DECREF(name);
1558 Py_DECREF(value);
1559 return;
1560
1561error:
1562 Py_XDECREF(name);
1563 Py_XDECREF(value);
1564 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001565 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001566 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001567 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001568}
1569
1570PyObject *
1571PySys_GetXOptions(void)
1572{
1573 return get_xoptions();
1574}
1575
Guido van Rossum40552d01998-08-06 03:34:39 +00001576/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1577 Two literals concatenated works just fine. If you have a K&R compiler
1578 or other abomination that however *does* understand longer strings,
1579 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001580PyDoc_VAR(sys_doc) =
1581PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001582"This module provides access to some objects used or maintained by the\n\
1583interpreter and to functions that interact strongly with the interpreter.\n\
1584\n\
1585Dynamic objects:\n\
1586\n\
1587argv -- command line arguments; argv[0] is the script pathname if known\n\
1588path -- module search path; path[0] is the script directory, else ''\n\
1589modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001590\n\
1591displayhook -- called to show results in an interactive session\n\
1592excepthook -- called to handle any uncaught exception other than SystemExit\n\
1593 To customize printing in an interactive session or to install a custom\n\
1594 top-level exception handler, assign other functions to replace these.\n\
1595\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001596stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001597stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001598stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001599 By assigning other file objects (or objects that behave like files)\n\
1600 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001601\n\
1602last_type -- type of last uncaught exception\n\
1603last_value -- value of last uncaught exception\n\
1604last_traceback -- traceback of last uncaught exception\n\
1605 These three are only available in an interactive session after a\n\
1606 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001607"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001608)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001609/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001610PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001611"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001612Static objects:\n\
1613\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001614builtin_module_names -- tuple of module names built into this interpreter\n\
1615copyright -- copyright notice pertaining to this interpreter\n\
1616exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001617executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001618float_info -- a struct sequence with information about the float implementation.\n\
1619float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001620hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001621hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001622implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001623int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001624maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001625maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001626platform -- platform identifier\n\
1627prefix -- prefix used to find the Python library\n\
1628thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001629version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001630version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001631"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001632)
Steve Dowercc16be82016-09-08 10:35:16 -07001633#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001634/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001635PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001636"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001637winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001638"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001639)
Steve Dowercc16be82016-09-08 10:35:16 -07001640#endif /* MS_COREDLL */
1641#ifdef MS_WINDOWS
1642/* concatenating string here */
1643PyDoc_STR(
1644"_enablelegacywindowsfsencoding -- [Windows only] \n\
1645"
1646)
1647#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001648PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001649"__stdin__ -- the original stdin; don't touch!\n\
1650__stdout__ -- the original stdout; don't touch!\n\
1651__stderr__ -- the original stderr; don't touch!\n\
1652__displayhook__ -- the original displayhook; don't touch!\n\
1653__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001654\n\
1655Functions:\n\
1656\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001657displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001658excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001659exc_info() -- return thread-safe information about the current exception\n\
1660exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001661getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001662getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001663getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001664getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001665getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001666gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001667setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001668setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001669setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001670setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001671settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001672"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001673)
Fred Drakeccede592000-08-14 20:59:57 +00001674/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001675
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001676
1677PyDoc_STRVAR(flags__doc__,
1678"sys.flags\n\
1679\n\
1680Flags provided through command line arguments or environment vars.");
1681
1682static PyTypeObject FlagsType;
1683
1684static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 {"inspect", "-i"},
1687 {"interactive", "-i"},
1688 {"optimize", "-O or -OO"},
1689 {"dont_write_bytecode", "-B"},
1690 {"no_user_site", "-s"},
1691 {"no_site", "-S"},
1692 {"ignore_environment", "-E"},
1693 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* {"unbuffered", "-u"}, */
1695 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001696 {"bytes_warning", "-b"},
1697 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001698 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001699 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001701};
1702
1703static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 "sys.flags", /* name */
1705 flags__doc__, /* doc */
1706 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001707 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001708};
1709
1710static PyObject*
1711make_flags(void)
1712{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001713 int pos = 0;
1714 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 seq = PyStructSequence_New(&FlagsType);
1717 if (seq == NULL)
1718 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001719
1720#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001722
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001723 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 SetFlag(Py_InspectFlag);
1725 SetFlag(Py_InteractiveFlag);
1726 SetFlag(Py_OptimizeFlag);
1727 SetFlag(Py_DontWriteBytecodeFlag);
1728 SetFlag(Py_NoUserSiteDirectory);
1729 SetFlag(Py_NoSiteFlag);
1730 SetFlag(Py_IgnoreEnvironmentFlag);
1731 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 /* SetFlag(saw_unbuffered_flag); */
1733 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001734 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001735 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001736 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001737 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001738#undef SetFlag
1739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001741 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001742 return NULL;
1743 }
1744 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001745}
1746
Eric Smith0e5b5622009-02-06 01:32:42 +00001747PyDoc_STRVAR(version_info__doc__,
1748"sys.version_info\n\
1749\n\
1750Version information as a named tuple.");
1751
1752static PyTypeObject VersionInfoType;
1753
1754static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 {"major", "Major release number"},
1756 {"minor", "Minor release number"},
1757 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001758 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 {"serial", "Serial release number"},
1760 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001761};
1762
1763static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 "sys.version_info", /* name */
1765 version_info__doc__, /* doc */
1766 version_info_fields, /* fields */
1767 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001768};
1769
1770static PyObject *
1771make_version_info(void)
1772{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 PyObject *version_info;
1774 char *s;
1775 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 version_info = PyStructSequence_New(&VersionInfoType);
1778 if (version_info == NULL) {
1779 return NULL;
1780 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /*
1783 * These release level checks are mutually exclusive and cover
1784 * the field, so don't get too fancy with the pre-processor!
1785 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001786#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001788#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001790#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001792#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001794#endif
1795
1796#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001798#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001800
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 SetIntItem(PY_MAJOR_VERSION);
1802 SetIntItem(PY_MINOR_VERSION);
1803 SetIntItem(PY_MICRO_VERSION);
1804 SetStrItem(s);
1805 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001806#undef SetIntItem
1807#undef SetStrItem
1808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 if (PyErr_Occurred()) {
1810 Py_CLEAR(version_info);
1811 return NULL;
1812 }
1813 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001814}
1815
Brett Cannon3adc7b72012-07-09 14:22:12 -04001816/* sys.implementation values */
1817#define NAME "cpython"
1818const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001819#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1820#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001821#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001822const char *_PySys_ImplCacheTag = TAG;
1823#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001824#undef MAJOR
1825#undef MINOR
1826#undef TAG
1827
Barry Warsaw409da152012-06-03 16:18:47 -04001828static PyObject *
1829make_impl_info(PyObject *version_info)
1830{
1831 int res;
1832 PyObject *impl_info, *value, *ns;
1833
1834 impl_info = PyDict_New();
1835 if (impl_info == NULL)
1836 return NULL;
1837
1838 /* populate the dict */
1839
Brett Cannon3adc7b72012-07-09 14:22:12 -04001840 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001841 if (value == NULL)
1842 goto error;
1843 res = PyDict_SetItemString(impl_info, "name", value);
1844 Py_DECREF(value);
1845 if (res < 0)
1846 goto error;
1847
Brett Cannon3adc7b72012-07-09 14:22:12 -04001848 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001849 if (value == NULL)
1850 goto error;
1851 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1852 Py_DECREF(value);
1853 if (res < 0)
1854 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001855
1856 res = PyDict_SetItemString(impl_info, "version", version_info);
1857 if (res < 0)
1858 goto error;
1859
1860 value = PyLong_FromLong(PY_VERSION_HEX);
1861 if (value == NULL)
1862 goto error;
1863 res = PyDict_SetItemString(impl_info, "hexversion", value);
1864 Py_DECREF(value);
1865 if (res < 0)
1866 goto error;
1867
doko@ubuntu.com55532312016-06-14 08:55:19 +02001868#ifdef MULTIARCH
1869 value = PyUnicode_FromString(MULTIARCH);
1870 if (value == NULL)
1871 goto error;
1872 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1873 Py_DECREF(value);
1874 if (res < 0)
1875 goto error;
1876#endif
1877
Barry Warsaw409da152012-06-03 16:18:47 -04001878 /* dict ready */
1879
1880 ns = _PyNamespace_New(impl_info);
1881 Py_DECREF(impl_info);
1882 return ns;
1883
1884error:
1885 Py_CLEAR(impl_info);
1886 return NULL;
1887}
1888
Martin v. Löwis1a214512008-06-11 05:26:20 +00001889static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 PyModuleDef_HEAD_INIT,
1891 "sys",
1892 sys_doc,
1893 -1, /* multiple "initialization" just copies the module dict. */
1894 sys_methods,
1895 NULL,
1896 NULL,
1897 NULL,
1898 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001899};
1900
Eric Snow6b4be192017-05-22 21:36:03 -07001901/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001902#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001903 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001904 PyObject *v = (value); \
1905 if (v == NULL) \
1906 return NULL; \
1907 res = PyDict_SetItemString(sysdict, key, v); \
1908 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001909 return NULL; \
1910 } \
1911 } while (0)
1912#define SET_SYS_FROM_STRING(key, value) \
1913 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001914 PyObject *v = (value); \
1915 if (v == NULL) \
1916 return NULL; \
1917 res = PyDict_SetItemString(sysdict, key, v); \
1918 Py_DECREF(v); \
1919 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001920 return NULL; \
1921 } \
1922 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001923
Eric Snow6b4be192017-05-22 21:36:03 -07001924PyObject *
1925_PySys_BeginInit(void)
1926{
1927 PyObject *m, *sysdict, *version_info;
1928 int res;
1929
Eric Snow86b7afd2017-09-04 17:54:09 -06001930 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Eric Snow6b4be192017-05-22 21:36:03 -07001931 if (m == NULL)
1932 return NULL;
1933 sysdict = PyModule_GetDict(m);
1934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 /* Check that stdin is not a directory
1936 Using shell redirection, you can redirect stdin to a directory,
1937 crashing the Python interpreter. Catch this common mistake here
1938 and output a useful error message. Note that under MS Windows,
1939 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001940#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001942 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001943 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 S_ISDIR(sb.st_mode)) {
1945 /* There's nothing more we can do. */
1946 /* Py_FatalError() will core dump, so just exit. */
1947 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1948 exit(EXIT_FAILURE);
1949 }
1950 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001951#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001952
Nick Coghland6009512014-11-20 21:39:37 +10001953 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001954
Victor Stinner8fea2522013-10-27 17:15:42 +01001955 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1956 PyDict_GetItemString(sysdict, "displayhook"));
1957 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1958 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001959 SET_SYS_FROM_STRING("version",
1960 PyUnicode_FromString(Py_GetVersion()));
1961 SET_SYS_FROM_STRING("hexversion",
1962 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001963 SET_SYS_FROM_STRING("_git",
1964 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1965 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001966 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 SET_SYS_FROM_STRING("api_version",
1968 PyLong_FromLong(PYTHON_API_VERSION));
1969 SET_SYS_FROM_STRING("copyright",
1970 PyUnicode_FromString(Py_GetCopyright()));
1971 SET_SYS_FROM_STRING("platform",
1972 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 SET_SYS_FROM_STRING("maxsize",
1974 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1975 SET_SYS_FROM_STRING("float_info",
1976 PyFloat_GetInfo());
1977 SET_SYS_FROM_STRING("int_info",
1978 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001979 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001980 if (Hash_InfoType.tp_name == NULL) {
1981 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1982 return NULL;
1983 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001984 SET_SYS_FROM_STRING("hash_info",
1985 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001987 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 SET_SYS_FROM_STRING("builtin_module_names",
1989 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001990#if PY_BIG_ENDIAN
1991 SET_SYS_FROM_STRING("byteorder",
1992 PyUnicode_FromString("big"));
1993#else
1994 SET_SYS_FROM_STRING("byteorder",
1995 PyUnicode_FromString("little"));
1996#endif
Fred Drake099325e2000-08-14 15:47:03 +00001997
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001998#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 SET_SYS_FROM_STRING("dllhandle",
2000 PyLong_FromVoidPtr(PyWin_DLLhModule));
2001 SET_SYS_FROM_STRING("winver",
2002 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002003#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002004#ifdef ABIFLAGS
2005 SET_SYS_FROM_STRING("abiflags",
2006 PyUnicode_FromString(ABIFLAGS));
2007#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002009 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002010 if (VersionInfoType.tp_name == NULL) {
2011 if (PyStructSequence_InitType2(&VersionInfoType,
2012 &version_info_desc) < 0)
2013 return NULL;
2014 }
Barry Warsaw409da152012-06-03 16:18:47 -04002015 version_info = make_version_info();
2016 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 /* prevent user from creating new instances */
2018 VersionInfoType.tp_init = NULL;
2019 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002020 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2021 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2022 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002023
Barry Warsaw409da152012-06-03 16:18:47 -04002024 /* implementation */
2025 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2026
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002028 if (FlagsType.tp_name == 0) {
2029 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2030 return NULL;
2031 }
Eric Snow6b4be192017-05-22 21:36:03 -07002032 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002034
2035#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* getwindowsversion */
2037 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002038 if (PyStructSequence_InitType2(&WindowsVersionType,
2039 &windows_version_desc) < 0)
2040 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 /* prevent user from creating new instances */
2042 WindowsVersionType.tp_init = NULL;
2043 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002044 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2045 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2046 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002047#endif
2048
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002050#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 SET_SYS_FROM_STRING("float_repr_style",
2052 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002053#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 SET_SYS_FROM_STRING("float_repr_style",
2055 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002056#endif
2057
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002058#ifdef WITH_THREAD
2059 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
2060#endif
2061
Yury Selivanoveb636452016-09-08 22:01:51 -07002062 /* initialize asyncgen_hooks */
2063 if (AsyncGenHooksType.tp_name == NULL) {
2064 if (PyStructSequence_InitType2(
2065 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2066 return NULL;
2067 }
2068 }
2069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 if (PyErr_Occurred())
2071 return NULL;
2072 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002073}
2074
Eric Snow6b4be192017-05-22 21:36:03 -07002075#undef SET_SYS_FROM_STRING
2076#undef SET_SYS_FROM_STRING_BORROW
2077
2078/* Updating the sys namespace, returning integer error codes */
2079#define SET_SYS_FROM_STRING_BORROW_INT_RESULT(key, value) \
2080 do { \
2081 PyObject *v = (value); \
2082 if (v == NULL) \
2083 return -1; \
2084 res = PyDict_SetItemString(sysdict, key, v); \
2085 if (res < 0) { \
2086 return res; \
2087 } \
2088 } while (0)
2089#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2090 do { \
2091 PyObject *v = (value); \
2092 if (v == NULL) \
2093 return -1; \
2094 res = PyDict_SetItemString(sysdict, key, v); \
2095 Py_DECREF(v); \
2096 if (res < 0) { \
2097 return res; \
2098 } \
2099 } while (0)
2100
2101int
2102_PySys_EndInit(PyObject *sysdict)
2103{
2104 int res;
2105
2106 /* Set flags to their final values */
2107 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2108 /* prevent user from creating new instances */
2109 FlagsType.tp_init = NULL;
2110 FlagsType.tp_new = NULL;
2111 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2112 if (res < 0) {
2113 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2114 return res;
2115 }
2116 PyErr_Clear();
2117 }
2118
2119 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2120 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2121 SET_SYS_FROM_STRING_INT_RESULT("executable",
2122 PyUnicode_FromWideChar(
2123 Py_GetProgramFullPath(), -1));
2124 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2125 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2126 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2127 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2128 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2129 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2130 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2131 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2132
Eric Snow05351c12017-09-05 21:43:08 -07002133 if (warnoptions == NULL) {
2134 warnoptions = PyList_New(0);
2135 if (warnoptions == NULL)
2136 return -1;
2137 }
Victor Stinner865de272017-06-08 13:27:47 +02002138
Eric Snow05351c12017-09-05 21:43:08 -07002139 SET_SYS_FROM_STRING_INT_RESULT("warnoptions",
2140 PyList_GetSlice(warnoptions,
2141 0, Py_SIZE(warnoptions)));
2142
2143 SET_SYS_FROM_STRING_BORROW_INT_RESULT("_xoptions", get_xoptions());
Eric Snow6b4be192017-05-22 21:36:03 -07002144
2145 if (PyErr_Occurred())
2146 return -1;
2147 return 0;
2148}
2149
2150#undef SET_SYS_FROM_STRING_INT_RESULT
2151#undef SET_SYS_FROM_STRING_BORROW_INT_RESULT
2152
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002153static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002154makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 int i, n;
2157 const wchar_t *p;
2158 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002159
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 n = 1;
2161 p = path;
2162 while ((p = wcschr(p, delim)) != NULL) {
2163 n++;
2164 p++;
2165 }
2166 v = PyList_New(n);
2167 if (v == NULL)
2168 return NULL;
2169 for (i = 0; ; i++) {
2170 p = wcschr(path, delim);
2171 if (p == NULL)
2172 p = path + wcslen(path); /* End of string */
2173 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2174 if (w == NULL) {
2175 Py_DECREF(v);
2176 return NULL;
2177 }
2178 PyList_SetItem(v, i, w);
2179 if (*p == '\0')
2180 break;
2181 path = p+1;
2182 }
2183 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002184}
2185
2186void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002187PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002188{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 PyObject *v;
2190 if ((v = makepathobject(path, DELIM)) == NULL)
2191 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002192 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 Py_FatalError("can't assign sys.path");
2194 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002195}
2196
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002197static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002198makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 PyObject *av;
2201 if (argc <= 0 || argv == NULL) {
2202 /* Ensure at least one (empty) argument is seen */
2203 static wchar_t *empty_argv[1] = {L""};
2204 argv = empty_argv;
2205 argc = 1;
2206 }
2207 av = PyList_New(argc);
2208 if (av != NULL) {
2209 int i;
2210 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 if (v == NULL) {
2213 Py_DECREF(av);
2214 av = NULL;
2215 break;
2216 }
2217 PyList_SetItem(av, i, v);
2218 }
2219 }
2220 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002221}
2222
Nick Coghland26c18a2010-08-17 13:06:11 +00002223#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2224 (argc > 0 && argv0 != NULL && \
2225 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002226
2227static void
2228sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002229{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002230 wchar_t *argv0;
2231 wchar_t *p = NULL;
2232 Py_ssize_t n = 0;
2233 PyObject *a;
2234 PyObject *path;
2235#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002236 wchar_t link[MAXPATHLEN+1];
2237 wchar_t argv0copy[2*MAXPATHLEN+1];
2238 int nr = 0;
2239#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002240#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002242#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002244#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002245
Victor Stinnerbd303c12013-11-07 23:07:29 +01002246 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002247 if (path == NULL)
2248 return;
2249
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002250 argv0 = argv[0];
2251
2252#ifdef HAVE_READLINK
2253 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2254 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2255 if (nr > 0) {
2256 /* It's a symlink */
2257 link[nr] = '\0';
2258 if (link[0] == SEP)
2259 argv0 = link; /* Link to absolute path */
2260 else if (wcschr(link, SEP) == NULL)
2261 ; /* Link without path */
2262 else {
2263 /* Must join(dirname(argv0), link) */
2264 wchar_t *q = wcsrchr(argv0, SEP);
2265 if (q == NULL)
2266 argv0 = link; /* argv0 without path */
2267 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002268 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2269 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002270 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002271 wcsncpy(q+1, link, MAXPATHLEN);
2272 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002273 argv0 = argv0copy;
2274 }
2275 }
2276 }
2277#endif /* HAVE_READLINK */
2278#if SEP == '\\' /* Special case for MS filename syntax */
2279 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2280 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002281#if defined(MS_WINDOWS)
2282 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002283 wchar_t *ptemp;
2284 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002285 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002286 fullpath,
2287 &ptemp)) {
2288 argv0 = fullpath;
2289 }
2290#endif
2291 p = wcsrchr(argv0, SEP);
2292 /* Test for alternate separator */
2293 q = wcsrchr(p ? p : argv0, '/');
2294 if (q != NULL)
2295 p = q;
2296 if (p != NULL) {
2297 n = p + 1 - argv0;
2298 if (n > 1 && p[-1] != ':')
2299 n--; /* Drop trailing separator */
2300 }
2301 }
2302#else /* All other filename syntaxes */
2303 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2304#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002305 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002306 argv0 = fullpath;
2307 }
2308#endif
2309 p = wcsrchr(argv0, SEP);
2310 }
2311 if (p != NULL) {
2312 n = p + 1 - argv0;
2313#if SEP == '/' /* Special case for Unix filename syntax */
2314 if (n > 1)
2315 n--; /* Drop trailing separator */
2316#endif /* Unix */
2317 }
2318#endif /* All others */
2319 a = PyUnicode_FromWideChar(argv0, n);
2320 if (a == NULL)
2321 Py_FatalError("no mem for sys.path insertion");
2322 if (PyList_Insert(path, 0, a) < 0)
2323 Py_FatalError("sys.path.insert(0) failed");
2324 Py_DECREF(a);
2325}
2326
2327void
2328PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 if (av == NULL)
2332 Py_FatalError("no mem for sys.argv");
2333 if (PySys_SetObject("argv", av) != 0)
2334 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002336 if (updatepath)
2337 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002338}
Guido van Rossuma890e681998-05-12 14:59:24 +00002339
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002340void
2341PySys_SetArgv(int argc, wchar_t **argv)
2342{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002343 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002344}
2345
Victor Stinner14284c22010-04-23 12:02:30 +00002346/* Reimplementation of PyFile_WriteString() no calling indirectly
2347 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2348
2349static int
Victor Stinner79766632010-08-16 17:36:42 +00002350sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002351{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002352 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002354
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002355 if (file == NULL)
2356 return -1;
2357
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002358 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 if (writer == NULL)
2360 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002361
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002362 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 if (result == NULL) {
2364 goto error;
2365 } else {
2366 err = 0;
2367 goto finally;
2368 }
Victor Stinner14284c22010-04-23 12:02:30 +00002369
2370error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002371 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002372finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 Py_XDECREF(result);
2375 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002376}
2377
Victor Stinner79766632010-08-16 17:36:42 +00002378static int
2379sys_pyfile_write(const char *text, PyObject *file)
2380{
2381 PyObject *unicode = NULL;
2382 int err;
2383
2384 if (file == NULL)
2385 return -1;
2386
2387 unicode = PyUnicode_FromString(text);
2388 if (unicode == NULL)
2389 return -1;
2390
2391 err = sys_pyfile_write_unicode(unicode, file);
2392 Py_DECREF(unicode);
2393 return err;
2394}
Guido van Rossuma890e681998-05-12 14:59:24 +00002395
2396/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2397 Adapted from code submitted by Just van Rossum.
2398
2399 PySys_WriteStdout(format, ...)
2400 PySys_WriteStderr(format, ...)
2401
2402 The first function writes to sys.stdout; the second to sys.stderr. When
2403 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002404 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002405
Victor Stinner14284c22010-04-23 12:02:30 +00002406 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002407 signal handlers: they may raise a new exception whereas sys_write()
2408 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002409
Guido van Rossuma890e681998-05-12 14:59:24 +00002410 Both take a printf-style format string as their first argument followed
2411 by a variable length argument list determined by the format string.
2412
2413 *** WARNING ***
2414
2415 The format should limit the total size of the formatted output string to
2416 1000 bytes. In particular, this means that no unrestricted "%s" formats
2417 should occur; these should be limited using "%.<N>s where <N> is a
2418 decimal number calculated so that <N> plus the maximum size of other
2419 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2420 which can print hundreds of digits for very large numbers.
2421
2422 */
2423
2424static void
Victor Stinner09054372013-11-06 22:41:44 +01002425sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002426{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 PyObject *file;
2428 PyObject *error_type, *error_value, *error_traceback;
2429 char buffer[1001];
2430 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002433 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2435 if (sys_pyfile_write(buffer, file) != 0) {
2436 PyErr_Clear();
2437 fputs(buffer, fp);
2438 }
2439 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2440 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002441 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 }
2444 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002445}
2446
2447void
Guido van Rossuma890e681998-05-12 14:59:24 +00002448PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002453 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002455}
2456
2457void
Guido van Rossuma890e681998-05-12 14:59:24 +00002458PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002459{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002463 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002464 va_end(va);
2465}
2466
2467static void
Victor Stinner09054372013-11-06 22:41:44 +01002468sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002469{
2470 PyObject *file, *message;
2471 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002472 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002473
2474 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002475 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002476 message = PyUnicode_FromFormatV(format, va);
2477 if (message != NULL) {
2478 if (sys_pyfile_write_unicode(message, file) != 0) {
2479 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002480 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002481 if (utf8 != NULL)
2482 fputs(utf8, fp);
2483 }
2484 Py_DECREF(message);
2485 }
2486 PyErr_Restore(error_type, error_value, error_traceback);
2487}
2488
2489void
2490PySys_FormatStdout(const char *format, ...)
2491{
2492 va_list va;
2493
2494 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002495 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002496 va_end(va);
2497}
2498
2499void
2500PySys_FormatStderr(const char *format, ...)
2501{
2502 va_list va;
2503
2504 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002505 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002507}