blob: fba7220e44ccd08c8b3b9211436639d25e609d0b [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 +0000559static PyObject *
560sys_setswitchinterval(PyObject *self, PyObject *args)
561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 double d;
563 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
564 return NULL;
565 if (d <= 0.0) {
566 PyErr_SetString(PyExc_ValueError,
567 "switch interval must be strictly positive");
568 return NULL;
569 }
570 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200571 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000572}
573
574PyDoc_STRVAR(setswitchinterval_doc,
575"setswitchinterval(n)\n\
576\n\
577Set the ideal thread switching delay inside the Python interpreter\n\
578The actual frequency of switching threads can be lower if the\n\
579interpreter executes long sequences of uninterruptible code\n\
580(this is implementation-specific and workload-dependent).\n\
581\n\
582The parameter must represent the desired switching delay in seconds\n\
583A typical value is 0.005 (5 milliseconds)."
584);
585
586static PyObject *
587sys_getswitchinterval(PyObject *self, PyObject *args)
588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000590}
591
592PyDoc_STRVAR(getswitchinterval_doc,
593"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
594);
595
Tim Peterse5e065b2003-07-06 18:36:54 +0000596static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000597sys_setrecursionlimit(PyObject *self, PyObject *args)
598{
Victor Stinner50856d52015-10-13 00:11:21 +0200599 int new_limit, mark;
600 PyThreadState *tstate;
601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
603 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200604
605 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200607 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 return NULL;
609 }
Victor Stinner50856d52015-10-13 00:11:21 +0200610
611 /* Issue #25274: When the recursion depth hits the recursion limit in
612 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
613 set to 1 and a RecursionError is raised. The overflowed flag is reset
614 to 0 when the recursion depth goes below the low-water mark: see
615 Py_LeaveRecursiveCall().
616
617 Reject too low new limit if the current recursion depth is higher than
618 the new low-water mark. Otherwise it may not be possible anymore to
619 reset the overflowed flag to 0. */
620 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
621 tstate = PyThreadState_GET();
622 if (tstate->recursion_depth >= mark) {
623 PyErr_Format(PyExc_RecursionError,
624 "cannot set the recursion limit to %i at "
625 "the recursion depth %i: the limit is too low",
626 new_limit, tstate->recursion_depth);
627 return NULL;
628 }
629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200631 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000632}
633
Yury Selivanov75445082015-05-11 22:57:16 -0400634static PyObject *
635sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
636{
637 if (wrapper != Py_None) {
638 if (!PyCallable_Check(wrapper)) {
639 PyErr_Format(PyExc_TypeError,
640 "callable expected, got %.50s",
641 Py_TYPE(wrapper)->tp_name);
642 return NULL;
643 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400644 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400645 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400646 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400647 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400648 }
Yury Selivanov75445082015-05-11 22:57:16 -0400649 Py_RETURN_NONE;
650}
651
652PyDoc_STRVAR(set_coroutine_wrapper_doc,
653"set_coroutine_wrapper(wrapper)\n\
654\n\
655Set a wrapper for coroutine objects."
656);
657
658static PyObject *
659sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
660{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400661 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400662 if (wrapper == NULL) {
663 wrapper = Py_None;
664 }
665 Py_INCREF(wrapper);
666 return wrapper;
667}
668
669PyDoc_STRVAR(get_coroutine_wrapper_doc,
670"get_coroutine_wrapper()\n\
671\n\
672Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
673);
674
675
Yury Selivanoveb636452016-09-08 22:01:51 -0700676static PyTypeObject AsyncGenHooksType;
677
678PyDoc_STRVAR(asyncgen_hooks_doc,
679"asyncgen_hooks\n\
680\n\
681A struct sequence providing information about asynhronous\n\
682generators hooks. The attributes are read only.");
683
684static PyStructSequence_Field asyncgen_hooks_fields[] = {
685 {"firstiter", "Hook to intercept first iteration"},
686 {"finalizer", "Hook to intercept finalization"},
687 {0}
688};
689
690static PyStructSequence_Desc asyncgen_hooks_desc = {
691 "asyncgen_hooks", /* name */
692 asyncgen_hooks_doc, /* doc */
693 asyncgen_hooks_fields , /* fields */
694 2
695};
696
697
698static PyObject *
699sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
700{
701 static char *keywords[] = {"firstiter", "finalizer", NULL};
702 PyObject *firstiter = NULL;
703 PyObject *finalizer = NULL;
704
705 if (!PyArg_ParseTupleAndKeywords(
706 args, kw, "|OO", keywords,
707 &firstiter, &finalizer)) {
708 return NULL;
709 }
710
711 if (finalizer && finalizer != Py_None) {
712 if (!PyCallable_Check(finalizer)) {
713 PyErr_Format(PyExc_TypeError,
714 "callable finalizer expected, got %.50s",
715 Py_TYPE(finalizer)->tp_name);
716 return NULL;
717 }
718 _PyEval_SetAsyncGenFinalizer(finalizer);
719 }
720 else if (finalizer == Py_None) {
721 _PyEval_SetAsyncGenFinalizer(NULL);
722 }
723
724 if (firstiter && firstiter != Py_None) {
725 if (!PyCallable_Check(firstiter)) {
726 PyErr_Format(PyExc_TypeError,
727 "callable firstiter expected, got %.50s",
728 Py_TYPE(firstiter)->tp_name);
729 return NULL;
730 }
731 _PyEval_SetAsyncGenFirstiter(firstiter);
732 }
733 else if (firstiter == Py_None) {
734 _PyEval_SetAsyncGenFirstiter(NULL);
735 }
736
737 Py_RETURN_NONE;
738}
739
740PyDoc_STRVAR(set_asyncgen_hooks_doc,
741"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
742\n\
743Set a finalizer for async generators objects."
744);
745
746static PyObject *
747sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
748{
749 PyObject *res;
750 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
751 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
752
753 res = PyStructSequence_New(&AsyncGenHooksType);
754 if (res == NULL) {
755 return NULL;
756 }
757
758 if (firstiter == NULL) {
759 firstiter = Py_None;
760 }
761
762 if (finalizer == NULL) {
763 finalizer = Py_None;
764 }
765
766 Py_INCREF(firstiter);
767 PyStructSequence_SET_ITEM(res, 0, firstiter);
768
769 Py_INCREF(finalizer);
770 PyStructSequence_SET_ITEM(res, 1, finalizer);
771
772 return res;
773}
774
775PyDoc_STRVAR(get_asyncgen_hooks_doc,
776"get_asyncgen_hooks()\n\
777\n\
778Return a namedtuple of installed asynchronous generators hooks \
779(firstiter, finalizer)."
780);
781
782
Mark Dickinsondc787d22010-05-23 13:33:13 +0000783static PyTypeObject Hash_InfoType;
784
785PyDoc_STRVAR(hash_info_doc,
786"hash_info\n\
787\n\
788A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100789hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000790
791static PyStructSequence_Field hash_info_fields[] = {
792 {"width", "width of the type used for hashing, in bits"},
793 {"modulus", "prime number giving the modulus on which the hash "
794 "function is based"},
795 {"inf", "value to be used for hash of a positive infinity"},
796 {"nan", "value to be used for hash of a nan"},
797 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100798 {"algorithm", "name of the algorithm for hashing of str, bytes and "
799 "memoryviews"},
800 {"hash_bits", "internal output size of hash algorithm"},
801 {"seed_bits", "seed size of hash algorithm"},
802 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000803 {NULL, NULL}
804};
805
806static PyStructSequence_Desc hash_info_desc = {
807 "sys.hash_info",
808 hash_info_doc,
809 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100810 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000811};
812
Matthias Klosed885e952010-07-06 10:53:30 +0000813static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000814get_hash_info(void)
815{
816 PyObject *hash_info;
817 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100818 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000819 hash_info = PyStructSequence_New(&Hash_InfoType);
820 if (hash_info == NULL)
821 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100822 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000823 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000824 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000825 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000826 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000827 PyStructSequence_SET_ITEM(hash_info, field++,
828 PyLong_FromLong(_PyHASH_INF));
829 PyStructSequence_SET_ITEM(hash_info, field++,
830 PyLong_FromLong(_PyHASH_NAN));
831 PyStructSequence_SET_ITEM(hash_info, field++,
832 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100833 PyStructSequence_SET_ITEM(hash_info, field++,
834 PyUnicode_FromString(hashfunc->name));
835 PyStructSequence_SET_ITEM(hash_info, field++,
836 PyLong_FromLong(hashfunc->hash_bits));
837 PyStructSequence_SET_ITEM(hash_info, field++,
838 PyLong_FromLong(hashfunc->seed_bits));
839 PyStructSequence_SET_ITEM(hash_info, field++,
840 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000841 if (PyErr_Occurred()) {
842 Py_CLEAR(hash_info);
843 return NULL;
844 }
845 return hash_info;
846}
847
848
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000849PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000850"setrecursionlimit(n)\n\
851\n\
852Set the maximum depth of the Python interpreter stack to n. This\n\
853limit prevents infinite recursion from causing an overflow of the C\n\
854stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000855dependent."
856);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000857
858static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000859sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000862}
863
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000864PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000865"getrecursionlimit()\n\
866\n\
867Return the current value of the recursion limit, the maximum depth\n\
868of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000869recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000870);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000871
Mark Hammond8696ebc2002-10-08 02:44:31 +0000872#ifdef MS_WINDOWS
873PyDoc_STRVAR(getwindowsversion_doc,
874"getwindowsversion()\n\
875\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000876Return information about the running version of Windows as a named tuple.\n\
877The members are named: major, minor, build, platform, service_pack,\n\
878service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200879backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700880All elements are numbers, except service_pack and platform_type which are\n\
881strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
882Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
883server. Platform_version is a 3-tuple containing a version number that is\n\
884intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000885);
886
Eric Smithf7bb5782010-01-27 00:44:57 +0000887static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
888
889static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000890 {"major", "Major version number"},
891 {"minor", "Minor version number"},
892 {"build", "Build number"},
893 {"platform", "Operating system platform"},
894 {"service_pack", "Latest Service Pack installed on the system"},
895 {"service_pack_major", "Service Pack major version number"},
896 {"service_pack_minor", "Service Pack minor version number"},
897 {"suite_mask", "Bit mask identifying available product suites"},
898 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700899 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000901};
902
903static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000904 "sys.getwindowsversion", /* name */
905 getwindowsversion_doc, /* doc */
906 windows_version_fields, /* fields */
907 5 /* For backward compatibility,
908 only the first 5 items are accessible
909 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000910};
911
Steve Dower3e96f322015-03-02 08:01:10 -0800912/* Disable deprecation warnings about GetVersionEx as the result is
913 being passed straight through to the caller, who is responsible for
914 using it correctly. */
915#pragma warning(push)
916#pragma warning(disable:4996)
917
Mark Hammond8696ebc2002-10-08 02:44:31 +0000918static PyObject *
919sys_getwindowsversion(PyObject *self)
920{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 PyObject *version;
922 int pos = 0;
923 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700924 DWORD realMajor, realMinor, realBuild;
925 HANDLE hKernel32;
926 wchar_t kernel32_path[MAX_PATH];
927 LPVOID verblock;
928 DWORD verblock_size;
929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000930 ver.dwOSVersionInfoSize = sizeof(ver);
931 if (!GetVersionEx((OSVERSIONINFO*) &ver))
932 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000933
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 version = PyStructSequence_New(&WindowsVersionType);
935 if (version == NULL)
936 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
939 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
940 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
941 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
942 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
943 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
944 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
945 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
946 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000947
Steve Dower74f4af72016-09-17 17:27:48 -0700948 realMajor = ver.dwMajorVersion;
949 realMinor = ver.dwMinorVersion;
950 realBuild = ver.dwBuildNumber;
951
952 // GetVersion will lie if we are running in a compatibility mode.
953 // We need to read the version info from a system file resource
954 // to accurately identify the OS version. If we fail for any reason,
955 // just return whatever GetVersion said.
956 hKernel32 = GetModuleHandleW(L"kernel32.dll");
957 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
958 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
959 (verblock = PyMem_RawMalloc(verblock_size))) {
960 VS_FIXEDFILEINFO *ffi;
961 UINT ffi_len;
962
963 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
964 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
965 realMajor = HIWORD(ffi->dwProductVersionMS);
966 realMinor = LOWORD(ffi->dwProductVersionMS);
967 realBuild = HIWORD(ffi->dwProductVersionLS);
968 }
969 PyMem_RawFree(verblock);
970 }
Segev Finer48fb7662017-06-04 20:52:27 +0300971 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
972 realMajor,
973 realMinor,
974 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700975 ));
976
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200977 if (PyErr_Occurred()) {
978 Py_DECREF(version);
979 return NULL;
980 }
Steve Dower74f4af72016-09-17 17:27:48 -0700981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000983}
984
Steve Dower3e96f322015-03-02 08:01:10 -0800985#pragma warning(pop)
986
Steve Dowercc16be82016-09-08 10:35:16 -0700987PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
988"_enablelegacywindowsfsencoding()\n\
989\n\
990Changes the default filesystem encoding to mbcs:replace for consistency\n\
991with earlier versions of Python. See PEP 529 for more information.\n\
992\n\
993This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
994environment variable before launching Python."
995);
996
997static PyObject *
998sys_enablelegacywindowsfsencoding(PyObject *self)
999{
1000 Py_FileSystemDefaultEncoding = "mbcs";
1001 Py_FileSystemDefaultEncodeErrors = "replace";
1002 Py_RETURN_NONE;
1003}
1004
Mark Hammond8696ebc2002-10-08 02:44:31 +00001005#endif /* MS_WINDOWS */
1006
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001007#ifdef HAVE_DLOPEN
1008static PyObject *
1009sys_setdlopenflags(PyObject *self, PyObject *args)
1010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 int new_val;
1012 PyThreadState *tstate = PyThreadState_GET();
1013 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1014 return NULL;
1015 if (!tstate)
1016 return NULL;
1017 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001018 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001019}
1020
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001021PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001022"setdlopenflags(n) -> None\n\
1023\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001024Set the flags used by the interpreter for dlopen calls, such as when the\n\
1025interpreter loads extension modules. Among other things, this will enable\n\
1026a lazy resolving of symbols when importing a module, if called as\n\
1027sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001028sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001029can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001030
1031static PyObject *
1032sys_getdlopenflags(PyObject *self, PyObject *args)
1033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 PyThreadState *tstate = PyThreadState_GET();
1035 if (!tstate)
1036 return NULL;
1037 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001038}
1039
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001040PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001041"getdlopenflags() -> int\n\
1042\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001043Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001044The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001045
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001047
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001048#ifdef USE_MALLOPT
1049/* Link with -lmalloc (or -lmpc) on an SGI */
1050#include <malloc.h>
1051
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001052static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001053sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 int flag;
1056 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1057 return NULL;
1058 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001059 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001060}
1061#endif /* USE_MALLOPT */
1062
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001063size_t
1064_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001068 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 /* Make sure the type is initialized. float gets initialized late */
1071 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001072 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001073
Benjamin Petersonce798522012-01-22 11:24:29 -05001074 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 if (method == NULL) {
1076 if (!PyErr_Occurred())
1077 PyErr_Format(PyExc_TypeError,
1078 "Type %.100s doesn't define __sizeof__",
1079 Py_TYPE(o)->tp_name);
1080 }
1081 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001082 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 Py_DECREF(method);
1084 }
1085
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001086 if (res == NULL)
1087 return (size_t)-1;
1088
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001089 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001090 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001091 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001092 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001093
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001094 if (size < 0) {
1095 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1096 return (size_t)-1;
1097 }
1098
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001100 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001101 return ((size_t)size) + sizeof(PyGC_Head);
1102 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001103}
1104
1105static PyObject *
1106sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1107{
1108 static char *kwlist[] = {"object", "default", 0};
1109 size_t size;
1110 PyObject *o, *dflt = NULL;
1111
1112 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1113 kwlist, &o, &dflt))
1114 return NULL;
1115
1116 size = _PySys_GetSizeOf(o);
1117
1118 if (size == (size_t)-1 && PyErr_Occurred()) {
1119 /* Has a default value been given */
1120 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1121 PyErr_Clear();
1122 Py_INCREF(dflt);
1123 return dflt;
1124 }
1125 else
1126 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001128
1129 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001130}
1131
1132PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001133"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001134\n\
1135Return the size of object in bytes.");
1136
1137static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001138sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001141}
1142
Tim Peters4be93d02002-07-07 19:59:50 +00001143#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001144static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001145sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001146{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001148}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001149#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001150
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001151PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001152"getrefcount(object) -> integer\n\
1153\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001154Return the reference count of object. The count returned is generally\n\
1155one higher than you might expect, because it includes the (temporary)\n\
1156reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001157);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001158
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001159static PyObject *
1160sys_getallocatedblocks(PyObject *self)
1161{
1162 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1163}
1164
1165PyDoc_STRVAR(getallocatedblocks_doc,
1166"getallocatedblocks() -> integer\n\
1167\n\
1168Return the number of memory blocks currently allocated, regardless of their\n\
1169size."
1170);
1171
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001172#ifdef COUNT_ALLOCS
1173static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001174sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001175{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001179}
1180#endif
1181
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001182PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001183"_getframe([depth]) -> frameobject\n\
1184\n\
1185Return a frame object from the call stack. If optional integer depth is\n\
1186given, return the frame object that many calls below the top of the stack.\n\
1187If that is deeper than the call stack, ValueError is raised. The default\n\
1188for depth is zero, returning the frame at the top of the call stack.\n\
1189\n\
1190This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001191purposes only."
1192);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001193
1194static PyObject *
1195sys_getframe(PyObject *self, PyObject *args)
1196{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197 PyFrameObject *f = PyThreadState_GET()->frame;
1198 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001199
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1201 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 while (depth > 0 && f != NULL) {
1204 f = f->f_back;
1205 --depth;
1206 }
1207 if (f == NULL) {
1208 PyErr_SetString(PyExc_ValueError,
1209 "call stack is not deep enough");
1210 return NULL;
1211 }
1212 Py_INCREF(f);
1213 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001214}
1215
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001216PyDoc_STRVAR(current_frames_doc,
1217"_current_frames() -> dictionary\n\
1218\n\
1219Return a dictionary mapping each current thread T's thread id to T's\n\
1220current stack frame.\n\
1221\n\
1222This function should be used for specialized purposes only."
1223);
1224
1225static PyObject *
1226sys_current_frames(PyObject *self, PyObject *noargs)
1227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001229}
1230
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001231PyDoc_STRVAR(call_tracing_doc,
1232"call_tracing(func, args) -> object\n\
1233\n\
1234Call func(*args), while tracing is enabled. The tracing state is\n\
1235saved, and restored afterwards. This is intended to be called from\n\
1236a debugger from a checkpoint, to recursively debug some other code."
1237);
1238
1239static PyObject *
1240sys_call_tracing(PyObject *self, PyObject *args)
1241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 PyObject *func, *funcargs;
1243 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1244 return NULL;
1245 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001246}
1247
Jeremy Hylton985eba52003-02-05 23:13:00 +00001248PyDoc_STRVAR(callstats_doc,
1249"callstats() -> tuple of integers\n\
1250\n\
1251Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1252when Python was built. Otherwise, return None.\n\
1253\n\
1254When enabled, this function returns detailed, implementation-specific\n\
1255details about the number of function calls executed. The return value is\n\
1256a 11-tuple where the entries in the tuple are counts of:\n\
12570. all function calls\n\
12581. calls to PyFunction_Type objects\n\
12592. PyFunction calls that do not create an argument tuple\n\
12603. PyFunction calls that do not create an argument tuple\n\
1261 and bypass PyEval_EvalCodeEx()\n\
12624. PyMethod calls\n\
12635. PyMethod calls on bound methods\n\
12646. PyType calls\n\
12657. PyCFunction calls\n\
12668. generator calls\n\
12679. All other calls\n\
126810. Number of stack pops performed by call_function()"
1269);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001270
Victor Stinner048afd92016-11-28 11:59:04 +01001271static PyObject *
1272sys_callstats(PyObject *self)
1273{
1274 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1275 "sys.callstats() has been deprecated in Python 3.7 "
1276 "and will be removed in the future", 1) < 0) {
1277 return NULL;
1278 }
1279
1280 Py_RETURN_NONE;
1281}
1282
1283
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001284#ifdef __cplusplus
1285extern "C" {
1286#endif
1287
David Malcolm49526f42012-06-22 14:55:41 -04001288static PyObject *
1289sys_debugmallocstats(PyObject *self, PyObject *args)
1290{
1291#ifdef WITH_PYMALLOC
Victor Stinner34be8072016-03-14 12:04:26 +01001292 if (_PyMem_PymallocEnabled()) {
1293 _PyObject_DebugMallocStats(stderr);
1294 fputc('\n', stderr);
1295 }
David Malcolm49526f42012-06-22 14:55:41 -04001296#endif
1297 _PyObject_DebugTypeStats(stderr);
1298
1299 Py_RETURN_NONE;
1300}
1301PyDoc_STRVAR(debugmallocstats_doc,
1302"_debugmallocstats()\n\
1303\n\
1304Print summary info to stderr about the state of\n\
1305pymalloc's structures.\n\
1306\n\
1307In Py_DEBUG mode, also perform some expensive internal consistency\n\
1308checks.\n\
1309");
1310
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001311#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001312/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001313extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001314#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001315
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001316#ifdef DYNAMIC_EXECUTION_PROFILE
1317/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001318extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001319#endif
1320
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001321#ifdef __cplusplus
1322}
1323#endif
1324
Christian Heimes15ebc882008-02-04 18:48:49 +00001325static PyObject *
1326sys_clear_type_cache(PyObject* self, PyObject* args)
1327{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 PyType_ClearCache();
1329 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001330}
1331
1332PyDoc_STRVAR(sys_clear_type_cache__doc__,
1333"_clear_type_cache() -> None\n\
1334Clear the internal type lookup cache.");
1335
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001336static PyObject *
1337sys_is_finalizing(PyObject* self, PyObject* args)
1338{
Eric Snow05351c12017-09-05 21:43:08 -07001339 return PyBool_FromLong(_Py_Finalizing != NULL);
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001340}
1341
1342PyDoc_STRVAR(is_finalizing_doc,
1343"is_finalizing()\n\
1344Return True if Python is exiting.");
1345
Christian Heimes15ebc882008-02-04 18:48:49 +00001346
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001347#ifdef ANDROID_API_LEVEL
1348PyDoc_STRVAR(getandroidapilevel_doc,
1349"getandroidapilevel()\n\
1350\n\
1351Return the build time API version of Android as an integer.");
1352
1353static PyObject *
1354sys_getandroidapilevel(PyObject *self)
1355{
1356 return PyLong_FromLong(ANDROID_API_LEVEL);
1357}
1358#endif /* ANDROID_API_LEVEL */
1359
1360
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001361static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001363 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 callstats_doc},
1365 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1366 sys_clear_type_cache__doc__},
1367 {"_current_frames", sys_current_frames, METH_NOARGS,
1368 current_frames_doc},
1369 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1370 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1371 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1372 {"exit", sys_exit, METH_VARARGS, exit_doc},
1373 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1374 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001375#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001376 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1377 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001378#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001379 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1380 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001381#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001382 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001383#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001384#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001385 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001386#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1388 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001389 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1390 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001391#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001393#endif
1394#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001396#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001397 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1398 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1399 getrecursionlimit_doc},
1400 {"getsizeof", (PyCFunction)sys_getsizeof,
1401 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1402 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001403#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1405 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001406 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1407 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001408#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001410 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001411#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001413#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1415 setcheckinterval_doc},
1416 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1417 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1419 setswitchinterval_doc},
1420 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1421 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001422#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1424 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001425#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1427 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1428 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1429 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 {"settrace", sys_settrace, METH_O, settrace_doc},
1431 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1432 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001433 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001434 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001435 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1436 set_coroutine_wrapper_doc},
1437 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1438 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001439 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001440 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1441 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1442 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001443#ifdef ANDROID_API_LEVEL
1444 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1445 getandroidapilevel_doc},
1446#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001448};
1449
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001450static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001451list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 PyObject *list = PyList_New(0);
1454 int i;
1455 if (list == NULL)
1456 return NULL;
1457 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1458 PyObject *name = PyUnicode_FromString(
1459 PyImport_Inittab[i].name);
1460 if (name == NULL)
1461 break;
1462 PyList_Append(list, name);
1463 Py_DECREF(name);
1464 }
1465 if (PyList_Sort(list) != 0) {
1466 Py_DECREF(list);
1467 list = NULL;
1468 }
1469 if (list) {
1470 PyObject *v = PyList_AsTuple(list);
1471 Py_DECREF(list);
1472 list = v;
1473 }
1474 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001475}
1476
Eric Snow05351c12017-09-05 21:43:08 -07001477static PyObject *warnoptions = NULL;
Guido van Rossum23fff912000-12-15 22:02:05 +00001478
1479void
1480PySys_ResetWarnOptions(void)
1481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 if (warnoptions == NULL || !PyList_Check(warnoptions))
1483 return;
1484 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001485}
1486
1487void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001488PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001489{
Eric Snow05351c12017-09-05 21:43:08 -07001490 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1491 Py_XDECREF(warnoptions);
1492 warnoptions = PyList_New(0);
1493 if (warnoptions == NULL)
1494 return;
1495 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001496 PyList_Append(warnoptions, unicode);
1497}
1498
1499void
1500PySys_AddWarnOption(const wchar_t *s)
1501{
1502 PyObject *unicode;
1503 unicode = PyUnicode_FromWideChar(s, -1);
1504 if (unicode == NULL)
1505 return;
1506 PySys_AddWarnOptionUnicode(unicode);
1507 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001508}
1509
Christian Heimes33fe8092008-04-13 13:53:33 +00001510int
1511PySys_HasWarnOptions(void)
1512{
1513 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1514}
1515
Eric Snow05351c12017-09-05 21:43:08 -07001516static PyObject *xoptions = NULL;
1517
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001518static PyObject *
1519get_xoptions(void)
1520{
1521 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1522 Py_XDECREF(xoptions);
1523 xoptions = PyDict_New();
1524 }
1525 return xoptions;
1526}
1527
1528void
1529PySys_AddXOption(const wchar_t *s)
1530{
1531 PyObject *opts;
1532 PyObject *name = NULL, *value = NULL;
1533 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001534
1535 opts = get_xoptions();
1536 if (opts == NULL)
1537 goto error;
1538
1539 name_end = wcschr(s, L'=');
1540 if (!name_end) {
1541 name = PyUnicode_FromWideChar(s, -1);
1542 value = Py_True;
1543 Py_INCREF(value);
1544 }
1545 else {
1546 name = PyUnicode_FromWideChar(s, name_end - s);
1547 value = PyUnicode_FromWideChar(name_end + 1, -1);
1548 }
1549 if (name == NULL || value == NULL)
1550 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001551 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001552 Py_DECREF(name);
1553 Py_DECREF(value);
1554 return;
1555
1556error:
1557 Py_XDECREF(name);
1558 Py_XDECREF(value);
1559 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001560 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001561 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001562 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001563}
1564
1565PyObject *
1566PySys_GetXOptions(void)
1567{
1568 return get_xoptions();
1569}
1570
Guido van Rossum40552d01998-08-06 03:34:39 +00001571/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1572 Two literals concatenated works just fine. If you have a K&R compiler
1573 or other abomination that however *does* understand longer strings,
1574 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001575PyDoc_VAR(sys_doc) =
1576PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001577"This module provides access to some objects used or maintained by the\n\
1578interpreter and to functions that interact strongly with the interpreter.\n\
1579\n\
1580Dynamic objects:\n\
1581\n\
1582argv -- command line arguments; argv[0] is the script pathname if known\n\
1583path -- module search path; path[0] is the script directory, else ''\n\
1584modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001585\n\
1586displayhook -- called to show results in an interactive session\n\
1587excepthook -- called to handle any uncaught exception other than SystemExit\n\
1588 To customize printing in an interactive session or to install a custom\n\
1589 top-level exception handler, assign other functions to replace these.\n\
1590\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001591stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001592stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001593stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001594 By assigning other file objects (or objects that behave like files)\n\
1595 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001596\n\
1597last_type -- type of last uncaught exception\n\
1598last_value -- value of last uncaught exception\n\
1599last_traceback -- traceback of last uncaught exception\n\
1600 These three are only available in an interactive session after a\n\
1601 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001602"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001603)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001604/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001605PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001606"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001607Static objects:\n\
1608\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001609builtin_module_names -- tuple of module names built into this interpreter\n\
1610copyright -- copyright notice pertaining to this interpreter\n\
1611exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001612executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001613float_info -- a struct sequence with information about the float implementation.\n\
1614float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001615hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001616hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001617implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001618int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001619maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001620maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001621platform -- platform identifier\n\
1622prefix -- prefix used to find the Python library\n\
1623thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001624version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001625version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001626"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001627)
Steve Dowercc16be82016-09-08 10:35:16 -07001628#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001629/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001630PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001631"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001632winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001633"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001634)
Steve Dowercc16be82016-09-08 10:35:16 -07001635#endif /* MS_COREDLL */
1636#ifdef MS_WINDOWS
1637/* concatenating string here */
1638PyDoc_STR(
1639"_enablelegacywindowsfsencoding -- [Windows only] \n\
1640"
1641)
1642#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001643PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001644"__stdin__ -- the original stdin; don't touch!\n\
1645__stdout__ -- the original stdout; don't touch!\n\
1646__stderr__ -- the original stderr; don't touch!\n\
1647__displayhook__ -- the original displayhook; don't touch!\n\
1648__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001649\n\
1650Functions:\n\
1651\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001652displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001653excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001654exc_info() -- return thread-safe information about the current exception\n\
1655exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001656getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001657getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001658getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001659getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001660getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001661gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001662setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001663setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001664setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001665setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001666settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001667"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001668)
Fred Drakeccede592000-08-14 20:59:57 +00001669/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001670
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001671
1672PyDoc_STRVAR(flags__doc__,
1673"sys.flags\n\
1674\n\
1675Flags provided through command line arguments or environment vars.");
1676
1677static PyTypeObject FlagsType;
1678
1679static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 {"inspect", "-i"},
1682 {"interactive", "-i"},
1683 {"optimize", "-O or -OO"},
1684 {"dont_write_bytecode", "-B"},
1685 {"no_user_site", "-s"},
1686 {"no_site", "-S"},
1687 {"ignore_environment", "-E"},
1688 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 /* {"unbuffered", "-u"}, */
1690 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001691 {"bytes_warning", "-b"},
1692 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001693 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001694 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001696};
1697
1698static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001699 "sys.flags", /* name */
1700 flags__doc__, /* doc */
1701 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001702 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001703};
1704
1705static PyObject*
1706make_flags(void)
1707{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001708 int pos = 0;
1709 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001710
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 seq = PyStructSequence_New(&FlagsType);
1712 if (seq == NULL)
1713 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001714
1715#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001717
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 SetFlag(Py_InspectFlag);
1720 SetFlag(Py_InteractiveFlag);
1721 SetFlag(Py_OptimizeFlag);
1722 SetFlag(Py_DontWriteBytecodeFlag);
1723 SetFlag(Py_NoUserSiteDirectory);
1724 SetFlag(Py_NoSiteFlag);
1725 SetFlag(Py_IgnoreEnvironmentFlag);
1726 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001727 /* SetFlag(saw_unbuffered_flag); */
1728 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001729 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001730 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001731 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001732 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001733#undef SetFlag
1734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001736 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 return NULL;
1738 }
1739 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001740}
1741
Eric Smith0e5b5622009-02-06 01:32:42 +00001742PyDoc_STRVAR(version_info__doc__,
1743"sys.version_info\n\
1744\n\
1745Version information as a named tuple.");
1746
1747static PyTypeObject VersionInfoType;
1748
1749static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 {"major", "Major release number"},
1751 {"minor", "Minor release number"},
1752 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001753 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001754 {"serial", "Serial release number"},
1755 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001756};
1757
1758static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 "sys.version_info", /* name */
1760 version_info__doc__, /* doc */
1761 version_info_fields, /* fields */
1762 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001763};
1764
1765static PyObject *
1766make_version_info(void)
1767{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 PyObject *version_info;
1769 char *s;
1770 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 version_info = PyStructSequence_New(&VersionInfoType);
1773 if (version_info == NULL) {
1774 return NULL;
1775 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 /*
1778 * These release level checks are mutually exclusive and cover
1779 * the field, so don't get too fancy with the pre-processor!
1780 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001781#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001783#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001785#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001786 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001787#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001789#endif
1790
1791#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001793#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001794 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 SetIntItem(PY_MAJOR_VERSION);
1797 SetIntItem(PY_MINOR_VERSION);
1798 SetIntItem(PY_MICRO_VERSION);
1799 SetStrItem(s);
1800 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001801#undef SetIntItem
1802#undef SetStrItem
1803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (PyErr_Occurred()) {
1805 Py_CLEAR(version_info);
1806 return NULL;
1807 }
1808 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001809}
1810
Brett Cannon3adc7b72012-07-09 14:22:12 -04001811/* sys.implementation values */
1812#define NAME "cpython"
1813const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001814#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1815#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001816#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001817const char *_PySys_ImplCacheTag = TAG;
1818#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001819#undef MAJOR
1820#undef MINOR
1821#undef TAG
1822
Barry Warsaw409da152012-06-03 16:18:47 -04001823static PyObject *
1824make_impl_info(PyObject *version_info)
1825{
1826 int res;
1827 PyObject *impl_info, *value, *ns;
1828
1829 impl_info = PyDict_New();
1830 if (impl_info == NULL)
1831 return NULL;
1832
1833 /* populate the dict */
1834
Brett Cannon3adc7b72012-07-09 14:22:12 -04001835 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001836 if (value == NULL)
1837 goto error;
1838 res = PyDict_SetItemString(impl_info, "name", value);
1839 Py_DECREF(value);
1840 if (res < 0)
1841 goto error;
1842
Brett Cannon3adc7b72012-07-09 14:22:12 -04001843 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001844 if (value == NULL)
1845 goto error;
1846 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1847 Py_DECREF(value);
1848 if (res < 0)
1849 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001850
1851 res = PyDict_SetItemString(impl_info, "version", version_info);
1852 if (res < 0)
1853 goto error;
1854
1855 value = PyLong_FromLong(PY_VERSION_HEX);
1856 if (value == NULL)
1857 goto error;
1858 res = PyDict_SetItemString(impl_info, "hexversion", value);
1859 Py_DECREF(value);
1860 if (res < 0)
1861 goto error;
1862
doko@ubuntu.com55532312016-06-14 08:55:19 +02001863#ifdef MULTIARCH
1864 value = PyUnicode_FromString(MULTIARCH);
1865 if (value == NULL)
1866 goto error;
1867 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1868 Py_DECREF(value);
1869 if (res < 0)
1870 goto error;
1871#endif
1872
Barry Warsaw409da152012-06-03 16:18:47 -04001873 /* dict ready */
1874
1875 ns = _PyNamespace_New(impl_info);
1876 Py_DECREF(impl_info);
1877 return ns;
1878
1879error:
1880 Py_CLEAR(impl_info);
1881 return NULL;
1882}
1883
Martin v. Löwis1a214512008-06-11 05:26:20 +00001884static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 PyModuleDef_HEAD_INIT,
1886 "sys",
1887 sys_doc,
1888 -1, /* multiple "initialization" just copies the module dict. */
1889 sys_methods,
1890 NULL,
1891 NULL,
1892 NULL,
1893 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001894};
1895
Eric Snow6b4be192017-05-22 21:36:03 -07001896/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001897#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001898 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001899 PyObject *v = (value); \
1900 if (v == NULL) \
1901 return NULL; \
1902 res = PyDict_SetItemString(sysdict, key, v); \
1903 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001904 return NULL; \
1905 } \
1906 } while (0)
1907#define SET_SYS_FROM_STRING(key, value) \
1908 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001909 PyObject *v = (value); \
1910 if (v == NULL) \
1911 return NULL; \
1912 res = PyDict_SetItemString(sysdict, key, v); \
1913 Py_DECREF(v); \
1914 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001915 return NULL; \
1916 } \
1917 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001918
Eric Snow6b4be192017-05-22 21:36:03 -07001919PyObject *
1920_PySys_BeginInit(void)
1921{
1922 PyObject *m, *sysdict, *version_info;
1923 int res;
1924
Eric Snow86b7afd2017-09-04 17:54:09 -06001925 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Eric Snow6b4be192017-05-22 21:36:03 -07001926 if (m == NULL)
1927 return NULL;
1928 sysdict = PyModule_GetDict(m);
1929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 /* Check that stdin is not a directory
1931 Using shell redirection, you can redirect stdin to a directory,
1932 crashing the Python interpreter. Catch this common mistake here
1933 and output a useful error message. Note that under MS Windows,
1934 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001935#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001937 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001938 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 S_ISDIR(sb.st_mode)) {
1940 /* There's nothing more we can do. */
1941 /* Py_FatalError() will core dump, so just exit. */
1942 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1943 exit(EXIT_FAILURE);
1944 }
1945 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001946#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001947
Nick Coghland6009512014-11-20 21:39:37 +10001948 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001949
Victor Stinner8fea2522013-10-27 17:15:42 +01001950 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1951 PyDict_GetItemString(sysdict, "displayhook"));
1952 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1953 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 SET_SYS_FROM_STRING("version",
1955 PyUnicode_FromString(Py_GetVersion()));
1956 SET_SYS_FROM_STRING("hexversion",
1957 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001958 SET_SYS_FROM_STRING("_git",
1959 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1960 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001961 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001962 SET_SYS_FROM_STRING("api_version",
1963 PyLong_FromLong(PYTHON_API_VERSION));
1964 SET_SYS_FROM_STRING("copyright",
1965 PyUnicode_FromString(Py_GetCopyright()));
1966 SET_SYS_FROM_STRING("platform",
1967 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001968 SET_SYS_FROM_STRING("maxsize",
1969 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1970 SET_SYS_FROM_STRING("float_info",
1971 PyFloat_GetInfo());
1972 SET_SYS_FROM_STRING("int_info",
1973 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001974 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001975 if (Hash_InfoType.tp_name == NULL) {
1976 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1977 return NULL;
1978 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001979 SET_SYS_FROM_STRING("hash_info",
1980 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001981 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001982 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001983 SET_SYS_FROM_STRING("builtin_module_names",
1984 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001985#if PY_BIG_ENDIAN
1986 SET_SYS_FROM_STRING("byteorder",
1987 PyUnicode_FromString("big"));
1988#else
1989 SET_SYS_FROM_STRING("byteorder",
1990 PyUnicode_FromString("little"));
1991#endif
Fred Drake099325e2000-08-14 15:47:03 +00001992
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001993#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 SET_SYS_FROM_STRING("dllhandle",
1995 PyLong_FromVoidPtr(PyWin_DLLhModule));
1996 SET_SYS_FROM_STRING("winver",
1997 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001998#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001999#ifdef ABIFLAGS
2000 SET_SYS_FROM_STRING("abiflags",
2001 PyUnicode_FromString(ABIFLAGS));
2002#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002003
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002005 if (VersionInfoType.tp_name == NULL) {
2006 if (PyStructSequence_InitType2(&VersionInfoType,
2007 &version_info_desc) < 0)
2008 return NULL;
2009 }
Barry Warsaw409da152012-06-03 16:18:47 -04002010 version_info = make_version_info();
2011 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 /* prevent user from creating new instances */
2013 VersionInfoType.tp_init = NULL;
2014 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002015 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2016 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2017 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002018
Barry Warsaw409da152012-06-03 16:18:47 -04002019 /* implementation */
2020 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002023 if (FlagsType.tp_name == 0) {
2024 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2025 return NULL;
2026 }
Eric Snow6b4be192017-05-22 21:36:03 -07002027 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002029
2030#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 /* getwindowsversion */
2032 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002033 if (PyStructSequence_InitType2(&WindowsVersionType,
2034 &windows_version_desc) < 0)
2035 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 /* prevent user from creating new instances */
2037 WindowsVersionType.tp_init = NULL;
2038 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002039 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2040 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2041 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002042#endif
2043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002045#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 SET_SYS_FROM_STRING("float_repr_style",
2047 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002048#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 SET_SYS_FROM_STRING("float_repr_style",
2050 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002051#endif
2052
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002053 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002054
Yury Selivanoveb636452016-09-08 22:01:51 -07002055 /* initialize asyncgen_hooks */
2056 if (AsyncGenHooksType.tp_name == NULL) {
2057 if (PyStructSequence_InitType2(
2058 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2059 return NULL;
2060 }
2061 }
2062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 if (PyErr_Occurred())
2064 return NULL;
2065 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002066}
2067
Eric Snow6b4be192017-05-22 21:36:03 -07002068#undef SET_SYS_FROM_STRING
2069#undef SET_SYS_FROM_STRING_BORROW
2070
2071/* Updating the sys namespace, returning integer error codes */
2072#define SET_SYS_FROM_STRING_BORROW_INT_RESULT(key, value) \
2073 do { \
2074 PyObject *v = (value); \
2075 if (v == NULL) \
2076 return -1; \
2077 res = PyDict_SetItemString(sysdict, key, v); \
2078 if (res < 0) { \
2079 return res; \
2080 } \
2081 } while (0)
2082#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2083 do { \
2084 PyObject *v = (value); \
2085 if (v == NULL) \
2086 return -1; \
2087 res = PyDict_SetItemString(sysdict, key, v); \
2088 Py_DECREF(v); \
2089 if (res < 0) { \
2090 return res; \
2091 } \
2092 } while (0)
2093
2094int
2095_PySys_EndInit(PyObject *sysdict)
2096{
2097 int res;
2098
2099 /* Set flags to their final values */
2100 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2101 /* prevent user from creating new instances */
2102 FlagsType.tp_init = NULL;
2103 FlagsType.tp_new = NULL;
2104 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2105 if (res < 0) {
2106 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2107 return res;
2108 }
2109 PyErr_Clear();
2110 }
2111
2112 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2113 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2114 SET_SYS_FROM_STRING_INT_RESULT("executable",
2115 PyUnicode_FromWideChar(
2116 Py_GetProgramFullPath(), -1));
2117 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2118 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2119 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2120 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2121 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2122 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2123 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2124 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2125
Eric Snow05351c12017-09-05 21:43:08 -07002126 if (warnoptions == NULL) {
2127 warnoptions = PyList_New(0);
2128 if (warnoptions == NULL)
2129 return -1;
2130 }
Victor Stinner865de272017-06-08 13:27:47 +02002131
Eric Snow05351c12017-09-05 21:43:08 -07002132 SET_SYS_FROM_STRING_INT_RESULT("warnoptions",
2133 PyList_GetSlice(warnoptions,
2134 0, Py_SIZE(warnoptions)));
2135
2136 SET_SYS_FROM_STRING_BORROW_INT_RESULT("_xoptions", get_xoptions());
Eric Snow6b4be192017-05-22 21:36:03 -07002137
2138 if (PyErr_Occurred())
2139 return -1;
2140 return 0;
2141}
2142
2143#undef SET_SYS_FROM_STRING_INT_RESULT
2144#undef SET_SYS_FROM_STRING_BORROW_INT_RESULT
2145
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002146static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002147makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002148{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 int i, n;
2150 const wchar_t *p;
2151 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 n = 1;
2154 p = path;
2155 while ((p = wcschr(p, delim)) != NULL) {
2156 n++;
2157 p++;
2158 }
2159 v = PyList_New(n);
2160 if (v == NULL)
2161 return NULL;
2162 for (i = 0; ; i++) {
2163 p = wcschr(path, delim);
2164 if (p == NULL)
2165 p = path + wcslen(path); /* End of string */
2166 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2167 if (w == NULL) {
2168 Py_DECREF(v);
2169 return NULL;
2170 }
2171 PyList_SetItem(v, i, w);
2172 if (*p == '\0')
2173 break;
2174 path = p+1;
2175 }
2176 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002177}
2178
2179void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002180PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 PyObject *v;
2183 if ((v = makepathobject(path, DELIM)) == NULL)
2184 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002185 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 Py_FatalError("can't assign sys.path");
2187 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002188}
2189
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002190static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002191makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 PyObject *av;
2194 if (argc <= 0 || argv == NULL) {
2195 /* Ensure at least one (empty) argument is seen */
2196 static wchar_t *empty_argv[1] = {L""};
2197 argv = empty_argv;
2198 argc = 1;
2199 }
2200 av = PyList_New(argc);
2201 if (av != NULL) {
2202 int i;
2203 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 if (v == NULL) {
2206 Py_DECREF(av);
2207 av = NULL;
2208 break;
2209 }
2210 PyList_SetItem(av, i, v);
2211 }
2212 }
2213 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002214}
2215
Nick Coghland26c18a2010-08-17 13:06:11 +00002216#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2217 (argc > 0 && argv0 != NULL && \
2218 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002219
2220static void
2221sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002222{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002223 wchar_t *argv0;
2224 wchar_t *p = NULL;
2225 Py_ssize_t n = 0;
2226 PyObject *a;
2227 PyObject *path;
2228#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002229 wchar_t link[MAXPATHLEN+1];
2230 wchar_t argv0copy[2*MAXPATHLEN+1];
2231 int nr = 0;
2232#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002233#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002235#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002237#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002238
Victor Stinnerbd303c12013-11-07 23:07:29 +01002239 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002240 if (path == NULL)
2241 return;
2242
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002243 argv0 = argv[0];
2244
2245#ifdef HAVE_READLINK
2246 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2247 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2248 if (nr > 0) {
2249 /* It's a symlink */
2250 link[nr] = '\0';
2251 if (link[0] == SEP)
2252 argv0 = link; /* Link to absolute path */
2253 else if (wcschr(link, SEP) == NULL)
2254 ; /* Link without path */
2255 else {
2256 /* Must join(dirname(argv0), link) */
2257 wchar_t *q = wcsrchr(argv0, SEP);
2258 if (q == NULL)
2259 argv0 = link; /* argv0 without path */
2260 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002261 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2262 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002263 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002264 wcsncpy(q+1, link, MAXPATHLEN);
2265 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002266 argv0 = argv0copy;
2267 }
2268 }
2269 }
2270#endif /* HAVE_READLINK */
2271#if SEP == '\\' /* Special case for MS filename syntax */
2272 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2273 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002274#if defined(MS_WINDOWS)
2275 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002276 wchar_t *ptemp;
2277 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002278 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002279 fullpath,
2280 &ptemp)) {
2281 argv0 = fullpath;
2282 }
2283#endif
2284 p = wcsrchr(argv0, SEP);
2285 /* Test for alternate separator */
2286 q = wcsrchr(p ? p : argv0, '/');
2287 if (q != NULL)
2288 p = q;
2289 if (p != NULL) {
2290 n = p + 1 - argv0;
2291 if (n > 1 && p[-1] != ':')
2292 n--; /* Drop trailing separator */
2293 }
2294 }
2295#else /* All other filename syntaxes */
2296 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2297#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002298 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002299 argv0 = fullpath;
2300 }
2301#endif
2302 p = wcsrchr(argv0, SEP);
2303 }
2304 if (p != NULL) {
2305 n = p + 1 - argv0;
2306#if SEP == '/' /* Special case for Unix filename syntax */
2307 if (n > 1)
2308 n--; /* Drop trailing separator */
2309#endif /* Unix */
2310 }
2311#endif /* All others */
2312 a = PyUnicode_FromWideChar(argv0, n);
2313 if (a == NULL)
2314 Py_FatalError("no mem for sys.path insertion");
2315 if (PyList_Insert(path, 0, a) < 0)
2316 Py_FatalError("sys.path.insert(0) failed");
2317 Py_DECREF(a);
2318}
2319
2320void
2321PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 if (av == NULL)
2325 Py_FatalError("no mem for sys.argv");
2326 if (PySys_SetObject("argv", av) != 0)
2327 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002329 if (updatepath)
2330 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002331}
Guido van Rossuma890e681998-05-12 14:59:24 +00002332
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002333void
2334PySys_SetArgv(int argc, wchar_t **argv)
2335{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002336 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002337}
2338
Victor Stinner14284c22010-04-23 12:02:30 +00002339/* Reimplementation of PyFile_WriteString() no calling indirectly
2340 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2341
2342static int
Victor Stinner79766632010-08-16 17:36:42 +00002343sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002344{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002345 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002346 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002347
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002348 if (file == NULL)
2349 return -1;
2350
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002351 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002352 if (writer == NULL)
2353 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002354
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002355 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 if (result == NULL) {
2357 goto error;
2358 } else {
2359 err = 0;
2360 goto finally;
2361 }
Victor Stinner14284c22010-04-23 12:02:30 +00002362
2363error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002365finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 Py_XDECREF(result);
2368 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002369}
2370
Victor Stinner79766632010-08-16 17:36:42 +00002371static int
2372sys_pyfile_write(const char *text, PyObject *file)
2373{
2374 PyObject *unicode = NULL;
2375 int err;
2376
2377 if (file == NULL)
2378 return -1;
2379
2380 unicode = PyUnicode_FromString(text);
2381 if (unicode == NULL)
2382 return -1;
2383
2384 err = sys_pyfile_write_unicode(unicode, file);
2385 Py_DECREF(unicode);
2386 return err;
2387}
Guido van Rossuma890e681998-05-12 14:59:24 +00002388
2389/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2390 Adapted from code submitted by Just van Rossum.
2391
2392 PySys_WriteStdout(format, ...)
2393 PySys_WriteStderr(format, ...)
2394
2395 The first function writes to sys.stdout; the second to sys.stderr. When
2396 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002397 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002398
Victor Stinner14284c22010-04-23 12:02:30 +00002399 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002400 signal handlers: they may raise a new exception whereas sys_write()
2401 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002402
Guido van Rossuma890e681998-05-12 14:59:24 +00002403 Both take a printf-style format string as their first argument followed
2404 by a variable length argument list determined by the format string.
2405
2406 *** WARNING ***
2407
2408 The format should limit the total size of the formatted output string to
2409 1000 bytes. In particular, this means that no unrestricted "%s" formats
2410 should occur; these should be limited using "%.<N>s where <N> is a
2411 decimal number calculated so that <N> plus the maximum size of other
2412 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2413 which can print hundreds of digits for very large numbers.
2414
2415 */
2416
2417static void
Victor Stinner09054372013-11-06 22:41:44 +01002418sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002419{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 PyObject *file;
2421 PyObject *error_type, *error_value, *error_traceback;
2422 char buffer[1001];
2423 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002424
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002426 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2428 if (sys_pyfile_write(buffer, file) != 0) {
2429 PyErr_Clear();
2430 fputs(buffer, fp);
2431 }
2432 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2433 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002434 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 }
2437 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002438}
2439
2440void
Guido van Rossuma890e681998-05-12 14:59:24 +00002441PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002446 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002447 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002448}
2449
2450void
Guido van Rossuma890e681998-05-12 14:59:24 +00002451PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002452{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002453 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002456 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002457 va_end(va);
2458}
2459
2460static void
Victor Stinner09054372013-11-06 22:41:44 +01002461sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002462{
2463 PyObject *file, *message;
2464 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002465 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002466
2467 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002468 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002469 message = PyUnicode_FromFormatV(format, va);
2470 if (message != NULL) {
2471 if (sys_pyfile_write_unicode(message, file) != 0) {
2472 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002473 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002474 if (utf8 != NULL)
2475 fputs(utf8, fp);
2476 }
2477 Py_DECREF(message);
2478 }
2479 PyErr_Restore(error_type, error_value, error_traceback);
2480}
2481
2482void
2483PySys_FormatStdout(const char *format, ...)
2484{
2485 va_list va;
2486
2487 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002488 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002489 va_end(va);
2490}
2491
2492void
2493PySys_FormatStderr(const char *format, ...)
2494{
2495 va_list va;
2496
2497 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002498 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002500}