blob: efe5b29ef33c8103cfdae0bca9a9c6ffdeb99c1a [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());
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700110 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 }
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700119 /* According to POSIX the string returned by getenv() might be invalidated
120 * or the string content might be overwritten by a subsequent call to
121 * getenv(). Since importing a module can performs the getenv() calls,
122 * we need to save a copy of envar. */
123 envar = _PyMem_RawStrdup(envar);
124 if (envar == NULL) {
125 PyErr_NoMemory();
126 return NULL;
127 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200128 const char *last_dot = strrchr(envar, '.');
129 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400130 PyObject *modulepath = NULL;
131
132 if (last_dot == NULL) {
133 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
134 modulepath = PyUnicode_FromString("builtins");
135 attrname = envar;
136 }
137 else {
138 /* Split on the last dot; */
139 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
140 attrname = last_dot + 1;
141 }
142 if (modulepath == NULL) {
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700143 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400144 return NULL;
145 }
146
147 PyObject *fromlist = Py_BuildValue("(s)", attrname);
148 if (fromlist == NULL) {
149 Py_DECREF(modulepath);
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700150 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400151 return NULL;
152 }
153 PyObject *module = PyImport_ImportModuleLevelObject(
154 modulepath, NULL, NULL, fromlist, 0);
155 Py_DECREF(modulepath);
156 Py_DECREF(fromlist);
157
158 if (module == NULL) {
159 goto error;
160 }
161
162 PyObject *hook = PyObject_GetAttrString(module, attrname);
163 Py_DECREF(module);
164
165 if (hook == NULL) {
166 goto error;
167 }
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700168 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400169 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
170 Py_DECREF(hook);
171 return retval;
172
173 error:
174 /* If any of the imports went wrong, then warn and ignore. */
175 PyErr_Clear();
176 int status = PyErr_WarnFormat(
177 PyExc_RuntimeWarning, 0,
178 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700179 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400180 if (status < 0) {
181 /* Printing the warning raised an exception. */
182 return NULL;
183 }
184 /* The warning was (probably) issued. */
185 Py_RETURN_NONE;
186}
187
188PyDoc_STRVAR(breakpointhook_doc,
189"breakpointhook(*args, **kws)\n"
190"\n"
191"This hook function is called by built-in breakpoint().\n"
192);
193
Victor Stinner13d49ee2010-12-04 17:24:33 +0000194/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
195 error handler. If sys.stdout has a buffer attribute, use
196 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
197 sys.stdout.write(redecoded).
198
199 Helper function for sys_displayhook(). */
200static int
201sys_displayhook_unencodable(PyObject *outf, PyObject *o)
202{
203 PyObject *stdout_encoding = NULL;
204 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200205 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000206 int ret;
207
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200208 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000209 if (stdout_encoding == NULL)
210 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200211 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000212 if (stdout_encoding_str == NULL)
213 goto error;
214
215 repr_str = PyObject_Repr(o);
216 if (repr_str == NULL)
217 goto error;
218 encoded = PyUnicode_AsEncodedString(repr_str,
219 stdout_encoding_str,
220 "backslashreplace");
221 Py_DECREF(repr_str);
222 if (encoded == NULL)
223 goto error;
224
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200225 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000226 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100227 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000228 Py_DECREF(buffer);
229 Py_DECREF(encoded);
230 if (result == NULL)
231 goto error;
232 Py_DECREF(result);
233 }
234 else {
235 PyErr_Clear();
236 escaped_str = PyUnicode_FromEncodedObject(encoded,
237 stdout_encoding_str,
238 "strict");
239 Py_DECREF(encoded);
240 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
241 Py_DECREF(escaped_str);
242 goto error;
243 }
244 Py_DECREF(escaped_str);
245 }
246 ret = 0;
247 goto finally;
248
249error:
250 ret = -1;
251finally:
252 Py_XDECREF(stdout_encoding);
253 return ret;
254}
255
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000256static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000257sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000258{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100260 PyObject *builtins;
261 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000262 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000263
Eric Snow3f9eee62017-09-15 16:35:20 -0600264 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 if (builtins == NULL) {
266 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
267 return NULL;
268 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600269 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000270
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 /* Print value except if None */
272 /* After printing, also assign to '_' */
273 /* Before, set '_' to None to avoid recursion */
274 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200275 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200277 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100279 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (outf == NULL || outf == Py_None) {
281 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
282 return NULL;
283 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000284 if (PyFile_WriteObject(o, outf, 0) != 0) {
285 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
286 /* repr(o) is not encodable to sys.stdout.encoding with
287 * sys.stdout.errors error handler (which is probably 'strict') */
288 PyErr_Clear();
289 err = sys_displayhook_unencodable(outf, o);
290 if (err)
291 return NULL;
292 }
293 else {
294 return NULL;
295 }
296 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100297 if (newline == NULL) {
298 newline = PyUnicode_FromString("\n");
299 if (newline == NULL)
300 return NULL;
301 }
302 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200304 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000305 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200306 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000307}
308
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000309PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000310"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000311"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000312"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000313);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000314
315static PyObject *
316sys_excepthook(PyObject* self, PyObject* args)
317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 PyObject *exc, *value, *tb;
319 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
320 return NULL;
321 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200322 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000323}
324
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000325PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000326"excepthook(exctype, value, traceback) -> None\n"
327"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000328"Handle an exception by displaying it with a traceback on sys.stderr.\n"
329);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000330
331static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000332sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000333{
Mark Shannonae3087c2017-10-22 22:41:51 +0100334 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000335 return Py_BuildValue(
336 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100337 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
338 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
339 err_info->exc_traceback != NULL ?
340 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000341}
342
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000343PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000344"exc_info() -> (type, value, traceback)\n\
345\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000346Return information about the most recent exception caught by an except\n\
347clause in the current stack frame or in an older stack frame."
348);
349
350static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000351sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject *exit_code = 0;
354 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
355 return NULL;
356 /* Raise SystemExit so callers may catch it or clean up. */
357 PyErr_SetObject(PyExc_SystemExit, exit_code);
358 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359}
360
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000361PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000362"exit([status])\n\
363\n\
364Exit the interpreter by raising SystemExit(status).\n\
365If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300366If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000367If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000368exit status will be one (i.e., failure)."
369);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000370
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000371
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000372static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000373sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000374{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000376}
377
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000378PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000379"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000380\n\
381Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000382implementation."
383);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000384
385static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000386sys_getfilesystemencoding(PyObject *self)
387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 if (Py_FileSystemDefaultEncoding)
389 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200390 PyErr_SetString(PyExc_RuntimeError,
391 "filesystem encoding is not initialized");
392 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000393}
394
395PyDoc_STRVAR(getfilesystemencoding_doc,
396"getfilesystemencoding() -> string\n\
397\n\
398Return the encoding used to convert Unicode filenames in\n\
399operating system filenames."
400);
401
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000402static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700403sys_getfilesystemencodeerrors(PyObject *self)
404{
405 if (Py_FileSystemDefaultEncodeErrors)
406 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
407 PyErr_SetString(PyExc_RuntimeError,
408 "filesystem encoding is not initialized");
409 return NULL;
410}
411
412PyDoc_STRVAR(getfilesystemencodeerrors_doc,
413 "getfilesystemencodeerrors() -> string\n\
414\n\
415Return the error mode used to convert Unicode filenames in\n\
416operating system filenames."
417);
418
419static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000420sys_intern(PyObject *self, PyObject *args)
421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyObject *s;
423 if (!PyArg_ParseTuple(args, "U:intern", &s))
424 return NULL;
425 if (PyUnicode_CheckExact(s)) {
426 Py_INCREF(s);
427 PyUnicode_InternInPlace(&s);
428 return s;
429 }
430 else {
431 PyErr_Format(PyExc_TypeError,
432 "can't intern %.400s", s->ob_type->tp_name);
433 return NULL;
434 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000435}
436
437PyDoc_STRVAR(intern_doc,
438"intern(string) -> string\n\
439\n\
440``Intern'' the given string. This enters the string in the (global)\n\
441table of interned strings whose purpose is to speed up dictionary lookups.\n\
442Return the string itself or the previously interned string object with the\n\
443same value.");
444
445
Fred Drake5755ce62001-06-27 19:19:46 +0000446/*
447 * Cached interned string objects used for calling the profile and
448 * trace functions. Initialized by trace_init().
449 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000450static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000451
452static int
453trace_init(void)
454{
Nick Coghlan5a851672017-09-08 10:14:16 +1000455 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200456 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000457 "c_call", "c_exception", "c_return",
458 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200459 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyObject *name;
461 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000462 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (whatstrings[i] == NULL) {
464 name = PyUnicode_InternFromString(whatnames[i]);
465 if (name == NULL)
466 return -1;
467 whatstrings[i] = name;
468 }
469 }
470 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000471}
472
473
474static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100475call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200479 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000480
Victor Stinner78da82b2016-08-20 01:22:57 +0200481 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200483 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100484
Victor Stinner78da82b2016-08-20 01:22:57 +0200485 stack[0] = (PyObject *)frame;
486 stack[1] = whatstrings[what];
487 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200490 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000491
Victor Stinner78da82b2016-08-20 01:22:57 +0200492 PyFrame_LocalsToFast(frame, 1);
493 if (result == NULL) {
494 PyTraceBack_Here(frame);
495 }
496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000498}
499
500static int
501profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (arg == NULL)
507 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100508 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (result == NULL) {
510 PyEval_SetProfile(NULL, NULL);
511 return -1;
512 }
513 Py_DECREF(result);
514 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000515}
516
517static int
518trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 PyObject *callback;
522 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (what == PyTrace_CALL)
525 callback = self;
526 else
527 callback = frame->f_trace;
528 if (callback == NULL)
529 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100530 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (result == NULL) {
532 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200533 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return -1;
535 }
536 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300537 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 }
539 else {
540 Py_DECREF(result);
541 }
542 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000543}
Fred Draked0838392001-06-16 21:02:31 +0000544
Fred Drake8b4d01d2000-05-09 19:57:01 +0000545static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000546sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (trace_init() == -1)
549 return NULL;
550 if (args == Py_None)
551 PyEval_SetTrace(NULL, NULL);
552 else
553 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200554 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000555}
556
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000557PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000558"settrace(function)\n\
559\n\
560Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000561function call. See the debugger chapter in the library manual."
562);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000563
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000564static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000565sys_gettrace(PyObject *self, PyObject *args)
566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyThreadState *tstate = PyThreadState_GET();
568 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (temp == NULL)
571 temp = Py_None;
572 Py_INCREF(temp);
573 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000574}
575
576PyDoc_STRVAR(gettrace_doc,
577"gettrace()\n\
578\n\
579Return the global debug tracing function set with sys.settrace.\n\
580See the debugger chapter in the library manual."
581);
582
583static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000584sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (trace_init() == -1)
587 return NULL;
588 if (args == Py_None)
589 PyEval_SetProfile(NULL, NULL);
590 else
591 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200592 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000593}
594
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000595PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000596"setprofile(function)\n\
597\n\
598Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000599and return. See the profiler chapter in the library manual."
600);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000601
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000602static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000603sys_getprofile(PyObject *self, PyObject *args)
604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 PyThreadState *tstate = PyThreadState_GET();
606 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (temp == NULL)
609 temp = Py_None;
610 Py_INCREF(temp);
611 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000612}
613
614PyDoc_STRVAR(getprofile_doc,
615"getprofile()\n\
616\n\
617Return the profiling function set with sys.setprofile.\n\
618See the profiler chapter in the library manual."
619);
620
621static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000622sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (PyErr_WarnEx(PyExc_DeprecationWarning,
625 "sys.getcheckinterval() and sys.setcheckinterval() "
626 "are deprecated. Use sys.setswitchinterval() "
627 "instead.", 1) < 0)
628 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600629 PyInterpreterState *interp = PyThreadState_GET()->interp;
630 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000631 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200632 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000633}
634
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000635PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000636"setcheckinterval(n)\n\
637\n\
638Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000639n instructions. This also affects how often thread switches occur."
640);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000641
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000642static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000643sys_getcheckinterval(PyObject *self, PyObject *args)
644{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (PyErr_WarnEx(PyExc_DeprecationWarning,
646 "sys.getcheckinterval() and sys.setcheckinterval() "
647 "are deprecated. Use sys.getswitchinterval() "
648 "instead.", 1) < 0)
649 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600650 PyInterpreterState *interp = PyThreadState_GET()->interp;
651 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000652}
653
654PyDoc_STRVAR(getcheckinterval_doc,
655"getcheckinterval() -> current check interval; see setcheckinterval()."
656);
657
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000658static PyObject *
659sys_setswitchinterval(PyObject *self, PyObject *args)
660{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000661 double d;
662 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
663 return NULL;
664 if (d <= 0.0) {
665 PyErr_SetString(PyExc_ValueError,
666 "switch interval must be strictly positive");
667 return NULL;
668 }
669 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200670 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000671}
672
673PyDoc_STRVAR(setswitchinterval_doc,
674"setswitchinterval(n)\n\
675\n\
676Set the ideal thread switching delay inside the Python interpreter\n\
677The actual frequency of switching threads can be lower if the\n\
678interpreter executes long sequences of uninterruptible code\n\
679(this is implementation-specific and workload-dependent).\n\
680\n\
681The parameter must represent the desired switching delay in seconds\n\
682A typical value is 0.005 (5 milliseconds)."
683);
684
685static PyObject *
686sys_getswitchinterval(PyObject *self, PyObject *args)
687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000689}
690
691PyDoc_STRVAR(getswitchinterval_doc,
692"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
693);
694
Tim Peterse5e065b2003-07-06 18:36:54 +0000695static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000696sys_setrecursionlimit(PyObject *self, PyObject *args)
697{
Victor Stinner50856d52015-10-13 00:11:21 +0200698 int new_limit, mark;
699 PyThreadState *tstate;
700
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
702 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200703
704 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200706 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 return NULL;
708 }
Victor Stinner50856d52015-10-13 00:11:21 +0200709
710 /* Issue #25274: When the recursion depth hits the recursion limit in
711 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
712 set to 1 and a RecursionError is raised. The overflowed flag is reset
713 to 0 when the recursion depth goes below the low-water mark: see
714 Py_LeaveRecursiveCall().
715
716 Reject too low new limit if the current recursion depth is higher than
717 the new low-water mark. Otherwise it may not be possible anymore to
718 reset the overflowed flag to 0. */
719 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
720 tstate = PyThreadState_GET();
721 if (tstate->recursion_depth >= mark) {
722 PyErr_Format(PyExc_RecursionError,
723 "cannot set the recursion limit to %i at "
724 "the recursion depth %i: the limit is too low",
725 new_limit, tstate->recursion_depth);
726 return NULL;
727 }
728
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000729 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200730 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000731}
732
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800733/*[clinic input]
734sys.set_coroutine_origin_tracking_depth
735
736 depth: int
737
738Enable or disable origin tracking for coroutine objects in this thread.
739
740Coroutine objects will track 'depth' frames of traceback information about
741where they came from, available in their cr_origin attribute. Set depth of 0
742to disable.
743[clinic start generated code]*/
744
745static PyObject *
746sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
747/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
748{
749 if (depth < 0) {
750 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
751 return NULL;
752 }
753 _PyEval_SetCoroutineOriginTrackingDepth(depth);
754 Py_RETURN_NONE;
755}
756
757/*[clinic input]
758sys.get_coroutine_origin_tracking_depth -> int
759
760Check status of origin tracking for coroutine objects in this thread.
761[clinic start generated code]*/
762
763static int
764sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
765/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
766{
767 return _PyEval_GetCoroutineOriginTrackingDepth();
768}
769
Yury Selivanov75445082015-05-11 22:57:16 -0400770static PyObject *
771sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
772{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800773 if (PyErr_WarnEx(PyExc_DeprecationWarning,
774 "set_coroutine_wrapper is deprecated", 1) < 0) {
775 return NULL;
776 }
777
Yury Selivanov75445082015-05-11 22:57:16 -0400778 if (wrapper != Py_None) {
779 if (!PyCallable_Check(wrapper)) {
780 PyErr_Format(PyExc_TypeError,
781 "callable expected, got %.50s",
782 Py_TYPE(wrapper)->tp_name);
783 return NULL;
784 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400785 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400786 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400787 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400788 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400789 }
Yury Selivanov75445082015-05-11 22:57:16 -0400790 Py_RETURN_NONE;
791}
792
793PyDoc_STRVAR(set_coroutine_wrapper_doc,
794"set_coroutine_wrapper(wrapper)\n\
795\n\
796Set a wrapper for coroutine objects."
797);
798
799static PyObject *
800sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
801{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800802 if (PyErr_WarnEx(PyExc_DeprecationWarning,
803 "get_coroutine_wrapper is deprecated", 1) < 0) {
804 return NULL;
805 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400806 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400807 if (wrapper == NULL) {
808 wrapper = Py_None;
809 }
810 Py_INCREF(wrapper);
811 return wrapper;
812}
813
814PyDoc_STRVAR(get_coroutine_wrapper_doc,
815"get_coroutine_wrapper()\n\
816\n\
817Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
818);
819
820
Yury Selivanoveb636452016-09-08 22:01:51 -0700821static PyTypeObject AsyncGenHooksType;
822
823PyDoc_STRVAR(asyncgen_hooks_doc,
824"asyncgen_hooks\n\
825\n\
826A struct sequence providing information about asynhronous\n\
827generators hooks. The attributes are read only.");
828
829static PyStructSequence_Field asyncgen_hooks_fields[] = {
830 {"firstiter", "Hook to intercept first iteration"},
831 {"finalizer", "Hook to intercept finalization"},
832 {0}
833};
834
835static PyStructSequence_Desc asyncgen_hooks_desc = {
836 "asyncgen_hooks", /* name */
837 asyncgen_hooks_doc, /* doc */
838 asyncgen_hooks_fields , /* fields */
839 2
840};
841
842
843static PyObject *
844sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
845{
846 static char *keywords[] = {"firstiter", "finalizer", NULL};
847 PyObject *firstiter = NULL;
848 PyObject *finalizer = NULL;
849
850 if (!PyArg_ParseTupleAndKeywords(
851 args, kw, "|OO", keywords,
852 &firstiter, &finalizer)) {
853 return NULL;
854 }
855
856 if (finalizer && finalizer != Py_None) {
857 if (!PyCallable_Check(finalizer)) {
858 PyErr_Format(PyExc_TypeError,
859 "callable finalizer expected, got %.50s",
860 Py_TYPE(finalizer)->tp_name);
861 return NULL;
862 }
863 _PyEval_SetAsyncGenFinalizer(finalizer);
864 }
865 else if (finalizer == Py_None) {
866 _PyEval_SetAsyncGenFinalizer(NULL);
867 }
868
869 if (firstiter && firstiter != Py_None) {
870 if (!PyCallable_Check(firstiter)) {
871 PyErr_Format(PyExc_TypeError,
872 "callable firstiter expected, got %.50s",
873 Py_TYPE(firstiter)->tp_name);
874 return NULL;
875 }
876 _PyEval_SetAsyncGenFirstiter(firstiter);
877 }
878 else if (firstiter == Py_None) {
879 _PyEval_SetAsyncGenFirstiter(NULL);
880 }
881
882 Py_RETURN_NONE;
883}
884
885PyDoc_STRVAR(set_asyncgen_hooks_doc,
886"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
887\n\
888Set a finalizer for async generators objects."
889);
890
891static PyObject *
892sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
893{
894 PyObject *res;
895 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
896 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
897
898 res = PyStructSequence_New(&AsyncGenHooksType);
899 if (res == NULL) {
900 return NULL;
901 }
902
903 if (firstiter == NULL) {
904 firstiter = Py_None;
905 }
906
907 if (finalizer == NULL) {
908 finalizer = Py_None;
909 }
910
911 Py_INCREF(firstiter);
912 PyStructSequence_SET_ITEM(res, 0, firstiter);
913
914 Py_INCREF(finalizer);
915 PyStructSequence_SET_ITEM(res, 1, finalizer);
916
917 return res;
918}
919
920PyDoc_STRVAR(get_asyncgen_hooks_doc,
921"get_asyncgen_hooks()\n\
922\n\
923Return a namedtuple of installed asynchronous generators hooks \
924(firstiter, finalizer)."
925);
926
927
Mark Dickinsondc787d22010-05-23 13:33:13 +0000928static PyTypeObject Hash_InfoType;
929
930PyDoc_STRVAR(hash_info_doc,
931"hash_info\n\
932\n\
933A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100934hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000935
936static PyStructSequence_Field hash_info_fields[] = {
937 {"width", "width of the type used for hashing, in bits"},
938 {"modulus", "prime number giving the modulus on which the hash "
939 "function is based"},
940 {"inf", "value to be used for hash of a positive infinity"},
941 {"nan", "value to be used for hash of a nan"},
942 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100943 {"algorithm", "name of the algorithm for hashing of str, bytes and "
944 "memoryviews"},
945 {"hash_bits", "internal output size of hash algorithm"},
946 {"seed_bits", "seed size of hash algorithm"},
947 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000948 {NULL, NULL}
949};
950
951static PyStructSequence_Desc hash_info_desc = {
952 "sys.hash_info",
953 hash_info_doc,
954 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100955 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000956};
957
Matthias Klosed885e952010-07-06 10:53:30 +0000958static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000959get_hash_info(void)
960{
961 PyObject *hash_info;
962 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100963 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000964 hash_info = PyStructSequence_New(&Hash_InfoType);
965 if (hash_info == NULL)
966 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100967 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000968 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000969 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000970 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000971 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000972 PyStructSequence_SET_ITEM(hash_info, field++,
973 PyLong_FromLong(_PyHASH_INF));
974 PyStructSequence_SET_ITEM(hash_info, field++,
975 PyLong_FromLong(_PyHASH_NAN));
976 PyStructSequence_SET_ITEM(hash_info, field++,
977 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100978 PyStructSequence_SET_ITEM(hash_info, field++,
979 PyUnicode_FromString(hashfunc->name));
980 PyStructSequence_SET_ITEM(hash_info, field++,
981 PyLong_FromLong(hashfunc->hash_bits));
982 PyStructSequence_SET_ITEM(hash_info, field++,
983 PyLong_FromLong(hashfunc->seed_bits));
984 PyStructSequence_SET_ITEM(hash_info, field++,
985 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000986 if (PyErr_Occurred()) {
987 Py_CLEAR(hash_info);
988 return NULL;
989 }
990 return hash_info;
991}
992
993
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000994PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000995"setrecursionlimit(n)\n\
996\n\
997Set the maximum depth of the Python interpreter stack to n. This\n\
998limit prevents infinite recursion from causing an overflow of the C\n\
999stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001000dependent."
1001);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001002
1003static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001004sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001007}
1008
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001009PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001010"getrecursionlimit()\n\
1011\n\
1012Return the current value of the recursion limit, the maximum depth\n\
1013of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001014recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001015);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001016
Mark Hammond8696ebc2002-10-08 02:44:31 +00001017#ifdef MS_WINDOWS
1018PyDoc_STRVAR(getwindowsversion_doc,
1019"getwindowsversion()\n\
1020\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001021Return information about the running version of Windows as a named tuple.\n\
1022The members are named: major, minor, build, platform, service_pack,\n\
1023service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001024backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001025All elements are numbers, except service_pack and platform_type which are\n\
1026strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1027Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1028server. Platform_version is a 3-tuple containing a version number that is\n\
1029intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001030);
1031
Eric Smithf7bb5782010-01-27 00:44:57 +00001032static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1033
1034static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 {"major", "Major version number"},
1036 {"minor", "Minor version number"},
1037 {"build", "Build number"},
1038 {"platform", "Operating system platform"},
1039 {"service_pack", "Latest Service Pack installed on the system"},
1040 {"service_pack_major", "Service Pack major version number"},
1041 {"service_pack_minor", "Service Pack minor version number"},
1042 {"suite_mask", "Bit mask identifying available product suites"},
1043 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001044 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001046};
1047
1048static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 "sys.getwindowsversion", /* name */
1050 getwindowsversion_doc, /* doc */
1051 windows_version_fields, /* fields */
1052 5 /* For backward compatibility,
1053 only the first 5 items are accessible
1054 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001055};
1056
Steve Dower3e96f322015-03-02 08:01:10 -08001057/* Disable deprecation warnings about GetVersionEx as the result is
1058 being passed straight through to the caller, who is responsible for
1059 using it correctly. */
1060#pragma warning(push)
1061#pragma warning(disable:4996)
1062
Mark Hammond8696ebc2002-10-08 02:44:31 +00001063static PyObject *
1064sys_getwindowsversion(PyObject *self)
1065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 PyObject *version;
1067 int pos = 0;
1068 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001069 DWORD realMajor, realMinor, realBuild;
1070 HANDLE hKernel32;
1071 wchar_t kernel32_path[MAX_PATH];
1072 LPVOID verblock;
1073 DWORD verblock_size;
1074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 ver.dwOSVersionInfoSize = sizeof(ver);
1076 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1077 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 version = PyStructSequence_New(&WindowsVersionType);
1080 if (version == NULL)
1081 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1084 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1085 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1086 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1087 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1088 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1089 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1090 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1091 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001092
Steve Dower74f4af72016-09-17 17:27:48 -07001093 realMajor = ver.dwMajorVersion;
1094 realMinor = ver.dwMinorVersion;
1095 realBuild = ver.dwBuildNumber;
1096
1097 // GetVersion will lie if we are running in a compatibility mode.
1098 // We need to read the version info from a system file resource
1099 // to accurately identify the OS version. If we fail for any reason,
1100 // just return whatever GetVersion said.
1101 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1102 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1103 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1104 (verblock = PyMem_RawMalloc(verblock_size))) {
1105 VS_FIXEDFILEINFO *ffi;
1106 UINT ffi_len;
1107
1108 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1109 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1110 realMajor = HIWORD(ffi->dwProductVersionMS);
1111 realMinor = LOWORD(ffi->dwProductVersionMS);
1112 realBuild = HIWORD(ffi->dwProductVersionLS);
1113 }
1114 PyMem_RawFree(verblock);
1115 }
Segev Finer48fb7662017-06-04 20:52:27 +03001116 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1117 realMajor,
1118 realMinor,
1119 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001120 ));
1121
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001122 if (PyErr_Occurred()) {
1123 Py_DECREF(version);
1124 return NULL;
1125 }
Steve Dower74f4af72016-09-17 17:27:48 -07001126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001128}
1129
Steve Dower3e96f322015-03-02 08:01:10 -08001130#pragma warning(pop)
1131
Steve Dowercc16be82016-09-08 10:35:16 -07001132PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1133"_enablelegacywindowsfsencoding()\n\
1134\n\
1135Changes the default filesystem encoding to mbcs:replace for consistency\n\
1136with earlier versions of Python. See PEP 529 for more information.\n\
1137\n\
1138This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1139environment variable before launching Python."
1140);
1141
1142static PyObject *
1143sys_enablelegacywindowsfsencoding(PyObject *self)
1144{
1145 Py_FileSystemDefaultEncoding = "mbcs";
1146 Py_FileSystemDefaultEncodeErrors = "replace";
1147 Py_RETURN_NONE;
1148}
1149
Mark Hammond8696ebc2002-10-08 02:44:31 +00001150#endif /* MS_WINDOWS */
1151
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001152#ifdef HAVE_DLOPEN
1153static PyObject *
1154sys_setdlopenflags(PyObject *self, PyObject *args)
1155{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 int new_val;
1157 PyThreadState *tstate = PyThreadState_GET();
1158 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1159 return NULL;
1160 if (!tstate)
1161 return NULL;
1162 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001163 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001164}
1165
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001166PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001167"setdlopenflags(n) -> None\n\
1168\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001169Set the flags used by the interpreter for dlopen calls, such as when the\n\
1170interpreter loads extension modules. Among other things, this will enable\n\
1171a lazy resolving of symbols when importing a module, if called as\n\
1172sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001173sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001174can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001175
1176static PyObject *
1177sys_getdlopenflags(PyObject *self, PyObject *args)
1178{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 PyThreadState *tstate = PyThreadState_GET();
1180 if (!tstate)
1181 return NULL;
1182 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001183}
1184
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001185PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001186"getdlopenflags() -> int\n\
1187\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001188Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001189The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001191#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001192
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001193#ifdef USE_MALLOPT
1194/* Link with -lmalloc (or -lmpc) on an SGI */
1195#include <malloc.h>
1196
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001197static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001198sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 int flag;
1201 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1202 return NULL;
1203 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001204 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001205}
1206#endif /* USE_MALLOPT */
1207
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001208size_t
1209_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001212 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001213 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 /* Make sure the type is initialized. float gets initialized late */
1216 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001217 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001218
Benjamin Petersonce798522012-01-22 11:24:29 -05001219 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 if (method == NULL) {
1221 if (!PyErr_Occurred())
1222 PyErr_Format(PyExc_TypeError,
1223 "Type %.100s doesn't define __sizeof__",
1224 Py_TYPE(o)->tp_name);
1225 }
1226 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001227 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 Py_DECREF(method);
1229 }
1230
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001231 if (res == NULL)
1232 return (size_t)-1;
1233
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001234 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001235 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001236 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001237 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001239 if (size < 0) {
1240 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1241 return (size_t)-1;
1242 }
1243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001245 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001246 return ((size_t)size) + sizeof(PyGC_Head);
1247 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001248}
1249
1250static PyObject *
1251sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1252{
1253 static char *kwlist[] = {"object", "default", 0};
1254 size_t size;
1255 PyObject *o, *dflt = NULL;
1256
1257 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1258 kwlist, &o, &dflt))
1259 return NULL;
1260
1261 size = _PySys_GetSizeOf(o);
1262
1263 if (size == (size_t)-1 && PyErr_Occurred()) {
1264 /* Has a default value been given */
1265 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1266 PyErr_Clear();
1267 Py_INCREF(dflt);
1268 return dflt;
1269 }
1270 else
1271 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001273
1274 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001275}
1276
1277PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001278"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001279\n\
1280Return the size of object in bytes.");
1281
1282static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001283sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001286}
1287
Tim Peters4be93d02002-07-07 19:59:50 +00001288#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001289static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001290sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001291{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001293}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001294#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001295
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001296PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001297"getrefcount(object) -> integer\n\
1298\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001299Return the reference count of object. The count returned is generally\n\
1300one higher than you might expect, because it includes the (temporary)\n\
1301reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001302);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001303
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001304static PyObject *
1305sys_getallocatedblocks(PyObject *self)
1306{
1307 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1308}
1309
1310PyDoc_STRVAR(getallocatedblocks_doc,
1311"getallocatedblocks() -> integer\n\
1312\n\
1313Return the number of memory blocks currently allocated, regardless of their\n\
1314size."
1315);
1316
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001317#ifdef COUNT_ALLOCS
1318static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001319sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001320{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001324}
1325#endif
1326
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001327PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001328"_getframe([depth]) -> frameobject\n\
1329\n\
1330Return a frame object from the call stack. If optional integer depth is\n\
1331given, return the frame object that many calls below the top of the stack.\n\
1332If that is deeper than the call stack, ValueError is raised. The default\n\
1333for depth is zero, returning the frame at the top of the call stack.\n\
1334\n\
1335This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001336purposes only."
1337);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001338
1339static PyObject *
1340sys_getframe(PyObject *self, PyObject *args)
1341{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 PyFrameObject *f = PyThreadState_GET()->frame;
1343 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1346 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 while (depth > 0 && f != NULL) {
1349 f = f->f_back;
1350 --depth;
1351 }
1352 if (f == NULL) {
1353 PyErr_SetString(PyExc_ValueError,
1354 "call stack is not deep enough");
1355 return NULL;
1356 }
1357 Py_INCREF(f);
1358 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001359}
1360
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001361PyDoc_STRVAR(current_frames_doc,
1362"_current_frames() -> dictionary\n\
1363\n\
1364Return a dictionary mapping each current thread T's thread id to T's\n\
1365current stack frame.\n\
1366\n\
1367This function should be used for specialized purposes only."
1368);
1369
1370static PyObject *
1371sys_current_frames(PyObject *self, PyObject *noargs)
1372{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001374}
1375
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001376PyDoc_STRVAR(call_tracing_doc,
1377"call_tracing(func, args) -> object\n\
1378\n\
1379Call func(*args), while tracing is enabled. The tracing state is\n\
1380saved, and restored afterwards. This is intended to be called from\n\
1381a debugger from a checkpoint, to recursively debug some other code."
1382);
1383
1384static PyObject *
1385sys_call_tracing(PyObject *self, PyObject *args)
1386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001387 PyObject *func, *funcargs;
1388 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1389 return NULL;
1390 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001391}
1392
Jeremy Hylton985eba52003-02-05 23:13:00 +00001393PyDoc_STRVAR(callstats_doc,
1394"callstats() -> tuple of integers\n\
1395\n\
1396Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1397when Python was built. Otherwise, return None.\n\
1398\n\
1399When enabled, this function returns detailed, implementation-specific\n\
1400details about the number of function calls executed. The return value is\n\
1401a 11-tuple where the entries in the tuple are counts of:\n\
14020. all function calls\n\
14031. calls to PyFunction_Type objects\n\
14042. PyFunction calls that do not create an argument tuple\n\
14053. PyFunction calls that do not create an argument tuple\n\
1406 and bypass PyEval_EvalCodeEx()\n\
14074. PyMethod calls\n\
14085. PyMethod calls on bound methods\n\
14096. PyType calls\n\
14107. PyCFunction calls\n\
14118. generator calls\n\
14129. All other calls\n\
141310. Number of stack pops performed by call_function()"
1414);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001415
Victor Stinner048afd92016-11-28 11:59:04 +01001416static PyObject *
1417sys_callstats(PyObject *self)
1418{
1419 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1420 "sys.callstats() has been deprecated in Python 3.7 "
1421 "and will be removed in the future", 1) < 0) {
1422 return NULL;
1423 }
1424
1425 Py_RETURN_NONE;
1426}
1427
1428
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001429#ifdef __cplusplus
1430extern "C" {
1431#endif
1432
David Malcolm49526f42012-06-22 14:55:41 -04001433static PyObject *
1434sys_debugmallocstats(PyObject *self, PyObject *args)
1435{
1436#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001437 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001438 fputc('\n', stderr);
1439 }
David Malcolm49526f42012-06-22 14:55:41 -04001440#endif
1441 _PyObject_DebugTypeStats(stderr);
1442
1443 Py_RETURN_NONE;
1444}
1445PyDoc_STRVAR(debugmallocstats_doc,
1446"_debugmallocstats()\n\
1447\n\
1448Print summary info to stderr about the state of\n\
1449pymalloc's structures.\n\
1450\n\
1451In Py_DEBUG mode, also perform some expensive internal consistency\n\
1452checks.\n\
1453");
1454
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001455#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001456/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001457extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001458#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001459
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001460#ifdef DYNAMIC_EXECUTION_PROFILE
1461/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001462extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001463#endif
1464
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001465#ifdef __cplusplus
1466}
1467#endif
1468
Christian Heimes15ebc882008-02-04 18:48:49 +00001469static PyObject *
1470sys_clear_type_cache(PyObject* self, PyObject* args)
1471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 PyType_ClearCache();
1473 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001474}
1475
1476PyDoc_STRVAR(sys_clear_type_cache__doc__,
1477"_clear_type_cache() -> None\n\
1478Clear the internal type lookup cache.");
1479
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001480static PyObject *
1481sys_is_finalizing(PyObject* self, PyObject* args)
1482{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001483 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001484}
1485
1486PyDoc_STRVAR(is_finalizing_doc,
1487"is_finalizing()\n\
1488Return True if Python is exiting.");
1489
Christian Heimes15ebc882008-02-04 18:48:49 +00001490
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001491#ifdef ANDROID_API_LEVEL
1492PyDoc_STRVAR(getandroidapilevel_doc,
1493"getandroidapilevel()\n\
1494\n\
1495Return the build time API version of Android as an integer.");
1496
1497static PyObject *
1498sys_getandroidapilevel(PyObject *self)
1499{
1500 return PyLong_FromLong(ANDROID_API_LEVEL);
1501}
1502#endif /* ANDROID_API_LEVEL */
1503
1504
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001505static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001507 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1508 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Victor Stinner048afd92016-11-28 11:59:04 +01001509 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 callstats_doc},
1511 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1512 sys_clear_type_cache__doc__},
1513 {"_current_frames", sys_current_frames, METH_NOARGS,
1514 current_frames_doc},
1515 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1516 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1517 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1518 {"exit", sys_exit, METH_VARARGS, exit_doc},
1519 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1520 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001521#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1523 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001524#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001525 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1526 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001527#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001529#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001530#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001532#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1534 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001535 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1536 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001537#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001539#endif
1540#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001542#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1544 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1545 getrecursionlimit_doc},
1546 {"getsizeof", (PyCFunction)sys_getsizeof,
1547 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1548 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001549#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1551 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001552 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1553 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001554#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001556 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001557#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001559#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1561 setcheckinterval_doc},
1562 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1563 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1565 setswitchinterval_doc},
1566 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1567 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001568#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1570 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001571#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1573 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1574 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1575 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 {"settrace", sys_settrace, METH_O, settrace_doc},
1577 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1578 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001579 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001580 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001581 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1582 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001583 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1584 set_coroutine_wrapper_doc},
1585 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1586 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001587 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001588 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1589 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1590 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001591#ifdef ANDROID_API_LEVEL
1592 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1593 getandroidapilevel_doc},
1594#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001596};
1597
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001598static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001599list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 PyObject *list = PyList_New(0);
1602 int i;
1603 if (list == NULL)
1604 return NULL;
1605 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1606 PyObject *name = PyUnicode_FromString(
1607 PyImport_Inittab[i].name);
1608 if (name == NULL)
1609 break;
1610 PyList_Append(list, name);
1611 Py_DECREF(name);
1612 }
1613 if (PyList_Sort(list) != 0) {
1614 Py_DECREF(list);
1615 list = NULL;
1616 }
1617 if (list) {
1618 PyObject *v = PyList_AsTuple(list);
1619 Py_DECREF(list);
1620 list = v;
1621 }
1622 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001623}
1624
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001625/* Pre-initialization support for sys.warnoptions and sys._xoptions
1626 *
1627 * Modern internal code paths:
1628 * These APIs get called after _Py_InitializeCore and get to use the
1629 * regular CPython list, dict, and unicode APIs.
1630 *
1631 * Legacy embedding code paths:
1632 * The multi-phase initialization API isn't public yet, so embedding
1633 * apps still need to be able configure sys.warnoptions and sys._xoptions
1634 * before they call Py_Initialize. To support this, we stash copies of
1635 * the supplied wchar * sequences in linked lists, and then migrate the
1636 * contents of those lists to the sys module in _PyInitializeCore.
1637 *
1638 */
1639
1640struct _preinit_entry {
1641 wchar_t *value;
1642 struct _preinit_entry *next;
1643};
1644
1645typedef struct _preinit_entry *_Py_PreInitEntry;
1646
1647static _Py_PreInitEntry _preinit_warnoptions = NULL;
1648static _Py_PreInitEntry _preinit_xoptions = NULL;
1649
1650static _Py_PreInitEntry
1651_alloc_preinit_entry(const wchar_t *value)
1652{
1653 /* To get this to work, we have to initialize the runtime implicitly */
1654 _PyRuntime_Initialize();
1655
1656 /* Force default allocator, so we can ensure that it also gets used to
1657 * destroy the linked list in _clear_preinit_entries.
1658 */
1659 PyMemAllocatorEx old_alloc;
1660 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1661
1662 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1663 if (node != NULL) {
1664 node->value = _PyMem_RawWcsdup(value);
1665 if (node->value == NULL) {
1666 PyMem_RawFree(node);
1667 node = NULL;
1668 };
1669 };
1670
1671 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1672 return node;
1673};
1674
1675static int
1676_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1677{
1678 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1679 if (new_entry == NULL) {
1680 return -1;
1681 }
1682 /* We maintain the linked list in this order so it's easy to play back
1683 * the add commands in the same order later on in _Py_InitializeCore
1684 */
1685 _Py_PreInitEntry last_entry = *optionlist;
1686 if (last_entry == NULL) {
1687 *optionlist = new_entry;
1688 } else {
1689 while (last_entry->next != NULL) {
1690 last_entry = last_entry->next;
1691 }
1692 last_entry->next = new_entry;
1693 }
1694 return 0;
1695};
1696
1697static void
1698_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1699{
1700 _Py_PreInitEntry current = *optionlist;
1701 *optionlist = NULL;
1702 /* Deallocate the nodes and their contents using the default allocator */
1703 PyMemAllocatorEx old_alloc;
1704 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1705 while (current != NULL) {
1706 _Py_PreInitEntry next = current->next;
1707 PyMem_RawFree(current->value);
1708 PyMem_RawFree(current);
1709 current = next;
1710 }
1711 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1712};
1713
1714static void
1715_clear_all_preinit_options(void)
1716{
1717 _clear_preinit_entries(&_preinit_warnoptions);
1718 _clear_preinit_entries(&_preinit_xoptions);
1719}
1720
1721static int
1722_PySys_ReadPreInitOptions(void)
1723{
1724 /* Rerun the add commands with the actual sys module available */
1725 PyThreadState *tstate = PyThreadState_GET();
1726 if (tstate == NULL) {
1727 /* Still don't have a thread state, so something is wrong! */
1728 return -1;
1729 }
1730 _Py_PreInitEntry entry = _preinit_warnoptions;
1731 while (entry != NULL) {
1732 PySys_AddWarnOption(entry->value);
1733 entry = entry->next;
1734 }
1735 entry = _preinit_xoptions;
1736 while (entry != NULL) {
1737 PySys_AddXOption(entry->value);
1738 entry = entry->next;
1739 }
1740
1741 _clear_all_preinit_options();
1742 return 0;
1743};
1744
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001745static PyObject *
1746get_warnoptions(void)
1747{
Eric Snowdae02762017-09-14 00:35:58 -07001748 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001749 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001750 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1751 * interpreter config. When that happens, we need to properly set
1752 * the `warnoptions` reference in the main interpreter config as well.
1753 *
1754 * For Python 3.7, we shouldn't be able to get here due to the
1755 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1756 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1757 * call optional for embedding applications, thus making this
1758 * reachable again.
1759 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001760 warnoptions = PyList_New(0);
1761 if (warnoptions == NULL)
1762 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001763 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1764 Py_DECREF(warnoptions);
1765 return NULL;
1766 }
1767 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001768 }
1769 return warnoptions;
1770}
Guido van Rossum23fff912000-12-15 22:02:05 +00001771
1772void
1773PySys_ResetWarnOptions(void)
1774{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001775 PyThreadState *tstate = PyThreadState_GET();
1776 if (tstate == NULL) {
1777 _clear_preinit_entries(&_preinit_warnoptions);
1778 return;
1779 }
1780
Eric Snowdae02762017-09-14 00:35:58 -07001781 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 if (warnoptions == NULL || !PyList_Check(warnoptions))
1783 return;
1784 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001785}
1786
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001787int
1788_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001789{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001790 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001791 if (warnoptions == NULL) {
1792 return -1;
1793 }
1794 if (PyList_Append(warnoptions, option)) {
1795 return -1;
1796 }
1797 return 0;
1798}
1799
1800void
1801PySys_AddWarnOptionUnicode(PyObject *option)
1802{
1803 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001804}
1805
1806void
1807PySys_AddWarnOption(const wchar_t *s)
1808{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001809 PyThreadState *tstate = PyThreadState_GET();
1810 if (tstate == NULL) {
1811 _append_preinit_entry(&_preinit_warnoptions, s);
1812 return;
1813 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001814 PyObject *unicode;
1815 unicode = PyUnicode_FromWideChar(s, -1);
1816 if (unicode == NULL)
1817 return;
1818 PySys_AddWarnOptionUnicode(unicode);
1819 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001820}
1821
Christian Heimes33fe8092008-04-13 13:53:33 +00001822int
1823PySys_HasWarnOptions(void)
1824{
Eric Snowdae02762017-09-14 00:35:58 -07001825 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Miss Islington (bot)ea773eb2018-12-10 04:37:09 -08001826 return (warnoptions != NULL && PyList_Check(warnoptions)
1827 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001828}
1829
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001830static PyObject *
1831get_xoptions(void)
1832{
Eric Snowdae02762017-09-14 00:35:58 -07001833 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001834 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001835 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1836 * interpreter config. When that happens, we need to properly set
1837 * the `xoptions` reference in the main interpreter config as well.
1838 *
1839 * For Python 3.7, we shouldn't be able to get here due to the
1840 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1841 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1842 * call optional for embedding applications, thus making this
1843 * reachable again.
1844 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001845 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001846 if (xoptions == NULL)
1847 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001848 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1849 Py_DECREF(xoptions);
1850 return NULL;
1851 }
1852 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001853 }
1854 return xoptions;
1855}
1856
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001857int
1858_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001859{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001860 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001861
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001862 PyObject *opts = get_xoptions();
1863 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001864 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001865 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001866
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001867 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001868 if (!name_end) {
1869 name = PyUnicode_FromWideChar(s, -1);
1870 value = Py_True;
1871 Py_INCREF(value);
1872 }
1873 else {
1874 name = PyUnicode_FromWideChar(s, name_end - s);
1875 value = PyUnicode_FromWideChar(name_end + 1, -1);
1876 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001877 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001878 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001879 }
1880 if (PyDict_SetItem(opts, name, value) < 0) {
1881 goto error;
1882 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001883 Py_DECREF(name);
1884 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001885 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001886
1887error:
1888 Py_XDECREF(name);
1889 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001890 return -1;
1891}
1892
1893void
1894PySys_AddXOption(const wchar_t *s)
1895{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001896 PyThreadState *tstate = PyThreadState_GET();
1897 if (tstate == NULL) {
1898 _append_preinit_entry(&_preinit_xoptions, s);
1899 return;
1900 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001901 if (_PySys_AddXOptionWithError(s) < 0) {
1902 /* No return value, therefore clear error state if possible */
1903 if (_PyThreadState_UncheckedGet()) {
1904 PyErr_Clear();
1905 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001906 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001907}
1908
1909PyObject *
1910PySys_GetXOptions(void)
1911{
1912 return get_xoptions();
1913}
1914
Guido van Rossum40552d01998-08-06 03:34:39 +00001915/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1916 Two literals concatenated works just fine. If you have a K&R compiler
1917 or other abomination that however *does* understand longer strings,
1918 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001919PyDoc_VAR(sys_doc) =
1920PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001921"This module provides access to some objects used or maintained by the\n\
1922interpreter and to functions that interact strongly with the interpreter.\n\
1923\n\
1924Dynamic objects:\n\
1925\n\
1926argv -- command line arguments; argv[0] is the script pathname if known\n\
1927path -- module search path; path[0] is the script directory, else ''\n\
1928modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001929\n\
1930displayhook -- called to show results in an interactive session\n\
1931excepthook -- called to handle any uncaught exception other than SystemExit\n\
1932 To customize printing in an interactive session or to install a custom\n\
1933 top-level exception handler, assign other functions to replace these.\n\
1934\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001935stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001936stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001937stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001938 By assigning other file objects (or objects that behave like files)\n\
1939 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001940\n\
1941last_type -- type of last uncaught exception\n\
1942last_value -- value of last uncaught exception\n\
1943last_traceback -- traceback of last uncaught exception\n\
1944 These three are only available in an interactive session after a\n\
1945 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001946"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001947)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001948/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001949PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001950"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001951Static objects:\n\
1952\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001953builtin_module_names -- tuple of module names built into this interpreter\n\
1954copyright -- copyright notice pertaining to this interpreter\n\
1955exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001956executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001957float_info -- a struct sequence with information about the float implementation.\n\
1958float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001959hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001960hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001961implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001962int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001963maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001964maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001965platform -- platform identifier\n\
1966prefix -- prefix used to find the Python library\n\
1967thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001968version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001969version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001970"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001971)
Steve Dowercc16be82016-09-08 10:35:16 -07001972#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001973/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001974PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001975"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001976winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001977"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001978)
Steve Dowercc16be82016-09-08 10:35:16 -07001979#endif /* MS_COREDLL */
1980#ifdef MS_WINDOWS
1981/* concatenating string here */
1982PyDoc_STR(
1983"_enablelegacywindowsfsencoding -- [Windows only] \n\
1984"
1985)
1986#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001987PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001988"__stdin__ -- the original stdin; don't touch!\n\
1989__stdout__ -- the original stdout; don't touch!\n\
1990__stderr__ -- the original stderr; don't touch!\n\
1991__displayhook__ -- the original displayhook; don't touch!\n\
1992__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001993\n\
1994Functions:\n\
1995\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001996displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001997excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001998exc_info() -- return thread-safe information about the current exception\n\
1999exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002000getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002001getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002002getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002003getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002004getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002005gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002006setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002007setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002008setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002009setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002010settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002011"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002012)
Fred Drakeccede592000-08-14 20:59:57 +00002013/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002014
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002015
2016PyDoc_STRVAR(flags__doc__,
2017"sys.flags\n\
2018\n\
2019Flags provided through command line arguments or environment vars.");
2020
2021static PyTypeObject FlagsType;
2022
2023static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 {"inspect", "-i"},
2026 {"interactive", "-i"},
2027 {"optimize", "-O or -OO"},
2028 {"dont_write_bytecode", "-B"},
2029 {"no_user_site", "-s"},
2030 {"no_site", "-S"},
2031 {"ignore_environment", "-E"},
2032 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 /* {"unbuffered", "-u"}, */
2034 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002035 {"bytes_warning", "-b"},
2036 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002037 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002038 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002039 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002040 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002041 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002042};
2043
2044static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 "sys.flags", /* name */
2046 flags__doc__, /* doc */
2047 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002048 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002049};
2050
2051static PyObject*
2052make_flags(void)
2053{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 int pos = 0;
2055 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01002056 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002057
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 seq = PyStructSequence_New(&FlagsType);
2059 if (seq == NULL)
2060 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002061
2062#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002066 SetFlag(Py_InspectFlag);
2067 SetFlag(Py_InteractiveFlag);
2068 SetFlag(Py_OptimizeFlag);
2069 SetFlag(Py_DontWriteBytecodeFlag);
2070 SetFlag(Py_NoUserSiteDirectory);
2071 SetFlag(Py_NoSiteFlag);
2072 SetFlag(Py_IgnoreEnvironmentFlag);
2073 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 /* SetFlag(saw_unbuffered_flag); */
2075 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00002076 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00002077 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002078 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02002079 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01002080 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01002081 SetFlag(Py_UTF8Mode);
2082#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002085 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 return NULL;
2087 }
2088 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002089}
2090
Eric Smith0e5b5622009-02-06 01:32:42 +00002091PyDoc_STRVAR(version_info__doc__,
2092"sys.version_info\n\
2093\n\
2094Version information as a named tuple.");
2095
2096static PyTypeObject VersionInfoType;
2097
2098static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 {"major", "Major release number"},
2100 {"minor", "Minor release number"},
2101 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002102 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 {"serial", "Serial release number"},
2104 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002105};
2106
2107static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 "sys.version_info", /* name */
2109 version_info__doc__, /* doc */
2110 version_info_fields, /* fields */
2111 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002112};
2113
2114static PyObject *
2115make_version_info(void)
2116{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 PyObject *version_info;
2118 char *s;
2119 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 version_info = PyStructSequence_New(&VersionInfoType);
2122 if (version_info == NULL) {
2123 return NULL;
2124 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 /*
2127 * These release level checks are mutually exclusive and cover
2128 * the field, so don't get too fancy with the pre-processor!
2129 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002130#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002132#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002133 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002134#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002136#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002138#endif
2139
2140#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002142#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002144
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 SetIntItem(PY_MAJOR_VERSION);
2146 SetIntItem(PY_MINOR_VERSION);
2147 SetIntItem(PY_MICRO_VERSION);
2148 SetStrItem(s);
2149 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002150#undef SetIntItem
2151#undef SetStrItem
2152
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 if (PyErr_Occurred()) {
2154 Py_CLEAR(version_info);
2155 return NULL;
2156 }
2157 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002158}
2159
Brett Cannon3adc7b72012-07-09 14:22:12 -04002160/* sys.implementation values */
2161#define NAME "cpython"
2162const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002163#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2164#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002165#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002166const char *_PySys_ImplCacheTag = TAG;
2167#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002168#undef MAJOR
2169#undef MINOR
2170#undef TAG
2171
Barry Warsaw409da152012-06-03 16:18:47 -04002172static PyObject *
2173make_impl_info(PyObject *version_info)
2174{
2175 int res;
2176 PyObject *impl_info, *value, *ns;
2177
2178 impl_info = PyDict_New();
2179 if (impl_info == NULL)
2180 return NULL;
2181
2182 /* populate the dict */
2183
Brett Cannon3adc7b72012-07-09 14:22:12 -04002184 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002185 if (value == NULL)
2186 goto error;
2187 res = PyDict_SetItemString(impl_info, "name", value);
2188 Py_DECREF(value);
2189 if (res < 0)
2190 goto error;
2191
Brett Cannon3adc7b72012-07-09 14:22:12 -04002192 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002193 if (value == NULL)
2194 goto error;
2195 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2196 Py_DECREF(value);
2197 if (res < 0)
2198 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002199
2200 res = PyDict_SetItemString(impl_info, "version", version_info);
2201 if (res < 0)
2202 goto error;
2203
2204 value = PyLong_FromLong(PY_VERSION_HEX);
2205 if (value == NULL)
2206 goto error;
2207 res = PyDict_SetItemString(impl_info, "hexversion", value);
2208 Py_DECREF(value);
2209 if (res < 0)
2210 goto error;
2211
doko@ubuntu.com55532312016-06-14 08:55:19 +02002212#ifdef MULTIARCH
2213 value = PyUnicode_FromString(MULTIARCH);
2214 if (value == NULL)
2215 goto error;
2216 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2217 Py_DECREF(value);
2218 if (res < 0)
2219 goto error;
2220#endif
2221
Barry Warsaw409da152012-06-03 16:18:47 -04002222 /* dict ready */
2223
2224 ns = _PyNamespace_New(impl_info);
2225 Py_DECREF(impl_info);
2226 return ns;
2227
2228error:
2229 Py_CLEAR(impl_info);
2230 return NULL;
2231}
2232
Martin v. Löwis1a214512008-06-11 05:26:20 +00002233static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 PyModuleDef_HEAD_INIT,
2235 "sys",
2236 sys_doc,
2237 -1, /* multiple "initialization" just copies the module dict. */
2238 sys_methods,
2239 NULL,
2240 NULL,
2241 NULL,
2242 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002243};
2244
Eric Snow6b4be192017-05-22 21:36:03 -07002245/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002246#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002247 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002248 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002249 if (v == NULL) { \
2250 goto err_occurred; \
2251 } \
Victor Stinner58049602013-07-22 22:40:00 +02002252 res = PyDict_SetItemString(sysdict, key, v); \
2253 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002254 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002255 } \
2256 } while (0)
2257#define SET_SYS_FROM_STRING(key, value) \
2258 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002259 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002260 if (v == NULL) { \
2261 goto err_occurred; \
2262 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002263 res = PyDict_SetItemString(sysdict, key, v); \
2264 Py_DECREF(v); \
2265 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002266 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002267 } \
2268 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002269
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002270
2271_PyInitError
2272_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002273{
2274 PyObject *m, *sysdict, *version_info;
2275 int res;
2276
Eric Snowd393c1b2017-09-14 12:18:12 -06002277 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002278 if (m == NULL) {
2279 return _Py_INIT_ERR("failed to create a module object");
2280 }
Eric Snow6b4be192017-05-22 21:36:03 -07002281 sysdict = PyModule_GetDict(m);
2282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002283 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002284 Using shell redirection, you can redirect stdin to a directory,
2285 crashing the Python interpreter. Catch this common mistake here
2286 and output a useful error message. Note that under MS Windows,
2287 the shell already prevents that. */
2288#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002290 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002291 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002292 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2294 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 }
2296 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002297#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002298
Nick Coghland6009512014-11-20 21:39:37 +10002299 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002300
Victor Stinner8fea2522013-10-27 17:15:42 +01002301 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2302 PyDict_GetItemString(sysdict, "displayhook"));
2303 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2304 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002305 SET_SYS_FROM_STRING_BORROW(
2306 "__breakpointhook__",
2307 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 SET_SYS_FROM_STRING("version",
2309 PyUnicode_FromString(Py_GetVersion()));
2310 SET_SYS_FROM_STRING("hexversion",
2311 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002312 SET_SYS_FROM_STRING("_git",
2313 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2314 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002315 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002316 SET_SYS_FROM_STRING("api_version",
2317 PyLong_FromLong(PYTHON_API_VERSION));
2318 SET_SYS_FROM_STRING("copyright",
2319 PyUnicode_FromString(Py_GetCopyright()));
2320 SET_SYS_FROM_STRING("platform",
2321 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 SET_SYS_FROM_STRING("maxsize",
2323 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2324 SET_SYS_FROM_STRING("float_info",
2325 PyFloat_GetInfo());
2326 SET_SYS_FROM_STRING("int_info",
2327 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002328 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002329 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002330 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2331 goto type_init_failed;
2332 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002333 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002334 SET_SYS_FROM_STRING("hash_info",
2335 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002337 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002338 SET_SYS_FROM_STRING("builtin_module_names",
2339 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002340#if PY_BIG_ENDIAN
2341 SET_SYS_FROM_STRING("byteorder",
2342 PyUnicode_FromString("big"));
2343#else
2344 SET_SYS_FROM_STRING("byteorder",
2345 PyUnicode_FromString("little"));
2346#endif
Fred Drake099325e2000-08-14 15:47:03 +00002347
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002348#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 SET_SYS_FROM_STRING("dllhandle",
2350 PyLong_FromVoidPtr(PyWin_DLLhModule));
2351 SET_SYS_FROM_STRING("winver",
2352 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002353#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002354#ifdef ABIFLAGS
2355 SET_SYS_FROM_STRING("abiflags",
2356 PyUnicode_FromString(ABIFLAGS));
2357#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002360 if (VersionInfoType.tp_name == NULL) {
2361 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002362 &version_info_desc) < 0) {
2363 goto type_init_failed;
2364 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002365 }
Barry Warsaw409da152012-06-03 16:18:47 -04002366 version_info = make_version_info();
2367 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002368 /* prevent user from creating new instances */
2369 VersionInfoType.tp_init = NULL;
2370 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002371 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2372 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2373 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002374
Barry Warsaw409da152012-06-03 16:18:47 -04002375 /* implementation */
2376 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2377
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002379 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002380 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2381 goto type_init_failed;
2382 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002383 }
Eric Snow6b4be192017-05-22 21:36:03 -07002384 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002386
2387#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* getwindowsversion */
2389 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002390 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002391 &windows_version_desc) < 0) {
2392 goto type_init_failed;
2393 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* prevent user from creating new instances */
2395 WindowsVersionType.tp_init = NULL;
2396 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002397 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002398 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002399 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002400 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002401 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002402#endif
2403
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002405#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 SET_SYS_FROM_STRING("float_repr_style",
2407 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002408#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 SET_SYS_FROM_STRING("float_repr_style",
2410 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002411#endif
2412
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002413 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002414
Yury Selivanoveb636452016-09-08 22:01:51 -07002415 /* initialize asyncgen_hooks */
2416 if (AsyncGenHooksType.tp_name == NULL) {
2417 if (PyStructSequence_InitType2(
2418 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002419 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002420 }
2421 }
2422
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002423 if (PyErr_Occurred()) {
2424 goto err_occurred;
2425 }
2426
2427 *sysmod = m;
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002428
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002429 return _Py_INIT_OK();
2430
2431type_init_failed:
2432 return _Py_INIT_ERR("failed to initialize a type");
2433
2434err_occurred:
2435 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002436}
2437
Eric Snow6b4be192017-05-22 21:36:03 -07002438#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002439
2440/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002441#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2442 do { \
2443 PyObject *v = (value); \
2444 if (v == NULL) \
2445 return -1; \
2446 res = PyDict_SetItemString(sysdict, key, v); \
2447 Py_DECREF(v); \
2448 if (res < 0) { \
2449 return res; \
2450 } \
2451 } while (0)
2452
2453int
Victor Stinner41264f12017-12-15 02:05:29 +01002454_PySys_EndInit(PyObject *sysdict, _PyMainInterpreterConfig *config)
Eric Snow6b4be192017-05-22 21:36:03 -07002455{
2456 int res;
2457
Victor Stinner41264f12017-12-15 02:05:29 +01002458 /* _PyMainInterpreterConfig_Read() must set all these variables */
2459 assert(config->module_search_path != NULL);
2460 assert(config->executable != NULL);
2461 assert(config->prefix != NULL);
2462 assert(config->base_prefix != NULL);
2463 assert(config->exec_prefix != NULL);
2464 assert(config->base_exec_prefix != NULL);
2465
Victor Stinnera5194112018-11-22 16:11:15 +01002466 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
Victor Stinner41264f12017-12-15 02:05:29 +01002467 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2468 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2469 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2470 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2471 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2472
2473 if (config->argv != NULL) {
2474 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2475 }
2476 if (config->warnoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002477 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002478 }
2479 if (config->xoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002480 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002481 }
2482
Eric Snow6b4be192017-05-22 21:36:03 -07002483 /* Set flags to their final values */
2484 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2485 /* prevent user from creating new instances */
2486 FlagsType.tp_init = NULL;
2487 FlagsType.tp_new = NULL;
2488 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2489 if (res < 0) {
2490 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2491 return res;
2492 }
2493 PyErr_Clear();
2494 }
2495
2496 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2497 PyBool_FromLong(Py_DontWriteBytecodeFlag));
Eric Snow6b4be192017-05-22 21:36:03 -07002498
Eric Snowdae02762017-09-14 00:35:58 -07002499 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002500 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002501
Eric Snowdae02762017-09-14 00:35:58 -07002502 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002503 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002504
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002505 /* Transfer any sys.warnoptions and sys._xoptions set directly
2506 * by an embedding application from the linked list to the module. */
2507 if (_PySys_ReadPreInitOptions() != 0)
2508 return -1;
2509
Eric Snow6b4be192017-05-22 21:36:03 -07002510 if (PyErr_Occurred())
2511 return -1;
2512 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002513
2514err_occurred:
2515 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002516}
2517
Victor Stinner41264f12017-12-15 02:05:29 +01002518#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002519#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002520
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002521static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002522makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002524 int i, n;
2525 const wchar_t *p;
2526 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002528 n = 1;
2529 p = path;
2530 while ((p = wcschr(p, delim)) != NULL) {
2531 n++;
2532 p++;
2533 }
2534 v = PyList_New(n);
2535 if (v == NULL)
2536 return NULL;
2537 for (i = 0; ; i++) {
2538 p = wcschr(path, delim);
2539 if (p == NULL)
2540 p = path + wcslen(path); /* End of string */
2541 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2542 if (w == NULL) {
2543 Py_DECREF(v);
2544 return NULL;
2545 }
Miss Islington (bot)8b7d8ac2018-12-08 06:34:49 -08002546 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 if (*p == '\0')
2548 break;
2549 path = p+1;
2550 }
2551 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002552}
2553
2554void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002555PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002557 PyObject *v;
2558 if ((v = makepathobject(path, DELIM)) == NULL)
2559 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002560 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 Py_FatalError("can't assign sys.path");
2562 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002563}
2564
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002565static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002566makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyObject *av;
2569 if (argc <= 0 || argv == NULL) {
2570 /* Ensure at least one (empty) argument is seen */
2571 static wchar_t *empty_argv[1] = {L""};
2572 argv = empty_argv;
2573 argc = 1;
2574 }
2575 av = PyList_New(argc);
2576 if (av != NULL) {
2577 int i;
2578 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002580 if (v == NULL) {
2581 Py_DECREF(av);
2582 av = NULL;
2583 break;
2584 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002585 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 }
2587 }
2588 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002589}
2590
Victor Stinner11a247d2017-12-13 21:05:57 +01002591void
2592PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002593{
2594 PyObject *av = makeargvobject(argc, argv);
2595 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002596 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002597 }
2598 if (PySys_SetObject("argv", av) != 0) {
2599 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002600 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002601 }
2602 Py_DECREF(av);
2603
2604 if (updatepath) {
2605 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2606 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002607 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2608 if (argv0 == NULL) {
2609 Py_FatalError("can't compute path0 from argv");
2610 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002611
Victor Stinner11a247d2017-12-13 21:05:57 +01002612 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2613 if (sys_path != NULL) {
2614 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2615 Py_DECREF(argv0);
2616 Py_FatalError("can't prepend path0 to sys.path");
2617 }
2618 }
2619 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002620 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002621}
Guido van Rossuma890e681998-05-12 14:59:24 +00002622
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002623void
2624PySys_SetArgv(int argc, wchar_t **argv)
2625{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002626 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002627}
2628
Victor Stinner14284c22010-04-23 12:02:30 +00002629/* Reimplementation of PyFile_WriteString() no calling indirectly
2630 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2631
2632static int
Victor Stinner79766632010-08-16 17:36:42 +00002633sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002634{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002635 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002636 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002637
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002638 if (file == NULL)
2639 return -1;
2640
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002641 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 if (writer == NULL)
2643 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002644
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002645 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 if (result == NULL) {
2647 goto error;
2648 } else {
2649 err = 0;
2650 goto finally;
2651 }
Victor Stinner14284c22010-04-23 12:02:30 +00002652
2653error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002654 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002655finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002656 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 Py_XDECREF(result);
2658 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002659}
2660
Victor Stinner79766632010-08-16 17:36:42 +00002661static int
2662sys_pyfile_write(const char *text, PyObject *file)
2663{
2664 PyObject *unicode = NULL;
2665 int err;
2666
2667 if (file == NULL)
2668 return -1;
2669
2670 unicode = PyUnicode_FromString(text);
2671 if (unicode == NULL)
2672 return -1;
2673
2674 err = sys_pyfile_write_unicode(unicode, file);
2675 Py_DECREF(unicode);
2676 return err;
2677}
Guido van Rossuma890e681998-05-12 14:59:24 +00002678
2679/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2680 Adapted from code submitted by Just van Rossum.
2681
2682 PySys_WriteStdout(format, ...)
2683 PySys_WriteStderr(format, ...)
2684
2685 The first function writes to sys.stdout; the second to sys.stderr. When
2686 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002687 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002688
Victor Stinner14284c22010-04-23 12:02:30 +00002689 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002690 signal handlers: they may raise a new exception whereas sys_write()
2691 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002692
Guido van Rossuma890e681998-05-12 14:59:24 +00002693 Both take a printf-style format string as their first argument followed
2694 by a variable length argument list determined by the format string.
2695
2696 *** WARNING ***
2697
2698 The format should limit the total size of the formatted output string to
2699 1000 bytes. In particular, this means that no unrestricted "%s" formats
2700 should occur; these should be limited using "%.<N>s where <N> is a
2701 decimal number calculated so that <N> plus the maximum size of other
2702 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2703 which can print hundreds of digits for very large numbers.
2704
2705 */
2706
2707static void
Victor Stinner09054372013-11-06 22:41:44 +01002708sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 PyObject *file;
2711 PyObject *error_type, *error_value, *error_traceback;
2712 char buffer[1001];
2713 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002715 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002716 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002717 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2718 if (sys_pyfile_write(buffer, file) != 0) {
2719 PyErr_Clear();
2720 fputs(buffer, fp);
2721 }
2722 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2723 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002724 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002725 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 }
2727 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002728}
2729
2730void
Guido van Rossuma890e681998-05-12 14:59:24 +00002731PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002736 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002738}
2739
2740void
Guido van Rossuma890e681998-05-12 14:59:24 +00002741PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002742{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002745 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002746 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002747 va_end(va);
2748}
2749
2750static void
Victor Stinner09054372013-11-06 22:41:44 +01002751sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002752{
2753 PyObject *file, *message;
2754 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002755 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002756
2757 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002758 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002759 message = PyUnicode_FromFormatV(format, va);
2760 if (message != NULL) {
2761 if (sys_pyfile_write_unicode(message, file) != 0) {
2762 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002763 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002764 if (utf8 != NULL)
2765 fputs(utf8, fp);
2766 }
2767 Py_DECREF(message);
2768 }
2769 PyErr_Restore(error_type, error_value, error_traceback);
2770}
2771
2772void
2773PySys_FormatStdout(const char *format, ...)
2774{
2775 va_list va;
2776
2777 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002778 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002779 va_end(va);
2780}
2781
2782void
2783PySys_FormatStderr(const char *format, ...)
2784{
2785 va_list va;
2786
2787 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002788 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002789 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002790}