blob: 9579eae4ff5f4d28b11919789a22a4f600668446 [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{
Victor Stinnercaba55b2018-08-03 15:33:52 +020059 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
60 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010061 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020062 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010063 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{
Victor Stinnercaba55b2018-08-03 15:33:52 +020069 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
70 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000071 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020072 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 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{
Victor Stinnercaba55b2018-08-03 15:33:52 +020079 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010080 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020081 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010082 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020083 }
84 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010085 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020086 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010087 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020088 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010089 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020090 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010091}
92
93int
Neal Norwitzf3081322007-08-25 00:32:45 +000094PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000095{
Victor Stinnercaba55b2018-08-03 15:33:52 +020096 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000097 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020098 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000099 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200100 }
101 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200103 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000104 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200105 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200107 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000108}
109
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400110static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200111sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400112{
113 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300114 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400115
116 if (envar == NULL || strlen(envar) == 0) {
117 envar = "pdb.set_trace";
118 }
119 else if (!strcmp(envar, "0")) {
120 /* The breakpoint is explicitly no-op'd. */
121 Py_RETURN_NONE;
122 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300123 /* According to POSIX the string returned by getenv() might be invalidated
124 * or the string content might be overwritten by a subsequent call to
125 * getenv(). Since importing a module can performs the getenv() calls,
126 * we need to save a copy of envar. */
127 envar = _PyMem_RawStrdup(envar);
128 if (envar == NULL) {
129 PyErr_NoMemory();
130 return NULL;
131 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200132 const char *last_dot = strrchr(envar, '.');
133 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400134 PyObject *modulepath = NULL;
135
136 if (last_dot == NULL) {
137 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
138 modulepath = PyUnicode_FromString("builtins");
139 attrname = envar;
140 }
141 else {
142 /* Split on the last dot; */
143 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
144 attrname = last_dot + 1;
145 }
146 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300147 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400148 return NULL;
149 }
150
151 PyObject *fromlist = Py_BuildValue("(s)", attrname);
152 if (fromlist == NULL) {
153 Py_DECREF(modulepath);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300154 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400155 return NULL;
156 }
157 PyObject *module = PyImport_ImportModuleLevelObject(
158 modulepath, NULL, NULL, fromlist, 0);
159 Py_DECREF(modulepath);
160 Py_DECREF(fromlist);
161
162 if (module == NULL) {
163 goto error;
164 }
165
166 PyObject *hook = PyObject_GetAttrString(module, attrname);
167 Py_DECREF(module);
168
169 if (hook == NULL) {
170 goto error;
171 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300172 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400173 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
174 Py_DECREF(hook);
175 return retval;
176
177 error:
178 /* If any of the imports went wrong, then warn and ignore. */
179 PyErr_Clear();
180 int status = PyErr_WarnFormat(
181 PyExc_RuntimeWarning, 0,
182 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300183 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400184 if (status < 0) {
185 /* Printing the warning raised an exception. */
186 return NULL;
187 }
188 /* The warning was (probably) issued. */
189 Py_RETURN_NONE;
190}
191
192PyDoc_STRVAR(breakpointhook_doc,
193"breakpointhook(*args, **kws)\n"
194"\n"
195"This hook function is called by built-in breakpoint().\n"
196);
197
Victor Stinner13d49ee2010-12-04 17:24:33 +0000198/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
199 error handler. If sys.stdout has a buffer attribute, use
200 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
201 sys.stdout.write(redecoded).
202
203 Helper function for sys_displayhook(). */
204static int
205sys_displayhook_unencodable(PyObject *outf, PyObject *o)
206{
207 PyObject *stdout_encoding = NULL;
208 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200209 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000210 int ret;
211
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200212 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000213 if (stdout_encoding == NULL)
214 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200215 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000216 if (stdout_encoding_str == NULL)
217 goto error;
218
219 repr_str = PyObject_Repr(o);
220 if (repr_str == NULL)
221 goto error;
222 encoded = PyUnicode_AsEncodedString(repr_str,
223 stdout_encoding_str,
224 "backslashreplace");
225 Py_DECREF(repr_str);
226 if (encoded == NULL)
227 goto error;
228
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200229 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000230 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100231 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000232 Py_DECREF(buffer);
233 Py_DECREF(encoded);
234 if (result == NULL)
235 goto error;
236 Py_DECREF(result);
237 }
238 else {
239 PyErr_Clear();
240 escaped_str = PyUnicode_FromEncodedObject(encoded,
241 stdout_encoding_str,
242 "strict");
243 Py_DECREF(encoded);
244 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
245 Py_DECREF(escaped_str);
246 goto error;
247 }
248 Py_DECREF(escaped_str);
249 }
250 ret = 0;
251 goto finally;
252
253error:
254 ret = -1;
255finally:
256 Py_XDECREF(stdout_encoding);
257 return ret;
258}
259
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000260static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000261sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100264 PyObject *builtins;
265 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000266 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000267
Eric Snow3f9eee62017-09-15 16:35:20 -0600268 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (builtins == NULL) {
270 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
271 return NULL;
272 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600273 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 /* Print value except if None */
276 /* After printing, also assign to '_' */
277 /* Before, set '_' to None to avoid recursion */
278 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200279 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200281 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100283 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 if (outf == NULL || outf == Py_None) {
285 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
286 return NULL;
287 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000288 if (PyFile_WriteObject(o, outf, 0) != 0) {
289 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
290 /* repr(o) is not encodable to sys.stdout.encoding with
291 * sys.stdout.errors error handler (which is probably 'strict') */
292 PyErr_Clear();
293 err = sys_displayhook_unencodable(outf, o);
294 if (err)
295 return NULL;
296 }
297 else {
298 return NULL;
299 }
300 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100301 if (newline == NULL) {
302 newline = PyUnicode_FromString("\n");
303 if (newline == NULL)
304 return NULL;
305 }
306 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000307 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200308 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200310 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000311}
312
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000313PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000314"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000315"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000316"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000317);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000318
319static PyObject *
320sys_excepthook(PyObject* self, PyObject* args)
321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000322 PyObject *exc, *value, *tb;
323 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
324 return NULL;
325 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200326 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000327}
328
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000329PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000330"excepthook(exctype, value, traceback) -> None\n"
331"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000332"Handle an exception by displaying it with a traceback on sys.stderr.\n"
333);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000334
335static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000336sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000337{
Mark Shannonae3087c2017-10-22 22:41:51 +0100338 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000339 return Py_BuildValue(
340 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100341 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
342 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
343 err_info->exc_traceback != NULL ?
344 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000345}
346
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000347PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000348"exc_info() -> (type, value, traceback)\n\
349\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000350Return information about the most recent exception caught by an except\n\
351clause in the current stack frame or in an older stack frame."
352);
353
354static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000355sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000356{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000357 PyObject *exit_code = 0;
358 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
359 return NULL;
360 /* Raise SystemExit so callers may catch it or clean up. */
361 PyErr_SetObject(PyExc_SystemExit, exit_code);
362 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363}
364
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000365PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000366"exit([status])\n\
367\n\
368Exit the interpreter by raising SystemExit(status).\n\
369If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300370If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000371If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000372exit status will be one (i.e., failure)."
373);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000374
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000375
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000376static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530377sys_getdefaultencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Fred Drake8b4d01d2000-05-09 19:57:01 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000380}
381
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000382PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000383"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000384\n\
oldkaa0735f2018-02-02 16:52:55 +0800385Return the current default string encoding used by the Unicode\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000386implementation."
387);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000388
389static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530390sys_getfilesystemencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000391{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200392 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
393 const _PyCoreConfig *config = &interp->core_config;
394 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000395}
396
397PyDoc_STRVAR(getfilesystemencoding_doc,
398"getfilesystemencoding() -> string\n\
399\n\
400Return the encoding used to convert Unicode filenames in\n\
401operating system filenames."
402);
403
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000404static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530405sys_getfilesystemencodeerrors(PyObject *self, PyObject *Py_UNUSED(ignored))
Steve Dowercc16be82016-09-08 10:35:16 -0700406{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200407 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
408 const _PyCoreConfig *config = &interp->core_config;
409 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700410}
411
412PyDoc_STRVAR(getfilesystemencodeerrors_doc,
413 "getfilesystemencodeerrors() -> string\n\
414\n\
415Return the error mode used to convert Unicode filenames in\n\
416operating system filenames."
417);
418
419static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000420sys_intern(PyObject *self, PyObject *args)
421{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000422 PyObject *s;
423 if (!PyArg_ParseTuple(args, "U:intern", &s))
424 return NULL;
425 if (PyUnicode_CheckExact(s)) {
426 Py_INCREF(s);
427 PyUnicode_InternInPlace(&s);
428 return s;
429 }
430 else {
431 PyErr_Format(PyExc_TypeError,
432 "can't intern %.400s", s->ob_type->tp_name);
433 return NULL;
434 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000435}
436
437PyDoc_STRVAR(intern_doc,
438"intern(string) -> string\n\
439\n\
440``Intern'' the given string. This enters the string in the (global)\n\
441table of interned strings whose purpose is to speed up dictionary lookups.\n\
442Return the string itself or the previously interned string object with the\n\
443same value.");
444
445
Fred Drake5755ce62001-06-27 19:19:46 +0000446/*
447 * Cached interned string objects used for calling the profile and
448 * trace functions. Initialized by trace_init().
449 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000450static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000451
452static int
453trace_init(void)
454{
Nick Coghlan5a851672017-09-08 10:14:16 +1000455 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200456 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000457 "c_call", "c_exception", "c_return",
458 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200459 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 PyObject *name;
461 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000462 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 if (whatstrings[i] == NULL) {
464 name = PyUnicode_InternFromString(whatnames[i]);
465 if (name == NULL)
466 return -1;
467 whatstrings[i] = name;
468 }
469 }
470 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000471}
472
473
474static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100475call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200479 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000480
Victor Stinner78da82b2016-08-20 01:22:57 +0200481 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200483 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100484
Victor Stinner78da82b2016-08-20 01:22:57 +0200485 stack[0] = (PyObject *)frame;
486 stack[1] = whatstrings[what];
487 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000488
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200490 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000491
Victor Stinner78da82b2016-08-20 01:22:57 +0200492 PyFrame_LocalsToFast(frame, 1);
493 if (result == NULL) {
494 PyTraceBack_Here(frame);
495 }
496
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000498}
499
500static int
501profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 if (arg == NULL)
507 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100508 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (result == NULL) {
510 PyEval_SetProfile(NULL, NULL);
511 return -1;
512 }
513 Py_DECREF(result);
514 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000515}
516
517static int
518trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 PyObject *callback;
522 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000523
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (what == PyTrace_CALL)
525 callback = self;
526 else
527 callback = frame->f_trace;
528 if (callback == NULL)
529 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100530 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (result == NULL) {
532 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200533 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 return -1;
535 }
536 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300537 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 }
539 else {
540 Py_DECREF(result);
541 }
542 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000543}
Fred Draked0838392001-06-16 21:02:31 +0000544
Fred Drake8b4d01d2000-05-09 19:57:01 +0000545static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000546sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000547{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 if (trace_init() == -1)
549 return NULL;
550 if (args == Py_None)
551 PyEval_SetTrace(NULL, NULL);
552 else
553 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200554 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000555}
556
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000557PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000558"settrace(function)\n\
559\n\
560Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000561function call. See the debugger chapter in the library manual."
562);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000563
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000564static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000565sys_gettrace(PyObject *self, PyObject *args)
566{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 PyThreadState *tstate = PyThreadState_GET();
568 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 if (temp == NULL)
571 temp = Py_None;
572 Py_INCREF(temp);
573 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000574}
575
576PyDoc_STRVAR(gettrace_doc,
577"gettrace()\n\
578\n\
579Return the global debug tracing function set with sys.settrace.\n\
580See the debugger chapter in the library manual."
581);
582
583static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000584sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 if (trace_init() == -1)
587 return NULL;
588 if (args == Py_None)
589 PyEval_SetProfile(NULL, NULL);
590 else
591 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200592 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000593}
594
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000595PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000596"setprofile(function)\n\
597\n\
598Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000599and return. See the profiler chapter in the library manual."
600);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000601
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000602static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000603sys_getprofile(PyObject *self, PyObject *args)
604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 PyThreadState *tstate = PyThreadState_GET();
606 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (temp == NULL)
609 temp = Py_None;
610 Py_INCREF(temp);
611 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000612}
613
614PyDoc_STRVAR(getprofile_doc,
615"getprofile()\n\
616\n\
617Return the profiling function set with sys.setprofile.\n\
618See the profiler chapter in the library manual."
619);
620
621static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000622sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000624 if (PyErr_WarnEx(PyExc_DeprecationWarning,
625 "sys.getcheckinterval() and sys.setcheckinterval() "
626 "are deprecated. Use sys.setswitchinterval() "
627 "instead.", 1) < 0)
628 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200629
630 int check_interval;
631 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200633
634 PyInterpreterState *interp = _PyInterpreterState_Get();
635 interp->check_interval = check_interval;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200636 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000637}
638
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000639PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000640"setcheckinterval(n)\n\
641\n\
642Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000643n instructions. This also affects how often thread switches occur."
644);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000645
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000646static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000647sys_getcheckinterval(PyObject *self, PyObject *args)
648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 if (PyErr_WarnEx(PyExc_DeprecationWarning,
650 "sys.getcheckinterval() and sys.setcheckinterval() "
651 "are deprecated. Use sys.getswitchinterval() "
652 "instead.", 1) < 0)
653 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200654 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600655 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000656}
657
658PyDoc_STRVAR(getcheckinterval_doc,
659"getcheckinterval() -> current check interval; see setcheckinterval()."
660);
661
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000662static PyObject *
663sys_setswitchinterval(PyObject *self, PyObject *args)
664{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000665 double d;
666 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
667 return NULL;
668 if (d <= 0.0) {
669 PyErr_SetString(PyExc_ValueError,
670 "switch interval must be strictly positive");
671 return NULL;
672 }
673 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200674 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000675}
676
677PyDoc_STRVAR(setswitchinterval_doc,
678"setswitchinterval(n)\n\
679\n\
680Set the ideal thread switching delay inside the Python interpreter\n\
681The actual frequency of switching threads can be lower if the\n\
682interpreter executes long sequences of uninterruptible code\n\
683(this is implementation-specific and workload-dependent).\n\
684\n\
685The parameter must represent the desired switching delay in seconds\n\
686A typical value is 0.005 (5 milliseconds)."
687);
688
689static PyObject *
690sys_getswitchinterval(PyObject *self, PyObject *args)
691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000693}
694
695PyDoc_STRVAR(getswitchinterval_doc,
696"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
697);
698
Tim Peterse5e065b2003-07-06 18:36:54 +0000699static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000700sys_setrecursionlimit(PyObject *self, PyObject *args)
701{
Victor Stinner50856d52015-10-13 00:11:21 +0200702 int new_limit, mark;
703 PyThreadState *tstate;
704
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000705 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
706 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200707
708 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200710 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000711 return NULL;
712 }
Victor Stinner50856d52015-10-13 00:11:21 +0200713
714 /* Issue #25274: When the recursion depth hits the recursion limit in
715 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
716 set to 1 and a RecursionError is raised. The overflowed flag is reset
717 to 0 when the recursion depth goes below the low-water mark: see
718 Py_LeaveRecursiveCall().
719
720 Reject too low new limit if the current recursion depth is higher than
721 the new low-water mark. Otherwise it may not be possible anymore to
722 reset the overflowed flag to 0. */
723 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
724 tstate = PyThreadState_GET();
725 if (tstate->recursion_depth >= mark) {
726 PyErr_Format(PyExc_RecursionError,
727 "cannot set the recursion limit to %i at "
728 "the recursion depth %i: the limit is too low",
729 new_limit, tstate->recursion_depth);
730 return NULL;
731 }
732
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200734 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000735}
736
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800737/*[clinic input]
738sys.set_coroutine_origin_tracking_depth
739
740 depth: int
741
742Enable or disable origin tracking for coroutine objects in this thread.
743
744Coroutine objects will track 'depth' frames of traceback information about
745where they came from, available in their cr_origin attribute. Set depth of 0
746to disable.
747[clinic start generated code]*/
748
749static PyObject *
750sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
751/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
752{
753 if (depth < 0) {
754 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
755 return NULL;
756 }
757 _PyEval_SetCoroutineOriginTrackingDepth(depth);
758 Py_RETURN_NONE;
759}
760
761/*[clinic input]
762sys.get_coroutine_origin_tracking_depth -> int
763
764Check status of origin tracking for coroutine objects in this thread.
765[clinic start generated code]*/
766
767static int
768sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
769/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
770{
771 return _PyEval_GetCoroutineOriginTrackingDepth();
772}
773
Yury Selivanov75445082015-05-11 22:57:16 -0400774static PyObject *
775sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
776{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800777 if (PyErr_WarnEx(PyExc_DeprecationWarning,
778 "set_coroutine_wrapper is deprecated", 1) < 0) {
779 return NULL;
780 }
781
Yury Selivanov75445082015-05-11 22:57:16 -0400782 if (wrapper != Py_None) {
783 if (!PyCallable_Check(wrapper)) {
784 PyErr_Format(PyExc_TypeError,
785 "callable expected, got %.50s",
786 Py_TYPE(wrapper)->tp_name);
787 return NULL;
788 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400789 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400790 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400791 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400792 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400793 }
Yury Selivanov75445082015-05-11 22:57:16 -0400794 Py_RETURN_NONE;
795}
796
797PyDoc_STRVAR(set_coroutine_wrapper_doc,
798"set_coroutine_wrapper(wrapper)\n\
799\n\
800Set a wrapper for coroutine objects."
801);
802
803static PyObject *
804sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
805{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800806 if (PyErr_WarnEx(PyExc_DeprecationWarning,
807 "get_coroutine_wrapper is deprecated", 1) < 0) {
808 return NULL;
809 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400810 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400811 if (wrapper == NULL) {
812 wrapper = Py_None;
813 }
814 Py_INCREF(wrapper);
815 return wrapper;
816}
817
818PyDoc_STRVAR(get_coroutine_wrapper_doc,
819"get_coroutine_wrapper()\n\
820\n\
821Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
822);
823
824
Yury Selivanoveb636452016-09-08 22:01:51 -0700825static PyTypeObject AsyncGenHooksType;
826
827PyDoc_STRVAR(asyncgen_hooks_doc,
828"asyncgen_hooks\n\
829\n\
830A struct sequence providing information about asynhronous\n\
831generators hooks. The attributes are read only.");
832
833static PyStructSequence_Field asyncgen_hooks_fields[] = {
834 {"firstiter", "Hook to intercept first iteration"},
835 {"finalizer", "Hook to intercept finalization"},
836 {0}
837};
838
839static PyStructSequence_Desc asyncgen_hooks_desc = {
840 "asyncgen_hooks", /* name */
841 asyncgen_hooks_doc, /* doc */
842 asyncgen_hooks_fields , /* fields */
843 2
844};
845
846
847static PyObject *
848sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
849{
850 static char *keywords[] = {"firstiter", "finalizer", NULL};
851 PyObject *firstiter = NULL;
852 PyObject *finalizer = NULL;
853
854 if (!PyArg_ParseTupleAndKeywords(
855 args, kw, "|OO", keywords,
856 &firstiter, &finalizer)) {
857 return NULL;
858 }
859
860 if (finalizer && finalizer != Py_None) {
861 if (!PyCallable_Check(finalizer)) {
862 PyErr_Format(PyExc_TypeError,
863 "callable finalizer expected, got %.50s",
864 Py_TYPE(finalizer)->tp_name);
865 return NULL;
866 }
867 _PyEval_SetAsyncGenFinalizer(finalizer);
868 }
869 else if (finalizer == Py_None) {
870 _PyEval_SetAsyncGenFinalizer(NULL);
871 }
872
873 if (firstiter && firstiter != Py_None) {
874 if (!PyCallable_Check(firstiter)) {
875 PyErr_Format(PyExc_TypeError,
876 "callable firstiter expected, got %.50s",
877 Py_TYPE(firstiter)->tp_name);
878 return NULL;
879 }
880 _PyEval_SetAsyncGenFirstiter(firstiter);
881 }
882 else if (firstiter == Py_None) {
883 _PyEval_SetAsyncGenFirstiter(NULL);
884 }
885
886 Py_RETURN_NONE;
887}
888
889PyDoc_STRVAR(set_asyncgen_hooks_doc,
890"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
891\n\
892Set a finalizer for async generators objects."
893);
894
895static PyObject *
896sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
897{
898 PyObject *res;
899 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
900 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
901
902 res = PyStructSequence_New(&AsyncGenHooksType);
903 if (res == NULL) {
904 return NULL;
905 }
906
907 if (firstiter == NULL) {
908 firstiter = Py_None;
909 }
910
911 if (finalizer == NULL) {
912 finalizer = Py_None;
913 }
914
915 Py_INCREF(firstiter);
916 PyStructSequence_SET_ITEM(res, 0, firstiter);
917
918 Py_INCREF(finalizer);
919 PyStructSequence_SET_ITEM(res, 1, finalizer);
920
921 return res;
922}
923
924PyDoc_STRVAR(get_asyncgen_hooks_doc,
925"get_asyncgen_hooks()\n\
926\n\
927Return a namedtuple of installed asynchronous generators hooks \
928(firstiter, finalizer)."
929);
930
931
Mark Dickinsondc787d22010-05-23 13:33:13 +0000932static PyTypeObject Hash_InfoType;
933
934PyDoc_STRVAR(hash_info_doc,
935"hash_info\n\
936\n\
937A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100938hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000939
940static PyStructSequence_Field hash_info_fields[] = {
941 {"width", "width of the type used for hashing, in bits"},
942 {"modulus", "prime number giving the modulus on which the hash "
943 "function is based"},
944 {"inf", "value to be used for hash of a positive infinity"},
945 {"nan", "value to be used for hash of a nan"},
946 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100947 {"algorithm", "name of the algorithm for hashing of str, bytes and "
948 "memoryviews"},
949 {"hash_bits", "internal output size of hash algorithm"},
950 {"seed_bits", "seed size of hash algorithm"},
951 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000952 {NULL, NULL}
953};
954
955static PyStructSequence_Desc hash_info_desc = {
956 "sys.hash_info",
957 hash_info_doc,
958 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100959 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000960};
961
Matthias Klosed885e952010-07-06 10:53:30 +0000962static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000963get_hash_info(void)
964{
965 PyObject *hash_info;
966 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100967 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000968 hash_info = PyStructSequence_New(&Hash_InfoType);
969 if (hash_info == NULL)
970 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100971 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000972 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000973 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000974 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000975 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000976 PyStructSequence_SET_ITEM(hash_info, field++,
977 PyLong_FromLong(_PyHASH_INF));
978 PyStructSequence_SET_ITEM(hash_info, field++,
979 PyLong_FromLong(_PyHASH_NAN));
980 PyStructSequence_SET_ITEM(hash_info, field++,
981 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100982 PyStructSequence_SET_ITEM(hash_info, field++,
983 PyUnicode_FromString(hashfunc->name));
984 PyStructSequence_SET_ITEM(hash_info, field++,
985 PyLong_FromLong(hashfunc->hash_bits));
986 PyStructSequence_SET_ITEM(hash_info, field++,
987 PyLong_FromLong(hashfunc->seed_bits));
988 PyStructSequence_SET_ITEM(hash_info, field++,
989 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000990 if (PyErr_Occurred()) {
991 Py_CLEAR(hash_info);
992 return NULL;
993 }
994 return hash_info;
995}
996
997
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000998PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000999"setrecursionlimit(n)\n\
1000\n\
1001Set the maximum depth of the Python interpreter stack to n. This\n\
1002limit prevents infinite recursion from causing an overflow of the C\n\
1003stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001004dependent."
1005);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001006
1007static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301008sys_getrecursionlimit(PyObject *self, PyObject *Py_UNUSED(ignored))
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001010 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001011}
1012
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001013PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001014"getrecursionlimit()\n\
1015\n\
1016Return the current value of the recursion limit, the maximum depth\n\
1017of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001018recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001019);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001020
Mark Hammond8696ebc2002-10-08 02:44:31 +00001021#ifdef MS_WINDOWS
1022PyDoc_STRVAR(getwindowsversion_doc,
1023"getwindowsversion()\n\
1024\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001025Return information about the running version of Windows as a named tuple.\n\
1026The members are named: major, minor, build, platform, service_pack,\n\
1027service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001028backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001029All elements are numbers, except service_pack and platform_type which are\n\
1030strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1031Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1032server. Platform_version is a 3-tuple containing a version number that is\n\
1033intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001034);
1035
Eric Smithf7bb5782010-01-27 00:44:57 +00001036static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1037
1038static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001039 {"major", "Major version number"},
1040 {"minor", "Minor version number"},
1041 {"build", "Build number"},
1042 {"platform", "Operating system platform"},
1043 {"service_pack", "Latest Service Pack installed on the system"},
1044 {"service_pack_major", "Service Pack major version number"},
1045 {"service_pack_minor", "Service Pack minor version number"},
1046 {"suite_mask", "Bit mask identifying available product suites"},
1047 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001048 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001050};
1051
1052static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 "sys.getwindowsversion", /* name */
1054 getwindowsversion_doc, /* doc */
1055 windows_version_fields, /* fields */
1056 5 /* For backward compatibility,
1057 only the first 5 items are accessible
1058 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001059};
1060
Steve Dower3e96f322015-03-02 08:01:10 -08001061/* Disable deprecation warnings about GetVersionEx as the result is
1062 being passed straight through to the caller, who is responsible for
1063 using it correctly. */
1064#pragma warning(push)
1065#pragma warning(disable:4996)
1066
Mark Hammond8696ebc2002-10-08 02:44:31 +00001067static PyObject *
1068sys_getwindowsversion(PyObject *self)
1069{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 PyObject *version;
1071 int pos = 0;
1072 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001073 DWORD realMajor, realMinor, realBuild;
1074 HANDLE hKernel32;
1075 wchar_t kernel32_path[MAX_PATH];
1076 LPVOID verblock;
1077 DWORD verblock_size;
1078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 ver.dwOSVersionInfoSize = sizeof(ver);
1080 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1081 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 version = PyStructSequence_New(&WindowsVersionType);
1084 if (version == NULL)
1085 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1088 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1089 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1090 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1091 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1092 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1093 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1094 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1095 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001096
Steve Dower74f4af72016-09-17 17:27:48 -07001097 realMajor = ver.dwMajorVersion;
1098 realMinor = ver.dwMinorVersion;
1099 realBuild = ver.dwBuildNumber;
1100
1101 // GetVersion will lie if we are running in a compatibility mode.
1102 // We need to read the version info from a system file resource
1103 // to accurately identify the OS version. If we fail for any reason,
1104 // just return whatever GetVersion said.
1105 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1106 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1107 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1108 (verblock = PyMem_RawMalloc(verblock_size))) {
1109 VS_FIXEDFILEINFO *ffi;
1110 UINT ffi_len;
1111
1112 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1113 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1114 realMajor = HIWORD(ffi->dwProductVersionMS);
1115 realMinor = LOWORD(ffi->dwProductVersionMS);
1116 realBuild = HIWORD(ffi->dwProductVersionLS);
1117 }
1118 PyMem_RawFree(verblock);
1119 }
Segev Finer48fb7662017-06-04 20:52:27 +03001120 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1121 realMajor,
1122 realMinor,
1123 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001124 ));
1125
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001126 if (PyErr_Occurred()) {
1127 Py_DECREF(version);
1128 return NULL;
1129 }
Steve Dower74f4af72016-09-17 17:27:48 -07001130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001132}
1133
Steve Dower3e96f322015-03-02 08:01:10 -08001134#pragma warning(pop)
1135
Steve Dowercc16be82016-09-08 10:35:16 -07001136PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1137"_enablelegacywindowsfsencoding()\n\
1138\n\
1139Changes the default filesystem encoding to mbcs:replace for consistency\n\
1140with earlier versions of Python. See PEP 529 for more information.\n\
1141\n\
oldkaa0735f2018-02-02 16:52:55 +08001142This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001143environment variable before launching Python."
1144);
1145
1146static PyObject *
1147sys_enablelegacywindowsfsencoding(PyObject *self)
1148{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001149 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1150 _PyCoreConfig *config = &interp->core_config;
1151
1152 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1153 char *encoding = _PyMem_RawStrdup("mbcs");
1154 char *errors = _PyMem_RawStrdup("replace");
1155 if (encoding == NULL || errors == NULL) {
1156 PyMem_Free(encoding);
1157 PyMem_Free(errors);
1158 PyErr_NoMemory();
1159 return NULL;
1160 }
1161
1162 PyMem_RawFree(config->filesystem_encoding);
1163 config->filesystem_encoding = encoding;
1164 PyMem_RawFree(config->filesystem_errors);
1165 config->filesystem_errors = errors;
1166
1167 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1168 config->filesystem_errors) < 0) {
1169 PyErr_NoMemory();
1170 return NULL;
1171 }
1172
Steve Dowercc16be82016-09-08 10:35:16 -07001173 Py_RETURN_NONE;
1174}
1175
Mark Hammond8696ebc2002-10-08 02:44:31 +00001176#endif /* MS_WINDOWS */
1177
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001178#ifdef HAVE_DLOPEN
1179static PyObject *
1180sys_setdlopenflags(PyObject *self, PyObject *args)
1181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 int new_val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1184 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001185 PyInterpreterState *interp = _PyInterpreterState_Get();
1186 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001187 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001188}
1189
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001190PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001191"setdlopenflags(n) -> None\n\
1192\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001193Set the flags used by the interpreter for dlopen calls, such as when the\n\
1194interpreter loads extension modules. Among other things, this will enable\n\
1195a lazy resolving of symbols when importing a module, if called as\n\
1196sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001197sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001198can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001199
1200static PyObject *
1201sys_getdlopenflags(PyObject *self, PyObject *args)
1202{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001203 PyInterpreterState *interp = _PyInterpreterState_Get();
1204 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001205}
1206
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001207PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001208"getdlopenflags() -> int\n\
1209\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001210Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001211The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001212
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001214
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001215#ifdef USE_MALLOPT
1216/* Link with -lmalloc (or -lmpc) on an SGI */
1217#include <malloc.h>
1218
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001219static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001220sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 int flag;
1223 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1224 return NULL;
1225 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001226 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001227}
1228#endif /* USE_MALLOPT */
1229
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001230size_t
1231_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001235 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 /* Make sure the type is initialized. float gets initialized late */
1238 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001239 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001240
Benjamin Petersonce798522012-01-22 11:24:29 -05001241 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242 if (method == NULL) {
1243 if (!PyErr_Occurred())
1244 PyErr_Format(PyExc_TypeError,
1245 "Type %.100s doesn't define __sizeof__",
1246 Py_TYPE(o)->tp_name);
1247 }
1248 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001249 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 Py_DECREF(method);
1251 }
1252
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001253 if (res == NULL)
1254 return (size_t)-1;
1255
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001256 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001257 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001258 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001259 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001261 if (size < 0) {
1262 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1263 return (size_t)-1;
1264 }
1265
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001267 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001268 return ((size_t)size) + sizeof(PyGC_Head);
1269 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001270}
1271
1272static PyObject *
1273sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1274{
1275 static char *kwlist[] = {"object", "default", 0};
1276 size_t size;
1277 PyObject *o, *dflt = NULL;
1278
1279 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1280 kwlist, &o, &dflt))
1281 return NULL;
1282
1283 size = _PySys_GetSizeOf(o);
1284
1285 if (size == (size_t)-1 && PyErr_Occurred()) {
1286 /* Has a default value been given */
1287 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1288 PyErr_Clear();
1289 Py_INCREF(dflt);
1290 return dflt;
1291 }
1292 else
1293 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001295
1296 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001297}
1298
1299PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001300"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001301\n\
1302Return the size of object in bytes.");
1303
1304static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001305sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001306{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001308}
1309
Tim Peters4be93d02002-07-07 19:59:50 +00001310#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001311static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301312sys_gettotalrefcount(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Hammond440d8982000-06-20 08:12:48 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001315}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001316#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001317
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001318PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001319"getrefcount(object) -> integer\n\
1320\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001321Return the reference count of object. The count returned is generally\n\
1322one higher than you might expect, because it includes the (temporary)\n\
1323reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001324);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001325
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001326static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301327sys_getallocatedblocks(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001328{
1329 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1330}
1331
1332PyDoc_STRVAR(getallocatedblocks_doc,
1333"getallocatedblocks() -> integer\n\
1334\n\
1335Return the number of memory blocks currently allocated, regardless of their\n\
1336size."
1337);
1338
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001339#ifdef COUNT_ALLOCS
1340static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001341sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001342{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001343 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001344
Pablo Galindo49c75a82018-10-28 15:02:17 +00001345 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001346}
1347#endif
1348
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001349PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001350"_getframe([depth]) -> frameobject\n\
1351\n\
1352Return a frame object from the call stack. If optional integer depth is\n\
1353given, return the frame object that many calls below the top of the stack.\n\
1354If that is deeper than the call stack, ValueError is raised. The default\n\
1355for depth is zero, returning the frame at the top of the call stack.\n\
1356\n\
1357This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001358purposes only."
1359);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001360
1361static PyObject *
1362sys_getframe(PyObject *self, PyObject *args)
1363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001364 PyFrameObject *f = PyThreadState_GET()->frame;
1365 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001366
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001367 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1368 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 while (depth > 0 && f != NULL) {
1371 f = f->f_back;
1372 --depth;
1373 }
1374 if (f == NULL) {
1375 PyErr_SetString(PyExc_ValueError,
1376 "call stack is not deep enough");
1377 return NULL;
1378 }
1379 Py_INCREF(f);
1380 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001381}
1382
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001383PyDoc_STRVAR(current_frames_doc,
1384"_current_frames() -> dictionary\n\
1385\n\
1386Return a dictionary mapping each current thread T's thread id to T's\n\
1387current stack frame.\n\
1388\n\
1389This function should be used for specialized purposes only."
1390);
1391
1392static PyObject *
1393sys_current_frames(PyObject *self, PyObject *noargs)
1394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001395 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001396}
1397
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001398PyDoc_STRVAR(call_tracing_doc,
1399"call_tracing(func, args) -> object\n\
1400\n\
1401Call func(*args), while tracing is enabled. The tracing state is\n\
1402saved, and restored afterwards. This is intended to be called from\n\
1403a debugger from a checkpoint, to recursively debug some other code."
1404);
1405
1406static PyObject *
1407sys_call_tracing(PyObject *self, PyObject *args)
1408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001409 PyObject *func, *funcargs;
1410 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1411 return NULL;
1412 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001413}
1414
Jeremy Hylton985eba52003-02-05 23:13:00 +00001415PyDoc_STRVAR(callstats_doc,
1416"callstats() -> tuple of integers\n\
1417\n\
1418Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1419when Python was built. Otherwise, return None.\n\
1420\n\
1421When enabled, this function returns detailed, implementation-specific\n\
1422details about the number of function calls executed. The return value is\n\
1423a 11-tuple where the entries in the tuple are counts of:\n\
14240. all function calls\n\
14251. calls to PyFunction_Type objects\n\
14262. PyFunction calls that do not create an argument tuple\n\
14273. PyFunction calls that do not create an argument tuple\n\
1428 and bypass PyEval_EvalCodeEx()\n\
14294. PyMethod calls\n\
14305. PyMethod calls on bound methods\n\
14316. PyType calls\n\
14327. PyCFunction calls\n\
14338. generator calls\n\
14349. All other calls\n\
143510. Number of stack pops performed by call_function()"
1436);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001437
Victor Stinner048afd92016-11-28 11:59:04 +01001438static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301439sys_callstats(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner048afd92016-11-28 11:59:04 +01001440{
1441 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1442 "sys.callstats() has been deprecated in Python 3.7 "
1443 "and will be removed in the future", 1) < 0) {
1444 return NULL;
1445 }
1446
1447 Py_RETURN_NONE;
1448}
1449
1450
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001451#ifdef __cplusplus
1452extern "C" {
1453#endif
1454
David Malcolm49526f42012-06-22 14:55:41 -04001455static PyObject *
1456sys_debugmallocstats(PyObject *self, PyObject *args)
1457{
1458#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001459 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001460 fputc('\n', stderr);
1461 }
David Malcolm49526f42012-06-22 14:55:41 -04001462#endif
1463 _PyObject_DebugTypeStats(stderr);
1464
1465 Py_RETURN_NONE;
1466}
1467PyDoc_STRVAR(debugmallocstats_doc,
1468"_debugmallocstats()\n\
1469\n\
1470Print summary info to stderr about the state of\n\
1471pymalloc's structures.\n\
1472\n\
1473In Py_DEBUG mode, also perform some expensive internal consistency\n\
1474checks.\n\
1475");
1476
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001477#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001478/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001479extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001480#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001481
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001482#ifdef DYNAMIC_EXECUTION_PROFILE
1483/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001484extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001485#endif
1486
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001487#ifdef __cplusplus
1488}
1489#endif
1490
Christian Heimes15ebc882008-02-04 18:48:49 +00001491static PyObject *
1492sys_clear_type_cache(PyObject* self, PyObject* args)
1493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 PyType_ClearCache();
1495 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001496}
1497
1498PyDoc_STRVAR(sys_clear_type_cache__doc__,
1499"_clear_type_cache() -> None\n\
1500Clear the internal type lookup cache.");
1501
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001502static PyObject *
1503sys_is_finalizing(PyObject* self, PyObject* args)
1504{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001505 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001506}
1507
1508PyDoc_STRVAR(is_finalizing_doc,
1509"is_finalizing()\n\
1510Return True if Python is exiting.");
1511
Christian Heimes15ebc882008-02-04 18:48:49 +00001512
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001513#ifdef ANDROID_API_LEVEL
1514PyDoc_STRVAR(getandroidapilevel_doc,
1515"getandroidapilevel()\n\
1516\n\
1517Return the build time API version of Android as an integer.");
1518
1519static PyObject *
1520sys_getandroidapilevel(PyObject *self)
1521{
1522 return PyLong_FromLong(ANDROID_API_LEVEL);
1523}
1524#endif /* ANDROID_API_LEVEL */
1525
1526
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001527static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001529 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1530 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301531 {"callstats", sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 callstats_doc},
1533 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1534 sys_clear_type_cache__doc__},
1535 {"_current_frames", sys_current_frames, METH_NOARGS,
1536 current_frames_doc},
1537 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1538 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1539 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1540 {"exit", sys_exit, METH_VARARGS, exit_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301541 {"getdefaultencoding", sys_getdefaultencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001543#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1545 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001546#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301547 {"getallocatedblocks", sys_getallocatedblocks, METH_NOARGS,
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001548 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001549#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001551#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001552#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001554#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301555 {"getfilesystemencoding", sys_getfilesystemencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 METH_NOARGS, getfilesystemencoding_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301557 { "getfilesystemencodeerrors", sys_getfilesystemencodeerrors,
Steve Dowercc16be82016-09-08 10:35:16 -07001558 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001559#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001561#endif
1562#ifdef Py_REF_DEBUG
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301563 {"gettotalrefcount", sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001564#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301566 {"getrecursionlimit", sys_getrecursionlimit, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 getrecursionlimit_doc},
1568 {"getsizeof", (PyCFunction)sys_getsizeof,
1569 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1570 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001571#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1573 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001574 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1575 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001576#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001578 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001579#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001581#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1583 setcheckinterval_doc},
1584 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1585 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1587 setswitchinterval_doc},
1588 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1589 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001590#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1592 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001593#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1595 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1596 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1597 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 {"settrace", sys_settrace, METH_O, settrace_doc},
1599 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1600 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001601 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001602 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001603 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1604 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001605 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1606 set_coroutine_wrapper_doc},
1607 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1608 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001609 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001610 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1611 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1612 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001613#ifdef ANDROID_API_LEVEL
1614 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1615 getandroidapilevel_doc},
1616#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001617 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001618};
1619
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001620static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001621list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001622{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 PyObject *list = PyList_New(0);
1624 int i;
1625 if (list == NULL)
1626 return NULL;
1627 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1628 PyObject *name = PyUnicode_FromString(
1629 PyImport_Inittab[i].name);
1630 if (name == NULL)
1631 break;
1632 PyList_Append(list, name);
1633 Py_DECREF(name);
1634 }
1635 if (PyList_Sort(list) != 0) {
1636 Py_DECREF(list);
1637 list = NULL;
1638 }
1639 if (list) {
1640 PyObject *v = PyList_AsTuple(list);
1641 Py_DECREF(list);
1642 list = v;
1643 }
1644 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001645}
1646
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001647/* Pre-initialization support for sys.warnoptions and sys._xoptions
1648 *
1649 * Modern internal code paths:
1650 * These APIs get called after _Py_InitializeCore and get to use the
1651 * regular CPython list, dict, and unicode APIs.
1652 *
1653 * Legacy embedding code paths:
1654 * The multi-phase initialization API isn't public yet, so embedding
1655 * apps still need to be able configure sys.warnoptions and sys._xoptions
1656 * before they call Py_Initialize. To support this, we stash copies of
1657 * the supplied wchar * sequences in linked lists, and then migrate the
1658 * contents of those lists to the sys module in _PyInitializeCore.
1659 *
1660 */
1661
1662struct _preinit_entry {
1663 wchar_t *value;
1664 struct _preinit_entry *next;
1665};
1666
1667typedef struct _preinit_entry *_Py_PreInitEntry;
1668
1669static _Py_PreInitEntry _preinit_warnoptions = NULL;
1670static _Py_PreInitEntry _preinit_xoptions = NULL;
1671
1672static _Py_PreInitEntry
1673_alloc_preinit_entry(const wchar_t *value)
1674{
1675 /* To get this to work, we have to initialize the runtime implicitly */
1676 _PyRuntime_Initialize();
1677
1678 /* Force default allocator, so we can ensure that it also gets used to
1679 * destroy the linked list in _clear_preinit_entries.
1680 */
1681 PyMemAllocatorEx old_alloc;
1682 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1683
1684 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1685 if (node != NULL) {
1686 node->value = _PyMem_RawWcsdup(value);
1687 if (node->value == NULL) {
1688 PyMem_RawFree(node);
1689 node = NULL;
1690 };
1691 };
1692
1693 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1694 return node;
1695};
1696
1697static int
1698_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1699{
1700 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1701 if (new_entry == NULL) {
1702 return -1;
1703 }
1704 /* We maintain the linked list in this order so it's easy to play back
1705 * the add commands in the same order later on in _Py_InitializeCore
1706 */
1707 _Py_PreInitEntry last_entry = *optionlist;
1708 if (last_entry == NULL) {
1709 *optionlist = new_entry;
1710 } else {
1711 while (last_entry->next != NULL) {
1712 last_entry = last_entry->next;
1713 }
1714 last_entry->next = new_entry;
1715 }
1716 return 0;
1717};
1718
1719static void
1720_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1721{
1722 _Py_PreInitEntry current = *optionlist;
1723 *optionlist = NULL;
1724 /* Deallocate the nodes and their contents using the default allocator */
1725 PyMemAllocatorEx old_alloc;
1726 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1727 while (current != NULL) {
1728 _Py_PreInitEntry next = current->next;
1729 PyMem_RawFree(current->value);
1730 PyMem_RawFree(current);
1731 current = next;
1732 }
1733 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1734};
1735
1736static void
1737_clear_all_preinit_options(void)
1738{
1739 _clear_preinit_entries(&_preinit_warnoptions);
1740 _clear_preinit_entries(&_preinit_xoptions);
1741}
1742
1743static int
1744_PySys_ReadPreInitOptions(void)
1745{
1746 /* Rerun the add commands with the actual sys module available */
1747 PyThreadState *tstate = PyThreadState_GET();
1748 if (tstate == NULL) {
1749 /* Still don't have a thread state, so something is wrong! */
1750 return -1;
1751 }
1752 _Py_PreInitEntry entry = _preinit_warnoptions;
1753 while (entry != NULL) {
1754 PySys_AddWarnOption(entry->value);
1755 entry = entry->next;
1756 }
1757 entry = _preinit_xoptions;
1758 while (entry != NULL) {
1759 PySys_AddXOption(entry->value);
1760 entry = entry->next;
1761 }
1762
1763 _clear_all_preinit_options();
1764 return 0;
1765};
1766
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001767static PyObject *
1768get_warnoptions(void)
1769{
Eric Snowdae02762017-09-14 00:35:58 -07001770 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001771 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001772 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1773 * interpreter config. When that happens, we need to properly set
1774 * the `warnoptions` reference in the main interpreter config as well.
1775 *
1776 * For Python 3.7, we shouldn't be able to get here due to the
1777 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1778 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1779 * call optional for embedding applications, thus making this
1780 * reachable again.
1781 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001782 Py_XDECREF(warnoptions);
1783 warnoptions = PyList_New(0);
1784 if (warnoptions == NULL)
1785 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001786 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1787 Py_DECREF(warnoptions);
1788 return NULL;
1789 }
1790 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001791 }
1792 return warnoptions;
1793}
Guido van Rossum23fff912000-12-15 22:02:05 +00001794
1795void
1796PySys_ResetWarnOptions(void)
1797{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001798 PyThreadState *tstate = PyThreadState_GET();
1799 if (tstate == NULL) {
1800 _clear_preinit_entries(&_preinit_warnoptions);
1801 return;
1802 }
1803
Eric Snowdae02762017-09-14 00:35:58 -07001804 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 if (warnoptions == NULL || !PyList_Check(warnoptions))
1806 return;
1807 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001808}
1809
Victor Stinnere1b29952018-10-30 14:31:42 +01001810static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001811_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001812{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001813 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001814 if (warnoptions == NULL) {
1815 return -1;
1816 }
1817 if (PyList_Append(warnoptions, option)) {
1818 return -1;
1819 }
1820 return 0;
1821}
1822
1823void
1824PySys_AddWarnOptionUnicode(PyObject *option)
1825{
Victor Stinnere1b29952018-10-30 14:31:42 +01001826 if (_PySys_AddWarnOptionWithError(option) < 0) {
1827 /* No return value, therefore clear error state if possible */
1828 if (_PyThreadState_UncheckedGet()) {
1829 PyErr_Clear();
1830 }
1831 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001832}
1833
1834void
1835PySys_AddWarnOption(const wchar_t *s)
1836{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001837 PyThreadState *tstate = PyThreadState_GET();
1838 if (tstate == NULL) {
1839 _append_preinit_entry(&_preinit_warnoptions, s);
1840 return;
1841 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001842 PyObject *unicode;
1843 unicode = PyUnicode_FromWideChar(s, -1);
1844 if (unicode == NULL)
1845 return;
1846 PySys_AddWarnOptionUnicode(unicode);
1847 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001848}
1849
Christian Heimes33fe8092008-04-13 13:53:33 +00001850int
1851PySys_HasWarnOptions(void)
1852{
Eric Snowdae02762017-09-14 00:35:58 -07001853 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001854 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1855}
1856
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001857static PyObject *
1858get_xoptions(void)
1859{
Eric Snowdae02762017-09-14 00:35:58 -07001860 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001861 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001862 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1863 * interpreter config. When that happens, we need to properly set
1864 * the `xoptions` reference in the main interpreter config as well.
1865 *
1866 * For Python 3.7, we shouldn't be able to get here due to the
1867 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1868 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1869 * call optional for embedding applications, thus making this
1870 * reachable again.
1871 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001872 Py_XDECREF(xoptions);
1873 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001874 if (xoptions == NULL)
1875 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001876 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1877 Py_DECREF(xoptions);
1878 return NULL;
1879 }
1880 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001881 }
1882 return xoptions;
1883}
1884
Victor Stinnere1b29952018-10-30 14:31:42 +01001885static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001886_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001887{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001888 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001889
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001890 PyObject *opts = get_xoptions();
1891 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001892 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001893 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001894
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001895 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001896 if (!name_end) {
1897 name = PyUnicode_FromWideChar(s, -1);
1898 value = Py_True;
1899 Py_INCREF(value);
1900 }
1901 else {
1902 name = PyUnicode_FromWideChar(s, name_end - s);
1903 value = PyUnicode_FromWideChar(name_end + 1, -1);
1904 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001905 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001906 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001907 }
1908 if (PyDict_SetItem(opts, name, value) < 0) {
1909 goto error;
1910 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001911 Py_DECREF(name);
1912 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001913 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001914
1915error:
1916 Py_XDECREF(name);
1917 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001918 return -1;
1919}
1920
1921void
1922PySys_AddXOption(const wchar_t *s)
1923{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001924 PyThreadState *tstate = PyThreadState_GET();
1925 if (tstate == NULL) {
1926 _append_preinit_entry(&_preinit_xoptions, s);
1927 return;
1928 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001929 if (_PySys_AddXOptionWithError(s) < 0) {
1930 /* No return value, therefore clear error state if possible */
1931 if (_PyThreadState_UncheckedGet()) {
1932 PyErr_Clear();
1933 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001934 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001935}
1936
1937PyObject *
1938PySys_GetXOptions(void)
1939{
1940 return get_xoptions();
1941}
1942
Guido van Rossum40552d01998-08-06 03:34:39 +00001943/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1944 Two literals concatenated works just fine. If you have a K&R compiler
1945 or other abomination that however *does* understand longer strings,
1946 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001947PyDoc_VAR(sys_doc) =
1948PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001949"This module provides access to some objects used or maintained by the\n\
1950interpreter and to functions that interact strongly with the interpreter.\n\
1951\n\
1952Dynamic objects:\n\
1953\n\
1954argv -- command line arguments; argv[0] is the script pathname if known\n\
1955path -- module search path; path[0] is the script directory, else ''\n\
1956modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001957\n\
1958displayhook -- called to show results in an interactive session\n\
1959excepthook -- called to handle any uncaught exception other than SystemExit\n\
1960 To customize printing in an interactive session or to install a custom\n\
1961 top-level exception handler, assign other functions to replace these.\n\
1962\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001963stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001964stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001965stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001966 By assigning other file objects (or objects that behave like files)\n\
1967 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001968\n\
1969last_type -- type of last uncaught exception\n\
1970last_value -- value of last uncaught exception\n\
1971last_traceback -- traceback of last uncaught exception\n\
1972 These three are only available in an interactive session after a\n\
1973 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001974"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001975)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001976/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001977PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001978"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001979Static objects:\n\
1980\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001981builtin_module_names -- tuple of module names built into this interpreter\n\
1982copyright -- copyright notice pertaining to this interpreter\n\
1983exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001984executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001985float_info -- a struct sequence with information about the float implementation.\n\
1986float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001987hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001988hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001989implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001990int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001991maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001992maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001993platform -- platform identifier\n\
1994prefix -- prefix used to find the Python library\n\
1995thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001996version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001997version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001998"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001999)
Steve Dowercc16be82016-09-08 10:35:16 -07002000#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002001/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002002PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002003"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002004winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002005"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002006)
Steve Dowercc16be82016-09-08 10:35:16 -07002007#endif /* MS_COREDLL */
2008#ifdef MS_WINDOWS
2009/* concatenating string here */
2010PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002011"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002012"
2013)
2014#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002015PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002016"__stdin__ -- the original stdin; don't touch!\n\
2017__stdout__ -- the original stdout; don't touch!\n\
2018__stderr__ -- the original stderr; don't touch!\n\
2019__displayhook__ -- the original displayhook; don't touch!\n\
2020__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002021\n\
2022Functions:\n\
2023\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002024displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002025excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002026exc_info() -- return thread-safe information about the current exception\n\
2027exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002028getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002029getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002030getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002031getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002032getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002033gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002034setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002035setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002036setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002037setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002038settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002039"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002040)
Fred Drakeccede592000-08-14 20:59:57 +00002041/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002042
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002043
2044PyDoc_STRVAR(flags__doc__,
2045"sys.flags\n\
2046\n\
2047Flags provided through command line arguments or environment vars.");
2048
2049static PyTypeObject FlagsType;
2050
2051static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 {"inspect", "-i"},
2054 {"interactive", "-i"},
2055 {"optimize", "-O or -OO"},
2056 {"dont_write_bytecode", "-B"},
2057 {"no_user_site", "-s"},
2058 {"no_site", "-S"},
2059 {"ignore_environment", "-E"},
2060 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002061 /* {"unbuffered", "-u"}, */
2062 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002063 {"bytes_warning", "-b"},
2064 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002065 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002066 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002067 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002068 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002070};
2071
2072static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002073 "sys.flags", /* name */
2074 flags__doc__, /* doc */
2075 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002076 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002077};
2078
2079static PyObject*
2080make_flags(void)
2081{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 int pos = 0;
2083 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002084 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 seq = PyStructSequence_New(&FlagsType);
2087 if (seq == NULL)
2088 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002089
2090#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002092
Victor Stinnerfbca9082018-08-30 00:50:45 +02002093 SetFlag(config->parser_debug);
2094 SetFlag(config->inspect);
2095 SetFlag(config->interactive);
2096 SetFlag(config->optimization_level);
2097 SetFlag(!config->write_bytecode);
2098 SetFlag(!config->user_site_directory);
2099 SetFlag(!config->site_import);
2100 SetFlag(!config->use_environment);
2101 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002102 /* SetFlag(saw_unbuffered_flag); */
2103 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002104 SetFlag(config->bytes_warning);
2105 SetFlag(config->quiet);
2106 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2107 SetFlag(config->isolated);
2108 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2109 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002110#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002111
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002113 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 return NULL;
2115 }
2116 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002117}
2118
Eric Smith0e5b5622009-02-06 01:32:42 +00002119PyDoc_STRVAR(version_info__doc__,
2120"sys.version_info\n\
2121\n\
2122Version information as a named tuple.");
2123
2124static PyTypeObject VersionInfoType;
2125
2126static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 {"major", "Major release number"},
2128 {"minor", "Minor release number"},
2129 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002130 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 {"serial", "Serial release number"},
2132 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002133};
2134
2135static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 "sys.version_info", /* name */
2137 version_info__doc__, /* doc */
2138 version_info_fields, /* fields */
2139 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002140};
2141
2142static PyObject *
2143make_version_info(void)
2144{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002145 PyObject *version_info;
2146 char *s;
2147 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 version_info = PyStructSequence_New(&VersionInfoType);
2150 if (version_info == NULL) {
2151 return NULL;
2152 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 /*
2155 * These release level checks are mutually exclusive and cover
2156 * the field, so don't get too fancy with the pre-processor!
2157 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002158#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002160#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002162#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002163 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002164#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002166#endif
2167
2168#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002170#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002171 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002172
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002173 SetIntItem(PY_MAJOR_VERSION);
2174 SetIntItem(PY_MINOR_VERSION);
2175 SetIntItem(PY_MICRO_VERSION);
2176 SetStrItem(s);
2177 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002178#undef SetIntItem
2179#undef SetStrItem
2180
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 if (PyErr_Occurred()) {
2182 Py_CLEAR(version_info);
2183 return NULL;
2184 }
2185 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002186}
2187
Brett Cannon3adc7b72012-07-09 14:22:12 -04002188/* sys.implementation values */
2189#define NAME "cpython"
2190const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002191#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2192#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002193#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002194const char *_PySys_ImplCacheTag = TAG;
2195#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002196#undef MAJOR
2197#undef MINOR
2198#undef TAG
2199
Barry Warsaw409da152012-06-03 16:18:47 -04002200static PyObject *
2201make_impl_info(PyObject *version_info)
2202{
2203 int res;
2204 PyObject *impl_info, *value, *ns;
2205
2206 impl_info = PyDict_New();
2207 if (impl_info == NULL)
2208 return NULL;
2209
2210 /* populate the dict */
2211
Brett Cannon3adc7b72012-07-09 14:22:12 -04002212 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002213 if (value == NULL)
2214 goto error;
2215 res = PyDict_SetItemString(impl_info, "name", value);
2216 Py_DECREF(value);
2217 if (res < 0)
2218 goto error;
2219
Brett Cannon3adc7b72012-07-09 14:22:12 -04002220 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002221 if (value == NULL)
2222 goto error;
2223 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2224 Py_DECREF(value);
2225 if (res < 0)
2226 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002227
2228 res = PyDict_SetItemString(impl_info, "version", version_info);
2229 if (res < 0)
2230 goto error;
2231
2232 value = PyLong_FromLong(PY_VERSION_HEX);
2233 if (value == NULL)
2234 goto error;
2235 res = PyDict_SetItemString(impl_info, "hexversion", value);
2236 Py_DECREF(value);
2237 if (res < 0)
2238 goto error;
2239
doko@ubuntu.com55532312016-06-14 08:55:19 +02002240#ifdef MULTIARCH
2241 value = PyUnicode_FromString(MULTIARCH);
2242 if (value == NULL)
2243 goto error;
2244 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2245 Py_DECREF(value);
2246 if (res < 0)
2247 goto error;
2248#endif
2249
Barry Warsaw409da152012-06-03 16:18:47 -04002250 /* dict ready */
2251
2252 ns = _PyNamespace_New(impl_info);
2253 Py_DECREF(impl_info);
2254 return ns;
2255
2256error:
2257 Py_CLEAR(impl_info);
2258 return NULL;
2259}
2260
Martin v. Löwis1a214512008-06-11 05:26:20 +00002261static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002262 PyModuleDef_HEAD_INIT,
2263 "sys",
2264 sys_doc,
2265 -1, /* multiple "initialization" just copies the module dict. */
2266 sys_methods,
2267 NULL,
2268 NULL,
2269 NULL,
2270 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002271};
2272
Eric Snow6b4be192017-05-22 21:36:03 -07002273/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002274#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002275 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002276 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002277 if (v == NULL) { \
2278 goto err_occurred; \
2279 } \
Victor Stinner58049602013-07-22 22:40:00 +02002280 res = PyDict_SetItemString(sysdict, key, v); \
2281 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002282 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002283 } \
2284 } while (0)
2285#define SET_SYS_FROM_STRING(key, value) \
2286 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002287 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002288 if (v == NULL) { \
2289 goto err_occurred; \
2290 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002291 res = PyDict_SetItemString(sysdict, key, v); \
2292 Py_DECREF(v); \
2293 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002294 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002295 } \
2296 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002297
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002298
2299_PyInitError
2300_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002301{
2302 PyObject *m, *sysdict, *version_info;
2303 int res;
2304
Eric Snowd393c1b2017-09-14 12:18:12 -06002305 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002306 if (m == NULL) {
2307 return _Py_INIT_ERR("failed to create a module object");
2308 }
Eric Snow6b4be192017-05-22 21:36:03 -07002309 sysdict = PyModule_GetDict(m);
2310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002311 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002312 Using shell redirection, you can redirect stdin to a directory,
2313 crashing the Python interpreter. Catch this common mistake here
2314 and output a useful error message. Note that under MS Windows,
2315 the shell already prevents that. */
2316#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002317 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002318 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002319 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002321 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2322 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 }
2324 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002325#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002326
Nick Coghland6009512014-11-20 21:39:37 +10002327 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002328
Victor Stinner8fea2522013-10-27 17:15:42 +01002329 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2330 PyDict_GetItemString(sysdict, "displayhook"));
2331 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2332 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002333 SET_SYS_FROM_STRING_BORROW(
2334 "__breakpointhook__",
2335 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 SET_SYS_FROM_STRING("version",
2337 PyUnicode_FromString(Py_GetVersion()));
2338 SET_SYS_FROM_STRING("hexversion",
2339 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002340 SET_SYS_FROM_STRING("_git",
2341 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2342 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002343 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002344 SET_SYS_FROM_STRING("api_version",
2345 PyLong_FromLong(PYTHON_API_VERSION));
2346 SET_SYS_FROM_STRING("copyright",
2347 PyUnicode_FromString(Py_GetCopyright()));
2348 SET_SYS_FROM_STRING("platform",
2349 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 SET_SYS_FROM_STRING("maxsize",
2351 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2352 SET_SYS_FROM_STRING("float_info",
2353 PyFloat_GetInfo());
2354 SET_SYS_FROM_STRING("int_info",
2355 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002356 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002357 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002358 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2359 goto type_init_failed;
2360 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002361 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002362 SET_SYS_FROM_STRING("hash_info",
2363 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002365 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002366 SET_SYS_FROM_STRING("builtin_module_names",
2367 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002368#if PY_BIG_ENDIAN
2369 SET_SYS_FROM_STRING("byteorder",
2370 PyUnicode_FromString("big"));
2371#else
2372 SET_SYS_FROM_STRING("byteorder",
2373 PyUnicode_FromString("little"));
2374#endif
Fred Drake099325e2000-08-14 15:47:03 +00002375
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002376#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002377 SET_SYS_FROM_STRING("dllhandle",
2378 PyLong_FromVoidPtr(PyWin_DLLhModule));
2379 SET_SYS_FROM_STRING("winver",
2380 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002381#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002382#ifdef ABIFLAGS
2383 SET_SYS_FROM_STRING("abiflags",
2384 PyUnicode_FromString(ABIFLAGS));
2385#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002386
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002388 if (VersionInfoType.tp_name == NULL) {
2389 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002390 &version_info_desc) < 0) {
2391 goto type_init_failed;
2392 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002393 }
Barry Warsaw409da152012-06-03 16:18:47 -04002394 version_info = make_version_info();
2395 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 /* prevent user from creating new instances */
2397 VersionInfoType.tp_init = NULL;
2398 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002399 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2400 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2401 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002402
Barry Warsaw409da152012-06-03 16:18:47 -04002403 /* implementation */
2404 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002407 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002408 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2409 goto type_init_failed;
2410 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002411 }
Eric Snow6b4be192017-05-22 21:36:03 -07002412 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002414
2415#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 /* getwindowsversion */
2417 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002418 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002419 &windows_version_desc) < 0) {
2420 goto type_init_failed;
2421 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 /* prevent user from creating new instances */
2423 WindowsVersionType.tp_init = NULL;
2424 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002425 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002426 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002427 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002428 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002429 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002430#endif
2431
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002433#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 SET_SYS_FROM_STRING("float_repr_style",
2435 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002436#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 SET_SYS_FROM_STRING("float_repr_style",
2438 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002439#endif
2440
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002441 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002442
Yury Selivanoveb636452016-09-08 22:01:51 -07002443 /* initialize asyncgen_hooks */
2444 if (AsyncGenHooksType.tp_name == NULL) {
2445 if (PyStructSequence_InitType2(
2446 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002447 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002448 }
2449 }
2450
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002451 if (PyErr_Occurred()) {
2452 goto err_occurred;
2453 }
2454
2455 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002456
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002457 return _Py_INIT_OK();
2458
2459type_init_failed:
2460 return _Py_INIT_ERR("failed to initialize a type");
2461
2462err_occurred:
2463 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002464}
2465
Eric Snow6b4be192017-05-22 21:36:03 -07002466#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002467
2468/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002469#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2470 do { \
2471 PyObject *v = (value); \
2472 if (v == NULL) \
2473 return -1; \
2474 res = PyDict_SetItemString(sysdict, key, v); \
2475 Py_DECREF(v); \
2476 if (res < 0) { \
2477 return res; \
2478 } \
2479 } while (0)
2480
2481int
Victor Stinnerfbca9082018-08-30 00:50:45 +02002482_PySys_EndInit(PyObject *sysdict, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002483{
Victor Stinnerfbca9082018-08-30 00:50:45 +02002484 const _PyCoreConfig *core_config = &interp->core_config;
2485 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002486 int res;
2487
Victor Stinner41264f12017-12-15 02:05:29 +01002488 /* _PyMainInterpreterConfig_Read() must set all these variables */
2489 assert(config->module_search_path != NULL);
2490 assert(config->executable != NULL);
2491 assert(config->prefix != NULL);
2492 assert(config->base_prefix != NULL);
2493 assert(config->exec_prefix != NULL);
2494 assert(config->base_exec_prefix != NULL);
2495
2496 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
2497 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2498 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2499 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2500 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2501 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2502
Carl Meyerb193fa92018-06-15 22:40:56 -06002503 if (config->pycache_prefix != NULL) {
2504 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2505 } else {
2506 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2507 }
2508
Victor Stinner41264f12017-12-15 02:05:29 +01002509 if (config->argv != NULL) {
2510 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2511 }
2512 if (config->warnoptions != NULL) {
2513 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
2514 }
2515 if (config->xoptions != NULL) {
2516 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
2517 }
2518
Eric Snow6b4be192017-05-22 21:36:03 -07002519 /* Set flags to their final values */
2520 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2521 /* prevent user from creating new instances */
2522 FlagsType.tp_init = NULL;
2523 FlagsType.tp_new = NULL;
2524 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2525 if (res < 0) {
2526 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2527 return res;
2528 }
2529 PyErr_Clear();
2530 }
2531
2532 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002533 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002534
Eric Snowdae02762017-09-14 00:35:58 -07002535 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002536 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002537
Eric Snowdae02762017-09-14 00:35:58 -07002538 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002539 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002540
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002541 /* Transfer any sys.warnoptions and sys._xoptions set directly
2542 * by an embedding application from the linked list to the module. */
2543 if (_PySys_ReadPreInitOptions() != 0)
2544 return -1;
2545
Eric Snow6b4be192017-05-22 21:36:03 -07002546 if (PyErr_Occurred())
2547 return -1;
2548 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002549
2550err_occurred:
2551 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002552}
2553
Victor Stinner41264f12017-12-15 02:05:29 +01002554#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002555#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002556
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002557static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002558makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 int i, n;
2561 const wchar_t *p;
2562 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002564 n = 1;
2565 p = path;
2566 while ((p = wcschr(p, delim)) != NULL) {
2567 n++;
2568 p++;
2569 }
2570 v = PyList_New(n);
2571 if (v == NULL)
2572 return NULL;
2573 for (i = 0; ; i++) {
2574 p = wcschr(path, delim);
2575 if (p == NULL)
2576 p = path + wcslen(path); /* End of string */
2577 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2578 if (w == NULL) {
2579 Py_DECREF(v);
2580 return NULL;
2581 }
2582 PyList_SetItem(v, i, w);
2583 if (*p == '\0')
2584 break;
2585 path = p+1;
2586 }
2587 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002588}
2589
2590void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002591PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 PyObject *v;
2594 if ((v = makepathobject(path, DELIM)) == NULL)
2595 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002596 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 Py_FatalError("can't assign sys.path");
2598 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002599}
2600
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002601static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002602makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002604 PyObject *av;
2605 if (argc <= 0 || argv == NULL) {
2606 /* Ensure at least one (empty) argument is seen */
2607 static wchar_t *empty_argv[1] = {L""};
2608 argv = empty_argv;
2609 argc = 1;
2610 }
2611 av = PyList_New(argc);
2612 if (av != NULL) {
2613 int i;
2614 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002615 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 if (v == NULL) {
2617 Py_DECREF(av);
2618 av = NULL;
2619 break;
2620 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002621 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 }
2623 }
2624 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002625}
2626
Victor Stinner11a247d2017-12-13 21:05:57 +01002627void
2628PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002629{
2630 PyObject *av = makeargvobject(argc, argv);
2631 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002632 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002633 }
2634 if (PySys_SetObject("argv", av) != 0) {
2635 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002636 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002637 }
2638 Py_DECREF(av);
2639
2640 if (updatepath) {
2641 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2642 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002643 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2644 if (argv0 == NULL) {
2645 Py_FatalError("can't compute path0 from argv");
2646 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002647
Victor Stinner11a247d2017-12-13 21:05:57 +01002648 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2649 if (sys_path != NULL) {
2650 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2651 Py_DECREF(argv0);
2652 Py_FatalError("can't prepend path0 to sys.path");
2653 }
2654 }
2655 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002656 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002657}
Guido van Rossuma890e681998-05-12 14:59:24 +00002658
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002659void
2660PySys_SetArgv(int argc, wchar_t **argv)
2661{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002662 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002663}
2664
Victor Stinner14284c22010-04-23 12:02:30 +00002665/* Reimplementation of PyFile_WriteString() no calling indirectly
2666 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2667
2668static int
Victor Stinner79766632010-08-16 17:36:42 +00002669sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002670{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002671 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002673
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002674 if (file == NULL)
2675 return -1;
2676
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002677 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002678 if (writer == NULL)
2679 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002680
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002681 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002682 if (result == NULL) {
2683 goto error;
2684 } else {
2685 err = 0;
2686 goto finally;
2687 }
Victor Stinner14284c22010-04-23 12:02:30 +00002688
2689error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002690 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002691finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 Py_XDECREF(result);
2694 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002695}
2696
Victor Stinner79766632010-08-16 17:36:42 +00002697static int
2698sys_pyfile_write(const char *text, PyObject *file)
2699{
2700 PyObject *unicode = NULL;
2701 int err;
2702
2703 if (file == NULL)
2704 return -1;
2705
2706 unicode = PyUnicode_FromString(text);
2707 if (unicode == NULL)
2708 return -1;
2709
2710 err = sys_pyfile_write_unicode(unicode, file);
2711 Py_DECREF(unicode);
2712 return err;
2713}
Guido van Rossuma890e681998-05-12 14:59:24 +00002714
2715/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2716 Adapted from code submitted by Just van Rossum.
2717
2718 PySys_WriteStdout(format, ...)
2719 PySys_WriteStderr(format, ...)
2720
2721 The first function writes to sys.stdout; the second to sys.stderr. When
2722 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002723 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002724
Victor Stinner14284c22010-04-23 12:02:30 +00002725 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002726 signal handlers: they may raise a new exception whereas sys_write()
2727 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002728
Guido van Rossuma890e681998-05-12 14:59:24 +00002729 Both take a printf-style format string as their first argument followed
2730 by a variable length argument list determined by the format string.
2731
2732 *** WARNING ***
2733
2734 The format should limit the total size of the formatted output string to
2735 1000 bytes. In particular, this means that no unrestricted "%s" formats
2736 should occur; these should be limited using "%.<N>s where <N> is a
2737 decimal number calculated so that <N> plus the maximum size of other
2738 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2739 which can print hundreds of digits for very large numbers.
2740
2741 */
2742
2743static void
Victor Stinner09054372013-11-06 22:41:44 +01002744sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002745{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 PyObject *file;
2747 PyObject *error_type, *error_value, *error_traceback;
2748 char buffer[1001];
2749 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002752 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2754 if (sys_pyfile_write(buffer, file) != 0) {
2755 PyErr_Clear();
2756 fputs(buffer, fp);
2757 }
2758 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2759 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002760 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 }
2763 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002764}
2765
2766void
Guido van Rossuma890e681998-05-12 14:59:24 +00002767PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002770
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002771 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002772 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002774}
2775
2776void
Guido van Rossuma890e681998-05-12 14:59:24 +00002777PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002779 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002780
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002782 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002783 va_end(va);
2784}
2785
2786static void
Victor Stinner09054372013-11-06 22:41:44 +01002787sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002788{
2789 PyObject *file, *message;
2790 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002791 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002792
2793 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002794 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002795 message = PyUnicode_FromFormatV(format, va);
2796 if (message != NULL) {
2797 if (sys_pyfile_write_unicode(message, file) != 0) {
2798 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002799 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002800 if (utf8 != NULL)
2801 fputs(utf8, fp);
2802 }
2803 Py_DECREF(message);
2804 }
2805 PyErr_Restore(error_type, error_value, error_traceback);
2806}
2807
2808void
2809PySys_FormatStdout(const char *format, ...)
2810{
2811 va_list va;
2812
2813 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002814 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002815 va_end(va);
2816}
2817
2818void
2819PySys_FormatStderr(const char *format, ...)
2820{
2821 va_list va;
2822
2823 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002824 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002825 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002826}