blob: fb1dcfa3afe86c5731caf539bd01fb88ef47b13b [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
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037/*[clinic input]
38module sys
39[clinic start generated code]*/
40/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
41
42#include "clinic/sysmodule.c.h"
43
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(_);
45_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070046_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(buffer);
48_Py_IDENTIFIER(builtins);
49_Py_IDENTIFIER(encoding);
50_Py_IDENTIFIER(path);
51_Py_IDENTIFIER(stdout);
52_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070053_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010054_Py_IDENTIFIER(write);
55
Guido van Rossum65bf9f21997-04-29 18:33:38 +000056PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010057_PySys_GetObjectId(_Py_Identifier *key)
58{
59 PyThreadState *tstate = PyThreadState_GET();
60 PyObject *sd = tstate->interp->sysdict;
61 if (sd == NULL)
62 return NULL;
63 return _PyDict_GetItemId(sd, key);
64}
65
66PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000067PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 PyThreadState *tstate = PyThreadState_GET();
70 PyObject *sd = tstate->interp->sysdict;
71 if (sd == NULL)
72 return NULL;
73 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074}
75
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076int
Victor Stinnerd67bd452013-11-06 22:36:40 +010077_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
78{
79 PyThreadState *tstate = PyThreadState_GET();
80 PyObject *sd = tstate->interp->sysdict;
81 if (v == NULL) {
82 if (_PyDict_GetItemId(sd, key) == NULL)
83 return 0;
84 else
85 return _PyDict_DelItemId(sd, key);
86 }
87 else
88 return _PyDict_SetItemId(sd, key, v);
89}
90
91int
Neal Norwitzf3081322007-08-25 00:32:45 +000092PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 PyThreadState *tstate = PyThreadState_GET();
95 PyObject *sd = tstate->interp->sysdict;
96 if (v == NULL) {
97 if (PyDict_GetItemString(sd, name) == NULL)
98 return 0;
99 else
100 return PyDict_DelItemString(sd, name);
101 }
102 else
103 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104}
105
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400106static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200107sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400108{
109 assert(!PyErr_Occurred());
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200110 const char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400111
112 if (envar == NULL || strlen(envar) == 0) {
113 envar = "pdb.set_trace";
114 }
115 else if (!strcmp(envar, "0")) {
116 /* The breakpoint is explicitly no-op'd. */
117 Py_RETURN_NONE;
118 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200119 const char *last_dot = strrchr(envar, '.');
120 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400121 PyObject *modulepath = NULL;
122
123 if (last_dot == NULL) {
124 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
125 modulepath = PyUnicode_FromString("builtins");
126 attrname = envar;
127 }
128 else {
129 /* Split on the last dot; */
130 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
131 attrname = last_dot + 1;
132 }
133 if (modulepath == NULL) {
134 return NULL;
135 }
136
137 PyObject *fromlist = Py_BuildValue("(s)", attrname);
138 if (fromlist == NULL) {
139 Py_DECREF(modulepath);
140 return NULL;
141 }
142 PyObject *module = PyImport_ImportModuleLevelObject(
143 modulepath, NULL, NULL, fromlist, 0);
144 Py_DECREF(modulepath);
145 Py_DECREF(fromlist);
146
147 if (module == NULL) {
148 goto error;
149 }
150
151 PyObject *hook = PyObject_GetAttrString(module, attrname);
152 Py_DECREF(module);
153
154 if (hook == NULL) {
155 goto error;
156 }
157 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
158 Py_DECREF(hook);
159 return retval;
160
161 error:
162 /* If any of the imports went wrong, then warn and ignore. */
163 PyErr_Clear();
164 int status = PyErr_WarnFormat(
165 PyExc_RuntimeWarning, 0,
166 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
167 if (status < 0) {
168 /* Printing the warning raised an exception. */
169 return NULL;
170 }
171 /* The warning was (probably) issued. */
172 Py_RETURN_NONE;
173}
174
175PyDoc_STRVAR(breakpointhook_doc,
176"breakpointhook(*args, **kws)\n"
177"\n"
178"This hook function is called by built-in breakpoint().\n"
179);
180
Victor Stinner13d49ee2010-12-04 17:24:33 +0000181/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
182 error handler. If sys.stdout has a buffer attribute, use
183 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
184 sys.stdout.write(redecoded).
185
186 Helper function for sys_displayhook(). */
187static int
188sys_displayhook_unencodable(PyObject *outf, PyObject *o)
189{
190 PyObject *stdout_encoding = NULL;
191 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200192 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000193 int ret;
194
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200195 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000196 if (stdout_encoding == NULL)
197 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200198 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000199 if (stdout_encoding_str == NULL)
200 goto error;
201
202 repr_str = PyObject_Repr(o);
203 if (repr_str == NULL)
204 goto error;
205 encoded = PyUnicode_AsEncodedString(repr_str,
206 stdout_encoding_str,
207 "backslashreplace");
208 Py_DECREF(repr_str);
209 if (encoded == NULL)
210 goto error;
211
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200212 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000213 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100214 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000215 Py_DECREF(buffer);
216 Py_DECREF(encoded);
217 if (result == NULL)
218 goto error;
219 Py_DECREF(result);
220 }
221 else {
222 PyErr_Clear();
223 escaped_str = PyUnicode_FromEncodedObject(encoded,
224 stdout_encoding_str,
225 "strict");
226 Py_DECREF(encoded);
227 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
228 Py_DECREF(escaped_str);
229 goto error;
230 }
231 Py_DECREF(escaped_str);
232 }
233 ret = 0;
234 goto finally;
235
236error:
237 ret = -1;
238finally:
239 Py_XDECREF(stdout_encoding);
240 return ret;
241}
242
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000243static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000244sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000245{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100247 PyObject *builtins;
248 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000249 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000250
Eric Snow3f9eee62017-09-15 16:35:20 -0600251 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 if (builtins == NULL) {
253 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
254 return NULL;
255 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600256 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000257
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 /* Print value except if None */
259 /* After printing, also assign to '_' */
260 /* Before, set '_' to None to avoid recursion */
261 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200262 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200264 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100266 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (outf == NULL || outf == Py_None) {
268 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
269 return NULL;
270 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000271 if (PyFile_WriteObject(o, outf, 0) != 0) {
272 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
273 /* repr(o) is not encodable to sys.stdout.encoding with
274 * sys.stdout.errors error handler (which is probably 'strict') */
275 PyErr_Clear();
276 err = sys_displayhook_unencodable(outf, o);
277 if (err)
278 return NULL;
279 }
280 else {
281 return NULL;
282 }
283 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100284 if (newline == NULL) {
285 newline = PyUnicode_FromString("\n");
286 if (newline == NULL)
287 return NULL;
288 }
289 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200291 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200293 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000294}
295
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000296PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000297"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000298"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000299"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000300);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000301
302static PyObject *
303sys_excepthook(PyObject* self, PyObject* args)
304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 PyObject *exc, *value, *tb;
306 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
307 return NULL;
308 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200309 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000310}
311
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000312PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000313"excepthook(exctype, value, traceback) -> None\n"
314"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000315"Handle an exception by displaying it with a traceback on sys.stderr.\n"
316);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000317
318static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000319sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000320{
Mark Shannonae3087c2017-10-22 22:41:51 +0100321 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 return Py_BuildValue(
323 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100324 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
325 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
326 err_info->exc_traceback != NULL ?
327 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000328}
329
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000330PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000331"exc_info() -> (type, value, traceback)\n\
332\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000333Return information about the most recent exception caught by an except\n\
334clause in the current stack frame or in an older stack frame."
335);
336
337static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000338sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000339{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 PyObject *exit_code = 0;
341 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
342 return NULL;
343 /* Raise SystemExit so callers may catch it or clean up. */
344 PyErr_SetObject(PyExc_SystemExit, exit_code);
345 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000346}
347
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000348PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000349"exit([status])\n\
350\n\
351Exit the interpreter by raising SystemExit(status).\n\
352If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300353If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000354If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000355exit status will be one (i.e., failure)."
356);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000357
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000358
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000359static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000360sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000363}
364
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000365PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000366"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000367\n\
oldkaa0735f2018-02-02 16:52:55 +0800368Return the current default string encoding used by the Unicode\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000369implementation."
370);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000371
372static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000373sys_getfilesystemencoding(PyObject *self)
374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 if (Py_FileSystemDefaultEncoding)
376 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200377 PyErr_SetString(PyExc_RuntimeError,
378 "filesystem encoding is not initialized");
379 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000380}
381
382PyDoc_STRVAR(getfilesystemencoding_doc,
383"getfilesystemencoding() -> string\n\
384\n\
385Return the encoding used to convert Unicode filenames in\n\
386operating system filenames."
387);
388
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000389static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700390sys_getfilesystemencodeerrors(PyObject *self)
391{
392 if (Py_FileSystemDefaultEncodeErrors)
393 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
394 PyErr_SetString(PyExc_RuntimeError,
395 "filesystem encoding is not initialized");
396 return NULL;
397}
398
399PyDoc_STRVAR(getfilesystemencodeerrors_doc,
400 "getfilesystemencodeerrors() -> string\n\
401\n\
402Return the error mode used to convert Unicode filenames in\n\
403operating system filenames."
404);
405
406static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000407sys_intern(PyObject *self, PyObject *args)
408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 PyObject *s;
410 if (!PyArg_ParseTuple(args, "U:intern", &s))
411 return NULL;
412 if (PyUnicode_CheckExact(s)) {
413 Py_INCREF(s);
414 PyUnicode_InternInPlace(&s);
415 return s;
416 }
417 else {
418 PyErr_Format(PyExc_TypeError,
419 "can't intern %.400s", s->ob_type->tp_name);
420 return NULL;
421 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000422}
423
424PyDoc_STRVAR(intern_doc,
425"intern(string) -> string\n\
426\n\
427``Intern'' the given string. This enters the string in the (global)\n\
428table of interned strings whose purpose is to speed up dictionary lookups.\n\
429Return the string itself or the previously interned string object with the\n\
430same value.");
431
432
Fred Drake5755ce62001-06-27 19:19:46 +0000433/*
434 * Cached interned string objects used for calling the profile and
435 * trace functions. Initialized by trace_init().
436 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000437static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000438
439static int
440trace_init(void)
441{
Nick Coghlan5a851672017-09-08 10:14:16 +1000442 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200443 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000444 "c_call", "c_exception", "c_return",
445 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200446 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000447 PyObject *name;
448 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000449 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (whatstrings[i] == NULL) {
451 name = PyUnicode_InternFromString(whatnames[i]);
452 if (name == NULL)
453 return -1;
454 whatstrings[i] = name;
455 }
456 }
457 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000458}
459
460
461static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100462call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200466 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000467
Victor Stinner78da82b2016-08-20 01:22:57 +0200468 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200470 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100471
Victor Stinner78da82b2016-08-20 01:22:57 +0200472 stack[0] = (PyObject *)frame;
473 stack[1] = whatstrings[what];
474 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200477 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000478
Victor Stinner78da82b2016-08-20 01:22:57 +0200479 PyFrame_LocalsToFast(frame, 1);
480 if (result == NULL) {
481 PyTraceBack_Here(frame);
482 }
483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000485}
486
487static int
488profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 if (arg == NULL)
494 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100495 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000496 if (result == NULL) {
497 PyEval_SetProfile(NULL, NULL);
498 return -1;
499 }
500 Py_DECREF(result);
501 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000502}
503
504static int
505trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyObject *callback;
509 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 if (what == PyTrace_CALL)
512 callback = self;
513 else
514 callback = frame->f_trace;
515 if (callback == NULL)
516 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100517 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 if (result == NULL) {
519 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200520 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return -1;
522 }
523 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300524 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 }
526 else {
527 Py_DECREF(result);
528 }
529 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000530}
Fred Draked0838392001-06-16 21:02:31 +0000531
Fred Drake8b4d01d2000-05-09 19:57:01 +0000532static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000533sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (trace_init() == -1)
536 return NULL;
537 if (args == Py_None)
538 PyEval_SetTrace(NULL, NULL);
539 else
540 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200541 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000542}
543
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000544PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000545"settrace(function)\n\
546\n\
547Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000548function call. See the debugger chapter in the library manual."
549);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000550
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000551static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000552sys_gettrace(PyObject *self, PyObject *args)
553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 PyThreadState *tstate = PyThreadState_GET();
555 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000556
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (temp == NULL)
558 temp = Py_None;
559 Py_INCREF(temp);
560 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000561}
562
563PyDoc_STRVAR(gettrace_doc,
564"gettrace()\n\
565\n\
566Return the global debug tracing function set with sys.settrace.\n\
567See the debugger chapter in the library manual."
568);
569
570static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000571sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (trace_init() == -1)
574 return NULL;
575 if (args == Py_None)
576 PyEval_SetProfile(NULL, NULL);
577 else
578 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200579 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000580}
581
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000582PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000583"setprofile(function)\n\
584\n\
585Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000586and return. See the profiler chapter in the library manual."
587);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000588
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000589static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000590sys_getprofile(PyObject *self, PyObject *args)
591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyThreadState *tstate = PyThreadState_GET();
593 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 if (temp == NULL)
596 temp = Py_None;
597 Py_INCREF(temp);
598 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000599}
600
601PyDoc_STRVAR(getprofile_doc,
602"getprofile()\n\
603\n\
604Return the profiling function set with sys.setprofile.\n\
605See the profiler chapter in the library manual."
606);
607
608static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000609sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (PyErr_WarnEx(PyExc_DeprecationWarning,
612 "sys.getcheckinterval() and sys.setcheckinterval() "
613 "are deprecated. Use sys.setswitchinterval() "
614 "instead.", 1) < 0)
615 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600616 PyInterpreterState *interp = PyThreadState_GET()->interp;
617 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200619 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000620}
621
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000622PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000623"setcheckinterval(n)\n\
624\n\
625Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000626n instructions. This also affects how often thread switches occur."
627);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000628
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000629static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000630sys_getcheckinterval(PyObject *self, PyObject *args)
631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (PyErr_WarnEx(PyExc_DeprecationWarning,
633 "sys.getcheckinterval() and sys.setcheckinterval() "
634 "are deprecated. Use sys.getswitchinterval() "
635 "instead.", 1) < 0)
636 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600637 PyInterpreterState *interp = PyThreadState_GET()->interp;
638 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000639}
640
641PyDoc_STRVAR(getcheckinterval_doc,
642"getcheckinterval() -> current check interval; see setcheckinterval()."
643);
644
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000645static PyObject *
646sys_setswitchinterval(PyObject *self, PyObject *args)
647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 double d;
649 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
650 return NULL;
651 if (d <= 0.0) {
652 PyErr_SetString(PyExc_ValueError,
653 "switch interval must be strictly positive");
654 return NULL;
655 }
656 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200657 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000658}
659
660PyDoc_STRVAR(setswitchinterval_doc,
661"setswitchinterval(n)\n\
662\n\
663Set the ideal thread switching delay inside the Python interpreter\n\
664The actual frequency of switching threads can be lower if the\n\
665interpreter executes long sequences of uninterruptible code\n\
666(this is implementation-specific and workload-dependent).\n\
667\n\
668The parameter must represent the desired switching delay in seconds\n\
669A typical value is 0.005 (5 milliseconds)."
670);
671
672static PyObject *
673sys_getswitchinterval(PyObject *self, PyObject *args)
674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000675 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000676}
677
678PyDoc_STRVAR(getswitchinterval_doc,
679"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
680);
681
Tim Peterse5e065b2003-07-06 18:36:54 +0000682static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000683sys_setrecursionlimit(PyObject *self, PyObject *args)
684{
Victor Stinner50856d52015-10-13 00:11:21 +0200685 int new_limit, mark;
686 PyThreadState *tstate;
687
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
689 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200690
691 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200693 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 return NULL;
695 }
Victor Stinner50856d52015-10-13 00:11:21 +0200696
697 /* Issue #25274: When the recursion depth hits the recursion limit in
698 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
699 set to 1 and a RecursionError is raised. The overflowed flag is reset
700 to 0 when the recursion depth goes below the low-water mark: see
701 Py_LeaveRecursiveCall().
702
703 Reject too low new limit if the current recursion depth is higher than
704 the new low-water mark. Otherwise it may not be possible anymore to
705 reset the overflowed flag to 0. */
706 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
707 tstate = PyThreadState_GET();
708 if (tstate->recursion_depth >= mark) {
709 PyErr_Format(PyExc_RecursionError,
710 "cannot set the recursion limit to %i at "
711 "the recursion depth %i: the limit is too low",
712 new_limit, tstate->recursion_depth);
713 return NULL;
714 }
715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200717 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000718}
719
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800720/*[clinic input]
721sys.set_coroutine_origin_tracking_depth
722
723 depth: int
724
725Enable or disable origin tracking for coroutine objects in this thread.
726
727Coroutine objects will track 'depth' frames of traceback information about
728where they came from, available in their cr_origin attribute. Set depth of 0
729to disable.
730[clinic start generated code]*/
731
732static PyObject *
733sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
734/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
735{
736 if (depth < 0) {
737 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
738 return NULL;
739 }
740 _PyEval_SetCoroutineOriginTrackingDepth(depth);
741 Py_RETURN_NONE;
742}
743
744/*[clinic input]
745sys.get_coroutine_origin_tracking_depth -> int
746
747Check status of origin tracking for coroutine objects in this thread.
748[clinic start generated code]*/
749
750static int
751sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
752/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
753{
754 return _PyEval_GetCoroutineOriginTrackingDepth();
755}
756
Yury Selivanov75445082015-05-11 22:57:16 -0400757static PyObject *
758sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
759{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800760 if (PyErr_WarnEx(PyExc_DeprecationWarning,
761 "set_coroutine_wrapper is deprecated", 1) < 0) {
762 return NULL;
763 }
764
Yury Selivanov75445082015-05-11 22:57:16 -0400765 if (wrapper != Py_None) {
766 if (!PyCallable_Check(wrapper)) {
767 PyErr_Format(PyExc_TypeError,
768 "callable expected, got %.50s",
769 Py_TYPE(wrapper)->tp_name);
770 return NULL;
771 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400772 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400773 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400774 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400775 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400776 }
Yury Selivanov75445082015-05-11 22:57:16 -0400777 Py_RETURN_NONE;
778}
779
780PyDoc_STRVAR(set_coroutine_wrapper_doc,
781"set_coroutine_wrapper(wrapper)\n\
782\n\
783Set a wrapper for coroutine objects."
784);
785
786static PyObject *
787sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
788{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800789 if (PyErr_WarnEx(PyExc_DeprecationWarning,
790 "get_coroutine_wrapper is deprecated", 1) < 0) {
791 return NULL;
792 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400793 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400794 if (wrapper == NULL) {
795 wrapper = Py_None;
796 }
797 Py_INCREF(wrapper);
798 return wrapper;
799}
800
801PyDoc_STRVAR(get_coroutine_wrapper_doc,
802"get_coroutine_wrapper()\n\
803\n\
804Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
805);
806
807
Yury Selivanoveb636452016-09-08 22:01:51 -0700808static PyTypeObject AsyncGenHooksType;
809
810PyDoc_STRVAR(asyncgen_hooks_doc,
811"asyncgen_hooks\n\
812\n\
813A struct sequence providing information about asynhronous\n\
814generators hooks. The attributes are read only.");
815
816static PyStructSequence_Field asyncgen_hooks_fields[] = {
817 {"firstiter", "Hook to intercept first iteration"},
818 {"finalizer", "Hook to intercept finalization"},
819 {0}
820};
821
822static PyStructSequence_Desc asyncgen_hooks_desc = {
823 "asyncgen_hooks", /* name */
824 asyncgen_hooks_doc, /* doc */
825 asyncgen_hooks_fields , /* fields */
826 2
827};
828
829
830static PyObject *
831sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
832{
833 static char *keywords[] = {"firstiter", "finalizer", NULL};
834 PyObject *firstiter = NULL;
835 PyObject *finalizer = NULL;
836
837 if (!PyArg_ParseTupleAndKeywords(
838 args, kw, "|OO", keywords,
839 &firstiter, &finalizer)) {
840 return NULL;
841 }
842
843 if (finalizer && finalizer != Py_None) {
844 if (!PyCallable_Check(finalizer)) {
845 PyErr_Format(PyExc_TypeError,
846 "callable finalizer expected, got %.50s",
847 Py_TYPE(finalizer)->tp_name);
848 return NULL;
849 }
850 _PyEval_SetAsyncGenFinalizer(finalizer);
851 }
852 else if (finalizer == Py_None) {
853 _PyEval_SetAsyncGenFinalizer(NULL);
854 }
855
856 if (firstiter && firstiter != Py_None) {
857 if (!PyCallable_Check(firstiter)) {
858 PyErr_Format(PyExc_TypeError,
859 "callable firstiter expected, got %.50s",
860 Py_TYPE(firstiter)->tp_name);
861 return NULL;
862 }
863 _PyEval_SetAsyncGenFirstiter(firstiter);
864 }
865 else if (firstiter == Py_None) {
866 _PyEval_SetAsyncGenFirstiter(NULL);
867 }
868
869 Py_RETURN_NONE;
870}
871
872PyDoc_STRVAR(set_asyncgen_hooks_doc,
873"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
874\n\
875Set a finalizer for async generators objects."
876);
877
878static PyObject *
879sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
880{
881 PyObject *res;
882 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
883 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
884
885 res = PyStructSequence_New(&AsyncGenHooksType);
886 if (res == NULL) {
887 return NULL;
888 }
889
890 if (firstiter == NULL) {
891 firstiter = Py_None;
892 }
893
894 if (finalizer == NULL) {
895 finalizer = Py_None;
896 }
897
898 Py_INCREF(firstiter);
899 PyStructSequence_SET_ITEM(res, 0, firstiter);
900
901 Py_INCREF(finalizer);
902 PyStructSequence_SET_ITEM(res, 1, finalizer);
903
904 return res;
905}
906
907PyDoc_STRVAR(get_asyncgen_hooks_doc,
908"get_asyncgen_hooks()\n\
909\n\
910Return a namedtuple of installed asynchronous generators hooks \
911(firstiter, finalizer)."
912);
913
914
Mark Dickinsondc787d22010-05-23 13:33:13 +0000915static PyTypeObject Hash_InfoType;
916
917PyDoc_STRVAR(hash_info_doc,
918"hash_info\n\
919\n\
920A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100921hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000922
923static PyStructSequence_Field hash_info_fields[] = {
924 {"width", "width of the type used for hashing, in bits"},
925 {"modulus", "prime number giving the modulus on which the hash "
926 "function is based"},
927 {"inf", "value to be used for hash of a positive infinity"},
928 {"nan", "value to be used for hash of a nan"},
929 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100930 {"algorithm", "name of the algorithm for hashing of str, bytes and "
931 "memoryviews"},
932 {"hash_bits", "internal output size of hash algorithm"},
933 {"seed_bits", "seed size of hash algorithm"},
934 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000935 {NULL, NULL}
936};
937
938static PyStructSequence_Desc hash_info_desc = {
939 "sys.hash_info",
940 hash_info_doc,
941 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100942 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000943};
944
Matthias Klosed885e952010-07-06 10:53:30 +0000945static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000946get_hash_info(void)
947{
948 PyObject *hash_info;
949 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100950 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000951 hash_info = PyStructSequence_New(&Hash_InfoType);
952 if (hash_info == NULL)
953 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100954 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000955 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000956 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000957 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000958 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000959 PyStructSequence_SET_ITEM(hash_info, field++,
960 PyLong_FromLong(_PyHASH_INF));
961 PyStructSequence_SET_ITEM(hash_info, field++,
962 PyLong_FromLong(_PyHASH_NAN));
963 PyStructSequence_SET_ITEM(hash_info, field++,
964 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100965 PyStructSequence_SET_ITEM(hash_info, field++,
966 PyUnicode_FromString(hashfunc->name));
967 PyStructSequence_SET_ITEM(hash_info, field++,
968 PyLong_FromLong(hashfunc->hash_bits));
969 PyStructSequence_SET_ITEM(hash_info, field++,
970 PyLong_FromLong(hashfunc->seed_bits));
971 PyStructSequence_SET_ITEM(hash_info, field++,
972 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000973 if (PyErr_Occurred()) {
974 Py_CLEAR(hash_info);
975 return NULL;
976 }
977 return hash_info;
978}
979
980
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000981PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000982"setrecursionlimit(n)\n\
983\n\
984Set the maximum depth of the Python interpreter stack to n. This\n\
985limit prevents infinite recursion from causing an overflow of the C\n\
986stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000987dependent."
988);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000989
990static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000991sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000992{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000994}
995
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000996PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000997"getrecursionlimit()\n\
998\n\
999Return the current value of the recursion limit, the maximum depth\n\
1000of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001001recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001002);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001003
Mark Hammond8696ebc2002-10-08 02:44:31 +00001004#ifdef MS_WINDOWS
1005PyDoc_STRVAR(getwindowsversion_doc,
1006"getwindowsversion()\n\
1007\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001008Return information about the running version of Windows as a named tuple.\n\
1009The members are named: major, minor, build, platform, service_pack,\n\
1010service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001011backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001012All elements are numbers, except service_pack and platform_type which are\n\
1013strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1014Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1015server. Platform_version is a 3-tuple containing a version number that is\n\
1016intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001017);
1018
Eric Smithf7bb5782010-01-27 00:44:57 +00001019static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1020
1021static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 {"major", "Major version number"},
1023 {"minor", "Minor version number"},
1024 {"build", "Build number"},
1025 {"platform", "Operating system platform"},
1026 {"service_pack", "Latest Service Pack installed on the system"},
1027 {"service_pack_major", "Service Pack major version number"},
1028 {"service_pack_minor", "Service Pack minor version number"},
1029 {"suite_mask", "Bit mask identifying available product suites"},
1030 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001031 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001032 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001033};
1034
1035static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 "sys.getwindowsversion", /* name */
1037 getwindowsversion_doc, /* doc */
1038 windows_version_fields, /* fields */
1039 5 /* For backward compatibility,
1040 only the first 5 items are accessible
1041 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001042};
1043
Steve Dower3e96f322015-03-02 08:01:10 -08001044/* Disable deprecation warnings about GetVersionEx as the result is
1045 being passed straight through to the caller, who is responsible for
1046 using it correctly. */
1047#pragma warning(push)
1048#pragma warning(disable:4996)
1049
Mark Hammond8696ebc2002-10-08 02:44:31 +00001050static PyObject *
1051sys_getwindowsversion(PyObject *self)
1052{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 PyObject *version;
1054 int pos = 0;
1055 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001056 DWORD realMajor, realMinor, realBuild;
1057 HANDLE hKernel32;
1058 wchar_t kernel32_path[MAX_PATH];
1059 LPVOID verblock;
1060 DWORD verblock_size;
1061
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 ver.dwOSVersionInfoSize = sizeof(ver);
1063 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1064 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 version = PyStructSequence_New(&WindowsVersionType);
1067 if (version == NULL)
1068 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1071 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1072 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1073 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1074 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1075 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1076 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1077 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1078 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001079
Steve Dower74f4af72016-09-17 17:27:48 -07001080 realMajor = ver.dwMajorVersion;
1081 realMinor = ver.dwMinorVersion;
1082 realBuild = ver.dwBuildNumber;
1083
1084 // GetVersion will lie if we are running in a compatibility mode.
1085 // We need to read the version info from a system file resource
1086 // to accurately identify the OS version. If we fail for any reason,
1087 // just return whatever GetVersion said.
1088 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1089 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1090 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1091 (verblock = PyMem_RawMalloc(verblock_size))) {
1092 VS_FIXEDFILEINFO *ffi;
1093 UINT ffi_len;
1094
1095 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1096 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1097 realMajor = HIWORD(ffi->dwProductVersionMS);
1098 realMinor = LOWORD(ffi->dwProductVersionMS);
1099 realBuild = HIWORD(ffi->dwProductVersionLS);
1100 }
1101 PyMem_RawFree(verblock);
1102 }
Segev Finer48fb7662017-06-04 20:52:27 +03001103 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1104 realMajor,
1105 realMinor,
1106 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001107 ));
1108
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001109 if (PyErr_Occurred()) {
1110 Py_DECREF(version);
1111 return NULL;
1112 }
Steve Dower74f4af72016-09-17 17:27:48 -07001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001115}
1116
Steve Dower3e96f322015-03-02 08:01:10 -08001117#pragma warning(pop)
1118
Steve Dowercc16be82016-09-08 10:35:16 -07001119PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1120"_enablelegacywindowsfsencoding()\n\
1121\n\
1122Changes the default filesystem encoding to mbcs:replace for consistency\n\
1123with earlier versions of Python. See PEP 529 for more information.\n\
1124\n\
oldkaa0735f2018-02-02 16:52:55 +08001125This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001126environment variable before launching Python."
1127);
1128
1129static PyObject *
1130sys_enablelegacywindowsfsencoding(PyObject *self)
1131{
1132 Py_FileSystemDefaultEncoding = "mbcs";
1133 Py_FileSystemDefaultEncodeErrors = "replace";
1134 Py_RETURN_NONE;
1135}
1136
Mark Hammond8696ebc2002-10-08 02:44:31 +00001137#endif /* MS_WINDOWS */
1138
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001139#ifdef HAVE_DLOPEN
1140static PyObject *
1141sys_setdlopenflags(PyObject *self, PyObject *args)
1142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 int new_val;
1144 PyThreadState *tstate = PyThreadState_GET();
1145 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1146 return NULL;
1147 if (!tstate)
1148 return NULL;
1149 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001150 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001151}
1152
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001153PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001154"setdlopenflags(n) -> None\n\
1155\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001156Set the flags used by the interpreter for dlopen calls, such as when the\n\
1157interpreter loads extension modules. Among other things, this will enable\n\
1158a lazy resolving of symbols when importing a module, if called as\n\
1159sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001160sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001161can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001162
1163static PyObject *
1164sys_getdlopenflags(PyObject *self, PyObject *args)
1165{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 PyThreadState *tstate = PyThreadState_GET();
1167 if (!tstate)
1168 return NULL;
1169 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001170}
1171
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001172PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001173"getdlopenflags() -> int\n\
1174\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001175Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001176The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001179
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001180#ifdef USE_MALLOPT
1181/* Link with -lmalloc (or -lmpc) on an SGI */
1182#include <malloc.h>
1183
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001184static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001185sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001186{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 int flag;
1188 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1189 return NULL;
1190 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001191 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001192}
1193#endif /* USE_MALLOPT */
1194
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001195size_t
1196_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001197{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001199 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001200 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202 /* Make sure the type is initialized. float gets initialized late */
1203 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001204 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001205
Benjamin Petersonce798522012-01-22 11:24:29 -05001206 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001207 if (method == NULL) {
1208 if (!PyErr_Occurred())
1209 PyErr_Format(PyExc_TypeError,
1210 "Type %.100s doesn't define __sizeof__",
1211 Py_TYPE(o)->tp_name);
1212 }
1213 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001214 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 Py_DECREF(method);
1216 }
1217
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001218 if (res == NULL)
1219 return (size_t)-1;
1220
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001221 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001222 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001223 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001224 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001226 if (size < 0) {
1227 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1228 return (size_t)-1;
1229 }
1230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001232 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001233 return ((size_t)size) + sizeof(PyGC_Head);
1234 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001235}
1236
1237static PyObject *
1238sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1239{
1240 static char *kwlist[] = {"object", "default", 0};
1241 size_t size;
1242 PyObject *o, *dflt = NULL;
1243
1244 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1245 kwlist, &o, &dflt))
1246 return NULL;
1247
1248 size = _PySys_GetSizeOf(o);
1249
1250 if (size == (size_t)-1 && PyErr_Occurred()) {
1251 /* Has a default value been given */
1252 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1253 PyErr_Clear();
1254 Py_INCREF(dflt);
1255 return dflt;
1256 }
1257 else
1258 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001260
1261 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001262}
1263
1264PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001265"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001266\n\
1267Return the size of object in bytes.");
1268
1269static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001270sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001271{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001273}
1274
Tim Peters4be93d02002-07-07 19:59:50 +00001275#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001276static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001277sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001280}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001281#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001282
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001283PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001284"getrefcount(object) -> integer\n\
1285\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001286Return the reference count of object. The count returned is generally\n\
1287one higher than you might expect, because it includes the (temporary)\n\
1288reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001289);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001290
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001291static PyObject *
1292sys_getallocatedblocks(PyObject *self)
1293{
1294 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1295}
1296
1297PyDoc_STRVAR(getallocatedblocks_doc,
1298"getallocatedblocks() -> integer\n\
1299\n\
1300Return the number of memory blocks currently allocated, regardless of their\n\
1301size."
1302);
1303
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001304#ifdef COUNT_ALLOCS
1305static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001306sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001311}
1312#endif
1313
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001314PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001315"_getframe([depth]) -> frameobject\n\
1316\n\
1317Return a frame object from the call stack. If optional integer depth is\n\
1318given, return the frame object that many calls below the top of the stack.\n\
1319If that is deeper than the call stack, ValueError is raised. The default\n\
1320for depth is zero, returning the frame at the top of the call stack.\n\
1321\n\
1322This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001323purposes only."
1324);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001325
1326static PyObject *
1327sys_getframe(PyObject *self, PyObject *args)
1328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 PyFrameObject *f = PyThreadState_GET()->frame;
1330 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1333 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 while (depth > 0 && f != NULL) {
1336 f = f->f_back;
1337 --depth;
1338 }
1339 if (f == NULL) {
1340 PyErr_SetString(PyExc_ValueError,
1341 "call stack is not deep enough");
1342 return NULL;
1343 }
1344 Py_INCREF(f);
1345 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001346}
1347
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001348PyDoc_STRVAR(current_frames_doc,
1349"_current_frames() -> dictionary\n\
1350\n\
1351Return a dictionary mapping each current thread T's thread id to T's\n\
1352current stack frame.\n\
1353\n\
1354This function should be used for specialized purposes only."
1355);
1356
1357static PyObject *
1358sys_current_frames(PyObject *self, PyObject *noargs)
1359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001361}
1362
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001363PyDoc_STRVAR(call_tracing_doc,
1364"call_tracing(func, args) -> object\n\
1365\n\
1366Call func(*args), while tracing is enabled. The tracing state is\n\
1367saved, and restored afterwards. This is intended to be called from\n\
1368a debugger from a checkpoint, to recursively debug some other code."
1369);
1370
1371static PyObject *
1372sys_call_tracing(PyObject *self, PyObject *args)
1373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 PyObject *func, *funcargs;
1375 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1376 return NULL;
1377 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001378}
1379
Jeremy Hylton985eba52003-02-05 23:13:00 +00001380PyDoc_STRVAR(callstats_doc,
1381"callstats() -> tuple of integers\n\
1382\n\
1383Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1384when Python was built. Otherwise, return None.\n\
1385\n\
1386When enabled, this function returns detailed, implementation-specific\n\
1387details about the number of function calls executed. The return value is\n\
1388a 11-tuple where the entries in the tuple are counts of:\n\
13890. all function calls\n\
13901. calls to PyFunction_Type objects\n\
13912. PyFunction calls that do not create an argument tuple\n\
13923. PyFunction calls that do not create an argument tuple\n\
1393 and bypass PyEval_EvalCodeEx()\n\
13944. PyMethod calls\n\
13955. PyMethod calls on bound methods\n\
13966. PyType calls\n\
13977. PyCFunction calls\n\
13988. generator calls\n\
13999. All other calls\n\
140010. Number of stack pops performed by call_function()"
1401);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001402
Victor Stinner048afd92016-11-28 11:59:04 +01001403static PyObject *
1404sys_callstats(PyObject *self)
1405{
1406 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1407 "sys.callstats() has been deprecated in Python 3.7 "
1408 "and will be removed in the future", 1) < 0) {
1409 return NULL;
1410 }
1411
1412 Py_RETURN_NONE;
1413}
1414
1415
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001416#ifdef __cplusplus
1417extern "C" {
1418#endif
1419
David Malcolm49526f42012-06-22 14:55:41 -04001420static PyObject *
1421sys_debugmallocstats(PyObject *self, PyObject *args)
1422{
1423#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001424 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001425 fputc('\n', stderr);
1426 }
David Malcolm49526f42012-06-22 14:55:41 -04001427#endif
1428 _PyObject_DebugTypeStats(stderr);
1429
1430 Py_RETURN_NONE;
1431}
1432PyDoc_STRVAR(debugmallocstats_doc,
1433"_debugmallocstats()\n\
1434\n\
1435Print summary info to stderr about the state of\n\
1436pymalloc's structures.\n\
1437\n\
1438In Py_DEBUG mode, also perform some expensive internal consistency\n\
1439checks.\n\
1440");
1441
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001442#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001443/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001444extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001445#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001446
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001447#ifdef DYNAMIC_EXECUTION_PROFILE
1448/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001449extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001450#endif
1451
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001452#ifdef __cplusplus
1453}
1454#endif
1455
Christian Heimes15ebc882008-02-04 18:48:49 +00001456static PyObject *
1457sys_clear_type_cache(PyObject* self, PyObject* args)
1458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyType_ClearCache();
1460 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001461}
1462
1463PyDoc_STRVAR(sys_clear_type_cache__doc__,
1464"_clear_type_cache() -> None\n\
1465Clear the internal type lookup cache.");
1466
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001467static PyObject *
1468sys_is_finalizing(PyObject* self, PyObject* args)
1469{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001470 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001471}
1472
1473PyDoc_STRVAR(is_finalizing_doc,
1474"is_finalizing()\n\
1475Return True if Python is exiting.");
1476
Christian Heimes15ebc882008-02-04 18:48:49 +00001477
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001478#ifdef ANDROID_API_LEVEL
1479PyDoc_STRVAR(getandroidapilevel_doc,
1480"getandroidapilevel()\n\
1481\n\
1482Return the build time API version of Android as an integer.");
1483
1484static PyObject *
1485sys_getandroidapilevel(PyObject *self)
1486{
1487 return PyLong_FromLong(ANDROID_API_LEVEL);
1488}
1489#endif /* ANDROID_API_LEVEL */
1490
1491
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001492static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001494 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1495 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Victor Stinner048afd92016-11-28 11:59:04 +01001496 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 callstats_doc},
1498 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1499 sys_clear_type_cache__doc__},
1500 {"_current_frames", sys_current_frames, METH_NOARGS,
1501 current_frames_doc},
1502 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1503 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1504 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1505 {"exit", sys_exit, METH_VARARGS, exit_doc},
1506 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1507 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001508#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001509 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1510 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001511#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001512 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1513 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001514#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001516#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001517#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001519#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1521 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001522 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1523 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001524#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001526#endif
1527#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001529#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001530 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1531 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1532 getrecursionlimit_doc},
1533 {"getsizeof", (PyCFunction)sys_getsizeof,
1534 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1535 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001536#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1538 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001539 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1540 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001541#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001543 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001544#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001546#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1548 setcheckinterval_doc},
1549 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1550 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1552 setswitchinterval_doc},
1553 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1554 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001555#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1557 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001558#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1560 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1561 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1562 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 {"settrace", sys_settrace, METH_O, settrace_doc},
1564 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1565 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001566 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001567 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001568 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1569 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001570 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1571 set_coroutine_wrapper_doc},
1572 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1573 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001574 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001575 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1576 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1577 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001578#ifdef ANDROID_API_LEVEL
1579 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1580 getandroidapilevel_doc},
1581#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001583};
1584
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001585static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001586list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyObject *list = PyList_New(0);
1589 int i;
1590 if (list == NULL)
1591 return NULL;
1592 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1593 PyObject *name = PyUnicode_FromString(
1594 PyImport_Inittab[i].name);
1595 if (name == NULL)
1596 break;
1597 PyList_Append(list, name);
1598 Py_DECREF(name);
1599 }
1600 if (PyList_Sort(list) != 0) {
1601 Py_DECREF(list);
1602 list = NULL;
1603 }
1604 if (list) {
1605 PyObject *v = PyList_AsTuple(list);
1606 Py_DECREF(list);
1607 list = v;
1608 }
1609 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001610}
1611
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001612static PyObject *
1613get_warnoptions(void)
1614{
Eric Snowdae02762017-09-14 00:35:58 -07001615 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001616 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1617 Py_XDECREF(warnoptions);
1618 warnoptions = PyList_New(0);
1619 if (warnoptions == NULL)
1620 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001621 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1622 Py_DECREF(warnoptions);
1623 return NULL;
1624 }
1625 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001626 }
1627 return warnoptions;
1628}
Guido van Rossum23fff912000-12-15 22:02:05 +00001629
1630void
1631PySys_ResetWarnOptions(void)
1632{
Eric Snowdae02762017-09-14 00:35:58 -07001633 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (warnoptions == NULL || !PyList_Check(warnoptions))
1635 return;
1636 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001637}
1638
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001639int
1640_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001641{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001642 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001643 if (warnoptions == NULL) {
1644 return -1;
1645 }
1646 if (PyList_Append(warnoptions, option)) {
1647 return -1;
1648 }
1649 return 0;
1650}
1651
1652void
1653PySys_AddWarnOptionUnicode(PyObject *option)
1654{
1655 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001656}
1657
1658void
1659PySys_AddWarnOption(const wchar_t *s)
1660{
1661 PyObject *unicode;
1662 unicode = PyUnicode_FromWideChar(s, -1);
1663 if (unicode == NULL)
1664 return;
1665 PySys_AddWarnOptionUnicode(unicode);
1666 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001667}
1668
Christian Heimes33fe8092008-04-13 13:53:33 +00001669int
1670PySys_HasWarnOptions(void)
1671{
Eric Snowdae02762017-09-14 00:35:58 -07001672 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001673 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1674}
1675
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001676static PyObject *
1677get_xoptions(void)
1678{
Eric Snowdae02762017-09-14 00:35:58 -07001679 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001680 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1681 Py_XDECREF(xoptions);
1682 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001683 if (xoptions == NULL)
1684 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001685 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1686 Py_DECREF(xoptions);
1687 return NULL;
1688 }
1689 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001690 }
1691 return xoptions;
1692}
1693
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001694int
1695_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001696{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001697 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001698
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001699 PyObject *opts = get_xoptions();
1700 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001701 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001702 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001703
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001704 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001705 if (!name_end) {
1706 name = PyUnicode_FromWideChar(s, -1);
1707 value = Py_True;
1708 Py_INCREF(value);
1709 }
1710 else {
1711 name = PyUnicode_FromWideChar(s, name_end - s);
1712 value = PyUnicode_FromWideChar(name_end + 1, -1);
1713 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001714 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001715 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001716 }
1717 if (PyDict_SetItem(opts, name, value) < 0) {
1718 goto error;
1719 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001720 Py_DECREF(name);
1721 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001722 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001723
1724error:
1725 Py_XDECREF(name);
1726 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001727 return -1;
1728}
1729
1730void
1731PySys_AddXOption(const wchar_t *s)
1732{
1733 if (_PySys_AddXOptionWithError(s) < 0) {
1734 /* No return value, therefore clear error state if possible */
1735 if (_PyThreadState_UncheckedGet()) {
1736 PyErr_Clear();
1737 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001738 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001739}
1740
1741PyObject *
1742PySys_GetXOptions(void)
1743{
1744 return get_xoptions();
1745}
1746
Guido van Rossum40552d01998-08-06 03:34:39 +00001747/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1748 Two literals concatenated works just fine. If you have a K&R compiler
1749 or other abomination that however *does* understand longer strings,
1750 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001751PyDoc_VAR(sys_doc) =
1752PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001753"This module provides access to some objects used or maintained by the\n\
1754interpreter and to functions that interact strongly with the interpreter.\n\
1755\n\
1756Dynamic objects:\n\
1757\n\
1758argv -- command line arguments; argv[0] is the script pathname if known\n\
1759path -- module search path; path[0] is the script directory, else ''\n\
1760modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001761\n\
1762displayhook -- called to show results in an interactive session\n\
1763excepthook -- called to handle any uncaught exception other than SystemExit\n\
1764 To customize printing in an interactive session or to install a custom\n\
1765 top-level exception handler, assign other functions to replace these.\n\
1766\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001767stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001768stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001769stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001770 By assigning other file objects (or objects that behave like files)\n\
1771 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001772\n\
1773last_type -- type of last uncaught exception\n\
1774last_value -- value of last uncaught exception\n\
1775last_traceback -- traceback of last uncaught exception\n\
1776 These three are only available in an interactive session after a\n\
1777 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001778"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001779)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001780/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001781PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001782"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001783Static objects:\n\
1784\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001785builtin_module_names -- tuple of module names built into this interpreter\n\
1786copyright -- copyright notice pertaining to this interpreter\n\
1787exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001788executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001789float_info -- a struct sequence with information about the float implementation.\n\
1790float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001791hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001792hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001793implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001794int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001795maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001796maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001797platform -- platform identifier\n\
1798prefix -- prefix used to find the Python library\n\
1799thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001800version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001801version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001802"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001803)
Steve Dowercc16be82016-09-08 10:35:16 -07001804#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001805/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001806PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001807"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001808winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001809"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001810)
Steve Dowercc16be82016-09-08 10:35:16 -07001811#endif /* MS_COREDLL */
1812#ifdef MS_WINDOWS
1813/* concatenating string here */
1814PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08001815"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001816"
1817)
1818#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001819PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001820"__stdin__ -- the original stdin; don't touch!\n\
1821__stdout__ -- the original stdout; don't touch!\n\
1822__stderr__ -- the original stderr; don't touch!\n\
1823__displayhook__ -- the original displayhook; don't touch!\n\
1824__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001825\n\
1826Functions:\n\
1827\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001828displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001829excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001830exc_info() -- return thread-safe information about the current exception\n\
1831exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001832getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001833getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001834getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001835getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001836getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001837gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001838setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001839setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001840setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001841setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001842settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001843"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001844)
Fred Drakeccede592000-08-14 20:59:57 +00001845/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001846
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001847
1848PyDoc_STRVAR(flags__doc__,
1849"sys.flags\n\
1850\n\
1851Flags provided through command line arguments or environment vars.");
1852
1853static PyTypeObject FlagsType;
1854
1855static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 {"inspect", "-i"},
1858 {"interactive", "-i"},
1859 {"optimize", "-O or -OO"},
1860 {"dont_write_bytecode", "-B"},
1861 {"no_user_site", "-s"},
1862 {"no_site", "-S"},
1863 {"ignore_environment", "-E"},
1864 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001865 /* {"unbuffered", "-u"}, */
1866 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001867 {"bytes_warning", "-b"},
1868 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001869 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001870 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01001871 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01001872 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001874};
1875
1876static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001877 "sys.flags", /* name */
1878 flags__doc__, /* doc */
1879 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01001880 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001881};
1882
1883static PyObject*
1884make_flags(void)
1885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 int pos = 0;
1887 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01001888 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 seq = PyStructSequence_New(&FlagsType);
1891 if (seq == NULL)
1892 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001893
1894#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001897 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001898 SetFlag(Py_InspectFlag);
1899 SetFlag(Py_InteractiveFlag);
1900 SetFlag(Py_OptimizeFlag);
1901 SetFlag(Py_DontWriteBytecodeFlag);
1902 SetFlag(Py_NoUserSiteDirectory);
1903 SetFlag(Py_NoSiteFlag);
1904 SetFlag(Py_IgnoreEnvironmentFlag);
1905 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001906 /* SetFlag(saw_unbuffered_flag); */
1907 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001908 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001909 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001910 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001911 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01001912 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01001913 SetFlag(Py_UTF8Mode);
1914#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001916 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001917 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 return NULL;
1919 }
1920 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001921}
1922
Eric Smith0e5b5622009-02-06 01:32:42 +00001923PyDoc_STRVAR(version_info__doc__,
1924"sys.version_info\n\
1925\n\
1926Version information as a named tuple.");
1927
1928static PyTypeObject VersionInfoType;
1929
1930static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 {"major", "Major release number"},
1932 {"minor", "Minor release number"},
1933 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04001934 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 {"serial", "Serial release number"},
1936 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001937};
1938
1939static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 "sys.version_info", /* name */
1941 version_info__doc__, /* doc */
1942 version_info_fields, /* fields */
1943 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001944};
1945
1946static PyObject *
1947make_version_info(void)
1948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001949 PyObject *version_info;
1950 char *s;
1951 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 version_info = PyStructSequence_New(&VersionInfoType);
1954 if (version_info == NULL) {
1955 return NULL;
1956 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 /*
1959 * These release level checks are mutually exclusive and cover
1960 * the field, so don't get too fancy with the pre-processor!
1961 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001962#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001964#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001965 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001966#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001968#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001970#endif
1971
1972#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001974#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001975 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001976
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001977 SetIntItem(PY_MAJOR_VERSION);
1978 SetIntItem(PY_MINOR_VERSION);
1979 SetIntItem(PY_MICRO_VERSION);
1980 SetStrItem(s);
1981 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001982#undef SetIntItem
1983#undef SetStrItem
1984
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001985 if (PyErr_Occurred()) {
1986 Py_CLEAR(version_info);
1987 return NULL;
1988 }
1989 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001990}
1991
Brett Cannon3adc7b72012-07-09 14:22:12 -04001992/* sys.implementation values */
1993#define NAME "cpython"
1994const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001995#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1996#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001997#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001998const char *_PySys_ImplCacheTag = TAG;
1999#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002000#undef MAJOR
2001#undef MINOR
2002#undef TAG
2003
Barry Warsaw409da152012-06-03 16:18:47 -04002004static PyObject *
2005make_impl_info(PyObject *version_info)
2006{
2007 int res;
2008 PyObject *impl_info, *value, *ns;
2009
2010 impl_info = PyDict_New();
2011 if (impl_info == NULL)
2012 return NULL;
2013
2014 /* populate the dict */
2015
Brett Cannon3adc7b72012-07-09 14:22:12 -04002016 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002017 if (value == NULL)
2018 goto error;
2019 res = PyDict_SetItemString(impl_info, "name", value);
2020 Py_DECREF(value);
2021 if (res < 0)
2022 goto error;
2023
Brett Cannon3adc7b72012-07-09 14:22:12 -04002024 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002025 if (value == NULL)
2026 goto error;
2027 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2028 Py_DECREF(value);
2029 if (res < 0)
2030 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002031
2032 res = PyDict_SetItemString(impl_info, "version", version_info);
2033 if (res < 0)
2034 goto error;
2035
2036 value = PyLong_FromLong(PY_VERSION_HEX);
2037 if (value == NULL)
2038 goto error;
2039 res = PyDict_SetItemString(impl_info, "hexversion", value);
2040 Py_DECREF(value);
2041 if (res < 0)
2042 goto error;
2043
doko@ubuntu.com55532312016-06-14 08:55:19 +02002044#ifdef MULTIARCH
2045 value = PyUnicode_FromString(MULTIARCH);
2046 if (value == NULL)
2047 goto error;
2048 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2049 Py_DECREF(value);
2050 if (res < 0)
2051 goto error;
2052#endif
2053
Barry Warsaw409da152012-06-03 16:18:47 -04002054 /* dict ready */
2055
2056 ns = _PyNamespace_New(impl_info);
2057 Py_DECREF(impl_info);
2058 return ns;
2059
2060error:
2061 Py_CLEAR(impl_info);
2062 return NULL;
2063}
2064
Martin v. Löwis1a214512008-06-11 05:26:20 +00002065static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 PyModuleDef_HEAD_INIT,
2067 "sys",
2068 sys_doc,
2069 -1, /* multiple "initialization" just copies the module dict. */
2070 sys_methods,
2071 NULL,
2072 NULL,
2073 NULL,
2074 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002075};
2076
Eric Snow6b4be192017-05-22 21:36:03 -07002077/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002078#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002079 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002080 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002081 if (v == NULL) { \
2082 goto err_occurred; \
2083 } \
Victor Stinner58049602013-07-22 22:40:00 +02002084 res = PyDict_SetItemString(sysdict, key, v); \
2085 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002086 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002087 } \
2088 } while (0)
2089#define SET_SYS_FROM_STRING(key, value) \
2090 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002091 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002092 if (v == NULL) { \
2093 goto err_occurred; \
2094 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002095 res = PyDict_SetItemString(sysdict, key, v); \
2096 Py_DECREF(v); \
2097 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002098 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002099 } \
2100 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002101
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002102
2103_PyInitError
2104_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002105{
2106 PyObject *m, *sysdict, *version_info;
2107 int res;
2108
Eric Snowd393c1b2017-09-14 12:18:12 -06002109 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002110 if (m == NULL) {
2111 return _Py_INIT_ERR("failed to create a module object");
2112 }
Eric Snow6b4be192017-05-22 21:36:03 -07002113 sysdict = PyModule_GetDict(m);
2114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002116 Using shell redirection, you can redirect stdin to a directory,
2117 crashing the Python interpreter. Catch this common mistake here
2118 and output a useful error message. Note that under MS Windows,
2119 the shell already prevents that. */
2120#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002122 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002123 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002125 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2126 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 }
2128 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002129#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002130
Nick Coghland6009512014-11-20 21:39:37 +10002131 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002132
Victor Stinner8fea2522013-10-27 17:15:42 +01002133 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2134 PyDict_GetItemString(sysdict, "displayhook"));
2135 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2136 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002137 SET_SYS_FROM_STRING_BORROW(
2138 "__breakpointhook__",
2139 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 SET_SYS_FROM_STRING("version",
2141 PyUnicode_FromString(Py_GetVersion()));
2142 SET_SYS_FROM_STRING("hexversion",
2143 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002144 SET_SYS_FROM_STRING("_git",
2145 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2146 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002147 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 SET_SYS_FROM_STRING("api_version",
2149 PyLong_FromLong(PYTHON_API_VERSION));
2150 SET_SYS_FROM_STRING("copyright",
2151 PyUnicode_FromString(Py_GetCopyright()));
2152 SET_SYS_FROM_STRING("platform",
2153 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 SET_SYS_FROM_STRING("maxsize",
2155 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2156 SET_SYS_FROM_STRING("float_info",
2157 PyFloat_GetInfo());
2158 SET_SYS_FROM_STRING("int_info",
2159 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002160 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002161 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002162 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2163 goto type_init_failed;
2164 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002165 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002166 SET_SYS_FROM_STRING("hash_info",
2167 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002169 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 SET_SYS_FROM_STRING("builtin_module_names",
2171 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002172#if PY_BIG_ENDIAN
2173 SET_SYS_FROM_STRING("byteorder",
2174 PyUnicode_FromString("big"));
2175#else
2176 SET_SYS_FROM_STRING("byteorder",
2177 PyUnicode_FromString("little"));
2178#endif
Fred Drake099325e2000-08-14 15:47:03 +00002179
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002180#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 SET_SYS_FROM_STRING("dllhandle",
2182 PyLong_FromVoidPtr(PyWin_DLLhModule));
2183 SET_SYS_FROM_STRING("winver",
2184 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002185#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002186#ifdef ABIFLAGS
2187 SET_SYS_FROM_STRING("abiflags",
2188 PyUnicode_FromString(ABIFLAGS));
2189#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002192 if (VersionInfoType.tp_name == NULL) {
2193 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002194 &version_info_desc) < 0) {
2195 goto type_init_failed;
2196 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002197 }
Barry Warsaw409da152012-06-03 16:18:47 -04002198 version_info = make_version_info();
2199 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 /* prevent user from creating new instances */
2201 VersionInfoType.tp_init = NULL;
2202 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002203 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2204 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2205 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002206
Barry Warsaw409da152012-06-03 16:18:47 -04002207 /* implementation */
2208 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2209
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002211 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002212 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2213 goto type_init_failed;
2214 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002215 }
Eric Snow6b4be192017-05-22 21:36:03 -07002216 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002218
2219#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 /* getwindowsversion */
2221 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002222 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002223 &windows_version_desc) < 0) {
2224 goto type_init_failed;
2225 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002226 /* prevent user from creating new instances */
2227 WindowsVersionType.tp_init = NULL;
2228 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002229 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002230 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002231 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002232 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002233 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002234#endif
2235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002237#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 SET_SYS_FROM_STRING("float_repr_style",
2239 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002240#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 SET_SYS_FROM_STRING("float_repr_style",
2242 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002243#endif
2244
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002245 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002246
Yury Selivanoveb636452016-09-08 22:01:51 -07002247 /* initialize asyncgen_hooks */
2248 if (AsyncGenHooksType.tp_name == NULL) {
2249 if (PyStructSequence_InitType2(
2250 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002251 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002252 }
2253 }
2254
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002255 if (PyErr_Occurred()) {
2256 goto err_occurred;
2257 }
2258
2259 *sysmod = m;
2260 return _Py_INIT_OK();
2261
2262type_init_failed:
2263 return _Py_INIT_ERR("failed to initialize a type");
2264
2265err_occurred:
2266 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002267}
2268
Eric Snow6b4be192017-05-22 21:36:03 -07002269#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002270
2271/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002272#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2273 do { \
2274 PyObject *v = (value); \
2275 if (v == NULL) \
2276 return -1; \
2277 res = PyDict_SetItemString(sysdict, key, v); \
2278 Py_DECREF(v); \
2279 if (res < 0) { \
2280 return res; \
2281 } \
2282 } while (0)
2283
2284int
Victor Stinner41264f12017-12-15 02:05:29 +01002285_PySys_EndInit(PyObject *sysdict, _PyMainInterpreterConfig *config)
Eric Snow6b4be192017-05-22 21:36:03 -07002286{
2287 int res;
2288
Victor Stinner41264f12017-12-15 02:05:29 +01002289 /* _PyMainInterpreterConfig_Read() must set all these variables */
2290 assert(config->module_search_path != NULL);
2291 assert(config->executable != NULL);
2292 assert(config->prefix != NULL);
2293 assert(config->base_prefix != NULL);
2294 assert(config->exec_prefix != NULL);
2295 assert(config->base_exec_prefix != NULL);
2296
2297 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
2298 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2299 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2300 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2301 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2302 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2303
2304 if (config->argv != NULL) {
2305 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2306 }
2307 if (config->warnoptions != NULL) {
2308 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
2309 }
2310 if (config->xoptions != NULL) {
2311 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
2312 }
2313
Eric Snow6b4be192017-05-22 21:36:03 -07002314 /* Set flags to their final values */
2315 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2316 /* prevent user from creating new instances */
2317 FlagsType.tp_init = NULL;
2318 FlagsType.tp_new = NULL;
2319 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2320 if (res < 0) {
2321 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2322 return res;
2323 }
2324 PyErr_Clear();
2325 }
2326
2327 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2328 PyBool_FromLong(Py_DontWriteBytecodeFlag));
Eric Snow6b4be192017-05-22 21:36:03 -07002329
Eric Snowdae02762017-09-14 00:35:58 -07002330 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002331 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002332
Eric Snowdae02762017-09-14 00:35:58 -07002333 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002334 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002335
2336 if (PyErr_Occurred())
2337 return -1;
2338 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002339
2340err_occurred:
2341 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002342}
2343
Victor Stinner41264f12017-12-15 02:05:29 +01002344#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002345#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002346
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002347static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002348makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002349{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 int i, n;
2351 const wchar_t *p;
2352 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 n = 1;
2355 p = path;
2356 while ((p = wcschr(p, delim)) != NULL) {
2357 n++;
2358 p++;
2359 }
2360 v = PyList_New(n);
2361 if (v == NULL)
2362 return NULL;
2363 for (i = 0; ; i++) {
2364 p = wcschr(path, delim);
2365 if (p == NULL)
2366 p = path + wcslen(path); /* End of string */
2367 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2368 if (w == NULL) {
2369 Py_DECREF(v);
2370 return NULL;
2371 }
2372 PyList_SetItem(v, i, w);
2373 if (*p == '\0')
2374 break;
2375 path = p+1;
2376 }
2377 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002378}
2379
2380void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002381PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 PyObject *v;
2384 if ((v = makepathobject(path, DELIM)) == NULL)
2385 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002386 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 Py_FatalError("can't assign sys.path");
2388 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002389}
2390
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002391static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002392makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 PyObject *av;
2395 if (argc <= 0 || argv == NULL) {
2396 /* Ensure at least one (empty) argument is seen */
2397 static wchar_t *empty_argv[1] = {L""};
2398 argv = empty_argv;
2399 argc = 1;
2400 }
2401 av = PyList_New(argc);
2402 if (av != NULL) {
2403 int i;
2404 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 if (v == NULL) {
2407 Py_DECREF(av);
2408 av = NULL;
2409 break;
2410 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002411 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 }
2413 }
2414 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002415}
2416
Victor Stinner11a247d2017-12-13 21:05:57 +01002417void
2418PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002419{
2420 PyObject *av = makeargvobject(argc, argv);
2421 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002422 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002423 }
2424 if (PySys_SetObject("argv", av) != 0) {
2425 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002426 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002427 }
2428 Py_DECREF(av);
2429
2430 if (updatepath) {
2431 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2432 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002433 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2434 if (argv0 == NULL) {
2435 Py_FatalError("can't compute path0 from argv");
2436 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002437
Victor Stinner11a247d2017-12-13 21:05:57 +01002438 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2439 if (sys_path != NULL) {
2440 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2441 Py_DECREF(argv0);
2442 Py_FatalError("can't prepend path0 to sys.path");
2443 }
2444 }
2445 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002446 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002447}
Guido van Rossuma890e681998-05-12 14:59:24 +00002448
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002449void
2450PySys_SetArgv(int argc, wchar_t **argv)
2451{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002452 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002453}
2454
Victor Stinner14284c22010-04-23 12:02:30 +00002455/* Reimplementation of PyFile_WriteString() no calling indirectly
2456 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2457
2458static int
Victor Stinner79766632010-08-16 17:36:42 +00002459sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002460{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002461 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002463
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002464 if (file == NULL)
2465 return -1;
2466
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002467 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (writer == NULL)
2469 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002470
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002471 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 if (result == NULL) {
2473 goto error;
2474 } else {
2475 err = 0;
2476 goto finally;
2477 }
Victor Stinner14284c22010-04-23 12:02:30 +00002478
2479error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002481finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002483 Py_XDECREF(result);
2484 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002485}
2486
Victor Stinner79766632010-08-16 17:36:42 +00002487static int
2488sys_pyfile_write(const char *text, PyObject *file)
2489{
2490 PyObject *unicode = NULL;
2491 int err;
2492
2493 if (file == NULL)
2494 return -1;
2495
2496 unicode = PyUnicode_FromString(text);
2497 if (unicode == NULL)
2498 return -1;
2499
2500 err = sys_pyfile_write_unicode(unicode, file);
2501 Py_DECREF(unicode);
2502 return err;
2503}
Guido van Rossuma890e681998-05-12 14:59:24 +00002504
2505/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2506 Adapted from code submitted by Just van Rossum.
2507
2508 PySys_WriteStdout(format, ...)
2509 PySys_WriteStderr(format, ...)
2510
2511 The first function writes to sys.stdout; the second to sys.stderr. When
2512 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002513 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002514
Victor Stinner14284c22010-04-23 12:02:30 +00002515 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002516 signal handlers: they may raise a new exception whereas sys_write()
2517 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002518
Guido van Rossuma890e681998-05-12 14:59:24 +00002519 Both take a printf-style format string as their first argument followed
2520 by a variable length argument list determined by the format string.
2521
2522 *** WARNING ***
2523
2524 The format should limit the total size of the formatted output string to
2525 1000 bytes. In particular, this means that no unrestricted "%s" formats
2526 should occur; these should be limited using "%.<N>s where <N> is a
2527 decimal number calculated so that <N> plus the maximum size of other
2528 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2529 which can print hundreds of digits for very large numbers.
2530
2531 */
2532
2533static void
Victor Stinner09054372013-11-06 22:41:44 +01002534sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002536 PyObject *file;
2537 PyObject *error_type, *error_value, *error_traceback;
2538 char buffer[1001];
2539 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002542 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2544 if (sys_pyfile_write(buffer, file) != 0) {
2545 PyErr_Clear();
2546 fputs(buffer, fp);
2547 }
2548 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2549 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002550 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002552 }
2553 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002554}
2555
2556void
Guido van Rossuma890e681998-05-12 14:59:24 +00002557PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002562 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002564}
2565
2566void
Guido van Rossuma890e681998-05-12 14:59:24 +00002567PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002569 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002571 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002572 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002573 va_end(va);
2574}
2575
2576static void
Victor Stinner09054372013-11-06 22:41:44 +01002577sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002578{
2579 PyObject *file, *message;
2580 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002581 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002582
2583 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002584 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002585 message = PyUnicode_FromFormatV(format, va);
2586 if (message != NULL) {
2587 if (sys_pyfile_write_unicode(message, file) != 0) {
2588 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002589 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002590 if (utf8 != NULL)
2591 fputs(utf8, fp);
2592 }
2593 Py_DECREF(message);
2594 }
2595 PyErr_Restore(error_type, error_value, error_traceback);
2596}
2597
2598void
2599PySys_FormatStdout(const char *format, ...)
2600{
2601 va_list va;
2602
2603 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002604 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002605 va_end(va);
2606}
2607
2608void
2609PySys_FormatStderr(const char *format, ...)
2610{
2611 va_list va;
2612
2613 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002614 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002616}