blob: 177b8307626d644c9ffea021ebdd856da8ac204a [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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 if (Py_FileSystemDefaultEncoding)
393 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200394 PyErr_SetString(PyExc_RuntimeError,
395 "filesystem encoding is not initialized");
396 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000397}
398
399PyDoc_STRVAR(getfilesystemencoding_doc,
400"getfilesystemencoding() -> string\n\
401\n\
402Return the encoding used to convert Unicode filenames in\n\
403operating system filenames."
404);
405
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000406static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530407sys_getfilesystemencodeerrors(PyObject *self, PyObject *Py_UNUSED(ignored))
Steve Dowercc16be82016-09-08 10:35:16 -0700408{
409 if (Py_FileSystemDefaultEncodeErrors)
410 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
411 PyErr_SetString(PyExc_RuntimeError,
412 "filesystem encoding is not initialized");
413 return NULL;
414}
415
416PyDoc_STRVAR(getfilesystemencodeerrors_doc,
417 "getfilesystemencodeerrors() -> string\n\
418\n\
419Return the error mode used to convert Unicode filenames in\n\
420operating system filenames."
421);
422
423static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000424sys_intern(PyObject *self, PyObject *args)
425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyObject *s;
427 if (!PyArg_ParseTuple(args, "U:intern", &s))
428 return NULL;
429 if (PyUnicode_CheckExact(s)) {
430 Py_INCREF(s);
431 PyUnicode_InternInPlace(&s);
432 return s;
433 }
434 else {
435 PyErr_Format(PyExc_TypeError,
436 "can't intern %.400s", s->ob_type->tp_name);
437 return NULL;
438 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000439}
440
441PyDoc_STRVAR(intern_doc,
442"intern(string) -> string\n\
443\n\
444``Intern'' the given string. This enters the string in the (global)\n\
445table of interned strings whose purpose is to speed up dictionary lookups.\n\
446Return the string itself or the previously interned string object with the\n\
447same value.");
448
449
Fred Drake5755ce62001-06-27 19:19:46 +0000450/*
451 * Cached interned string objects used for calling the profile and
452 * trace functions. Initialized by trace_init().
453 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000454static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000455
456static int
457trace_init(void)
458{
Nick Coghlan5a851672017-09-08 10:14:16 +1000459 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200460 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000461 "c_call", "c_exception", "c_return",
462 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200463 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 PyObject *name;
465 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000466 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 if (whatstrings[i] == NULL) {
468 name = PyUnicode_InternFromString(whatnames[i]);
469 if (name == NULL)
470 return -1;
471 whatstrings[i] = name;
472 }
473 }
474 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000475}
476
477
478static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100479call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000481{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200483 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000484
Victor Stinner78da82b2016-08-20 01:22:57 +0200485 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200487 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100488
Victor Stinner78da82b2016-08-20 01:22:57 +0200489 stack[0] = (PyObject *)frame;
490 stack[1] = whatstrings[what];
491 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000492
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200494 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000495
Victor Stinner78da82b2016-08-20 01:22:57 +0200496 PyFrame_LocalsToFast(frame, 1);
497 if (result == NULL) {
498 PyTraceBack_Here(frame);
499 }
500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000502}
503
504static int
505profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000507{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (arg == NULL)
511 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100512 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (result == NULL) {
514 PyEval_SetProfile(NULL, NULL);
515 return -1;
516 }
517 Py_DECREF(result);
518 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000519}
520
521static int
522trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyObject *callback;
526 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 if (what == PyTrace_CALL)
529 callback = self;
530 else
531 callback = frame->f_trace;
532 if (callback == NULL)
533 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100534 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (result == NULL) {
536 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200537 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 return -1;
539 }
540 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300541 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 }
543 else {
544 Py_DECREF(result);
545 }
546 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000547}
Fred Draked0838392001-06-16 21:02:31 +0000548
Fred Drake8b4d01d2000-05-09 19:57:01 +0000549static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000550sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (trace_init() == -1)
553 return NULL;
554 if (args == Py_None)
555 PyEval_SetTrace(NULL, NULL);
556 else
557 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200558 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000559}
560
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000561PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000562"settrace(function)\n\
563\n\
564Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000565function call. See the debugger chapter in the library manual."
566);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000567
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000568static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000569sys_gettrace(PyObject *self, PyObject *args)
570{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 PyThreadState *tstate = PyThreadState_GET();
572 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (temp == NULL)
575 temp = Py_None;
576 Py_INCREF(temp);
577 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000578}
579
580PyDoc_STRVAR(gettrace_doc,
581"gettrace()\n\
582\n\
583Return the global debug tracing function set with sys.settrace.\n\
584See the debugger chapter in the library manual."
585);
586
587static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000588sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000589{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000590 if (trace_init() == -1)
591 return NULL;
592 if (args == Py_None)
593 PyEval_SetProfile(NULL, NULL);
594 else
595 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200596 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000597}
598
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000599PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000600"setprofile(function)\n\
601\n\
602Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000603and return. See the profiler chapter in the library manual."
604);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000605
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000606static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000607sys_getprofile(PyObject *self, PyObject *args)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyThreadState *tstate = PyThreadState_GET();
610 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (temp == NULL)
613 temp = Py_None;
614 Py_INCREF(temp);
615 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000616}
617
618PyDoc_STRVAR(getprofile_doc,
619"getprofile()\n\
620\n\
621Return the profiling function set with sys.setprofile.\n\
622See the profiler chapter in the library manual."
623);
624
625static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000626sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000627{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (PyErr_WarnEx(PyExc_DeprecationWarning,
629 "sys.getcheckinterval() and sys.setcheckinterval() "
630 "are deprecated. Use sys.setswitchinterval() "
631 "instead.", 1) < 0)
632 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200633
634 int check_interval;
635 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200637
638 PyInterpreterState *interp = _PyInterpreterState_Get();
639 interp->check_interval = check_interval;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200640 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000641}
642
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000643PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000644"setcheckinterval(n)\n\
645\n\
646Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000647n instructions. This also affects how often thread switches occur."
648);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000649
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000650static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000651sys_getcheckinterval(PyObject *self, PyObject *args)
652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 if (PyErr_WarnEx(PyExc_DeprecationWarning,
654 "sys.getcheckinterval() and sys.setcheckinterval() "
655 "are deprecated. Use sys.getswitchinterval() "
656 "instead.", 1) < 0)
657 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200658 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600659 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000660}
661
662PyDoc_STRVAR(getcheckinterval_doc,
663"getcheckinterval() -> current check interval; see setcheckinterval()."
664);
665
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000666static PyObject *
667sys_setswitchinterval(PyObject *self, PyObject *args)
668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 double d;
670 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
671 return NULL;
672 if (d <= 0.0) {
673 PyErr_SetString(PyExc_ValueError,
674 "switch interval must be strictly positive");
675 return NULL;
676 }
677 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200678 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000679}
680
681PyDoc_STRVAR(setswitchinterval_doc,
682"setswitchinterval(n)\n\
683\n\
684Set the ideal thread switching delay inside the Python interpreter\n\
685The actual frequency of switching threads can be lower if the\n\
686interpreter executes long sequences of uninterruptible code\n\
687(this is implementation-specific and workload-dependent).\n\
688\n\
689The parameter must represent the desired switching delay in seconds\n\
690A typical value is 0.005 (5 milliseconds)."
691);
692
693static PyObject *
694sys_getswitchinterval(PyObject *self, PyObject *args)
695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000697}
698
699PyDoc_STRVAR(getswitchinterval_doc,
700"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
701);
702
Tim Peterse5e065b2003-07-06 18:36:54 +0000703static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000704sys_setrecursionlimit(PyObject *self, PyObject *args)
705{
Victor Stinner50856d52015-10-13 00:11:21 +0200706 int new_limit, mark;
707 PyThreadState *tstate;
708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
710 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200711
712 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200714 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 return NULL;
716 }
Victor Stinner50856d52015-10-13 00:11:21 +0200717
718 /* Issue #25274: When the recursion depth hits the recursion limit in
719 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
720 set to 1 and a RecursionError is raised. The overflowed flag is reset
721 to 0 when the recursion depth goes below the low-water mark: see
722 Py_LeaveRecursiveCall().
723
724 Reject too low new limit if the current recursion depth is higher than
725 the new low-water mark. Otherwise it may not be possible anymore to
726 reset the overflowed flag to 0. */
727 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
728 tstate = PyThreadState_GET();
729 if (tstate->recursion_depth >= mark) {
730 PyErr_Format(PyExc_RecursionError,
731 "cannot set the recursion limit to %i at "
732 "the recursion depth %i: the limit is too low",
733 new_limit, tstate->recursion_depth);
734 return NULL;
735 }
736
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000737 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200738 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000739}
740
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800741/*[clinic input]
742sys.set_coroutine_origin_tracking_depth
743
744 depth: int
745
746Enable or disable origin tracking for coroutine objects in this thread.
747
748Coroutine objects will track 'depth' frames of traceback information about
749where they came from, available in their cr_origin attribute. Set depth of 0
750to disable.
751[clinic start generated code]*/
752
753static PyObject *
754sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
755/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
756{
757 if (depth < 0) {
758 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
759 return NULL;
760 }
761 _PyEval_SetCoroutineOriginTrackingDepth(depth);
762 Py_RETURN_NONE;
763}
764
765/*[clinic input]
766sys.get_coroutine_origin_tracking_depth -> int
767
768Check status of origin tracking for coroutine objects in this thread.
769[clinic start generated code]*/
770
771static int
772sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
773/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
774{
775 return _PyEval_GetCoroutineOriginTrackingDepth();
776}
777
Yury Selivanov75445082015-05-11 22:57:16 -0400778static PyObject *
779sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
780{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800781 if (PyErr_WarnEx(PyExc_DeprecationWarning,
782 "set_coroutine_wrapper is deprecated", 1) < 0) {
783 return NULL;
784 }
785
Yury Selivanov75445082015-05-11 22:57:16 -0400786 if (wrapper != Py_None) {
787 if (!PyCallable_Check(wrapper)) {
788 PyErr_Format(PyExc_TypeError,
789 "callable expected, got %.50s",
790 Py_TYPE(wrapper)->tp_name);
791 return NULL;
792 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400793 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400794 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400795 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400796 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400797 }
Yury Selivanov75445082015-05-11 22:57:16 -0400798 Py_RETURN_NONE;
799}
800
801PyDoc_STRVAR(set_coroutine_wrapper_doc,
802"set_coroutine_wrapper(wrapper)\n\
803\n\
804Set a wrapper for coroutine objects."
805);
806
807static PyObject *
808sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
809{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800810 if (PyErr_WarnEx(PyExc_DeprecationWarning,
811 "get_coroutine_wrapper is deprecated", 1) < 0) {
812 return NULL;
813 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400814 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400815 if (wrapper == NULL) {
816 wrapper = Py_None;
817 }
818 Py_INCREF(wrapper);
819 return wrapper;
820}
821
822PyDoc_STRVAR(get_coroutine_wrapper_doc,
823"get_coroutine_wrapper()\n\
824\n\
825Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
826);
827
828
Yury Selivanoveb636452016-09-08 22:01:51 -0700829static PyTypeObject AsyncGenHooksType;
830
831PyDoc_STRVAR(asyncgen_hooks_doc,
832"asyncgen_hooks\n\
833\n\
834A struct sequence providing information about asynhronous\n\
835generators hooks. The attributes are read only.");
836
837static PyStructSequence_Field asyncgen_hooks_fields[] = {
838 {"firstiter", "Hook to intercept first iteration"},
839 {"finalizer", "Hook to intercept finalization"},
840 {0}
841};
842
843static PyStructSequence_Desc asyncgen_hooks_desc = {
844 "asyncgen_hooks", /* name */
845 asyncgen_hooks_doc, /* doc */
846 asyncgen_hooks_fields , /* fields */
847 2
848};
849
850
851static PyObject *
852sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
853{
854 static char *keywords[] = {"firstiter", "finalizer", NULL};
855 PyObject *firstiter = NULL;
856 PyObject *finalizer = NULL;
857
858 if (!PyArg_ParseTupleAndKeywords(
859 args, kw, "|OO", keywords,
860 &firstiter, &finalizer)) {
861 return NULL;
862 }
863
864 if (finalizer && finalizer != Py_None) {
865 if (!PyCallable_Check(finalizer)) {
866 PyErr_Format(PyExc_TypeError,
867 "callable finalizer expected, got %.50s",
868 Py_TYPE(finalizer)->tp_name);
869 return NULL;
870 }
871 _PyEval_SetAsyncGenFinalizer(finalizer);
872 }
873 else if (finalizer == Py_None) {
874 _PyEval_SetAsyncGenFinalizer(NULL);
875 }
876
877 if (firstiter && firstiter != Py_None) {
878 if (!PyCallable_Check(firstiter)) {
879 PyErr_Format(PyExc_TypeError,
880 "callable firstiter expected, got %.50s",
881 Py_TYPE(firstiter)->tp_name);
882 return NULL;
883 }
884 _PyEval_SetAsyncGenFirstiter(firstiter);
885 }
886 else if (firstiter == Py_None) {
887 _PyEval_SetAsyncGenFirstiter(NULL);
888 }
889
890 Py_RETURN_NONE;
891}
892
893PyDoc_STRVAR(set_asyncgen_hooks_doc,
894"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
895\n\
896Set a finalizer for async generators objects."
897);
898
899static PyObject *
900sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
901{
902 PyObject *res;
903 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
904 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
905
906 res = PyStructSequence_New(&AsyncGenHooksType);
907 if (res == NULL) {
908 return NULL;
909 }
910
911 if (firstiter == NULL) {
912 firstiter = Py_None;
913 }
914
915 if (finalizer == NULL) {
916 finalizer = Py_None;
917 }
918
919 Py_INCREF(firstiter);
920 PyStructSequence_SET_ITEM(res, 0, firstiter);
921
922 Py_INCREF(finalizer);
923 PyStructSequence_SET_ITEM(res, 1, finalizer);
924
925 return res;
926}
927
928PyDoc_STRVAR(get_asyncgen_hooks_doc,
929"get_asyncgen_hooks()\n\
930\n\
931Return a namedtuple of installed asynchronous generators hooks \
932(firstiter, finalizer)."
933);
934
935
Mark Dickinsondc787d22010-05-23 13:33:13 +0000936static PyTypeObject Hash_InfoType;
937
938PyDoc_STRVAR(hash_info_doc,
939"hash_info\n\
940\n\
941A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100942hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000943
944static PyStructSequence_Field hash_info_fields[] = {
945 {"width", "width of the type used for hashing, in bits"},
946 {"modulus", "prime number giving the modulus on which the hash "
947 "function is based"},
948 {"inf", "value to be used for hash of a positive infinity"},
949 {"nan", "value to be used for hash of a nan"},
950 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100951 {"algorithm", "name of the algorithm for hashing of str, bytes and "
952 "memoryviews"},
953 {"hash_bits", "internal output size of hash algorithm"},
954 {"seed_bits", "seed size of hash algorithm"},
955 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000956 {NULL, NULL}
957};
958
959static PyStructSequence_Desc hash_info_desc = {
960 "sys.hash_info",
961 hash_info_doc,
962 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100963 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000964};
965
Matthias Klosed885e952010-07-06 10:53:30 +0000966static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000967get_hash_info(void)
968{
969 PyObject *hash_info;
970 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100971 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000972 hash_info = PyStructSequence_New(&Hash_InfoType);
973 if (hash_info == NULL)
974 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100975 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000976 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000977 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000978 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000979 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000980 PyStructSequence_SET_ITEM(hash_info, field++,
981 PyLong_FromLong(_PyHASH_INF));
982 PyStructSequence_SET_ITEM(hash_info, field++,
983 PyLong_FromLong(_PyHASH_NAN));
984 PyStructSequence_SET_ITEM(hash_info, field++,
985 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100986 PyStructSequence_SET_ITEM(hash_info, field++,
987 PyUnicode_FromString(hashfunc->name));
988 PyStructSequence_SET_ITEM(hash_info, field++,
989 PyLong_FromLong(hashfunc->hash_bits));
990 PyStructSequence_SET_ITEM(hash_info, field++,
991 PyLong_FromLong(hashfunc->seed_bits));
992 PyStructSequence_SET_ITEM(hash_info, field++,
993 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000994 if (PyErr_Occurred()) {
995 Py_CLEAR(hash_info);
996 return NULL;
997 }
998 return hash_info;
999}
1000
1001
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001002PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001003"setrecursionlimit(n)\n\
1004\n\
1005Set the maximum depth of the Python interpreter stack to n. This\n\
1006limit prevents infinite recursion from causing an overflow of the C\n\
1007stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001008dependent."
1009);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001010
1011static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301012sys_getrecursionlimit(PyObject *self, PyObject *Py_UNUSED(ignored))
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001015}
1016
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001017PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001018"getrecursionlimit()\n\
1019\n\
1020Return the current value of the recursion limit, the maximum depth\n\
1021of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001022recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001023);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001024
Mark Hammond8696ebc2002-10-08 02:44:31 +00001025#ifdef MS_WINDOWS
1026PyDoc_STRVAR(getwindowsversion_doc,
1027"getwindowsversion()\n\
1028\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001029Return information about the running version of Windows as a named tuple.\n\
1030The members are named: major, minor, build, platform, service_pack,\n\
1031service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001032backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001033All elements are numbers, except service_pack and platform_type which are\n\
1034strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1035Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1036server. Platform_version is a 3-tuple containing a version number that is\n\
1037intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001038);
1039
Eric Smithf7bb5782010-01-27 00:44:57 +00001040static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1041
1042static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001043 {"major", "Major version number"},
1044 {"minor", "Minor version number"},
1045 {"build", "Build number"},
1046 {"platform", "Operating system platform"},
1047 {"service_pack", "Latest Service Pack installed on the system"},
1048 {"service_pack_major", "Service Pack major version number"},
1049 {"service_pack_minor", "Service Pack minor version number"},
1050 {"suite_mask", "Bit mask identifying available product suites"},
1051 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001052 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001054};
1055
1056static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001057 "sys.getwindowsversion", /* name */
1058 getwindowsversion_doc, /* doc */
1059 windows_version_fields, /* fields */
1060 5 /* For backward compatibility,
1061 only the first 5 items are accessible
1062 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001063};
1064
Steve Dower3e96f322015-03-02 08:01:10 -08001065/* Disable deprecation warnings about GetVersionEx as the result is
1066 being passed straight through to the caller, who is responsible for
1067 using it correctly. */
1068#pragma warning(push)
1069#pragma warning(disable:4996)
1070
Mark Hammond8696ebc2002-10-08 02:44:31 +00001071static PyObject *
1072sys_getwindowsversion(PyObject *self)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 PyObject *version;
1075 int pos = 0;
1076 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001077 DWORD realMajor, realMinor, realBuild;
1078 HANDLE hKernel32;
1079 wchar_t kernel32_path[MAX_PATH];
1080 LPVOID verblock;
1081 DWORD verblock_size;
1082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 ver.dwOSVersionInfoSize = sizeof(ver);
1084 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1085 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 version = PyStructSequence_New(&WindowsVersionType);
1088 if (version == NULL)
1089 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001090
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1092 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1093 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1094 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1095 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1096 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1097 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1098 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1099 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001100
Steve Dower74f4af72016-09-17 17:27:48 -07001101 realMajor = ver.dwMajorVersion;
1102 realMinor = ver.dwMinorVersion;
1103 realBuild = ver.dwBuildNumber;
1104
1105 // GetVersion will lie if we are running in a compatibility mode.
1106 // We need to read the version info from a system file resource
1107 // to accurately identify the OS version. If we fail for any reason,
1108 // just return whatever GetVersion said.
1109 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1110 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1111 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1112 (verblock = PyMem_RawMalloc(verblock_size))) {
1113 VS_FIXEDFILEINFO *ffi;
1114 UINT ffi_len;
1115
1116 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1117 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1118 realMajor = HIWORD(ffi->dwProductVersionMS);
1119 realMinor = LOWORD(ffi->dwProductVersionMS);
1120 realBuild = HIWORD(ffi->dwProductVersionLS);
1121 }
1122 PyMem_RawFree(verblock);
1123 }
Segev Finer48fb7662017-06-04 20:52:27 +03001124 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1125 realMajor,
1126 realMinor,
1127 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001128 ));
1129
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001130 if (PyErr_Occurred()) {
1131 Py_DECREF(version);
1132 return NULL;
1133 }
Steve Dower74f4af72016-09-17 17:27:48 -07001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001136}
1137
Steve Dower3e96f322015-03-02 08:01:10 -08001138#pragma warning(pop)
1139
Steve Dowercc16be82016-09-08 10:35:16 -07001140PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1141"_enablelegacywindowsfsencoding()\n\
1142\n\
1143Changes the default filesystem encoding to mbcs:replace for consistency\n\
1144with earlier versions of Python. See PEP 529 for more information.\n\
1145\n\
oldkaa0735f2018-02-02 16:52:55 +08001146This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001147environment variable before launching Python."
1148);
1149
1150static PyObject *
1151sys_enablelegacywindowsfsencoding(PyObject *self)
1152{
1153 Py_FileSystemDefaultEncoding = "mbcs";
1154 Py_FileSystemDefaultEncodeErrors = "replace";
1155 Py_RETURN_NONE;
1156}
1157
Mark Hammond8696ebc2002-10-08 02:44:31 +00001158#endif /* MS_WINDOWS */
1159
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001160#ifdef HAVE_DLOPEN
1161static PyObject *
1162sys_setdlopenflags(PyObject *self, PyObject *args)
1163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 int new_val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1166 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001167 PyInterpreterState *interp = _PyInterpreterState_Get();
1168 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001169 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001170}
1171
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001172PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001173"setdlopenflags(n) -> None\n\
1174\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001175Set the flags used by the interpreter for dlopen calls, such as when the\n\
1176interpreter loads extension modules. Among other things, this will enable\n\
1177a lazy resolving of symbols when importing a module, if called as\n\
1178sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001179sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001180can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001181
1182static PyObject *
1183sys_getdlopenflags(PyObject *self, PyObject *args)
1184{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001185 PyInterpreterState *interp = _PyInterpreterState_Get();
1186 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001187}
1188
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001189PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001190"getdlopenflags() -> int\n\
1191\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001192Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001193The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001196
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001197#ifdef USE_MALLOPT
1198/* Link with -lmalloc (or -lmpc) on an SGI */
1199#include <malloc.h>
1200
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001201static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001202sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204 int flag;
1205 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1206 return NULL;
1207 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001208 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001209}
1210#endif /* USE_MALLOPT */
1211
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001212size_t
1213_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001214{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001217 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001218
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001219 /* Make sure the type is initialized. float gets initialized late */
1220 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001221 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001222
Benjamin Petersonce798522012-01-22 11:24:29 -05001223 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (method == NULL) {
1225 if (!PyErr_Occurred())
1226 PyErr_Format(PyExc_TypeError,
1227 "Type %.100s doesn't define __sizeof__",
1228 Py_TYPE(o)->tp_name);
1229 }
1230 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001231 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 Py_DECREF(method);
1233 }
1234
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001235 if (res == NULL)
1236 return (size_t)-1;
1237
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001238 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001239 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001240 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001241 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001242
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001243 if (size < 0) {
1244 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1245 return (size_t)-1;
1246 }
1247
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001248 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001249 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001250 return ((size_t)size) + sizeof(PyGC_Head);
1251 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001252}
1253
1254static PyObject *
1255sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1256{
1257 static char *kwlist[] = {"object", "default", 0};
1258 size_t size;
1259 PyObject *o, *dflt = NULL;
1260
1261 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1262 kwlist, &o, &dflt))
1263 return NULL;
1264
1265 size = _PySys_GetSizeOf(o);
1266
1267 if (size == (size_t)-1 && PyErr_Occurred()) {
1268 /* Has a default value been given */
1269 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1270 PyErr_Clear();
1271 Py_INCREF(dflt);
1272 return dflt;
1273 }
1274 else
1275 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001277
1278 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001279}
1280
1281PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001282"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001283\n\
1284Return the size of object in bytes.");
1285
1286static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001287sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001290}
1291
Tim Peters4be93d02002-07-07 19:59:50 +00001292#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001293static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301294sys_gettotalrefcount(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Hammond440d8982000-06-20 08:12:48 +00001295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001297}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001298#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001299
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001300PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001301"getrefcount(object) -> integer\n\
1302\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001303Return the reference count of object. The count returned is generally\n\
1304one higher than you might expect, because it includes the (temporary)\n\
1305reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001306);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001307
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001308static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301309sys_getallocatedblocks(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001310{
1311 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1312}
1313
1314PyDoc_STRVAR(getallocatedblocks_doc,
1315"getallocatedblocks() -> integer\n\
1316\n\
1317Return the number of memory blocks currently allocated, regardless of their\n\
1318size."
1319);
1320
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001321#ifdef COUNT_ALLOCS
1322static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001323sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001328}
1329#endif
1330
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001331PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001332"_getframe([depth]) -> frameobject\n\
1333\n\
1334Return a frame object from the call stack. If optional integer depth is\n\
1335given, return the frame object that many calls below the top of the stack.\n\
1336If that is deeper than the call stack, ValueError is raised. The default\n\
1337for depth is zero, returning the frame at the top of the call stack.\n\
1338\n\
1339This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001340purposes only."
1341);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001342
1343static PyObject *
1344sys_getframe(PyObject *self, PyObject *args)
1345{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 PyFrameObject *f = PyThreadState_GET()->frame;
1347 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1350 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 while (depth > 0 && f != NULL) {
1353 f = f->f_back;
1354 --depth;
1355 }
1356 if (f == NULL) {
1357 PyErr_SetString(PyExc_ValueError,
1358 "call stack is not deep enough");
1359 return NULL;
1360 }
1361 Py_INCREF(f);
1362 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001363}
1364
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001365PyDoc_STRVAR(current_frames_doc,
1366"_current_frames() -> dictionary\n\
1367\n\
1368Return a dictionary mapping each current thread T's thread id to T's\n\
1369current stack frame.\n\
1370\n\
1371This function should be used for specialized purposes only."
1372);
1373
1374static PyObject *
1375sys_current_frames(PyObject *self, PyObject *noargs)
1376{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001378}
1379
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001380PyDoc_STRVAR(call_tracing_doc,
1381"call_tracing(func, args) -> object\n\
1382\n\
1383Call func(*args), while tracing is enabled. The tracing state is\n\
1384saved, and restored afterwards. This is intended to be called from\n\
1385a debugger from a checkpoint, to recursively debug some other code."
1386);
1387
1388static PyObject *
1389sys_call_tracing(PyObject *self, PyObject *args)
1390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 PyObject *func, *funcargs;
1392 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1393 return NULL;
1394 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001395}
1396
Jeremy Hylton985eba52003-02-05 23:13:00 +00001397PyDoc_STRVAR(callstats_doc,
1398"callstats() -> tuple of integers\n\
1399\n\
1400Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1401when Python was built. Otherwise, return None.\n\
1402\n\
1403When enabled, this function returns detailed, implementation-specific\n\
1404details about the number of function calls executed. The return value is\n\
1405a 11-tuple where the entries in the tuple are counts of:\n\
14060. all function calls\n\
14071. calls to PyFunction_Type objects\n\
14082. PyFunction calls that do not create an argument tuple\n\
14093. PyFunction calls that do not create an argument tuple\n\
1410 and bypass PyEval_EvalCodeEx()\n\
14114. PyMethod calls\n\
14125. PyMethod calls on bound methods\n\
14136. PyType calls\n\
14147. PyCFunction calls\n\
14158. generator calls\n\
14169. All other calls\n\
141710. Number of stack pops performed by call_function()"
1418);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001419
Victor Stinner048afd92016-11-28 11:59:04 +01001420static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301421sys_callstats(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner048afd92016-11-28 11:59:04 +01001422{
1423 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1424 "sys.callstats() has been deprecated in Python 3.7 "
1425 "and will be removed in the future", 1) < 0) {
1426 return NULL;
1427 }
1428
1429 Py_RETURN_NONE;
1430}
1431
1432
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001433#ifdef __cplusplus
1434extern "C" {
1435#endif
1436
David Malcolm49526f42012-06-22 14:55:41 -04001437static PyObject *
1438sys_debugmallocstats(PyObject *self, PyObject *args)
1439{
1440#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001441 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001442 fputc('\n', stderr);
1443 }
David Malcolm49526f42012-06-22 14:55:41 -04001444#endif
1445 _PyObject_DebugTypeStats(stderr);
1446
1447 Py_RETURN_NONE;
1448}
1449PyDoc_STRVAR(debugmallocstats_doc,
1450"_debugmallocstats()\n\
1451\n\
1452Print summary info to stderr about the state of\n\
1453pymalloc's structures.\n\
1454\n\
1455In Py_DEBUG mode, also perform some expensive internal consistency\n\
1456checks.\n\
1457");
1458
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001459#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001460/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001461extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001462#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001463
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001464#ifdef DYNAMIC_EXECUTION_PROFILE
1465/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001466extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001467#endif
1468
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001469#ifdef __cplusplus
1470}
1471#endif
1472
Christian Heimes15ebc882008-02-04 18:48:49 +00001473static PyObject *
1474sys_clear_type_cache(PyObject* self, PyObject* args)
1475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 PyType_ClearCache();
1477 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001478}
1479
1480PyDoc_STRVAR(sys_clear_type_cache__doc__,
1481"_clear_type_cache() -> None\n\
1482Clear the internal type lookup cache.");
1483
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001484static PyObject *
1485sys_is_finalizing(PyObject* self, PyObject* args)
1486{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001487 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001488}
1489
1490PyDoc_STRVAR(is_finalizing_doc,
1491"is_finalizing()\n\
1492Return True if Python is exiting.");
1493
Christian Heimes15ebc882008-02-04 18:48:49 +00001494
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001495#ifdef ANDROID_API_LEVEL
1496PyDoc_STRVAR(getandroidapilevel_doc,
1497"getandroidapilevel()\n\
1498\n\
1499Return the build time API version of Android as an integer.");
1500
1501static PyObject *
1502sys_getandroidapilevel(PyObject *self)
1503{
1504 return PyLong_FromLong(ANDROID_API_LEVEL);
1505}
1506#endif /* ANDROID_API_LEVEL */
1507
1508
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001509static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001511 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1512 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301513 {"callstats", sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 callstats_doc},
1515 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1516 sys_clear_type_cache__doc__},
1517 {"_current_frames", sys_current_frames, METH_NOARGS,
1518 current_frames_doc},
1519 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1520 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1521 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1522 {"exit", sys_exit, METH_VARARGS, exit_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301523 {"getdefaultencoding", sys_getdefaultencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001524 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001525#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1527 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001528#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301529 {"getallocatedblocks", sys_getallocatedblocks, METH_NOARGS,
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001530 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001531#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001533#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001534#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001536#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301537 {"getfilesystemencoding", sys_getfilesystemencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 METH_NOARGS, getfilesystemencoding_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301539 { "getfilesystemencodeerrors", sys_getfilesystemencodeerrors,
Steve Dowercc16be82016-09-08 10:35:16 -07001540 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001541#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001543#endif
1544#ifdef Py_REF_DEBUG
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301545 {"gettotalrefcount", sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001546#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301548 {"getrecursionlimit", sys_getrecursionlimit, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 getrecursionlimit_doc},
1550 {"getsizeof", (PyCFunction)sys_getsizeof,
1551 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1552 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001553#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1555 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001556 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1557 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001558#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001560 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001561#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001563#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1565 setcheckinterval_doc},
1566 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1567 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1569 setswitchinterval_doc},
1570 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1571 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001572#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1574 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001575#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1577 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1578 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1579 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"settrace", sys_settrace, METH_O, settrace_doc},
1581 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1582 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001583 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001584 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001585 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1586 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001587 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1588 set_coroutine_wrapper_doc},
1589 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1590 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001591 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001592 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1593 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1594 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001595#ifdef ANDROID_API_LEVEL
1596 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1597 getandroidapilevel_doc},
1598#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001600};
1601
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001602static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001603list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 PyObject *list = PyList_New(0);
1606 int i;
1607 if (list == NULL)
1608 return NULL;
1609 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1610 PyObject *name = PyUnicode_FromString(
1611 PyImport_Inittab[i].name);
1612 if (name == NULL)
1613 break;
1614 PyList_Append(list, name);
1615 Py_DECREF(name);
1616 }
1617 if (PyList_Sort(list) != 0) {
1618 Py_DECREF(list);
1619 list = NULL;
1620 }
1621 if (list) {
1622 PyObject *v = PyList_AsTuple(list);
1623 Py_DECREF(list);
1624 list = v;
1625 }
1626 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001627}
1628
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001629/* Pre-initialization support for sys.warnoptions and sys._xoptions
1630 *
1631 * Modern internal code paths:
1632 * These APIs get called after _Py_InitializeCore and get to use the
1633 * regular CPython list, dict, and unicode APIs.
1634 *
1635 * Legacy embedding code paths:
1636 * The multi-phase initialization API isn't public yet, so embedding
1637 * apps still need to be able configure sys.warnoptions and sys._xoptions
1638 * before they call Py_Initialize. To support this, we stash copies of
1639 * the supplied wchar * sequences in linked lists, and then migrate the
1640 * contents of those lists to the sys module in _PyInitializeCore.
1641 *
1642 */
1643
1644struct _preinit_entry {
1645 wchar_t *value;
1646 struct _preinit_entry *next;
1647};
1648
1649typedef struct _preinit_entry *_Py_PreInitEntry;
1650
1651static _Py_PreInitEntry _preinit_warnoptions = NULL;
1652static _Py_PreInitEntry _preinit_xoptions = NULL;
1653
1654static _Py_PreInitEntry
1655_alloc_preinit_entry(const wchar_t *value)
1656{
1657 /* To get this to work, we have to initialize the runtime implicitly */
1658 _PyRuntime_Initialize();
1659
1660 /* Force default allocator, so we can ensure that it also gets used to
1661 * destroy the linked list in _clear_preinit_entries.
1662 */
1663 PyMemAllocatorEx old_alloc;
1664 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1665
1666 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1667 if (node != NULL) {
1668 node->value = _PyMem_RawWcsdup(value);
1669 if (node->value == NULL) {
1670 PyMem_RawFree(node);
1671 node = NULL;
1672 };
1673 };
1674
1675 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1676 return node;
1677};
1678
1679static int
1680_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1681{
1682 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1683 if (new_entry == NULL) {
1684 return -1;
1685 }
1686 /* We maintain the linked list in this order so it's easy to play back
1687 * the add commands in the same order later on in _Py_InitializeCore
1688 */
1689 _Py_PreInitEntry last_entry = *optionlist;
1690 if (last_entry == NULL) {
1691 *optionlist = new_entry;
1692 } else {
1693 while (last_entry->next != NULL) {
1694 last_entry = last_entry->next;
1695 }
1696 last_entry->next = new_entry;
1697 }
1698 return 0;
1699};
1700
1701static void
1702_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1703{
1704 _Py_PreInitEntry current = *optionlist;
1705 *optionlist = NULL;
1706 /* Deallocate the nodes and their contents using the default allocator */
1707 PyMemAllocatorEx old_alloc;
1708 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1709 while (current != NULL) {
1710 _Py_PreInitEntry next = current->next;
1711 PyMem_RawFree(current->value);
1712 PyMem_RawFree(current);
1713 current = next;
1714 }
1715 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1716};
1717
1718static void
1719_clear_all_preinit_options(void)
1720{
1721 _clear_preinit_entries(&_preinit_warnoptions);
1722 _clear_preinit_entries(&_preinit_xoptions);
1723}
1724
1725static int
1726_PySys_ReadPreInitOptions(void)
1727{
1728 /* Rerun the add commands with the actual sys module available */
1729 PyThreadState *tstate = PyThreadState_GET();
1730 if (tstate == NULL) {
1731 /* Still don't have a thread state, so something is wrong! */
1732 return -1;
1733 }
1734 _Py_PreInitEntry entry = _preinit_warnoptions;
1735 while (entry != NULL) {
1736 PySys_AddWarnOption(entry->value);
1737 entry = entry->next;
1738 }
1739 entry = _preinit_xoptions;
1740 while (entry != NULL) {
1741 PySys_AddXOption(entry->value);
1742 entry = entry->next;
1743 }
1744
1745 _clear_all_preinit_options();
1746 return 0;
1747};
1748
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001749static PyObject *
1750get_warnoptions(void)
1751{
Eric Snowdae02762017-09-14 00:35:58 -07001752 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001753 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001754 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1755 * interpreter config. When that happens, we need to properly set
1756 * the `warnoptions` reference in the main interpreter config as well.
1757 *
1758 * For Python 3.7, we shouldn't be able to get here due to the
1759 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1760 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1761 * call optional for embedding applications, thus making this
1762 * reachable again.
1763 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001764 Py_XDECREF(warnoptions);
1765 warnoptions = PyList_New(0);
1766 if (warnoptions == NULL)
1767 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001768 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1769 Py_DECREF(warnoptions);
1770 return NULL;
1771 }
1772 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001773 }
1774 return warnoptions;
1775}
Guido van Rossum23fff912000-12-15 22:02:05 +00001776
1777void
1778PySys_ResetWarnOptions(void)
1779{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001780 PyThreadState *tstate = PyThreadState_GET();
1781 if (tstate == NULL) {
1782 _clear_preinit_entries(&_preinit_warnoptions);
1783 return;
1784 }
1785
Eric Snowdae02762017-09-14 00:35:58 -07001786 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (warnoptions == NULL || !PyList_Check(warnoptions))
1788 return;
1789 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001790}
1791
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001792int
1793_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001794{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001795 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001796 if (warnoptions == NULL) {
1797 return -1;
1798 }
1799 if (PyList_Append(warnoptions, option)) {
1800 return -1;
1801 }
1802 return 0;
1803}
1804
1805void
1806PySys_AddWarnOptionUnicode(PyObject *option)
1807{
1808 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001809}
1810
1811void
1812PySys_AddWarnOption(const wchar_t *s)
1813{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001814 PyThreadState *tstate = PyThreadState_GET();
1815 if (tstate == NULL) {
1816 _append_preinit_entry(&_preinit_warnoptions, s);
1817 return;
1818 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001819 PyObject *unicode;
1820 unicode = PyUnicode_FromWideChar(s, -1);
1821 if (unicode == NULL)
1822 return;
1823 PySys_AddWarnOptionUnicode(unicode);
1824 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001825}
1826
Christian Heimes33fe8092008-04-13 13:53:33 +00001827int
1828PySys_HasWarnOptions(void)
1829{
Eric Snowdae02762017-09-14 00:35:58 -07001830 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001831 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1832}
1833
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001834static PyObject *
1835get_xoptions(void)
1836{
Eric Snowdae02762017-09-14 00:35:58 -07001837 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001838 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001839 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1840 * interpreter config. When that happens, we need to properly set
1841 * the `xoptions` reference in the main interpreter config as well.
1842 *
1843 * For Python 3.7, we shouldn't be able to get here due to the
1844 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1845 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1846 * call optional for embedding applications, thus making this
1847 * reachable again.
1848 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001849 Py_XDECREF(xoptions);
1850 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001851 if (xoptions == NULL)
1852 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001853 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1854 Py_DECREF(xoptions);
1855 return NULL;
1856 }
1857 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001858 }
1859 return xoptions;
1860}
1861
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001862int
1863_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001864{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001865 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001866
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001867 PyObject *opts = get_xoptions();
1868 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001869 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001870 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001871
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001872 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001873 if (!name_end) {
1874 name = PyUnicode_FromWideChar(s, -1);
1875 value = Py_True;
1876 Py_INCREF(value);
1877 }
1878 else {
1879 name = PyUnicode_FromWideChar(s, name_end - s);
1880 value = PyUnicode_FromWideChar(name_end + 1, -1);
1881 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001882 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001883 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001884 }
1885 if (PyDict_SetItem(opts, name, value) < 0) {
1886 goto error;
1887 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001888 Py_DECREF(name);
1889 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001890 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001891
1892error:
1893 Py_XDECREF(name);
1894 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001895 return -1;
1896}
1897
1898void
1899PySys_AddXOption(const wchar_t *s)
1900{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001901 PyThreadState *tstate = PyThreadState_GET();
1902 if (tstate == NULL) {
1903 _append_preinit_entry(&_preinit_xoptions, s);
1904 return;
1905 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001906 if (_PySys_AddXOptionWithError(s) < 0) {
1907 /* No return value, therefore clear error state if possible */
1908 if (_PyThreadState_UncheckedGet()) {
1909 PyErr_Clear();
1910 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001911 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001912}
1913
1914PyObject *
1915PySys_GetXOptions(void)
1916{
1917 return get_xoptions();
1918}
1919
Guido van Rossum40552d01998-08-06 03:34:39 +00001920/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1921 Two literals concatenated works just fine. If you have a K&R compiler
1922 or other abomination that however *does* understand longer strings,
1923 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001924PyDoc_VAR(sys_doc) =
1925PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001926"This module provides access to some objects used or maintained by the\n\
1927interpreter and to functions that interact strongly with the interpreter.\n\
1928\n\
1929Dynamic objects:\n\
1930\n\
1931argv -- command line arguments; argv[0] is the script pathname if known\n\
1932path -- module search path; path[0] is the script directory, else ''\n\
1933modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001934\n\
1935displayhook -- called to show results in an interactive session\n\
1936excepthook -- called to handle any uncaught exception other than SystemExit\n\
1937 To customize printing in an interactive session or to install a custom\n\
1938 top-level exception handler, assign other functions to replace these.\n\
1939\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001940stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001941stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001942stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001943 By assigning other file objects (or objects that behave like files)\n\
1944 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001945\n\
1946last_type -- type of last uncaught exception\n\
1947last_value -- value of last uncaught exception\n\
1948last_traceback -- traceback of last uncaught exception\n\
1949 These three are only available in an interactive session after a\n\
1950 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001951"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001952)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001953/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001954PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001955"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001956Static objects:\n\
1957\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001958builtin_module_names -- tuple of module names built into this interpreter\n\
1959copyright -- copyright notice pertaining to this interpreter\n\
1960exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001961executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001962float_info -- a struct sequence with information about the float implementation.\n\
1963float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001964hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001965hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001966implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001967int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001968maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001969maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001970platform -- platform identifier\n\
1971prefix -- prefix used to find the Python library\n\
1972thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001973version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001974version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001975"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001976)
Steve Dowercc16be82016-09-08 10:35:16 -07001977#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001978/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001979PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001980"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001981winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001982"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001983)
Steve Dowercc16be82016-09-08 10:35:16 -07001984#endif /* MS_COREDLL */
1985#ifdef MS_WINDOWS
1986/* concatenating string here */
1987PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08001988"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001989"
1990)
1991#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001992PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001993"__stdin__ -- the original stdin; don't touch!\n\
1994__stdout__ -- the original stdout; don't touch!\n\
1995__stderr__ -- the original stderr; don't touch!\n\
1996__displayhook__ -- the original displayhook; don't touch!\n\
1997__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001998\n\
1999Functions:\n\
2000\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002001displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002002excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002003exc_info() -- return thread-safe information about the current exception\n\
2004exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002005getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002006getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002007getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002008getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002009getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002010gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002011setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002012setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002013setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002014setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002015settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002016"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002017)
Fred Drakeccede592000-08-14 20:59:57 +00002018/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002019
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002020
2021PyDoc_STRVAR(flags__doc__,
2022"sys.flags\n\
2023\n\
2024Flags provided through command line arguments or environment vars.");
2025
2026static PyTypeObject FlagsType;
2027
2028static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002029 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 {"inspect", "-i"},
2031 {"interactive", "-i"},
2032 {"optimize", "-O or -OO"},
2033 {"dont_write_bytecode", "-B"},
2034 {"no_user_site", "-s"},
2035 {"no_site", "-S"},
2036 {"ignore_environment", "-E"},
2037 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 /* {"unbuffered", "-u"}, */
2039 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002040 {"bytes_warning", "-b"},
2041 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002042 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002043 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002044 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002045 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002047};
2048
2049static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 "sys.flags", /* name */
2051 flags__doc__, /* doc */
2052 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002053 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002054};
2055
2056static PyObject*
2057make_flags(void)
2058{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 int pos = 0;
2060 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01002061 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 seq = PyStructSequence_New(&FlagsType);
2064 if (seq == NULL)
2065 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002066
2067#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 SetFlag(Py_InspectFlag);
2072 SetFlag(Py_InteractiveFlag);
2073 SetFlag(Py_OptimizeFlag);
2074 SetFlag(Py_DontWriteBytecodeFlag);
2075 SetFlag(Py_NoUserSiteDirectory);
2076 SetFlag(Py_NoSiteFlag);
2077 SetFlag(Py_IgnoreEnvironmentFlag);
2078 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 /* SetFlag(saw_unbuffered_flag); */
2080 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00002081 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00002082 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002083 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02002084 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01002085 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01002086 SetFlag(Py_UTF8Mode);
2087#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002090 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 return NULL;
2092 }
2093 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002094}
2095
Eric Smith0e5b5622009-02-06 01:32:42 +00002096PyDoc_STRVAR(version_info__doc__,
2097"sys.version_info\n\
2098\n\
2099Version information as a named tuple.");
2100
2101static PyTypeObject VersionInfoType;
2102
2103static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 {"major", "Major release number"},
2105 {"minor", "Minor release number"},
2106 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002107 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 {"serial", "Serial release number"},
2109 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002110};
2111
2112static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 "sys.version_info", /* name */
2114 version_info__doc__, /* doc */
2115 version_info_fields, /* fields */
2116 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002117};
2118
2119static PyObject *
2120make_version_info(void)
2121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 PyObject *version_info;
2123 char *s;
2124 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 version_info = PyStructSequence_New(&VersionInfoType);
2127 if (version_info == NULL) {
2128 return NULL;
2129 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 /*
2132 * These release level checks are mutually exclusive and cover
2133 * the field, so don't get too fancy with the pre-processor!
2134 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002135#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002137#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002139#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002141#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002143#endif
2144
2145#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002147#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 SetIntItem(PY_MAJOR_VERSION);
2151 SetIntItem(PY_MINOR_VERSION);
2152 SetIntItem(PY_MICRO_VERSION);
2153 SetStrItem(s);
2154 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002155#undef SetIntItem
2156#undef SetStrItem
2157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 if (PyErr_Occurred()) {
2159 Py_CLEAR(version_info);
2160 return NULL;
2161 }
2162 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002163}
2164
Brett Cannon3adc7b72012-07-09 14:22:12 -04002165/* sys.implementation values */
2166#define NAME "cpython"
2167const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002168#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2169#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002170#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002171const char *_PySys_ImplCacheTag = TAG;
2172#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002173#undef MAJOR
2174#undef MINOR
2175#undef TAG
2176
Barry Warsaw409da152012-06-03 16:18:47 -04002177static PyObject *
2178make_impl_info(PyObject *version_info)
2179{
2180 int res;
2181 PyObject *impl_info, *value, *ns;
2182
2183 impl_info = PyDict_New();
2184 if (impl_info == NULL)
2185 return NULL;
2186
2187 /* populate the dict */
2188
Brett Cannon3adc7b72012-07-09 14:22:12 -04002189 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002190 if (value == NULL)
2191 goto error;
2192 res = PyDict_SetItemString(impl_info, "name", value);
2193 Py_DECREF(value);
2194 if (res < 0)
2195 goto error;
2196
Brett Cannon3adc7b72012-07-09 14:22:12 -04002197 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002198 if (value == NULL)
2199 goto error;
2200 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2201 Py_DECREF(value);
2202 if (res < 0)
2203 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002204
2205 res = PyDict_SetItemString(impl_info, "version", version_info);
2206 if (res < 0)
2207 goto error;
2208
2209 value = PyLong_FromLong(PY_VERSION_HEX);
2210 if (value == NULL)
2211 goto error;
2212 res = PyDict_SetItemString(impl_info, "hexversion", value);
2213 Py_DECREF(value);
2214 if (res < 0)
2215 goto error;
2216
doko@ubuntu.com55532312016-06-14 08:55:19 +02002217#ifdef MULTIARCH
2218 value = PyUnicode_FromString(MULTIARCH);
2219 if (value == NULL)
2220 goto error;
2221 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2222 Py_DECREF(value);
2223 if (res < 0)
2224 goto error;
2225#endif
2226
Barry Warsaw409da152012-06-03 16:18:47 -04002227 /* dict ready */
2228
2229 ns = _PyNamespace_New(impl_info);
2230 Py_DECREF(impl_info);
2231 return ns;
2232
2233error:
2234 Py_CLEAR(impl_info);
2235 return NULL;
2236}
2237
Martin v. Löwis1a214512008-06-11 05:26:20 +00002238static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyModuleDef_HEAD_INIT,
2240 "sys",
2241 sys_doc,
2242 -1, /* multiple "initialization" just copies the module dict. */
2243 sys_methods,
2244 NULL,
2245 NULL,
2246 NULL,
2247 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002248};
2249
Eric Snow6b4be192017-05-22 21:36:03 -07002250/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002251#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002252 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002253 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002254 if (v == NULL) { \
2255 goto err_occurred; \
2256 } \
Victor Stinner58049602013-07-22 22:40:00 +02002257 res = PyDict_SetItemString(sysdict, key, v); \
2258 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002259 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002260 } \
2261 } while (0)
2262#define SET_SYS_FROM_STRING(key, value) \
2263 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002264 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002265 if (v == NULL) { \
2266 goto err_occurred; \
2267 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002268 res = PyDict_SetItemString(sysdict, key, v); \
2269 Py_DECREF(v); \
2270 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002271 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002272 } \
2273 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002274
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002275
2276_PyInitError
2277_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002278{
2279 PyObject *m, *sysdict, *version_info;
2280 int res;
2281
Eric Snowd393c1b2017-09-14 12:18:12 -06002282 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283 if (m == NULL) {
2284 return _Py_INIT_ERR("failed to create a module object");
2285 }
Eric Snow6b4be192017-05-22 21:36:03 -07002286 sysdict = PyModule_GetDict(m);
2287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002288 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289 Using shell redirection, you can redirect stdin to a directory,
2290 crashing the Python interpreter. Catch this common mistake here
2291 and output a useful error message. Note that under MS Windows,
2292 the shell already prevents that. */
2293#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002295 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002296 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002297 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002298 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2299 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 }
2301 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002302#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002303
Nick Coghland6009512014-11-20 21:39:37 +10002304 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002305
Victor Stinner8fea2522013-10-27 17:15:42 +01002306 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2307 PyDict_GetItemString(sysdict, "displayhook"));
2308 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2309 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002310 SET_SYS_FROM_STRING_BORROW(
2311 "__breakpointhook__",
2312 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 SET_SYS_FROM_STRING("version",
2314 PyUnicode_FromString(Py_GetVersion()));
2315 SET_SYS_FROM_STRING("hexversion",
2316 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002317 SET_SYS_FROM_STRING("_git",
2318 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2319 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002320 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 SET_SYS_FROM_STRING("api_version",
2322 PyLong_FromLong(PYTHON_API_VERSION));
2323 SET_SYS_FROM_STRING("copyright",
2324 PyUnicode_FromString(Py_GetCopyright()));
2325 SET_SYS_FROM_STRING("platform",
2326 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 SET_SYS_FROM_STRING("maxsize",
2328 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2329 SET_SYS_FROM_STRING("float_info",
2330 PyFloat_GetInfo());
2331 SET_SYS_FROM_STRING("int_info",
2332 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002333 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002334 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002335 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2336 goto type_init_failed;
2337 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002338 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002339 SET_SYS_FROM_STRING("hash_info",
2340 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002342 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002343 SET_SYS_FROM_STRING("builtin_module_names",
2344 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002345#if PY_BIG_ENDIAN
2346 SET_SYS_FROM_STRING("byteorder",
2347 PyUnicode_FromString("big"));
2348#else
2349 SET_SYS_FROM_STRING("byteorder",
2350 PyUnicode_FromString("little"));
2351#endif
Fred Drake099325e2000-08-14 15:47:03 +00002352
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002353#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002354 SET_SYS_FROM_STRING("dllhandle",
2355 PyLong_FromVoidPtr(PyWin_DLLhModule));
2356 SET_SYS_FROM_STRING("winver",
2357 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002358#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002359#ifdef ABIFLAGS
2360 SET_SYS_FROM_STRING("abiflags",
2361 PyUnicode_FromString(ABIFLAGS));
2362#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002365 if (VersionInfoType.tp_name == NULL) {
2366 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002367 &version_info_desc) < 0) {
2368 goto type_init_failed;
2369 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002370 }
Barry Warsaw409da152012-06-03 16:18:47 -04002371 version_info = make_version_info();
2372 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* prevent user from creating new instances */
2374 VersionInfoType.tp_init = NULL;
2375 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002376 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2377 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2378 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002379
Barry Warsaw409da152012-06-03 16:18:47 -04002380 /* implementation */
2381 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002383 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002384 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002385 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2386 goto type_init_failed;
2387 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002388 }
Eric Snow6b4be192017-05-22 21:36:03 -07002389 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002391
2392#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 /* getwindowsversion */
2394 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002395 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002396 &windows_version_desc) < 0) {
2397 goto type_init_failed;
2398 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* prevent user from creating new instances */
2400 WindowsVersionType.tp_init = NULL;
2401 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002402 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002403 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002404 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002405 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002406 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002407#endif
2408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002410#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 SET_SYS_FROM_STRING("float_repr_style",
2412 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002413#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 SET_SYS_FROM_STRING("float_repr_style",
2415 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002416#endif
2417
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002418 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002419
Yury Selivanoveb636452016-09-08 22:01:51 -07002420 /* initialize asyncgen_hooks */
2421 if (AsyncGenHooksType.tp_name == NULL) {
2422 if (PyStructSequence_InitType2(
2423 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002424 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002425 }
2426 }
2427
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002428 if (PyErr_Occurred()) {
2429 goto err_occurred;
2430 }
2431
2432 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002433
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002434 return _Py_INIT_OK();
2435
2436type_init_failed:
2437 return _Py_INIT_ERR("failed to initialize a type");
2438
2439err_occurred:
2440 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002441}
2442
Eric Snow6b4be192017-05-22 21:36:03 -07002443#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002444
2445/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002446#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2447 do { \
2448 PyObject *v = (value); \
2449 if (v == NULL) \
2450 return -1; \
2451 res = PyDict_SetItemString(sysdict, key, v); \
2452 Py_DECREF(v); \
2453 if (res < 0) { \
2454 return res; \
2455 } \
2456 } while (0)
2457
2458int
Victor Stinner41264f12017-12-15 02:05:29 +01002459_PySys_EndInit(PyObject *sysdict, _PyMainInterpreterConfig *config)
Eric Snow6b4be192017-05-22 21:36:03 -07002460{
2461 int res;
2462
Victor Stinner41264f12017-12-15 02:05:29 +01002463 /* _PyMainInterpreterConfig_Read() must set all these variables */
2464 assert(config->module_search_path != NULL);
2465 assert(config->executable != NULL);
2466 assert(config->prefix != NULL);
2467 assert(config->base_prefix != NULL);
2468 assert(config->exec_prefix != NULL);
2469 assert(config->base_exec_prefix != NULL);
2470
2471 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
2472 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2473 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2474 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2475 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2476 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2477
Carl Meyerb193fa92018-06-15 22:40:56 -06002478 if (config->pycache_prefix != NULL) {
2479 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2480 } else {
2481 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2482 }
2483
Victor Stinner41264f12017-12-15 02:05:29 +01002484 if (config->argv != NULL) {
2485 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2486 }
2487 if (config->warnoptions != NULL) {
2488 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
2489 }
2490 if (config->xoptions != NULL) {
2491 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
2492 }
2493
Eric Snow6b4be192017-05-22 21:36:03 -07002494 /* Set flags to their final values */
2495 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2496 /* prevent user from creating new instances */
2497 FlagsType.tp_init = NULL;
2498 FlagsType.tp_new = NULL;
2499 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2500 if (res < 0) {
2501 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2502 return res;
2503 }
2504 PyErr_Clear();
2505 }
2506
2507 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2508 PyBool_FromLong(Py_DontWriteBytecodeFlag));
Eric Snow6b4be192017-05-22 21:36:03 -07002509
Eric Snowdae02762017-09-14 00:35:58 -07002510 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002511 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002512
Eric Snowdae02762017-09-14 00:35:58 -07002513 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002514 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002515
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002516 /* Transfer any sys.warnoptions and sys._xoptions set directly
2517 * by an embedding application from the linked list to the module. */
2518 if (_PySys_ReadPreInitOptions() != 0)
2519 return -1;
2520
Eric Snow6b4be192017-05-22 21:36:03 -07002521 if (PyErr_Occurred())
2522 return -1;
2523 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002524
2525err_occurred:
2526 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002527}
2528
Victor Stinner41264f12017-12-15 02:05:29 +01002529#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002530#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002531
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002532static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002533makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 int i, n;
2536 const wchar_t *p;
2537 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 n = 1;
2540 p = path;
2541 while ((p = wcschr(p, delim)) != NULL) {
2542 n++;
2543 p++;
2544 }
2545 v = PyList_New(n);
2546 if (v == NULL)
2547 return NULL;
2548 for (i = 0; ; i++) {
2549 p = wcschr(path, delim);
2550 if (p == NULL)
2551 p = path + wcslen(path); /* End of string */
2552 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2553 if (w == NULL) {
2554 Py_DECREF(v);
2555 return NULL;
2556 }
2557 PyList_SetItem(v, i, w);
2558 if (*p == '\0')
2559 break;
2560 path = p+1;
2561 }
2562 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002563}
2564
2565void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002566PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyObject *v;
2569 if ((v = makepathobject(path, DELIM)) == NULL)
2570 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002571 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 Py_FatalError("can't assign sys.path");
2573 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002574}
2575
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002576static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002577makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 PyObject *av;
2580 if (argc <= 0 || argv == NULL) {
2581 /* Ensure at least one (empty) argument is seen */
2582 static wchar_t *empty_argv[1] = {L""};
2583 argv = empty_argv;
2584 argc = 1;
2585 }
2586 av = PyList_New(argc);
2587 if (av != NULL) {
2588 int i;
2589 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (v == NULL) {
2592 Py_DECREF(av);
2593 av = NULL;
2594 break;
2595 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002596 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 }
2598 }
2599 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002600}
2601
Victor Stinner11a247d2017-12-13 21:05:57 +01002602void
2603PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002604{
2605 PyObject *av = makeargvobject(argc, argv);
2606 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002607 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002608 }
2609 if (PySys_SetObject("argv", av) != 0) {
2610 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002611 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002612 }
2613 Py_DECREF(av);
2614
2615 if (updatepath) {
2616 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2617 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002618 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2619 if (argv0 == NULL) {
2620 Py_FatalError("can't compute path0 from argv");
2621 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002622
Victor Stinner11a247d2017-12-13 21:05:57 +01002623 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2624 if (sys_path != NULL) {
2625 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2626 Py_DECREF(argv0);
2627 Py_FatalError("can't prepend path0 to sys.path");
2628 }
2629 }
2630 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002631 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002632}
Guido van Rossuma890e681998-05-12 14:59:24 +00002633
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002634void
2635PySys_SetArgv(int argc, wchar_t **argv)
2636{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002637 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002638}
2639
Victor Stinner14284c22010-04-23 12:02:30 +00002640/* Reimplementation of PyFile_WriteString() no calling indirectly
2641 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2642
2643static int
Victor Stinner79766632010-08-16 17:36:42 +00002644sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002645{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002646 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002648
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002649 if (file == NULL)
2650 return -1;
2651
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002652 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (writer == NULL)
2654 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002655
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002656 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (result == NULL) {
2658 goto error;
2659 } else {
2660 err = 0;
2661 goto finally;
2662 }
Victor Stinner14284c22010-04-23 12:02:30 +00002663
2664error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002666finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 Py_XDECREF(result);
2669 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002670}
2671
Victor Stinner79766632010-08-16 17:36:42 +00002672static int
2673sys_pyfile_write(const char *text, PyObject *file)
2674{
2675 PyObject *unicode = NULL;
2676 int err;
2677
2678 if (file == NULL)
2679 return -1;
2680
2681 unicode = PyUnicode_FromString(text);
2682 if (unicode == NULL)
2683 return -1;
2684
2685 err = sys_pyfile_write_unicode(unicode, file);
2686 Py_DECREF(unicode);
2687 return err;
2688}
Guido van Rossuma890e681998-05-12 14:59:24 +00002689
2690/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2691 Adapted from code submitted by Just van Rossum.
2692
2693 PySys_WriteStdout(format, ...)
2694 PySys_WriteStderr(format, ...)
2695
2696 The first function writes to sys.stdout; the second to sys.stderr. When
2697 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002698 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002699
Victor Stinner14284c22010-04-23 12:02:30 +00002700 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002701 signal handlers: they may raise a new exception whereas sys_write()
2702 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002703
Guido van Rossuma890e681998-05-12 14:59:24 +00002704 Both take a printf-style format string as their first argument followed
2705 by a variable length argument list determined by the format string.
2706
2707 *** WARNING ***
2708
2709 The format should limit the total size of the formatted output string to
2710 1000 bytes. In particular, this means that no unrestricted "%s" formats
2711 should occur; these should be limited using "%.<N>s where <N> is a
2712 decimal number calculated so that <N> plus the maximum size of other
2713 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2714 which can print hundreds of digits for very large numbers.
2715
2716 */
2717
2718static void
Victor Stinner09054372013-11-06 22:41:44 +01002719sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyObject *file;
2722 PyObject *error_type, *error_value, *error_traceback;
2723 char buffer[1001];
2724 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002727 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2729 if (sys_pyfile_write(buffer, file) != 0) {
2730 PyErr_Clear();
2731 fputs(buffer, fp);
2732 }
2733 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2734 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002735 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 }
2738 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002739}
2740
2741void
Guido van Rossuma890e681998-05-12 14:59:24 +00002742PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002747 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002749}
2750
2751void
Guido van Rossuma890e681998-05-12 14:59:24 +00002752PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002757 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002758 va_end(va);
2759}
2760
2761static void
Victor Stinner09054372013-11-06 22:41:44 +01002762sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002763{
2764 PyObject *file, *message;
2765 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002766 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002767
2768 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002769 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002770 message = PyUnicode_FromFormatV(format, va);
2771 if (message != NULL) {
2772 if (sys_pyfile_write_unicode(message, file) != 0) {
2773 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002774 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002775 if (utf8 != NULL)
2776 fputs(utf8, fp);
2777 }
2778 Py_DECREF(message);
2779 }
2780 PyErr_Restore(error_type, error_value, error_traceback);
2781}
2782
2783void
2784PySys_FormatStdout(const char *format, ...)
2785{
2786 va_list va;
2787
2788 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002789 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002790 va_end(va);
2791}
2792
2793void
2794PySys_FormatStderr(const char *format, ...)
2795{
2796 va_list va;
2797
2798 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002799 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002801}