blob: 75e4f4bf294f22499f63b966109f215487855025 [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:
Miss Islington (bot)6d0254b2019-01-14 03:17:06 -0800174 if (!PyErr_ExceptionMatches(PyExc_ImportError)
175 && !PyErr_ExceptionMatches(PyExc_AttributeError))
176 {
177 PyMem_RawFree(envar);
178 return NULL;
179 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400180 /* If any of the imports went wrong, then warn and ignore. */
181 PyErr_Clear();
182 int status = PyErr_WarnFormat(
183 PyExc_RuntimeWarning, 0,
184 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700185 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400186 if (status < 0) {
187 /* Printing the warning raised an exception. */
188 return NULL;
189 }
190 /* The warning was (probably) issued. */
191 Py_RETURN_NONE;
192}
193
194PyDoc_STRVAR(breakpointhook_doc,
195"breakpointhook(*args, **kws)\n"
196"\n"
197"This hook function is called by built-in breakpoint().\n"
198);
199
Victor Stinner13d49ee2010-12-04 17:24:33 +0000200/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
201 error handler. If sys.stdout has a buffer attribute, use
202 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
203 sys.stdout.write(redecoded).
204
205 Helper function for sys_displayhook(). */
206static int
207sys_displayhook_unencodable(PyObject *outf, PyObject *o)
208{
209 PyObject *stdout_encoding = NULL;
210 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200211 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000212 int ret;
213
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200214 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000215 if (stdout_encoding == NULL)
216 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200217 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000218 if (stdout_encoding_str == NULL)
219 goto error;
220
221 repr_str = PyObject_Repr(o);
222 if (repr_str == NULL)
223 goto error;
224 encoded = PyUnicode_AsEncodedString(repr_str,
225 stdout_encoding_str,
226 "backslashreplace");
227 Py_DECREF(repr_str);
228 if (encoded == NULL)
229 goto error;
230
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200231 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000232 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100233 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000234 Py_DECREF(buffer);
235 Py_DECREF(encoded);
236 if (result == NULL)
237 goto error;
238 Py_DECREF(result);
239 }
240 else {
241 PyErr_Clear();
242 escaped_str = PyUnicode_FromEncodedObject(encoded,
243 stdout_encoding_str,
244 "strict");
245 Py_DECREF(encoded);
246 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
247 Py_DECREF(escaped_str);
248 goto error;
249 }
250 Py_DECREF(escaped_str);
251 }
252 ret = 0;
253 goto finally;
254
255error:
256 ret = -1;
257finally:
258 Py_XDECREF(stdout_encoding);
259 return ret;
260}
261
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000262static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000263sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000264{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000265 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100266 PyObject *builtins;
267 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000268 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000269
Eric Snow3f9eee62017-09-15 16:35:20 -0600270 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000271 if (builtins == NULL) {
272 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
273 return NULL;
274 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600275 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000276
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 /* Print value except if None */
278 /* After printing, also assign to '_' */
279 /* Before, set '_' to None to avoid recursion */
280 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200281 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200283 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100285 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 if (outf == NULL || outf == Py_None) {
287 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
288 return NULL;
289 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000290 if (PyFile_WriteObject(o, outf, 0) != 0) {
291 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
292 /* repr(o) is not encodable to sys.stdout.encoding with
293 * sys.stdout.errors error handler (which is probably 'strict') */
294 PyErr_Clear();
295 err = sys_displayhook_unencodable(outf, o);
296 if (err)
297 return NULL;
298 }
299 else {
300 return NULL;
301 }
302 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100303 if (newline == NULL) {
304 newline = PyUnicode_FromString("\n");
305 if (newline == NULL)
306 return NULL;
307 }
308 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200310 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200312 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000313}
314
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000315PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000316"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000317"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000318"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000319);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000320
321static PyObject *
322sys_excepthook(PyObject* self, PyObject* args)
323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 PyObject *exc, *value, *tb;
325 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
326 return NULL;
327 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200328 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000329}
330
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000331PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000332"excepthook(exctype, value, traceback) -> None\n"
333"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000334"Handle an exception by displaying it with a traceback on sys.stderr.\n"
335);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000336
337static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000338sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000339{
Mark Shannonae3087c2017-10-22 22:41:51 +0100340 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 return Py_BuildValue(
342 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100343 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
344 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
345 err_info->exc_traceback != NULL ?
346 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000347}
348
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000349PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000350"exc_info() -> (type, value, traceback)\n\
351\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000352Return information about the most recent exception caught by an except\n\
353clause in the current stack frame or in an older stack frame."
354);
355
356static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000357sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 PyObject *exit_code = 0;
360 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
361 return NULL;
362 /* Raise SystemExit so callers may catch it or clean up. */
363 PyErr_SetObject(PyExc_SystemExit, exit_code);
364 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365}
366
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000367PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000368"exit([status])\n\
369\n\
370Exit the interpreter by raising SystemExit(status).\n\
371If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300372If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000373If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000374exit status will be one (i.e., failure)."
375);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000376
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000377
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000378static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000379sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000382}
383
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000384PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000385"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000386\n\
387Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000388implementation."
389);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000390
391static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000392sys_getfilesystemencoding(PyObject *self)
393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 if (Py_FileSystemDefaultEncoding)
395 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200396 PyErr_SetString(PyExc_RuntimeError,
397 "filesystem encoding is not initialized");
398 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000399}
400
401PyDoc_STRVAR(getfilesystemencoding_doc,
402"getfilesystemencoding() -> string\n\
403\n\
404Return the encoding used to convert Unicode filenames in\n\
405operating system filenames."
406);
407
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000408static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700409sys_getfilesystemencodeerrors(PyObject *self)
410{
411 if (Py_FileSystemDefaultEncodeErrors)
412 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
413 PyErr_SetString(PyExc_RuntimeError,
414 "filesystem encoding is not initialized");
415 return NULL;
416}
417
418PyDoc_STRVAR(getfilesystemencodeerrors_doc,
419 "getfilesystemencodeerrors() -> string\n\
420\n\
421Return the error mode used to convert Unicode filenames in\n\
422operating system filenames."
423);
424
425static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000426sys_intern(PyObject *self, PyObject *args)
427{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 PyObject *s;
429 if (!PyArg_ParseTuple(args, "U:intern", &s))
430 return NULL;
431 if (PyUnicode_CheckExact(s)) {
432 Py_INCREF(s);
433 PyUnicode_InternInPlace(&s);
434 return s;
435 }
436 else {
437 PyErr_Format(PyExc_TypeError,
438 "can't intern %.400s", s->ob_type->tp_name);
439 return NULL;
440 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000441}
442
443PyDoc_STRVAR(intern_doc,
444"intern(string) -> string\n\
445\n\
446``Intern'' the given string. This enters the string in the (global)\n\
447table of interned strings whose purpose is to speed up dictionary lookups.\n\
448Return the string itself or the previously interned string object with the\n\
449same value.");
450
451
Fred Drake5755ce62001-06-27 19:19:46 +0000452/*
453 * Cached interned string objects used for calling the profile and
454 * trace functions. Initialized by trace_init().
455 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000456static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000457
458static int
459trace_init(void)
460{
Nick Coghlan5a851672017-09-08 10:14:16 +1000461 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200462 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000463 "c_call", "c_exception", "c_return",
464 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200465 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 PyObject *name;
467 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000468 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 if (whatstrings[i] == NULL) {
470 name = PyUnicode_InternFromString(whatnames[i]);
471 if (name == NULL)
472 return -1;
473 whatstrings[i] = name;
474 }
475 }
476 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000477}
478
479
480static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100481call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200485 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000486
Victor Stinner78da82b2016-08-20 01:22:57 +0200487 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200489 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100490
Victor Stinner78da82b2016-08-20 01:22:57 +0200491 stack[0] = (PyObject *)frame;
492 stack[1] = whatstrings[what];
493 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000494
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200496 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000497
Victor Stinner78da82b2016-08-20 01:22:57 +0200498 PyFrame_LocalsToFast(frame, 1);
499 if (result == NULL) {
500 PyTraceBack_Here(frame);
501 }
502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000504}
505
506static int
507profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (arg == NULL)
513 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100514 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 if (result == NULL) {
516 PyEval_SetProfile(NULL, NULL);
517 return -1;
518 }
519 Py_DECREF(result);
520 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000521}
522
523static int
524trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000526{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 PyObject *callback;
528 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000529
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (what == PyTrace_CALL)
531 callback = self;
532 else
533 callback = frame->f_trace;
534 if (callback == NULL)
535 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100536 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (result == NULL) {
538 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200539 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 return -1;
541 }
542 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300543 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 }
545 else {
546 Py_DECREF(result);
547 }
548 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000549}
Fred Draked0838392001-06-16 21:02:31 +0000550
Fred Drake8b4d01d2000-05-09 19:57:01 +0000551static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000552sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000553{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000554 if (trace_init() == -1)
555 return NULL;
556 if (args == Py_None)
557 PyEval_SetTrace(NULL, NULL);
558 else
559 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200560 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000561}
562
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000563PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000564"settrace(function)\n\
565\n\
566Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000567function call. See the debugger chapter in the library manual."
568);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000569
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000570static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000571sys_gettrace(PyObject *self, PyObject *args)
572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 PyThreadState *tstate = PyThreadState_GET();
574 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (temp == NULL)
577 temp = Py_None;
578 Py_INCREF(temp);
579 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000580}
581
582PyDoc_STRVAR(gettrace_doc,
583"gettrace()\n\
584\n\
585Return the global debug tracing function set with sys.settrace.\n\
586See the debugger chapter in the library manual."
587);
588
589static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000590sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 if (trace_init() == -1)
593 return NULL;
594 if (args == Py_None)
595 PyEval_SetProfile(NULL, NULL);
596 else
597 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200598 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000599}
600
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000601PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000602"setprofile(function)\n\
603\n\
604Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000605and return. See the profiler chapter in the library manual."
606);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000607
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000608static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000609sys_getprofile(PyObject *self, PyObject *args)
610{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 PyThreadState *tstate = PyThreadState_GET();
612 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000613
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (temp == NULL)
615 temp = Py_None;
616 Py_INCREF(temp);
617 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000618}
619
620PyDoc_STRVAR(getprofile_doc,
621"getprofile()\n\
622\n\
623Return the profiling function set with sys.setprofile.\n\
624See the profiler chapter in the library manual."
625);
626
627static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000628sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000629{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 if (PyErr_WarnEx(PyExc_DeprecationWarning,
631 "sys.getcheckinterval() and sys.setcheckinterval() "
632 "are deprecated. Use sys.setswitchinterval() "
633 "instead.", 1) < 0)
634 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600635 PyInterpreterState *interp = PyThreadState_GET()->interp;
636 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200638 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000639}
640
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000641PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000642"setcheckinterval(n)\n\
643\n\
644Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000645n instructions. This also affects how often thread switches occur."
646);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000647
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000648static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000649sys_getcheckinterval(PyObject *self, PyObject *args)
650{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 if (PyErr_WarnEx(PyExc_DeprecationWarning,
652 "sys.getcheckinterval() and sys.setcheckinterval() "
653 "are deprecated. Use sys.getswitchinterval() "
654 "instead.", 1) < 0)
655 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 PyInterpreterState *interp = PyThreadState_GET()->interp;
657 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000658}
659
660PyDoc_STRVAR(getcheckinterval_doc,
661"getcheckinterval() -> current check interval; see setcheckinterval()."
662);
663
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000664static PyObject *
665sys_setswitchinterval(PyObject *self, PyObject *args)
666{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000667 double d;
668 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
669 return NULL;
670 if (d <= 0.0) {
671 PyErr_SetString(PyExc_ValueError,
672 "switch interval must be strictly positive");
673 return NULL;
674 }
675 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200676 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000677}
678
679PyDoc_STRVAR(setswitchinterval_doc,
680"setswitchinterval(n)\n\
681\n\
682Set the ideal thread switching delay inside the Python interpreter\n\
683The actual frequency of switching threads can be lower if the\n\
684interpreter executes long sequences of uninterruptible code\n\
685(this is implementation-specific and workload-dependent).\n\
686\n\
687The parameter must represent the desired switching delay in seconds\n\
688A typical value is 0.005 (5 milliseconds)."
689);
690
691static PyObject *
692sys_getswitchinterval(PyObject *self, PyObject *args)
693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000694 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000695}
696
697PyDoc_STRVAR(getswitchinterval_doc,
698"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
699);
700
Tim Peterse5e065b2003-07-06 18:36:54 +0000701static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000702sys_setrecursionlimit(PyObject *self, PyObject *args)
703{
Victor Stinner50856d52015-10-13 00:11:21 +0200704 int new_limit, mark;
705 PyThreadState *tstate;
706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000707 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
708 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200709
710 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200712 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 return NULL;
714 }
Victor Stinner50856d52015-10-13 00:11:21 +0200715
716 /* Issue #25274: When the recursion depth hits the recursion limit in
717 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
718 set to 1 and a RecursionError is raised. The overflowed flag is reset
719 to 0 when the recursion depth goes below the low-water mark: see
720 Py_LeaveRecursiveCall().
721
722 Reject too low new limit if the current recursion depth is higher than
723 the new low-water mark. Otherwise it may not be possible anymore to
724 reset the overflowed flag to 0. */
725 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
726 tstate = PyThreadState_GET();
727 if (tstate->recursion_depth >= mark) {
728 PyErr_Format(PyExc_RecursionError,
729 "cannot set the recursion limit to %i at "
730 "the recursion depth %i: the limit is too low",
731 new_limit, tstate->recursion_depth);
732 return NULL;
733 }
734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200736 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000737}
738
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800739/*[clinic input]
740sys.set_coroutine_origin_tracking_depth
741
742 depth: int
743
744Enable or disable origin tracking for coroutine objects in this thread.
745
746Coroutine objects will track 'depth' frames of traceback information about
747where they came from, available in their cr_origin attribute. Set depth of 0
748to disable.
749[clinic start generated code]*/
750
751static PyObject *
752sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
753/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
754{
755 if (depth < 0) {
756 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
757 return NULL;
758 }
759 _PyEval_SetCoroutineOriginTrackingDepth(depth);
760 Py_RETURN_NONE;
761}
762
763/*[clinic input]
764sys.get_coroutine_origin_tracking_depth -> int
765
766Check status of origin tracking for coroutine objects in this thread.
767[clinic start generated code]*/
768
769static int
770sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
771/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
772{
773 return _PyEval_GetCoroutineOriginTrackingDepth();
774}
775
Yury Selivanov75445082015-05-11 22:57:16 -0400776static PyObject *
777sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
778{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800779 if (PyErr_WarnEx(PyExc_DeprecationWarning,
780 "set_coroutine_wrapper is deprecated", 1) < 0) {
781 return NULL;
782 }
783
Yury Selivanov75445082015-05-11 22:57:16 -0400784 if (wrapper != Py_None) {
785 if (!PyCallable_Check(wrapper)) {
786 PyErr_Format(PyExc_TypeError,
787 "callable expected, got %.50s",
788 Py_TYPE(wrapper)->tp_name);
789 return NULL;
790 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400791 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400792 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400793 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400794 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400795 }
Yury Selivanov75445082015-05-11 22:57:16 -0400796 Py_RETURN_NONE;
797}
798
799PyDoc_STRVAR(set_coroutine_wrapper_doc,
800"set_coroutine_wrapper(wrapper)\n\
801\n\
802Set a wrapper for coroutine objects."
803);
804
805static PyObject *
806sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
807{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800808 if (PyErr_WarnEx(PyExc_DeprecationWarning,
809 "get_coroutine_wrapper is deprecated", 1) < 0) {
810 return NULL;
811 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400812 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400813 if (wrapper == NULL) {
814 wrapper = Py_None;
815 }
816 Py_INCREF(wrapper);
817 return wrapper;
818}
819
820PyDoc_STRVAR(get_coroutine_wrapper_doc,
821"get_coroutine_wrapper()\n\
822\n\
823Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
824);
825
826
Yury Selivanoveb636452016-09-08 22:01:51 -0700827static PyTypeObject AsyncGenHooksType;
828
829PyDoc_STRVAR(asyncgen_hooks_doc,
830"asyncgen_hooks\n\
831\n\
832A struct sequence providing information about asynhronous\n\
833generators hooks. The attributes are read only.");
834
835static PyStructSequence_Field asyncgen_hooks_fields[] = {
836 {"firstiter", "Hook to intercept first iteration"},
837 {"finalizer", "Hook to intercept finalization"},
838 {0}
839};
840
841static PyStructSequence_Desc asyncgen_hooks_desc = {
842 "asyncgen_hooks", /* name */
843 asyncgen_hooks_doc, /* doc */
844 asyncgen_hooks_fields , /* fields */
845 2
846};
847
848
849static PyObject *
850sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
851{
852 static char *keywords[] = {"firstiter", "finalizer", NULL};
853 PyObject *firstiter = NULL;
854 PyObject *finalizer = NULL;
855
856 if (!PyArg_ParseTupleAndKeywords(
857 args, kw, "|OO", keywords,
858 &firstiter, &finalizer)) {
859 return NULL;
860 }
861
862 if (finalizer && finalizer != Py_None) {
863 if (!PyCallable_Check(finalizer)) {
864 PyErr_Format(PyExc_TypeError,
865 "callable finalizer expected, got %.50s",
866 Py_TYPE(finalizer)->tp_name);
867 return NULL;
868 }
869 _PyEval_SetAsyncGenFinalizer(finalizer);
870 }
871 else if (finalizer == Py_None) {
872 _PyEval_SetAsyncGenFinalizer(NULL);
873 }
874
875 if (firstiter && firstiter != Py_None) {
876 if (!PyCallable_Check(firstiter)) {
877 PyErr_Format(PyExc_TypeError,
878 "callable firstiter expected, got %.50s",
879 Py_TYPE(firstiter)->tp_name);
880 return NULL;
881 }
882 _PyEval_SetAsyncGenFirstiter(firstiter);
883 }
884 else if (firstiter == Py_None) {
885 _PyEval_SetAsyncGenFirstiter(NULL);
886 }
887
888 Py_RETURN_NONE;
889}
890
891PyDoc_STRVAR(set_asyncgen_hooks_doc,
892"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
893\n\
894Set a finalizer for async generators objects."
895);
896
897static PyObject *
898sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
899{
900 PyObject *res;
901 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
902 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
903
904 res = PyStructSequence_New(&AsyncGenHooksType);
905 if (res == NULL) {
906 return NULL;
907 }
908
909 if (firstiter == NULL) {
910 firstiter = Py_None;
911 }
912
913 if (finalizer == NULL) {
914 finalizer = Py_None;
915 }
916
917 Py_INCREF(firstiter);
918 PyStructSequence_SET_ITEM(res, 0, firstiter);
919
920 Py_INCREF(finalizer);
921 PyStructSequence_SET_ITEM(res, 1, finalizer);
922
923 return res;
924}
925
926PyDoc_STRVAR(get_asyncgen_hooks_doc,
927"get_asyncgen_hooks()\n\
928\n\
929Return a namedtuple of installed asynchronous generators hooks \
930(firstiter, finalizer)."
931);
932
933
Mark Dickinsondc787d22010-05-23 13:33:13 +0000934static PyTypeObject Hash_InfoType;
935
936PyDoc_STRVAR(hash_info_doc,
937"hash_info\n\
938\n\
939A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100940hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000941
942static PyStructSequence_Field hash_info_fields[] = {
943 {"width", "width of the type used for hashing, in bits"},
944 {"modulus", "prime number giving the modulus on which the hash "
945 "function is based"},
946 {"inf", "value to be used for hash of a positive infinity"},
947 {"nan", "value to be used for hash of a nan"},
948 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100949 {"algorithm", "name of the algorithm for hashing of str, bytes and "
950 "memoryviews"},
951 {"hash_bits", "internal output size of hash algorithm"},
952 {"seed_bits", "seed size of hash algorithm"},
953 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000954 {NULL, NULL}
955};
956
957static PyStructSequence_Desc hash_info_desc = {
958 "sys.hash_info",
959 hash_info_doc,
960 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100961 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000962};
963
Matthias Klosed885e952010-07-06 10:53:30 +0000964static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000965get_hash_info(void)
966{
967 PyObject *hash_info;
968 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100969 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000970 hash_info = PyStructSequence_New(&Hash_InfoType);
971 if (hash_info == NULL)
972 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100973 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000974 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000975 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000976 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000977 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000978 PyStructSequence_SET_ITEM(hash_info, field++,
979 PyLong_FromLong(_PyHASH_INF));
980 PyStructSequence_SET_ITEM(hash_info, field++,
981 PyLong_FromLong(_PyHASH_NAN));
982 PyStructSequence_SET_ITEM(hash_info, field++,
983 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100984 PyStructSequence_SET_ITEM(hash_info, field++,
985 PyUnicode_FromString(hashfunc->name));
986 PyStructSequence_SET_ITEM(hash_info, field++,
987 PyLong_FromLong(hashfunc->hash_bits));
988 PyStructSequence_SET_ITEM(hash_info, field++,
989 PyLong_FromLong(hashfunc->seed_bits));
990 PyStructSequence_SET_ITEM(hash_info, field++,
991 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000992 if (PyErr_Occurred()) {
993 Py_CLEAR(hash_info);
994 return NULL;
995 }
996 return hash_info;
997}
998
999
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001000PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001001"setrecursionlimit(n)\n\
1002\n\
1003Set the maximum depth of the Python interpreter stack to n. This\n\
1004limit prevents infinite recursion from causing an overflow of the C\n\
1005stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001006dependent."
1007);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001008
1009static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001010sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001012 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001013}
1014
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001015PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001016"getrecursionlimit()\n\
1017\n\
1018Return the current value of the recursion limit, the maximum depth\n\
1019of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001020recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001021);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001022
Mark Hammond8696ebc2002-10-08 02:44:31 +00001023#ifdef MS_WINDOWS
1024PyDoc_STRVAR(getwindowsversion_doc,
1025"getwindowsversion()\n\
1026\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001027Return information about the running version of Windows as a named tuple.\n\
1028The members are named: major, minor, build, platform, service_pack,\n\
1029service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001030backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001031All elements are numbers, except service_pack and platform_type which are\n\
1032strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1033Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1034server. Platform_version is a 3-tuple containing a version number that is\n\
1035intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001036);
1037
Eric Smithf7bb5782010-01-27 00:44:57 +00001038static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1039
1040static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 {"major", "Major version number"},
1042 {"minor", "Minor version number"},
1043 {"build", "Build number"},
1044 {"platform", "Operating system platform"},
1045 {"service_pack", "Latest Service Pack installed on the system"},
1046 {"service_pack_major", "Service Pack major version number"},
1047 {"service_pack_minor", "Service Pack minor version number"},
1048 {"suite_mask", "Bit mask identifying available product suites"},
1049 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001050 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001052};
1053
1054static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 "sys.getwindowsversion", /* name */
1056 getwindowsversion_doc, /* doc */
1057 windows_version_fields, /* fields */
1058 5 /* For backward compatibility,
1059 only the first 5 items are accessible
1060 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001061};
1062
Steve Dower3e96f322015-03-02 08:01:10 -08001063/* Disable deprecation warnings about GetVersionEx as the result is
1064 being passed straight through to the caller, who is responsible for
1065 using it correctly. */
1066#pragma warning(push)
1067#pragma warning(disable:4996)
1068
Mark Hammond8696ebc2002-10-08 02:44:31 +00001069static PyObject *
1070sys_getwindowsversion(PyObject *self)
1071{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001072 PyObject *version;
1073 int pos = 0;
1074 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001075 DWORD realMajor, realMinor, realBuild;
1076 HANDLE hKernel32;
1077 wchar_t kernel32_path[MAX_PATH];
1078 LPVOID verblock;
1079 DWORD verblock_size;
1080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 ver.dwOSVersionInfoSize = sizeof(ver);
1082 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1083 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001084
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001085 version = PyStructSequence_New(&WindowsVersionType);
1086 if (version == NULL)
1087 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1090 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1091 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1092 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1093 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1094 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1095 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1096 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1097 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001098
Steve Dower74f4af72016-09-17 17:27:48 -07001099 realMajor = ver.dwMajorVersion;
1100 realMinor = ver.dwMinorVersion;
1101 realBuild = ver.dwBuildNumber;
1102
1103 // GetVersion will lie if we are running in a compatibility mode.
1104 // We need to read the version info from a system file resource
1105 // to accurately identify the OS version. If we fail for any reason,
1106 // just return whatever GetVersion said.
1107 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1108 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1109 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1110 (verblock = PyMem_RawMalloc(verblock_size))) {
1111 VS_FIXEDFILEINFO *ffi;
1112 UINT ffi_len;
1113
1114 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1115 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1116 realMajor = HIWORD(ffi->dwProductVersionMS);
1117 realMinor = LOWORD(ffi->dwProductVersionMS);
1118 realBuild = HIWORD(ffi->dwProductVersionLS);
1119 }
1120 PyMem_RawFree(verblock);
1121 }
Segev Finer48fb7662017-06-04 20:52:27 +03001122 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1123 realMajor,
1124 realMinor,
1125 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001126 ));
1127
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001128 if (PyErr_Occurred()) {
1129 Py_DECREF(version);
1130 return NULL;
1131 }
Steve Dower74f4af72016-09-17 17:27:48 -07001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001134}
1135
Steve Dower3e96f322015-03-02 08:01:10 -08001136#pragma warning(pop)
1137
Steve Dowercc16be82016-09-08 10:35:16 -07001138PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1139"_enablelegacywindowsfsencoding()\n\
1140\n\
1141Changes the default filesystem encoding to mbcs:replace for consistency\n\
1142with earlier versions of Python. See PEP 529 for more information.\n\
1143\n\
1144This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1145environment variable before launching Python."
1146);
1147
1148static PyObject *
1149sys_enablelegacywindowsfsencoding(PyObject *self)
1150{
1151 Py_FileSystemDefaultEncoding = "mbcs";
1152 Py_FileSystemDefaultEncodeErrors = "replace";
1153 Py_RETURN_NONE;
1154}
1155
Mark Hammond8696ebc2002-10-08 02:44:31 +00001156#endif /* MS_WINDOWS */
1157
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001158#ifdef HAVE_DLOPEN
1159static PyObject *
1160sys_setdlopenflags(PyObject *self, PyObject *args)
1161{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001162 int new_val;
1163 PyThreadState *tstate = PyThreadState_GET();
1164 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1165 return NULL;
1166 if (!tstate)
1167 return NULL;
1168 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001169 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001170}
1171
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001172PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001173"setdlopenflags(n) -> None\n\
1174\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001175Set the flags used by the interpreter for dlopen calls, such as when the\n\
1176interpreter loads extension modules. Among other things, this will enable\n\
1177a lazy resolving of symbols when importing a module, if called as\n\
1178sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001179sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001180can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001181
1182static PyObject *
1183sys_getdlopenflags(PyObject *self, PyObject *args)
1184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 PyThreadState *tstate = PyThreadState_GET();
1186 if (!tstate)
1187 return NULL;
1188 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001189}
1190
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001191PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001192"getdlopenflags() -> int\n\
1193\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001194Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001195The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001196
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001197#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001198
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001199#ifdef USE_MALLOPT
1200/* Link with -lmalloc (or -lmpc) on an SGI */
1201#include <malloc.h>
1202
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001203static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001204sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 int flag;
1207 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1208 return NULL;
1209 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001210 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001211}
1212#endif /* USE_MALLOPT */
1213
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001214size_t
1215_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001218 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001219 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001220
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 /* Make sure the type is initialized. float gets initialized late */
1222 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001223 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001224
Benjamin Petersonce798522012-01-22 11:24:29 -05001225 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 if (method == NULL) {
1227 if (!PyErr_Occurred())
1228 PyErr_Format(PyExc_TypeError,
1229 "Type %.100s doesn't define __sizeof__",
1230 Py_TYPE(o)->tp_name);
1231 }
1232 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001233 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 Py_DECREF(method);
1235 }
1236
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001237 if (res == NULL)
1238 return (size_t)-1;
1239
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001240 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001241 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001242 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001243 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001245 if (size < 0) {
1246 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1247 return (size_t)-1;
1248 }
1249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001251 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001252 return ((size_t)size) + sizeof(PyGC_Head);
1253 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001254}
1255
1256static PyObject *
1257sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1258{
1259 static char *kwlist[] = {"object", "default", 0};
1260 size_t size;
1261 PyObject *o, *dflt = NULL;
1262
1263 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1264 kwlist, &o, &dflt))
1265 return NULL;
1266
1267 size = _PySys_GetSizeOf(o);
1268
1269 if (size == (size_t)-1 && PyErr_Occurred()) {
1270 /* Has a default value been given */
1271 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1272 PyErr_Clear();
1273 Py_INCREF(dflt);
1274 return dflt;
1275 }
1276 else
1277 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001279
1280 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001281}
1282
1283PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001284"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001285\n\
1286Return the size of object in bytes.");
1287
1288static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001289sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001290{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001292}
1293
Tim Peters4be93d02002-07-07 19:59:50 +00001294#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001295static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001296sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001299}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001300#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001301
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001302PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001303"getrefcount(object) -> integer\n\
1304\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001305Return the reference count of object. The count returned is generally\n\
1306one higher than you might expect, because it includes the (temporary)\n\
1307reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001308);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001309
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001310static PyObject *
1311sys_getallocatedblocks(PyObject *self)
1312{
1313 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1314}
1315
1316PyDoc_STRVAR(getallocatedblocks_doc,
1317"getallocatedblocks() -> integer\n\
1318\n\
1319Return the number of memory blocks currently allocated, regardless of their\n\
1320size."
1321);
1322
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001323#ifdef COUNT_ALLOCS
1324static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001325sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001330}
1331#endif
1332
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001333PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001334"_getframe([depth]) -> frameobject\n\
1335\n\
1336Return a frame object from the call stack. If optional integer depth is\n\
1337given, return the frame object that many calls below the top of the stack.\n\
1338If that is deeper than the call stack, ValueError is raised. The default\n\
1339for depth is zero, returning the frame at the top of the call stack.\n\
1340\n\
1341This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001342purposes only."
1343);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001344
1345static PyObject *
1346sys_getframe(PyObject *self, PyObject *args)
1347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001348 PyFrameObject *f = PyThreadState_GET()->frame;
1349 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1352 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001353
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 while (depth > 0 && f != NULL) {
1355 f = f->f_back;
1356 --depth;
1357 }
1358 if (f == NULL) {
1359 PyErr_SetString(PyExc_ValueError,
1360 "call stack is not deep enough");
1361 return NULL;
1362 }
1363 Py_INCREF(f);
1364 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001365}
1366
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001367PyDoc_STRVAR(current_frames_doc,
1368"_current_frames() -> dictionary\n\
1369\n\
1370Return a dictionary mapping each current thread T's thread id to T's\n\
1371current stack frame.\n\
1372\n\
1373This function should be used for specialized purposes only."
1374);
1375
1376static PyObject *
1377sys_current_frames(PyObject *self, PyObject *noargs)
1378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001380}
1381
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001382PyDoc_STRVAR(call_tracing_doc,
1383"call_tracing(func, args) -> object\n\
1384\n\
1385Call func(*args), while tracing is enabled. The tracing state is\n\
1386saved, and restored afterwards. This is intended to be called from\n\
1387a debugger from a checkpoint, to recursively debug some other code."
1388);
1389
1390static PyObject *
1391sys_call_tracing(PyObject *self, PyObject *args)
1392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 PyObject *func, *funcargs;
1394 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1395 return NULL;
1396 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001397}
1398
Jeremy Hylton985eba52003-02-05 23:13:00 +00001399PyDoc_STRVAR(callstats_doc,
1400"callstats() -> tuple of integers\n\
1401\n\
1402Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1403when Python was built. Otherwise, return None.\n\
1404\n\
1405When enabled, this function returns detailed, implementation-specific\n\
1406details about the number of function calls executed. The return value is\n\
1407a 11-tuple where the entries in the tuple are counts of:\n\
14080. all function calls\n\
14091. calls to PyFunction_Type objects\n\
14102. PyFunction calls that do not create an argument tuple\n\
14113. PyFunction calls that do not create an argument tuple\n\
1412 and bypass PyEval_EvalCodeEx()\n\
14134. PyMethod calls\n\
14145. PyMethod calls on bound methods\n\
14156. PyType calls\n\
14167. PyCFunction calls\n\
14178. generator calls\n\
14189. All other calls\n\
141910. Number of stack pops performed by call_function()"
1420);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001421
Victor Stinner048afd92016-11-28 11:59:04 +01001422static PyObject *
1423sys_callstats(PyObject *self)
1424{
1425 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1426 "sys.callstats() has been deprecated in Python 3.7 "
1427 "and will be removed in the future", 1) < 0) {
1428 return NULL;
1429 }
1430
1431 Py_RETURN_NONE;
1432}
1433
1434
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001435#ifdef __cplusplus
1436extern "C" {
1437#endif
1438
David Malcolm49526f42012-06-22 14:55:41 -04001439static PyObject *
1440sys_debugmallocstats(PyObject *self, PyObject *args)
1441{
1442#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001443 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001444 fputc('\n', stderr);
1445 }
David Malcolm49526f42012-06-22 14:55:41 -04001446#endif
1447 _PyObject_DebugTypeStats(stderr);
1448
1449 Py_RETURN_NONE;
1450}
1451PyDoc_STRVAR(debugmallocstats_doc,
1452"_debugmallocstats()\n\
1453\n\
1454Print summary info to stderr about the state of\n\
1455pymalloc's structures.\n\
1456\n\
1457In Py_DEBUG mode, also perform some expensive internal consistency\n\
1458checks.\n\
1459");
1460
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001461#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001462/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001463extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001464#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001465
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001466#ifdef DYNAMIC_EXECUTION_PROFILE
1467/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001468extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001469#endif
1470
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001471#ifdef __cplusplus
1472}
1473#endif
1474
Christian Heimes15ebc882008-02-04 18:48:49 +00001475static PyObject *
1476sys_clear_type_cache(PyObject* self, PyObject* args)
1477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 PyType_ClearCache();
1479 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001480}
1481
1482PyDoc_STRVAR(sys_clear_type_cache__doc__,
1483"_clear_type_cache() -> None\n\
1484Clear the internal type lookup cache.");
1485
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001486static PyObject *
1487sys_is_finalizing(PyObject* self, PyObject* args)
1488{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001489 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001490}
1491
1492PyDoc_STRVAR(is_finalizing_doc,
1493"is_finalizing()\n\
1494Return True if Python is exiting.");
1495
Christian Heimes15ebc882008-02-04 18:48:49 +00001496
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001497#ifdef ANDROID_API_LEVEL
1498PyDoc_STRVAR(getandroidapilevel_doc,
1499"getandroidapilevel()\n\
1500\n\
1501Return the build time API version of Android as an integer.");
1502
1503static PyObject *
1504sys_getandroidapilevel(PyObject *self)
1505{
1506 return PyLong_FromLong(ANDROID_API_LEVEL);
1507}
1508#endif /* ANDROID_API_LEVEL */
1509
1510
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001511static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001512 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001513 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1514 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Victor Stinner048afd92016-11-28 11:59:04 +01001515 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 callstats_doc},
1517 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1518 sys_clear_type_cache__doc__},
1519 {"_current_frames", sys_current_frames, METH_NOARGS,
1520 current_frames_doc},
1521 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1522 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1523 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1524 {"exit", sys_exit, METH_VARARGS, exit_doc},
1525 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1526 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001527#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1529 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001530#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001531 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1532 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001533#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001535#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001536#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001538#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1540 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001541 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1542 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001543#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001545#endif
1546#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001548#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1550 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1551 getrecursionlimit_doc},
1552 {"getsizeof", (PyCFunction)sys_getsizeof,
1553 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1554 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001555#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1557 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001558 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1559 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001560#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001562 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001563#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001565#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1567 setcheckinterval_doc},
1568 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1569 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1571 setswitchinterval_doc},
1572 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1573 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001574#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1576 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001577#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1579 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1580 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1581 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 {"settrace", sys_settrace, METH_O, settrace_doc},
1583 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1584 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001585 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001586 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001587 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1588 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001589 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1590 set_coroutine_wrapper_doc},
1591 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1592 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001593 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001594 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1595 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1596 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001597#ifdef ANDROID_API_LEVEL
1598 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1599 getandroidapilevel_doc},
1600#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001602};
1603
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001604static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001605list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 PyObject *list = PyList_New(0);
1608 int i;
1609 if (list == NULL)
1610 return NULL;
1611 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1612 PyObject *name = PyUnicode_FromString(
1613 PyImport_Inittab[i].name);
1614 if (name == NULL)
1615 break;
1616 PyList_Append(list, name);
1617 Py_DECREF(name);
1618 }
1619 if (PyList_Sort(list) != 0) {
1620 Py_DECREF(list);
1621 list = NULL;
1622 }
1623 if (list) {
1624 PyObject *v = PyList_AsTuple(list);
1625 Py_DECREF(list);
1626 list = v;
1627 }
1628 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001629}
1630
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001631/* Pre-initialization support for sys.warnoptions and sys._xoptions
1632 *
1633 * Modern internal code paths:
1634 * These APIs get called after _Py_InitializeCore and get to use the
1635 * regular CPython list, dict, and unicode APIs.
1636 *
1637 * Legacy embedding code paths:
1638 * The multi-phase initialization API isn't public yet, so embedding
1639 * apps still need to be able configure sys.warnoptions and sys._xoptions
1640 * before they call Py_Initialize. To support this, we stash copies of
1641 * the supplied wchar * sequences in linked lists, and then migrate the
1642 * contents of those lists to the sys module in _PyInitializeCore.
1643 *
1644 */
1645
1646struct _preinit_entry {
1647 wchar_t *value;
1648 struct _preinit_entry *next;
1649};
1650
1651typedef struct _preinit_entry *_Py_PreInitEntry;
1652
1653static _Py_PreInitEntry _preinit_warnoptions = NULL;
1654static _Py_PreInitEntry _preinit_xoptions = NULL;
1655
1656static _Py_PreInitEntry
1657_alloc_preinit_entry(const wchar_t *value)
1658{
1659 /* To get this to work, we have to initialize the runtime implicitly */
1660 _PyRuntime_Initialize();
1661
1662 /* Force default allocator, so we can ensure that it also gets used to
1663 * destroy the linked list in _clear_preinit_entries.
1664 */
1665 PyMemAllocatorEx old_alloc;
1666 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1667
1668 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1669 if (node != NULL) {
1670 node->value = _PyMem_RawWcsdup(value);
1671 if (node->value == NULL) {
1672 PyMem_RawFree(node);
1673 node = NULL;
1674 };
1675 };
1676
1677 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1678 return node;
1679};
1680
1681static int
1682_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1683{
1684 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1685 if (new_entry == NULL) {
1686 return -1;
1687 }
1688 /* We maintain the linked list in this order so it's easy to play back
1689 * the add commands in the same order later on in _Py_InitializeCore
1690 */
1691 _Py_PreInitEntry last_entry = *optionlist;
1692 if (last_entry == NULL) {
1693 *optionlist = new_entry;
1694 } else {
1695 while (last_entry->next != NULL) {
1696 last_entry = last_entry->next;
1697 }
1698 last_entry->next = new_entry;
1699 }
1700 return 0;
1701};
1702
1703static void
1704_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1705{
1706 _Py_PreInitEntry current = *optionlist;
1707 *optionlist = NULL;
1708 /* Deallocate the nodes and their contents using the default allocator */
1709 PyMemAllocatorEx old_alloc;
1710 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1711 while (current != NULL) {
1712 _Py_PreInitEntry next = current->next;
1713 PyMem_RawFree(current->value);
1714 PyMem_RawFree(current);
1715 current = next;
1716 }
1717 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1718};
1719
1720static void
1721_clear_all_preinit_options(void)
1722{
1723 _clear_preinit_entries(&_preinit_warnoptions);
1724 _clear_preinit_entries(&_preinit_xoptions);
1725}
1726
1727static int
1728_PySys_ReadPreInitOptions(void)
1729{
1730 /* Rerun the add commands with the actual sys module available */
1731 PyThreadState *tstate = PyThreadState_GET();
1732 if (tstate == NULL) {
1733 /* Still don't have a thread state, so something is wrong! */
1734 return -1;
1735 }
1736 _Py_PreInitEntry entry = _preinit_warnoptions;
1737 while (entry != NULL) {
1738 PySys_AddWarnOption(entry->value);
1739 entry = entry->next;
1740 }
1741 entry = _preinit_xoptions;
1742 while (entry != NULL) {
1743 PySys_AddXOption(entry->value);
1744 entry = entry->next;
1745 }
1746
1747 _clear_all_preinit_options();
1748 return 0;
1749};
1750
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001751static PyObject *
1752get_warnoptions(void)
1753{
Eric Snowdae02762017-09-14 00:35:58 -07001754 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001755 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001756 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1757 * interpreter config. When that happens, we need to properly set
1758 * the `warnoptions` reference in the main interpreter config as well.
1759 *
1760 * For Python 3.7, we shouldn't be able to get here due to the
1761 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1762 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1763 * call optional for embedding applications, thus making this
1764 * reachable again.
1765 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001766 warnoptions = PyList_New(0);
1767 if (warnoptions == NULL)
1768 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001769 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1770 Py_DECREF(warnoptions);
1771 return NULL;
1772 }
1773 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001774 }
1775 return warnoptions;
1776}
Guido van Rossum23fff912000-12-15 22:02:05 +00001777
1778void
1779PySys_ResetWarnOptions(void)
1780{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001781 PyThreadState *tstate = PyThreadState_GET();
1782 if (tstate == NULL) {
1783 _clear_preinit_entries(&_preinit_warnoptions);
1784 return;
1785 }
1786
Eric Snowdae02762017-09-14 00:35:58 -07001787 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 if (warnoptions == NULL || !PyList_Check(warnoptions))
1789 return;
1790 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001791}
1792
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001793int
1794_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001795{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001796 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001797 if (warnoptions == NULL) {
1798 return -1;
1799 }
1800 if (PyList_Append(warnoptions, option)) {
1801 return -1;
1802 }
1803 return 0;
1804}
1805
1806void
1807PySys_AddWarnOptionUnicode(PyObject *option)
1808{
1809 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001810}
1811
1812void
1813PySys_AddWarnOption(const wchar_t *s)
1814{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001815 PyThreadState *tstate = PyThreadState_GET();
1816 if (tstate == NULL) {
1817 _append_preinit_entry(&_preinit_warnoptions, s);
1818 return;
1819 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001820 PyObject *unicode;
1821 unicode = PyUnicode_FromWideChar(s, -1);
1822 if (unicode == NULL)
1823 return;
1824 PySys_AddWarnOptionUnicode(unicode);
1825 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001826}
1827
Christian Heimes33fe8092008-04-13 13:53:33 +00001828int
1829PySys_HasWarnOptions(void)
1830{
Eric Snowdae02762017-09-14 00:35:58 -07001831 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Miss Islington (bot)ea773eb2018-12-10 04:37:09 -08001832 return (warnoptions != NULL && PyList_Check(warnoptions)
1833 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001834}
1835
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001836static PyObject *
1837get_xoptions(void)
1838{
Eric Snowdae02762017-09-14 00:35:58 -07001839 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001840 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001841 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1842 * interpreter config. When that happens, we need to properly set
1843 * the `xoptions` reference in the main interpreter config as well.
1844 *
1845 * For Python 3.7, we shouldn't be able to get here due to the
1846 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1847 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1848 * call optional for embedding applications, thus making this
1849 * reachable again.
1850 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001851 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001852 if (xoptions == NULL)
1853 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001854 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1855 Py_DECREF(xoptions);
1856 return NULL;
1857 }
1858 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001859 }
1860 return xoptions;
1861}
1862
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001863int
1864_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001865{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001866 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001867
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001868 PyObject *opts = get_xoptions();
1869 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001870 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001871 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001872
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001873 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001874 if (!name_end) {
1875 name = PyUnicode_FromWideChar(s, -1);
1876 value = Py_True;
1877 Py_INCREF(value);
1878 }
1879 else {
1880 name = PyUnicode_FromWideChar(s, name_end - s);
1881 value = PyUnicode_FromWideChar(name_end + 1, -1);
1882 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001883 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001884 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001885 }
1886 if (PyDict_SetItem(opts, name, value) < 0) {
1887 goto error;
1888 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001889 Py_DECREF(name);
1890 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001891 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001892
1893error:
1894 Py_XDECREF(name);
1895 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896 return -1;
1897}
1898
1899void
1900PySys_AddXOption(const wchar_t *s)
1901{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001902 PyThreadState *tstate = PyThreadState_GET();
1903 if (tstate == NULL) {
1904 _append_preinit_entry(&_preinit_xoptions, s);
1905 return;
1906 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001907 if (_PySys_AddXOptionWithError(s) < 0) {
1908 /* No return value, therefore clear error state if possible */
1909 if (_PyThreadState_UncheckedGet()) {
1910 PyErr_Clear();
1911 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001912 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001913}
1914
1915PyObject *
1916PySys_GetXOptions(void)
1917{
1918 return get_xoptions();
1919}
1920
Guido van Rossum40552d01998-08-06 03:34:39 +00001921/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1922 Two literals concatenated works just fine. If you have a K&R compiler
1923 or other abomination that however *does* understand longer strings,
1924 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001925PyDoc_VAR(sys_doc) =
1926PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001927"This module provides access to some objects used or maintained by the\n\
1928interpreter and to functions that interact strongly with the interpreter.\n\
1929\n\
1930Dynamic objects:\n\
1931\n\
1932argv -- command line arguments; argv[0] is the script pathname if known\n\
1933path -- module search path; path[0] is the script directory, else ''\n\
1934modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001935\n\
1936displayhook -- called to show results in an interactive session\n\
1937excepthook -- called to handle any uncaught exception other than SystemExit\n\
1938 To customize printing in an interactive session or to install a custom\n\
1939 top-level exception handler, assign other functions to replace these.\n\
1940\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001941stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001942stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001943stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001944 By assigning other file objects (or objects that behave like files)\n\
1945 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001946\n\
1947last_type -- type of last uncaught exception\n\
1948last_value -- value of last uncaught exception\n\
1949last_traceback -- traceback of last uncaught exception\n\
1950 These three are only available in an interactive session after a\n\
1951 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001952"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001953)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001954/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001955PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001956"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001957Static objects:\n\
1958\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001959builtin_module_names -- tuple of module names built into this interpreter\n\
1960copyright -- copyright notice pertaining to this interpreter\n\
1961exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001962executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001963float_info -- a struct sequence with information about the float implementation.\n\
1964float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001965hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001966hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001967implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001968int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001969maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001970maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001971platform -- platform identifier\n\
1972prefix -- prefix used to find the Python library\n\
1973thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001974version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001975version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001976"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001977)
Steve Dowercc16be82016-09-08 10:35:16 -07001978#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001979/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001980PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001981"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001982winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001983"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001984)
Steve Dowercc16be82016-09-08 10:35:16 -07001985#endif /* MS_COREDLL */
1986#ifdef MS_WINDOWS
1987/* concatenating string here */
1988PyDoc_STR(
1989"_enablelegacywindowsfsencoding -- [Windows only] \n\
1990"
1991)
1992#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001993PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001994"__stdin__ -- the original stdin; don't touch!\n\
1995__stdout__ -- the original stdout; don't touch!\n\
1996__stderr__ -- the original stderr; don't touch!\n\
1997__displayhook__ -- the original displayhook; don't touch!\n\
1998__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001999\n\
2000Functions:\n\
2001\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002002displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002003excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002004exc_info() -- return thread-safe information about the current exception\n\
2005exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002006getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002007getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002008getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002009getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002010getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002011gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002012setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002013setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002014setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002015setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002016settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002017"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002018)
Fred Drakeccede592000-08-14 20:59:57 +00002019/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002020
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002021
2022PyDoc_STRVAR(flags__doc__,
2023"sys.flags\n\
2024\n\
2025Flags provided through command line arguments or environment vars.");
2026
2027static PyTypeObject FlagsType;
2028
2029static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 {"inspect", "-i"},
2032 {"interactive", "-i"},
2033 {"optimize", "-O or -OO"},
2034 {"dont_write_bytecode", "-B"},
2035 {"no_user_site", "-s"},
2036 {"no_site", "-S"},
2037 {"ignore_environment", "-E"},
2038 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 /* {"unbuffered", "-u"}, */
2040 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002041 {"bytes_warning", "-b"},
2042 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002043 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002044 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002045 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002046 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002048};
2049
2050static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002051 "sys.flags", /* name */
2052 flags__doc__, /* doc */
2053 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002054 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002055};
2056
2057static PyObject*
2058make_flags(void)
2059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 int pos = 0;
2061 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01002062 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002063
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 seq = PyStructSequence_New(&FlagsType);
2065 if (seq == NULL)
2066 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002067
2068#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 SetFlag(Py_InspectFlag);
2073 SetFlag(Py_InteractiveFlag);
2074 SetFlag(Py_OptimizeFlag);
2075 SetFlag(Py_DontWriteBytecodeFlag);
2076 SetFlag(Py_NoUserSiteDirectory);
2077 SetFlag(Py_NoSiteFlag);
2078 SetFlag(Py_IgnoreEnvironmentFlag);
2079 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002080 /* SetFlag(saw_unbuffered_flag); */
2081 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00002082 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00002083 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002084 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02002085 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01002086 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01002087 SetFlag(Py_UTF8Mode);
2088#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002091 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 return NULL;
2093 }
2094 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002095}
2096
Eric Smith0e5b5622009-02-06 01:32:42 +00002097PyDoc_STRVAR(version_info__doc__,
2098"sys.version_info\n\
2099\n\
2100Version information as a named tuple.");
2101
2102static PyTypeObject VersionInfoType;
2103
2104static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 {"major", "Major release number"},
2106 {"minor", "Minor release number"},
2107 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002108 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 {"serial", "Serial release number"},
2110 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002111};
2112
2113static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 "sys.version_info", /* name */
2115 version_info__doc__, /* doc */
2116 version_info_fields, /* fields */
2117 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002118};
2119
2120static PyObject *
2121make_version_info(void)
2122{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 PyObject *version_info;
2124 char *s;
2125 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 version_info = PyStructSequence_New(&VersionInfoType);
2128 if (version_info == NULL) {
2129 return NULL;
2130 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 /*
2133 * These release level checks are mutually exclusive and cover
2134 * the field, so don't get too fancy with the pre-processor!
2135 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002136#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002138#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002140#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002142#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002144#endif
2145
2146#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002148#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002150
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 SetIntItem(PY_MAJOR_VERSION);
2152 SetIntItem(PY_MINOR_VERSION);
2153 SetIntItem(PY_MICRO_VERSION);
2154 SetStrItem(s);
2155 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002156#undef SetIntItem
2157#undef SetStrItem
2158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 if (PyErr_Occurred()) {
2160 Py_CLEAR(version_info);
2161 return NULL;
2162 }
2163 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002164}
2165
Brett Cannon3adc7b72012-07-09 14:22:12 -04002166/* sys.implementation values */
2167#define NAME "cpython"
2168const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002169#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2170#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002171#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002172const char *_PySys_ImplCacheTag = TAG;
2173#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002174#undef MAJOR
2175#undef MINOR
2176#undef TAG
2177
Barry Warsaw409da152012-06-03 16:18:47 -04002178static PyObject *
2179make_impl_info(PyObject *version_info)
2180{
2181 int res;
2182 PyObject *impl_info, *value, *ns;
2183
2184 impl_info = PyDict_New();
2185 if (impl_info == NULL)
2186 return NULL;
2187
2188 /* populate the dict */
2189
Brett Cannon3adc7b72012-07-09 14:22:12 -04002190 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002191 if (value == NULL)
2192 goto error;
2193 res = PyDict_SetItemString(impl_info, "name", value);
2194 Py_DECREF(value);
2195 if (res < 0)
2196 goto error;
2197
Brett Cannon3adc7b72012-07-09 14:22:12 -04002198 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002199 if (value == NULL)
2200 goto error;
2201 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2202 Py_DECREF(value);
2203 if (res < 0)
2204 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002205
2206 res = PyDict_SetItemString(impl_info, "version", version_info);
2207 if (res < 0)
2208 goto error;
2209
2210 value = PyLong_FromLong(PY_VERSION_HEX);
2211 if (value == NULL)
2212 goto error;
2213 res = PyDict_SetItemString(impl_info, "hexversion", value);
2214 Py_DECREF(value);
2215 if (res < 0)
2216 goto error;
2217
doko@ubuntu.com55532312016-06-14 08:55:19 +02002218#ifdef MULTIARCH
2219 value = PyUnicode_FromString(MULTIARCH);
2220 if (value == NULL)
2221 goto error;
2222 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2223 Py_DECREF(value);
2224 if (res < 0)
2225 goto error;
2226#endif
2227
Barry Warsaw409da152012-06-03 16:18:47 -04002228 /* dict ready */
2229
2230 ns = _PyNamespace_New(impl_info);
2231 Py_DECREF(impl_info);
2232 return ns;
2233
2234error:
2235 Py_CLEAR(impl_info);
2236 return NULL;
2237}
2238
Martin v. Löwis1a214512008-06-11 05:26:20 +00002239static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 PyModuleDef_HEAD_INIT,
2241 "sys",
2242 sys_doc,
2243 -1, /* multiple "initialization" just copies the module dict. */
2244 sys_methods,
2245 NULL,
2246 NULL,
2247 NULL,
2248 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002249};
2250
Eric Snow6b4be192017-05-22 21:36:03 -07002251/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002252#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002253 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002254 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002255 if (v == NULL) { \
2256 goto err_occurred; \
2257 } \
Victor Stinner58049602013-07-22 22:40:00 +02002258 res = PyDict_SetItemString(sysdict, key, v); \
2259 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002260 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002261 } \
2262 } while (0)
2263#define SET_SYS_FROM_STRING(key, value) \
2264 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002265 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002266 if (v == NULL) { \
2267 goto err_occurred; \
2268 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002269 res = PyDict_SetItemString(sysdict, key, v); \
2270 Py_DECREF(v); \
2271 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002272 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002273 } \
2274 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002275
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002276
2277_PyInitError
2278_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002279{
2280 PyObject *m, *sysdict, *version_info;
2281 int res;
2282
Eric Snowd393c1b2017-09-14 12:18:12 -06002283 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002284 if (m == NULL) {
2285 return _Py_INIT_ERR("failed to create a module object");
2286 }
Eric Snow6b4be192017-05-22 21:36:03 -07002287 sysdict = PyModule_GetDict(m);
2288
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002289 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002290 Using shell redirection, you can redirect stdin to a directory,
2291 crashing the Python interpreter. Catch this common mistake here
2292 and output a useful error message. Note that under MS Windows,
2293 the shell already prevents that. */
2294#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002295 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002296 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002297 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002298 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002299 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2300 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002301 }
2302 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002303#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002304
Nick Coghland6009512014-11-20 21:39:37 +10002305 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002306
Victor Stinner8fea2522013-10-27 17:15:42 +01002307 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2308 PyDict_GetItemString(sysdict, "displayhook"));
2309 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2310 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002311 SET_SYS_FROM_STRING_BORROW(
2312 "__breakpointhook__",
2313 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 SET_SYS_FROM_STRING("version",
2315 PyUnicode_FromString(Py_GetVersion()));
2316 SET_SYS_FROM_STRING("hexversion",
2317 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002318 SET_SYS_FROM_STRING("_git",
2319 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2320 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002321 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002322 SET_SYS_FROM_STRING("api_version",
2323 PyLong_FromLong(PYTHON_API_VERSION));
2324 SET_SYS_FROM_STRING("copyright",
2325 PyUnicode_FromString(Py_GetCopyright()));
2326 SET_SYS_FROM_STRING("platform",
2327 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 SET_SYS_FROM_STRING("maxsize",
2329 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2330 SET_SYS_FROM_STRING("float_info",
2331 PyFloat_GetInfo());
2332 SET_SYS_FROM_STRING("int_info",
2333 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002334 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002335 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002336 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2337 goto type_init_failed;
2338 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002339 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002340 SET_SYS_FROM_STRING("hash_info",
2341 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002343 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 SET_SYS_FROM_STRING("builtin_module_names",
2345 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002346#if PY_BIG_ENDIAN
2347 SET_SYS_FROM_STRING("byteorder",
2348 PyUnicode_FromString("big"));
2349#else
2350 SET_SYS_FROM_STRING("byteorder",
2351 PyUnicode_FromString("little"));
2352#endif
Fred Drake099325e2000-08-14 15:47:03 +00002353
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002354#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002355 SET_SYS_FROM_STRING("dllhandle",
2356 PyLong_FromVoidPtr(PyWin_DLLhModule));
2357 SET_SYS_FROM_STRING("winver",
2358 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002359#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002360#ifdef ABIFLAGS
2361 SET_SYS_FROM_STRING("abiflags",
2362 PyUnicode_FromString(ABIFLAGS));
2363#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002366 if (VersionInfoType.tp_name == NULL) {
2367 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002368 &version_info_desc) < 0) {
2369 goto type_init_failed;
2370 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002371 }
Barry Warsaw409da152012-06-03 16:18:47 -04002372 version_info = make_version_info();
2373 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002374 /* prevent user from creating new instances */
2375 VersionInfoType.tp_init = NULL;
2376 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002377 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2378 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2379 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002380
Barry Warsaw409da152012-06-03 16:18:47 -04002381 /* implementation */
2382 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002384 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002385 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002386 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2387 goto type_init_failed;
2388 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002389 }
Eric Snow6b4be192017-05-22 21:36:03 -07002390 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002392
2393#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 /* getwindowsversion */
2395 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002396 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002397 &windows_version_desc) < 0) {
2398 goto type_init_failed;
2399 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 /* prevent user from creating new instances */
2401 WindowsVersionType.tp_init = NULL;
2402 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002403 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002404 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002405 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002406 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002407 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002408#endif
2409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002410 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002411#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 SET_SYS_FROM_STRING("float_repr_style",
2413 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002414#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 SET_SYS_FROM_STRING("float_repr_style",
2416 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002417#endif
2418
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002419 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002420
Yury Selivanoveb636452016-09-08 22:01:51 -07002421 /* initialize asyncgen_hooks */
2422 if (AsyncGenHooksType.tp_name == NULL) {
2423 if (PyStructSequence_InitType2(
2424 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002425 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002426 }
2427 }
2428
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002429 if (PyErr_Occurred()) {
2430 goto err_occurred;
2431 }
2432
2433 *sysmod = m;
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002434
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002435 return _Py_INIT_OK();
2436
2437type_init_failed:
2438 return _Py_INIT_ERR("failed to initialize a type");
2439
2440err_occurred:
2441 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002442}
2443
Eric Snow6b4be192017-05-22 21:36:03 -07002444#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002445
2446/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002447#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2448 do { \
2449 PyObject *v = (value); \
2450 if (v == NULL) \
2451 return -1; \
2452 res = PyDict_SetItemString(sysdict, key, v); \
2453 Py_DECREF(v); \
2454 if (res < 0) { \
2455 return res; \
2456 } \
2457 } while (0)
2458
2459int
Victor Stinner41264f12017-12-15 02:05:29 +01002460_PySys_EndInit(PyObject *sysdict, _PyMainInterpreterConfig *config)
Eric Snow6b4be192017-05-22 21:36:03 -07002461{
2462 int res;
2463
Victor Stinner41264f12017-12-15 02:05:29 +01002464 /* _PyMainInterpreterConfig_Read() must set all these variables */
2465 assert(config->module_search_path != NULL);
2466 assert(config->executable != NULL);
2467 assert(config->prefix != NULL);
2468 assert(config->base_prefix != NULL);
2469 assert(config->exec_prefix != NULL);
2470 assert(config->base_exec_prefix != NULL);
2471
Victor Stinnera5194112018-11-22 16:11:15 +01002472 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
Victor Stinner41264f12017-12-15 02:05:29 +01002473 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2474 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2475 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2476 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2477 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2478
2479 if (config->argv != NULL) {
2480 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2481 }
2482 if (config->warnoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002483 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002484 }
2485 if (config->xoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002486 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002487 }
2488
Eric Snow6b4be192017-05-22 21:36:03 -07002489 /* Set flags to their final values */
2490 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2491 /* prevent user from creating new instances */
2492 FlagsType.tp_init = NULL;
2493 FlagsType.tp_new = NULL;
2494 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2495 if (res < 0) {
2496 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2497 return res;
2498 }
2499 PyErr_Clear();
2500 }
2501
2502 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2503 PyBool_FromLong(Py_DontWriteBytecodeFlag));
Eric Snow6b4be192017-05-22 21:36:03 -07002504
Eric Snowdae02762017-09-14 00:35:58 -07002505 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002506 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002507
Eric Snowdae02762017-09-14 00:35:58 -07002508 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002509 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002510
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002511 /* Transfer any sys.warnoptions and sys._xoptions set directly
2512 * by an embedding application from the linked list to the module. */
2513 if (_PySys_ReadPreInitOptions() != 0)
2514 return -1;
2515
Eric Snow6b4be192017-05-22 21:36:03 -07002516 if (PyErr_Occurred())
2517 return -1;
2518 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002519
2520err_occurred:
2521 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002522}
2523
Victor Stinner41264f12017-12-15 02:05:29 +01002524#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002525#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002526
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002527static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002528makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002530 int i, n;
2531 const wchar_t *p;
2532 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 n = 1;
2535 p = path;
2536 while ((p = wcschr(p, delim)) != NULL) {
2537 n++;
2538 p++;
2539 }
2540 v = PyList_New(n);
2541 if (v == NULL)
2542 return NULL;
2543 for (i = 0; ; i++) {
2544 p = wcschr(path, delim);
2545 if (p == NULL)
2546 p = path + wcslen(path); /* End of string */
2547 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2548 if (w == NULL) {
2549 Py_DECREF(v);
2550 return NULL;
2551 }
Miss Islington (bot)8b7d8ac2018-12-08 06:34:49 -08002552 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002553 if (*p == '\0')
2554 break;
2555 path = p+1;
2556 }
2557 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002558}
2559
2560void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002561PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 PyObject *v;
2564 if ((v = makepathobject(path, DELIM)) == NULL)
2565 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002566 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 Py_FatalError("can't assign sys.path");
2568 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002569}
2570
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002571static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002572makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 PyObject *av;
2575 if (argc <= 0 || argv == NULL) {
2576 /* Ensure at least one (empty) argument is seen */
2577 static wchar_t *empty_argv[1] = {L""};
2578 argv = empty_argv;
2579 argc = 1;
2580 }
2581 av = PyList_New(argc);
2582 if (av != NULL) {
2583 int i;
2584 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002586 if (v == NULL) {
2587 Py_DECREF(av);
2588 av = NULL;
2589 break;
2590 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002591 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 }
2593 }
2594 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002595}
2596
Victor Stinner11a247d2017-12-13 21:05:57 +01002597void
2598PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002599{
2600 PyObject *av = makeargvobject(argc, argv);
2601 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002602 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002603 }
2604 if (PySys_SetObject("argv", av) != 0) {
2605 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002606 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002607 }
2608 Py_DECREF(av);
2609
2610 if (updatepath) {
2611 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2612 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002613 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2614 if (argv0 == NULL) {
2615 Py_FatalError("can't compute path0 from argv");
2616 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002617
Victor Stinner11a247d2017-12-13 21:05:57 +01002618 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2619 if (sys_path != NULL) {
2620 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2621 Py_DECREF(argv0);
2622 Py_FatalError("can't prepend path0 to sys.path");
2623 }
2624 }
2625 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002626 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002627}
Guido van Rossuma890e681998-05-12 14:59:24 +00002628
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002629void
2630PySys_SetArgv(int argc, wchar_t **argv)
2631{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002632 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002633}
2634
Victor Stinner14284c22010-04-23 12:02:30 +00002635/* Reimplementation of PyFile_WriteString() no calling indirectly
2636 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2637
2638static int
Victor Stinner79766632010-08-16 17:36:42 +00002639sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002640{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002641 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002643
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002644 if (file == NULL)
2645 return -1;
2646
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002647 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 if (writer == NULL)
2649 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002650
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002651 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 if (result == NULL) {
2653 goto error;
2654 } else {
2655 err = 0;
2656 goto finally;
2657 }
Victor Stinner14284c22010-04-23 12:02:30 +00002658
2659error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002660 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002661finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002663 Py_XDECREF(result);
2664 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002665}
2666
Victor Stinner79766632010-08-16 17:36:42 +00002667static int
2668sys_pyfile_write(const char *text, PyObject *file)
2669{
2670 PyObject *unicode = NULL;
2671 int err;
2672
2673 if (file == NULL)
2674 return -1;
2675
2676 unicode = PyUnicode_FromString(text);
2677 if (unicode == NULL)
2678 return -1;
2679
2680 err = sys_pyfile_write_unicode(unicode, file);
2681 Py_DECREF(unicode);
2682 return err;
2683}
Guido van Rossuma890e681998-05-12 14:59:24 +00002684
2685/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2686 Adapted from code submitted by Just van Rossum.
2687
2688 PySys_WriteStdout(format, ...)
2689 PySys_WriteStderr(format, ...)
2690
2691 The first function writes to sys.stdout; the second to sys.stderr. When
2692 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002693 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002694
Victor Stinner14284c22010-04-23 12:02:30 +00002695 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002696 signal handlers: they may raise a new exception whereas sys_write()
2697 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002698
Guido van Rossuma890e681998-05-12 14:59:24 +00002699 Both take a printf-style format string as their first argument followed
2700 by a variable length argument list determined by the format string.
2701
2702 *** WARNING ***
2703
2704 The format should limit the total size of the formatted output string to
2705 1000 bytes. In particular, this means that no unrestricted "%s" formats
2706 should occur; these should be limited using "%.<N>s where <N> is a
2707 decimal number calculated so that <N> plus the maximum size of other
2708 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2709 which can print hundreds of digits for very large numbers.
2710
2711 */
2712
2713static void
Victor Stinner09054372013-11-06 22:41:44 +01002714sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002715{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002716 PyObject *file;
2717 PyObject *error_type, *error_value, *error_traceback;
2718 char buffer[1001];
2719 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002720
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002722 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002723 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2724 if (sys_pyfile_write(buffer, file) != 0) {
2725 PyErr_Clear();
2726 fputs(buffer, fp);
2727 }
2728 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2729 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002730 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002732 }
2733 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002734}
2735
2736void
Guido van Rossuma890e681998-05-12 14:59:24 +00002737PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002742 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002743 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002744}
2745
2746void
Guido van Rossuma890e681998-05-12 14:59:24 +00002747PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002752 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002753 va_end(va);
2754}
2755
2756static void
Victor Stinner09054372013-11-06 22:41:44 +01002757sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002758{
2759 PyObject *file, *message;
2760 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002761 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002762
2763 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002764 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002765 message = PyUnicode_FromFormatV(format, va);
2766 if (message != NULL) {
2767 if (sys_pyfile_write_unicode(message, file) != 0) {
2768 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002769 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002770 if (utf8 != NULL)
2771 fputs(utf8, fp);
2772 }
2773 Py_DECREF(message);
2774 }
2775 PyErr_Restore(error_type, error_value, error_traceback);
2776}
2777
2778void
2779PySys_FormatStdout(const char *format, ...)
2780{
2781 va_list va;
2782
2783 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002784 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002785 va_end(va);
2786}
2787
2788void
2789PySys_FormatStderr(const char *format, ...)
2790{
2791 va_list va;
2792
2793 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002794 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002795 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002796}