blob: 21647083d683d725fcbe13e99609e998ffe57016 [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 Stinnera1c249c2018-11-01 03:15:58 +010020#include "pycore_lifecycle.h"
21#include "pycore_mem.h"
22#include "pycore_pathconfig.h"
23#include "pycore_state.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
154 PyObject *fromlist = Py_BuildValue("(s)", attrname);
155 if (fromlist == NULL) {
156 Py_DECREF(modulepath);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300157 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400158 return NULL;
159 }
160 PyObject *module = PyImport_ImportModuleLevelObject(
161 modulepath, NULL, NULL, fromlist, 0);
162 Py_DECREF(modulepath);
163 Py_DECREF(fromlist);
164
165 if (module == NULL) {
166 goto error;
167 }
168
169 PyObject *hook = PyObject_GetAttrString(module, attrname);
170 Py_DECREF(module);
171
172 if (hook == NULL) {
173 goto error;
174 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300175 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400176 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
177 Py_DECREF(hook);
178 return retval;
179
180 error:
181 /* If any of the imports went wrong, then warn and ignore. */
182 PyErr_Clear();
183 int status = PyErr_WarnFormat(
184 PyExc_RuntimeWarning, 0,
185 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300186 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400187 if (status < 0) {
188 /* Printing the warning raised an exception. */
189 return NULL;
190 }
191 /* The warning was (probably) issued. */
192 Py_RETURN_NONE;
193}
194
195PyDoc_STRVAR(breakpointhook_doc,
196"breakpointhook(*args, **kws)\n"
197"\n"
198"This hook function is called by built-in breakpoint().\n"
199);
200
Victor Stinner13d49ee2010-12-04 17:24:33 +0000201/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
202 error handler. If sys.stdout has a buffer attribute, use
203 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
204 sys.stdout.write(redecoded).
205
206 Helper function for sys_displayhook(). */
207static int
208sys_displayhook_unencodable(PyObject *outf, PyObject *o)
209{
210 PyObject *stdout_encoding = NULL;
211 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200212 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000213 int ret;
214
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200215 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000216 if (stdout_encoding == NULL)
217 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200218 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000219 if (stdout_encoding_str == NULL)
220 goto error;
221
222 repr_str = PyObject_Repr(o);
223 if (repr_str == NULL)
224 goto error;
225 encoded = PyUnicode_AsEncodedString(repr_str,
226 stdout_encoding_str,
227 "backslashreplace");
228 Py_DECREF(repr_str);
229 if (encoded == NULL)
230 goto error;
231
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200232 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000233 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100234 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000235 Py_DECREF(buffer);
236 Py_DECREF(encoded);
237 if (result == NULL)
238 goto error;
239 Py_DECREF(result);
240 }
241 else {
242 PyErr_Clear();
243 escaped_str = PyUnicode_FromEncodedObject(encoded,
244 stdout_encoding_str,
245 "strict");
246 Py_DECREF(encoded);
247 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
248 Py_DECREF(escaped_str);
249 goto error;
250 }
251 Py_DECREF(escaped_str);
252 }
253 ret = 0;
254 goto finally;
255
256error:
257 ret = -1;
258finally:
259 Py_XDECREF(stdout_encoding);
260 return ret;
261}
262
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000263static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000264sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100267 PyObject *builtins;
268 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000269 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000270
Eric Snow3f9eee62017-09-15 16:35:20 -0600271 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 if (builtins == NULL) {
273 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
274 return NULL;
275 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600276 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000278 /* Print value except if None */
279 /* After printing, also assign to '_' */
280 /* Before, set '_' to None to avoid recursion */
281 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200282 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200284 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100286 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 if (outf == NULL || outf == Py_None) {
288 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
289 return NULL;
290 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000291 if (PyFile_WriteObject(o, outf, 0) != 0) {
292 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
293 /* repr(o) is not encodable to sys.stdout.encoding with
294 * sys.stdout.errors error handler (which is probably 'strict') */
295 PyErr_Clear();
296 err = sys_displayhook_unencodable(outf, o);
297 if (err)
298 return NULL;
299 }
300 else {
301 return NULL;
302 }
303 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100304 if (newline == NULL) {
305 newline = PyUnicode_FromString("\n");
306 if (newline == NULL)
307 return NULL;
308 }
309 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200311 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200313 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000314}
315
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000316PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000317"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000318"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000319"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000320);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000321
322static PyObject *
323sys_excepthook(PyObject* self, PyObject* args)
324{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 PyObject *exc, *value, *tb;
326 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
327 return NULL;
328 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200329 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000330}
331
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000332PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000333"excepthook(exctype, value, traceback) -> None\n"
334"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000335"Handle an exception by displaying it with a traceback on sys.stderr.\n"
336);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000337
338static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000339sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000340{
Victor Stinner50b48572018-11-01 01:51:40 +0100341 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 return Py_BuildValue(
343 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100344 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
345 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
346 err_info->exc_traceback != NULL ?
347 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000348}
349
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000350PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000351"exc_info() -> (type, value, traceback)\n\
352\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000353Return information about the most recent exception caught by an except\n\
354clause in the current stack frame or in an older stack frame."
355);
356
357static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000358sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000359{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 PyObject *exit_code = 0;
361 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
362 return NULL;
363 /* Raise SystemExit so callers may catch it or clean up. */
364 PyErr_SetObject(PyExc_SystemExit, exit_code);
365 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000366}
367
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000368PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000369"exit([status])\n\
370\n\
371Exit the interpreter by raising SystemExit(status).\n\
372If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300373If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000374If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000375exit status will be one (i.e., failure)."
376);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000377
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000378
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000379static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530380sys_getdefaultencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Fred Drake8b4d01d2000-05-09 19:57:01 +0000381{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000383}
384
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000385PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000386"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000387\n\
oldkaa0735f2018-02-02 16:52:55 +0800388Return the current default string encoding used by the Unicode\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000389implementation."
390);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000391
392static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530393sys_getfilesystemencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000394{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200395 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
396 const _PyCoreConfig *config = &interp->core_config;
397 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000398}
399
400PyDoc_STRVAR(getfilesystemencoding_doc,
401"getfilesystemencoding() -> string\n\
402\n\
403Return the encoding used to convert Unicode filenames in\n\
404operating system filenames."
405);
406
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000407static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530408sys_getfilesystemencodeerrors(PyObject *self, PyObject *Py_UNUSED(ignored))
Steve Dowercc16be82016-09-08 10:35:16 -0700409{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200410 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
411 const _PyCoreConfig *config = &interp->core_config;
412 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700413}
414
415PyDoc_STRVAR(getfilesystemencodeerrors_doc,
416 "getfilesystemencodeerrors() -> string\n\
417\n\
418Return the error mode used to convert Unicode filenames in\n\
419operating system filenames."
420);
421
422static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000423sys_intern(PyObject *self, PyObject *args)
424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 PyObject *s;
426 if (!PyArg_ParseTuple(args, "U:intern", &s))
427 return NULL;
428 if (PyUnicode_CheckExact(s)) {
429 Py_INCREF(s);
430 PyUnicode_InternInPlace(&s);
431 return s;
432 }
433 else {
434 PyErr_Format(PyExc_TypeError,
435 "can't intern %.400s", s->ob_type->tp_name);
436 return NULL;
437 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000438}
439
440PyDoc_STRVAR(intern_doc,
441"intern(string) -> string\n\
442\n\
443``Intern'' the given string. This enters the string in the (global)\n\
444table of interned strings whose purpose is to speed up dictionary lookups.\n\
445Return the string itself or the previously interned string object with the\n\
446same value.");
447
448
Fred Drake5755ce62001-06-27 19:19:46 +0000449/*
450 * Cached interned string objects used for calling the profile and
451 * trace functions. Initialized by trace_init().
452 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000453static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000454
455static int
456trace_init(void)
457{
Nick Coghlan5a851672017-09-08 10:14:16 +1000458 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200459 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000460 "c_call", "c_exception", "c_return",
461 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200462 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000463 PyObject *name;
464 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000465 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000466 if (whatstrings[i] == NULL) {
467 name = PyUnicode_InternFromString(whatnames[i]);
468 if (name == NULL)
469 return -1;
470 whatstrings[i] = name;
471 }
472 }
473 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000474}
475
476
477static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100478call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000480{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200482 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000483
Victor Stinner78da82b2016-08-20 01:22:57 +0200484 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000485 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200486 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100487
Victor Stinner78da82b2016-08-20 01:22:57 +0200488 stack[0] = (PyObject *)frame;
489 stack[1] = whatstrings[what];
490 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000491
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200493 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000494
Victor Stinner78da82b2016-08-20 01:22:57 +0200495 PyFrame_LocalsToFast(frame, 1);
496 if (result == NULL) {
497 PyTraceBack_Here(frame);
498 }
499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000501}
502
503static int
504profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000508
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000509 if (arg == NULL)
510 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100511 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (result == NULL) {
513 PyEval_SetProfile(NULL, NULL);
514 return -1;
515 }
516 Py_DECREF(result);
517 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000518}
519
520static int
521trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000523{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 PyObject *callback;
525 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (what == PyTrace_CALL)
528 callback = self;
529 else
530 callback = frame->f_trace;
531 if (callback == NULL)
532 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100533 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (result == NULL) {
535 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200536 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 return -1;
538 }
539 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300540 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000541 }
542 else {
543 Py_DECREF(result);
544 }
545 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000546}
Fred Draked0838392001-06-16 21:02:31 +0000547
Fred Drake8b4d01d2000-05-09 19:57:01 +0000548static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000549sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000550{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 if (trace_init() == -1)
552 return NULL;
553 if (args == Py_None)
554 PyEval_SetTrace(NULL, NULL);
555 else
556 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200557 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000558}
559
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000560PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000561"settrace(function)\n\
562\n\
563Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000564function call. See the debugger chapter in the library manual."
565);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000566
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000567static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000568sys_gettrace(PyObject *self, PyObject *args)
569{
Victor Stinner50b48572018-11-01 01:51:40 +0100570 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (temp == NULL)
574 temp = Py_None;
575 Py_INCREF(temp);
576 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000577}
578
579PyDoc_STRVAR(gettrace_doc,
580"gettrace()\n\
581\n\
582Return the global debug tracing function set with sys.settrace.\n\
583See the debugger chapter in the library manual."
584);
585
586static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000587sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (trace_init() == -1)
590 return NULL;
591 if (args == Py_None)
592 PyEval_SetProfile(NULL, NULL);
593 else
594 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200595 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000596}
597
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000598PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000599"setprofile(function)\n\
600\n\
601Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000602and return. See the profiler chapter in the library manual."
603);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000604
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000605static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000606sys_getprofile(PyObject *self, PyObject *args)
607{
Victor Stinner50b48572018-11-01 01:51:40 +0100608 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000610
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000611 if (temp == NULL)
612 temp = Py_None;
613 Py_INCREF(temp);
614 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000615}
616
617PyDoc_STRVAR(getprofile_doc,
618"getprofile()\n\
619\n\
620Return the profiling function set with sys.setprofile.\n\
621See the profiler chapter in the library manual."
622);
623
624static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000625sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000626{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000627 if (PyErr_WarnEx(PyExc_DeprecationWarning,
628 "sys.getcheckinterval() and sys.setcheckinterval() "
629 "are deprecated. Use sys.setswitchinterval() "
630 "instead.", 1) < 0)
631 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200632
633 int check_interval;
634 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200636
637 PyInterpreterState *interp = _PyInterpreterState_Get();
638 interp->check_interval = check_interval;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200639 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000640}
641
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000642PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000643"setcheckinterval(n)\n\
644\n\
645Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000646n instructions. This also affects how often thread switches occur."
647);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000648
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000649static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000650sys_getcheckinterval(PyObject *self, PyObject *args)
651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000652 if (PyErr_WarnEx(PyExc_DeprecationWarning,
653 "sys.getcheckinterval() and sys.setcheckinterval() "
654 "are deprecated. Use sys.getswitchinterval() "
655 "instead.", 1) < 0)
656 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200657 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600658 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000659}
660
661PyDoc_STRVAR(getcheckinterval_doc,
662"getcheckinterval() -> current check interval; see setcheckinterval()."
663);
664
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000665static PyObject *
666sys_setswitchinterval(PyObject *self, PyObject *args)
667{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000668 double d;
669 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
670 return NULL;
671 if (d <= 0.0) {
672 PyErr_SetString(PyExc_ValueError,
673 "switch interval must be strictly positive");
674 return NULL;
675 }
676 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200677 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000678}
679
680PyDoc_STRVAR(setswitchinterval_doc,
681"setswitchinterval(n)\n\
682\n\
683Set the ideal thread switching delay inside the Python interpreter\n\
684The actual frequency of switching threads can be lower if the\n\
685interpreter executes long sequences of uninterruptible code\n\
686(this is implementation-specific and workload-dependent).\n\
687\n\
688The parameter must represent the desired switching delay in seconds\n\
689A typical value is 0.005 (5 milliseconds)."
690);
691
692static PyObject *
693sys_getswitchinterval(PyObject *self, PyObject *args)
694{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000696}
697
698PyDoc_STRVAR(getswitchinterval_doc,
699"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
700);
701
Tim Peterse5e065b2003-07-06 18:36:54 +0000702static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000703sys_setrecursionlimit(PyObject *self, PyObject *args)
704{
Victor Stinner50856d52015-10-13 00:11:21 +0200705 int new_limit, mark;
706 PyThreadState *tstate;
707
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000708 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
709 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200710
711 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200713 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 return NULL;
715 }
Victor Stinner50856d52015-10-13 00:11:21 +0200716
717 /* Issue #25274: When the recursion depth hits the recursion limit in
718 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
719 set to 1 and a RecursionError is raised. The overflowed flag is reset
720 to 0 when the recursion depth goes below the low-water mark: see
721 Py_LeaveRecursiveCall().
722
723 Reject too low new limit if the current recursion depth is higher than
724 the new low-water mark. Otherwise it may not be possible anymore to
725 reset the overflowed flag to 0. */
726 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100727 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200728 if (tstate->recursion_depth >= mark) {
729 PyErr_Format(PyExc_RecursionError,
730 "cannot set the recursion limit to %i at "
731 "the recursion depth %i: the limit is too low",
732 new_limit, tstate->recursion_depth);
733 return NULL;
734 }
735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000736 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200737 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000738}
739
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800740/*[clinic input]
741sys.set_coroutine_origin_tracking_depth
742
743 depth: int
744
745Enable or disable origin tracking for coroutine objects in this thread.
746
747Coroutine objects will track 'depth' frames of traceback information about
748where they came from, available in their cr_origin attribute. Set depth of 0
749to disable.
750[clinic start generated code]*/
751
752static PyObject *
753sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
754/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
755{
756 if (depth < 0) {
757 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
758 return NULL;
759 }
760 _PyEval_SetCoroutineOriginTrackingDepth(depth);
761 Py_RETURN_NONE;
762}
763
764/*[clinic input]
765sys.get_coroutine_origin_tracking_depth -> int
766
767Check status of origin tracking for coroutine objects in this thread.
768[clinic start generated code]*/
769
770static int
771sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
772/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
773{
774 return _PyEval_GetCoroutineOriginTrackingDepth();
775}
776
Yury Selivanov75445082015-05-11 22:57:16 -0400777static PyObject *
778sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
779{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800780 if (PyErr_WarnEx(PyExc_DeprecationWarning,
781 "set_coroutine_wrapper is deprecated", 1) < 0) {
782 return NULL;
783 }
784
Yury Selivanov75445082015-05-11 22:57:16 -0400785 if (wrapper != Py_None) {
786 if (!PyCallable_Check(wrapper)) {
787 PyErr_Format(PyExc_TypeError,
788 "callable expected, got %.50s",
789 Py_TYPE(wrapper)->tp_name);
790 return NULL;
791 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400792 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400793 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400794 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400795 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400796 }
Yury Selivanov75445082015-05-11 22:57:16 -0400797 Py_RETURN_NONE;
798}
799
800PyDoc_STRVAR(set_coroutine_wrapper_doc,
801"set_coroutine_wrapper(wrapper)\n\
802\n\
803Set a wrapper for coroutine objects."
804);
805
806static PyObject *
807sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
808{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800809 if (PyErr_WarnEx(PyExc_DeprecationWarning,
810 "get_coroutine_wrapper is deprecated", 1) < 0) {
811 return NULL;
812 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400813 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400814 if (wrapper == NULL) {
815 wrapper = Py_None;
816 }
817 Py_INCREF(wrapper);
818 return wrapper;
819}
820
821PyDoc_STRVAR(get_coroutine_wrapper_doc,
822"get_coroutine_wrapper()\n\
823\n\
824Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
825);
826
827
Yury Selivanoveb636452016-09-08 22:01:51 -0700828static PyTypeObject AsyncGenHooksType;
829
830PyDoc_STRVAR(asyncgen_hooks_doc,
831"asyncgen_hooks\n\
832\n\
833A struct sequence providing information about asynhronous\n\
834generators hooks. The attributes are read only.");
835
836static PyStructSequence_Field asyncgen_hooks_fields[] = {
837 {"firstiter", "Hook to intercept first iteration"},
838 {"finalizer", "Hook to intercept finalization"},
839 {0}
840};
841
842static PyStructSequence_Desc asyncgen_hooks_desc = {
843 "asyncgen_hooks", /* name */
844 asyncgen_hooks_doc, /* doc */
845 asyncgen_hooks_fields , /* fields */
846 2
847};
848
849
850static PyObject *
851sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
852{
853 static char *keywords[] = {"firstiter", "finalizer", NULL};
854 PyObject *firstiter = NULL;
855 PyObject *finalizer = NULL;
856
857 if (!PyArg_ParseTupleAndKeywords(
858 args, kw, "|OO", keywords,
859 &firstiter, &finalizer)) {
860 return NULL;
861 }
862
863 if (finalizer && finalizer != Py_None) {
864 if (!PyCallable_Check(finalizer)) {
865 PyErr_Format(PyExc_TypeError,
866 "callable finalizer expected, got %.50s",
867 Py_TYPE(finalizer)->tp_name);
868 return NULL;
869 }
870 _PyEval_SetAsyncGenFinalizer(finalizer);
871 }
872 else if (finalizer == Py_None) {
873 _PyEval_SetAsyncGenFinalizer(NULL);
874 }
875
876 if (firstiter && firstiter != Py_None) {
877 if (!PyCallable_Check(firstiter)) {
878 PyErr_Format(PyExc_TypeError,
879 "callable firstiter expected, got %.50s",
880 Py_TYPE(firstiter)->tp_name);
881 return NULL;
882 }
883 _PyEval_SetAsyncGenFirstiter(firstiter);
884 }
885 else if (firstiter == Py_None) {
886 _PyEval_SetAsyncGenFirstiter(NULL);
887 }
888
889 Py_RETURN_NONE;
890}
891
892PyDoc_STRVAR(set_asyncgen_hooks_doc,
893"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
894\n\
895Set a finalizer for async generators objects."
896);
897
898static PyObject *
899sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
900{
901 PyObject *res;
902 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
903 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
904
905 res = PyStructSequence_New(&AsyncGenHooksType);
906 if (res == NULL) {
907 return NULL;
908 }
909
910 if (firstiter == NULL) {
911 firstiter = Py_None;
912 }
913
914 if (finalizer == NULL) {
915 finalizer = Py_None;
916 }
917
918 Py_INCREF(firstiter);
919 PyStructSequence_SET_ITEM(res, 0, firstiter);
920
921 Py_INCREF(finalizer);
922 PyStructSequence_SET_ITEM(res, 1, finalizer);
923
924 return res;
925}
926
927PyDoc_STRVAR(get_asyncgen_hooks_doc,
928"get_asyncgen_hooks()\n\
929\n\
930Return a namedtuple of installed asynchronous generators hooks \
931(firstiter, finalizer)."
932);
933
934
Mark Dickinsondc787d22010-05-23 13:33:13 +0000935static PyTypeObject Hash_InfoType;
936
937PyDoc_STRVAR(hash_info_doc,
938"hash_info\n\
939\n\
940A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100941hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000942
943static PyStructSequence_Field hash_info_fields[] = {
944 {"width", "width of the type used for hashing, in bits"},
945 {"modulus", "prime number giving the modulus on which the hash "
946 "function is based"},
947 {"inf", "value to be used for hash of a positive infinity"},
948 {"nan", "value to be used for hash of a nan"},
949 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100950 {"algorithm", "name of the algorithm for hashing of str, bytes and "
951 "memoryviews"},
952 {"hash_bits", "internal output size of hash algorithm"},
953 {"seed_bits", "seed size of hash algorithm"},
954 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000955 {NULL, NULL}
956};
957
958static PyStructSequence_Desc hash_info_desc = {
959 "sys.hash_info",
960 hash_info_doc,
961 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100962 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000963};
964
Matthias Klosed885e952010-07-06 10:53:30 +0000965static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000966get_hash_info(void)
967{
968 PyObject *hash_info;
969 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100970 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000971 hash_info = PyStructSequence_New(&Hash_InfoType);
972 if (hash_info == NULL)
973 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100974 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000975 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000976 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000977 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000978 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000979 PyStructSequence_SET_ITEM(hash_info, field++,
980 PyLong_FromLong(_PyHASH_INF));
981 PyStructSequence_SET_ITEM(hash_info, field++,
982 PyLong_FromLong(_PyHASH_NAN));
983 PyStructSequence_SET_ITEM(hash_info, field++,
984 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100985 PyStructSequence_SET_ITEM(hash_info, field++,
986 PyUnicode_FromString(hashfunc->name));
987 PyStructSequence_SET_ITEM(hash_info, field++,
988 PyLong_FromLong(hashfunc->hash_bits));
989 PyStructSequence_SET_ITEM(hash_info, field++,
990 PyLong_FromLong(hashfunc->seed_bits));
991 PyStructSequence_SET_ITEM(hash_info, field++,
992 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000993 if (PyErr_Occurred()) {
994 Py_CLEAR(hash_info);
995 return NULL;
996 }
997 return hash_info;
998}
999
1000
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001001PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001002"setrecursionlimit(n)\n\
1003\n\
1004Set the maximum depth of the Python interpreter stack to n. This\n\
1005limit prevents infinite recursion from causing an overflow of the C\n\
1006stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001007dependent."
1008);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001009
1010static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301011sys_getrecursionlimit(PyObject *self, PyObject *Py_UNUSED(ignored))
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001014}
1015
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001016PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001017"getrecursionlimit()\n\
1018\n\
1019Return the current value of the recursion limit, the maximum depth\n\
1020of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001021recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001022);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001023
Mark Hammond8696ebc2002-10-08 02:44:31 +00001024#ifdef MS_WINDOWS
1025PyDoc_STRVAR(getwindowsversion_doc,
1026"getwindowsversion()\n\
1027\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001028Return information about the running version of Windows as a named tuple.\n\
1029The members are named: major, minor, build, platform, service_pack,\n\
1030service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001031backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001032All elements are numbers, except service_pack and platform_type which are\n\
1033strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1034Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1035server. Platform_version is a 3-tuple containing a version number that is\n\
1036intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001037);
1038
Eric Smithf7bb5782010-01-27 00:44:57 +00001039static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1040
1041static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 {"major", "Major version number"},
1043 {"minor", "Minor version number"},
1044 {"build", "Build number"},
1045 {"platform", "Operating system platform"},
1046 {"service_pack", "Latest Service Pack installed on the system"},
1047 {"service_pack_major", "Service Pack major version number"},
1048 {"service_pack_minor", "Service Pack minor version number"},
1049 {"suite_mask", "Bit mask identifying available product suites"},
1050 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001051 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001053};
1054
1055static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 "sys.getwindowsversion", /* name */
1057 getwindowsversion_doc, /* doc */
1058 windows_version_fields, /* fields */
1059 5 /* For backward compatibility,
1060 only the first 5 items are accessible
1061 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001062};
1063
Steve Dower3e96f322015-03-02 08:01:10 -08001064/* Disable deprecation warnings about GetVersionEx as the result is
1065 being passed straight through to the caller, who is responsible for
1066 using it correctly. */
1067#pragma warning(push)
1068#pragma warning(disable:4996)
1069
Mark Hammond8696ebc2002-10-08 02:44:31 +00001070static PyObject *
1071sys_getwindowsversion(PyObject *self)
1072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 PyObject *version;
1074 int pos = 0;
1075 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001076 DWORD realMajor, realMinor, realBuild;
1077 HANDLE hKernel32;
1078 wchar_t kernel32_path[MAX_PATH];
1079 LPVOID verblock;
1080 DWORD verblock_size;
1081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 ver.dwOSVersionInfoSize = sizeof(ver);
1083 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1084 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 version = PyStructSequence_New(&WindowsVersionType);
1087 if (version == NULL)
1088 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1091 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1092 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1093 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1094 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1095 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1096 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1097 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1098 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001099
Steve Dower74f4af72016-09-17 17:27:48 -07001100 realMajor = ver.dwMajorVersion;
1101 realMinor = ver.dwMinorVersion;
1102 realBuild = ver.dwBuildNumber;
1103
1104 // GetVersion will lie if we are running in a compatibility mode.
1105 // We need to read the version info from a system file resource
1106 // to accurately identify the OS version. If we fail for any reason,
1107 // just return whatever GetVersion said.
1108 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1109 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1110 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1111 (verblock = PyMem_RawMalloc(verblock_size))) {
1112 VS_FIXEDFILEINFO *ffi;
1113 UINT ffi_len;
1114
1115 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1116 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1117 realMajor = HIWORD(ffi->dwProductVersionMS);
1118 realMinor = LOWORD(ffi->dwProductVersionMS);
1119 realBuild = HIWORD(ffi->dwProductVersionLS);
1120 }
1121 PyMem_RawFree(verblock);
1122 }
Segev Finer48fb7662017-06-04 20:52:27 +03001123 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1124 realMajor,
1125 realMinor,
1126 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001127 ));
1128
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001129 if (PyErr_Occurred()) {
1130 Py_DECREF(version);
1131 return NULL;
1132 }
Steve Dower74f4af72016-09-17 17:27:48 -07001133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001135}
1136
Steve Dower3e96f322015-03-02 08:01:10 -08001137#pragma warning(pop)
1138
Steve Dowercc16be82016-09-08 10:35:16 -07001139PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1140"_enablelegacywindowsfsencoding()\n\
1141\n\
1142Changes the default filesystem encoding to mbcs:replace for consistency\n\
1143with earlier versions of Python. See PEP 529 for more information.\n\
1144\n\
oldkaa0735f2018-02-02 16:52:55 +08001145This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001146environment variable before launching Python."
1147);
1148
1149static PyObject *
1150sys_enablelegacywindowsfsencoding(PyObject *self)
1151{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001152 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1153 _PyCoreConfig *config = &interp->core_config;
1154
1155 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1156 char *encoding = _PyMem_RawStrdup("mbcs");
1157 char *errors = _PyMem_RawStrdup("replace");
1158 if (encoding == NULL || errors == NULL) {
1159 PyMem_Free(encoding);
1160 PyMem_Free(errors);
1161 PyErr_NoMemory();
1162 return NULL;
1163 }
1164
1165 PyMem_RawFree(config->filesystem_encoding);
1166 config->filesystem_encoding = encoding;
1167 PyMem_RawFree(config->filesystem_errors);
1168 config->filesystem_errors = errors;
1169
1170 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1171 config->filesystem_errors) < 0) {
1172 PyErr_NoMemory();
1173 return NULL;
1174 }
1175
Steve Dowercc16be82016-09-08 10:35:16 -07001176 Py_RETURN_NONE;
1177}
1178
Mark Hammond8696ebc2002-10-08 02:44:31 +00001179#endif /* MS_WINDOWS */
1180
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001181#ifdef HAVE_DLOPEN
1182static PyObject *
1183sys_setdlopenflags(PyObject *self, PyObject *args)
1184{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001185 int new_val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001186 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1187 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001188 PyInterpreterState *interp = _PyInterpreterState_Get();
1189 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001190 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001191}
1192
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001193PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001194"setdlopenflags(n) -> None\n\
1195\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001196Set the flags used by the interpreter for dlopen calls, such as when the\n\
1197interpreter loads extension modules. Among other things, this will enable\n\
1198a lazy resolving of symbols when importing a module, if called as\n\
1199sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001200sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001201can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001202
1203static PyObject *
1204sys_getdlopenflags(PyObject *self, PyObject *args)
1205{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001206 PyInterpreterState *interp = _PyInterpreterState_Get();
1207 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001208}
1209
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001210PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001211"getdlopenflags() -> int\n\
1212\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001213Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001214The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001217
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001218#ifdef USE_MALLOPT
1219/* Link with -lmalloc (or -lmpc) on an SGI */
1220#include <malloc.h>
1221
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001222static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001223sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 int flag;
1226 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1227 return NULL;
1228 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001229 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001230}
1231#endif /* USE_MALLOPT */
1232
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001233size_t
1234_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001235{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001238 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 /* Make sure the type is initialized. float gets initialized late */
1241 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001242 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001243
Benjamin Petersonce798522012-01-22 11:24:29 -05001244 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001245 if (method == NULL) {
1246 if (!PyErr_Occurred())
1247 PyErr_Format(PyExc_TypeError,
1248 "Type %.100s doesn't define __sizeof__",
1249 Py_TYPE(o)->tp_name);
1250 }
1251 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001252 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 Py_DECREF(method);
1254 }
1255
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001256 if (res == NULL)
1257 return (size_t)-1;
1258
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001259 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001260 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001261 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001262 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001264 if (size < 0) {
1265 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1266 return (size_t)-1;
1267 }
1268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001270 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001271 return ((size_t)size) + sizeof(PyGC_Head);
1272 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001273}
1274
1275static PyObject *
1276sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1277{
1278 static char *kwlist[] = {"object", "default", 0};
1279 size_t size;
1280 PyObject *o, *dflt = NULL;
1281
1282 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1283 kwlist, &o, &dflt))
1284 return NULL;
1285
1286 size = _PySys_GetSizeOf(o);
1287
1288 if (size == (size_t)-1 && PyErr_Occurred()) {
1289 /* Has a default value been given */
1290 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1291 PyErr_Clear();
1292 Py_INCREF(dflt);
1293 return dflt;
1294 }
1295 else
1296 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001298
1299 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001300}
1301
1302PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001303"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001304\n\
1305Return the size of object in bytes.");
1306
1307static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001308sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001311}
1312
Tim Peters4be93d02002-07-07 19:59:50 +00001313#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001314static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301315sys_gettotalrefcount(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Hammond440d8982000-06-20 08:12:48 +00001316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001318}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001319#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001320
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001321PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001322"getrefcount(object) -> integer\n\
1323\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001324Return the reference count of object. The count returned is generally\n\
1325one higher than you might expect, because it includes the (temporary)\n\
1326reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001327);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001328
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001329static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301330sys_getallocatedblocks(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001331{
1332 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1333}
1334
1335PyDoc_STRVAR(getallocatedblocks_doc,
1336"getallocatedblocks() -> integer\n\
1337\n\
1338Return the number of memory blocks currently allocated, regardless of their\n\
1339size."
1340);
1341
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001342#ifdef COUNT_ALLOCS
1343static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001344sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001345{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001346 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001347
Pablo Galindo49c75a82018-10-28 15:02:17 +00001348 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001349}
1350#endif
1351
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001352PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001353"_getframe([depth]) -> frameobject\n\
1354\n\
1355Return a frame object from the call stack. If optional integer depth is\n\
1356given, return the frame object that many calls below the top of the stack.\n\
1357If that is deeper than the call stack, ValueError is raised. The default\n\
1358for depth is zero, returning the frame at the top of the call stack.\n\
1359\n\
1360This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001361purposes only."
1362);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001363
1364static PyObject *
1365sys_getframe(PyObject *self, PyObject *args)
1366{
Victor Stinner50b48572018-11-01 01:51:40 +01001367 PyFrameObject *f = _PyThreadState_GET()->frame;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1371 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 while (depth > 0 && f != NULL) {
1374 f = f->f_back;
1375 --depth;
1376 }
1377 if (f == NULL) {
1378 PyErr_SetString(PyExc_ValueError,
1379 "call stack is not deep enough");
1380 return NULL;
1381 }
1382 Py_INCREF(f);
1383 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001384}
1385
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001386PyDoc_STRVAR(current_frames_doc,
1387"_current_frames() -> dictionary\n\
1388\n\
1389Return a dictionary mapping each current thread T's thread id to T's\n\
1390current stack frame.\n\
1391\n\
1392This function should be used for specialized purposes only."
1393);
1394
1395static PyObject *
1396sys_current_frames(PyObject *self, PyObject *noargs)
1397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001399}
1400
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001401PyDoc_STRVAR(call_tracing_doc,
1402"call_tracing(func, args) -> object\n\
1403\n\
1404Call func(*args), while tracing is enabled. The tracing state is\n\
1405saved, and restored afterwards. This is intended to be called from\n\
1406a debugger from a checkpoint, to recursively debug some other code."
1407);
1408
1409static PyObject *
1410sys_call_tracing(PyObject *self, PyObject *args)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyObject *func, *funcargs;
1413 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1414 return NULL;
1415 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001416}
1417
Jeremy Hylton985eba52003-02-05 23:13:00 +00001418PyDoc_STRVAR(callstats_doc,
1419"callstats() -> tuple of integers\n\
1420\n\
1421Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1422when Python was built. Otherwise, return None.\n\
1423\n\
1424When enabled, this function returns detailed, implementation-specific\n\
1425details about the number of function calls executed. The return value is\n\
1426a 11-tuple where the entries in the tuple are counts of:\n\
14270. all function calls\n\
14281. calls to PyFunction_Type objects\n\
14292. PyFunction calls that do not create an argument tuple\n\
14303. PyFunction calls that do not create an argument tuple\n\
1431 and bypass PyEval_EvalCodeEx()\n\
14324. PyMethod calls\n\
14335. PyMethod calls on bound methods\n\
14346. PyType calls\n\
14357. PyCFunction calls\n\
14368. generator calls\n\
14379. All other calls\n\
143810. Number of stack pops performed by call_function()"
1439);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001440
Victor Stinner048afd92016-11-28 11:59:04 +01001441static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301442sys_callstats(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner048afd92016-11-28 11:59:04 +01001443{
1444 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1445 "sys.callstats() has been deprecated in Python 3.7 "
1446 "and will be removed in the future", 1) < 0) {
1447 return NULL;
1448 }
1449
1450 Py_RETURN_NONE;
1451}
1452
1453
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001454#ifdef __cplusplus
1455extern "C" {
1456#endif
1457
David Malcolm49526f42012-06-22 14:55:41 -04001458static PyObject *
1459sys_debugmallocstats(PyObject *self, PyObject *args)
1460{
1461#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001462 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001463 fputc('\n', stderr);
1464 }
David Malcolm49526f42012-06-22 14:55:41 -04001465#endif
1466 _PyObject_DebugTypeStats(stderr);
1467
1468 Py_RETURN_NONE;
1469}
1470PyDoc_STRVAR(debugmallocstats_doc,
1471"_debugmallocstats()\n\
1472\n\
1473Print summary info to stderr about the state of\n\
1474pymalloc's structures.\n\
1475\n\
1476In Py_DEBUG mode, also perform some expensive internal consistency\n\
1477checks.\n\
1478");
1479
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001480#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001481/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001482extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001483#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001484
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001485#ifdef DYNAMIC_EXECUTION_PROFILE
1486/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001487extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001488#endif
1489
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001490#ifdef __cplusplus
1491}
1492#endif
1493
Christian Heimes15ebc882008-02-04 18:48:49 +00001494static PyObject *
1495sys_clear_type_cache(PyObject* self, PyObject* args)
1496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 PyType_ClearCache();
1498 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001499}
1500
1501PyDoc_STRVAR(sys_clear_type_cache__doc__,
1502"_clear_type_cache() -> None\n\
1503Clear the internal type lookup cache.");
1504
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001505static PyObject *
1506sys_is_finalizing(PyObject* self, PyObject* args)
1507{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001508 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001509}
1510
1511PyDoc_STRVAR(is_finalizing_doc,
1512"is_finalizing()\n\
1513Return True if Python is exiting.");
1514
Christian Heimes15ebc882008-02-04 18:48:49 +00001515
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001516#ifdef ANDROID_API_LEVEL
1517PyDoc_STRVAR(getandroidapilevel_doc,
1518"getandroidapilevel()\n\
1519\n\
1520Return the build time API version of Android as an integer.");
1521
1522static PyObject *
1523sys_getandroidapilevel(PyObject *self)
1524{
1525 return PyLong_FromLong(ANDROID_API_LEVEL);
1526}
1527#endif /* ANDROID_API_LEVEL */
1528
1529
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001530static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001532 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1533 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301534 {"callstats", sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 callstats_doc},
1536 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1537 sys_clear_type_cache__doc__},
1538 {"_current_frames", sys_current_frames, METH_NOARGS,
1539 current_frames_doc},
1540 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1541 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1542 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1543 {"exit", sys_exit, METH_VARARGS, exit_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301544 {"getdefaultencoding", sys_getdefaultencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001546#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1548 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001549#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301550 {"getallocatedblocks", sys_getallocatedblocks, METH_NOARGS,
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001551 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001552#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001554#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001555#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001557#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301558 {"getfilesystemencoding", sys_getfilesystemencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 METH_NOARGS, getfilesystemencoding_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301560 { "getfilesystemencodeerrors", sys_getfilesystemencodeerrors,
Steve Dowercc16be82016-09-08 10:35:16 -07001561 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001562#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001564#endif
1565#ifdef Py_REF_DEBUG
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301566 {"gettotalrefcount", sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001567#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301569 {"getrecursionlimit", sys_getrecursionlimit, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 getrecursionlimit_doc},
1571 {"getsizeof", (PyCFunction)sys_getsizeof,
1572 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1573 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001574#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1576 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001577 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1578 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001579#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001581 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001582#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1586 setcheckinterval_doc},
1587 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1588 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1590 setswitchinterval_doc},
1591 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1592 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001593#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1595 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001596#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1598 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1599 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1600 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 {"settrace", sys_settrace, METH_O, settrace_doc},
1602 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1603 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001604 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001605 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001606 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1607 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001608 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1609 set_coroutine_wrapper_doc},
1610 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1611 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001612 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001613 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1614 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1615 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001616#ifdef ANDROID_API_LEVEL
1617 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1618 getandroidapilevel_doc},
1619#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001621};
1622
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001623static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001624list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001625{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 PyObject *list = PyList_New(0);
1627 int i;
1628 if (list == NULL)
1629 return NULL;
1630 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1631 PyObject *name = PyUnicode_FromString(
1632 PyImport_Inittab[i].name);
1633 if (name == NULL)
1634 break;
1635 PyList_Append(list, name);
1636 Py_DECREF(name);
1637 }
1638 if (PyList_Sort(list) != 0) {
1639 Py_DECREF(list);
1640 list = NULL;
1641 }
1642 if (list) {
1643 PyObject *v = PyList_AsTuple(list);
1644 Py_DECREF(list);
1645 list = v;
1646 }
1647 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001648}
1649
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001650/* Pre-initialization support for sys.warnoptions and sys._xoptions
1651 *
1652 * Modern internal code paths:
1653 * These APIs get called after _Py_InitializeCore and get to use the
1654 * regular CPython list, dict, and unicode APIs.
1655 *
1656 * Legacy embedding code paths:
1657 * The multi-phase initialization API isn't public yet, so embedding
1658 * apps still need to be able configure sys.warnoptions and sys._xoptions
1659 * before they call Py_Initialize. To support this, we stash copies of
1660 * the supplied wchar * sequences in linked lists, and then migrate the
1661 * contents of those lists to the sys module in _PyInitializeCore.
1662 *
1663 */
1664
1665struct _preinit_entry {
1666 wchar_t *value;
1667 struct _preinit_entry *next;
1668};
1669
1670typedef struct _preinit_entry *_Py_PreInitEntry;
1671
1672static _Py_PreInitEntry _preinit_warnoptions = NULL;
1673static _Py_PreInitEntry _preinit_xoptions = NULL;
1674
1675static _Py_PreInitEntry
1676_alloc_preinit_entry(const wchar_t *value)
1677{
1678 /* To get this to work, we have to initialize the runtime implicitly */
1679 _PyRuntime_Initialize();
1680
1681 /* Force default allocator, so we can ensure that it also gets used to
1682 * destroy the linked list in _clear_preinit_entries.
1683 */
1684 PyMemAllocatorEx old_alloc;
1685 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1686
1687 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1688 if (node != NULL) {
1689 node->value = _PyMem_RawWcsdup(value);
1690 if (node->value == NULL) {
1691 PyMem_RawFree(node);
1692 node = NULL;
1693 };
1694 };
1695
1696 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1697 return node;
1698};
1699
1700static int
1701_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1702{
1703 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1704 if (new_entry == NULL) {
1705 return -1;
1706 }
1707 /* We maintain the linked list in this order so it's easy to play back
1708 * the add commands in the same order later on in _Py_InitializeCore
1709 */
1710 _Py_PreInitEntry last_entry = *optionlist;
1711 if (last_entry == NULL) {
1712 *optionlist = new_entry;
1713 } else {
1714 while (last_entry->next != NULL) {
1715 last_entry = last_entry->next;
1716 }
1717 last_entry->next = new_entry;
1718 }
1719 return 0;
1720};
1721
1722static void
1723_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1724{
1725 _Py_PreInitEntry current = *optionlist;
1726 *optionlist = NULL;
1727 /* Deallocate the nodes and their contents using the default allocator */
1728 PyMemAllocatorEx old_alloc;
1729 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1730 while (current != NULL) {
1731 _Py_PreInitEntry next = current->next;
1732 PyMem_RawFree(current->value);
1733 PyMem_RawFree(current);
1734 current = next;
1735 }
1736 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1737};
1738
1739static void
1740_clear_all_preinit_options(void)
1741{
1742 _clear_preinit_entries(&_preinit_warnoptions);
1743 _clear_preinit_entries(&_preinit_xoptions);
1744}
1745
1746static int
1747_PySys_ReadPreInitOptions(void)
1748{
1749 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001750 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001751 if (tstate == NULL) {
1752 /* Still don't have a thread state, so something is wrong! */
1753 return -1;
1754 }
1755 _Py_PreInitEntry entry = _preinit_warnoptions;
1756 while (entry != NULL) {
1757 PySys_AddWarnOption(entry->value);
1758 entry = entry->next;
1759 }
1760 entry = _preinit_xoptions;
1761 while (entry != NULL) {
1762 PySys_AddXOption(entry->value);
1763 entry = entry->next;
1764 }
1765
1766 _clear_all_preinit_options();
1767 return 0;
1768};
1769
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001770static PyObject *
1771get_warnoptions(void)
1772{
Eric Snowdae02762017-09-14 00:35:58 -07001773 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001774 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001775 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1776 * interpreter config. When that happens, we need to properly set
1777 * the `warnoptions` reference in the main interpreter config as well.
1778 *
1779 * For Python 3.7, we shouldn't be able to get here due to the
1780 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1781 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1782 * call optional for embedding applications, thus making this
1783 * reachable again.
1784 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001785 Py_XDECREF(warnoptions);
1786 warnoptions = PyList_New(0);
1787 if (warnoptions == NULL)
1788 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001789 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1790 Py_DECREF(warnoptions);
1791 return NULL;
1792 }
1793 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001794 }
1795 return warnoptions;
1796}
Guido van Rossum23fff912000-12-15 22:02:05 +00001797
1798void
1799PySys_ResetWarnOptions(void)
1800{
Victor Stinner50b48572018-11-01 01:51:40 +01001801 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001802 if (tstate == NULL) {
1803 _clear_preinit_entries(&_preinit_warnoptions);
1804 return;
1805 }
1806
Eric Snowdae02762017-09-14 00:35:58 -07001807 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 if (warnoptions == NULL || !PyList_Check(warnoptions))
1809 return;
1810 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001811}
1812
Victor Stinnere1b29952018-10-30 14:31:42 +01001813static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001814_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001815{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001816 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001817 if (warnoptions == NULL) {
1818 return -1;
1819 }
1820 if (PyList_Append(warnoptions, option)) {
1821 return -1;
1822 }
1823 return 0;
1824}
1825
1826void
1827PySys_AddWarnOptionUnicode(PyObject *option)
1828{
Victor Stinnere1b29952018-10-30 14:31:42 +01001829 if (_PySys_AddWarnOptionWithError(option) < 0) {
1830 /* No return value, therefore clear error state if possible */
1831 if (_PyThreadState_UncheckedGet()) {
1832 PyErr_Clear();
1833 }
1834 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001835}
1836
1837void
1838PySys_AddWarnOption(const wchar_t *s)
1839{
Victor Stinner50b48572018-11-01 01:51:40 +01001840 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001841 if (tstate == NULL) {
1842 _append_preinit_entry(&_preinit_warnoptions, s);
1843 return;
1844 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001845 PyObject *unicode;
1846 unicode = PyUnicode_FromWideChar(s, -1);
1847 if (unicode == NULL)
1848 return;
1849 PySys_AddWarnOptionUnicode(unicode);
1850 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001851}
1852
Christian Heimes33fe8092008-04-13 13:53:33 +00001853int
1854PySys_HasWarnOptions(void)
1855{
Eric Snowdae02762017-09-14 00:35:58 -07001856 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001857 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1858}
1859
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001860static PyObject *
1861get_xoptions(void)
1862{
Eric Snowdae02762017-09-14 00:35:58 -07001863 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001864 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001865 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1866 * interpreter config. When that happens, we need to properly set
1867 * the `xoptions` reference in the main interpreter config as well.
1868 *
1869 * For Python 3.7, we shouldn't be able to get here due to the
1870 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1871 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1872 * call optional for embedding applications, thus making this
1873 * reachable again.
1874 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001875 Py_XDECREF(xoptions);
1876 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001877 if (xoptions == NULL)
1878 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001879 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1880 Py_DECREF(xoptions);
1881 return NULL;
1882 }
1883 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001884 }
1885 return xoptions;
1886}
1887
Victor Stinnere1b29952018-10-30 14:31:42 +01001888static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001889_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001890{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001891 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001892
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001893 PyObject *opts = get_xoptions();
1894 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001895 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001897
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001898 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001899 if (!name_end) {
1900 name = PyUnicode_FromWideChar(s, -1);
1901 value = Py_True;
1902 Py_INCREF(value);
1903 }
1904 else {
1905 name = PyUnicode_FromWideChar(s, name_end - s);
1906 value = PyUnicode_FromWideChar(name_end + 1, -1);
1907 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001908 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001909 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001910 }
1911 if (PyDict_SetItem(opts, name, value) < 0) {
1912 goto error;
1913 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001914 Py_DECREF(name);
1915 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001916 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001917
1918error:
1919 Py_XDECREF(name);
1920 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001921 return -1;
1922}
1923
1924void
1925PySys_AddXOption(const wchar_t *s)
1926{
Victor Stinner50b48572018-11-01 01:51:40 +01001927 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001928 if (tstate == NULL) {
1929 _append_preinit_entry(&_preinit_xoptions, s);
1930 return;
1931 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001932 if (_PySys_AddXOptionWithError(s) < 0) {
1933 /* No return value, therefore clear error state if possible */
1934 if (_PyThreadState_UncheckedGet()) {
1935 PyErr_Clear();
1936 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001937 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001938}
1939
1940PyObject *
1941PySys_GetXOptions(void)
1942{
1943 return get_xoptions();
1944}
1945
Guido van Rossum40552d01998-08-06 03:34:39 +00001946/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1947 Two literals concatenated works just fine. If you have a K&R compiler
1948 or other abomination that however *does* understand longer strings,
1949 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001950PyDoc_VAR(sys_doc) =
1951PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001952"This module provides access to some objects used or maintained by the\n\
1953interpreter and to functions that interact strongly with the interpreter.\n\
1954\n\
1955Dynamic objects:\n\
1956\n\
1957argv -- command line arguments; argv[0] is the script pathname if known\n\
1958path -- module search path; path[0] is the script directory, else ''\n\
1959modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001960\n\
1961displayhook -- called to show results in an interactive session\n\
1962excepthook -- called to handle any uncaught exception other than SystemExit\n\
1963 To customize printing in an interactive session or to install a custom\n\
1964 top-level exception handler, assign other functions to replace these.\n\
1965\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001966stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001967stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001968stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001969 By assigning other file objects (or objects that behave like files)\n\
1970 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001971\n\
1972last_type -- type of last uncaught exception\n\
1973last_value -- value of last uncaught exception\n\
1974last_traceback -- traceback of last uncaught exception\n\
1975 These three are only available in an interactive session after a\n\
1976 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001977"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001978)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001979/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001980PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001981"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001982Static objects:\n\
1983\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001984builtin_module_names -- tuple of module names built into this interpreter\n\
1985copyright -- copyright notice pertaining to this interpreter\n\
1986exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001987executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001988float_info -- a struct sequence with information about the float implementation.\n\
1989float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001990hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001991hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001992implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001993int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001994maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001995maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001996platform -- platform identifier\n\
1997prefix -- prefix used to find the Python library\n\
1998thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001999version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002000version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002001"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002002)
Steve Dowercc16be82016-09-08 10:35:16 -07002003#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002004/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002005PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002006"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002007winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002008"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002009)
Steve Dowercc16be82016-09-08 10:35:16 -07002010#endif /* MS_COREDLL */
2011#ifdef MS_WINDOWS
2012/* concatenating string here */
2013PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002014"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002015"
2016)
2017#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002018PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002019"__stdin__ -- the original stdin; don't touch!\n\
2020__stdout__ -- the original stdout; don't touch!\n\
2021__stderr__ -- the original stderr; don't touch!\n\
2022__displayhook__ -- the original displayhook; don't touch!\n\
2023__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002024\n\
2025Functions:\n\
2026\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002027displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002028excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002029exc_info() -- return thread-safe information about the current exception\n\
2030exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002031getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002032getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002033getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002034getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002035getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002036gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002037setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002038setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002039setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002040setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002041settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002042"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002043)
Fred Drakeccede592000-08-14 20:59:57 +00002044/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002045
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002046
2047PyDoc_STRVAR(flags__doc__,
2048"sys.flags\n\
2049\n\
2050Flags provided through command line arguments or environment vars.");
2051
2052static PyTypeObject FlagsType;
2053
2054static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 {"inspect", "-i"},
2057 {"interactive", "-i"},
2058 {"optimize", "-O or -OO"},
2059 {"dont_write_bytecode", "-B"},
2060 {"no_user_site", "-s"},
2061 {"no_site", "-S"},
2062 {"ignore_environment", "-E"},
2063 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002064 /* {"unbuffered", "-u"}, */
2065 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002066 {"bytes_warning", "-b"},
2067 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002068 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002069 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002070 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002071 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002072 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002073};
2074
2075static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 "sys.flags", /* name */
2077 flags__doc__, /* doc */
2078 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002079 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002080};
2081
2082static PyObject*
2083make_flags(void)
2084{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 int pos = 0;
2086 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002087 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002088
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 seq = PyStructSequence_New(&FlagsType);
2090 if (seq == NULL)
2091 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002092
2093#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002095
Victor Stinnerfbca9082018-08-30 00:50:45 +02002096 SetFlag(config->parser_debug);
2097 SetFlag(config->inspect);
2098 SetFlag(config->interactive);
2099 SetFlag(config->optimization_level);
2100 SetFlag(!config->write_bytecode);
2101 SetFlag(!config->user_site_directory);
2102 SetFlag(!config->site_import);
2103 SetFlag(!config->use_environment);
2104 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 /* SetFlag(saw_unbuffered_flag); */
2106 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002107 SetFlag(config->bytes_warning);
2108 SetFlag(config->quiet);
2109 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2110 SetFlag(config->isolated);
2111 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2112 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002113#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002116 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002117 return NULL;
2118 }
2119 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002120}
2121
Eric Smith0e5b5622009-02-06 01:32:42 +00002122PyDoc_STRVAR(version_info__doc__,
2123"sys.version_info\n\
2124\n\
2125Version information as a named tuple.");
2126
2127static PyTypeObject VersionInfoType;
2128
2129static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 {"major", "Major release number"},
2131 {"minor", "Minor release number"},
2132 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002133 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 {"serial", "Serial release number"},
2135 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002136};
2137
2138static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 "sys.version_info", /* name */
2140 version_info__doc__, /* doc */
2141 version_info_fields, /* fields */
2142 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002143};
2144
2145static PyObject *
2146make_version_info(void)
2147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 PyObject *version_info;
2149 char *s;
2150 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002151
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 version_info = PyStructSequence_New(&VersionInfoType);
2153 if (version_info == NULL) {
2154 return NULL;
2155 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002156
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002157 /*
2158 * These release level checks are mutually exclusive and cover
2159 * the field, so don't get too fancy with the pre-processor!
2160 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002161#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002163#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002165#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002167#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002168 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002169#endif
2170
2171#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002173#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002175
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 SetIntItem(PY_MAJOR_VERSION);
2177 SetIntItem(PY_MINOR_VERSION);
2178 SetIntItem(PY_MICRO_VERSION);
2179 SetStrItem(s);
2180 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002181#undef SetIntItem
2182#undef SetStrItem
2183
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 if (PyErr_Occurred()) {
2185 Py_CLEAR(version_info);
2186 return NULL;
2187 }
2188 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002189}
2190
Brett Cannon3adc7b72012-07-09 14:22:12 -04002191/* sys.implementation values */
2192#define NAME "cpython"
2193const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002194#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2195#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002196#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002197const char *_PySys_ImplCacheTag = TAG;
2198#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002199#undef MAJOR
2200#undef MINOR
2201#undef TAG
2202
Barry Warsaw409da152012-06-03 16:18:47 -04002203static PyObject *
2204make_impl_info(PyObject *version_info)
2205{
2206 int res;
2207 PyObject *impl_info, *value, *ns;
2208
2209 impl_info = PyDict_New();
2210 if (impl_info == NULL)
2211 return NULL;
2212
2213 /* populate the dict */
2214
Brett Cannon3adc7b72012-07-09 14:22:12 -04002215 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002216 if (value == NULL)
2217 goto error;
2218 res = PyDict_SetItemString(impl_info, "name", value);
2219 Py_DECREF(value);
2220 if (res < 0)
2221 goto error;
2222
Brett Cannon3adc7b72012-07-09 14:22:12 -04002223 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002224 if (value == NULL)
2225 goto error;
2226 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2227 Py_DECREF(value);
2228 if (res < 0)
2229 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002230
2231 res = PyDict_SetItemString(impl_info, "version", version_info);
2232 if (res < 0)
2233 goto error;
2234
2235 value = PyLong_FromLong(PY_VERSION_HEX);
2236 if (value == NULL)
2237 goto error;
2238 res = PyDict_SetItemString(impl_info, "hexversion", value);
2239 Py_DECREF(value);
2240 if (res < 0)
2241 goto error;
2242
doko@ubuntu.com55532312016-06-14 08:55:19 +02002243#ifdef MULTIARCH
2244 value = PyUnicode_FromString(MULTIARCH);
2245 if (value == NULL)
2246 goto error;
2247 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2248 Py_DECREF(value);
2249 if (res < 0)
2250 goto error;
2251#endif
2252
Barry Warsaw409da152012-06-03 16:18:47 -04002253 /* dict ready */
2254
2255 ns = _PyNamespace_New(impl_info);
2256 Py_DECREF(impl_info);
2257 return ns;
2258
2259error:
2260 Py_CLEAR(impl_info);
2261 return NULL;
2262}
2263
Martin v. Löwis1a214512008-06-11 05:26:20 +00002264static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 PyModuleDef_HEAD_INIT,
2266 "sys",
2267 sys_doc,
2268 -1, /* multiple "initialization" just copies the module dict. */
2269 sys_methods,
2270 NULL,
2271 NULL,
2272 NULL,
2273 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002274};
2275
Eric Snow6b4be192017-05-22 21:36:03 -07002276/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002277#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002278 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002279 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002280 if (v == NULL) { \
2281 goto err_occurred; \
2282 } \
Victor Stinner58049602013-07-22 22:40:00 +02002283 res = PyDict_SetItemString(sysdict, key, v); \
2284 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002285 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002286 } \
2287 } while (0)
2288#define SET_SYS_FROM_STRING(key, value) \
2289 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002290 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002291 if (v == NULL) { \
2292 goto err_occurred; \
2293 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002294 res = PyDict_SetItemString(sysdict, key, v); \
2295 Py_DECREF(v); \
2296 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002297 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002298 } \
2299 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002300
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002301
2302_PyInitError
2303_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002304{
2305 PyObject *m, *sysdict, *version_info;
2306 int res;
2307
Eric Snowd393c1b2017-09-14 12:18:12 -06002308 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002309 if (m == NULL) {
2310 return _Py_INIT_ERR("failed to create a module object");
2311 }
Eric Snow6b4be192017-05-22 21:36:03 -07002312 sysdict = PyModule_GetDict(m);
2313
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002314 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002315 Using shell redirection, you can redirect stdin to a directory,
2316 crashing the Python interpreter. Catch this common mistake here
2317 and output a useful error message. Note that under MS Windows,
2318 the shell already prevents that. */
2319#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002321 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002322 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002323 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002324 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2325 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002326 }
2327 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002328#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002329
Nick Coghland6009512014-11-20 21:39:37 +10002330 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002331
Victor Stinner8fea2522013-10-27 17:15:42 +01002332 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2333 PyDict_GetItemString(sysdict, "displayhook"));
2334 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2335 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002336 SET_SYS_FROM_STRING_BORROW(
2337 "__breakpointhook__",
2338 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002339 SET_SYS_FROM_STRING("version",
2340 PyUnicode_FromString(Py_GetVersion()));
2341 SET_SYS_FROM_STRING("hexversion",
2342 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002343 SET_SYS_FROM_STRING("_git",
2344 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2345 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002346 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 SET_SYS_FROM_STRING("api_version",
2348 PyLong_FromLong(PYTHON_API_VERSION));
2349 SET_SYS_FROM_STRING("copyright",
2350 PyUnicode_FromString(Py_GetCopyright()));
2351 SET_SYS_FROM_STRING("platform",
2352 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002353 SET_SYS_FROM_STRING("maxsize",
2354 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2355 SET_SYS_FROM_STRING("float_info",
2356 PyFloat_GetInfo());
2357 SET_SYS_FROM_STRING("int_info",
2358 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002359 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002360 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002361 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2362 goto type_init_failed;
2363 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002364 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002365 SET_SYS_FROM_STRING("hash_info",
2366 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002368 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002369 SET_SYS_FROM_STRING("builtin_module_names",
2370 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002371#if PY_BIG_ENDIAN
2372 SET_SYS_FROM_STRING("byteorder",
2373 PyUnicode_FromString("big"));
2374#else
2375 SET_SYS_FROM_STRING("byteorder",
2376 PyUnicode_FromString("little"));
2377#endif
Fred Drake099325e2000-08-14 15:47:03 +00002378
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002379#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 SET_SYS_FROM_STRING("dllhandle",
2381 PyLong_FromVoidPtr(PyWin_DLLhModule));
2382 SET_SYS_FROM_STRING("winver",
2383 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002384#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002385#ifdef ABIFLAGS
2386 SET_SYS_FROM_STRING("abiflags",
2387 PyUnicode_FromString(ABIFLAGS));
2388#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002390 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002391 if (VersionInfoType.tp_name == NULL) {
2392 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002393 &version_info_desc) < 0) {
2394 goto type_init_failed;
2395 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002396 }
Barry Warsaw409da152012-06-03 16:18:47 -04002397 version_info = make_version_info();
2398 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* prevent user from creating new instances */
2400 VersionInfoType.tp_init = NULL;
2401 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002402 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2403 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2404 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002405
Barry Warsaw409da152012-06-03 16:18:47 -04002406 /* implementation */
2407 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2408
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002409 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002410 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002411 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2412 goto type_init_failed;
2413 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002414 }
Eric Snow6b4be192017-05-22 21:36:03 -07002415 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002417
2418#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 /* getwindowsversion */
2420 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002421 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002422 &windows_version_desc) < 0) {
2423 goto type_init_failed;
2424 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002425 /* prevent user from creating new instances */
2426 WindowsVersionType.tp_init = NULL;
2427 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002428 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002429 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002430 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002431 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002432 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002433#endif
2434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002436#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 SET_SYS_FROM_STRING("float_repr_style",
2438 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002439#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002440 SET_SYS_FROM_STRING("float_repr_style",
2441 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002442#endif
2443
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002444 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002445
Yury Selivanoveb636452016-09-08 22:01:51 -07002446 /* initialize asyncgen_hooks */
2447 if (AsyncGenHooksType.tp_name == NULL) {
2448 if (PyStructSequence_InitType2(
2449 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002450 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002451 }
2452 }
2453
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002454 if (PyErr_Occurred()) {
2455 goto err_occurred;
2456 }
2457
2458 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002459
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002460 return _Py_INIT_OK();
2461
2462type_init_failed:
2463 return _Py_INIT_ERR("failed to initialize a type");
2464
2465err_occurred:
2466 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002467}
2468
Eric Snow6b4be192017-05-22 21:36:03 -07002469#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002470
2471/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002472#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2473 do { \
2474 PyObject *v = (value); \
2475 if (v == NULL) \
2476 return -1; \
2477 res = PyDict_SetItemString(sysdict, key, v); \
2478 Py_DECREF(v); \
2479 if (res < 0) { \
2480 return res; \
2481 } \
2482 } while (0)
2483
2484int
Victor Stinnerfbca9082018-08-30 00:50:45 +02002485_PySys_EndInit(PyObject *sysdict, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002486{
Victor Stinnerfbca9082018-08-30 00:50:45 +02002487 const _PyCoreConfig *core_config = &interp->core_config;
2488 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002489 int res;
2490
Victor Stinner41264f12017-12-15 02:05:29 +01002491 /* _PyMainInterpreterConfig_Read() must set all these variables */
2492 assert(config->module_search_path != NULL);
2493 assert(config->executable != NULL);
2494 assert(config->prefix != NULL);
2495 assert(config->base_prefix != NULL);
2496 assert(config->exec_prefix != NULL);
2497 assert(config->base_exec_prefix != NULL);
2498
2499 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
2500 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2501 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2502 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2503 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2504 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2505
Carl Meyerb193fa92018-06-15 22:40:56 -06002506 if (config->pycache_prefix != NULL) {
2507 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2508 } else {
2509 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2510 }
2511
Victor Stinner41264f12017-12-15 02:05:29 +01002512 if (config->argv != NULL) {
2513 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2514 }
2515 if (config->warnoptions != NULL) {
2516 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
2517 }
2518 if (config->xoptions != NULL) {
2519 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
2520 }
2521
Eric Snow6b4be192017-05-22 21:36:03 -07002522 /* Set flags to their final values */
2523 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2524 /* prevent user from creating new instances */
2525 FlagsType.tp_init = NULL;
2526 FlagsType.tp_new = NULL;
2527 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2528 if (res < 0) {
2529 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2530 return res;
2531 }
2532 PyErr_Clear();
2533 }
2534
2535 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002536 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002537
Eric Snowdae02762017-09-14 00:35:58 -07002538 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002539 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002540
Eric Snowdae02762017-09-14 00:35:58 -07002541 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002542 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002543
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002544 /* Transfer any sys.warnoptions and sys._xoptions set directly
2545 * by an embedding application from the linked list to the module. */
2546 if (_PySys_ReadPreInitOptions() != 0)
2547 return -1;
2548
Eric Snow6b4be192017-05-22 21:36:03 -07002549 if (PyErr_Occurred())
2550 return -1;
2551 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002552
2553err_occurred:
2554 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002555}
2556
Victor Stinner41264f12017-12-15 02:05:29 +01002557#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002558#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002559
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002560static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002561makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002563 int i, n;
2564 const wchar_t *p;
2565 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002567 n = 1;
2568 p = path;
2569 while ((p = wcschr(p, delim)) != NULL) {
2570 n++;
2571 p++;
2572 }
2573 v = PyList_New(n);
2574 if (v == NULL)
2575 return NULL;
2576 for (i = 0; ; i++) {
2577 p = wcschr(path, delim);
2578 if (p == NULL)
2579 p = path + wcslen(path); /* End of string */
2580 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2581 if (w == NULL) {
2582 Py_DECREF(v);
2583 return NULL;
2584 }
2585 PyList_SetItem(v, i, w);
2586 if (*p == '\0')
2587 break;
2588 path = p+1;
2589 }
2590 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002591}
2592
2593void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002594PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002596 PyObject *v;
2597 if ((v = makepathobject(path, DELIM)) == NULL)
2598 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002599 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 Py_FatalError("can't assign sys.path");
2601 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002602}
2603
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002604static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002605makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002607 PyObject *av;
2608 if (argc <= 0 || argv == NULL) {
2609 /* Ensure at least one (empty) argument is seen */
2610 static wchar_t *empty_argv[1] = {L""};
2611 argv = empty_argv;
2612 argc = 1;
2613 }
2614 av = PyList_New(argc);
2615 if (av != NULL) {
2616 int i;
2617 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002619 if (v == NULL) {
2620 Py_DECREF(av);
2621 av = NULL;
2622 break;
2623 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002624 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 }
2626 }
2627 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002628}
2629
Victor Stinner11a247d2017-12-13 21:05:57 +01002630void
2631PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002632{
2633 PyObject *av = makeargvobject(argc, argv);
2634 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002635 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002636 }
2637 if (PySys_SetObject("argv", av) != 0) {
2638 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002639 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002640 }
2641 Py_DECREF(av);
2642
2643 if (updatepath) {
2644 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2645 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002646 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2647 if (argv0 == NULL) {
2648 Py_FatalError("can't compute path0 from argv");
2649 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002650
Victor Stinner11a247d2017-12-13 21:05:57 +01002651 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2652 if (sys_path != NULL) {
2653 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2654 Py_DECREF(argv0);
2655 Py_FatalError("can't prepend path0 to sys.path");
2656 }
2657 }
2658 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002659 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002660}
Guido van Rossuma890e681998-05-12 14:59:24 +00002661
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002662void
2663PySys_SetArgv(int argc, wchar_t **argv)
2664{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002665 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002666}
2667
Victor Stinner14284c22010-04-23 12:02:30 +00002668/* Reimplementation of PyFile_WriteString() no calling indirectly
2669 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2670
2671static int
Victor Stinner79766632010-08-16 17:36:42 +00002672sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002673{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002674 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002676
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002677 if (file == NULL)
2678 return -1;
2679
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002680 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 if (writer == NULL)
2682 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002683
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002684 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 if (result == NULL) {
2686 goto error;
2687 } else {
2688 err = 0;
2689 goto finally;
2690 }
Victor Stinner14284c22010-04-23 12:02:30 +00002691
2692error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002694finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002695 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002696 Py_XDECREF(result);
2697 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002698}
2699
Victor Stinner79766632010-08-16 17:36:42 +00002700static int
2701sys_pyfile_write(const char *text, PyObject *file)
2702{
2703 PyObject *unicode = NULL;
2704 int err;
2705
2706 if (file == NULL)
2707 return -1;
2708
2709 unicode = PyUnicode_FromString(text);
2710 if (unicode == NULL)
2711 return -1;
2712
2713 err = sys_pyfile_write_unicode(unicode, file);
2714 Py_DECREF(unicode);
2715 return err;
2716}
Guido van Rossuma890e681998-05-12 14:59:24 +00002717
2718/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2719 Adapted from code submitted by Just van Rossum.
2720
2721 PySys_WriteStdout(format, ...)
2722 PySys_WriteStderr(format, ...)
2723
2724 The first function writes to sys.stdout; the second to sys.stderr. When
2725 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002726 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002727
Victor Stinner14284c22010-04-23 12:02:30 +00002728 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002729 signal handlers: they may raise a new exception whereas sys_write()
2730 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002731
Guido van Rossuma890e681998-05-12 14:59:24 +00002732 Both take a printf-style format string as their first argument followed
2733 by a variable length argument list determined by the format string.
2734
2735 *** WARNING ***
2736
2737 The format should limit the total size of the formatted output string to
2738 1000 bytes. In particular, this means that no unrestricted "%s" formats
2739 should occur; these should be limited using "%.<N>s where <N> is a
2740 decimal number calculated so that <N> plus the maximum size of other
2741 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2742 which can print hundreds of digits for very large numbers.
2743
2744 */
2745
2746static void
Victor Stinner09054372013-11-06 22:41:44 +01002747sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 PyObject *file;
2750 PyObject *error_type, *error_value, *error_traceback;
2751 char buffer[1001];
2752 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002753
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002755 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2757 if (sys_pyfile_write(buffer, file) != 0) {
2758 PyErr_Clear();
2759 fputs(buffer, fp);
2760 }
2761 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2762 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002763 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002765 }
2766 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002767}
2768
2769void
Guido van Rossuma890e681998-05-12 14:59:24 +00002770PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002773
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002775 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002777}
2778
2779void
Guido van Rossuma890e681998-05-12 14:59:24 +00002780PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002781{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002783
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002784 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002785 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002786 va_end(va);
2787}
2788
2789static void
Victor Stinner09054372013-11-06 22:41:44 +01002790sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002791{
2792 PyObject *file, *message;
2793 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002794 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002795
2796 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002797 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002798 message = PyUnicode_FromFormatV(format, va);
2799 if (message != NULL) {
2800 if (sys_pyfile_write_unicode(message, file) != 0) {
2801 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002802 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002803 if (utf8 != NULL)
2804 fputs(utf8, fp);
2805 }
2806 Py_DECREF(message);
2807 }
2808 PyErr_Restore(error_type, error_value, error_traceback);
2809}
2810
2811void
2812PySys_FormatStdout(const char *format, ...)
2813{
2814 va_list va;
2815
2816 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002817 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002818 va_end(va);
2819}
2820
2821void
2822PySys_FormatStderr(const char *format, ...)
2823{
2824 va_list va;
2825
2826 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002827 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002829}