blob: 71414c959789e5fa2ebaac86193d9804167824e5 [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"
Victor Stinner2be00d92018-10-31 20:19:24 +010018#include "internal/mem.h"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060019#include "internal/pystate.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000020#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000021#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020022#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000023
Guido van Rossume2437a11992-03-23 18:20:18 +000024#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020025#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000026
Mark Hammond8696ebc2002-10-08 02:44:31 +000027#ifdef MS_WINDOWS
28#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000029#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000030#endif /* MS_WINDOWS */
31
Guido van Rossum9b38a141996-09-11 23:12:24 +000032#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000033extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000034/* A string loaded from the DLL at startup: */
35extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000036#endif
37
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080038/*[clinic input]
39module sys
40[clinic start generated code]*/
41/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
42
43#include "clinic/sysmodule.c.h"
44
Victor Stinnerbd303c12013-11-07 23:07:29 +010045_Py_IDENTIFIER(_);
46_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070047_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010048_Py_IDENTIFIER(buffer);
49_Py_IDENTIFIER(builtins);
50_Py_IDENTIFIER(encoding);
51_Py_IDENTIFIER(path);
52_Py_IDENTIFIER(stdout);
53_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070054_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010055_Py_IDENTIFIER(write);
56
Guido van Rossum65bf9f21997-04-29 18:33:38 +000057PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010058_PySys_GetObjectId(_Py_Identifier *key)
59{
Victor Stinnercaba55b2018-08-03 15:33:52 +020060 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
61 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010062 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020063 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010064 return _PyDict_GetItemId(sd, key);
65}
66
67PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000068PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000069{
Victor Stinnercaba55b2018-08-03 15:33:52 +020070 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
71 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020073 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000075}
76
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077int
Victor Stinnerd67bd452013-11-06 22:36:40 +010078_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
79{
Victor Stinnercaba55b2018-08-03 15:33:52 +020080 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010081 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020082 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010083 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020084 }
85 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010086 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020087 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010090 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020091 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010092}
93
94int
Neal Norwitzf3081322007-08-25 00:32:45 +000095PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000096{
Victor Stinnercaba55b2018-08-03 15:33:52 +020097 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000098 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020099 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200101 }
102 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200104 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200108 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000109}
110
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400111static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200112sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400113{
114 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300115 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400116
117 if (envar == NULL || strlen(envar) == 0) {
118 envar = "pdb.set_trace";
119 }
120 else if (!strcmp(envar, "0")) {
121 /* The breakpoint is explicitly no-op'd. */
122 Py_RETURN_NONE;
123 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300124 /* According to POSIX the string returned by getenv() might be invalidated
125 * or the string content might be overwritten by a subsequent call to
126 * getenv(). Since importing a module can performs the getenv() calls,
127 * we need to save a copy of envar. */
128 envar = _PyMem_RawStrdup(envar);
129 if (envar == NULL) {
130 PyErr_NoMemory();
131 return NULL;
132 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200133 const char *last_dot = strrchr(envar, '.');
134 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400135 PyObject *modulepath = NULL;
136
137 if (last_dot == NULL) {
138 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
139 modulepath = PyUnicode_FromString("builtins");
140 attrname = envar;
141 }
142 else {
143 /* Split on the last dot; */
144 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
145 attrname = last_dot + 1;
146 }
147 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300148 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400149 return NULL;
150 }
151
152 PyObject *fromlist = Py_BuildValue("(s)", attrname);
153 if (fromlist == NULL) {
154 Py_DECREF(modulepath);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300155 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400156 return NULL;
157 }
158 PyObject *module = PyImport_ImportModuleLevelObject(
159 modulepath, NULL, NULL, fromlist, 0);
160 Py_DECREF(modulepath);
161 Py_DECREF(fromlist);
162
163 if (module == NULL) {
164 goto error;
165 }
166
167 PyObject *hook = PyObject_GetAttrString(module, attrname);
168 Py_DECREF(module);
169
170 if (hook == NULL) {
171 goto error;
172 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300173 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400174 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
175 Py_DECREF(hook);
176 return retval;
177
178 error:
179 /* If any of the imports went wrong, then warn and ignore. */
180 PyErr_Clear();
181 int status = PyErr_WarnFormat(
182 PyExc_RuntimeWarning, 0,
183 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300184 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400185 if (status < 0) {
186 /* Printing the warning raised an exception. */
187 return NULL;
188 }
189 /* The warning was (probably) issued. */
190 Py_RETURN_NONE;
191}
192
193PyDoc_STRVAR(breakpointhook_doc,
194"breakpointhook(*args, **kws)\n"
195"\n"
196"This hook function is called by built-in breakpoint().\n"
197);
198
Victor Stinner13d49ee2010-12-04 17:24:33 +0000199/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
200 error handler. If sys.stdout has a buffer attribute, use
201 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
202 sys.stdout.write(redecoded).
203
204 Helper function for sys_displayhook(). */
205static int
206sys_displayhook_unencodable(PyObject *outf, PyObject *o)
207{
208 PyObject *stdout_encoding = NULL;
209 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200210 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000211 int ret;
212
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200213 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000214 if (stdout_encoding == NULL)
215 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200216 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000217 if (stdout_encoding_str == NULL)
218 goto error;
219
220 repr_str = PyObject_Repr(o);
221 if (repr_str == NULL)
222 goto error;
223 encoded = PyUnicode_AsEncodedString(repr_str,
224 stdout_encoding_str,
225 "backslashreplace");
226 Py_DECREF(repr_str);
227 if (encoded == NULL)
228 goto error;
229
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200230 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000231 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100232 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000233 Py_DECREF(buffer);
234 Py_DECREF(encoded);
235 if (result == NULL)
236 goto error;
237 Py_DECREF(result);
238 }
239 else {
240 PyErr_Clear();
241 escaped_str = PyUnicode_FromEncodedObject(encoded,
242 stdout_encoding_str,
243 "strict");
244 Py_DECREF(encoded);
245 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
246 Py_DECREF(escaped_str);
247 goto error;
248 }
249 Py_DECREF(escaped_str);
250 }
251 ret = 0;
252 goto finally;
253
254error:
255 ret = -1;
256finally:
257 Py_XDECREF(stdout_encoding);
258 return ret;
259}
260
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000261static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000262sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100265 PyObject *builtins;
266 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000267 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000268
Eric Snow3f9eee62017-09-15 16:35:20 -0600269 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 if (builtins == NULL) {
271 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
272 return NULL;
273 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600274 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 /* Print value except if None */
277 /* After printing, also assign to '_' */
278 /* Before, set '_' to None to avoid recursion */
279 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200280 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000281 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200282 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000283 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100284 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (outf == NULL || outf == Py_None) {
286 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
287 return NULL;
288 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000289 if (PyFile_WriteObject(o, outf, 0) != 0) {
290 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
291 /* repr(o) is not encodable to sys.stdout.encoding with
292 * sys.stdout.errors error handler (which is probably 'strict') */
293 PyErr_Clear();
294 err = sys_displayhook_unencodable(outf, o);
295 if (err)
296 return NULL;
297 }
298 else {
299 return NULL;
300 }
301 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100302 if (newline == NULL) {
303 newline = PyUnicode_FromString("\n");
304 if (newline == NULL)
305 return NULL;
306 }
307 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200309 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200311 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000312}
313
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000314PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000315"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000316"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000317"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000318);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000319
320static PyObject *
321sys_excepthook(PyObject* self, PyObject* args)
322{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 PyObject *exc, *value, *tb;
324 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
325 return NULL;
326 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200327 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000328}
329
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000330PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000331"excepthook(exctype, value, traceback) -> None\n"
332"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000333"Handle an exception by displaying it with a traceback on sys.stderr.\n"
334);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000335
336static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000337sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000338{
Mark Shannonae3087c2017-10-22 22:41:51 +0100339 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000340 return Py_BuildValue(
341 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100342 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
343 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
344 err_info->exc_traceback != NULL ?
345 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000346}
347
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000348PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000349"exc_info() -> (type, value, traceback)\n\
350\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000351Return information about the most recent exception caught by an except\n\
352clause in the current stack frame or in an older stack frame."
353);
354
355static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000356sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 PyObject *exit_code = 0;
359 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
360 return NULL;
361 /* Raise SystemExit so callers may catch it or clean up. */
362 PyErr_SetObject(PyExc_SystemExit, exit_code);
363 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000364}
365
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000366PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000367"exit([status])\n\
368\n\
369Exit the interpreter by raising SystemExit(status).\n\
370If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300371If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000372If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000373exit status will be one (i.e., failure)."
374);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000375
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000376
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000377static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530378sys_getdefaultencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Fred Drake8b4d01d2000-05-09 19:57:01 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000381}
382
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000383PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000384"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000385\n\
oldkaa0735f2018-02-02 16:52:55 +0800386Return the current default string encoding used by the Unicode\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000387implementation."
388);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000389
390static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530391sys_getfilesystemencoding(PyObject *self, PyObject *Py_UNUSED(ignored))
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000392{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200393 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
394 const _PyCoreConfig *config = &interp->core_config;
395 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000396}
397
398PyDoc_STRVAR(getfilesystemencoding_doc,
399"getfilesystemencoding() -> string\n\
400\n\
401Return the encoding used to convert Unicode filenames in\n\
402operating system filenames."
403);
404
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000405static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +0530406sys_getfilesystemencodeerrors(PyObject *self, PyObject *Py_UNUSED(ignored))
Steve Dowercc16be82016-09-08 10:35:16 -0700407{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200408 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
409 const _PyCoreConfig *config = &interp->core_config;
410 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700411}
412
413PyDoc_STRVAR(getfilesystemencodeerrors_doc,
414 "getfilesystemencodeerrors() -> string\n\
415\n\
416Return the error mode used to convert Unicode filenames in\n\
417operating system filenames."
418);
419
420static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000421sys_intern(PyObject *self, PyObject *args)
422{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 PyObject *s;
424 if (!PyArg_ParseTuple(args, "U:intern", &s))
425 return NULL;
426 if (PyUnicode_CheckExact(s)) {
427 Py_INCREF(s);
428 PyUnicode_InternInPlace(&s);
429 return s;
430 }
431 else {
432 PyErr_Format(PyExc_TypeError,
433 "can't intern %.400s", s->ob_type->tp_name);
434 return NULL;
435 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000436}
437
438PyDoc_STRVAR(intern_doc,
439"intern(string) -> string\n\
440\n\
441``Intern'' the given string. This enters the string in the (global)\n\
442table of interned strings whose purpose is to speed up dictionary lookups.\n\
443Return the string itself or the previously interned string object with the\n\
444same value.");
445
446
Fred Drake5755ce62001-06-27 19:19:46 +0000447/*
448 * Cached interned string objects used for calling the profile and
449 * trace functions. Initialized by trace_init().
450 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000451static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000452
453static int
454trace_init(void)
455{
Nick Coghlan5a851672017-09-08 10:14:16 +1000456 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200457 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000458 "c_call", "c_exception", "c_return",
459 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200460 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyObject *name;
462 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000463 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (whatstrings[i] == NULL) {
465 name = PyUnicode_InternFromString(whatnames[i]);
466 if (name == NULL)
467 return -1;
468 whatstrings[i] = name;
469 }
470 }
471 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000472}
473
474
475static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100476call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000478{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200480 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000481
Victor Stinner78da82b2016-08-20 01:22:57 +0200482 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000483 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200484 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100485
Victor Stinner78da82b2016-08-20 01:22:57 +0200486 stack[0] = (PyObject *)frame;
487 stack[1] = whatstrings[what];
488 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200491 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000492
Victor Stinner78da82b2016-08-20 01:22:57 +0200493 PyFrame_LocalsToFast(frame, 1);
494 if (result == NULL) {
495 PyTraceBack_Here(frame);
496 }
497
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000498 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000499}
500
501static int
502profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000506
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 if (arg == NULL)
508 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100509 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 if (result == NULL) {
511 PyEval_SetProfile(NULL, NULL);
512 return -1;
513 }
514 Py_DECREF(result);
515 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000516}
517
518static int
519trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000521{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 PyObject *callback;
523 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 if (what == PyTrace_CALL)
526 callback = self;
527 else
528 callback = frame->f_trace;
529 if (callback == NULL)
530 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100531 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (result == NULL) {
533 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200534 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return -1;
536 }
537 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300538 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 }
540 else {
541 Py_DECREF(result);
542 }
543 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000544}
Fred Draked0838392001-06-16 21:02:31 +0000545
Fred Drake8b4d01d2000-05-09 19:57:01 +0000546static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000547sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 if (trace_init() == -1)
550 return NULL;
551 if (args == Py_None)
552 PyEval_SetTrace(NULL, NULL);
553 else
554 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200555 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000556}
557
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000558PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000559"settrace(function)\n\
560\n\
561Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000562function call. See the debugger chapter in the library manual."
563);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000564
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000565static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000566sys_gettrace(PyObject *self, PyObject *args)
567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 PyThreadState *tstate = PyThreadState_GET();
569 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (temp == NULL)
572 temp = Py_None;
573 Py_INCREF(temp);
574 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000575}
576
577PyDoc_STRVAR(gettrace_doc,
578"gettrace()\n\
579\n\
580Return the global debug tracing function set with sys.settrace.\n\
581See the debugger chapter in the library manual."
582);
583
584static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000585sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000586{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 if (trace_init() == -1)
588 return NULL;
589 if (args == Py_None)
590 PyEval_SetProfile(NULL, NULL);
591 else
592 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200593 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000594}
595
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000596PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000597"setprofile(function)\n\
598\n\
599Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000600and return. See the profiler chapter in the library manual."
601);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000602
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000603static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000604sys_getprofile(PyObject *self, PyObject *args)
605{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyThreadState *tstate = PyThreadState_GET();
607 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (temp == NULL)
610 temp = Py_None;
611 Py_INCREF(temp);
612 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000613}
614
615PyDoc_STRVAR(getprofile_doc,
616"getprofile()\n\
617\n\
618Return the profiling function set with sys.setprofile.\n\
619See the profiler chapter in the library manual."
620);
621
622static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000623sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000624{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000625 if (PyErr_WarnEx(PyExc_DeprecationWarning,
626 "sys.getcheckinterval() and sys.setcheckinterval() "
627 "are deprecated. Use sys.setswitchinterval() "
628 "instead.", 1) < 0)
629 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200630
631 int check_interval;
632 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200634
635 PyInterpreterState *interp = _PyInterpreterState_Get();
636 interp->check_interval = check_interval;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200637 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000638}
639
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000640PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000641"setcheckinterval(n)\n\
642\n\
643Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000644n instructions. This also affects how often thread switches occur."
645);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000646
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000647static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000648sys_getcheckinterval(PyObject *self, PyObject *args)
649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000650 if (PyErr_WarnEx(PyExc_DeprecationWarning,
651 "sys.getcheckinterval() and sys.setcheckinterval() "
652 "are deprecated. Use sys.getswitchinterval() "
653 "instead.", 1) < 0)
654 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200655 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600656 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000657}
658
659PyDoc_STRVAR(getcheckinterval_doc,
660"getcheckinterval() -> current check interval; see setcheckinterval()."
661);
662
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000663static PyObject *
664sys_setswitchinterval(PyObject *self, PyObject *args)
665{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000666 double d;
667 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
668 return NULL;
669 if (d <= 0.0) {
670 PyErr_SetString(PyExc_ValueError,
671 "switch interval must be strictly positive");
672 return NULL;
673 }
674 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200675 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000676}
677
678PyDoc_STRVAR(setswitchinterval_doc,
679"setswitchinterval(n)\n\
680\n\
681Set the ideal thread switching delay inside the Python interpreter\n\
682The actual frequency of switching threads can be lower if the\n\
683interpreter executes long sequences of uninterruptible code\n\
684(this is implementation-specific and workload-dependent).\n\
685\n\
686The parameter must represent the desired switching delay in seconds\n\
687A typical value is 0.005 (5 milliseconds)."
688);
689
690static PyObject *
691sys_getswitchinterval(PyObject *self, PyObject *args)
692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000694}
695
696PyDoc_STRVAR(getswitchinterval_doc,
697"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
698);
699
Tim Peterse5e065b2003-07-06 18:36:54 +0000700static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000701sys_setrecursionlimit(PyObject *self, PyObject *args)
702{
Victor Stinner50856d52015-10-13 00:11:21 +0200703 int new_limit, mark;
704 PyThreadState *tstate;
705
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000706 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
707 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200708
709 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000710 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200711 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 return NULL;
713 }
Victor Stinner50856d52015-10-13 00:11:21 +0200714
715 /* Issue #25274: When the recursion depth hits the recursion limit in
716 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
717 set to 1 and a RecursionError is raised. The overflowed flag is reset
718 to 0 when the recursion depth goes below the low-water mark: see
719 Py_LeaveRecursiveCall().
720
721 Reject too low new limit if the current recursion depth is higher than
722 the new low-water mark. Otherwise it may not be possible anymore to
723 reset the overflowed flag to 0. */
724 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
725 tstate = PyThreadState_GET();
726 if (tstate->recursion_depth >= mark) {
727 PyErr_Format(PyExc_RecursionError,
728 "cannot set the recursion limit to %i at "
729 "the recursion depth %i: the limit is too low",
730 new_limit, tstate->recursion_depth);
731 return NULL;
732 }
733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200735 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000736}
737
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800738/*[clinic input]
739sys.set_coroutine_origin_tracking_depth
740
741 depth: int
742
743Enable or disable origin tracking for coroutine objects in this thread.
744
745Coroutine objects will track 'depth' frames of traceback information about
746where they came from, available in their cr_origin attribute. Set depth of 0
747to disable.
748[clinic start generated code]*/
749
750static PyObject *
751sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
752/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
753{
754 if (depth < 0) {
755 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
756 return NULL;
757 }
758 _PyEval_SetCoroutineOriginTrackingDepth(depth);
759 Py_RETURN_NONE;
760}
761
762/*[clinic input]
763sys.get_coroutine_origin_tracking_depth -> int
764
765Check status of origin tracking for coroutine objects in this thread.
766[clinic start generated code]*/
767
768static int
769sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
770/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
771{
772 return _PyEval_GetCoroutineOriginTrackingDepth();
773}
774
Yury Selivanov75445082015-05-11 22:57:16 -0400775static PyObject *
776sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
777{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800778 if (PyErr_WarnEx(PyExc_DeprecationWarning,
779 "set_coroutine_wrapper is deprecated", 1) < 0) {
780 return NULL;
781 }
782
Yury Selivanov75445082015-05-11 22:57:16 -0400783 if (wrapper != Py_None) {
784 if (!PyCallable_Check(wrapper)) {
785 PyErr_Format(PyExc_TypeError,
786 "callable expected, got %.50s",
787 Py_TYPE(wrapper)->tp_name);
788 return NULL;
789 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400790 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400791 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400792 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400793 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400794 }
Yury Selivanov75445082015-05-11 22:57:16 -0400795 Py_RETURN_NONE;
796}
797
798PyDoc_STRVAR(set_coroutine_wrapper_doc,
799"set_coroutine_wrapper(wrapper)\n\
800\n\
801Set a wrapper for coroutine objects."
802);
803
804static PyObject *
805sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
806{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800807 if (PyErr_WarnEx(PyExc_DeprecationWarning,
808 "get_coroutine_wrapper is deprecated", 1) < 0) {
809 return NULL;
810 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400811 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400812 if (wrapper == NULL) {
813 wrapper = Py_None;
814 }
815 Py_INCREF(wrapper);
816 return wrapper;
817}
818
819PyDoc_STRVAR(get_coroutine_wrapper_doc,
820"get_coroutine_wrapper()\n\
821\n\
822Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
823);
824
825
Yury Selivanoveb636452016-09-08 22:01:51 -0700826static PyTypeObject AsyncGenHooksType;
827
828PyDoc_STRVAR(asyncgen_hooks_doc,
829"asyncgen_hooks\n\
830\n\
831A struct sequence providing information about asynhronous\n\
832generators hooks. The attributes are read only.");
833
834static PyStructSequence_Field asyncgen_hooks_fields[] = {
835 {"firstiter", "Hook to intercept first iteration"},
836 {"finalizer", "Hook to intercept finalization"},
837 {0}
838};
839
840static PyStructSequence_Desc asyncgen_hooks_desc = {
841 "asyncgen_hooks", /* name */
842 asyncgen_hooks_doc, /* doc */
843 asyncgen_hooks_fields , /* fields */
844 2
845};
846
847
848static PyObject *
849sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
850{
851 static char *keywords[] = {"firstiter", "finalizer", NULL};
852 PyObject *firstiter = NULL;
853 PyObject *finalizer = NULL;
854
855 if (!PyArg_ParseTupleAndKeywords(
856 args, kw, "|OO", keywords,
857 &firstiter, &finalizer)) {
858 return NULL;
859 }
860
861 if (finalizer && finalizer != Py_None) {
862 if (!PyCallable_Check(finalizer)) {
863 PyErr_Format(PyExc_TypeError,
864 "callable finalizer expected, got %.50s",
865 Py_TYPE(finalizer)->tp_name);
866 return NULL;
867 }
868 _PyEval_SetAsyncGenFinalizer(finalizer);
869 }
870 else if (finalizer == Py_None) {
871 _PyEval_SetAsyncGenFinalizer(NULL);
872 }
873
874 if (firstiter && firstiter != Py_None) {
875 if (!PyCallable_Check(firstiter)) {
876 PyErr_Format(PyExc_TypeError,
877 "callable firstiter expected, got %.50s",
878 Py_TYPE(firstiter)->tp_name);
879 return NULL;
880 }
881 _PyEval_SetAsyncGenFirstiter(firstiter);
882 }
883 else if (firstiter == Py_None) {
884 _PyEval_SetAsyncGenFirstiter(NULL);
885 }
886
887 Py_RETURN_NONE;
888}
889
890PyDoc_STRVAR(set_asyncgen_hooks_doc,
891"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
892\n\
893Set a finalizer for async generators objects."
894);
895
896static PyObject *
897sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
898{
899 PyObject *res;
900 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
901 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
902
903 res = PyStructSequence_New(&AsyncGenHooksType);
904 if (res == NULL) {
905 return NULL;
906 }
907
908 if (firstiter == NULL) {
909 firstiter = Py_None;
910 }
911
912 if (finalizer == NULL) {
913 finalizer = Py_None;
914 }
915
916 Py_INCREF(firstiter);
917 PyStructSequence_SET_ITEM(res, 0, firstiter);
918
919 Py_INCREF(finalizer);
920 PyStructSequence_SET_ITEM(res, 1, finalizer);
921
922 return res;
923}
924
925PyDoc_STRVAR(get_asyncgen_hooks_doc,
926"get_asyncgen_hooks()\n\
927\n\
928Return a namedtuple of installed asynchronous generators hooks \
929(firstiter, finalizer)."
930);
931
932
Mark Dickinsondc787d22010-05-23 13:33:13 +0000933static PyTypeObject Hash_InfoType;
934
935PyDoc_STRVAR(hash_info_doc,
936"hash_info\n\
937\n\
938A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100939hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000940
941static PyStructSequence_Field hash_info_fields[] = {
942 {"width", "width of the type used for hashing, in bits"},
943 {"modulus", "prime number giving the modulus on which the hash "
944 "function is based"},
945 {"inf", "value to be used for hash of a positive infinity"},
946 {"nan", "value to be used for hash of a nan"},
947 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100948 {"algorithm", "name of the algorithm for hashing of str, bytes and "
949 "memoryviews"},
950 {"hash_bits", "internal output size of hash algorithm"},
951 {"seed_bits", "seed size of hash algorithm"},
952 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000953 {NULL, NULL}
954};
955
956static PyStructSequence_Desc hash_info_desc = {
957 "sys.hash_info",
958 hash_info_doc,
959 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100960 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000961};
962
Matthias Klosed885e952010-07-06 10:53:30 +0000963static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000964get_hash_info(void)
965{
966 PyObject *hash_info;
967 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100968 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000969 hash_info = PyStructSequence_New(&Hash_InfoType);
970 if (hash_info == NULL)
971 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100972 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000973 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000974 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000975 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000976 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000977 PyStructSequence_SET_ITEM(hash_info, field++,
978 PyLong_FromLong(_PyHASH_INF));
979 PyStructSequence_SET_ITEM(hash_info, field++,
980 PyLong_FromLong(_PyHASH_NAN));
981 PyStructSequence_SET_ITEM(hash_info, field++,
982 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100983 PyStructSequence_SET_ITEM(hash_info, field++,
984 PyUnicode_FromString(hashfunc->name));
985 PyStructSequence_SET_ITEM(hash_info, field++,
986 PyLong_FromLong(hashfunc->hash_bits));
987 PyStructSequence_SET_ITEM(hash_info, field++,
988 PyLong_FromLong(hashfunc->seed_bits));
989 PyStructSequence_SET_ITEM(hash_info, field++,
990 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000991 if (PyErr_Occurred()) {
992 Py_CLEAR(hash_info);
993 return NULL;
994 }
995 return hash_info;
996}
997
998
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000999PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001000"setrecursionlimit(n)\n\
1001\n\
1002Set the maximum depth of the Python interpreter stack to n. This\n\
1003limit prevents infinite recursion from causing an overflow of the C\n\
1004stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001005dependent."
1006);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001007
1008static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301009sys_getrecursionlimit(PyObject *self, PyObject *Py_UNUSED(ignored))
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001012}
1013
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001014PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001015"getrecursionlimit()\n\
1016\n\
1017Return the current value of the recursion limit, the maximum depth\n\
1018of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001019recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001020);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001021
Mark Hammond8696ebc2002-10-08 02:44:31 +00001022#ifdef MS_WINDOWS
1023PyDoc_STRVAR(getwindowsversion_doc,
1024"getwindowsversion()\n\
1025\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001026Return information about the running version of Windows as a named tuple.\n\
1027The members are named: major, minor, build, platform, service_pack,\n\
1028service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001029backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001030All elements are numbers, except service_pack and platform_type which are\n\
1031strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1032Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1033server. Platform_version is a 3-tuple containing a version number that is\n\
1034intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001035);
1036
Eric Smithf7bb5782010-01-27 00:44:57 +00001037static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1038
1039static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 {"major", "Major version number"},
1041 {"minor", "Minor version number"},
1042 {"build", "Build number"},
1043 {"platform", "Operating system platform"},
1044 {"service_pack", "Latest Service Pack installed on the system"},
1045 {"service_pack_major", "Service Pack major version number"},
1046 {"service_pack_minor", "Service Pack minor version number"},
1047 {"suite_mask", "Bit mask identifying available product suites"},
1048 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001049 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001051};
1052
1053static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 "sys.getwindowsversion", /* name */
1055 getwindowsversion_doc, /* doc */
1056 windows_version_fields, /* fields */
1057 5 /* For backward compatibility,
1058 only the first 5 items are accessible
1059 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001060};
1061
Steve Dower3e96f322015-03-02 08:01:10 -08001062/* Disable deprecation warnings about GetVersionEx as the result is
1063 being passed straight through to the caller, who is responsible for
1064 using it correctly. */
1065#pragma warning(push)
1066#pragma warning(disable:4996)
1067
Mark Hammond8696ebc2002-10-08 02:44:31 +00001068static PyObject *
1069sys_getwindowsversion(PyObject *self)
1070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 PyObject *version;
1072 int pos = 0;
1073 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001074 DWORD realMajor, realMinor, realBuild;
1075 HANDLE hKernel32;
1076 wchar_t kernel32_path[MAX_PATH];
1077 LPVOID verblock;
1078 DWORD verblock_size;
1079
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 ver.dwOSVersionInfoSize = sizeof(ver);
1081 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1082 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 version = PyStructSequence_New(&WindowsVersionType);
1085 if (version == NULL)
1086 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1089 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1090 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1091 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1092 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1093 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1094 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1095 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1096 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001097
Steve Dower74f4af72016-09-17 17:27:48 -07001098 realMajor = ver.dwMajorVersion;
1099 realMinor = ver.dwMinorVersion;
1100 realBuild = ver.dwBuildNumber;
1101
1102 // GetVersion will lie if we are running in a compatibility mode.
1103 // We need to read the version info from a system file resource
1104 // to accurately identify the OS version. If we fail for any reason,
1105 // just return whatever GetVersion said.
1106 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1107 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1108 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1109 (verblock = PyMem_RawMalloc(verblock_size))) {
1110 VS_FIXEDFILEINFO *ffi;
1111 UINT ffi_len;
1112
1113 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1114 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1115 realMajor = HIWORD(ffi->dwProductVersionMS);
1116 realMinor = LOWORD(ffi->dwProductVersionMS);
1117 realBuild = HIWORD(ffi->dwProductVersionLS);
1118 }
1119 PyMem_RawFree(verblock);
1120 }
Segev Finer48fb7662017-06-04 20:52:27 +03001121 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1122 realMajor,
1123 realMinor,
1124 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001125 ));
1126
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001127 if (PyErr_Occurred()) {
1128 Py_DECREF(version);
1129 return NULL;
1130 }
Steve Dower74f4af72016-09-17 17:27:48 -07001131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001133}
1134
Steve Dower3e96f322015-03-02 08:01:10 -08001135#pragma warning(pop)
1136
Steve Dowercc16be82016-09-08 10:35:16 -07001137PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1138"_enablelegacywindowsfsencoding()\n\
1139\n\
1140Changes the default filesystem encoding to mbcs:replace for consistency\n\
1141with earlier versions of Python. See PEP 529 for more information.\n\
1142\n\
oldkaa0735f2018-02-02 16:52:55 +08001143This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING\n\
Steve Dowercc16be82016-09-08 10:35:16 -07001144environment variable before launching Python."
1145);
1146
1147static PyObject *
1148sys_enablelegacywindowsfsencoding(PyObject *self)
1149{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001150 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1151 _PyCoreConfig *config = &interp->core_config;
1152
1153 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1154 char *encoding = _PyMem_RawStrdup("mbcs");
1155 char *errors = _PyMem_RawStrdup("replace");
1156 if (encoding == NULL || errors == NULL) {
1157 PyMem_Free(encoding);
1158 PyMem_Free(errors);
1159 PyErr_NoMemory();
1160 return NULL;
1161 }
1162
1163 PyMem_RawFree(config->filesystem_encoding);
1164 config->filesystem_encoding = encoding;
1165 PyMem_RawFree(config->filesystem_errors);
1166 config->filesystem_errors = errors;
1167
1168 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1169 config->filesystem_errors) < 0) {
1170 PyErr_NoMemory();
1171 return NULL;
1172 }
1173
Steve Dowercc16be82016-09-08 10:35:16 -07001174 Py_RETURN_NONE;
1175}
1176
Mark Hammond8696ebc2002-10-08 02:44:31 +00001177#endif /* MS_WINDOWS */
1178
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001179#ifdef HAVE_DLOPEN
1180static PyObject *
1181sys_setdlopenflags(PyObject *self, PyObject *args)
1182{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 int new_val;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1185 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +02001186 PyInterpreterState *interp = _PyInterpreterState_Get();
1187 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001188 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001189}
1190
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001191PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001192"setdlopenflags(n) -> None\n\
1193\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001194Set the flags used by the interpreter for dlopen calls, such as when the\n\
1195interpreter loads extension modules. Among other things, this will enable\n\
1196a lazy resolving of symbols when importing a module, if called as\n\
1197sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001198sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001199can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001200
1201static PyObject *
1202sys_getdlopenflags(PyObject *self, PyObject *args)
1203{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001204 PyInterpreterState *interp = _PyInterpreterState_Get();
1205 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001206}
1207
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001208PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001209"getdlopenflags() -> int\n\
1210\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001211Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001212The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001213
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001214#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001215
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001216#ifdef USE_MALLOPT
1217/* Link with -lmalloc (or -lmpc) on an SGI */
1218#include <malloc.h>
1219
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001220static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001221sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 int flag;
1224 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1225 return NULL;
1226 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001227 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001228}
1229#endif /* USE_MALLOPT */
1230
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001231size_t
1232_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001235 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001236 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001237
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001238 /* Make sure the type is initialized. float gets initialized late */
1239 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001240 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001241
Benjamin Petersonce798522012-01-22 11:24:29 -05001242 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001243 if (method == NULL) {
1244 if (!PyErr_Occurred())
1245 PyErr_Format(PyExc_TypeError,
1246 "Type %.100s doesn't define __sizeof__",
1247 Py_TYPE(o)->tp_name);
1248 }
1249 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001250 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251 Py_DECREF(method);
1252 }
1253
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001254 if (res == NULL)
1255 return (size_t)-1;
1256
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001257 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001258 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001259 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001260 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001262 if (size < 0) {
1263 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1264 return (size_t)-1;
1265 }
1266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001268 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001269 return ((size_t)size) + sizeof(PyGC_Head);
1270 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001271}
1272
1273static PyObject *
1274sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1275{
1276 static char *kwlist[] = {"object", "default", 0};
1277 size_t size;
1278 PyObject *o, *dflt = NULL;
1279
1280 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1281 kwlist, &o, &dflt))
1282 return NULL;
1283
1284 size = _PySys_GetSizeOf(o);
1285
1286 if (size == (size_t)-1 && PyErr_Occurred()) {
1287 /* Has a default value been given */
1288 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1289 PyErr_Clear();
1290 Py_INCREF(dflt);
1291 return dflt;
1292 }
1293 else
1294 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001296
1297 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001298}
1299
1300PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001301"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001302\n\
1303Return the size of object in bytes.");
1304
1305static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001306sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001309}
1310
Tim Peters4be93d02002-07-07 19:59:50 +00001311#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001312static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301313sys_gettotalrefcount(PyObject *self, PyObject *Py_UNUSED(ignored))
Mark Hammond440d8982000-06-20 08:12:48 +00001314{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001316}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001317#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001318
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001319PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001320"getrefcount(object) -> integer\n\
1321\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001322Return the reference count of object. The count returned is generally\n\
1323one higher than you might expect, because it includes the (temporary)\n\
1324reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001325);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001326
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001327static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301328sys_getallocatedblocks(PyObject *self, PyObject *Py_UNUSED(ignored))
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001329{
1330 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1331}
1332
1333PyDoc_STRVAR(getallocatedblocks_doc,
1334"getallocatedblocks() -> integer\n\
1335\n\
1336Return the number of memory blocks currently allocated, regardless of their\n\
1337size."
1338);
1339
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001340#ifdef COUNT_ALLOCS
1341static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001342sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001343{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001344 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001345
Pablo Galindo49c75a82018-10-28 15:02:17 +00001346 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001347}
1348#endif
1349
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001350PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001351"_getframe([depth]) -> frameobject\n\
1352\n\
1353Return a frame object from the call stack. If optional integer depth is\n\
1354given, return the frame object that many calls below the top of the stack.\n\
1355If that is deeper than the call stack, ValueError is raised. The default\n\
1356for depth is zero, returning the frame at the top of the call stack.\n\
1357\n\
1358This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001359purposes only."
1360);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001361
1362static PyObject *
1363sys_getframe(PyObject *self, PyObject *args)
1364{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 PyFrameObject *f = PyThreadState_GET()->frame;
1366 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001367
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1369 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001370
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001371 while (depth > 0 && f != NULL) {
1372 f = f->f_back;
1373 --depth;
1374 }
1375 if (f == NULL) {
1376 PyErr_SetString(PyExc_ValueError,
1377 "call stack is not deep enough");
1378 return NULL;
1379 }
1380 Py_INCREF(f);
1381 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001382}
1383
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001384PyDoc_STRVAR(current_frames_doc,
1385"_current_frames() -> dictionary\n\
1386\n\
1387Return a dictionary mapping each current thread T's thread id to T's\n\
1388current stack frame.\n\
1389\n\
1390This function should be used for specialized purposes only."
1391);
1392
1393static PyObject *
1394sys_current_frames(PyObject *self, PyObject *noargs)
1395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001397}
1398
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001399PyDoc_STRVAR(call_tracing_doc,
1400"call_tracing(func, args) -> object\n\
1401\n\
1402Call func(*args), while tracing is enabled. The tracing state is\n\
1403saved, and restored afterwards. This is intended to be called from\n\
1404a debugger from a checkpoint, to recursively debug some other code."
1405);
1406
1407static PyObject *
1408sys_call_tracing(PyObject *self, PyObject *args)
1409{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 PyObject *func, *funcargs;
1411 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1412 return NULL;
1413 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001414}
1415
Jeremy Hylton985eba52003-02-05 23:13:00 +00001416PyDoc_STRVAR(callstats_doc,
1417"callstats() -> tuple of integers\n\
1418\n\
1419Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1420when Python was built. Otherwise, return None.\n\
1421\n\
1422When enabled, this function returns detailed, implementation-specific\n\
1423details about the number of function calls executed. The return value is\n\
1424a 11-tuple where the entries in the tuple are counts of:\n\
14250. all function calls\n\
14261. calls to PyFunction_Type objects\n\
14272. PyFunction calls that do not create an argument tuple\n\
14283. PyFunction calls that do not create an argument tuple\n\
1429 and bypass PyEval_EvalCodeEx()\n\
14304. PyMethod calls\n\
14315. PyMethod calls on bound methods\n\
14326. PyType calls\n\
14337. PyCFunction calls\n\
14348. generator calls\n\
14359. All other calls\n\
143610. Number of stack pops performed by call_function()"
1437);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001438
Victor Stinner048afd92016-11-28 11:59:04 +01001439static PyObject *
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301440sys_callstats(PyObject *self, PyObject *Py_UNUSED(ignored))
Victor Stinner048afd92016-11-28 11:59:04 +01001441{
1442 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1443 "sys.callstats() has been deprecated in Python 3.7 "
1444 "and will be removed in the future", 1) < 0) {
1445 return NULL;
1446 }
1447
1448 Py_RETURN_NONE;
1449}
1450
1451
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001452#ifdef __cplusplus
1453extern "C" {
1454#endif
1455
David Malcolm49526f42012-06-22 14:55:41 -04001456static PyObject *
1457sys_debugmallocstats(PyObject *self, PyObject *args)
1458{
1459#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001460 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001461 fputc('\n', stderr);
1462 }
David Malcolm49526f42012-06-22 14:55:41 -04001463#endif
1464 _PyObject_DebugTypeStats(stderr);
1465
1466 Py_RETURN_NONE;
1467}
1468PyDoc_STRVAR(debugmallocstats_doc,
1469"_debugmallocstats()\n\
1470\n\
1471Print summary info to stderr about the state of\n\
1472pymalloc's structures.\n\
1473\n\
1474In Py_DEBUG mode, also perform some expensive internal consistency\n\
1475checks.\n\
1476");
1477
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001478#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001479/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001480extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001481#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001482
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001483#ifdef DYNAMIC_EXECUTION_PROFILE
1484/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001485extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001486#endif
1487
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001488#ifdef __cplusplus
1489}
1490#endif
1491
Christian Heimes15ebc882008-02-04 18:48:49 +00001492static PyObject *
1493sys_clear_type_cache(PyObject* self, PyObject* args)
1494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 PyType_ClearCache();
1496 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001497}
1498
1499PyDoc_STRVAR(sys_clear_type_cache__doc__,
1500"_clear_type_cache() -> None\n\
1501Clear the internal type lookup cache.");
1502
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001503static PyObject *
1504sys_is_finalizing(PyObject* self, PyObject* args)
1505{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001506 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001507}
1508
1509PyDoc_STRVAR(is_finalizing_doc,
1510"is_finalizing()\n\
1511Return True if Python is exiting.");
1512
Christian Heimes15ebc882008-02-04 18:48:49 +00001513
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001514#ifdef ANDROID_API_LEVEL
1515PyDoc_STRVAR(getandroidapilevel_doc,
1516"getandroidapilevel()\n\
1517\n\
1518Return the build time API version of Android as an integer.");
1519
1520static PyObject *
1521sys_getandroidapilevel(PyObject *self)
1522{
1523 return PyLong_FromLong(ANDROID_API_LEVEL);
1524}
1525#endif /* ANDROID_API_LEVEL */
1526
1527
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001528static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001530 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1531 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301532 {"callstats", sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 callstats_doc},
1534 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1535 sys_clear_type_cache__doc__},
1536 {"_current_frames", sys_current_frames, METH_NOARGS,
1537 current_frames_doc},
1538 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1539 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1540 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1541 {"exit", sys_exit, METH_VARARGS, exit_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301542 {"getdefaultencoding", sys_getdefaultencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001544#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1546 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001547#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301548 {"getallocatedblocks", sys_getallocatedblocks, METH_NOARGS,
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001549 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001550#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001552#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001553#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001555#endif
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301556 {"getfilesystemencoding", sys_getfilesystemencoding,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 METH_NOARGS, getfilesystemencoding_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301558 { "getfilesystemencodeerrors", sys_getfilesystemencodeerrors,
Steve Dowercc16be82016-09-08 10:35:16 -07001559 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001560#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001562#endif
1563#ifdef Py_REF_DEBUG
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301564 {"gettotalrefcount", sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001565#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
Siddhesh Poyarekar55edd0c2018-04-30 00:29:33 +05301567 {"getrecursionlimit", sys_getrecursionlimit, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 getrecursionlimit_doc},
1569 {"getsizeof", (PyCFunction)sys_getsizeof,
1570 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1571 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001572#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1574 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001575 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1576 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001577#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001579 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001580#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001582#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1584 setcheckinterval_doc},
1585 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1586 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1588 setswitchinterval_doc},
1589 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1590 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001591#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1593 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001594#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1596 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1597 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1598 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 {"settrace", sys_settrace, METH_O, settrace_doc},
1600 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1601 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001602 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001603 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001604 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1605 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001606 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1607 set_coroutine_wrapper_doc},
1608 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1609 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001610 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001611 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1612 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1613 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001614#ifdef ANDROID_API_LEVEL
1615 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1616 getandroidapilevel_doc},
1617#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001619};
1620
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001621static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001622list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 PyObject *list = PyList_New(0);
1625 int i;
1626 if (list == NULL)
1627 return NULL;
1628 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1629 PyObject *name = PyUnicode_FromString(
1630 PyImport_Inittab[i].name);
1631 if (name == NULL)
1632 break;
1633 PyList_Append(list, name);
1634 Py_DECREF(name);
1635 }
1636 if (PyList_Sort(list) != 0) {
1637 Py_DECREF(list);
1638 list = NULL;
1639 }
1640 if (list) {
1641 PyObject *v = PyList_AsTuple(list);
1642 Py_DECREF(list);
1643 list = v;
1644 }
1645 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001646}
1647
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001648/* Pre-initialization support for sys.warnoptions and sys._xoptions
1649 *
1650 * Modern internal code paths:
1651 * These APIs get called after _Py_InitializeCore and get to use the
1652 * regular CPython list, dict, and unicode APIs.
1653 *
1654 * Legacy embedding code paths:
1655 * The multi-phase initialization API isn't public yet, so embedding
1656 * apps still need to be able configure sys.warnoptions and sys._xoptions
1657 * before they call Py_Initialize. To support this, we stash copies of
1658 * the supplied wchar * sequences in linked lists, and then migrate the
1659 * contents of those lists to the sys module in _PyInitializeCore.
1660 *
1661 */
1662
1663struct _preinit_entry {
1664 wchar_t *value;
1665 struct _preinit_entry *next;
1666};
1667
1668typedef struct _preinit_entry *_Py_PreInitEntry;
1669
1670static _Py_PreInitEntry _preinit_warnoptions = NULL;
1671static _Py_PreInitEntry _preinit_xoptions = NULL;
1672
1673static _Py_PreInitEntry
1674_alloc_preinit_entry(const wchar_t *value)
1675{
1676 /* To get this to work, we have to initialize the runtime implicitly */
1677 _PyRuntime_Initialize();
1678
1679 /* Force default allocator, so we can ensure that it also gets used to
1680 * destroy the linked list in _clear_preinit_entries.
1681 */
1682 PyMemAllocatorEx old_alloc;
1683 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1684
1685 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1686 if (node != NULL) {
1687 node->value = _PyMem_RawWcsdup(value);
1688 if (node->value == NULL) {
1689 PyMem_RawFree(node);
1690 node = NULL;
1691 };
1692 };
1693
1694 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1695 return node;
1696};
1697
1698static int
1699_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1700{
1701 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1702 if (new_entry == NULL) {
1703 return -1;
1704 }
1705 /* We maintain the linked list in this order so it's easy to play back
1706 * the add commands in the same order later on in _Py_InitializeCore
1707 */
1708 _Py_PreInitEntry last_entry = *optionlist;
1709 if (last_entry == NULL) {
1710 *optionlist = new_entry;
1711 } else {
1712 while (last_entry->next != NULL) {
1713 last_entry = last_entry->next;
1714 }
1715 last_entry->next = new_entry;
1716 }
1717 return 0;
1718};
1719
1720static void
1721_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1722{
1723 _Py_PreInitEntry current = *optionlist;
1724 *optionlist = NULL;
1725 /* Deallocate the nodes and their contents using the default allocator */
1726 PyMemAllocatorEx old_alloc;
1727 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1728 while (current != NULL) {
1729 _Py_PreInitEntry next = current->next;
1730 PyMem_RawFree(current->value);
1731 PyMem_RawFree(current);
1732 current = next;
1733 }
1734 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1735};
1736
1737static void
1738_clear_all_preinit_options(void)
1739{
1740 _clear_preinit_entries(&_preinit_warnoptions);
1741 _clear_preinit_entries(&_preinit_xoptions);
1742}
1743
1744static int
1745_PySys_ReadPreInitOptions(void)
1746{
1747 /* Rerun the add commands with the actual sys module available */
1748 PyThreadState *tstate = PyThreadState_GET();
1749 if (tstate == NULL) {
1750 /* Still don't have a thread state, so something is wrong! */
1751 return -1;
1752 }
1753 _Py_PreInitEntry entry = _preinit_warnoptions;
1754 while (entry != NULL) {
1755 PySys_AddWarnOption(entry->value);
1756 entry = entry->next;
1757 }
1758 entry = _preinit_xoptions;
1759 while (entry != NULL) {
1760 PySys_AddXOption(entry->value);
1761 entry = entry->next;
1762 }
1763
1764 _clear_all_preinit_options();
1765 return 0;
1766};
1767
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001768static PyObject *
1769get_warnoptions(void)
1770{
Eric Snowdae02762017-09-14 00:35:58 -07001771 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001772 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001773 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1774 * interpreter config. When that happens, we need to properly set
1775 * the `warnoptions` reference in the main interpreter config as well.
1776 *
1777 * For Python 3.7, we shouldn't be able to get here due to the
1778 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1779 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1780 * call optional for embedding applications, thus making this
1781 * reachable again.
1782 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001783 Py_XDECREF(warnoptions);
1784 warnoptions = PyList_New(0);
1785 if (warnoptions == NULL)
1786 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001787 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1788 Py_DECREF(warnoptions);
1789 return NULL;
1790 }
1791 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001792 }
1793 return warnoptions;
1794}
Guido van Rossum23fff912000-12-15 22:02:05 +00001795
1796void
1797PySys_ResetWarnOptions(void)
1798{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001799 PyThreadState *tstate = PyThreadState_GET();
1800 if (tstate == NULL) {
1801 _clear_preinit_entries(&_preinit_warnoptions);
1802 return;
1803 }
1804
Eric Snowdae02762017-09-14 00:35:58 -07001805 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 if (warnoptions == NULL || !PyList_Check(warnoptions))
1807 return;
1808 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001809}
1810
Victor Stinnere1b29952018-10-30 14:31:42 +01001811static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001812_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001813{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001814 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001815 if (warnoptions == NULL) {
1816 return -1;
1817 }
1818 if (PyList_Append(warnoptions, option)) {
1819 return -1;
1820 }
1821 return 0;
1822}
1823
1824void
1825PySys_AddWarnOptionUnicode(PyObject *option)
1826{
Victor Stinnere1b29952018-10-30 14:31:42 +01001827 if (_PySys_AddWarnOptionWithError(option) < 0) {
1828 /* No return value, therefore clear error state if possible */
1829 if (_PyThreadState_UncheckedGet()) {
1830 PyErr_Clear();
1831 }
1832 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001833}
1834
1835void
1836PySys_AddWarnOption(const wchar_t *s)
1837{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001838 PyThreadState *tstate = PyThreadState_GET();
1839 if (tstate == NULL) {
1840 _append_preinit_entry(&_preinit_warnoptions, s);
1841 return;
1842 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001843 PyObject *unicode;
1844 unicode = PyUnicode_FromWideChar(s, -1);
1845 if (unicode == NULL)
1846 return;
1847 PySys_AddWarnOptionUnicode(unicode);
1848 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001849}
1850
Christian Heimes33fe8092008-04-13 13:53:33 +00001851int
1852PySys_HasWarnOptions(void)
1853{
Eric Snowdae02762017-09-14 00:35:58 -07001854 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Christian Heimes33fe8092008-04-13 13:53:33 +00001855 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1856}
1857
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001858static PyObject *
1859get_xoptions(void)
1860{
Eric Snowdae02762017-09-14 00:35:58 -07001861 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001862 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001863 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1864 * interpreter config. When that happens, we need to properly set
1865 * the `xoptions` reference in the main interpreter config as well.
1866 *
1867 * For Python 3.7, we shouldn't be able to get here due to the
1868 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1869 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1870 * call optional for embedding applications, thus making this
1871 * reachable again.
1872 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001873 Py_XDECREF(xoptions);
1874 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001875 if (xoptions == NULL)
1876 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001877 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1878 Py_DECREF(xoptions);
1879 return NULL;
1880 }
1881 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001882 }
1883 return xoptions;
1884}
1885
Victor Stinnere1b29952018-10-30 14:31:42 +01001886static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001887_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001888{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001889 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001890
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001891 PyObject *opts = get_xoptions();
1892 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001893 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001894 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001895
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001897 if (!name_end) {
1898 name = PyUnicode_FromWideChar(s, -1);
1899 value = Py_True;
1900 Py_INCREF(value);
1901 }
1902 else {
1903 name = PyUnicode_FromWideChar(s, name_end - s);
1904 value = PyUnicode_FromWideChar(name_end + 1, -1);
1905 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001906 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001907 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001908 }
1909 if (PyDict_SetItem(opts, name, value) < 0) {
1910 goto error;
1911 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001912 Py_DECREF(name);
1913 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001914 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001915
1916error:
1917 Py_XDECREF(name);
1918 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001919 return -1;
1920}
1921
1922void
1923PySys_AddXOption(const wchar_t *s)
1924{
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001925 PyThreadState *tstate = PyThreadState_GET();
1926 if (tstate == NULL) {
1927 _append_preinit_entry(&_preinit_xoptions, s);
1928 return;
1929 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001930 if (_PySys_AddXOptionWithError(s) < 0) {
1931 /* No return value, therefore clear error state if possible */
1932 if (_PyThreadState_UncheckedGet()) {
1933 PyErr_Clear();
1934 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001935 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001936}
1937
1938PyObject *
1939PySys_GetXOptions(void)
1940{
1941 return get_xoptions();
1942}
1943
Guido van Rossum40552d01998-08-06 03:34:39 +00001944/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1945 Two literals concatenated works just fine. If you have a K&R compiler
1946 or other abomination that however *does* understand longer strings,
1947 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001948PyDoc_VAR(sys_doc) =
1949PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001950"This module provides access to some objects used or maintained by the\n\
1951interpreter and to functions that interact strongly with the interpreter.\n\
1952\n\
1953Dynamic objects:\n\
1954\n\
1955argv -- command line arguments; argv[0] is the script pathname if known\n\
1956path -- module search path; path[0] is the script directory, else ''\n\
1957modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001958\n\
1959displayhook -- called to show results in an interactive session\n\
1960excepthook -- called to handle any uncaught exception other than SystemExit\n\
1961 To customize printing in an interactive session or to install a custom\n\
1962 top-level exception handler, assign other functions to replace these.\n\
1963\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001964stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001965stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001966stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001967 By assigning other file objects (or objects that behave like files)\n\
1968 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001969\n\
1970last_type -- type of last uncaught exception\n\
1971last_value -- value of last uncaught exception\n\
1972last_traceback -- traceback of last uncaught exception\n\
1973 These three are only available in an interactive session after a\n\
1974 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001975"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001976)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001977/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001978PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001979"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001980Static objects:\n\
1981\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001982builtin_module_names -- tuple of module names built into this interpreter\n\
1983copyright -- copyright notice pertaining to this interpreter\n\
1984exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001985executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001986float_info -- a struct sequence with information about the float implementation.\n\
1987float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001988hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001989hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001990implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001991int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001992maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001993maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001994platform -- platform identifier\n\
1995prefix -- prefix used to find the Python library\n\
1996thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001997version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001998version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001999"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002000)
Steve Dowercc16be82016-09-08 10:35:16 -07002001#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002002/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002003PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002004"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002005winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002006"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002007)
Steve Dowercc16be82016-09-08 10:35:16 -07002008#endif /* MS_COREDLL */
2009#ifdef MS_WINDOWS
2010/* concatenating string here */
2011PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002012"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002013"
2014)
2015#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002016PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002017"__stdin__ -- the original stdin; don't touch!\n\
2018__stdout__ -- the original stdout; don't touch!\n\
2019__stderr__ -- the original stderr; don't touch!\n\
2020__displayhook__ -- the original displayhook; don't touch!\n\
2021__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002022\n\
2023Functions:\n\
2024\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002025displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002026excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002027exc_info() -- return thread-safe information about the current exception\n\
2028exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002029getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002030getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002031getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002032getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002033getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002034gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002035setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002036setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002037setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002038setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002039settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002040"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002041)
Fred Drakeccede592000-08-14 20:59:57 +00002042/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002043
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002044
2045PyDoc_STRVAR(flags__doc__,
2046"sys.flags\n\
2047\n\
2048Flags provided through command line arguments or environment vars.");
2049
2050static PyTypeObject FlagsType;
2051
2052static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 {"inspect", "-i"},
2055 {"interactive", "-i"},
2056 {"optimize", "-O or -OO"},
2057 {"dont_write_bytecode", "-B"},
2058 {"no_user_site", "-s"},
2059 {"no_site", "-S"},
2060 {"ignore_environment", "-E"},
2061 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002062 /* {"unbuffered", "-u"}, */
2063 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002064 {"bytes_warning", "-b"},
2065 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002066 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002067 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002068 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002069 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002070 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002071};
2072
2073static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 "sys.flags", /* name */
2075 flags__doc__, /* doc */
2076 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002077 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002078};
2079
2080static PyObject*
2081make_flags(void)
2082{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002083 int pos = 0;
2084 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002085 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002086
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 seq = PyStructSequence_New(&FlagsType);
2088 if (seq == NULL)
2089 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002090
2091#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002092 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002093
Victor Stinnerfbca9082018-08-30 00:50:45 +02002094 SetFlag(config->parser_debug);
2095 SetFlag(config->inspect);
2096 SetFlag(config->interactive);
2097 SetFlag(config->optimization_level);
2098 SetFlag(!config->write_bytecode);
2099 SetFlag(!config->user_site_directory);
2100 SetFlag(!config->site_import);
2101 SetFlag(!config->use_environment);
2102 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 /* SetFlag(saw_unbuffered_flag); */
2104 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002105 SetFlag(config->bytes_warning);
2106 SetFlag(config->quiet);
2107 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2108 SetFlag(config->isolated);
2109 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2110 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002111#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002112
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002113 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002114 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 return NULL;
2116 }
2117 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002118}
2119
Eric Smith0e5b5622009-02-06 01:32:42 +00002120PyDoc_STRVAR(version_info__doc__,
2121"sys.version_info\n\
2122\n\
2123Version information as a named tuple.");
2124
2125static PyTypeObject VersionInfoType;
2126
2127static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 {"major", "Major release number"},
2129 {"minor", "Minor release number"},
2130 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002131 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 {"serial", "Serial release number"},
2133 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002134};
2135
2136static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 "sys.version_info", /* name */
2138 version_info__doc__, /* doc */
2139 version_info_fields, /* fields */
2140 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002141};
2142
2143static PyObject *
2144make_version_info(void)
2145{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 PyObject *version_info;
2147 char *s;
2148 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002149
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 version_info = PyStructSequence_New(&VersionInfoType);
2151 if (version_info == NULL) {
2152 return NULL;
2153 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002154
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 /*
2156 * These release level checks are mutually exclusive and cover
2157 * the field, so don't get too fancy with the pre-processor!
2158 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002159#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002161#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002162 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002163#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002165#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002167#endif
2168
2169#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002171#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 SetIntItem(PY_MAJOR_VERSION);
2175 SetIntItem(PY_MINOR_VERSION);
2176 SetIntItem(PY_MICRO_VERSION);
2177 SetStrItem(s);
2178 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002179#undef SetIntItem
2180#undef SetStrItem
2181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 if (PyErr_Occurred()) {
2183 Py_CLEAR(version_info);
2184 return NULL;
2185 }
2186 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002187}
2188
Brett Cannon3adc7b72012-07-09 14:22:12 -04002189/* sys.implementation values */
2190#define NAME "cpython"
2191const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002192#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2193#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002194#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002195const char *_PySys_ImplCacheTag = TAG;
2196#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002197#undef MAJOR
2198#undef MINOR
2199#undef TAG
2200
Barry Warsaw409da152012-06-03 16:18:47 -04002201static PyObject *
2202make_impl_info(PyObject *version_info)
2203{
2204 int res;
2205 PyObject *impl_info, *value, *ns;
2206
2207 impl_info = PyDict_New();
2208 if (impl_info == NULL)
2209 return NULL;
2210
2211 /* populate the dict */
2212
Brett Cannon3adc7b72012-07-09 14:22:12 -04002213 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002214 if (value == NULL)
2215 goto error;
2216 res = PyDict_SetItemString(impl_info, "name", value);
2217 Py_DECREF(value);
2218 if (res < 0)
2219 goto error;
2220
Brett Cannon3adc7b72012-07-09 14:22:12 -04002221 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002222 if (value == NULL)
2223 goto error;
2224 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2225 Py_DECREF(value);
2226 if (res < 0)
2227 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002228
2229 res = PyDict_SetItemString(impl_info, "version", version_info);
2230 if (res < 0)
2231 goto error;
2232
2233 value = PyLong_FromLong(PY_VERSION_HEX);
2234 if (value == NULL)
2235 goto error;
2236 res = PyDict_SetItemString(impl_info, "hexversion", value);
2237 Py_DECREF(value);
2238 if (res < 0)
2239 goto error;
2240
doko@ubuntu.com55532312016-06-14 08:55:19 +02002241#ifdef MULTIARCH
2242 value = PyUnicode_FromString(MULTIARCH);
2243 if (value == NULL)
2244 goto error;
2245 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2246 Py_DECREF(value);
2247 if (res < 0)
2248 goto error;
2249#endif
2250
Barry Warsaw409da152012-06-03 16:18:47 -04002251 /* dict ready */
2252
2253 ns = _PyNamespace_New(impl_info);
2254 Py_DECREF(impl_info);
2255 return ns;
2256
2257error:
2258 Py_CLEAR(impl_info);
2259 return NULL;
2260}
2261
Martin v. Löwis1a214512008-06-11 05:26:20 +00002262static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 PyModuleDef_HEAD_INIT,
2264 "sys",
2265 sys_doc,
2266 -1, /* multiple "initialization" just copies the module dict. */
2267 sys_methods,
2268 NULL,
2269 NULL,
2270 NULL,
2271 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002272};
2273
Eric Snow6b4be192017-05-22 21:36:03 -07002274/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002275#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002276 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002277 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002278 if (v == NULL) { \
2279 goto err_occurred; \
2280 } \
Victor Stinner58049602013-07-22 22:40:00 +02002281 res = PyDict_SetItemString(sysdict, key, v); \
2282 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002284 } \
2285 } while (0)
2286#define SET_SYS_FROM_STRING(key, value) \
2287 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002288 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289 if (v == NULL) { \
2290 goto err_occurred; \
2291 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002292 res = PyDict_SetItemString(sysdict, key, v); \
2293 Py_DECREF(v); \
2294 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002295 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002296 } \
2297 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002298
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002299
2300_PyInitError
2301_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002302{
2303 PyObject *m, *sysdict, *version_info;
2304 int res;
2305
Eric Snowd393c1b2017-09-14 12:18:12 -06002306 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002307 if (m == NULL) {
2308 return _Py_INIT_ERR("failed to create a module object");
2309 }
Eric Snow6b4be192017-05-22 21:36:03 -07002310 sysdict = PyModule_GetDict(m);
2311
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002312 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002313 Using shell redirection, you can redirect stdin to a directory,
2314 crashing the Python interpreter. Catch this common mistake here
2315 and output a useful error message. Note that under MS Windows,
2316 the shell already prevents that. */
2317#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002318 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002319 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002320 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002322 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2323 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 }
2325 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002326#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002327
Nick Coghland6009512014-11-20 21:39:37 +10002328 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002329
Victor Stinner8fea2522013-10-27 17:15:42 +01002330 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2331 PyDict_GetItemString(sysdict, "displayhook"));
2332 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2333 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002334 SET_SYS_FROM_STRING_BORROW(
2335 "__breakpointhook__",
2336 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002337 SET_SYS_FROM_STRING("version",
2338 PyUnicode_FromString(Py_GetVersion()));
2339 SET_SYS_FROM_STRING("hexversion",
2340 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002341 SET_SYS_FROM_STRING("_git",
2342 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2343 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002344 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 SET_SYS_FROM_STRING("api_version",
2346 PyLong_FromLong(PYTHON_API_VERSION));
2347 SET_SYS_FROM_STRING("copyright",
2348 PyUnicode_FromString(Py_GetCopyright()));
2349 SET_SYS_FROM_STRING("platform",
2350 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 SET_SYS_FROM_STRING("maxsize",
2352 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2353 SET_SYS_FROM_STRING("float_info",
2354 PyFloat_GetInfo());
2355 SET_SYS_FROM_STRING("int_info",
2356 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002357 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002358 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002359 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2360 goto type_init_failed;
2361 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002362 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002363 SET_SYS_FROM_STRING("hash_info",
2364 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002365 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002366 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002367 SET_SYS_FROM_STRING("builtin_module_names",
2368 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002369#if PY_BIG_ENDIAN
2370 SET_SYS_FROM_STRING("byteorder",
2371 PyUnicode_FromString("big"));
2372#else
2373 SET_SYS_FROM_STRING("byteorder",
2374 PyUnicode_FromString("little"));
2375#endif
Fred Drake099325e2000-08-14 15:47:03 +00002376
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002377#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002378 SET_SYS_FROM_STRING("dllhandle",
2379 PyLong_FromVoidPtr(PyWin_DLLhModule));
2380 SET_SYS_FROM_STRING("winver",
2381 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002382#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002383#ifdef ABIFLAGS
2384 SET_SYS_FROM_STRING("abiflags",
2385 PyUnicode_FromString(ABIFLAGS));
2386#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002387
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002389 if (VersionInfoType.tp_name == NULL) {
2390 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002391 &version_info_desc) < 0) {
2392 goto type_init_failed;
2393 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002394 }
Barry Warsaw409da152012-06-03 16:18:47 -04002395 version_info = make_version_info();
2396 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 /* prevent user from creating new instances */
2398 VersionInfoType.tp_init = NULL;
2399 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002400 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2401 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2402 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002403
Barry Warsaw409da152012-06-03 16:18:47 -04002404 /* implementation */
2405 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002408 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002409 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2410 goto type_init_failed;
2411 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002412 }
Eric Snow6b4be192017-05-22 21:36:03 -07002413 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002415
2416#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 /* getwindowsversion */
2418 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002419 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002420 &windows_version_desc) < 0) {
2421 goto type_init_failed;
2422 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 /* prevent user from creating new instances */
2424 WindowsVersionType.tp_init = NULL;
2425 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002426 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002427 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002428 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002429 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002430 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002431#endif
2432
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002434#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 SET_SYS_FROM_STRING("float_repr_style",
2436 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002437#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002438 SET_SYS_FROM_STRING("float_repr_style",
2439 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002440#endif
2441
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002442 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002443
Yury Selivanoveb636452016-09-08 22:01:51 -07002444 /* initialize asyncgen_hooks */
2445 if (AsyncGenHooksType.tp_name == NULL) {
2446 if (PyStructSequence_InitType2(
2447 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002448 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002449 }
2450 }
2451
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002452 if (PyErr_Occurred()) {
2453 goto err_occurred;
2454 }
2455
2456 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002457
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002458 return _Py_INIT_OK();
2459
2460type_init_failed:
2461 return _Py_INIT_ERR("failed to initialize a type");
2462
2463err_occurred:
2464 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002465}
2466
Eric Snow6b4be192017-05-22 21:36:03 -07002467#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002468
2469/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002470#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2471 do { \
2472 PyObject *v = (value); \
2473 if (v == NULL) \
2474 return -1; \
2475 res = PyDict_SetItemString(sysdict, key, v); \
2476 Py_DECREF(v); \
2477 if (res < 0) { \
2478 return res; \
2479 } \
2480 } while (0)
2481
2482int
Victor Stinnerfbca9082018-08-30 00:50:45 +02002483_PySys_EndInit(PyObject *sysdict, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002484{
Victor Stinnerfbca9082018-08-30 00:50:45 +02002485 const _PyCoreConfig *core_config = &interp->core_config;
2486 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002487 int res;
2488
Victor Stinner41264f12017-12-15 02:05:29 +01002489 /* _PyMainInterpreterConfig_Read() must set all these variables */
2490 assert(config->module_search_path != NULL);
2491 assert(config->executable != NULL);
2492 assert(config->prefix != NULL);
2493 assert(config->base_prefix != NULL);
2494 assert(config->exec_prefix != NULL);
2495 assert(config->base_exec_prefix != NULL);
2496
2497 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
2498 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2499 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2500 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2501 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2502 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2503
Carl Meyerb193fa92018-06-15 22:40:56 -06002504 if (config->pycache_prefix != NULL) {
2505 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2506 } else {
2507 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2508 }
2509
Victor Stinner41264f12017-12-15 02:05:29 +01002510 if (config->argv != NULL) {
2511 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2512 }
2513 if (config->warnoptions != NULL) {
2514 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
2515 }
2516 if (config->xoptions != NULL) {
2517 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
2518 }
2519
Eric Snow6b4be192017-05-22 21:36:03 -07002520 /* Set flags to their final values */
2521 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2522 /* prevent user from creating new instances */
2523 FlagsType.tp_init = NULL;
2524 FlagsType.tp_new = NULL;
2525 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2526 if (res < 0) {
2527 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2528 return res;
2529 }
2530 PyErr_Clear();
2531 }
2532
2533 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002534 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002535
Eric Snowdae02762017-09-14 00:35:58 -07002536 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002537 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002538
Eric Snowdae02762017-09-14 00:35:58 -07002539 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002540 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002541
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002542 /* Transfer any sys.warnoptions and sys._xoptions set directly
2543 * by an embedding application from the linked list to the module. */
2544 if (_PySys_ReadPreInitOptions() != 0)
2545 return -1;
2546
Eric Snow6b4be192017-05-22 21:36:03 -07002547 if (PyErr_Occurred())
2548 return -1;
2549 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002550
2551err_occurred:
2552 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002553}
2554
Victor Stinner41264f12017-12-15 02:05:29 +01002555#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002556#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002557
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002558static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002559makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002561 int i, n;
2562 const wchar_t *p;
2563 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002565 n = 1;
2566 p = path;
2567 while ((p = wcschr(p, delim)) != NULL) {
2568 n++;
2569 p++;
2570 }
2571 v = PyList_New(n);
2572 if (v == NULL)
2573 return NULL;
2574 for (i = 0; ; i++) {
2575 p = wcschr(path, delim);
2576 if (p == NULL)
2577 p = path + wcslen(path); /* End of string */
2578 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2579 if (w == NULL) {
2580 Py_DECREF(v);
2581 return NULL;
2582 }
2583 PyList_SetItem(v, i, w);
2584 if (*p == '\0')
2585 break;
2586 path = p+1;
2587 }
2588 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002589}
2590
2591void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002592PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002593{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002594 PyObject *v;
2595 if ((v = makepathobject(path, DELIM)) == NULL)
2596 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002597 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002598 Py_FatalError("can't assign sys.path");
2599 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002600}
2601
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002602static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002603makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002604{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 PyObject *av;
2606 if (argc <= 0 || argv == NULL) {
2607 /* Ensure at least one (empty) argument is seen */
2608 static wchar_t *empty_argv[1] = {L""};
2609 argv = empty_argv;
2610 argc = 1;
2611 }
2612 av = PyList_New(argc);
2613 if (av != NULL) {
2614 int i;
2615 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002616 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 if (v == NULL) {
2618 Py_DECREF(av);
2619 av = NULL;
2620 break;
2621 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002622 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002623 }
2624 }
2625 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002626}
2627
Victor Stinner11a247d2017-12-13 21:05:57 +01002628void
2629PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002630{
2631 PyObject *av = makeargvobject(argc, argv);
2632 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002633 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002634 }
2635 if (PySys_SetObject("argv", av) != 0) {
2636 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002637 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002638 }
2639 Py_DECREF(av);
2640
2641 if (updatepath) {
2642 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2643 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002644 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2645 if (argv0 == NULL) {
2646 Py_FatalError("can't compute path0 from argv");
2647 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002648
Victor Stinner11a247d2017-12-13 21:05:57 +01002649 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2650 if (sys_path != NULL) {
2651 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2652 Py_DECREF(argv0);
2653 Py_FatalError("can't prepend path0 to sys.path");
2654 }
2655 }
2656 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002657 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002658}
Guido van Rossuma890e681998-05-12 14:59:24 +00002659
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002660void
2661PySys_SetArgv(int argc, wchar_t **argv)
2662{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002663 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002664}
2665
Victor Stinner14284c22010-04-23 12:02:30 +00002666/* Reimplementation of PyFile_WriteString() no calling indirectly
2667 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2668
2669static int
Victor Stinner79766632010-08-16 17:36:42 +00002670sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002671{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002672 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002674
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002675 if (file == NULL)
2676 return -1;
2677
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002678 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 if (writer == NULL)
2680 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002681
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002682 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002683 if (result == NULL) {
2684 goto error;
2685 } else {
2686 err = 0;
2687 goto finally;
2688 }
Victor Stinner14284c22010-04-23 12:02:30 +00002689
2690error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002691 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002692finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002694 Py_XDECREF(result);
2695 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002696}
2697
Victor Stinner79766632010-08-16 17:36:42 +00002698static int
2699sys_pyfile_write(const char *text, PyObject *file)
2700{
2701 PyObject *unicode = NULL;
2702 int err;
2703
2704 if (file == NULL)
2705 return -1;
2706
2707 unicode = PyUnicode_FromString(text);
2708 if (unicode == NULL)
2709 return -1;
2710
2711 err = sys_pyfile_write_unicode(unicode, file);
2712 Py_DECREF(unicode);
2713 return err;
2714}
Guido van Rossuma890e681998-05-12 14:59:24 +00002715
2716/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2717 Adapted from code submitted by Just van Rossum.
2718
2719 PySys_WriteStdout(format, ...)
2720 PySys_WriteStderr(format, ...)
2721
2722 The first function writes to sys.stdout; the second to sys.stderr. When
2723 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002724 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002725
Victor Stinner14284c22010-04-23 12:02:30 +00002726 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002727 signal handlers: they may raise a new exception whereas sys_write()
2728 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002729
Guido van Rossuma890e681998-05-12 14:59:24 +00002730 Both take a printf-style format string as their first argument followed
2731 by a variable length argument list determined by the format string.
2732
2733 *** WARNING ***
2734
2735 The format should limit the total size of the formatted output string to
2736 1000 bytes. In particular, this means that no unrestricted "%s" formats
2737 should occur; these should be limited using "%.<N>s where <N> is a
2738 decimal number calculated so that <N> plus the maximum size of other
2739 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2740 which can print hundreds of digits for very large numbers.
2741
2742 */
2743
2744static void
Victor Stinner09054372013-11-06 22:41:44 +01002745sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002747 PyObject *file;
2748 PyObject *error_type, *error_value, *error_traceback;
2749 char buffer[1001];
2750 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002752 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002753 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2755 if (sys_pyfile_write(buffer, file) != 0) {
2756 PyErr_Clear();
2757 fputs(buffer, fp);
2758 }
2759 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2760 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002761 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002763 }
2764 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002765}
2766
2767void
Guido van Rossuma890e681998-05-12 14:59:24 +00002768PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002769{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002773 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002775}
2776
2777void
Guido van Rossuma890e681998-05-12 14:59:24 +00002778PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002782 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002783 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002784 va_end(va);
2785}
2786
2787static void
Victor Stinner09054372013-11-06 22:41:44 +01002788sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002789{
2790 PyObject *file, *message;
2791 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002792 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002793
2794 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002795 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002796 message = PyUnicode_FromFormatV(format, va);
2797 if (message != NULL) {
2798 if (sys_pyfile_write_unicode(message, file) != 0) {
2799 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002800 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002801 if (utf8 != NULL)
2802 fputs(utf8, fp);
2803 }
2804 Py_DECREF(message);
2805 }
2806 PyErr_Restore(error_type, error_value, error_traceback);
2807}
2808
2809void
2810PySys_FormatStdout(const char *format, ...)
2811{
2812 va_list va;
2813
2814 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002815 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002816 va_end(va);
2817}
2818
2819void
2820PySys_FormatStderr(const char *format, ...)
2821{
2822 va_list va;
2823
2824 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002825 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002826 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002827}