blob: ea2ccb2a15288efaaacccf374871917ed833eaa0 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060018#include "internal/pystate.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000019#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000020#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020021#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossume2437a11992-03-23 18:20:18 +000023#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020024#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Mark Hammond8696ebc2002-10-08 02:44:31 +000026#ifdef MS_WINDOWS
27#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000028#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#endif /* MS_WINDOWS */
30
Guido van Rossum9b38a141996-09-11 23:12:24 +000031#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000032extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000033/* A string loaded from the DLL at startup: */
34extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000035#endif
36
Victor Stinnerbd303c12013-11-07 23:07:29 +010037_Py_IDENTIFIER(_);
38_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070039_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010040_Py_IDENTIFIER(buffer);
41_Py_IDENTIFIER(builtins);
42_Py_IDENTIFIER(encoding);
43_Py_IDENTIFIER(path);
44_Py_IDENTIFIER(stdout);
45_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070046_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(write);
48
Guido van Rossum65bf9f21997-04-29 18:33:38 +000049PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010050_PySys_GetObjectId(_Py_Identifier *key)
51{
52 PyThreadState *tstate = PyThreadState_GET();
53 PyObject *sd = tstate->interp->sysdict;
54 if (sd == NULL)
55 return NULL;
56 return _PyDict_GetItemId(sd, key);
57}
58
59PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000060PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 PyThreadState *tstate = PyThreadState_GET();
63 PyObject *sd = tstate->interp->sysdict;
64 if (sd == NULL)
65 return NULL;
66 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000067}
68
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069int
Victor Stinnerd67bd452013-11-06 22:36:40 +010070_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
71{
72 PyThreadState *tstate = PyThreadState_GET();
73 PyObject *sd = tstate->interp->sysdict;
74 if (v == NULL) {
75 if (_PyDict_GetItemId(sd, key) == NULL)
76 return 0;
77 else
78 return _PyDict_DelItemId(sd, key);
79 }
80 else
81 return _PyDict_SetItemId(sd, key, v);
82}
83
84int
Neal Norwitzf3081322007-08-25 00:32:45 +000085PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000086{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000087 PyThreadState *tstate = PyThreadState_GET();
88 PyObject *sd = tstate->interp->sysdict;
89 if (v == NULL) {
90 if (PyDict_GetItemString(sd, name) == NULL)
91 return 0;
92 else
93 return PyDict_DelItemString(sd, name);
94 }
95 else
96 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000097}
98
Barry Warsaw36c1d1f2017-10-05 12:11:18 -040099static PyObject *
100sys_breakpointhook(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *keywords)
101{
102 assert(!PyErr_Occurred());
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200103 const char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400104
105 if (envar == NULL || strlen(envar) == 0) {
106 envar = "pdb.set_trace";
107 }
108 else if (!strcmp(envar, "0")) {
109 /* The breakpoint is explicitly no-op'd. */
110 Py_RETURN_NONE;
111 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200112 const char *last_dot = strrchr(envar, '.');
113 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400114 PyObject *modulepath = NULL;
115
116 if (last_dot == NULL) {
117 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
118 modulepath = PyUnicode_FromString("builtins");
119 attrname = envar;
120 }
121 else {
122 /* Split on the last dot; */
123 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
124 attrname = last_dot + 1;
125 }
126 if (modulepath == NULL) {
127 return NULL;
128 }
129
130 PyObject *fromlist = Py_BuildValue("(s)", attrname);
131 if (fromlist == NULL) {
132 Py_DECREF(modulepath);
133 return NULL;
134 }
135 PyObject *module = PyImport_ImportModuleLevelObject(
136 modulepath, NULL, NULL, fromlist, 0);
137 Py_DECREF(modulepath);
138 Py_DECREF(fromlist);
139
140 if (module == NULL) {
141 goto error;
142 }
143
144 PyObject *hook = PyObject_GetAttrString(module, attrname);
145 Py_DECREF(module);
146
147 if (hook == NULL) {
148 goto error;
149 }
150 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
151 Py_DECREF(hook);
152 return retval;
153
154 error:
155 /* If any of the imports went wrong, then warn and ignore. */
156 PyErr_Clear();
157 int status = PyErr_WarnFormat(
158 PyExc_RuntimeWarning, 0,
159 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
160 if (status < 0) {
161 /* Printing the warning raised an exception. */
162 return NULL;
163 }
164 /* The warning was (probably) issued. */
165 Py_RETURN_NONE;
166}
167
168PyDoc_STRVAR(breakpointhook_doc,
169"breakpointhook(*args, **kws)\n"
170"\n"
171"This hook function is called by built-in breakpoint().\n"
172);
173
Victor Stinner13d49ee2010-12-04 17:24:33 +0000174/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
175 error handler. If sys.stdout has a buffer attribute, use
176 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
177 sys.stdout.write(redecoded).
178
179 Helper function for sys_displayhook(). */
180static int
181sys_displayhook_unencodable(PyObject *outf, PyObject *o)
182{
183 PyObject *stdout_encoding = NULL;
184 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200185 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000186 int ret;
187
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200188 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000189 if (stdout_encoding == NULL)
190 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200191 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000192 if (stdout_encoding_str == NULL)
193 goto error;
194
195 repr_str = PyObject_Repr(o);
196 if (repr_str == NULL)
197 goto error;
198 encoded = PyUnicode_AsEncodedString(repr_str,
199 stdout_encoding_str,
200 "backslashreplace");
201 Py_DECREF(repr_str);
202 if (encoded == NULL)
203 goto error;
204
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200205 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000206 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100207 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000208 Py_DECREF(buffer);
209 Py_DECREF(encoded);
210 if (result == NULL)
211 goto error;
212 Py_DECREF(result);
213 }
214 else {
215 PyErr_Clear();
216 escaped_str = PyUnicode_FromEncodedObject(encoded,
217 stdout_encoding_str,
218 "strict");
219 Py_DECREF(encoded);
220 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
221 Py_DECREF(escaped_str);
222 goto error;
223 }
224 Py_DECREF(escaped_str);
225 }
226 ret = 0;
227 goto finally;
228
229error:
230 ret = -1;
231finally:
232 Py_XDECREF(stdout_encoding);
233 return ret;
234}
235
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000236static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000237sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000238{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000239 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100240 PyObject *builtins;
241 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000242 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000243
Eric Snow3f9eee62017-09-15 16:35:20 -0600244 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000245 if (builtins == NULL) {
246 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
247 return NULL;
248 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600249 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000251 /* Print value except if None */
252 /* After printing, also assign to '_' */
253 /* Before, set '_' to None to avoid recursion */
254 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200255 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200257 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100259 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (outf == NULL || outf == Py_None) {
261 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
262 return NULL;
263 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000264 if (PyFile_WriteObject(o, outf, 0) != 0) {
265 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
266 /* repr(o) is not encodable to sys.stdout.encoding with
267 * sys.stdout.errors error handler (which is probably 'strict') */
268 PyErr_Clear();
269 err = sys_displayhook_unencodable(outf, o);
270 if (err)
271 return NULL;
272 }
273 else {
274 return NULL;
275 }
276 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100277 if (newline == NULL) {
278 newline = PyUnicode_FromString("\n");
279 if (newline == NULL)
280 return NULL;
281 }
282 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200284 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200286 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000287}
288
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000289PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000290"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000291"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000292"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000293);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000294
295static PyObject *
296sys_excepthook(PyObject* self, PyObject* args)
297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 PyObject *exc, *value, *tb;
299 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
300 return NULL;
301 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200302 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000303}
304
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000305PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000306"excepthook(exctype, value, traceback) -> None\n"
307"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000308"Handle an exception by displaying it with a traceback on sys.stderr.\n"
309);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000310
311static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000312sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000313{
Mark Shannonae3087c2017-10-22 22:41:51 +0100314 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000315 return Py_BuildValue(
316 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100317 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
318 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
319 err_info->exc_traceback != NULL ?
320 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000321}
322
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000323PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000324"exc_info() -> (type, value, traceback)\n\
325\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000326Return information about the most recent exception caught by an except\n\
327clause in the current stack frame or in an older stack frame."
328);
329
330static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000331sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *exit_code = 0;
334 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
335 return NULL;
336 /* Raise SystemExit so callers may catch it or clean up. */
337 PyErr_SetObject(PyExc_SystemExit, exit_code);
338 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339}
340
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000341PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000342"exit([status])\n\
343\n\
344Exit the interpreter by raising SystemExit(status).\n\
345If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300346If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000347If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000348exit status will be one (i.e., failure)."
349);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000350
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000351
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000352static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000353sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000356}
357
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000358PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000359"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000360\n\
361Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000362implementation."
363);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000364
365static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000366sys_getfilesystemencoding(PyObject *self)
367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 if (Py_FileSystemDefaultEncoding)
369 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200370 PyErr_SetString(PyExc_RuntimeError,
371 "filesystem encoding is not initialized");
372 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000373}
374
375PyDoc_STRVAR(getfilesystemencoding_doc,
376"getfilesystemencoding() -> string\n\
377\n\
378Return the encoding used to convert Unicode filenames in\n\
379operating system filenames."
380);
381
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000382static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700383sys_getfilesystemencodeerrors(PyObject *self)
384{
385 if (Py_FileSystemDefaultEncodeErrors)
386 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
387 PyErr_SetString(PyExc_RuntimeError,
388 "filesystem encoding is not initialized");
389 return NULL;
390}
391
392PyDoc_STRVAR(getfilesystemencodeerrors_doc,
393 "getfilesystemencodeerrors() -> string\n\
394\n\
395Return the error mode used to convert Unicode filenames in\n\
396operating system filenames."
397);
398
399static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000400sys_intern(PyObject *self, PyObject *args)
401{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 PyObject *s;
403 if (!PyArg_ParseTuple(args, "U:intern", &s))
404 return NULL;
405 if (PyUnicode_CheckExact(s)) {
406 Py_INCREF(s);
407 PyUnicode_InternInPlace(&s);
408 return s;
409 }
410 else {
411 PyErr_Format(PyExc_TypeError,
412 "can't intern %.400s", s->ob_type->tp_name);
413 return NULL;
414 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000415}
416
417PyDoc_STRVAR(intern_doc,
418"intern(string) -> string\n\
419\n\
420``Intern'' the given string. This enters the string in the (global)\n\
421table of interned strings whose purpose is to speed up dictionary lookups.\n\
422Return the string itself or the previously interned string object with the\n\
423same value.");
424
425
Fred Drake5755ce62001-06-27 19:19:46 +0000426/*
427 * Cached interned string objects used for calling the profile and
428 * trace functions. Initialized by trace_init().
429 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000430static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000431
432static int
433trace_init(void)
434{
Nick Coghlan5a851672017-09-08 10:14:16 +1000435 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200436 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000437 "c_call", "c_exception", "c_return",
438 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200439 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000440 PyObject *name;
441 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000442 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 if (whatstrings[i] == NULL) {
444 name = PyUnicode_InternFromString(whatnames[i]);
445 if (name == NULL)
446 return -1;
447 whatstrings[i] = name;
448 }
449 }
450 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000451}
452
453
454static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100455call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200459 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000460
Victor Stinner78da82b2016-08-20 01:22:57 +0200461 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200463 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100464
Victor Stinner78da82b2016-08-20 01:22:57 +0200465 stack[0] = (PyObject *)frame;
466 stack[1] = whatstrings[what];
467 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200470 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000471
Victor Stinner78da82b2016-08-20 01:22:57 +0200472 PyFrame_LocalsToFast(frame, 1);
473 if (result == NULL) {
474 PyTraceBack_Here(frame);
475 }
476
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000478}
479
480static int
481profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000485
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (arg == NULL)
487 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100488 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (result == NULL) {
490 PyEval_SetProfile(NULL, NULL);
491 return -1;
492 }
493 Py_DECREF(result);
494 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000495}
496
497static int
498trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 PyObject *callback;
502 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (what == PyTrace_CALL)
505 callback = self;
506 else
507 callback = frame->f_trace;
508 if (callback == NULL)
509 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100510 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (result == NULL) {
512 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200513 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 return -1;
515 }
516 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300517 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 }
519 else {
520 Py_DECREF(result);
521 }
522 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000523}
Fred Draked0838392001-06-16 21:02:31 +0000524
Fred Drake8b4d01d2000-05-09 19:57:01 +0000525static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000526sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (trace_init() == -1)
529 return NULL;
530 if (args == Py_None)
531 PyEval_SetTrace(NULL, NULL);
532 else
533 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200534 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000535}
536
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000537PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000538"settrace(function)\n\
539\n\
540Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000541function call. See the debugger chapter in the library manual."
542);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000543
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000544static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000545sys_gettrace(PyObject *self, PyObject *args)
546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 PyThreadState *tstate = PyThreadState_GET();
548 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (temp == NULL)
551 temp = Py_None;
552 Py_INCREF(temp);
553 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000554}
555
556PyDoc_STRVAR(gettrace_doc,
557"gettrace()\n\
558\n\
559Return the global debug tracing function set with sys.settrace.\n\
560See the debugger chapter in the library manual."
561);
562
563static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000564sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 if (trace_init() == -1)
567 return NULL;
568 if (args == Py_None)
569 PyEval_SetProfile(NULL, NULL);
570 else
571 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200572 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000573}
574
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000575PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000576"setprofile(function)\n\
577\n\
578Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000579and return. See the profiler chapter in the library manual."
580);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000581
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000582static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000583sys_getprofile(PyObject *self, PyObject *args)
584{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000585 PyThreadState *tstate = PyThreadState_GET();
586 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000588 if (temp == NULL)
589 temp = Py_None;
590 Py_INCREF(temp);
591 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000592}
593
594PyDoc_STRVAR(getprofile_doc,
595"getprofile()\n\
596\n\
597Return the profiling function set with sys.setprofile.\n\
598See the profiler chapter in the library manual."
599);
600
601static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000602sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000604 if (PyErr_WarnEx(PyExc_DeprecationWarning,
605 "sys.getcheckinterval() and sys.setcheckinterval() "
606 "are deprecated. Use sys.setswitchinterval() "
607 "instead.", 1) < 0)
608 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600609 PyInterpreterState *interp = PyThreadState_GET()->interp;
610 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200612 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000613}
614
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000615PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000616"setcheckinterval(n)\n\
617\n\
618Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000619n instructions. This also affects how often thread switches occur."
620);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000621
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000622static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000623sys_getcheckinterval(PyObject *self, PyObject *args)
624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (PyErr_WarnEx(PyExc_DeprecationWarning,
626 "sys.getcheckinterval() and sys.setcheckinterval() "
627 "are deprecated. Use sys.getswitchinterval() "
628 "instead.", 1) < 0)
629 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600630 PyInterpreterState *interp = PyThreadState_GET()->interp;
631 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000632}
633
634PyDoc_STRVAR(getcheckinterval_doc,
635"getcheckinterval() -> current check interval; see setcheckinterval()."
636);
637
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000638static PyObject *
639sys_setswitchinterval(PyObject *self, PyObject *args)
640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 double d;
642 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
643 return NULL;
644 if (d <= 0.0) {
645 PyErr_SetString(PyExc_ValueError,
646 "switch interval must be strictly positive");
647 return NULL;
648 }
649 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200650 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000651}
652
653PyDoc_STRVAR(setswitchinterval_doc,
654"setswitchinterval(n)\n\
655\n\
656Set the ideal thread switching delay inside the Python interpreter\n\
657The actual frequency of switching threads can be lower if the\n\
658interpreter executes long sequences of uninterruptible code\n\
659(this is implementation-specific and workload-dependent).\n\
660\n\
661The parameter must represent the desired switching delay in seconds\n\
662A typical value is 0.005 (5 milliseconds)."
663);
664
665static PyObject *
666sys_getswitchinterval(PyObject *self, PyObject *args)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000669}
670
671PyDoc_STRVAR(getswitchinterval_doc,
672"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
673);
674
Tim Peterse5e065b2003-07-06 18:36:54 +0000675static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000676sys_setrecursionlimit(PyObject *self, PyObject *args)
677{
Victor Stinner50856d52015-10-13 00:11:21 +0200678 int new_limit, mark;
679 PyThreadState *tstate;
680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
682 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200683
684 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200686 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return NULL;
688 }
Victor Stinner50856d52015-10-13 00:11:21 +0200689
690 /* Issue #25274: When the recursion depth hits the recursion limit in
691 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
692 set to 1 and a RecursionError is raised. The overflowed flag is reset
693 to 0 when the recursion depth goes below the low-water mark: see
694 Py_LeaveRecursiveCall().
695
696 Reject too low new limit if the current recursion depth is higher than
697 the new low-water mark. Otherwise it may not be possible anymore to
698 reset the overflowed flag to 0. */
699 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
700 tstate = PyThreadState_GET();
701 if (tstate->recursion_depth >= mark) {
702 PyErr_Format(PyExc_RecursionError,
703 "cannot set the recursion limit to %i at "
704 "the recursion depth %i: the limit is too low",
705 new_limit, tstate->recursion_depth);
706 return NULL;
707 }
708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200710 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000711}
712
Yury Selivanov75445082015-05-11 22:57:16 -0400713static PyObject *
714sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
715{
716 if (wrapper != Py_None) {
717 if (!PyCallable_Check(wrapper)) {
718 PyErr_Format(PyExc_TypeError,
719 "callable expected, got %.50s",
720 Py_TYPE(wrapper)->tp_name);
721 return NULL;
722 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400723 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400724 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400725 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400726 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400727 }
Yury Selivanov75445082015-05-11 22:57:16 -0400728 Py_RETURN_NONE;
729}
730
731PyDoc_STRVAR(set_coroutine_wrapper_doc,
732"set_coroutine_wrapper(wrapper)\n\
733\n\
734Set a wrapper for coroutine objects."
735);
736
737static PyObject *
738sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
739{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400740 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400741 if (wrapper == NULL) {
742 wrapper = Py_None;
743 }
744 Py_INCREF(wrapper);
745 return wrapper;
746}
747
748PyDoc_STRVAR(get_coroutine_wrapper_doc,
749"get_coroutine_wrapper()\n\
750\n\
751Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
752);
753
754
Yury Selivanoveb636452016-09-08 22:01:51 -0700755static PyTypeObject AsyncGenHooksType;
756
757PyDoc_STRVAR(asyncgen_hooks_doc,
758"asyncgen_hooks\n\
759\n\
760A struct sequence providing information about asynhronous\n\
761generators hooks. The attributes are read only.");
762
763static PyStructSequence_Field asyncgen_hooks_fields[] = {
764 {"firstiter", "Hook to intercept first iteration"},
765 {"finalizer", "Hook to intercept finalization"},
766 {0}
767};
768
769static PyStructSequence_Desc asyncgen_hooks_desc = {
770 "asyncgen_hooks", /* name */
771 asyncgen_hooks_doc, /* doc */
772 asyncgen_hooks_fields , /* fields */
773 2
774};
775
776
777static PyObject *
778sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
779{
780 static char *keywords[] = {"firstiter", "finalizer", NULL};
781 PyObject *firstiter = NULL;
782 PyObject *finalizer = NULL;
783
784 if (!PyArg_ParseTupleAndKeywords(
785 args, kw, "|OO", keywords,
786 &firstiter, &finalizer)) {
787 return NULL;
788 }
789
790 if (finalizer && finalizer != Py_None) {
791 if (!PyCallable_Check(finalizer)) {
792 PyErr_Format(PyExc_TypeError,
793 "callable finalizer expected, got %.50s",
794 Py_TYPE(finalizer)->tp_name);
795 return NULL;
796 }
797 _PyEval_SetAsyncGenFinalizer(finalizer);
798 }
799 else if (finalizer == Py_None) {
800 _PyEval_SetAsyncGenFinalizer(NULL);
801 }
802
803 if (firstiter && firstiter != Py_None) {
804 if (!PyCallable_Check(firstiter)) {
805 PyErr_Format(PyExc_TypeError,
806 "callable firstiter expected, got %.50s",
807 Py_TYPE(firstiter)->tp_name);
808 return NULL;
809 }
810 _PyEval_SetAsyncGenFirstiter(firstiter);
811 }
812 else if (firstiter == Py_None) {
813 _PyEval_SetAsyncGenFirstiter(NULL);
814 }
815
816 Py_RETURN_NONE;
817}
818
819PyDoc_STRVAR(set_asyncgen_hooks_doc,
820"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
821\n\
822Set a finalizer for async generators objects."
823);
824
825static PyObject *
826sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
827{
828 PyObject *res;
829 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
830 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
831
832 res = PyStructSequence_New(&AsyncGenHooksType);
833 if (res == NULL) {
834 return NULL;
835 }
836
837 if (firstiter == NULL) {
838 firstiter = Py_None;
839 }
840
841 if (finalizer == NULL) {
842 finalizer = Py_None;
843 }
844
845 Py_INCREF(firstiter);
846 PyStructSequence_SET_ITEM(res, 0, firstiter);
847
848 Py_INCREF(finalizer);
849 PyStructSequence_SET_ITEM(res, 1, finalizer);
850
851 return res;
852}
853
854PyDoc_STRVAR(get_asyncgen_hooks_doc,
855"get_asyncgen_hooks()\n\
856\n\
857Return a namedtuple of installed asynchronous generators hooks \
858(firstiter, finalizer)."
859);
860
861
Mark Dickinsondc787d22010-05-23 13:33:13 +0000862static PyTypeObject Hash_InfoType;
863
864PyDoc_STRVAR(hash_info_doc,
865"hash_info\n\
866\n\
867A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100868hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000869
870static PyStructSequence_Field hash_info_fields[] = {
871 {"width", "width of the type used for hashing, in bits"},
872 {"modulus", "prime number giving the modulus on which the hash "
873 "function is based"},
874 {"inf", "value to be used for hash of a positive infinity"},
875 {"nan", "value to be used for hash of a nan"},
876 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100877 {"algorithm", "name of the algorithm for hashing of str, bytes and "
878 "memoryviews"},
879 {"hash_bits", "internal output size of hash algorithm"},
880 {"seed_bits", "seed size of hash algorithm"},
881 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000882 {NULL, NULL}
883};
884
885static PyStructSequence_Desc hash_info_desc = {
886 "sys.hash_info",
887 hash_info_doc,
888 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100889 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000890};
891
Matthias Klosed885e952010-07-06 10:53:30 +0000892static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000893get_hash_info(void)
894{
895 PyObject *hash_info;
896 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100897 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000898 hash_info = PyStructSequence_New(&Hash_InfoType);
899 if (hash_info == NULL)
900 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100901 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000902 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000903 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000904 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000905 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000906 PyStructSequence_SET_ITEM(hash_info, field++,
907 PyLong_FromLong(_PyHASH_INF));
908 PyStructSequence_SET_ITEM(hash_info, field++,
909 PyLong_FromLong(_PyHASH_NAN));
910 PyStructSequence_SET_ITEM(hash_info, field++,
911 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100912 PyStructSequence_SET_ITEM(hash_info, field++,
913 PyUnicode_FromString(hashfunc->name));
914 PyStructSequence_SET_ITEM(hash_info, field++,
915 PyLong_FromLong(hashfunc->hash_bits));
916 PyStructSequence_SET_ITEM(hash_info, field++,
917 PyLong_FromLong(hashfunc->seed_bits));
918 PyStructSequence_SET_ITEM(hash_info, field++,
919 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000920 if (PyErr_Occurred()) {
921 Py_CLEAR(hash_info);
922 return NULL;
923 }
924 return hash_info;
925}
926
927
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000928PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000929"setrecursionlimit(n)\n\
930\n\
931Set the maximum depth of the Python interpreter stack to n. This\n\
932limit prevents infinite recursion from causing an overflow of the C\n\
933stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000934dependent."
935);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000936
937static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000938sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000941}
942
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000943PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000944"getrecursionlimit()\n\
945\n\
946Return the current value of the recursion limit, the maximum depth\n\
947of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000948recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000949);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000950
Mark Hammond8696ebc2002-10-08 02:44:31 +0000951#ifdef MS_WINDOWS
952PyDoc_STRVAR(getwindowsversion_doc,
953"getwindowsversion()\n\
954\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000955Return information about the running version of Windows as a named tuple.\n\
956The members are named: major, minor, build, platform, service_pack,\n\
957service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200958backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -0700959All elements are numbers, except service_pack and platform_type which are\n\
960strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
961Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
962server. Platform_version is a 3-tuple containing a version number that is\n\
963intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000964);
965
Eric Smithf7bb5782010-01-27 00:44:57 +0000966static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
967
968static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 {"major", "Major version number"},
970 {"minor", "Minor version number"},
971 {"build", "Build number"},
972 {"platform", "Operating system platform"},
973 {"service_pack", "Latest Service Pack installed on the system"},
974 {"service_pack_major", "Service Pack major version number"},
975 {"service_pack_minor", "Service Pack minor version number"},
976 {"suite_mask", "Bit mask identifying available product suites"},
977 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -0700978 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000980};
981
982static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 "sys.getwindowsversion", /* name */
984 getwindowsversion_doc, /* doc */
985 windows_version_fields, /* fields */
986 5 /* For backward compatibility,
987 only the first 5 items are accessible
988 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000989};
990
Steve Dower3e96f322015-03-02 08:01:10 -0800991/* Disable deprecation warnings about GetVersionEx as the result is
992 being passed straight through to the caller, who is responsible for
993 using it correctly. */
994#pragma warning(push)
995#pragma warning(disable:4996)
996
Mark Hammond8696ebc2002-10-08 02:44:31 +0000997static PyObject *
998sys_getwindowsversion(PyObject *self)
999{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 PyObject *version;
1001 int pos = 0;
1002 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001003 DWORD realMajor, realMinor, realBuild;
1004 HANDLE hKernel32;
1005 wchar_t kernel32_path[MAX_PATH];
1006 LPVOID verblock;
1007 DWORD verblock_size;
1008
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 ver.dwOSVersionInfoSize = sizeof(ver);
1010 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1011 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001012
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 version = PyStructSequence_New(&WindowsVersionType);
1014 if (version == NULL)
1015 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1018 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1019 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1020 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1021 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1022 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1023 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1024 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1025 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001026
Steve Dower74f4af72016-09-17 17:27:48 -07001027 realMajor = ver.dwMajorVersion;
1028 realMinor = ver.dwMinorVersion;
1029 realBuild = ver.dwBuildNumber;
1030
1031 // GetVersion will lie if we are running in a compatibility mode.
1032 // We need to read the version info from a system file resource
1033 // to accurately identify the OS version. If we fail for any reason,
1034 // just return whatever GetVersion said.
1035 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1036 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1037 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1038 (verblock = PyMem_RawMalloc(verblock_size))) {
1039 VS_FIXEDFILEINFO *ffi;
1040 UINT ffi_len;
1041
1042 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1043 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1044 realMajor = HIWORD(ffi->dwProductVersionMS);
1045 realMinor = LOWORD(ffi->dwProductVersionMS);
1046 realBuild = HIWORD(ffi->dwProductVersionLS);
1047 }
1048 PyMem_RawFree(verblock);
1049 }
Segev Finer48fb7662017-06-04 20:52:27 +03001050 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1051 realMajor,
1052 realMinor,
1053 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001054 ));
1055
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001056 if (PyErr_Occurred()) {
1057 Py_DECREF(version);
1058 return NULL;
1059 }
Steve Dower74f4af72016-09-17 17:27:48 -07001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001062}
1063
Steve Dower3e96f322015-03-02 08:01:10 -08001064#pragma warning(pop)
1065
Steve Dowercc16be82016-09-08 10:35:16 -07001066PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1067"_enablelegacywindowsfsencoding()\n\
1068\n\
1069Changes the default filesystem encoding to mbcs:replace for consistency\n\
1070with earlier versions of Python. See PEP 529 for more information.\n\
1071\n\
1072This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1073environment variable before launching Python."
1074);
1075
1076static PyObject *
1077sys_enablelegacywindowsfsencoding(PyObject *self)
1078{
1079 Py_FileSystemDefaultEncoding = "mbcs";
1080 Py_FileSystemDefaultEncodeErrors = "replace";
1081 Py_RETURN_NONE;
1082}
1083
Mark Hammond8696ebc2002-10-08 02:44:31 +00001084#endif /* MS_WINDOWS */
1085
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001086#ifdef HAVE_DLOPEN
1087static PyObject *
1088sys_setdlopenflags(PyObject *self, PyObject *args)
1089{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 int new_val;
1091 PyThreadState *tstate = PyThreadState_GET();
1092 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1093 return NULL;
1094 if (!tstate)
1095 return NULL;
1096 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001097 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001098}
1099
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001100PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001101"setdlopenflags(n) -> None\n\
1102\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001103Set the flags used by the interpreter for dlopen calls, such as when the\n\
1104interpreter loads extension modules. Among other things, this will enable\n\
1105a lazy resolving of symbols when importing a module, if called as\n\
1106sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001107sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001108can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001109
1110static PyObject *
1111sys_getdlopenflags(PyObject *self, PyObject *args)
1112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001113 PyThreadState *tstate = PyThreadState_GET();
1114 if (!tstate)
1115 return NULL;
1116 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001117}
1118
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001119PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001120"getdlopenflags() -> int\n\
1121\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001122Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001123The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001126
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001127#ifdef USE_MALLOPT
1128/* Link with -lmalloc (or -lmpc) on an SGI */
1129#include <malloc.h>
1130
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001131static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001132sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001133{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 int flag;
1135 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1136 return NULL;
1137 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001138 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001139}
1140#endif /* USE_MALLOPT */
1141
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001142size_t
1143_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001147 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 /* Make sure the type is initialized. float gets initialized late */
1150 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001151 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001152
Benjamin Petersonce798522012-01-22 11:24:29 -05001153 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 if (method == NULL) {
1155 if (!PyErr_Occurred())
1156 PyErr_Format(PyExc_TypeError,
1157 "Type %.100s doesn't define __sizeof__",
1158 Py_TYPE(o)->tp_name);
1159 }
1160 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001161 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 Py_DECREF(method);
1163 }
1164
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001165 if (res == NULL)
1166 return (size_t)-1;
1167
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001168 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001169 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001170 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001171 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001173 if (size < 0) {
1174 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1175 return (size_t)-1;
1176 }
1177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001179 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001180 return ((size_t)size) + sizeof(PyGC_Head);
1181 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001182}
1183
1184static PyObject *
1185sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1186{
1187 static char *kwlist[] = {"object", "default", 0};
1188 size_t size;
1189 PyObject *o, *dflt = NULL;
1190
1191 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1192 kwlist, &o, &dflt))
1193 return NULL;
1194
1195 size = _PySys_GetSizeOf(o);
1196
1197 if (size == (size_t)-1 && PyErr_Occurred()) {
1198 /* Has a default value been given */
1199 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1200 PyErr_Clear();
1201 Py_INCREF(dflt);
1202 return dflt;
1203 }
1204 else
1205 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001207
1208 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001209}
1210
1211PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001212"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001213\n\
1214Return the size of object in bytes.");
1215
1216static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001217sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001220}
1221
Tim Peters4be93d02002-07-07 19:59:50 +00001222#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001223static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001224sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001225{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001227}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001228#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001229
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001230PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001231"getrefcount(object) -> integer\n\
1232\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001233Return the reference count of object. The count returned is generally\n\
1234one higher than you might expect, because it includes the (temporary)\n\
1235reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001236);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001237
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001238static PyObject *
1239sys_getallocatedblocks(PyObject *self)
1240{
1241 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1242}
1243
1244PyDoc_STRVAR(getallocatedblocks_doc,
1245"getallocatedblocks() -> integer\n\
1246\n\
1247Return the number of memory blocks currently allocated, regardless of their\n\
1248size."
1249);
1250
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001251#ifdef COUNT_ALLOCS
1252static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001253sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001254{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001258}
1259#endif
1260
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001261PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001262"_getframe([depth]) -> frameobject\n\
1263\n\
1264Return a frame object from the call stack. If optional integer depth is\n\
1265given, return the frame object that many calls below the top of the stack.\n\
1266If that is deeper than the call stack, ValueError is raised. The default\n\
1267for depth is zero, returning the frame at the top of the call stack.\n\
1268\n\
1269This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001270purposes only."
1271);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001272
1273static PyObject *
1274sys_getframe(PyObject *self, PyObject *args)
1275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 PyFrameObject *f = PyThreadState_GET()->frame;
1277 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1280 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 while (depth > 0 && f != NULL) {
1283 f = f->f_back;
1284 --depth;
1285 }
1286 if (f == NULL) {
1287 PyErr_SetString(PyExc_ValueError,
1288 "call stack is not deep enough");
1289 return NULL;
1290 }
1291 Py_INCREF(f);
1292 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001293}
1294
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001295PyDoc_STRVAR(current_frames_doc,
1296"_current_frames() -> dictionary\n\
1297\n\
1298Return a dictionary mapping each current thread T's thread id to T's\n\
1299current stack frame.\n\
1300\n\
1301This function should be used for specialized purposes only."
1302);
1303
1304static PyObject *
1305sys_current_frames(PyObject *self, PyObject *noargs)
1306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001308}
1309
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001310PyDoc_STRVAR(call_tracing_doc,
1311"call_tracing(func, args) -> object\n\
1312\n\
1313Call func(*args), while tracing is enabled. The tracing state is\n\
1314saved, and restored afterwards. This is intended to be called from\n\
1315a debugger from a checkpoint, to recursively debug some other code."
1316);
1317
1318static PyObject *
1319sys_call_tracing(PyObject *self, PyObject *args)
1320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 PyObject *func, *funcargs;
1322 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1323 return NULL;
1324 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001325}
1326
Jeremy Hylton985eba52003-02-05 23:13:00 +00001327PyDoc_STRVAR(callstats_doc,
1328"callstats() -> tuple of integers\n\
1329\n\
1330Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1331when Python was built. Otherwise, return None.\n\
1332\n\
1333When enabled, this function returns detailed, implementation-specific\n\
1334details about the number of function calls executed. The return value is\n\
1335a 11-tuple where the entries in the tuple are counts of:\n\
13360. all function calls\n\
13371. calls to PyFunction_Type objects\n\
13382. PyFunction calls that do not create an argument tuple\n\
13393. PyFunction calls that do not create an argument tuple\n\
1340 and bypass PyEval_EvalCodeEx()\n\
13414. PyMethod calls\n\
13425. PyMethod calls on bound methods\n\
13436. PyType calls\n\
13447. PyCFunction calls\n\
13458. generator calls\n\
13469. All other calls\n\
134710. Number of stack pops performed by call_function()"
1348);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001349
Victor Stinner048afd92016-11-28 11:59:04 +01001350static PyObject *
1351sys_callstats(PyObject *self)
1352{
1353 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1354 "sys.callstats() has been deprecated in Python 3.7 "
1355 "and will be removed in the future", 1) < 0) {
1356 return NULL;
1357 }
1358
1359 Py_RETURN_NONE;
1360}
1361
1362
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001363#ifdef __cplusplus
1364extern "C" {
1365#endif
1366
David Malcolm49526f42012-06-22 14:55:41 -04001367static PyObject *
1368sys_debugmallocstats(PyObject *self, PyObject *args)
1369{
1370#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001371 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001372 fputc('\n', stderr);
1373 }
David Malcolm49526f42012-06-22 14:55:41 -04001374#endif
1375 _PyObject_DebugTypeStats(stderr);
1376
1377 Py_RETURN_NONE;
1378}
1379PyDoc_STRVAR(debugmallocstats_doc,
1380"_debugmallocstats()\n\
1381\n\
1382Print summary info to stderr about the state of\n\
1383pymalloc's structures.\n\
1384\n\
1385In Py_DEBUG mode, also perform some expensive internal consistency\n\
1386checks.\n\
1387");
1388
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001389#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001390/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001391extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001392#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001393
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001394#ifdef DYNAMIC_EXECUTION_PROFILE
1395/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001396extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001397#endif
1398
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001399#ifdef __cplusplus
1400}
1401#endif
1402
Christian Heimes15ebc882008-02-04 18:48:49 +00001403static PyObject *
1404sys_clear_type_cache(PyObject* self, PyObject* args)
1405{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 PyType_ClearCache();
1407 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001408}
1409
1410PyDoc_STRVAR(sys_clear_type_cache__doc__,
1411"_clear_type_cache() -> None\n\
1412Clear the internal type lookup cache.");
1413
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001414static PyObject *
1415sys_is_finalizing(PyObject* self, PyObject* args)
1416{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001417 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001418}
1419
1420PyDoc_STRVAR(is_finalizing_doc,
1421"is_finalizing()\n\
1422Return True if Python is exiting.");
1423
Christian Heimes15ebc882008-02-04 18:48:49 +00001424
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001425#ifdef ANDROID_API_LEVEL
1426PyDoc_STRVAR(getandroidapilevel_doc,
1427"getandroidapilevel()\n\
1428\n\
1429Return the build time API version of Android as an integer.");
1430
1431static PyObject *
1432sys_getandroidapilevel(PyObject *self)
1433{
1434 return PyLong_FromLong(ANDROID_API_LEVEL);
1435}
1436#endif /* ANDROID_API_LEVEL */
1437
1438
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001439static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001441 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1442 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Victor Stinner048afd92016-11-28 11:59:04 +01001443 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 callstats_doc},
1445 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1446 sys_clear_type_cache__doc__},
1447 {"_current_frames", sys_current_frames, METH_NOARGS,
1448 current_frames_doc},
1449 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1450 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1451 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1452 {"exit", sys_exit, METH_VARARGS, exit_doc},
1453 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1454 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001455#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1457 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001458#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001459 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1460 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001461#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001462 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001463#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001464#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001465 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001466#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1468 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001469 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1470 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001471#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001473#endif
1474#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001475 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001476#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001477 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1478 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1479 getrecursionlimit_doc},
1480 {"getsizeof", (PyCFunction)sys_getsizeof,
1481 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1482 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001483#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1485 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001486 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1487 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001488#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001490 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001491#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001493#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1495 setcheckinterval_doc},
1496 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1497 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1499 setswitchinterval_doc},
1500 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1501 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001502#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1504 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001505#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1507 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1508 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1509 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 {"settrace", sys_settrace, METH_O, settrace_doc},
1511 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1512 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001513 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001514 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001515 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1516 set_coroutine_wrapper_doc},
1517 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1518 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001519 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001520 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1521 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1522 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001523#ifdef ANDROID_API_LEVEL
1524 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1525 getandroidapilevel_doc},
1526#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001528};
1529
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001530static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001531list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyObject *list = PyList_New(0);
1534 int i;
1535 if (list == NULL)
1536 return NULL;
1537 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1538 PyObject *name = PyUnicode_FromString(
1539 PyImport_Inittab[i].name);
1540 if (name == NULL)
1541 break;
1542 PyList_Append(list, name);
1543 Py_DECREF(name);
1544 }
1545 if (PyList_Sort(list) != 0) {
1546 Py_DECREF(list);
1547 list = NULL;
1548 }
1549 if (list) {
1550 PyObject *v = PyList_AsTuple(list);
1551 Py_DECREF(list);
1552 list = v;
1553 }
1554 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001555}
1556
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001557static PyObject *
1558get_warnoptions(void)
1559{
Eric Snowdae02762017-09-14 00:35:58 -07001560 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001561 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1562 Py_XDECREF(warnoptions);
1563 warnoptions = PyList_New(0);
1564 if (warnoptions == NULL)
1565 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001566 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1567 Py_DECREF(warnoptions);
1568 return NULL;
1569 }
1570 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001571 }
1572 return warnoptions;
1573}
Guido van Rossum23fff912000-12-15 22:02:05 +00001574
1575void
1576PySys_ResetWarnOptions(void)
1577{
Eric Snowdae02762017-09-14 00:35:58 -07001578 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (warnoptions == NULL || !PyList_Check(warnoptions))
1580 return;
1581 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001582}
1583
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001584int
1585_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001586{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001587 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001588 if (warnoptions == NULL) {
1589 return -1;
1590 }
1591 if (PyList_Append(warnoptions, option)) {
1592 return -1;
1593 }
1594 return 0;
1595}
1596
1597void
1598PySys_AddWarnOptionUnicode(PyObject *option)
1599{
1600 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001601}
1602
1603void
1604PySys_AddWarnOption(const wchar_t *s)
1605{
1606 PyObject *unicode;
1607 unicode = PyUnicode_FromWideChar(s, -1);
1608 if (unicode == NULL)
1609 return;
1610 PySys_AddWarnOptionUnicode(unicode);
1611 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001612}
1613
Christian Heimes33fe8092008-04-13 13:53:33 +00001614int
1615PySys_HasWarnOptions(void)
1616{
Eric Snowdae02762017-09-14 00:35:58 -07001617 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001618 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1619}
1620
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001621static PyObject *
1622get_xoptions(void)
1623{
Eric Snowdae02762017-09-14 00:35:58 -07001624 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001625 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1626 Py_XDECREF(xoptions);
1627 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001628 if (xoptions == NULL)
1629 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001630 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1631 Py_DECREF(xoptions);
1632 return NULL;
1633 }
1634 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001635 }
1636 return xoptions;
1637}
1638
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001639int
1640_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001641{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001642 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001643
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001644 PyObject *opts = get_xoptions();
1645 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001646 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001647 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001648
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001649 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001650 if (!name_end) {
1651 name = PyUnicode_FromWideChar(s, -1);
1652 value = Py_True;
1653 Py_INCREF(value);
1654 }
1655 else {
1656 name = PyUnicode_FromWideChar(s, name_end - s);
1657 value = PyUnicode_FromWideChar(name_end + 1, -1);
1658 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001659 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001660 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001661 }
1662 if (PyDict_SetItem(opts, name, value) < 0) {
1663 goto error;
1664 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001665 Py_DECREF(name);
1666 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001667 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001668
1669error:
1670 Py_XDECREF(name);
1671 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001672 return -1;
1673}
1674
1675void
1676PySys_AddXOption(const wchar_t *s)
1677{
1678 if (_PySys_AddXOptionWithError(s) < 0) {
1679 /* No return value, therefore clear error state if possible */
1680 if (_PyThreadState_UncheckedGet()) {
1681 PyErr_Clear();
1682 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001683 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001684}
1685
1686PyObject *
1687PySys_GetXOptions(void)
1688{
1689 return get_xoptions();
1690}
1691
Guido van Rossum40552d01998-08-06 03:34:39 +00001692/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1693 Two literals concatenated works just fine. If you have a K&R compiler
1694 or other abomination that however *does* understand longer strings,
1695 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001696PyDoc_VAR(sys_doc) =
1697PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001698"This module provides access to some objects used or maintained by the\n\
1699interpreter and to functions that interact strongly with the interpreter.\n\
1700\n\
1701Dynamic objects:\n\
1702\n\
1703argv -- command line arguments; argv[0] is the script pathname if known\n\
1704path -- module search path; path[0] is the script directory, else ''\n\
1705modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001706\n\
1707displayhook -- called to show results in an interactive session\n\
1708excepthook -- called to handle any uncaught exception other than SystemExit\n\
1709 To customize printing in an interactive session or to install a custom\n\
1710 top-level exception handler, assign other functions to replace these.\n\
1711\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001712stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001713stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001714stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001715 By assigning other file objects (or objects that behave like files)\n\
1716 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001717\n\
1718last_type -- type of last uncaught exception\n\
1719last_value -- value of last uncaught exception\n\
1720last_traceback -- traceback of last uncaught exception\n\
1721 These three are only available in an interactive session after a\n\
1722 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001723"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001724)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001725/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001726PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001727"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001728Static objects:\n\
1729\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001730builtin_module_names -- tuple of module names built into this interpreter\n\
1731copyright -- copyright notice pertaining to this interpreter\n\
1732exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001733executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001734float_info -- a struct sequence with information about the float implementation.\n\
1735float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001736hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001737hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001738implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001739int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001740maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001741maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001742platform -- platform identifier\n\
1743prefix -- prefix used to find the Python library\n\
1744thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001745version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001746version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001747"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001748)
Steve Dowercc16be82016-09-08 10:35:16 -07001749#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001750/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001751PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001752"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001753winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001754"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001755)
Steve Dowercc16be82016-09-08 10:35:16 -07001756#endif /* MS_COREDLL */
1757#ifdef MS_WINDOWS
1758/* concatenating string here */
1759PyDoc_STR(
1760"_enablelegacywindowsfsencoding -- [Windows only] \n\
1761"
1762)
1763#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001764PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001765"__stdin__ -- the original stdin; don't touch!\n\
1766__stdout__ -- the original stdout; don't touch!\n\
1767__stderr__ -- the original stderr; don't touch!\n\
1768__displayhook__ -- the original displayhook; don't touch!\n\
1769__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001770\n\
1771Functions:\n\
1772\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001773displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001774excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001775exc_info() -- return thread-safe information about the current exception\n\
1776exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001777getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001778getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001779getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001780getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001781getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001782gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001783setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001784setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001785setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001786setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001787settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001788"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001789)
Fred Drakeccede592000-08-14 20:59:57 +00001790/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001791
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001792
1793PyDoc_STRVAR(flags__doc__,
1794"sys.flags\n\
1795\n\
1796Flags provided through command line arguments or environment vars.");
1797
1798static PyTypeObject FlagsType;
1799
1800static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 {"inspect", "-i"},
1803 {"interactive", "-i"},
1804 {"optimize", "-O or -OO"},
1805 {"dont_write_bytecode", "-B"},
1806 {"no_user_site", "-s"},
1807 {"no_site", "-S"},
1808 {"ignore_environment", "-E"},
1809 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 /* {"unbuffered", "-u"}, */
1811 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001812 {"bytes_warning", "-b"},
1813 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001814 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001815 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01001816 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01001817 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001819};
1820
1821static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 "sys.flags", /* name */
1823 flags__doc__, /* doc */
1824 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01001825 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001826};
1827
1828static PyObject*
1829make_flags(void)
1830{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001831 int pos = 0;
1832 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01001833 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001834
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001835 seq = PyStructSequence_New(&FlagsType);
1836 if (seq == NULL)
1837 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001838
1839#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001840 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001841
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001842 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 SetFlag(Py_InspectFlag);
1844 SetFlag(Py_InteractiveFlag);
1845 SetFlag(Py_OptimizeFlag);
1846 SetFlag(Py_DontWriteBytecodeFlag);
1847 SetFlag(Py_NoUserSiteDirectory);
1848 SetFlag(Py_NoSiteFlag);
1849 SetFlag(Py_IgnoreEnvironmentFlag);
1850 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001851 /* SetFlag(saw_unbuffered_flag); */
1852 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001853 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001854 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001855 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001856 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01001857 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01001858 SetFlag(Py_UTF8Mode);
1859#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001860
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001862 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 return NULL;
1864 }
1865 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001866}
1867
Eric Smith0e5b5622009-02-06 01:32:42 +00001868PyDoc_STRVAR(version_info__doc__,
1869"sys.version_info\n\
1870\n\
1871Version information as a named tuple.");
1872
1873static PyTypeObject VersionInfoType;
1874
1875static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001876 {"major", "Major release number"},
1877 {"minor", "Minor release number"},
1878 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001879 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 {"serial", "Serial release number"},
1881 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001882};
1883
1884static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001885 "sys.version_info", /* name */
1886 version_info__doc__, /* doc */
1887 version_info_fields, /* fields */
1888 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001889};
1890
1891static PyObject *
1892make_version_info(void)
1893{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 PyObject *version_info;
1895 char *s;
1896 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001897
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 version_info = PyStructSequence_New(&VersionInfoType);
1899 if (version_info == NULL) {
1900 return NULL;
1901 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001902
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /*
1904 * These release level checks are mutually exclusive and cover
1905 * the field, so don't get too fancy with the pre-processor!
1906 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001907#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001909#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001911#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001913#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001915#endif
1916
1917#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001919#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001922 SetIntItem(PY_MAJOR_VERSION);
1923 SetIntItem(PY_MINOR_VERSION);
1924 SetIntItem(PY_MICRO_VERSION);
1925 SetStrItem(s);
1926 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001927#undef SetIntItem
1928#undef SetStrItem
1929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 if (PyErr_Occurred()) {
1931 Py_CLEAR(version_info);
1932 return NULL;
1933 }
1934 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001935}
1936
Brett Cannon3adc7b72012-07-09 14:22:12 -04001937/* sys.implementation values */
1938#define NAME "cpython"
1939const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001940#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1941#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001942#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001943const char *_PySys_ImplCacheTag = TAG;
1944#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001945#undef MAJOR
1946#undef MINOR
1947#undef TAG
1948
Barry Warsaw409da152012-06-03 16:18:47 -04001949static PyObject *
1950make_impl_info(PyObject *version_info)
1951{
1952 int res;
1953 PyObject *impl_info, *value, *ns;
1954
1955 impl_info = PyDict_New();
1956 if (impl_info == NULL)
1957 return NULL;
1958
1959 /* populate the dict */
1960
Brett Cannon3adc7b72012-07-09 14:22:12 -04001961 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001962 if (value == NULL)
1963 goto error;
1964 res = PyDict_SetItemString(impl_info, "name", value);
1965 Py_DECREF(value);
1966 if (res < 0)
1967 goto error;
1968
Brett Cannon3adc7b72012-07-09 14:22:12 -04001969 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001970 if (value == NULL)
1971 goto error;
1972 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1973 Py_DECREF(value);
1974 if (res < 0)
1975 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001976
1977 res = PyDict_SetItemString(impl_info, "version", version_info);
1978 if (res < 0)
1979 goto error;
1980
1981 value = PyLong_FromLong(PY_VERSION_HEX);
1982 if (value == NULL)
1983 goto error;
1984 res = PyDict_SetItemString(impl_info, "hexversion", value);
1985 Py_DECREF(value);
1986 if (res < 0)
1987 goto error;
1988
doko@ubuntu.com55532312016-06-14 08:55:19 +02001989#ifdef MULTIARCH
1990 value = PyUnicode_FromString(MULTIARCH);
1991 if (value == NULL)
1992 goto error;
1993 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1994 Py_DECREF(value);
1995 if (res < 0)
1996 goto error;
1997#endif
1998
Barry Warsaw409da152012-06-03 16:18:47 -04001999 /* dict ready */
2000
2001 ns = _PyNamespace_New(impl_info);
2002 Py_DECREF(impl_info);
2003 return ns;
2004
2005error:
2006 Py_CLEAR(impl_info);
2007 return NULL;
2008}
2009
Martin v. Löwis1a214512008-06-11 05:26:20 +00002010static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyModuleDef_HEAD_INIT,
2012 "sys",
2013 sys_doc,
2014 -1, /* multiple "initialization" just copies the module dict. */
2015 sys_methods,
2016 NULL,
2017 NULL,
2018 NULL,
2019 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002020};
2021
Eric Snow6b4be192017-05-22 21:36:03 -07002022/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002023#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002024 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002025 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002026 if (v == NULL) { \
2027 goto err_occurred; \
2028 } \
Victor Stinner58049602013-07-22 22:40:00 +02002029 res = PyDict_SetItemString(sysdict, key, v); \
2030 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002031 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002032 } \
2033 } while (0)
2034#define SET_SYS_FROM_STRING(key, value) \
2035 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002036 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002037 if (v == NULL) { \
2038 goto err_occurred; \
2039 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002040 res = PyDict_SetItemString(sysdict, key, v); \
2041 Py_DECREF(v); \
2042 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002043 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002044 } \
2045 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002046
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002047
2048_PyInitError
2049_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002050{
2051 PyObject *m, *sysdict, *version_info;
2052 int res;
2053
Eric Snowd393c1b2017-09-14 12:18:12 -06002054 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002055 if (m == NULL) {
2056 return _Py_INIT_ERR("failed to create a module object");
2057 }
Eric Snow6b4be192017-05-22 21:36:03 -07002058 sysdict = PyModule_GetDict(m);
2059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002061 Using shell redirection, you can redirect stdin to a directory,
2062 crashing the Python interpreter. Catch this common mistake here
2063 and output a useful error message. Note that under MS Windows,
2064 the shell already prevents that. */
2065#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002067 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002068 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002070 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2071 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 }
2073 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002074#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002075
Nick Coghland6009512014-11-20 21:39:37 +10002076 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002077
Victor Stinner8fea2522013-10-27 17:15:42 +01002078 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2079 PyDict_GetItemString(sysdict, "displayhook"));
2080 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2081 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002082 SET_SYS_FROM_STRING_BORROW(
2083 "__breakpointhook__",
2084 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 SET_SYS_FROM_STRING("version",
2086 PyUnicode_FromString(Py_GetVersion()));
2087 SET_SYS_FROM_STRING("hexversion",
2088 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002089 SET_SYS_FROM_STRING("_git",
2090 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2091 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002092 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 SET_SYS_FROM_STRING("api_version",
2094 PyLong_FromLong(PYTHON_API_VERSION));
2095 SET_SYS_FROM_STRING("copyright",
2096 PyUnicode_FromString(Py_GetCopyright()));
2097 SET_SYS_FROM_STRING("platform",
2098 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 SET_SYS_FROM_STRING("maxsize",
2100 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2101 SET_SYS_FROM_STRING("float_info",
2102 PyFloat_GetInfo());
2103 SET_SYS_FROM_STRING("int_info",
2104 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002105 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002106 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002107 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2108 goto type_init_failed;
2109 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002110 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002111 SET_SYS_FROM_STRING("hash_info",
2112 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002114 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 SET_SYS_FROM_STRING("builtin_module_names",
2116 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002117#if PY_BIG_ENDIAN
2118 SET_SYS_FROM_STRING("byteorder",
2119 PyUnicode_FromString("big"));
2120#else
2121 SET_SYS_FROM_STRING("byteorder",
2122 PyUnicode_FromString("little"));
2123#endif
Fred Drake099325e2000-08-14 15:47:03 +00002124
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002125#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 SET_SYS_FROM_STRING("dllhandle",
2127 PyLong_FromVoidPtr(PyWin_DLLhModule));
2128 SET_SYS_FROM_STRING("winver",
2129 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002130#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002131#ifdef ABIFLAGS
2132 SET_SYS_FROM_STRING("abiflags",
2133 PyUnicode_FromString(ABIFLAGS));
2134#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002137 if (VersionInfoType.tp_name == NULL) {
2138 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002139 &version_info_desc) < 0) {
2140 goto type_init_failed;
2141 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002142 }
Barry Warsaw409da152012-06-03 16:18:47 -04002143 version_info = make_version_info();
2144 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 /* prevent user from creating new instances */
2146 VersionInfoType.tp_init = NULL;
2147 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002148 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2149 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2150 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002151
Barry Warsaw409da152012-06-03 16:18:47 -04002152 /* implementation */
2153 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002156 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002157 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2158 goto type_init_failed;
2159 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002160 }
Eric Snow6b4be192017-05-22 21:36:03 -07002161 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002163
2164#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 /* getwindowsversion */
2166 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002167 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002168 &windows_version_desc) < 0) {
2169 goto type_init_failed;
2170 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 /* prevent user from creating new instances */
2172 WindowsVersionType.tp_init = NULL;
2173 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002174 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002175 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002176 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002177 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002178 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002179#endif
2180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002182#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 SET_SYS_FROM_STRING("float_repr_style",
2184 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002185#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 SET_SYS_FROM_STRING("float_repr_style",
2187 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002188#endif
2189
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002190 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002191
Yury Selivanoveb636452016-09-08 22:01:51 -07002192 /* initialize asyncgen_hooks */
2193 if (AsyncGenHooksType.tp_name == NULL) {
2194 if (PyStructSequence_InitType2(
2195 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002196 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002197 }
2198 }
2199
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002200 if (PyErr_Occurred()) {
2201 goto err_occurred;
2202 }
2203
2204 *sysmod = m;
2205 return _Py_INIT_OK();
2206
2207type_init_failed:
2208 return _Py_INIT_ERR("failed to initialize a type");
2209
2210err_occurred:
2211 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002212}
2213
Eric Snow6b4be192017-05-22 21:36:03 -07002214#undef SET_SYS_FROM_STRING
2215#undef SET_SYS_FROM_STRING_BORROW
2216
2217/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002218#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2219 do { \
2220 PyObject *v = (value); \
2221 if (v == NULL) \
2222 return -1; \
2223 res = PyDict_SetItemString(sysdict, key, v); \
2224 Py_DECREF(v); \
2225 if (res < 0) { \
2226 return res; \
2227 } \
2228 } while (0)
2229
2230int
2231_PySys_EndInit(PyObject *sysdict)
2232{
2233 int res;
2234
2235 /* Set flags to their final values */
2236 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2237 /* prevent user from creating new instances */
2238 FlagsType.tp_init = NULL;
2239 FlagsType.tp_new = NULL;
2240 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2241 if (res < 0) {
2242 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2243 return res;
2244 }
2245 PyErr_Clear();
2246 }
2247
2248 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2249 PyBool_FromLong(Py_DontWriteBytecodeFlag));
2250 SET_SYS_FROM_STRING_INT_RESULT("executable",
2251 PyUnicode_FromWideChar(
2252 Py_GetProgramFullPath(), -1));
2253 SET_SYS_FROM_STRING_INT_RESULT("prefix",
2254 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2255 SET_SYS_FROM_STRING_INT_RESULT("exec_prefix",
2256 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2257 SET_SYS_FROM_STRING_INT_RESULT("base_prefix",
2258 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
2259 SET_SYS_FROM_STRING_INT_RESULT("base_exec_prefix",
2260 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
2261
Eric Snowdae02762017-09-14 00:35:58 -07002262 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002263 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002264
Eric Snowdae02762017-09-14 00:35:58 -07002265 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002266 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002267
2268 if (PyErr_Occurred())
2269 return -1;
2270 return 0;
2271}
2272
2273#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002274
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002275static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002276makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002277{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002278 int i, n;
2279 const wchar_t *p;
2280 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002282 n = 1;
2283 p = path;
2284 while ((p = wcschr(p, delim)) != NULL) {
2285 n++;
2286 p++;
2287 }
2288 v = PyList_New(n);
2289 if (v == NULL)
2290 return NULL;
2291 for (i = 0; ; i++) {
2292 p = wcschr(path, delim);
2293 if (p == NULL)
2294 p = path + wcslen(path); /* End of string */
2295 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2296 if (w == NULL) {
2297 Py_DECREF(v);
2298 return NULL;
2299 }
2300 PyList_SetItem(v, i, w);
2301 if (*p == '\0')
2302 break;
2303 path = p+1;
2304 }
2305 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002306}
2307
2308void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002309PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002310{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 PyObject *v;
2312 if ((v = makepathobject(path, DELIM)) == NULL)
2313 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002314 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 Py_FatalError("can't assign sys.path");
2316 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002317}
2318
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002319static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002320makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 PyObject *av;
2323 if (argc <= 0 || argv == NULL) {
2324 /* Ensure at least one (empty) argument is seen */
2325 static wchar_t *empty_argv[1] = {L""};
2326 argv = empty_argv;
2327 argc = 1;
2328 }
2329 av = PyList_New(argc);
2330 if (av != NULL) {
2331 int i;
2332 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002334 if (v == NULL) {
2335 Py_DECREF(av);
2336 av = NULL;
2337 break;
2338 }
2339 PyList_SetItem(av, i, v);
2340 }
2341 }
2342 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002343}
2344
Nick Coghland26c18a2010-08-17 13:06:11 +00002345#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2346 (argc > 0 && argv0 != NULL && \
2347 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002348
2349static void
2350sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002351{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002352 wchar_t *argv0;
2353 wchar_t *p = NULL;
2354 Py_ssize_t n = 0;
2355 PyObject *a;
2356 PyObject *path;
2357#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002358 wchar_t link[MAXPATHLEN+1];
2359 wchar_t argv0copy[2*MAXPATHLEN+1];
2360 int nr = 0;
2361#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002362#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002363 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002364#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002366#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002367
Victor Stinnerbd303c12013-11-07 23:07:29 +01002368 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002369 if (path == NULL)
2370 return;
2371
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002372 argv0 = argv[0];
2373
2374#ifdef HAVE_READLINK
2375 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2376 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2377 if (nr > 0) {
2378 /* It's a symlink */
2379 link[nr] = '\0';
2380 if (link[0] == SEP)
2381 argv0 = link; /* Link to absolute path */
2382 else if (wcschr(link, SEP) == NULL)
2383 ; /* Link without path */
2384 else {
2385 /* Must join(dirname(argv0), link) */
2386 wchar_t *q = wcsrchr(argv0, SEP);
2387 if (q == NULL)
2388 argv0 = link; /* argv0 without path */
2389 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002390 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2391 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002392 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002393 wcsncpy(q+1, link, MAXPATHLEN);
2394 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002395 argv0 = argv0copy;
2396 }
2397 }
2398 }
2399#endif /* HAVE_READLINK */
2400#if SEP == '\\' /* Special case for MS filename syntax */
2401 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2402 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002403#if defined(MS_WINDOWS)
2404 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002405 wchar_t *ptemp;
2406 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002407 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002408 fullpath,
2409 &ptemp)) {
2410 argv0 = fullpath;
2411 }
2412#endif
2413 p = wcsrchr(argv0, SEP);
2414 /* Test for alternate separator */
2415 q = wcsrchr(p ? p : argv0, '/');
2416 if (q != NULL)
2417 p = q;
2418 if (p != NULL) {
2419 n = p + 1 - argv0;
2420 if (n > 1 && p[-1] != ':')
2421 n--; /* Drop trailing separator */
2422 }
2423 }
2424#else /* All other filename syntaxes */
2425 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2426#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002427 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002428 argv0 = fullpath;
2429 }
2430#endif
2431 p = wcsrchr(argv0, SEP);
2432 }
2433 if (p != NULL) {
2434 n = p + 1 - argv0;
2435#if SEP == '/' /* Special case for Unix filename syntax */
2436 if (n > 1)
2437 n--; /* Drop trailing separator */
2438#endif /* Unix */
2439 }
2440#endif /* All others */
2441 a = PyUnicode_FromWideChar(argv0, n);
2442 if (a == NULL)
2443 Py_FatalError("no mem for sys.path insertion");
2444 if (PyList_Insert(path, 0, a) < 0)
2445 Py_FatalError("sys.path.insert(0) failed");
2446 Py_DECREF(a);
2447}
2448
Victor Stinnerd5dda982017-12-13 17:31:16 +01002449_PyInitError
2450_PySys_SetArgvWithError(int argc, wchar_t **argv, int updatepath)
2451{
2452 PyObject *av = makeargvobject(argc, argv);
2453 if (av == NULL) {
2454 return _Py_INIT_NO_MEMORY();
2455 }
2456 if (PySys_SetObject("argv", av) != 0) {
2457 Py_DECREF(av);
2458 return _Py_INIT_ERR("can't assign sys.argv");
2459 }
2460 Py_DECREF(av);
2461
2462 if (updatepath) {
2463 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2464 If argv[0] is a symlink, use the real path. */
2465 sys_update_path(argc, argv);
2466 }
2467 return _Py_INIT_OK();
2468}
2469
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002470void
2471PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2472{
Victor Stinnerd5dda982017-12-13 17:31:16 +01002473 _PyInitError err = _PySys_SetArgvWithError(argc, argv, updatepath);
2474 if (_Py_INIT_FAILED(err)) {
2475 _Py_FatalInitError(err);
2476 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002477}
Guido van Rossuma890e681998-05-12 14:59:24 +00002478
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002479void
2480PySys_SetArgv(int argc, wchar_t **argv)
2481{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002482 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002483}
2484
Victor Stinner14284c22010-04-23 12:02:30 +00002485/* Reimplementation of PyFile_WriteString() no calling indirectly
2486 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2487
2488static int
Victor Stinner79766632010-08-16 17:36:42 +00002489sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002490{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002491 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002493
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002494 if (file == NULL)
2495 return -1;
2496
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002497 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 if (writer == NULL)
2499 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002500
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002501 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 if (result == NULL) {
2503 goto error;
2504 } else {
2505 err = 0;
2506 goto finally;
2507 }
Victor Stinner14284c22010-04-23 12:02:30 +00002508
2509error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002510 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002511finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002513 Py_XDECREF(result);
2514 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002515}
2516
Victor Stinner79766632010-08-16 17:36:42 +00002517static int
2518sys_pyfile_write(const char *text, PyObject *file)
2519{
2520 PyObject *unicode = NULL;
2521 int err;
2522
2523 if (file == NULL)
2524 return -1;
2525
2526 unicode = PyUnicode_FromString(text);
2527 if (unicode == NULL)
2528 return -1;
2529
2530 err = sys_pyfile_write_unicode(unicode, file);
2531 Py_DECREF(unicode);
2532 return err;
2533}
Guido van Rossuma890e681998-05-12 14:59:24 +00002534
2535/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2536 Adapted from code submitted by Just van Rossum.
2537
2538 PySys_WriteStdout(format, ...)
2539 PySys_WriteStderr(format, ...)
2540
2541 The first function writes to sys.stdout; the second to sys.stderr. When
2542 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002543 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002544
Victor Stinner14284c22010-04-23 12:02:30 +00002545 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002546 signal handlers: they may raise a new exception whereas sys_write()
2547 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002548
Guido van Rossuma890e681998-05-12 14:59:24 +00002549 Both take a printf-style format string as their first argument followed
2550 by a variable length argument list determined by the format string.
2551
2552 *** WARNING ***
2553
2554 The format should limit the total size of the formatted output string to
2555 1000 bytes. In particular, this means that no unrestricted "%s" formats
2556 should occur; these should be limited using "%.<N>s where <N> is a
2557 decimal number calculated so that <N> plus the maximum size of other
2558 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2559 which can print hundreds of digits for very large numbers.
2560
2561 */
2562
2563static void
Victor Stinner09054372013-11-06 22:41:44 +01002564sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002565{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002566 PyObject *file;
2567 PyObject *error_type, *error_value, *error_traceback;
2568 char buffer[1001];
2569 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002572 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2574 if (sys_pyfile_write(buffer, file) != 0) {
2575 PyErr_Clear();
2576 fputs(buffer, fp);
2577 }
2578 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2579 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002580 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002582 }
2583 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002584}
2585
2586void
Guido van Rossuma890e681998-05-12 14:59:24 +00002587PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002589 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002592 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002594}
2595
2596void
Guido van Rossuma890e681998-05-12 14:59:24 +00002597PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002601 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002602 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002603 va_end(va);
2604}
2605
2606static void
Victor Stinner09054372013-11-06 22:41:44 +01002607sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002608{
2609 PyObject *file, *message;
2610 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002611 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002612
2613 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002614 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002615 message = PyUnicode_FromFormatV(format, va);
2616 if (message != NULL) {
2617 if (sys_pyfile_write_unicode(message, file) != 0) {
2618 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002619 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002620 if (utf8 != NULL)
2621 fputs(utf8, fp);
2622 }
2623 Py_DECREF(message);
2624 }
2625 PyErr_Restore(error_type, error_value, error_traceback);
2626}
2627
2628void
2629PySys_FormatStdout(const char *format, ...)
2630{
2631 va_list va;
2632
2633 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002634 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002635 va_end(va);
2636}
2637
2638void
2639PySys_FormatStderr(const char *format, ...)
2640{
2641 va_list va;
2642
2643 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002644 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002646}