blob: 021b95d2c3d4449debc68b161aaf833cda6e6e2d [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 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000352static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000353
354static int
355trace_init(void)
356{
Nick Coghlan5a851672017-09-08 10:14:16 +1000357 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200358 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000359 "c_call", "c_exception", "c_return",
360 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200361 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyObject *name;
363 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000364 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (whatstrings[i] == NULL) {
366 name = PyUnicode_InternFromString(whatnames[i]);
367 if (name == NULL)
368 return -1;
369 whatstrings[i] = name;
370 }
371 }
372 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000373}
374
375
376static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100377call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200381 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000382
Victor Stinner78da82b2016-08-20 01:22:57 +0200383 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200385 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100386
Victor Stinner78da82b2016-08-20 01:22:57 +0200387 stack[0] = (PyObject *)frame;
388 stack[1] = whatstrings[what];
389 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000391 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200392 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000393
Victor Stinner78da82b2016-08-20 01:22:57 +0200394 PyFrame_LocalsToFast(frame, 1);
395 if (result == NULL) {
396 PyTraceBack_Here(frame);
397 }
398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000400}
401
402static int
403profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000407
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 if (arg == NULL)
409 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100410 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (result == NULL) {
412 PyEval_SetProfile(NULL, NULL);
413 return -1;
414 }
415 Py_DECREF(result);
416 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000417}
418
419static int
420trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 PyObject *callback;
424 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 if (what == PyTrace_CALL)
427 callback = self;
428 else
429 callback = frame->f_trace;
430 if (callback == NULL)
431 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100432 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 if (result == NULL) {
434 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200435 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return -1;
437 }
438 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300439 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 }
441 else {
442 Py_DECREF(result);
443 }
444 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000445}
Fred Draked0838392001-06-16 21:02:31 +0000446
Fred Drake8b4d01d2000-05-09 19:57:01 +0000447static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000448sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (trace_init() == -1)
451 return NULL;
452 if (args == Py_None)
453 PyEval_SetTrace(NULL, NULL);
454 else
455 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200456 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000457}
458
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000459PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000460"settrace(function)\n\
461\n\
462Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000463function call. See the debugger chapter in the library manual."
464);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000465
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000466static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000467sys_gettrace(PyObject *self, PyObject *args)
468{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 PyThreadState *tstate = PyThreadState_GET();
470 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 if (temp == NULL)
473 temp = Py_None;
474 Py_INCREF(temp);
475 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000476}
477
478PyDoc_STRVAR(gettrace_doc,
479"gettrace()\n\
480\n\
481Return the global debug tracing function set with sys.settrace.\n\
482See the debugger chapter in the library manual."
483);
484
485static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000486sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 if (trace_init() == -1)
489 return NULL;
490 if (args == Py_None)
491 PyEval_SetProfile(NULL, NULL);
492 else
493 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200494 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000495}
496
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000497PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000498"setprofile(function)\n\
499\n\
500Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000501and return. See the profiler chapter in the library manual."
502);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000503
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000504static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000505sys_getprofile(PyObject *self, PyObject *args)
506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyThreadState *tstate = PyThreadState_GET();
508 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (temp == NULL)
511 temp = Py_None;
512 Py_INCREF(temp);
513 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000514}
515
516PyDoc_STRVAR(getprofile_doc,
517"getprofile()\n\
518\n\
519Return the profiling function set with sys.setprofile.\n\
520See the profiler chapter in the library manual."
521);
522
Eric Snow05351c12017-09-05 21:43:08 -0700523static int _check_interval = 100;
524
Christian Heimes9bd667a2008-01-20 15:14:11 +0000525static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000526sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (PyErr_WarnEx(PyExc_DeprecationWarning,
529 "sys.getcheckinterval() and sys.setcheckinterval() "
530 "are deprecated. Use sys.setswitchinterval() "
531 "instead.", 1) < 0)
532 return NULL;
Eric Snow05351c12017-09-05 21:43:08 -0700533 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200535 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000536}
537
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000538PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000539"setcheckinterval(n)\n\
540\n\
541Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000542n instructions. This also affects how often thread switches occur."
543);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000544
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000545static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000546sys_getcheckinterval(PyObject *self, PyObject *args)
547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (PyErr_WarnEx(PyExc_DeprecationWarning,
549 "sys.getcheckinterval() and sys.setcheckinterval() "
550 "are deprecated. Use sys.getswitchinterval() "
551 "instead.", 1) < 0)
552 return NULL;
Eric Snow05351c12017-09-05 21:43:08 -0700553 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000554}
555
556PyDoc_STRVAR(getcheckinterval_doc,
557"getcheckinterval() -> current check interval; see setcheckinterval()."
558);
559
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000560static PyObject *
561sys_setswitchinterval(PyObject *self, PyObject *args)
562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 double d;
564 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
565 return NULL;
566 if (d <= 0.0) {
567 PyErr_SetString(PyExc_ValueError,
568 "switch interval must be strictly positive");
569 return NULL;
570 }
571 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200572 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000573}
574
575PyDoc_STRVAR(setswitchinterval_doc,
576"setswitchinterval(n)\n\
577\n\
578Set the ideal thread switching delay inside the Python interpreter\n\
579The actual frequency of switching threads can be lower if the\n\
580interpreter executes long sequences of uninterruptible code\n\
581(this is implementation-specific and workload-dependent).\n\
582\n\
583The parameter must represent the desired switching delay in seconds\n\
584A typical value is 0.005 (5 milliseconds)."
585);
586
587static PyObject *
588sys_getswitchinterval(PyObject *self, PyObject *args)
589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000591}
592
593PyDoc_STRVAR(getswitchinterval_doc,
594"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
595);
596
Tim Peterse5e065b2003-07-06 18:36:54 +0000597static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000598sys_setrecursionlimit(PyObject *self, PyObject *args)
599{
Victor Stinner50856d52015-10-13 00:11:21 +0200600 int new_limit, mark;
601 PyThreadState *tstate;
602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
604 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200605
606 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200608 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 return NULL;
610 }
Victor Stinner50856d52015-10-13 00:11:21 +0200611
612 /* Issue #25274: When the recursion depth hits the recursion limit in
613 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
614 set to 1 and a RecursionError is raised. The overflowed flag is reset
615 to 0 when the recursion depth goes below the low-water mark: see
616 Py_LeaveRecursiveCall().
617
618 Reject too low new limit if the current recursion depth is higher than
619 the new low-water mark. Otherwise it may not be possible anymore to
620 reset the overflowed flag to 0. */
621 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
622 tstate = PyThreadState_GET();
623 if (tstate->recursion_depth >= mark) {
624 PyErr_Format(PyExc_RecursionError,
625 "cannot set the recursion limit to %i at "
626 "the recursion depth %i: the limit is too low",
627 new_limit, tstate->recursion_depth);
628 return NULL;
629 }
630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200632 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000633}
634
Yury Selivanov75445082015-05-11 22:57:16 -0400635static PyObject *
636sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
637{
638 if (wrapper != Py_None) {
639 if (!PyCallable_Check(wrapper)) {
640 PyErr_Format(PyExc_TypeError,
641 "callable expected, got %.50s",
642 Py_TYPE(wrapper)->tp_name);
643 return NULL;
644 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400645 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400646 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400647 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400648 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400649 }
Yury Selivanov75445082015-05-11 22:57:16 -0400650 Py_RETURN_NONE;
651}
652
653PyDoc_STRVAR(set_coroutine_wrapper_doc,
654"set_coroutine_wrapper(wrapper)\n\
655\n\
656Set a wrapper for coroutine objects."
657);
658
659static PyObject *
660sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
661{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400662 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400663 if (wrapper == NULL) {
664 wrapper = Py_None;
665 }
666 Py_INCREF(wrapper);
667 return wrapper;
668}
669
670PyDoc_STRVAR(get_coroutine_wrapper_doc,
671"get_coroutine_wrapper()\n\
672\n\
673Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
674);
675
676
Yury Selivanoveb636452016-09-08 22:01:51 -0700677static PyTypeObject AsyncGenHooksType;
678
679PyDoc_STRVAR(asyncgen_hooks_doc,
680"asyncgen_hooks\n\
681\n\
682A struct sequence providing information about asynhronous\n\
683generators hooks. The attributes are read only.");
684
685static PyStructSequence_Field asyncgen_hooks_fields[] = {
686 {"firstiter", "Hook to intercept first iteration"},
687 {"finalizer", "Hook to intercept finalization"},
688 {0}
689};
690
691static PyStructSequence_Desc asyncgen_hooks_desc = {
692 "asyncgen_hooks", /* name */
693 asyncgen_hooks_doc, /* doc */
694 asyncgen_hooks_fields , /* fields */
695 2
696};
697
698
699static PyObject *
700sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
701{
702 static char *keywords[] = {"firstiter", "finalizer", NULL};
703 PyObject *firstiter = NULL;
704 PyObject *finalizer = NULL;
705
706 if (!PyArg_ParseTupleAndKeywords(
707 args, kw, "|OO", keywords,
708 &firstiter, &finalizer)) {
709 return NULL;
710 }
711
712 if (finalizer && finalizer != Py_None) {
713 if (!PyCallable_Check(finalizer)) {
714 PyErr_Format(PyExc_TypeError,
715 "callable finalizer expected, got %.50s",
716 Py_TYPE(finalizer)->tp_name);
717 return NULL;
718 }
719 _PyEval_SetAsyncGenFinalizer(finalizer);
720 }
721 else if (finalizer == Py_None) {
722 _PyEval_SetAsyncGenFinalizer(NULL);
723 }
724
725 if (firstiter && firstiter != Py_None) {
726 if (!PyCallable_Check(firstiter)) {
727 PyErr_Format(PyExc_TypeError,
728 "callable firstiter expected, got %.50s",
729 Py_TYPE(firstiter)->tp_name);
730 return NULL;
731 }
732 _PyEval_SetAsyncGenFirstiter(firstiter);
733 }
734 else if (firstiter == Py_None) {
735 _PyEval_SetAsyncGenFirstiter(NULL);
736 }
737
738 Py_RETURN_NONE;
739}
740
741PyDoc_STRVAR(set_asyncgen_hooks_doc,
742"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
743\n\
744Set a finalizer for async generators objects."
745);
746
747static PyObject *
748sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
749{
750 PyObject *res;
751 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
752 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
753
754 res = PyStructSequence_New(&AsyncGenHooksType);
755 if (res == NULL) {
756 return NULL;
757 }
758
759 if (firstiter == NULL) {
760 firstiter = Py_None;
761 }
762
763 if (finalizer == NULL) {
764 finalizer = Py_None;
765 }
766
767 Py_INCREF(firstiter);
768 PyStructSequence_SET_ITEM(res, 0, firstiter);
769
770 Py_INCREF(finalizer);
771 PyStructSequence_SET_ITEM(res, 1, finalizer);
772
773 return res;
774}
775
776PyDoc_STRVAR(get_asyncgen_hooks_doc,
777"get_asyncgen_hooks()\n\
778\n\
779Return a namedtuple of installed asynchronous generators hooks \
780(firstiter, finalizer)."
781);
782
783
Mark Dickinsondc787d22010-05-23 13:33:13 +0000784static PyTypeObject Hash_InfoType;
785
786PyDoc_STRVAR(hash_info_doc,
787"hash_info\n\
788\n\
789A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100790hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000791
792static PyStructSequence_Field hash_info_fields[] = {
793 {"width", "width of the type used for hashing, in bits"},
794 {"modulus", "prime number giving the modulus on which the hash "
795 "function is based"},
796 {"inf", "value to be used for hash of a positive infinity"},
797 {"nan", "value to be used for hash of a nan"},
798 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100799 {"algorithm", "name of the algorithm for hashing of str, bytes and "
800 "memoryviews"},
801 {"hash_bits", "internal output size of hash algorithm"},
802 {"seed_bits", "seed size of hash algorithm"},
803 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000804 {NULL, NULL}
805};
806
807static PyStructSequence_Desc hash_info_desc = {
808 "sys.hash_info",
809 hash_info_doc,
810 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100811 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000812};
813
Matthias Klosed885e952010-07-06 10:53:30 +0000814static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000815get_hash_info(void)
816{
817 PyObject *hash_info;
818 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100819 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000820 hash_info = PyStructSequence_New(&Hash_InfoType);
821 if (hash_info == NULL)
822 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100823 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000824 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000825 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000826 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000827 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000828 PyStructSequence_SET_ITEM(hash_info, field++,
829 PyLong_FromLong(_PyHASH_INF));
830 PyStructSequence_SET_ITEM(hash_info, field++,
831 PyLong_FromLong(_PyHASH_NAN));
832 PyStructSequence_SET_ITEM(hash_info, field++,
833 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100834 PyStructSequence_SET_ITEM(hash_info, field++,
835 PyUnicode_FromString(hashfunc->name));
836 PyStructSequence_SET_ITEM(hash_info, field++,
837 PyLong_FromLong(hashfunc->hash_bits));
838 PyStructSequence_SET_ITEM(hash_info, field++,
839 PyLong_FromLong(hashfunc->seed_bits));
840 PyStructSequence_SET_ITEM(hash_info, field++,
841 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000842 if (PyErr_Occurred()) {
843 Py_CLEAR(hash_info);
844 return NULL;
845 }
846 return hash_info;
847}
848
849
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000850PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000851"setrecursionlimit(n)\n\
852\n\
853Set the maximum depth of the Python interpreter stack to n. This\n\
854limit prevents infinite recursion from causing an overflow of the C\n\
855stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000856dependent."
857);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000858
859static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000860sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000863}
864
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000865PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000866"getrecursionlimit()\n\
867\n\
868Return the current value of the recursion limit, the maximum depth\n\
869of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000870recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000871);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000872
Mark Hammond8696ebc2002-10-08 02:44:31 +0000873#ifdef MS_WINDOWS
874PyDoc_STRVAR(getwindowsversion_doc,
875"getwindowsversion()\n\
876\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000877Return information about the running version of Windows as a named tuple.\n\
878The members are named: major, minor, build, platform, service_pack,\n\
879service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200880backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700881All elements are numbers, except service_pack and platform_type which are\n\
882strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
883Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
884server. Platform_version is a 3-tuple containing a version number that is\n\
885intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000886);
887
Eric Smithf7bb5782010-01-27 00:44:57 +0000888static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
889
890static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000891 {"major", "Major version number"},
892 {"minor", "Minor version number"},
893 {"build", "Build number"},
894 {"platform", "Operating system platform"},
895 {"service_pack", "Latest Service Pack installed on the system"},
896 {"service_pack_major", "Service Pack major version number"},
897 {"service_pack_minor", "Service Pack minor version number"},
898 {"suite_mask", "Bit mask identifying available product suites"},
899 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700900 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000901 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000902};
903
904static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000905 "sys.getwindowsversion", /* name */
906 getwindowsversion_doc, /* doc */
907 windows_version_fields, /* fields */
908 5 /* For backward compatibility,
909 only the first 5 items are accessible
910 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000911};
912
Steve Dower3e96f322015-03-02 08:01:10 -0800913/* Disable deprecation warnings about GetVersionEx as the result is
914 being passed straight through to the caller, who is responsible for
915 using it correctly. */
916#pragma warning(push)
917#pragma warning(disable:4996)
918
Mark Hammond8696ebc2002-10-08 02:44:31 +0000919static PyObject *
920sys_getwindowsversion(PyObject *self)
921{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 PyObject *version;
923 int pos = 0;
924 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -0700925 DWORD realMajor, realMinor, realBuild;
926 HANDLE hKernel32;
927 wchar_t kernel32_path[MAX_PATH];
928 LPVOID verblock;
929 DWORD verblock_size;
930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 ver.dwOSVersionInfoSize = sizeof(ver);
932 if (!GetVersionEx((OSVERSIONINFO*) &ver))
933 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000934
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 version = PyStructSequence_New(&WindowsVersionType);
936 if (version == NULL)
937 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000938
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000939 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
940 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
941 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
942 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
943 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
944 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
945 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
946 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
947 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000948
Steve Dower74f4af72016-09-17 17:27:48 -0700949 realMajor = ver.dwMajorVersion;
950 realMinor = ver.dwMinorVersion;
951 realBuild = ver.dwBuildNumber;
952
953 // GetVersion will lie if we are running in a compatibility mode.
954 // We need to read the version info from a system file resource
955 // to accurately identify the OS version. If we fail for any reason,
956 // just return whatever GetVersion said.
957 hKernel32 = GetModuleHandleW(L"kernel32.dll");
958 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
959 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
960 (verblock = PyMem_RawMalloc(verblock_size))) {
961 VS_FIXEDFILEINFO *ffi;
962 UINT ffi_len;
963
964 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
965 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
966 realMajor = HIWORD(ffi->dwProductVersionMS);
967 realMinor = LOWORD(ffi->dwProductVersionMS);
968 realBuild = HIWORD(ffi->dwProductVersionLS);
969 }
970 PyMem_RawFree(verblock);
971 }
Segev Finer48fb7662017-06-04 20:52:27 +0300972 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
973 realMajor,
974 realMinor,
975 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -0700976 ));
977
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200978 if (PyErr_Occurred()) {
979 Py_DECREF(version);
980 return NULL;
981 }
Steve Dower74f4af72016-09-17 17:27:48 -0700982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000984}
985
Steve Dower3e96f322015-03-02 08:01:10 -0800986#pragma warning(pop)
987
Steve Dowercc16be82016-09-08 10:35:16 -0700988PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
989"_enablelegacywindowsfsencoding()\n\
990\n\
991Changes the default filesystem encoding to mbcs:replace for consistency\n\
992with earlier versions of Python. See PEP 529 for more information.\n\
993\n\
994This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
995environment variable before launching Python."
996);
997
998static PyObject *
999sys_enablelegacywindowsfsencoding(PyObject *self)
1000{
1001 Py_FileSystemDefaultEncoding = "mbcs";
1002 Py_FileSystemDefaultEncodeErrors = "replace";
1003 Py_RETURN_NONE;
1004}
1005
Mark Hammond8696ebc2002-10-08 02:44:31 +00001006#endif /* MS_WINDOWS */
1007
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001008#ifdef HAVE_DLOPEN
1009static PyObject *
1010sys_setdlopenflags(PyObject *self, PyObject *args)
1011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 int new_val;
1013 PyThreadState *tstate = PyThreadState_GET();
1014 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1015 return NULL;
1016 if (!tstate)
1017 return NULL;
1018 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001019 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001020}
1021
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001022PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001023"setdlopenflags(n) -> None\n\
1024\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001025Set the flags used by the interpreter for dlopen calls, such as when the\n\
1026interpreter loads extension modules. Among other things, this will enable\n\
1027a lazy resolving of symbols when importing a module, if called as\n\
1028sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001029sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001030can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001031
1032static PyObject *
1033sys_getdlopenflags(PyObject *self, PyObject *args)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyThreadState *tstate = PyThreadState_GET();
1036 if (!tstate)
1037 return NULL;
1038 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001039}
1040
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001041PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001042"getdlopenflags() -> int\n\
1043\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001044Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001045The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001048
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001049#ifdef USE_MALLOPT
1050/* Link with -lmalloc (or -lmpc) on an SGI */
1051#include <malloc.h>
1052
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001053static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001054sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 int flag;
1057 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1058 return NULL;
1059 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001060 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001061}
1062#endif /* USE_MALLOPT */
1063
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001064size_t
1065_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001069 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 /* Make sure the type is initialized. float gets initialized late */
1072 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001073 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001074
Benjamin Petersonce798522012-01-22 11:24:29 -05001075 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (method == NULL) {
1077 if (!PyErr_Occurred())
1078 PyErr_Format(PyExc_TypeError,
1079 "Type %.100s doesn't define __sizeof__",
1080 Py_TYPE(o)->tp_name);
1081 }
1082 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001083 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 Py_DECREF(method);
1085 }
1086
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001087 if (res == NULL)
1088 return (size_t)-1;
1089
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001090 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001091 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001092 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001093 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001095 if (size < 0) {
1096 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1097 return (size_t)-1;
1098 }
1099
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001100 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001101 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001102 return ((size_t)size) + sizeof(PyGC_Head);
1103 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001104}
1105
1106static PyObject *
1107sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1108{
1109 static char *kwlist[] = {"object", "default", 0};
1110 size_t size;
1111 PyObject *o, *dflt = NULL;
1112
1113 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1114 kwlist, &o, &dflt))
1115 return NULL;
1116
1117 size = _PySys_GetSizeOf(o);
1118
1119 if (size == (size_t)-1 && PyErr_Occurred()) {
1120 /* Has a default value been given */
1121 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1122 PyErr_Clear();
1123 Py_INCREF(dflt);
1124 return dflt;
1125 }
1126 else
1127 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001129
1130 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001131}
1132
1133PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001134"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001135\n\
1136Return the size of object in bytes.");
1137
1138static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001139sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001140{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001142}
1143
Tim Peters4be93d02002-07-07 19:59:50 +00001144#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001145static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001146sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001148 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001149}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001150#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001151
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001152PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001153"getrefcount(object) -> integer\n\
1154\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001155Return the reference count of object. The count returned is generally\n\
1156one higher than you might expect, because it includes the (temporary)\n\
1157reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001158);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001159
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001160static PyObject *
1161sys_getallocatedblocks(PyObject *self)
1162{
1163 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1164}
1165
1166PyDoc_STRVAR(getallocatedblocks_doc,
1167"getallocatedblocks() -> integer\n\
1168\n\
1169Return the number of memory blocks currently allocated, regardless of their\n\
1170size."
1171);
1172
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001173#ifdef COUNT_ALLOCS
1174static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001175sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001178
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001180}
1181#endif
1182
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001183PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001184"_getframe([depth]) -> frameobject\n\
1185\n\
1186Return a frame object from the call stack. If optional integer depth is\n\
1187given, return the frame object that many calls below the top of the stack.\n\
1188If that is deeper than the call stack, ValueError is raised. The default\n\
1189for depth is zero, returning the frame at the top of the call stack.\n\
1190\n\
1191This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001192purposes only."
1193);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001194
1195static PyObject *
1196sys_getframe(PyObject *self, PyObject *args)
1197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyFrameObject *f = PyThreadState_GET()->frame;
1199 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001200
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1202 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 while (depth > 0 && f != NULL) {
1205 f = f->f_back;
1206 --depth;
1207 }
1208 if (f == NULL) {
1209 PyErr_SetString(PyExc_ValueError,
1210 "call stack is not deep enough");
1211 return NULL;
1212 }
1213 Py_INCREF(f);
1214 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001215}
1216
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001217PyDoc_STRVAR(current_frames_doc,
1218"_current_frames() -> dictionary\n\
1219\n\
1220Return a dictionary mapping each current thread T's thread id to T's\n\
1221current stack frame.\n\
1222\n\
1223This function should be used for specialized purposes only."
1224);
1225
1226static PyObject *
1227sys_current_frames(PyObject *self, PyObject *noargs)
1228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001230}
1231
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001232PyDoc_STRVAR(call_tracing_doc,
1233"call_tracing(func, args) -> object\n\
1234\n\
1235Call func(*args), while tracing is enabled. The tracing state is\n\
1236saved, and restored afterwards. This is intended to be called from\n\
1237a debugger from a checkpoint, to recursively debug some other code."
1238);
1239
1240static PyObject *
1241sys_call_tracing(PyObject *self, PyObject *args)
1242{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 PyObject *func, *funcargs;
1244 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1245 return NULL;
1246 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001247}
1248
Jeremy Hylton985eba52003-02-05 23:13:00 +00001249PyDoc_STRVAR(callstats_doc,
1250"callstats() -> tuple of integers\n\
1251\n\
1252Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1253when Python was built. Otherwise, return None.\n\
1254\n\
1255When enabled, this function returns detailed, implementation-specific\n\
1256details about the number of function calls executed. The return value is\n\
1257a 11-tuple where the entries in the tuple are counts of:\n\
12580. all function calls\n\
12591. calls to PyFunction_Type objects\n\
12602. PyFunction calls that do not create an argument tuple\n\
12613. PyFunction calls that do not create an argument tuple\n\
1262 and bypass PyEval_EvalCodeEx()\n\
12634. PyMethod calls\n\
12645. PyMethod calls on bound methods\n\
12656. PyType calls\n\
12667. PyCFunction calls\n\
12678. generator calls\n\
12689. All other calls\n\
126910. Number of stack pops performed by call_function()"
1270);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001271
Victor Stinner048afd92016-11-28 11:59:04 +01001272static PyObject *
1273sys_callstats(PyObject *self)
1274{
1275 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1276 "sys.callstats() has been deprecated in Python 3.7 "
1277 "and will be removed in the future", 1) < 0) {
1278 return NULL;
1279 }
1280
1281 Py_RETURN_NONE;
1282}
1283
1284
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001285#ifdef __cplusplus
1286extern "C" {
1287#endif
1288
David Malcolm49526f42012-06-22 14:55:41 -04001289static PyObject *
1290sys_debugmallocstats(PyObject *self, PyObject *args)
1291{
1292#ifdef WITH_PYMALLOC
Victor Stinner34be8072016-03-14 12:04:26 +01001293 if (_PyMem_PymallocEnabled()) {
1294 _PyObject_DebugMallocStats(stderr);
1295 fputc('\n', stderr);
1296 }
David Malcolm49526f42012-06-22 14:55:41 -04001297#endif
1298 _PyObject_DebugTypeStats(stderr);
1299
1300 Py_RETURN_NONE;
1301}
1302PyDoc_STRVAR(debugmallocstats_doc,
1303"_debugmallocstats()\n\
1304\n\
1305Print summary info to stderr about the state of\n\
1306pymalloc's structures.\n\
1307\n\
1308In Py_DEBUG mode, also perform some expensive internal consistency\n\
1309checks.\n\
1310");
1311
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001312#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001313/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001314extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001315#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001316
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001317#ifdef DYNAMIC_EXECUTION_PROFILE
1318/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001319extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001320#endif
1321
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001322#ifdef __cplusplus
1323}
1324#endif
1325
Christian Heimes15ebc882008-02-04 18:48:49 +00001326static PyObject *
1327sys_clear_type_cache(PyObject* self, PyObject* args)
1328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyType_ClearCache();
1330 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001331}
1332
1333PyDoc_STRVAR(sys_clear_type_cache__doc__,
1334"_clear_type_cache() -> None\n\
1335Clear the internal type lookup cache.");
1336
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001337static PyObject *
1338sys_is_finalizing(PyObject* self, PyObject* args)
1339{
Eric Snow05351c12017-09-05 21:43:08 -07001340 return PyBool_FromLong(_Py_Finalizing != NULL);
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001341}
1342
1343PyDoc_STRVAR(is_finalizing_doc,
1344"is_finalizing()\n\
1345Return True if Python is exiting.");
1346
Christian Heimes15ebc882008-02-04 18:48:49 +00001347
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001348#ifdef ANDROID_API_LEVEL
1349PyDoc_STRVAR(getandroidapilevel_doc,
1350"getandroidapilevel()\n\
1351\n\
1352Return the build time API version of Android as an integer.");
1353
1354static PyObject *
1355sys_getandroidapilevel(PyObject *self)
1356{
1357 return PyLong_FromLong(ANDROID_API_LEVEL);
1358}
1359#endif /* ANDROID_API_LEVEL */
1360
1361
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001362static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001363 /* Might as well keep this in alphabetic order */
Victor Stinner048afd92016-11-28 11:59:04 +01001364 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 callstats_doc},
1366 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1367 sys_clear_type_cache__doc__},
1368 {"_current_frames", sys_current_frames, METH_NOARGS,
1369 current_frames_doc},
1370 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1371 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1372 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1373 {"exit", sys_exit, METH_VARARGS, exit_doc},
1374 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1375 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001376#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1378 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001379#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001380 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1381 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001382#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001384#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001385#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001387#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1389 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001390 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1391 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001392#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001394#endif
1395#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001397#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1399 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1400 getrecursionlimit_doc},
1401 {"getsizeof", (PyCFunction)sys_getsizeof,
1402 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1403 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001404#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1406 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001407 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1408 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001409#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001411 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001412#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001414#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1416 setcheckinterval_doc},
1417 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1418 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1420 setswitchinterval_doc},
1421 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1422 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001423#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1425 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001426#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1428 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1429 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1430 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 {"settrace", sys_settrace, METH_O, settrace_doc},
1432 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1433 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001434 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001435 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001436 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1437 set_coroutine_wrapper_doc},
1438 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1439 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001440 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001441 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1442 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1443 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001444#ifdef ANDROID_API_LEVEL
1445 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1446 getandroidapilevel_doc},
1447#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001449};
1450
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001451static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001452list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001454 PyObject *list = PyList_New(0);
1455 int i;
1456 if (list == NULL)
1457 return NULL;
1458 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1459 PyObject *name = PyUnicode_FromString(
1460 PyImport_Inittab[i].name);
1461 if (name == NULL)
1462 break;
1463 PyList_Append(list, name);
1464 Py_DECREF(name);
1465 }
1466 if (PyList_Sort(list) != 0) {
1467 Py_DECREF(list);
1468 list = NULL;
1469 }
1470 if (list) {
1471 PyObject *v = PyList_AsTuple(list);
1472 Py_DECREF(list);
1473 list = v;
1474 }
1475 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001476}
1477
Eric Snow05351c12017-09-05 21:43:08 -07001478static PyObject *warnoptions = NULL;
Guido van Rossum23fff912000-12-15 22:02:05 +00001479
1480void
1481PySys_ResetWarnOptions(void)
1482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 if (warnoptions == NULL || !PyList_Check(warnoptions))
1484 return;
1485 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001486}
1487
1488void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001489PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001490{
Eric Snow05351c12017-09-05 21:43:08 -07001491 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1492 Py_XDECREF(warnoptions);
1493 warnoptions = PyList_New(0);
1494 if (warnoptions == NULL)
1495 return;
1496 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001497 PyList_Append(warnoptions, unicode);
1498}
1499
1500void
1501PySys_AddWarnOption(const wchar_t *s)
1502{
1503 PyObject *unicode;
1504 unicode = PyUnicode_FromWideChar(s, -1);
1505 if (unicode == NULL)
1506 return;
1507 PySys_AddWarnOptionUnicode(unicode);
1508 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001509}
1510
Christian Heimes33fe8092008-04-13 13:53:33 +00001511int
1512PySys_HasWarnOptions(void)
1513{
1514 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1515}
1516
Eric Snow05351c12017-09-05 21:43:08 -07001517static PyObject *xoptions = NULL;
1518
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001519static PyObject *
1520get_xoptions(void)
1521{
1522 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1523 Py_XDECREF(xoptions);
1524 xoptions = PyDict_New();
1525 }
1526 return xoptions;
1527}
1528
1529void
1530PySys_AddXOption(const wchar_t *s)
1531{
1532 PyObject *opts;
1533 PyObject *name = NULL, *value = NULL;
1534 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001535
1536 opts = get_xoptions();
1537 if (opts == NULL)
1538 goto error;
1539
1540 name_end = wcschr(s, L'=');
1541 if (!name_end) {
1542 name = PyUnicode_FromWideChar(s, -1);
1543 value = Py_True;
1544 Py_INCREF(value);
1545 }
1546 else {
1547 name = PyUnicode_FromWideChar(s, name_end - s);
1548 value = PyUnicode_FromWideChar(name_end + 1, -1);
1549 }
1550 if (name == NULL || value == NULL)
1551 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001552 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001553 Py_DECREF(name);
1554 Py_DECREF(value);
1555 return;
1556
1557error:
1558 Py_XDECREF(name);
1559 Py_XDECREF(value);
1560 /* No return value, therefore clear error state if possible */
Victor Stinner0cae6092016-11-11 01:43:56 +01001561 if (_PyThreadState_UncheckedGet()) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001562 PyErr_Clear();
Victor Stinner0cae6092016-11-11 01:43:56 +01001563 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001564}
1565
1566PyObject *
1567PySys_GetXOptions(void)
1568{
1569 return get_xoptions();
1570}
1571
Guido van Rossum40552d01998-08-06 03:34:39 +00001572/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1573 Two literals concatenated works just fine. If you have a K&R compiler
1574 or other abomination that however *does* understand longer strings,
1575 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001576PyDoc_VAR(sys_doc) =
1577PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001578"This module provides access to some objects used or maintained by the\n\
1579interpreter and to functions that interact strongly with the interpreter.\n\
1580\n\
1581Dynamic objects:\n\
1582\n\
1583argv -- command line arguments; argv[0] is the script pathname if known\n\
1584path -- module search path; path[0] is the script directory, else ''\n\
1585modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001586\n\
1587displayhook -- called to show results in an interactive session\n\
1588excepthook -- called to handle any uncaught exception other than SystemExit\n\
1589 To customize printing in an interactive session or to install a custom\n\
1590 top-level exception handler, assign other functions to replace these.\n\
1591\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001592stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001593stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001594stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001595 By assigning other file objects (or objects that behave like files)\n\
1596 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001597\n\
1598last_type -- type of last uncaught exception\n\
1599last_value -- value of last uncaught exception\n\
1600last_traceback -- traceback of last uncaught exception\n\
1601 These three are only available in an interactive session after a\n\
1602 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001603"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001604)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001605/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001606PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001607"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001608Static objects:\n\
1609\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001610builtin_module_names -- tuple of module names built into this interpreter\n\
1611copyright -- copyright notice pertaining to this interpreter\n\
1612exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001613executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001614float_info -- a struct sequence with information about the float implementation.\n\
1615float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001616hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001617hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001618implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001619int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001620maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001621maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001622platform -- platform identifier\n\
1623prefix -- prefix used to find the Python library\n\
1624thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001625version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001626version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001627"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001628)
Steve Dowercc16be82016-09-08 10:35:16 -07001629#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001630/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001631PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001632"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001633winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001634"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001635)
Steve Dowercc16be82016-09-08 10:35:16 -07001636#endif /* MS_COREDLL */
1637#ifdef MS_WINDOWS
1638/* concatenating string here */
1639PyDoc_STR(
1640"_enablelegacywindowsfsencoding -- [Windows only] \n\
1641"
1642)
1643#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001644PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001645"__stdin__ -- the original stdin; don't touch!\n\
1646__stdout__ -- the original stdout; don't touch!\n\
1647__stderr__ -- the original stderr; don't touch!\n\
1648__displayhook__ -- the original displayhook; don't touch!\n\
1649__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001650\n\
1651Functions:\n\
1652\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001653displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001654excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001655exc_info() -- return thread-safe information about the current exception\n\
1656exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001657getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001658getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001659getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001660getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001661getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001662gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001663setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001664setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001665setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001666setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001667settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001668"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001669)
Fred Drakeccede592000-08-14 20:59:57 +00001670/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001671
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001672
1673PyDoc_STRVAR(flags__doc__,
1674"sys.flags\n\
1675\n\
1676Flags provided through command line arguments or environment vars.");
1677
1678static PyTypeObject FlagsType;
1679
1680static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 {"inspect", "-i"},
1683 {"interactive", "-i"},
1684 {"optimize", "-O or -OO"},
1685 {"dont_write_bytecode", "-B"},
1686 {"no_user_site", "-s"},
1687 {"no_site", "-S"},
1688 {"ignore_environment", "-E"},
1689 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 /* {"unbuffered", "-u"}, */
1691 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001692 {"bytes_warning", "-b"},
1693 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001694 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001695 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001697};
1698
1699static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 "sys.flags", /* name */
1701 flags__doc__, /* doc */
1702 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001703 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001704};
1705
1706static PyObject*
1707make_flags(void)
1708{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 int pos = 0;
1710 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 seq = PyStructSequence_New(&FlagsType);
1713 if (seq == NULL)
1714 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001715
1716#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001718
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 SetFlag(Py_InspectFlag);
1721 SetFlag(Py_InteractiveFlag);
1722 SetFlag(Py_OptimizeFlag);
1723 SetFlag(Py_DontWriteBytecodeFlag);
1724 SetFlag(Py_NoUserSiteDirectory);
1725 SetFlag(Py_NoSiteFlag);
1726 SetFlag(Py_IgnoreEnvironmentFlag);
1727 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001728 /* SetFlag(saw_unbuffered_flag); */
1729 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001730 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001731 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001732 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001733 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001734#undef SetFlag
1735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001737 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 return NULL;
1739 }
1740 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001741}
1742
Eric Smith0e5b5622009-02-06 01:32:42 +00001743PyDoc_STRVAR(version_info__doc__,
1744"sys.version_info\n\
1745\n\
1746Version information as a named tuple.");
1747
1748static PyTypeObject VersionInfoType;
1749
1750static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 {"major", "Major release number"},
1752 {"minor", "Minor release number"},
1753 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001754 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 {"serial", "Serial release number"},
1756 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001757};
1758
1759static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 "sys.version_info", /* name */
1761 version_info__doc__, /* doc */
1762 version_info_fields, /* fields */
1763 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001764};
1765
1766static PyObject *
1767make_version_info(void)
1768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001769 PyObject *version_info;
1770 char *s;
1771 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001772
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 version_info = PyStructSequence_New(&VersionInfoType);
1774 if (version_info == NULL) {
1775 return NULL;
1776 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /*
1779 * These release level checks are mutually exclusive and cover
1780 * the field, so don't get too fancy with the pre-processor!
1781 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001782#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001784#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001786#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001788#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001790#endif
1791
1792#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001794#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001796
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 SetIntItem(PY_MAJOR_VERSION);
1798 SetIntItem(PY_MINOR_VERSION);
1799 SetIntItem(PY_MICRO_VERSION);
1800 SetStrItem(s);
1801 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001802#undef SetIntItem
1803#undef SetStrItem
1804
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (PyErr_Occurred()) {
1806 Py_CLEAR(version_info);
1807 return NULL;
1808 }
1809 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001810}
1811
Brett Cannon3adc7b72012-07-09 14:22:12 -04001812/* sys.implementation values */
1813#define NAME "cpython"
1814const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001815#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1816#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001817#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001818const char *_PySys_ImplCacheTag = TAG;
1819#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001820#undef MAJOR
1821#undef MINOR
1822#undef TAG
1823
Barry Warsaw409da152012-06-03 16:18:47 -04001824static PyObject *
1825make_impl_info(PyObject *version_info)
1826{
1827 int res;
1828 PyObject *impl_info, *value, *ns;
1829
1830 impl_info = PyDict_New();
1831 if (impl_info == NULL)
1832 return NULL;
1833
1834 /* populate the dict */
1835
Brett Cannon3adc7b72012-07-09 14:22:12 -04001836 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001837 if (value == NULL)
1838 goto error;
1839 res = PyDict_SetItemString(impl_info, "name", value);
1840 Py_DECREF(value);
1841 if (res < 0)
1842 goto error;
1843
Brett Cannon3adc7b72012-07-09 14:22:12 -04001844 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001845 if (value == NULL)
1846 goto error;
1847 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1848 Py_DECREF(value);
1849 if (res < 0)
1850 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001851
1852 res = PyDict_SetItemString(impl_info, "version", version_info);
1853 if (res < 0)
1854 goto error;
1855
1856 value = PyLong_FromLong(PY_VERSION_HEX);
1857 if (value == NULL)
1858 goto error;
1859 res = PyDict_SetItemString(impl_info, "hexversion", value);
1860 Py_DECREF(value);
1861 if (res < 0)
1862 goto error;
1863
doko@ubuntu.com55532312016-06-14 08:55:19 +02001864#ifdef MULTIARCH
1865 value = PyUnicode_FromString(MULTIARCH);
1866 if (value == NULL)
1867 goto error;
1868 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1869 Py_DECREF(value);
1870 if (res < 0)
1871 goto error;
1872#endif
1873
Barry Warsaw409da152012-06-03 16:18:47 -04001874 /* dict ready */
1875
1876 ns = _PyNamespace_New(impl_info);
1877 Py_DECREF(impl_info);
1878 return ns;
1879
1880error:
1881 Py_CLEAR(impl_info);
1882 return NULL;
1883}
1884
Martin v. Löwis1a214512008-06-11 05:26:20 +00001885static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 PyModuleDef_HEAD_INIT,
1887 "sys",
1888 sys_doc,
1889 -1, /* multiple "initialization" just copies the module dict. */
1890 sys_methods,
1891 NULL,
1892 NULL,
1893 NULL,
1894 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001895};
1896
Eric Snow6b4be192017-05-22 21:36:03 -07001897/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01001898#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001899 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001900 PyObject *v = (value); \
1901 if (v == NULL) \
1902 return NULL; \
1903 res = PyDict_SetItemString(sysdict, key, v); \
1904 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001905 return NULL; \
1906 } \
1907 } while (0)
1908#define SET_SYS_FROM_STRING(key, value) \
1909 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001910 PyObject *v = (value); \
1911 if (v == NULL) \
1912 return NULL; \
1913 res = PyDict_SetItemString(sysdict, key, v); \
1914 Py_DECREF(v); \
1915 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001916 return NULL; \
1917 } \
1918 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001919
Eric Snow6b4be192017-05-22 21:36:03 -07001920PyObject *
1921_PySys_BeginInit(void)
1922{
1923 PyObject *m, *sysdict, *version_info;
1924 int res;
1925
Eric Snow86b7afd2017-09-04 17:54:09 -06001926 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Eric Snow6b4be192017-05-22 21:36:03 -07001927 if (m == NULL)
1928 return NULL;
1929 sysdict = PyModule_GetDict(m);
1930
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 /* Check that stdin is not a directory
1932 Using shell redirection, you can redirect stdin to a directory,
1933 crashing the Python interpreter. Catch this common mistake here
1934 and output a useful error message. Note that under MS Windows,
1935 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001936#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001937 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001938 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001939 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 S_ISDIR(sb.st_mode)) {
1941 /* There's nothing more we can do. */
1942 /* Py_FatalError() will core dump, so just exit. */
1943 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1944 exit(EXIT_FAILURE);
1945 }
1946 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001947#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001948
Nick Coghland6009512014-11-20 21:39:37 +10001949 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001950
Victor Stinner8fea2522013-10-27 17:15:42 +01001951 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1952 PyDict_GetItemString(sysdict, "displayhook"));
1953 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1954 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 SET_SYS_FROM_STRING("version",
1956 PyUnicode_FromString(Py_GetVersion()));
1957 SET_SYS_FROM_STRING("hexversion",
1958 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05001959 SET_SYS_FROM_STRING("_git",
1960 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
1961 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09001962 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 SET_SYS_FROM_STRING("api_version",
1964 PyLong_FromLong(PYTHON_API_VERSION));
1965 SET_SYS_FROM_STRING("copyright",
1966 PyUnicode_FromString(Py_GetCopyright()));
1967 SET_SYS_FROM_STRING("platform",
1968 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 SET_SYS_FROM_STRING("maxsize",
1970 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1971 SET_SYS_FROM_STRING("float_info",
1972 PyFloat_GetInfo());
1973 SET_SYS_FROM_STRING("int_info",
1974 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001975 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001976 if (Hash_InfoType.tp_name == NULL) {
1977 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1978 return NULL;
1979 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001980 SET_SYS_FROM_STRING("hash_info",
1981 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001983 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001984 SET_SYS_FROM_STRING("builtin_module_names",
1985 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001986#if PY_BIG_ENDIAN
1987 SET_SYS_FROM_STRING("byteorder",
1988 PyUnicode_FromString("big"));
1989#else
1990 SET_SYS_FROM_STRING("byteorder",
1991 PyUnicode_FromString("little"));
1992#endif
Fred Drake099325e2000-08-14 15:47:03 +00001993
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001994#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001995 SET_SYS_FROM_STRING("dllhandle",
1996 PyLong_FromVoidPtr(PyWin_DLLhModule));
1997 SET_SYS_FROM_STRING("winver",
1998 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001999#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002000#ifdef ABIFLAGS
2001 SET_SYS_FROM_STRING("abiflags",
2002 PyUnicode_FromString(ABIFLAGS));
2003#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002004
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002005 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002006 if (VersionInfoType.tp_name == NULL) {
2007 if (PyStructSequence_InitType2(&VersionInfoType,
2008 &version_info_desc) < 0)
2009 return NULL;
2010 }
Barry Warsaw409da152012-06-03 16:18:47 -04002011 version_info = make_version_info();
2012 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002013 /* prevent user from creating new instances */
2014 VersionInfoType.tp_init = NULL;
2015 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002016 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2017 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2018 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002019
Barry Warsaw409da152012-06-03 16:18:47 -04002020 /* implementation */
2021 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2022
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002024 if (FlagsType.tp_name == 0) {
2025 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
2026 return NULL;
2027 }
Eric Snow6b4be192017-05-22 21:36:03 -07002028 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002030
2031#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 /* getwindowsversion */
2033 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002034 if (PyStructSequence_InitType2(&WindowsVersionType,
2035 &windows_version_desc) < 0)
2036 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 /* prevent user from creating new instances */
2038 WindowsVersionType.tp_init = NULL;
2039 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002040 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
2041 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2042 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00002043#endif
2044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002046#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 SET_SYS_FROM_STRING("float_repr_style",
2048 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002049#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 SET_SYS_FROM_STRING("float_repr_style",
2051 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002052#endif
2053
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002054 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002055
Yury Selivanoveb636452016-09-08 22:01:51 -07002056 /* initialize asyncgen_hooks */
2057 if (AsyncGenHooksType.tp_name == NULL) {
2058 if (PyStructSequence_InitType2(
2059 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
2060 return NULL;
2061 }
2062 }
2063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 if (PyErr_Occurred())
2065 return NULL;
2066 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002067}
2068
Eric Snow6b4be192017-05-22 21:36:03 -07002069#undef SET_SYS_FROM_STRING
2070#undef SET_SYS_FROM_STRING_BORROW
2071
2072/* Updating the sys namespace, returning integer error codes */
2073#define SET_SYS_FROM_STRING_BORROW_INT_RESULT(key, value) \
2074 do { \
2075 PyObject *v = (value); \
2076 if (v == NULL) \
2077 return -1; \
2078 res = PyDict_SetItemString(sysdict, key, v); \
2079 if (res < 0) { \
2080 return res; \
2081 } \
2082 } while (0)
2083#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2084 do { \
2085 PyObject *v = (value); \
2086 if (v == NULL) \
2087 return -1; \
2088 res = PyDict_SetItemString(sysdict, key, v); \
2089 Py_DECREF(v); \
2090 if (res < 0) { \
2091 return res; \
2092 } \
2093 } while (0)
2094
2095int
2096_PySys_EndInit(PyObject *sysdict)
2097{
2098 int res;
2099
2100 /* Set flags to their final values */
2101 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2102 /* prevent user from creating new instances */
2103 FlagsType.tp_init = NULL;
2104 FlagsType.tp_new = NULL;
2105 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2106 if (res < 0) {
2107 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2108 return res;
2109 }
2110 PyErr_Clear();
2111 }
2112
2113 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2114 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2115 SET_SYS_FROM_STRING_INT_RESULT("executable",
2116 PyUnicode_FromWideChar(
2117 Py_GetProgramFullPath(), -1));
2118 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2119 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2120 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2121 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2122 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2123 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2124 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2125 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2126
Eric Snow05351c12017-09-05 21:43:08 -07002127 if (warnoptions == NULL) {
2128 warnoptions = PyList_New(0);
2129 if (warnoptions == NULL)
2130 return -1;
2131 }
Victor Stinner865de272017-06-08 13:27:47 +02002132
Eric Snow05351c12017-09-05 21:43:08 -07002133 SET_SYS_FROM_STRING_INT_RESULT("warnoptions",
2134 PyList_GetSlice(warnoptions,
2135 0, Py_SIZE(warnoptions)));
2136
2137 SET_SYS_FROM_STRING_BORROW_INT_RESULT("_xoptions", get_xoptions());
Eric Snow6b4be192017-05-22 21:36:03 -07002138
2139 if (PyErr_Occurred())
2140 return -1;
2141 return 0;
2142}
2143
2144#undef SET_SYS_FROM_STRING_INT_RESULT
2145#undef SET_SYS_FROM_STRING_BORROW_INT_RESULT
2146
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002147static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002148makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 int i, n;
2151 const wchar_t *p;
2152 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 n = 1;
2155 p = path;
2156 while ((p = wcschr(p, delim)) != NULL) {
2157 n++;
2158 p++;
2159 }
2160 v = PyList_New(n);
2161 if (v == NULL)
2162 return NULL;
2163 for (i = 0; ; i++) {
2164 p = wcschr(path, delim);
2165 if (p == NULL)
2166 p = path + wcslen(path); /* End of string */
2167 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2168 if (w == NULL) {
2169 Py_DECREF(v);
2170 return NULL;
2171 }
2172 PyList_SetItem(v, i, w);
2173 if (*p == '\0')
2174 break;
2175 path = p+1;
2176 }
2177 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002178}
2179
2180void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002181PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 PyObject *v;
2184 if ((v = makepathobject(path, DELIM)) == NULL)
2185 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002186 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 Py_FatalError("can't assign sys.path");
2188 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002189}
2190
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002191static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002192makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002193{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 PyObject *av;
2195 if (argc <= 0 || argv == NULL) {
2196 /* Ensure at least one (empty) argument is seen */
2197 static wchar_t *empty_argv[1] = {L""};
2198 argv = empty_argv;
2199 argc = 1;
2200 }
2201 av = PyList_New(argc);
2202 if (av != NULL) {
2203 int i;
2204 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 if (v == NULL) {
2207 Py_DECREF(av);
2208 av = NULL;
2209 break;
2210 }
2211 PyList_SetItem(av, i, v);
2212 }
2213 }
2214 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002215}
2216
Nick Coghland26c18a2010-08-17 13:06:11 +00002217#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2218 (argc > 0 && argv0 != NULL && \
2219 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002220
2221static void
2222sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002223{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002224 wchar_t *argv0;
2225 wchar_t *p = NULL;
2226 Py_ssize_t n = 0;
2227 PyObject *a;
2228 PyObject *path;
2229#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002230 wchar_t link[MAXPATHLEN+1];
2231 wchar_t argv0copy[2*MAXPATHLEN+1];
2232 int nr = 0;
2233#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002234#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002236#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002238#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002239
Victor Stinnerbd303c12013-11-07 23:07:29 +01002240 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002241 if (path == NULL)
2242 return;
2243
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002244 argv0 = argv[0];
2245
2246#ifdef HAVE_READLINK
2247 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2248 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2249 if (nr > 0) {
2250 /* It's a symlink */
2251 link[nr] = '\0';
2252 if (link[0] == SEP)
2253 argv0 = link; /* Link to absolute path */
2254 else if (wcschr(link, SEP) == NULL)
2255 ; /* Link without path */
2256 else {
2257 /* Must join(dirname(argv0), link) */
2258 wchar_t *q = wcsrchr(argv0, SEP);
2259 if (q == NULL)
2260 argv0 = link; /* argv0 without path */
2261 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002262 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2263 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002264 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002265 wcsncpy(q+1, link, MAXPATHLEN);
2266 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002267 argv0 = argv0copy;
2268 }
2269 }
2270 }
2271#endif /* HAVE_READLINK */
2272#if SEP == '\\' /* Special case for MS filename syntax */
2273 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2274 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002275#if defined(MS_WINDOWS)
2276 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002277 wchar_t *ptemp;
2278 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002279 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002280 fullpath,
2281 &ptemp)) {
2282 argv0 = fullpath;
2283 }
2284#endif
2285 p = wcsrchr(argv0, SEP);
2286 /* Test for alternate separator */
2287 q = wcsrchr(p ? p : argv0, '/');
2288 if (q != NULL)
2289 p = q;
2290 if (p != NULL) {
2291 n = p + 1 - argv0;
2292 if (n > 1 && p[-1] != ':')
2293 n--; /* Drop trailing separator */
2294 }
2295 }
2296#else /* All other filename syntaxes */
2297 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2298#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002299 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002300 argv0 = fullpath;
2301 }
2302#endif
2303 p = wcsrchr(argv0, SEP);
2304 }
2305 if (p != NULL) {
2306 n = p + 1 - argv0;
2307#if SEP == '/' /* Special case for Unix filename syntax */
2308 if (n > 1)
2309 n--; /* Drop trailing separator */
2310#endif /* Unix */
2311 }
2312#endif /* All others */
2313 a = PyUnicode_FromWideChar(argv0, n);
2314 if (a == NULL)
2315 Py_FatalError("no mem for sys.path insertion");
2316 if (PyList_Insert(path, 0, a) < 0)
2317 Py_FatalError("sys.path.insert(0) failed");
2318 Py_DECREF(a);
2319}
2320
2321void
2322PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002325 if (av == NULL)
2326 Py_FatalError("no mem for sys.argv");
2327 if (PySys_SetObject("argv", av) != 0)
2328 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002330 if (updatepath)
2331 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002332}
Guido van Rossuma890e681998-05-12 14:59:24 +00002333
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002334void
2335PySys_SetArgv(int argc, wchar_t **argv)
2336{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002337 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002338}
2339
Victor Stinner14284c22010-04-23 12:02:30 +00002340/* Reimplementation of PyFile_WriteString() no calling indirectly
2341 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2342
2343static int
Victor Stinner79766632010-08-16 17:36:42 +00002344sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002345{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002346 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002348
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002349 if (file == NULL)
2350 return -1;
2351
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002352 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 if (writer == NULL)
2354 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002355
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002356 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002357 if (result == NULL) {
2358 goto error;
2359 } else {
2360 err = 0;
2361 goto finally;
2362 }
Victor Stinner14284c22010-04-23 12:02:30 +00002363
2364error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002366finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 Py_XDECREF(result);
2369 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002370}
2371
Victor Stinner79766632010-08-16 17:36:42 +00002372static int
2373sys_pyfile_write(const char *text, PyObject *file)
2374{
2375 PyObject *unicode = NULL;
2376 int err;
2377
2378 if (file == NULL)
2379 return -1;
2380
2381 unicode = PyUnicode_FromString(text);
2382 if (unicode == NULL)
2383 return -1;
2384
2385 err = sys_pyfile_write_unicode(unicode, file);
2386 Py_DECREF(unicode);
2387 return err;
2388}
Guido van Rossuma890e681998-05-12 14:59:24 +00002389
2390/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2391 Adapted from code submitted by Just van Rossum.
2392
2393 PySys_WriteStdout(format, ...)
2394 PySys_WriteStderr(format, ...)
2395
2396 The first function writes to sys.stdout; the second to sys.stderr. When
2397 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002398 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002399
Victor Stinner14284c22010-04-23 12:02:30 +00002400 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002401 signal handlers: they may raise a new exception whereas sys_write()
2402 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002403
Guido van Rossuma890e681998-05-12 14:59:24 +00002404 Both take a printf-style format string as their first argument followed
2405 by a variable length argument list determined by the format string.
2406
2407 *** WARNING ***
2408
2409 The format should limit the total size of the formatted output string to
2410 1000 bytes. In particular, this means that no unrestricted "%s" formats
2411 should occur; these should be limited using "%.<N>s where <N> is a
2412 decimal number calculated so that <N> plus the maximum size of other
2413 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2414 which can print hundreds of digits for very large numbers.
2415
2416 */
2417
2418static void
Victor Stinner09054372013-11-06 22:41:44 +01002419sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 PyObject *file;
2422 PyObject *error_type, *error_value, *error_traceback;
2423 char buffer[1001];
2424 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002425
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002427 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2429 if (sys_pyfile_write(buffer, file) != 0) {
2430 PyErr_Clear();
2431 fputs(buffer, fp);
2432 }
2433 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2434 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002435 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002436 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 }
2438 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002439}
2440
2441void
Guido van Rossuma890e681998-05-12 14:59:24 +00002442PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002444 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002445
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002447 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002448 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002449}
2450
2451void
Guido van Rossuma890e681998-05-12 14:59:24 +00002452PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002454 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002457 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002458 va_end(va);
2459}
2460
2461static void
Victor Stinner09054372013-11-06 22:41:44 +01002462sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002463{
2464 PyObject *file, *message;
2465 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002466 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002467
2468 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002469 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002470 message = PyUnicode_FromFormatV(format, va);
2471 if (message != NULL) {
2472 if (sys_pyfile_write_unicode(message, file) != 0) {
2473 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002474 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002475 if (utf8 != NULL)
2476 fputs(utf8, fp);
2477 }
2478 Py_DECREF(message);
2479 }
2480 PyErr_Restore(error_type, error_value, error_traceback);
2481}
2482
2483void
2484PySys_FormatStdout(const char *format, ...)
2485{
2486 va_list va;
2487
2488 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002489 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002490 va_end(va);
2491}
2492
2493void
2494PySys_FormatStderr(const char *format, ...)
2495{
2496 va_list va;
2497
2498 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002499 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002501}