blob: 2284e88d4c11800ffff6cdbd7b428bce7f8cfdbe [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"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010020#include "pycore_pylifecycle.h"
21#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010022#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010023#include "pycore_pystate.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020024#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000025
Guido van Rossume2437a11992-03-23 18:20:18 +000026#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020027#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000028
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#ifdef MS_WINDOWS
30#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000031#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000032#endif /* MS_WINDOWS */
33
Guido van Rossum9b38a141996-09-11 23:12:24 +000034#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000035extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000036/* A string loaded from the DLL at startup: */
37extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000038#endif
39
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080040/*[clinic input]
41module sys
42[clinic start generated code]*/
43/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
44
45#include "clinic/sysmodule.c.h"
46
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(_);
48_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070049_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(buffer);
51_Py_IDENTIFIER(builtins);
52_Py_IDENTIFIER(encoding);
53_Py_IDENTIFIER(path);
54_Py_IDENTIFIER(stdout);
55_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070056_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010057_Py_IDENTIFIER(write);
58
Guido van Rossum65bf9f21997-04-29 18:33:38 +000059PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010060_PySys_GetObjectId(_Py_Identifier *key)
61{
Victor Stinnercaba55b2018-08-03 15:33:52 +020062 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
63 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010064 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020065 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010066 return _PyDict_GetItemId(sd, key);
67}
68
69PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000070PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071{
Victor Stinnercaba55b2018-08-03 15:33:52 +020072 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
73 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077}
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079int
Victor Stinnerd67bd452013-11-06 22:36:40 +010080_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
81{
Victor Stinnercaba55b2018-08-03 15:33:52 +020082 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010083 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020084 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010085 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020086 }
87 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010090 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020091 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010092 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020093 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010094}
95
96int
Neal Norwitzf3081322007-08-25 00:32:45 +000097PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Victor Stinnercaba55b2018-08-03 15:33:52 +020099 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200101 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200103 }
104 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200108 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200110 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111}
112
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400113static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200114sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400115{
116 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300117 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400118
119 if (envar == NULL || strlen(envar) == 0) {
120 envar = "pdb.set_trace";
121 }
122 else if (!strcmp(envar, "0")) {
123 /* The breakpoint is explicitly no-op'd. */
124 Py_RETURN_NONE;
125 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300126 /* According to POSIX the string returned by getenv() might be invalidated
127 * or the string content might be overwritten by a subsequent call to
128 * getenv(). Since importing a module can performs the getenv() calls,
129 * we need to save a copy of envar. */
130 envar = _PyMem_RawStrdup(envar);
131 if (envar == NULL) {
132 PyErr_NoMemory();
133 return NULL;
134 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200135 const char *last_dot = strrchr(envar, '.');
136 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400137 PyObject *modulepath = NULL;
138
139 if (last_dot == NULL) {
140 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
141 modulepath = PyUnicode_FromString("builtins");
142 attrname = envar;
143 }
144 else {
145 /* Split on the last dot; */
146 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
147 attrname = last_dot + 1;
148 }
149 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300150 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400151 return NULL;
152 }
153
Anthony Sottiledce345c2018-11-01 10:25:05 -0700154 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400155 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400156
157 if (module == NULL) {
158 goto error;
159 }
160
161 PyObject *hook = PyObject_GetAttrString(module, attrname);
162 Py_DECREF(module);
163
164 if (hook == NULL) {
165 goto error;
166 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300167 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400168 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
169 Py_DECREF(hook);
170 return retval;
171
172 error:
173 /* If any of the imports went wrong, then warn and ignore. */
174 PyErr_Clear();
175 int status = PyErr_WarnFormat(
176 PyExc_RuntimeWarning, 0,
177 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300178 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400179 if (status < 0) {
180 /* Printing the warning raised an exception. */
181 return NULL;
182 }
183 /* The warning was (probably) issued. */
184 Py_RETURN_NONE;
185}
186
187PyDoc_STRVAR(breakpointhook_doc,
188"breakpointhook(*args, **kws)\n"
189"\n"
190"This hook function is called by built-in breakpoint().\n"
191);
192
Victor Stinner13d49ee2010-12-04 17:24:33 +0000193/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
194 error handler. If sys.stdout has a buffer attribute, use
195 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
196 sys.stdout.write(redecoded).
197
198 Helper function for sys_displayhook(). */
199static int
200sys_displayhook_unencodable(PyObject *outf, PyObject *o)
201{
202 PyObject *stdout_encoding = NULL;
203 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200204 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000205 int ret;
206
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200207 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000208 if (stdout_encoding == NULL)
209 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200210 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000211 if (stdout_encoding_str == NULL)
212 goto error;
213
214 repr_str = PyObject_Repr(o);
215 if (repr_str == NULL)
216 goto error;
217 encoded = PyUnicode_AsEncodedString(repr_str,
218 stdout_encoding_str,
219 "backslashreplace");
220 Py_DECREF(repr_str);
221 if (encoded == NULL)
222 goto error;
223
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200224 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000225 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100226 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000227 Py_DECREF(buffer);
228 Py_DECREF(encoded);
229 if (result == NULL)
230 goto error;
231 Py_DECREF(result);
232 }
233 else {
234 PyErr_Clear();
235 escaped_str = PyUnicode_FromEncodedObject(encoded,
236 stdout_encoding_str,
237 "strict");
238 Py_DECREF(encoded);
239 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
240 Py_DECREF(escaped_str);
241 goto error;
242 }
243 Py_DECREF(escaped_str);
244 }
245 ret = 0;
246 goto finally;
247
248error:
249 ret = -1;
250finally:
251 Py_XDECREF(stdout_encoding);
252 return ret;
253}
254
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000255static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000256sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000257{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000258 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100259 PyObject *builtins;
260 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000261 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000262
Eric Snow3f9eee62017-09-15 16:35:20 -0600263 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (builtins == NULL) {
265 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
266 return NULL;
267 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600268 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 /* Print value except if None */
271 /* After printing, also assign to '_' */
272 /* Before, set '_' to None to avoid recursion */
273 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200274 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000275 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200276 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100278 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 if (outf == NULL || outf == Py_None) {
280 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
281 return NULL;
282 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000283 if (PyFile_WriteObject(o, outf, 0) != 0) {
284 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
285 /* repr(o) is not encodable to sys.stdout.encoding with
286 * sys.stdout.errors error handler (which is probably 'strict') */
287 PyErr_Clear();
288 err = sys_displayhook_unencodable(outf, o);
289 if (err)
290 return NULL;
291 }
292 else {
293 return NULL;
294 }
295 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100296 if (newline == NULL) {
297 newline = PyUnicode_FromString("\n");
298 if (newline == NULL)
299 return NULL;
300 }
301 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200303 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000304 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200305 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000306}
307
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000308PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000309"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000310"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000311"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000312);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000313
314static PyObject *
315sys_excepthook(PyObject* self, PyObject* args)
316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 PyObject *exc, *value, *tb;
318 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
319 return NULL;
320 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200321 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000322}
323
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000324PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000325"excepthook(exctype, value, traceback) -> None\n"
326"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000327"Handle an exception by displaying it with a traceback on sys.stderr.\n"
328);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000329
330static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000331sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000332{
Victor Stinner50b48572018-11-01 01:51:40 +0100333 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 return Py_BuildValue(
335 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100336 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
337 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
338 err_info->exc_traceback != NULL ?
339 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000340}
341
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000342PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000343"exc_info() -> (type, value, traceback)\n\
344\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000345Return information about the most recent exception caught by an except\n\
346clause in the current stack frame or in an older stack frame."
347);
348
349static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000350sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 PyObject *exit_code = 0;
353 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
354 return NULL;
355 /* Raise SystemExit so callers may catch it or clean up. */
356 PyErr_SetObject(PyExc_SystemExit, exit_code);
357 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000358}
359
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000360PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000361"exit([status])\n\
362\n\
363Exit the interpreter by raising SystemExit(status).\n\
364If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300365If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000366If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000367exit status will be one (i.e., failure)."
368);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000369
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000370
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000371static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530372sys_getdefaultencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Fred Drake8b4d01d2000-05-09 19:57:01 +0000373{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000375}
376
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000377PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000378"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000379\n\
oldkaa0735f2018-02-02 16:52:55 +0800380Return the current default string encoding used by the Unicode\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000381implementation."
382);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000383
384static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530385sys_getfilesystemencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000386{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200387 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
388 const _PyCoreConfig *config = &interp->core_config;
389 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000390}
391
392PyDoc_STRVAR(getfilesystemencoding_doc,
393"getfilesystemencoding() -> string\n\
394\n\
395Return the encoding used to convert Unicode filenames in\n\
396operating system filenames."
397);
398
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000399static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530400sys_getfilesystemencodeerrors(PyObject *self, PyObject *Py_UNUSED(ignored))
Steve Dowercc16be82016-09-08 10:35:16 -0700401{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200402 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
403 const _PyCoreConfig *config = &interp->core_config;
404 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700405}
406
407PyDoc_STRVAR(getfilesystemencodeerrors_doc,
408 "getfilesystemencodeerrors() -> string\n\
409\n\
410Return the error mode used to convert Unicode filenames in\n\
411operating system filenames."
412);
413
414static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000415sys_intern(PyObject *self, PyObject *args)
416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyObject *s;
418 if (!PyArg_ParseTuple(args, "U:intern", &s))
419 return NULL;
420 if (PyUnicode_CheckExact(s)) {
421 Py_INCREF(s);
422 PyUnicode_InternInPlace(&s);
423 return s;
424 }
425 else {
426 PyErr_Format(PyExc_TypeError,
427 "can't intern %.400s", s->ob_type->tp_name);
428 return NULL;
429 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000430}
431
432PyDoc_STRVAR(intern_doc,
433"intern(string) -> string\n\
434\n\
435``Intern'' the given string. This enters the string in the (global)\n\
436table of interned strings whose purpose is to speed up dictionary lookups.\n\
437Return the string itself or the previously interned string object with the\n\
438same value.");
439
440
Fred Drake5755ce62001-06-27 19:19:46 +0000441/*
442 * Cached interned string objects used for calling the profile and
443 * trace functions. Initialized by trace_init().
444 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000445static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000446
447static int
448trace_init(void)
449{
Nick Coghlan5a851672017-09-08 10:14:16 +1000450 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200451 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000452 "c_call", "c_exception", "c_return",
453 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200454 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000455 PyObject *name;
456 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000457 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (whatstrings[i] == NULL) {
459 name = PyUnicode_InternFromString(whatnames[i]);
460 if (name == NULL)
461 return -1;
462 whatstrings[i] = name;
463 }
464 }
465 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000466}
467
468
469static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100470call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200474 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000475
Victor Stinner78da82b2016-08-20 01:22:57 +0200476 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200478 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100479
Victor Stinner78da82b2016-08-20 01:22:57 +0200480 stack[0] = (PyObject *)frame;
481 stack[1] = whatstrings[what];
482 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000483
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200485 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000486
Victor Stinner78da82b2016-08-20 01:22:57 +0200487 PyFrame_LocalsToFast(frame, 1);
488 if (result == NULL) {
489 PyTraceBack_Here(frame);
490 }
491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000493}
494
495static int
496profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000501 if (arg == NULL)
502 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100503 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 if (result == NULL) {
505 PyEval_SetProfile(NULL, NULL);
506 return -1;
507 }
508 Py_DECREF(result);
509 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000510}
511
512static int
513trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000514 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 PyObject *callback;
517 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (what == PyTrace_CALL)
520 callback = self;
521 else
522 callback = frame->f_trace;
523 if (callback == NULL)
524 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100525 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 if (result == NULL) {
527 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200528 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 return -1;
530 }
531 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300532 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 }
534 else {
535 Py_DECREF(result);
536 }
537 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000538}
Fred Draked0838392001-06-16 21:02:31 +0000539
Fred Drake8b4d01d2000-05-09 19:57:01 +0000540static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000541sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000542{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000543 if (trace_init() == -1)
544 return NULL;
545 if (args == Py_None)
546 PyEval_SetTrace(NULL, NULL);
547 else
548 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200549 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000550}
551
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000552PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000553"settrace(function)\n\
554\n\
555Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000556function call. See the debugger chapter in the library manual."
557);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000558
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000559static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000560sys_gettrace(PyObject *self, PyObject *args)
561{
Victor Stinner50b48572018-11-01 01:51:40 +0100562 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000565 if (temp == NULL)
566 temp = Py_None;
567 Py_INCREF(temp);
568 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000569}
570
571PyDoc_STRVAR(gettrace_doc,
572"gettrace()\n\
573\n\
574Return the global debug tracing function set with sys.settrace.\n\
575See the debugger chapter in the library manual."
576);
577
578static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000579sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (trace_init() == -1)
582 return NULL;
583 if (args == Py_None)
584 PyEval_SetProfile(NULL, NULL);
585 else
586 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200587 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000588}
589
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000590PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000591"setprofile(function)\n\
592\n\
593Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000594and return. See the profiler chapter in the library manual."
595);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000596
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000597static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000598sys_getprofile(PyObject *self, PyObject *args)
599{
Victor Stinner50b48572018-11-01 01:51:40 +0100600 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (temp == NULL)
604 temp = Py_None;
605 Py_INCREF(temp);
606 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000607}
608
609PyDoc_STRVAR(getprofile_doc,
610"getprofile()\n\
611\n\
612Return the profiling function set with sys.setprofile.\n\
613See the profiler chapter in the library manual."
614);
615
616static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000617sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (PyErr_WarnEx(PyExc_DeprecationWarning,
620 "sys.getcheckinterval() and sys.setcheckinterval() "
621 "are deprecated. Use sys.setswitchinterval() "
622 "instead.", 1) < 0)
623 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200624
625 int check_interval;
626 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200628
629 PyInterpreterState *interp = _PyInterpreterState_Get();
630 interp->check_interval = check_interval;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200631 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000632}
633
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000634PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000635"setcheckinterval(n)\n\
636\n\
637Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000638n instructions. This also affects how often thread switches occur."
639);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000640
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000641static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000642sys_getcheckinterval(PyObject *self, PyObject *args)
643{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 if (PyErr_WarnEx(PyExc_DeprecationWarning,
645 "sys.getcheckinterval() and sys.setcheckinterval() "
646 "are deprecated. Use sys.getswitchinterval() "
647 "instead.", 1) < 0)
648 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200649 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600650 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000651}
652
653PyDoc_STRVAR(getcheckinterval_doc,
654"getcheckinterval() -> current check interval; see setcheckinterval()."
655);
656
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000657static PyObject *
658sys_setswitchinterval(PyObject *self, PyObject *args)
659{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000660 double d;
661 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
662 return NULL;
663 if (d <= 0.0) {
664 PyErr_SetString(PyExc_ValueError,
665 "switch interval must be strictly positive");
666 return NULL;
667 }
668 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200669 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000670}
671
672PyDoc_STRVAR(setswitchinterval_doc,
673"setswitchinterval(n)\n\
674\n\
675Set the ideal thread switching delay inside the Python interpreter\n\
676The actual frequency of switching threads can be lower if the\n\
677interpreter executes long sequences of uninterruptible code\n\
678(this is implementation-specific and workload-dependent).\n\
679\n\
680The parameter must represent the desired switching delay in seconds\n\
681A typical value is 0.005 (5 milliseconds)."
682);
683
684static PyObject *
685sys_getswitchinterval(PyObject *self, PyObject *args)
686{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000687 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000688}
689
690PyDoc_STRVAR(getswitchinterval_doc,
691"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
692);
693
Tim Peterse5e065b2003-07-06 18:36:54 +0000694static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000695sys_setrecursionlimit(PyObject *self, PyObject *args)
696{
Victor Stinner50856d52015-10-13 00:11:21 +0200697 int new_limit, mark;
698 PyThreadState *tstate;
699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
701 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200702
703 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000704 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200705 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 return NULL;
707 }
Victor Stinner50856d52015-10-13 00:11:21 +0200708
709 /* Issue #25274: When the recursion depth hits the recursion limit in
710 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
711 set to 1 and a RecursionError is raised. The overflowed flag is reset
712 to 0 when the recursion depth goes below the low-water mark: see
713 Py_LeaveRecursiveCall().
714
715 Reject too low new limit if the current recursion depth is higher than
716 the new low-water mark. Otherwise it may not be possible anymore to
717 reset the overflowed flag to 0. */
718 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100719 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200720 if (tstate->recursion_depth >= mark) {
721 PyErr_Format(PyExc_RecursionError,
722 "cannot set the recursion limit to %i at "
723 "the recursion depth %i: the limit is too low",
724 new_limit, tstate->recursion_depth);
725 return NULL;
726 }
727
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000728 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200729 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000730}
731
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800732/*[clinic input]
733sys.set_coroutine_origin_tracking_depth
734
735 depth: int
736
737Enable or disable origin tracking for coroutine objects in this thread.
738
739Coroutine objects will track 'depth' frames of traceback information about
740where they came from, available in their cr_origin attribute. Set depth of 0
741to disable.
742[clinic start generated code]*/
743
744static PyObject *
745sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
746/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
747{
748 if (depth < 0) {
749 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
750 return NULL;
751 }
752 _PyEval_SetCoroutineOriginTrackingDepth(depth);
753 Py_RETURN_NONE;
754}
755
756/*[clinic input]
757sys.get_coroutine_origin_tracking_depth -> int
758
759Check status of origin tracking for coroutine objects in this thread.
760[clinic start generated code]*/
761
762static int
763sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
764/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
765{
766 return _PyEval_GetCoroutineOriginTrackingDepth();
767}
768
Yury Selivanov75445082015-05-11 22:57:16 -0400769static PyObject *
770sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
771{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800772 if (PyErr_WarnEx(PyExc_DeprecationWarning,
773 "set_coroutine_wrapper is deprecated", 1) < 0) {
774 return NULL;
775 }
776
Yury Selivanov75445082015-05-11 22:57:16 -0400777 if (wrapper != Py_None) {
778 if (!PyCallable_Check(wrapper)) {
779 PyErr_Format(PyExc_TypeError,
780 "callable expected, got %.50s",
781 Py_TYPE(wrapper)->tp_name);
782 return NULL;
783 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400784 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400785 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400786 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400787 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400788 }
Yury Selivanov75445082015-05-11 22:57:16 -0400789 Py_RETURN_NONE;
790}
791
792PyDoc_STRVAR(set_coroutine_wrapper_doc,
793"set_coroutine_wrapper(wrapper)\n\
794\n\
795Set a wrapper for coroutine objects."
796);
797
798static PyObject *
799sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
800{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800801 if (PyErr_WarnEx(PyExc_DeprecationWarning,
802 "get_coroutine_wrapper is deprecated", 1) < 0) {
803 return NULL;
804 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400805 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400806 if (wrapper == NULL) {
807 wrapper = Py_None;
808 }
809 Py_INCREF(wrapper);
810 return wrapper;
811}
812
813PyDoc_STRVAR(get_coroutine_wrapper_doc,
814"get_coroutine_wrapper()\n\
815\n\
816Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
817);
818
819
Yury Selivanoveb636452016-09-08 22:01:51 -0700820static PyTypeObject AsyncGenHooksType;
821
822PyDoc_STRVAR(asyncgen_hooks_doc,
823"asyncgen_hooks\n\
824\n\
825A struct sequence providing information about asynhronous\n\
826generators hooks. The attributes are read only.");
827
828static PyStructSequence_Field asyncgen_hooks_fields[] = {
829 {"firstiter", "Hook to intercept first iteration"},
830 {"finalizer", "Hook to intercept finalization"},
831 {0}
832};
833
834static PyStructSequence_Desc asyncgen_hooks_desc = {
835 "asyncgen_hooks", /* name */
836 asyncgen_hooks_doc, /* doc */
837 asyncgen_hooks_fields , /* fields */
838 2
839};
840
841
842static PyObject *
843sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
844{
845 static char *keywords[] = {"firstiter", "finalizer", NULL};
846 PyObject *firstiter = NULL;
847 PyObject *finalizer = NULL;
848
849 if (!PyArg_ParseTupleAndKeywords(
850 args, kw, "|OO", keywords,
851 &firstiter, &finalizer)) {
852 return NULL;
853 }
854
855 if (finalizer && finalizer != Py_None) {
856 if (!PyCallable_Check(finalizer)) {
857 PyErr_Format(PyExc_TypeError,
858 "callable finalizer expected, got %.50s",
859 Py_TYPE(finalizer)->tp_name);
860 return NULL;
861 }
862 _PyEval_SetAsyncGenFinalizer(finalizer);
863 }
864 else if (finalizer == Py_None) {
865 _PyEval_SetAsyncGenFinalizer(NULL);
866 }
867
868 if (firstiter && firstiter != Py_None) {
869 if (!PyCallable_Check(firstiter)) {
870 PyErr_Format(PyExc_TypeError,
871 "callable firstiter expected, got %.50s",
872 Py_TYPE(firstiter)->tp_name);
873 return NULL;
874 }
875 _PyEval_SetAsyncGenFirstiter(firstiter);
876 }
877 else if (firstiter == Py_None) {
878 _PyEval_SetAsyncGenFirstiter(NULL);
879 }
880
881 Py_RETURN_NONE;
882}
883
884PyDoc_STRVAR(set_asyncgen_hooks_doc,
885"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
886\n\
887Set a finalizer for async generators objects."
888);
889
890static PyObject *
891sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
892{
893 PyObject *res;
894 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
895 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
896
897 res = PyStructSequence_New(&AsyncGenHooksType);
898 if (res == NULL) {
899 return NULL;
900 }
901
902 if (firstiter == NULL) {
903 firstiter = Py_None;
904 }
905
906 if (finalizer == NULL) {
907 finalizer = Py_None;
908 }
909
910 Py_INCREF(firstiter);
911 PyStructSequence_SET_ITEM(res, 0, firstiter);
912
913 Py_INCREF(finalizer);
914 PyStructSequence_SET_ITEM(res, 1, finalizer);
915
916 return res;
917}
918
919PyDoc_STRVAR(get_asyncgen_hooks_doc,
920"get_asyncgen_hooks()\n\
921\n\
922Return a namedtuple of installed asynchronous generators hooks \
923(firstiter, finalizer)."
924);
925
926
Mark Dickinsondc787d22010-05-23 13:33:13 +0000927static PyTypeObject Hash_InfoType;
928
929PyDoc_STRVAR(hash_info_doc,
930"hash_info\n\
931\n\
932A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100933hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000934
935static PyStructSequence_Field hash_info_fields[] = {
936 {"width", "width of the type used for hashing, in bits"},
937 {"modulus", "prime number giving the modulus on which the hash "
938 "function is based"},
939 {"inf", "value to be used for hash of a positive infinity"},
940 {"nan", "value to be used for hash of a nan"},
941 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100942 {"algorithm", "name of the algorithm for hashing of str, bytes and "
943 "memoryviews"},
944 {"hash_bits", "internal output size of hash algorithm"},
945 {"seed_bits", "seed size of hash algorithm"},
946 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000947 {NULL, NULL}
948};
949
950static PyStructSequence_Desc hash_info_desc = {
951 "sys.hash_info",
952 hash_info_doc,
953 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100954 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000955};
956
Matthias Klosed885e952010-07-06 10:53:30 +0000957static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000958get_hash_info(void)
959{
960 PyObject *hash_info;
961 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100962 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000963 hash_info = PyStructSequence_New(&Hash_InfoType);
964 if (hash_info == NULL)
965 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100966 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000967 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000968 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000969 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000970 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000971 PyStructSequence_SET_ITEM(hash_info, field++,
972 PyLong_FromLong(_PyHASH_INF));
973 PyStructSequence_SET_ITEM(hash_info, field++,
974 PyLong_FromLong(_PyHASH_NAN));
975 PyStructSequence_SET_ITEM(hash_info, field++,
976 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100977 PyStructSequence_SET_ITEM(hash_info, field++,
978 PyUnicode_FromString(hashfunc->name));
979 PyStructSequence_SET_ITEM(hash_info, field++,
980 PyLong_FromLong(hashfunc->hash_bits));
981 PyStructSequence_SET_ITEM(hash_info, field++,
982 PyLong_FromLong(hashfunc->seed_bits));
983 PyStructSequence_SET_ITEM(hash_info, field++,
984 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000985 if (PyErr_Occurred()) {
986 Py_CLEAR(hash_info);
987 return NULL;
988 }
989 return hash_info;
990}
991
992
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000993PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000994"setrecursionlimit(n)\n\
995\n\
996Set the maximum depth of the Python interpreter stack to n. This\n\
997limit prevents infinite recursion from causing an overflow of the C\n\
998stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000999dependent."
1000);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001001
1002static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301003sys_getrecursionlimit(PyObject *self, PyObject *Py_UNUSED(ignored))
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001004{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001005 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001006}
1007
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001008PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001009"getrecursionlimit()\n\
1010\n\
1011Return the current value of the recursion limit, the maximum depth\n\
1012of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001013recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001014);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001015
Mark Hammond8696ebc2002-10-08 02:44:31 +00001016#ifdef MS_WINDOWS
1017PyDoc_STRVAR(getwindowsversion_doc,
1018"getwindowsversion()\n\
1019\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001020Return information about the running version of Windows as a named tuple.\n\
1021The members are named: major, minor, build, platform, service_pack,\n\
1022service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001023backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001024All elements are numbers, except service_pack and platform_type which are\n\
1025strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1026Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1027server. Platform_version is a 3-tuple containing a version number that is\n\
1028intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001029);
1030
Eric Smithf7bb5782010-01-27 00:44:57 +00001031static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1032
1033static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001034 {"major", "Major version number"},
1035 {"minor", "Minor version number"},
1036 {"build", "Build number"},
1037 {"platform", "Operating system platform"},
1038 {"service_pack", "Latest Service Pack installed on the system"},
1039 {"service_pack_major", "Service Pack major version number"},
1040 {"service_pack_minor", "Service Pack minor version number"},
1041 {"suite_mask", "Bit mask identifying available product suites"},
1042 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001043 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001045};
1046
1047static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 "sys.getwindowsversion", /* name */
1049 getwindowsversion_doc, /* doc */
1050 windows_version_fields, /* fields */
1051 5 /* For backward compatibility,
1052 only the first 5 items are accessible
1053 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001054};
1055
Steve Dower3e96f322015-03-02 08:01:10 -08001056/* Disable deprecation warnings about GetVersionEx as the result is
1057 being passed straight through to the caller, who is responsible for
1058 using it correctly. */
1059#pragma warning(push)
1060#pragma warning(disable:4996)
1061
Mark Hammond8696ebc2002-10-08 02:44:31 +00001062static PyObject *
1063sys_getwindowsversion(PyObject *self)
1064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 PyObject *version;
1066 int pos = 0;
1067 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001068 DWORD realMajor, realMinor, realBuild;
1069 HANDLE hKernel32;
1070 wchar_t kernel32_path[MAX_PATH];
1071 LPVOID verblock;
1072 DWORD verblock_size;
1073
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 ver.dwOSVersionInfoSize = sizeof(ver);
1075 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1076 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 version = PyStructSequence_New(&WindowsVersionType);
1079 if (version == NULL)
1080 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1083 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1084 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1085 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1086 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1087 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1088 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1089 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1090 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001091
Steve Dower74f4af72016-09-17 17:27:48 -07001092 realMajor = ver.dwMajorVersion;
1093 realMinor = ver.dwMinorVersion;
1094 realBuild = ver.dwBuildNumber;
1095
1096 // GetVersion will lie if we are running in a compatibility mode.
1097 // We need to read the version info from a system file resource
1098 // to accurately identify the OS version. If we fail for any reason,
1099 // just return whatever GetVersion said.
1100 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1101 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1102 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1103 (verblock = PyMem_RawMalloc(verblock_size))) {
1104 VS_FIXEDFILEINFO *ffi;
1105 UINT ffi_len;
1106
1107 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1108 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1109 realMajor = HIWORD(ffi->dwProductVersionMS);
1110 realMinor = LOWORD(ffi->dwProductVersionMS);
1111 realBuild = HIWORD(ffi->dwProductVersionLS);
1112 }
1113 PyMem_RawFree(verblock);
1114 }
Segev Finer48fb7662017-06-04 20:52:27 +03001115 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1116 realMajor,
1117 realMinor,
1118 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001119 ));
1120
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001121 if (PyErr_Occurred()) {
1122 Py_DECREF(version);
1123 return NULL;
1124 }
Steve Dower74f4af72016-09-17 17:27:48 -07001125
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001126 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001127}
1128
Steve Dower3e96f322015-03-02 08:01:10 -08001129#pragma warning(pop)
1130
Steve Dowercc16be82016-09-08 10:35:16 -07001131PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1132"_enablelegacywindowsfsencoding()\n\
1133\n\
1134Changes the default filesystem encoding to mbcs:replace for consistency\n\
1135with earlier versions of Python. See PEP 529 for more information.\n\
1136\n\
oldkaa0735f2018-02-02 16:52:55 +08001137This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001138environment variable before launching Python."
1139);
1140
1141static PyObject *
1142sys_enablelegacywindowsfsencoding(PyObject *self)
1143{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001144 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1145 _PyCoreConfig *config = &interp->core_config;
1146
1147 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1148 char *encoding = _PyMem_RawStrdup("mbcs");
1149 char *errors = _PyMem_RawStrdup("replace");
1150 if (encoding == NULL || errors == NULL) {
1151 PyMem_Free(encoding);
1152 PyMem_Free(errors);
1153 PyErr_NoMemory();
1154 return NULL;
1155 }
1156
1157 PyMem_RawFree(config->filesystem_encoding);
1158 config->filesystem_encoding = encoding;
1159 PyMem_RawFree(config->filesystem_errors);
1160 config->filesystem_errors = errors;
1161
1162 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1163 config->filesystem_errors) < 0) {
1164 PyErr_NoMemory();
1165 return NULL;
1166 }
1167
Steve Dowercc16be82016-09-08 10:35:16 -07001168 Py_RETURN_NONE;
1169}
1170
Mark Hammond8696ebc2002-10-08 02:44:31 +00001171#endif /* MS_WINDOWS */
1172
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001173#ifdef HAVE_DLOPEN
1174static PyObject *
1175sys_setdlopenflags(PyObject *self, PyObject *args)
1176{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 int new_val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001178 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1179 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001180 PyInterpreterState *interp = _PyInterpreterState_Get();
1181 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001182 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001183}
1184
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001185PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001186"setdlopenflags(n) -> None\n\
1187\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001188Set the flags used by the interpreter for dlopen calls, such as when the\n\
1189interpreter loads extension modules. Among other things, this will enable\n\
1190a lazy resolving of symbols when importing a module, if called as\n\
1191sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001192sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001193can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001194
1195static PyObject *
1196sys_getdlopenflags(PyObject *self, PyObject *args)
1197{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001198 PyInterpreterState *interp = _PyInterpreterState_Get();
1199 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001200}
1201
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001202PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001203"getdlopenflags() -> int\n\
1204\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001205Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001206The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001207
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001208#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001209
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001210#ifdef USE_MALLOPT
1211/* Link with -lmalloc (or -lmpc) on an SGI */
1212#include <malloc.h>
1213
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001214static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001215sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001216{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 int flag;
1218 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1219 return NULL;
1220 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001221 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001222}
1223#endif /* USE_MALLOPT */
1224
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001225size_t
1226_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001230 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 /* Make sure the type is initialized. float gets initialized late */
1233 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001234 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001235
Benjamin Petersonce798522012-01-22 11:24:29 -05001236 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (method == NULL) {
1238 if (!PyErr_Occurred())
1239 PyErr_Format(PyExc_TypeError,
1240 "Type %.100s doesn't define __sizeof__",
1241 Py_TYPE(o)->tp_name);
1242 }
1243 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001244 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 Py_DECREF(method);
1246 }
1247
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001248 if (res == NULL)
1249 return (size_t)-1;
1250
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001251 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001252 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001253 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001254 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001256 if (size < 0) {
1257 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1258 return (size_t)-1;
1259 }
1260
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001262 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001263 return ((size_t)size) + sizeof(PyGC_Head);
1264 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001265}
1266
1267static PyObject *
1268sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1269{
1270 static char *kwlist[] = {"object", "default", 0};
1271 size_t size;
1272 PyObject *o, *dflt = NULL;
1273
1274 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1275 kwlist, &o, &dflt))
1276 return NULL;
1277
1278 size = _PySys_GetSizeOf(o);
1279
1280 if (size == (size_t)-1 && PyErr_Occurred()) {
1281 /* Has a default value been given */
1282 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1283 PyErr_Clear();
1284 Py_INCREF(dflt);
1285 return dflt;
1286 }
1287 else
1288 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001290
1291 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001292}
1293
1294PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001295"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001296\n\
1297Return the size of object in bytes.");
1298
1299static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001300sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001301{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001303}
1304
Tim Peters4be93d02002-07-07 19:59:50 +00001305#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001306static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301307sys_gettotalrefcount(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Hammond440d8982000-06-20 08:12:48 +00001308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001310}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001311#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001312
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001313PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001314"getrefcount(object) -> integer\n\
1315\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001316Return the reference count of object. The count returned is generally\n\
1317one higher than you might expect, because it includes the (temporary)\n\
1318reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001319);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001320
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001321static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301322sys_getallocatedblocks(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001323{
1324 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1325}
1326
1327PyDoc_STRVAR(getallocatedblocks_doc,
1328"getallocatedblocks() -> integer\n\
1329\n\
1330Return the number of memory blocks currently allocated, regardless of their\n\
1331size."
1332);
1333
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001334#ifdef COUNT_ALLOCS
1335static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001336sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001337{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001338 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001339
Pablo Galindo49c75a82018-10-28 15:02:17 +00001340 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001341}
1342#endif
1343
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001344PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001345"_getframe([depth]) -> frameobject\n\
1346\n\
1347Return a frame object from the call stack. If optional integer depth is\n\
1348given, return the frame object that many calls below the top of the stack.\n\
1349If that is deeper than the call stack, ValueError is raised. The default\n\
1350for depth is zero, returning the frame at the top of the call stack.\n\
1351\n\
1352This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001353purposes only."
1354);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001355
1356static PyObject *
1357sys_getframe(PyObject *self, PyObject *args)
1358{
Victor Stinner50b48572018-11-01 01:51:40 +01001359 PyFrameObject *f = _PyThreadState_GET()->frame;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1363 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 while (depth > 0 && f != NULL) {
1366 f = f->f_back;
1367 --depth;
1368 }
1369 if (f == NULL) {
1370 PyErr_SetString(PyExc_ValueError,
1371 "call stack is not deep enough");
1372 return NULL;
1373 }
1374 Py_INCREF(f);
1375 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001376}
1377
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001378PyDoc_STRVAR(current_frames_doc,
1379"_current_frames() -> dictionary\n\
1380\n\
1381Return a dictionary mapping each current thread T's thread id to T's\n\
1382current stack frame.\n\
1383\n\
1384This function should be used for specialized purposes only."
1385);
1386
1387static PyObject *
1388sys_current_frames(PyObject *self, PyObject *noargs)
1389{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001390 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001391}
1392
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001393PyDoc_STRVAR(call_tracing_doc,
1394"call_tracing(func, args) -> object\n\
1395\n\
1396Call func(*args), while tracing is enabled. The tracing state is\n\
1397saved, and restored afterwards. This is intended to be called from\n\
1398a debugger from a checkpoint, to recursively debug some other code."
1399);
1400
1401static PyObject *
1402sys_call_tracing(PyObject *self, PyObject *args)
1403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 PyObject *func, *funcargs;
1405 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1406 return NULL;
1407 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001408}
1409
Jeremy Hylton985eba52003-02-05 23:13:00 +00001410PyDoc_STRVAR(callstats_doc,
1411"callstats() -> tuple of integers\n\
1412\n\
1413Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1414when Python was built. Otherwise, return None.\n\
1415\n\
1416When enabled, this function returns detailed, implementation-specific\n\
1417details about the number of function calls executed. The return value is\n\
1418a 11-tuple where the entries in the tuple are counts of:\n\
14190. all function calls\n\
14201. calls to PyFunction_Type objects\n\
14212. PyFunction calls that do not create an argument tuple\n\
14223. PyFunction calls that do not create an argument tuple\n\
1423 and bypass PyEval_EvalCodeEx()\n\
14244. PyMethod calls\n\
14255. PyMethod calls on bound methods\n\
14266. PyType calls\n\
14277. PyCFunction calls\n\
14288. generator calls\n\
14299. All other calls\n\
143010. Number of stack pops performed by call_function()"
1431);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001432
Victor Stinner048afd92016-11-28 11:59:04 +01001433static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301434sys_callstats(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner048afd92016-11-28 11:59:04 +01001435{
1436 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1437 "sys.callstats() has been deprecated in Python 3.7 "
1438 "and will be removed in the future", 1) < 0) {
1439 return NULL;
1440 }
1441
1442 Py_RETURN_NONE;
1443}
1444
1445
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001446#ifdef __cplusplus
1447extern "C" {
1448#endif
1449
David Malcolm49526f42012-06-22 14:55:41 -04001450static PyObject *
1451sys_debugmallocstats(PyObject *self, PyObject *args)
1452{
1453#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001454 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001455 fputc('\n', stderr);
1456 }
David Malcolm49526f42012-06-22 14:55:41 -04001457#endif
1458 _PyObject_DebugTypeStats(stderr);
1459
1460 Py_RETURN_NONE;
1461}
1462PyDoc_STRVAR(debugmallocstats_doc,
1463"_debugmallocstats()\n\
1464\n\
1465Print summary info to stderr about the state of\n\
1466pymalloc's structures.\n\
1467\n\
1468In Py_DEBUG mode, also perform some expensive internal consistency\n\
1469checks.\n\
1470");
1471
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001472#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001473/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001474extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001475#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001476
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001477#ifdef DYNAMIC_EXECUTION_PROFILE
1478/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001479extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001480#endif
1481
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001482#ifdef __cplusplus
1483}
1484#endif
1485
Christian Heimes15ebc882008-02-04 18:48:49 +00001486static PyObject *
1487sys_clear_type_cache(PyObject* self, PyObject* args)
1488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyType_ClearCache();
1490 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001491}
1492
1493PyDoc_STRVAR(sys_clear_type_cache__doc__,
1494"_clear_type_cache() -> None\n\
1495Clear the internal type lookup cache.");
1496
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001497static PyObject *
1498sys_is_finalizing(PyObject* self, PyObject* args)
1499{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001500 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001501}
1502
1503PyDoc_STRVAR(is_finalizing_doc,
1504"is_finalizing()\n\
1505Return True if Python is exiting.");
1506
Christian Heimes15ebc882008-02-04 18:48:49 +00001507
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001508#ifdef ANDROID_API_LEVEL
1509PyDoc_STRVAR(getandroidapilevel_doc,
1510"getandroidapilevel()\n\
1511\n\
1512Return the build time API version of Android as an integer.");
1513
1514static PyObject *
1515sys_getandroidapilevel(PyObject *self)
1516{
1517 return PyLong_FromLong(ANDROID_API_LEVEL);
1518}
1519#endif /* ANDROID_API_LEVEL */
1520
1521
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001522static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001524 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1525 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301526 {"callstats", sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 callstats_doc},
1528 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1529 sys_clear_type_cache__doc__},
1530 {"_current_frames", sys_current_frames, METH_NOARGS,
1531 current_frames_doc},
1532 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1533 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1534 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1535 {"exit", sys_exit, METH_VARARGS, exit_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301536 {"getdefaultencoding", sys_getdefaultencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001538#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1540 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001541#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301542 {"getallocatedblocks", sys_getallocatedblocks, METH_NOARGS,
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001543 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001544#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001546#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001547#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001549#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301550 {"getfilesystemencoding", sys_getfilesystemencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 METH_NOARGS, getfilesystemencoding_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301552 { "getfilesystemencodeerrors", sys_getfilesystemencodeerrors,
Steve Dowercc16be82016-09-08 10:35:16 -07001553 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001554#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001556#endif
1557#ifdef Py_REF_DEBUG
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301558 {"gettotalrefcount", sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001559#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301561 {"getrecursionlimit", sys_getrecursionlimit, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 getrecursionlimit_doc},
1563 {"getsizeof", (PyCFunction)sys_getsizeof,
1564 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1565 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001566#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1568 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001569 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1570 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001571#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001573 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001574#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001576#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1578 setcheckinterval_doc},
1579 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1580 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1582 setswitchinterval_doc},
1583 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1584 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001585#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1587 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001588#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1590 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1591 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1592 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 {"settrace", sys_settrace, METH_O, settrace_doc},
1594 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1595 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001596 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001597 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001598 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1599 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001600 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1601 set_coroutine_wrapper_doc},
1602 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1603 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001604 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001605 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1606 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1607 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001608#ifdef ANDROID_API_LEVEL
1609 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1610 getandroidapilevel_doc},
1611#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001613};
1614
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001615static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001616list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyObject *list = PyList_New(0);
1619 int i;
1620 if (list == NULL)
1621 return NULL;
1622 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1623 PyObject *name = PyUnicode_FromString(
1624 PyImport_Inittab[i].name);
1625 if (name == NULL)
1626 break;
1627 PyList_Append(list, name);
1628 Py_DECREF(name);
1629 }
1630 if (PyList_Sort(list) != 0) {
1631 Py_DECREF(list);
1632 list = NULL;
1633 }
1634 if (list) {
1635 PyObject *v = PyList_AsTuple(list);
1636 Py_DECREF(list);
1637 list = v;
1638 }
1639 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001640}
1641
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001642/* Pre-initialization support for sys.warnoptions and sys._xoptions
1643 *
1644 * Modern internal code paths:
1645 * These APIs get called after _Py_InitializeCore and get to use the
1646 * regular CPython list, dict, and unicode APIs.
1647 *
1648 * Legacy embedding code paths:
1649 * The multi-phase initialization API isn't public yet, so embedding
1650 * apps still need to be able configure sys.warnoptions and sys._xoptions
1651 * before they call Py_Initialize. To support this, we stash copies of
1652 * the supplied wchar * sequences in linked lists, and then migrate the
1653 * contents of those lists to the sys module in _PyInitializeCore.
1654 *
1655 */
1656
1657struct _preinit_entry {
1658 wchar_t *value;
1659 struct _preinit_entry *next;
1660};
1661
1662typedef struct _preinit_entry *_Py_PreInitEntry;
1663
1664static _Py_PreInitEntry _preinit_warnoptions = NULL;
1665static _Py_PreInitEntry _preinit_xoptions = NULL;
1666
1667static _Py_PreInitEntry
1668_alloc_preinit_entry(const wchar_t *value)
1669{
1670 /* To get this to work, we have to initialize the runtime implicitly */
1671 _PyRuntime_Initialize();
1672
1673 /* Force default allocator, so we can ensure that it also gets used to
1674 * destroy the linked list in _clear_preinit_entries.
1675 */
1676 PyMemAllocatorEx old_alloc;
1677 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1678
1679 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1680 if (node != NULL) {
1681 node->value = _PyMem_RawWcsdup(value);
1682 if (node->value == NULL) {
1683 PyMem_RawFree(node);
1684 node = NULL;
1685 };
1686 };
1687
1688 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1689 return node;
1690};
1691
1692static int
1693_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1694{
1695 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1696 if (new_entry == NULL) {
1697 return -1;
1698 }
1699 /* We maintain the linked list in this order so it's easy to play back
1700 * the add commands in the same order later on in _Py_InitializeCore
1701 */
1702 _Py_PreInitEntry last_entry = *optionlist;
1703 if (last_entry == NULL) {
1704 *optionlist = new_entry;
1705 } else {
1706 while (last_entry->next != NULL) {
1707 last_entry = last_entry->next;
1708 }
1709 last_entry->next = new_entry;
1710 }
1711 return 0;
1712};
1713
1714static void
1715_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1716{
1717 _Py_PreInitEntry current = *optionlist;
1718 *optionlist = NULL;
1719 /* Deallocate the nodes and their contents using the default allocator */
1720 PyMemAllocatorEx old_alloc;
1721 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1722 while (current != NULL) {
1723 _Py_PreInitEntry next = current->next;
1724 PyMem_RawFree(current->value);
1725 PyMem_RawFree(current);
1726 current = next;
1727 }
1728 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1729};
1730
1731static void
1732_clear_all_preinit_options(void)
1733{
1734 _clear_preinit_entries(&_preinit_warnoptions);
1735 _clear_preinit_entries(&_preinit_xoptions);
1736}
1737
1738static int
1739_PySys_ReadPreInitOptions(void)
1740{
1741 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001742 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001743 if (tstate == NULL) {
1744 /* Still don't have a thread state, so something is wrong! */
1745 return -1;
1746 }
1747 _Py_PreInitEntry entry = _preinit_warnoptions;
1748 while (entry != NULL) {
1749 PySys_AddWarnOption(entry->value);
1750 entry = entry->next;
1751 }
1752 entry = _preinit_xoptions;
1753 while (entry != NULL) {
1754 PySys_AddXOption(entry->value);
1755 entry = entry->next;
1756 }
1757
1758 _clear_all_preinit_options();
1759 return 0;
1760};
1761
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001762static PyObject *
1763get_warnoptions(void)
1764{
Eric Snowdae02762017-09-14 00:35:58 -07001765 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001766 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001767 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1768 * interpreter config. When that happens, we need to properly set
1769 * the `warnoptions` reference in the main interpreter config as well.
1770 *
1771 * For Python 3.7, we shouldn't be able to get here due to the
1772 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1773 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1774 * call optional for embedding applications, thus making this
1775 * reachable again.
1776 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001777 Py_XDECREF(warnoptions);
1778 warnoptions = PyList_New(0);
1779 if (warnoptions == NULL)
1780 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001781 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1782 Py_DECREF(warnoptions);
1783 return NULL;
1784 }
1785 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001786 }
1787 return warnoptions;
1788}
Guido van Rossum23fff912000-12-15 22:02:05 +00001789
1790void
1791PySys_ResetWarnOptions(void)
1792{
Victor Stinner50b48572018-11-01 01:51:40 +01001793 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001794 if (tstate == NULL) {
1795 _clear_preinit_entries(&_preinit_warnoptions);
1796 return;
1797 }
1798
Eric Snowdae02762017-09-14 00:35:58 -07001799 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001800 if (warnoptions == NULL || !PyList_Check(warnoptions))
1801 return;
1802 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001803}
1804
Victor Stinnere1b29952018-10-30 14:31:42 +01001805static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001806_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001807{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001808 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001809 if (warnoptions == NULL) {
1810 return -1;
1811 }
1812 if (PyList_Append(warnoptions, option)) {
1813 return -1;
1814 }
1815 return 0;
1816}
1817
1818void
1819PySys_AddWarnOptionUnicode(PyObject *option)
1820{
Victor Stinnere1b29952018-10-30 14:31:42 +01001821 if (_PySys_AddWarnOptionWithError(option) < 0) {
1822 /* No return value, therefore clear error state if possible */
1823 if (_PyThreadState_UncheckedGet()) {
1824 PyErr_Clear();
1825 }
1826 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001827}
1828
1829void
1830PySys_AddWarnOption(const wchar_t *s)
1831{
Victor Stinner50b48572018-11-01 01:51:40 +01001832 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001833 if (tstate == NULL) {
1834 _append_preinit_entry(&_preinit_warnoptions, s);
1835 return;
1836 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001837 PyObject *unicode;
1838 unicode = PyUnicode_FromWideChar(s, -1);
1839 if (unicode == NULL)
1840 return;
1841 PySys_AddWarnOptionUnicode(unicode);
1842 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001843}
1844
Christian Heimes33fe8092008-04-13 13:53:33 +00001845int
1846PySys_HasWarnOptions(void)
1847{
Eric Snowdae02762017-09-14 00:35:58 -07001848 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001849 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1850}
1851
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001852static PyObject *
1853get_xoptions(void)
1854{
Eric Snowdae02762017-09-14 00:35:58 -07001855 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001856 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001857 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1858 * interpreter config. When that happens, we need to properly set
1859 * the `xoptions` reference in the main interpreter config as well.
1860 *
1861 * For Python 3.7, we shouldn't be able to get here due to the
1862 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1863 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1864 * call optional for embedding applications, thus making this
1865 * reachable again.
1866 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001867 Py_XDECREF(xoptions);
1868 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001869 if (xoptions == NULL)
1870 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001871 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1872 Py_DECREF(xoptions);
1873 return NULL;
1874 }
1875 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001876 }
1877 return xoptions;
1878}
1879
Victor Stinnere1b29952018-10-30 14:31:42 +01001880static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001881_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001882{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001883 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001884
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001885 PyObject *opts = get_xoptions();
1886 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001887 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001888 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001889
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001890 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001891 if (!name_end) {
1892 name = PyUnicode_FromWideChar(s, -1);
1893 value = Py_True;
1894 Py_INCREF(value);
1895 }
1896 else {
1897 name = PyUnicode_FromWideChar(s, name_end - s);
1898 value = PyUnicode_FromWideChar(name_end + 1, -1);
1899 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001900 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001901 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001902 }
1903 if (PyDict_SetItem(opts, name, value) < 0) {
1904 goto error;
1905 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001906 Py_DECREF(name);
1907 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001908 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001909
1910error:
1911 Py_XDECREF(name);
1912 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001913 return -1;
1914}
1915
1916void
1917PySys_AddXOption(const wchar_t *s)
1918{
Victor Stinner50b48572018-11-01 01:51:40 +01001919 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001920 if (tstate == NULL) {
1921 _append_preinit_entry(&_preinit_xoptions, s);
1922 return;
1923 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001924 if (_PySys_AddXOptionWithError(s) < 0) {
1925 /* No return value, therefore clear error state if possible */
1926 if (_PyThreadState_UncheckedGet()) {
1927 PyErr_Clear();
1928 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001929 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001930}
1931
1932PyObject *
1933PySys_GetXOptions(void)
1934{
1935 return get_xoptions();
1936}
1937
Guido van Rossum40552d01998-08-06 03:34:39 +00001938/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1939 Two literals concatenated works just fine. If you have a K&R compiler
1940 or other abomination that however *does* understand longer strings,
1941 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001942PyDoc_VAR(sys_doc) =
1943PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001944"This module provides access to some objects used or maintained by the\n\
1945interpreter and to functions that interact strongly with the interpreter.\n\
1946\n\
1947Dynamic objects:\n\
1948\n\
1949argv -- command line arguments; argv[0] is the script pathname if known\n\
1950path -- module search path; path[0] is the script directory, else ''\n\
1951modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001952\n\
1953displayhook -- called to show results in an interactive session\n\
1954excepthook -- called to handle any uncaught exception other than SystemExit\n\
1955 To customize printing in an interactive session or to install a custom\n\
1956 top-level exception handler, assign other functions to replace these.\n\
1957\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001958stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001959stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001960stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001961 By assigning other file objects (or objects that behave like files)\n\
1962 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001963\n\
1964last_type -- type of last uncaught exception\n\
1965last_value -- value of last uncaught exception\n\
1966last_traceback -- traceback of last uncaught exception\n\
1967 These three are only available in an interactive session after a\n\
1968 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001969"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001970)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001971/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001972PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001973"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001974Static objects:\n\
1975\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001976builtin_module_names -- tuple of module names built into this interpreter\n\
1977copyright -- copyright notice pertaining to this interpreter\n\
1978exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001979executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001980float_info -- a struct sequence with information about the float implementation.\n\
1981float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001982hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001983hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001984implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001985int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001986maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001987maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001988platform -- platform identifier\n\
1989prefix -- prefix used to find the Python library\n\
1990thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001991version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001992version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001993"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001994)
Steve Dowercc16be82016-09-08 10:35:16 -07001995#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001996/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001997PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001998"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001999winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002000"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002001)
Steve Dowercc16be82016-09-08 10:35:16 -07002002#endif /* MS_COREDLL */
2003#ifdef MS_WINDOWS
2004/* concatenating string here */
2005PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002006"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002007"
2008)
2009#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002010PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002011"__stdin__ -- the original stdin; don't touch!\n\
2012__stdout__ -- the original stdout; don't touch!\n\
2013__stderr__ -- the original stderr; don't touch!\n\
2014__displayhook__ -- the original displayhook; don't touch!\n\
2015__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002016\n\
2017Functions:\n\
2018\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002019displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002020excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002021exc_info() -- return thread-safe information about the current exception\n\
2022exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002023getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002024getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002025getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002026getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002027getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002028gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002029setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002030setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002031setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002032setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002033settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002034"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002035)
Fred Drakeccede592000-08-14 20:59:57 +00002036/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002037
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002038
2039PyDoc_STRVAR(flags__doc__,
2040"sys.flags\n\
2041\n\
2042Flags provided through command line arguments or environment vars.");
2043
2044static PyTypeObject FlagsType;
2045
2046static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 {"inspect", "-i"},
2049 {"interactive", "-i"},
2050 {"optimize", "-O or -OO"},
2051 {"dont_write_bytecode", "-B"},
2052 {"no_user_site", "-s"},
2053 {"no_site", "-S"},
2054 {"ignore_environment", "-E"},
2055 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 /* {"unbuffered", "-u"}, */
2057 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002058 {"bytes_warning", "-b"},
2059 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002060 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002061 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002062 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002063 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002065};
2066
2067static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002068 "sys.flags", /* name */
2069 flags__doc__, /* doc */
2070 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002071 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002072};
2073
2074static PyObject*
2075make_flags(void)
2076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 int pos = 0;
2078 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002079 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002080
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002081 seq = PyStructSequence_New(&FlagsType);
2082 if (seq == NULL)
2083 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002084
2085#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002086 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002087
Victor Stinnerfbca9082018-08-30 00:50:45 +02002088 SetFlag(config->parser_debug);
2089 SetFlag(config->inspect);
2090 SetFlag(config->interactive);
2091 SetFlag(config->optimization_level);
2092 SetFlag(!config->write_bytecode);
2093 SetFlag(!config->user_site_directory);
2094 SetFlag(!config->site_import);
2095 SetFlag(!config->use_environment);
2096 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 /* SetFlag(saw_unbuffered_flag); */
2098 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002099 SetFlag(config->bytes_warning);
2100 SetFlag(config->quiet);
2101 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2102 SetFlag(config->isolated);
2103 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2104 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002105#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002108 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 return NULL;
2110 }
2111 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002112}
2113
Eric Smith0e5b5622009-02-06 01:32:42 +00002114PyDoc_STRVAR(version_info__doc__,
2115"sys.version_info\n\
2116\n\
2117Version information as a named tuple.");
2118
2119static PyTypeObject VersionInfoType;
2120
2121static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 {"major", "Major release number"},
2123 {"minor", "Minor release number"},
2124 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002125 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 {"serial", "Serial release number"},
2127 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002128};
2129
2130static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 "sys.version_info", /* name */
2132 version_info__doc__, /* doc */
2133 version_info_fields, /* fields */
2134 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002135};
2136
2137static PyObject *
2138make_version_info(void)
2139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 PyObject *version_info;
2141 char *s;
2142 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 version_info = PyStructSequence_New(&VersionInfoType);
2145 if (version_info == NULL) {
2146 return NULL;
2147 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002148
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 /*
2150 * These release level checks are mutually exclusive and cover
2151 * the field, so don't get too fancy with the pre-processor!
2152 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002153#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002155#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002157#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002159#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002161#endif
2162
2163#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002165#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002167
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 SetIntItem(PY_MAJOR_VERSION);
2169 SetIntItem(PY_MINOR_VERSION);
2170 SetIntItem(PY_MICRO_VERSION);
2171 SetStrItem(s);
2172 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002173#undef SetIntItem
2174#undef SetStrItem
2175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 if (PyErr_Occurred()) {
2177 Py_CLEAR(version_info);
2178 return NULL;
2179 }
2180 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002181}
2182
Brett Cannon3adc7b72012-07-09 14:22:12 -04002183/* sys.implementation values */
2184#define NAME "cpython"
2185const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002186#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2187#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002188#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002189const char *_PySys_ImplCacheTag = TAG;
2190#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002191#undef MAJOR
2192#undef MINOR
2193#undef TAG
2194
Barry Warsaw409da152012-06-03 16:18:47 -04002195static PyObject *
2196make_impl_info(PyObject *version_info)
2197{
2198 int res;
2199 PyObject *impl_info, *value, *ns;
2200
2201 impl_info = PyDict_New();
2202 if (impl_info == NULL)
2203 return NULL;
2204
2205 /* populate the dict */
2206
Brett Cannon3adc7b72012-07-09 14:22:12 -04002207 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002208 if (value == NULL)
2209 goto error;
2210 res = PyDict_SetItemString(impl_info, "name", value);
2211 Py_DECREF(value);
2212 if (res < 0)
2213 goto error;
2214
Brett Cannon3adc7b72012-07-09 14:22:12 -04002215 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002216 if (value == NULL)
2217 goto error;
2218 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2219 Py_DECREF(value);
2220 if (res < 0)
2221 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002222
2223 res = PyDict_SetItemString(impl_info, "version", version_info);
2224 if (res < 0)
2225 goto error;
2226
2227 value = PyLong_FromLong(PY_VERSION_HEX);
2228 if (value == NULL)
2229 goto error;
2230 res = PyDict_SetItemString(impl_info, "hexversion", value);
2231 Py_DECREF(value);
2232 if (res < 0)
2233 goto error;
2234
doko@ubuntu.com55532312016-06-14 08:55:19 +02002235#ifdef MULTIARCH
2236 value = PyUnicode_FromString(MULTIARCH);
2237 if (value == NULL)
2238 goto error;
2239 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2240 Py_DECREF(value);
2241 if (res < 0)
2242 goto error;
2243#endif
2244
Barry Warsaw409da152012-06-03 16:18:47 -04002245 /* dict ready */
2246
2247 ns = _PyNamespace_New(impl_info);
2248 Py_DECREF(impl_info);
2249 return ns;
2250
2251error:
2252 Py_CLEAR(impl_info);
2253 return NULL;
2254}
2255
Martin v. Löwis1a214512008-06-11 05:26:20 +00002256static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 PyModuleDef_HEAD_INIT,
2258 "sys",
2259 sys_doc,
2260 -1, /* multiple "initialization" just copies the module dict. */
2261 sys_methods,
2262 NULL,
2263 NULL,
2264 NULL,
2265 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002266};
2267
Eric Snow6b4be192017-05-22 21:36:03 -07002268/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002269#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002270 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002271 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002272 if (v == NULL) { \
2273 goto err_occurred; \
2274 } \
Victor Stinner58049602013-07-22 22:40:00 +02002275 res = PyDict_SetItemString(sysdict, key, v); \
2276 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002277 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002278 } \
2279 } while (0)
2280#define SET_SYS_FROM_STRING(key, value) \
2281 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002282 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283 if (v == NULL) { \
2284 goto err_occurred; \
2285 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002286 res = PyDict_SetItemString(sysdict, key, v); \
2287 Py_DECREF(v); \
2288 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002290 } \
2291 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002292
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002293
2294_PyInitError
2295_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002296{
2297 PyObject *m, *sysdict, *version_info;
2298 int res;
2299
Eric Snowd393c1b2017-09-14 12:18:12 -06002300 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002301 if (m == NULL) {
2302 return _Py_INIT_ERR("failed to create a module object");
2303 }
Eric Snow6b4be192017-05-22 21:36:03 -07002304 sysdict = PyModule_GetDict(m);
2305
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002307 Using shell redirection, you can redirect stdin to a directory,
2308 crashing the Python interpreter. Catch this common mistake here
2309 and output a useful error message. Note that under MS Windows,
2310 the shell already prevents that. */
2311#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002313 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002314 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002315 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002316 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2317 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 }
2319 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002320#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002321
Nick Coghland6009512014-11-20 21:39:37 +10002322 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002323
Victor Stinner8fea2522013-10-27 17:15:42 +01002324 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2325 PyDict_GetItemString(sysdict, "displayhook"));
2326 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2327 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002328 SET_SYS_FROM_STRING_BORROW(
2329 "__breakpointhook__",
2330 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002331 SET_SYS_FROM_STRING("version",
2332 PyUnicode_FromString(Py_GetVersion()));
2333 SET_SYS_FROM_STRING("hexversion",
2334 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002335 SET_SYS_FROM_STRING("_git",
2336 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2337 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002338 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 SET_SYS_FROM_STRING("api_version",
2340 PyLong_FromLong(PYTHON_API_VERSION));
2341 SET_SYS_FROM_STRING("copyright",
2342 PyUnicode_FromString(Py_GetCopyright()));
2343 SET_SYS_FROM_STRING("platform",
2344 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 SET_SYS_FROM_STRING("maxsize",
2346 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2347 SET_SYS_FROM_STRING("float_info",
2348 PyFloat_GetInfo());
2349 SET_SYS_FROM_STRING("int_info",
2350 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002351 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002352 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002353 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2354 goto type_init_failed;
2355 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002356 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002357 SET_SYS_FROM_STRING("hash_info",
2358 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002359 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002360 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002361 SET_SYS_FROM_STRING("builtin_module_names",
2362 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002363#if PY_BIG_ENDIAN
2364 SET_SYS_FROM_STRING("byteorder",
2365 PyUnicode_FromString("big"));
2366#else
2367 SET_SYS_FROM_STRING("byteorder",
2368 PyUnicode_FromString("little"));
2369#endif
Fred Drake099325e2000-08-14 15:47:03 +00002370
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002371#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 SET_SYS_FROM_STRING("dllhandle",
2373 PyLong_FromVoidPtr(PyWin_DLLhModule));
2374 SET_SYS_FROM_STRING("winver",
2375 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002376#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002377#ifdef ABIFLAGS
2378 SET_SYS_FROM_STRING("abiflags",
2379 PyUnicode_FromString(ABIFLAGS));
2380#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002383 if (VersionInfoType.tp_name == NULL) {
2384 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002385 &version_info_desc) < 0) {
2386 goto type_init_failed;
2387 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002388 }
Barry Warsaw409da152012-06-03 16:18:47 -04002389 version_info = make_version_info();
2390 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* prevent user from creating new instances */
2392 VersionInfoType.tp_init = NULL;
2393 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002394 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2395 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2396 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002397
Barry Warsaw409da152012-06-03 16:18:47 -04002398 /* implementation */
2399 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002402 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002403 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2404 goto type_init_failed;
2405 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002406 }
Eric Snow6b4be192017-05-22 21:36:03 -07002407 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002409
2410#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 /* getwindowsversion */
2412 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002413 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002414 &windows_version_desc) < 0) {
2415 goto type_init_failed;
2416 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 /* prevent user from creating new instances */
2418 WindowsVersionType.tp_init = NULL;
2419 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002420 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002421 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002422 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002423 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002424 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002425#endif
2426
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002428#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002429 SET_SYS_FROM_STRING("float_repr_style",
2430 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002431#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 SET_SYS_FROM_STRING("float_repr_style",
2433 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002434#endif
2435
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002436 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002437
Yury Selivanoveb636452016-09-08 22:01:51 -07002438 /* initialize asyncgen_hooks */
2439 if (AsyncGenHooksType.tp_name == NULL) {
2440 if (PyStructSequence_InitType2(
2441 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002442 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002443 }
2444 }
2445
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002446 if (PyErr_Occurred()) {
2447 goto err_occurred;
2448 }
2449
2450 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002451
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002452 return _Py_INIT_OK();
2453
2454type_init_failed:
2455 return _Py_INIT_ERR("failed to initialize a type");
2456
2457err_occurred:
2458 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002459}
2460
Eric Snow6b4be192017-05-22 21:36:03 -07002461#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002462
2463/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002464#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2465 do { \
2466 PyObject *v = (value); \
2467 if (v == NULL) \
2468 return -1; \
2469 res = PyDict_SetItemString(sysdict, key, v); \
2470 Py_DECREF(v); \
2471 if (res < 0) { \
2472 return res; \
2473 } \
2474 } while (0)
2475
2476int
Victor Stinnerfbca9082018-08-30 00:50:45 +02002477_PySys_EndInit(PyObject *sysdict, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002478{
Victor Stinnerfbca9082018-08-30 00:50:45 +02002479 const _PyCoreConfig *core_config = &interp->core_config;
2480 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002481 int res;
2482
Victor Stinner41264f12017-12-15 02:05:29 +01002483 /* _PyMainInterpreterConfig_Read() must set all these variables */
2484 assert(config->module_search_path != NULL);
2485 assert(config->executable != NULL);
2486 assert(config->prefix != NULL);
2487 assert(config->base_prefix != NULL);
2488 assert(config->exec_prefix != NULL);
2489 assert(config->base_exec_prefix != NULL);
2490
Victor Stinner37cd9822018-11-16 11:55:35 +01002491#define COPY_LIST(KEY, ATTR) \
2492 do { \
2493 assert(PyList_Check(config->ATTR)); \
2494 PyObject *list = PyList_GetSlice(config->ATTR, \
2495 0, PyList_GET_SIZE(config->ATTR)); \
2496 if (list == NULL) { \
2497 return -1; \
2498 } \
2499 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2500 Py_DECREF(list); \
2501 } while (0)
2502
2503 COPY_LIST("path", module_search_path);
2504
Victor Stinner41264f12017-12-15 02:05:29 +01002505 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2506 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2507 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2508 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2509 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2510
Carl Meyerb193fa92018-06-15 22:40:56 -06002511 if (config->pycache_prefix != NULL) {
2512 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2513 } else {
2514 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2515 }
2516
Victor Stinner41264f12017-12-15 02:05:29 +01002517 if (config->argv != NULL) {
2518 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2519 }
2520 if (config->warnoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002521 COPY_LIST("warnoptions", warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002522 }
2523 if (config->xoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002524 PyObject *dict = PyDict_Copy(config->xoptions);
2525 if (dict == NULL) {
2526 return -1;
2527 }
2528 SET_SYS_FROM_STRING_BORROW("_xoptions", dict);
2529 Py_DECREF(dict);
Victor Stinner41264f12017-12-15 02:05:29 +01002530 }
2531
Victor Stinner37cd9822018-11-16 11:55:35 +01002532#undef COPY_LIST
2533
Eric Snow6b4be192017-05-22 21:36:03 -07002534 /* Set flags to their final values */
2535 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2536 /* prevent user from creating new instances */
2537 FlagsType.tp_init = NULL;
2538 FlagsType.tp_new = NULL;
2539 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2540 if (res < 0) {
2541 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2542 return res;
2543 }
2544 PyErr_Clear();
2545 }
2546
2547 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002548 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002549
Eric Snowdae02762017-09-14 00:35:58 -07002550 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002551 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002552
Eric Snowdae02762017-09-14 00:35:58 -07002553 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002554 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002555
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002556 /* Transfer any sys.warnoptions and sys._xoptions set directly
2557 * by an embedding application from the linked list to the module. */
2558 if (_PySys_ReadPreInitOptions() != 0)
2559 return -1;
2560
Eric Snow6b4be192017-05-22 21:36:03 -07002561 if (PyErr_Occurred())
2562 return -1;
2563 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002564
2565err_occurred:
2566 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002567}
2568
Victor Stinner41264f12017-12-15 02:05:29 +01002569#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002570#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002571
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002572static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002573makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002575 int i, n;
2576 const wchar_t *p;
2577 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 n = 1;
2580 p = path;
2581 while ((p = wcschr(p, delim)) != NULL) {
2582 n++;
2583 p++;
2584 }
2585 v = PyList_New(n);
2586 if (v == NULL)
2587 return NULL;
2588 for (i = 0; ; i++) {
2589 p = wcschr(path, delim);
2590 if (p == NULL)
2591 p = path + wcslen(path); /* End of string */
2592 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2593 if (w == NULL) {
2594 Py_DECREF(v);
2595 return NULL;
2596 }
2597 PyList_SetItem(v, i, w);
2598 if (*p == '\0')
2599 break;
2600 path = p+1;
2601 }
2602 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002603}
2604
2605void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002606PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002608 PyObject *v;
2609 if ((v = makepathobject(path, DELIM)) == NULL)
2610 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002611 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 Py_FatalError("can't assign sys.path");
2613 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002614}
2615
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002616static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002617makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 PyObject *av;
2620 if (argc <= 0 || argv == NULL) {
2621 /* Ensure at least one (empty) argument is seen */
2622 static wchar_t *empty_argv[1] = {L""};
2623 argv = empty_argv;
2624 argc = 1;
2625 }
2626 av = PyList_New(argc);
2627 if (av != NULL) {
2628 int i;
2629 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002631 if (v == NULL) {
2632 Py_DECREF(av);
2633 av = NULL;
2634 break;
2635 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002636 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 }
2638 }
2639 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002640}
2641
Victor Stinner11a247d2017-12-13 21:05:57 +01002642void
2643PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002644{
2645 PyObject *av = makeargvobject(argc, argv);
2646 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002647 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002648 }
2649 if (PySys_SetObject("argv", av) != 0) {
2650 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002651 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002652 }
2653 Py_DECREF(av);
2654
2655 if (updatepath) {
2656 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2657 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002658 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2659 if (argv0 == NULL) {
2660 Py_FatalError("can't compute path0 from argv");
2661 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002662
Victor Stinner11a247d2017-12-13 21:05:57 +01002663 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2664 if (sys_path != NULL) {
2665 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2666 Py_DECREF(argv0);
2667 Py_FatalError("can't prepend path0 to sys.path");
2668 }
2669 }
2670 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002671 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002672}
Guido van Rossuma890e681998-05-12 14:59:24 +00002673
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002674void
2675PySys_SetArgv(int argc, wchar_t **argv)
2676{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002677 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002678}
2679
Victor Stinner14284c22010-04-23 12:02:30 +00002680/* Reimplementation of PyFile_WriteString() no calling indirectly
2681 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2682
2683static int
Victor Stinner79766632010-08-16 17:36:42 +00002684sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002685{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002686 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002687 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002688
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002689 if (file == NULL)
2690 return -1;
2691
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002692 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 if (writer == NULL)
2694 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002695
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002696 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 if (result == NULL) {
2698 goto error;
2699 } else {
2700 err = 0;
2701 goto finally;
2702 }
Victor Stinner14284c22010-04-23 12:02:30 +00002703
2704error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002706finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002708 Py_XDECREF(result);
2709 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002710}
2711
Victor Stinner79766632010-08-16 17:36:42 +00002712static int
2713sys_pyfile_write(const char *text, PyObject *file)
2714{
2715 PyObject *unicode = NULL;
2716 int err;
2717
2718 if (file == NULL)
2719 return -1;
2720
2721 unicode = PyUnicode_FromString(text);
2722 if (unicode == NULL)
2723 return -1;
2724
2725 err = sys_pyfile_write_unicode(unicode, file);
2726 Py_DECREF(unicode);
2727 return err;
2728}
Guido van Rossuma890e681998-05-12 14:59:24 +00002729
2730/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2731 Adapted from code submitted by Just van Rossum.
2732
2733 PySys_WriteStdout(format, ...)
2734 PySys_WriteStderr(format, ...)
2735
2736 The first function writes to sys.stdout; the second to sys.stderr. When
2737 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002738 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002739
Victor Stinner14284c22010-04-23 12:02:30 +00002740 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002741 signal handlers: they may raise a new exception whereas sys_write()
2742 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002743
Guido van Rossuma890e681998-05-12 14:59:24 +00002744 Both take a printf-style format string as their first argument followed
2745 by a variable length argument list determined by the format string.
2746
2747 *** WARNING ***
2748
2749 The format should limit the total size of the formatted output string to
2750 1000 bytes. In particular, this means that no unrestricted "%s" formats
2751 should occur; these should be limited using "%.<N>s where <N> is a
2752 decimal number calculated so that <N> plus the maximum size of other
2753 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2754 which can print hundreds of digits for very large numbers.
2755
2756 */
2757
2758static void
Victor Stinner09054372013-11-06 22:41:44 +01002759sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002760{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 PyObject *file;
2762 PyObject *error_type, *error_value, *error_traceback;
2763 char buffer[1001];
2764 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002767 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2769 if (sys_pyfile_write(buffer, file) != 0) {
2770 PyErr_Clear();
2771 fputs(buffer, fp);
2772 }
2773 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2774 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002775 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 }
2778 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002779}
2780
2781void
Guido van Rossuma890e681998-05-12 14:59:24 +00002782PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002785
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002786 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002787 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002789}
2790
2791void
Guido van Rossuma890e681998-05-12 14:59:24 +00002792PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002793{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002794 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002796 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002797 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002798 va_end(va);
2799}
2800
2801static void
Victor Stinner09054372013-11-06 22:41:44 +01002802sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002803{
2804 PyObject *file, *message;
2805 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002806 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002807
2808 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002809 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002810 message = PyUnicode_FromFormatV(format, va);
2811 if (message != NULL) {
2812 if (sys_pyfile_write_unicode(message, file) != 0) {
2813 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002814 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002815 if (utf8 != NULL)
2816 fputs(utf8, fp);
2817 }
2818 Py_DECREF(message);
2819 }
2820 PyErr_Restore(error_type, error_value, error_traceback);
2821}
2822
2823void
2824PySys_FormatStdout(const char *format, ...)
2825{
2826 va_list va;
2827
2828 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002829 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002830 va_end(va);
2831}
2832
2833void
2834PySys_FormatStderr(const char *format, ...)
2835{
2836 va_list va;
2837
2838 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002839 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002840 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002841}