blob: 869834b92432599b541f99fa20167903b021d6f4 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010020#include "pycore_pylifecycle.h"
21#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010022#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010023#include "pycore_pystate.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020024#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000025
Guido van Rossume2437a11992-03-23 18:20:18 +000026#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020027#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000028
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#ifdef MS_WINDOWS
30#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000031#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000032#endif /* MS_WINDOWS */
33
Guido van Rossum9b38a141996-09-11 23:12:24 +000034#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000035extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000036/* A string loaded from the DLL at startup: */
37extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000038#endif
39
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080040/*[clinic input]
41module sys
42[clinic start generated code]*/
43/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
44
45#include "clinic/sysmodule.c.h"
46
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(_);
48_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070049_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(buffer);
51_Py_IDENTIFIER(builtins);
52_Py_IDENTIFIER(encoding);
53_Py_IDENTIFIER(path);
54_Py_IDENTIFIER(stdout);
55_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070056_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010057_Py_IDENTIFIER(write);
58
Guido van Rossum65bf9f21997-04-29 18:33:38 +000059PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010060_PySys_GetObjectId(_Py_Identifier *key)
61{
Victor Stinnercaba55b2018-08-03 15:33:52 +020062 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
63 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010064 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020065 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010066 return _PyDict_GetItemId(sd, key);
67}
68
69PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000070PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071{
Victor Stinnercaba55b2018-08-03 15:33:52 +020072 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
73 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077}
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079int
Victor Stinnerd67bd452013-11-06 22:36:40 +010080_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
81{
Victor Stinnercaba55b2018-08-03 15:33:52 +020082 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010083 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020084 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010085 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020086 }
87 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010090 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020091 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010092 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020093 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010094}
95
96int
Neal Norwitzf3081322007-08-25 00:32:45 +000097PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Victor Stinnercaba55b2018-08-03 15:33:52 +020099 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200101 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200103 }
104 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200108 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200110 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111}
112
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400113static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200114sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400115{
116 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300117 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400118
119 if (envar == NULL || strlen(envar) == 0) {
120 envar = "pdb.set_trace";
121 }
122 else if (!strcmp(envar, "0")) {
123 /* The breakpoint is explicitly no-op'd. */
124 Py_RETURN_NONE;
125 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300126 /* According to POSIX the string returned by getenv() might be invalidated
127 * or the string content might be overwritten by a subsequent call to
128 * getenv(). Since importing a module can performs the getenv() calls,
129 * we need to save a copy of envar. */
130 envar = _PyMem_RawStrdup(envar);
131 if (envar == NULL) {
132 PyErr_NoMemory();
133 return NULL;
134 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200135 const char *last_dot = strrchr(envar, '.');
136 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400137 PyObject *modulepath = NULL;
138
139 if (last_dot == NULL) {
140 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
141 modulepath = PyUnicode_FromString("builtins");
142 attrname = envar;
143 }
144 else {
145 /* Split on the last dot; */
146 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
147 attrname = last_dot + 1;
148 }
149 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300150 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400151 return NULL;
152 }
153
Anthony Sottiledce345c2018-11-01 10:25:05 -0700154 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400155 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400156
157 if (module == NULL) {
158 goto error;
159 }
160
161 PyObject *hook = PyObject_GetAttrString(module, attrname);
162 Py_DECREF(module);
163
164 if (hook == NULL) {
165 goto error;
166 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300167 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400168 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
169 Py_DECREF(hook);
170 return retval;
171
172 error:
Serhiy Storchaka6fe9c442019-01-14 12:58:37 +0200173 if (!PyErr_ExceptionMatches(PyExc_ImportError)
174 && !PyErr_ExceptionMatches(PyExc_AttributeError))
175 {
176 PyMem_RawFree(envar);
177 return NULL;
178 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400179 /* 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
Tal Einatede0b6f2018-12-31 17:12:08 +0200261/*[clinic input]
262sys.displayhook
263
264 object as o: object
265 /
266
267Print an object to sys.stdout and also save it in builtins._
268[clinic start generated code]*/
269
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000270static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200271sys_displayhook(PyObject *module, PyObject *o)
272/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100275 PyObject *builtins;
276 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000277 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000278
Eric Snow3f9eee62017-09-15 16:35:20 -0600279 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (builtins == NULL) {
281 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
282 return NULL;
283 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600284 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000285
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 /* Print value except if None */
287 /* After printing, also assign to '_' */
288 /* Before, set '_' to None to avoid recursion */
289 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200290 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200292 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100294 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000295 if (outf == NULL || outf == Py_None) {
296 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
297 return NULL;
298 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000299 if (PyFile_WriteObject(o, outf, 0) != 0) {
300 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
301 /* repr(o) is not encodable to sys.stdout.encoding with
302 * sys.stdout.errors error handler (which is probably 'strict') */
303 PyErr_Clear();
304 err = sys_displayhook_unencodable(outf, o);
305 if (err)
306 return NULL;
307 }
308 else {
309 return NULL;
310 }
311 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100312 if (newline == NULL) {
313 newline = PyUnicode_FromString("\n");
314 if (newline == NULL)
315 return NULL;
316 }
317 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200319 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200321 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000322}
323
Tal Einatede0b6f2018-12-31 17:12:08 +0200324
325/*[clinic input]
326sys.excepthook
327
328 exctype: object
329 value: object
330 traceback: object
331 /
332
333Handle an exception by displaying it with a traceback on sys.stderr.
334[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000335
336static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200337sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
338 PyObject *traceback)
339/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000340{
Tal Einatede0b6f2018-12-31 17:12:08 +0200341 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200342 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000343}
344
Tal Einatede0b6f2018-12-31 17:12:08 +0200345
346/*[clinic input]
347sys.exc_info
348
349Return current exception information: (type, value, traceback).
350
351Return information about the most recent exception caught by an except
352clause in the current stack frame or in an older stack frame.
353[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000354
355static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200356sys_exc_info_impl(PyObject *module)
357/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000358{
Victor Stinner50b48572018-11-01 01:51:40 +0100359 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 return Py_BuildValue(
361 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100362 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
363 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
364 err_info->exc_traceback != NULL ?
365 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000366}
367
Tal Einatede0b6f2018-12-31 17:12:08 +0200368
369/*[clinic input]
370sys.exit
371
372 status: object = NULL
373 /
374
375Exit the interpreter by raising SystemExit(status).
376
377If the status is omitted or None, it defaults to zero (i.e., success).
378If the status is an integer, it will be used as the system exit status.
379If it is another kind of object, it will be printed and the system
380exit status will be one (i.e., failure).
381[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000382
383static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200384sys_exit_impl(PyObject *module, PyObject *status)
385/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000386{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000387 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200388 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000390}
391
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000392
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000393
Tal Einatede0b6f2018-12-31 17:12:08 +0200394/*[clinic input]
395sys.getdefaultencoding
396
397Return the current default encoding used by the Unicode implementation.
398[clinic start generated code]*/
399
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000400static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200401sys_getdefaultencoding_impl(PyObject *module)
402/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000405}
406
Tal Einatede0b6f2018-12-31 17:12:08 +0200407/*[clinic input]
408sys.getfilesystemencoding
409
410Return the encoding used to convert Unicode filenames to OS filenames.
411[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000412
413static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200414sys_getfilesystemencoding_impl(PyObject *module)
415/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000416{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200417 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
418 const _PyCoreConfig *config = &interp->core_config;
419 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000420}
421
Tal Einatede0b6f2018-12-31 17:12:08 +0200422/*[clinic input]
423sys.getfilesystemencodeerrors
424
425Return the error mode used Unicode to OS filename conversion.
426[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000427
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000428static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200429sys_getfilesystemencodeerrors_impl(PyObject *module)
430/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700431{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200432 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
433 const _PyCoreConfig *config = &interp->core_config;
434 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700435}
436
Tal Einatede0b6f2018-12-31 17:12:08 +0200437/*[clinic input]
438sys.intern
439
440 string as s: unicode
441 /
442
443``Intern'' the given string.
444
445This enters the string in the (global) table of interned strings whose
446purpose is to speed up dictionary lookups. Return the string itself or
447the previously interned string object with the same value.
448[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700449
450static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200451sys_intern_impl(PyObject *module, PyObject *s)
452/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000453{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000454 if (PyUnicode_CheckExact(s)) {
455 Py_INCREF(s);
456 PyUnicode_InternInPlace(&s);
457 return s;
458 }
459 else {
460 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200461 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return NULL;
463 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000464}
465
Georg Brandl66a796e2006-12-19 20:50:34 +0000466
Fred Drake5755ce62001-06-27 19:19:46 +0000467/*
468 * Cached interned string objects used for calling the profile and
469 * trace functions. Initialized by trace_init().
470 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000471static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000472
473static int
474trace_init(void)
475{
Nick Coghlan5a851672017-09-08 10:14:16 +1000476 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200477 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000478 "c_call", "c_exception", "c_return",
479 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200480 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 PyObject *name;
482 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000483 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000484 if (whatstrings[i] == NULL) {
485 name = PyUnicode_InternFromString(whatnames[i]);
486 if (name == NULL)
487 return -1;
488 whatstrings[i] = name;
489 }
490 }
491 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000492}
493
494
495static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100496call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000499 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200500 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000501
Victor Stinner78da82b2016-08-20 01:22:57 +0200502 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200504 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100505
Victor Stinner78da82b2016-08-20 01:22:57 +0200506 stack[0] = (PyObject *)frame;
507 stack[1] = whatstrings[what];
508 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200511 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000512
Victor Stinner78da82b2016-08-20 01:22:57 +0200513 PyFrame_LocalsToFast(frame, 1);
514 if (result == NULL) {
515 PyTraceBack_Here(frame);
516 }
517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000519}
520
521static int
522profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000524{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000527 if (arg == NULL)
528 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100529 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 if (result == NULL) {
531 PyEval_SetProfile(NULL, NULL);
532 return -1;
533 }
534 Py_DECREF(result);
535 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000536}
537
538static int
539trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 PyObject *callback;
543 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000544
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 if (what == PyTrace_CALL)
546 callback = self;
547 else
548 callback = frame->f_trace;
549 if (callback == NULL)
550 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100551 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (result == NULL) {
553 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200554 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 return -1;
556 }
557 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300558 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 }
560 else {
561 Py_DECREF(result);
562 }
563 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000564}
Fred Draked0838392001-06-16 21:02:31 +0000565
Fred Drake8b4d01d2000-05-09 19:57:01 +0000566static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000567sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 if (trace_init() == -1)
570 return NULL;
571 if (args == Py_None)
572 PyEval_SetTrace(NULL, NULL);
573 else
574 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200575 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000576}
577
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000578PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000579"settrace(function)\n\
580\n\
581Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000582function call. See the debugger chapter in the library manual."
583);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000584
Tal Einatede0b6f2018-12-31 17:12:08 +0200585/*[clinic input]
586sys.gettrace
587
588Return the global debug tracing function set with sys.settrace.
589
590See the debugger chapter in the library manual.
591[clinic start generated code]*/
592
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000593static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200594sys_gettrace_impl(PyObject *module)
595/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000596{
Victor Stinner50b48572018-11-01 01:51:40 +0100597 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000598 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000600 if (temp == NULL)
601 temp = Py_None;
602 Py_INCREF(temp);
603 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000604}
605
Christian Heimes9bd667a2008-01-20 15:14:11 +0000606static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000607sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 if (trace_init() == -1)
610 return NULL;
611 if (args == Py_None)
612 PyEval_SetProfile(NULL, NULL);
613 else
614 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200615 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000616}
617
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000618PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000619"setprofile(function)\n\
620\n\
621Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000622and return. See the profiler chapter in the library manual."
623);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000624
Tal Einatede0b6f2018-12-31 17:12:08 +0200625/*[clinic input]
626sys.getprofile
627
628Return the profiling function set with sys.setprofile.
629
630See the profiler chapter in the library manual.
631[clinic start generated code]*/
632
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000633static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200634sys_getprofile_impl(PyObject *module)
635/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000636{
Victor Stinner50b48572018-11-01 01:51:40 +0100637 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000638 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if (temp == NULL)
641 temp = Py_None;
642 Py_INCREF(temp);
643 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000644}
645
Tal Einatede0b6f2018-12-31 17:12:08 +0200646/*[clinic input]
647sys.setcheckinterval
648
649 n: int
650 /
651
652Set the async event check interval to n instructions.
653
654This tells the Python interpreter to check for asynchronous events
655every n instructions.
656
657This also affects how often thread switches occur.
658[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000659
660static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200661sys_setcheckinterval_impl(PyObject *module, int n)
662/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000663{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 if (PyErr_WarnEx(PyExc_DeprecationWarning,
665 "sys.getcheckinterval() and sys.setcheckinterval() "
666 "are deprecated. Use sys.setswitchinterval() "
667 "instead.", 1) < 0)
668 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200669
Victor Stinnercaba55b2018-08-03 15:33:52 +0200670 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +0200671 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200672 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000673}
674
Tal Einatede0b6f2018-12-31 17:12:08 +0200675/*[clinic input]
676sys.getcheckinterval
677
678Return the current check interval; see sys.setcheckinterval().
679[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000680
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000681static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200682sys_getcheckinterval_impl(PyObject *module)
683/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000685 if (PyErr_WarnEx(PyExc_DeprecationWarning,
686 "sys.getcheckinterval() and sys.setcheckinterval() "
687 "are deprecated. Use sys.getswitchinterval() "
688 "instead.", 1) < 0)
689 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200690 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600691 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000692}
693
Tal Einatede0b6f2018-12-31 17:12:08 +0200694/*[clinic input]
695sys.setswitchinterval
696
697 interval: double
698 /
699
700Set the ideal thread switching delay inside the Python interpreter.
701
702The actual frequency of switching threads can be lower if the
703interpreter executes long sequences of uninterruptible code
704(this is implementation-specific and workload-dependent).
705
706The parameter must represent the desired switching delay in seconds
707A typical value is 0.005 (5 milliseconds).
708[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000709
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000710static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200711sys_setswitchinterval_impl(PyObject *module, double interval)
712/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000713{
Tal Einatede0b6f2018-12-31 17:12:08 +0200714 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 PyErr_SetString(PyExc_ValueError,
716 "switch interval must be strictly positive");
717 return NULL;
718 }
Tal Einatede0b6f2018-12-31 17:12:08 +0200719 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200720 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000721}
722
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000723
Tal Einatede0b6f2018-12-31 17:12:08 +0200724/*[clinic input]
725sys.getswitchinterval -> double
726
727Return the current thread switch interval; see sys.setswitchinterval().
728[clinic start generated code]*/
729
730static double
731sys_getswitchinterval_impl(PyObject *module)
732/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000733{
Tal Einatede0b6f2018-12-31 17:12:08 +0200734 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000735}
736
Tal Einatede0b6f2018-12-31 17:12:08 +0200737/*[clinic input]
738sys.setrecursionlimit
739
740 limit as new_limit: int
741 /
742
743Set the maximum depth of the Python interpreter stack to n.
744
745This limit prevents infinite recursion from causing an overflow of the C
746stack and crashing Python. The highest possible limit is platform-
747dependent.
748[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000749
Tim Peterse5e065b2003-07-06 18:36:54 +0000750static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200751sys_setrecursionlimit_impl(PyObject *module, int new_limit)
752/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000753{
Tal Einatede0b6f2018-12-31 17:12:08 +0200754 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +0200755 PyThreadState *tstate;
756
Victor Stinner50856d52015-10-13 00:11:21 +0200757 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000758 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200759 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 return NULL;
761 }
Victor Stinner50856d52015-10-13 00:11:21 +0200762
763 /* Issue #25274: When the recursion depth hits the recursion limit in
764 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
765 set to 1 and a RecursionError is raised. The overflowed flag is reset
766 to 0 when the recursion depth goes below the low-water mark: see
767 Py_LeaveRecursiveCall().
768
769 Reject too low new limit if the current recursion depth is higher than
770 the new low-water mark. Otherwise it may not be possible anymore to
771 reset the overflowed flag to 0. */
772 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100773 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200774 if (tstate->recursion_depth >= mark) {
775 PyErr_Format(PyExc_RecursionError,
776 "cannot set the recursion limit to %i at "
777 "the recursion depth %i: the limit is too low",
778 new_limit, tstate->recursion_depth);
779 return NULL;
780 }
781
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000782 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200783 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000784}
785
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800786/*[clinic input]
787sys.set_coroutine_origin_tracking_depth
788
789 depth: int
790
791Enable or disable origin tracking for coroutine objects in this thread.
792
Tal Einatede0b6f2018-12-31 17:12:08 +0200793Coroutine objects will track 'depth' frames of traceback information
794about where they came from, available in their cr_origin attribute.
795
796Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800797[clinic start generated code]*/
798
799static PyObject *
800sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +0200801/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800802{
803 if (depth < 0) {
804 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
805 return NULL;
806 }
807 _PyEval_SetCoroutineOriginTrackingDepth(depth);
808 Py_RETURN_NONE;
809}
810
811/*[clinic input]
812sys.get_coroutine_origin_tracking_depth -> int
813
814Check status of origin tracking for coroutine objects in this thread.
815[clinic start generated code]*/
816
817static int
818sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
819/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
820{
821 return _PyEval_GetCoroutineOriginTrackingDepth();
822}
823
Tal Einatede0b6f2018-12-31 17:12:08 +0200824/*[clinic input]
825sys.set_coroutine_wrapper
826
827 wrapper: object
828 /
829
830Set a wrapper for coroutine objects.
831[clinic start generated code]*/
832
Yury Selivanov75445082015-05-11 22:57:16 -0400833static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200834sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
835/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400836{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800837 if (PyErr_WarnEx(PyExc_DeprecationWarning,
838 "set_coroutine_wrapper is deprecated", 1) < 0) {
839 return NULL;
840 }
841
Yury Selivanov75445082015-05-11 22:57:16 -0400842 if (wrapper != Py_None) {
843 if (!PyCallable_Check(wrapper)) {
844 PyErr_Format(PyExc_TypeError,
845 "callable expected, got %.50s",
846 Py_TYPE(wrapper)->tp_name);
847 return NULL;
848 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400849 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400850 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400851 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400852 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400853 }
Yury Selivanov75445082015-05-11 22:57:16 -0400854 Py_RETURN_NONE;
855}
856
Tal Einatede0b6f2018-12-31 17:12:08 +0200857/*[clinic input]
858sys.get_coroutine_wrapper
859
860Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
861[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400862
863static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200864sys_get_coroutine_wrapper_impl(PyObject *module)
865/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400866{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800867 if (PyErr_WarnEx(PyExc_DeprecationWarning,
868 "get_coroutine_wrapper is deprecated", 1) < 0) {
869 return NULL;
870 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400871 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400872 if (wrapper == NULL) {
873 wrapper = Py_None;
874 }
875 Py_INCREF(wrapper);
876 return wrapper;
877}
878
Yury Selivanov75445082015-05-11 22:57:16 -0400879
Yury Selivanoveb636452016-09-08 22:01:51 -0700880static PyTypeObject AsyncGenHooksType;
881
882PyDoc_STRVAR(asyncgen_hooks_doc,
883"asyncgen_hooks\n\
884\n\
885A struct sequence providing information about asynhronous\n\
886generators hooks. The attributes are read only.");
887
888static PyStructSequence_Field asyncgen_hooks_fields[] = {
889 {"firstiter", "Hook to intercept first iteration"},
890 {"finalizer", "Hook to intercept finalization"},
891 {0}
892};
893
894static PyStructSequence_Desc asyncgen_hooks_desc = {
895 "asyncgen_hooks", /* name */
896 asyncgen_hooks_doc, /* doc */
897 asyncgen_hooks_fields , /* fields */
898 2
899};
900
Yury Selivanoveb636452016-09-08 22:01:51 -0700901static PyObject *
902sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
903{
904 static char *keywords[] = {"firstiter", "finalizer", NULL};
905 PyObject *firstiter = NULL;
906 PyObject *finalizer = NULL;
907
908 if (!PyArg_ParseTupleAndKeywords(
909 args, kw, "|OO", keywords,
910 &firstiter, &finalizer)) {
911 return NULL;
912 }
913
914 if (finalizer && finalizer != Py_None) {
915 if (!PyCallable_Check(finalizer)) {
916 PyErr_Format(PyExc_TypeError,
917 "callable finalizer expected, got %.50s",
918 Py_TYPE(finalizer)->tp_name);
919 return NULL;
920 }
921 _PyEval_SetAsyncGenFinalizer(finalizer);
922 }
923 else if (finalizer == Py_None) {
924 _PyEval_SetAsyncGenFinalizer(NULL);
925 }
926
927 if (firstiter && firstiter != Py_None) {
928 if (!PyCallable_Check(firstiter)) {
929 PyErr_Format(PyExc_TypeError,
930 "callable firstiter expected, got %.50s",
931 Py_TYPE(firstiter)->tp_name);
932 return NULL;
933 }
934 _PyEval_SetAsyncGenFirstiter(firstiter);
935 }
936 else if (firstiter == Py_None) {
937 _PyEval_SetAsyncGenFirstiter(NULL);
938 }
939
940 Py_RETURN_NONE;
941}
942
943PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +0200944"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -0700945\n\
946Set a finalizer for async generators objects."
947);
948
Tal Einatede0b6f2018-12-31 17:12:08 +0200949/*[clinic input]
950sys.get_asyncgen_hooks
951
952Return the installed asynchronous generators hooks.
953
954This returns a namedtuple of the form (firstiter, finalizer).
955[clinic start generated code]*/
956
Yury Selivanoveb636452016-09-08 22:01:51 -0700957static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200958sys_get_asyncgen_hooks_impl(PyObject *module)
959/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -0700960{
961 PyObject *res;
962 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
963 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
964
965 res = PyStructSequence_New(&AsyncGenHooksType);
966 if (res == NULL) {
967 return NULL;
968 }
969
970 if (firstiter == NULL) {
971 firstiter = Py_None;
972 }
973
974 if (finalizer == NULL) {
975 finalizer = Py_None;
976 }
977
978 Py_INCREF(firstiter);
979 PyStructSequence_SET_ITEM(res, 0, firstiter);
980
981 Py_INCREF(finalizer);
982 PyStructSequence_SET_ITEM(res, 1, finalizer);
983
984 return res;
985}
986
Yury Selivanoveb636452016-09-08 22:01:51 -0700987
Mark Dickinsondc787d22010-05-23 13:33:13 +0000988static PyTypeObject Hash_InfoType;
989
990PyDoc_STRVAR(hash_info_doc,
991"hash_info\n\
992\n\
993A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100994hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000995
996static PyStructSequence_Field hash_info_fields[] = {
997 {"width", "width of the type used for hashing, in bits"},
998 {"modulus", "prime number giving the modulus on which the hash "
999 "function is based"},
1000 {"inf", "value to be used for hash of a positive infinity"},
1001 {"nan", "value to be used for hash of a nan"},
1002 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001003 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1004 "memoryviews"},
1005 {"hash_bits", "internal output size of hash algorithm"},
1006 {"seed_bits", "seed size of hash algorithm"},
1007 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001008 {NULL, NULL}
1009};
1010
1011static PyStructSequence_Desc hash_info_desc = {
1012 "sys.hash_info",
1013 hash_info_doc,
1014 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001015 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001016};
1017
Matthias Klosed885e952010-07-06 10:53:30 +00001018static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001019get_hash_info(void)
1020{
1021 PyObject *hash_info;
1022 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001023 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001024 hash_info = PyStructSequence_New(&Hash_InfoType);
1025 if (hash_info == NULL)
1026 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001027 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001028 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001029 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001030 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001031 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001032 PyStructSequence_SET_ITEM(hash_info, field++,
1033 PyLong_FromLong(_PyHASH_INF));
1034 PyStructSequence_SET_ITEM(hash_info, field++,
1035 PyLong_FromLong(_PyHASH_NAN));
1036 PyStructSequence_SET_ITEM(hash_info, field++,
1037 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001038 PyStructSequence_SET_ITEM(hash_info, field++,
1039 PyUnicode_FromString(hashfunc->name));
1040 PyStructSequence_SET_ITEM(hash_info, field++,
1041 PyLong_FromLong(hashfunc->hash_bits));
1042 PyStructSequence_SET_ITEM(hash_info, field++,
1043 PyLong_FromLong(hashfunc->seed_bits));
1044 PyStructSequence_SET_ITEM(hash_info, field++,
1045 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001046 if (PyErr_Occurred()) {
1047 Py_CLEAR(hash_info);
1048 return NULL;
1049 }
1050 return hash_info;
1051}
Tal Einatede0b6f2018-12-31 17:12:08 +02001052/*[clinic input]
1053sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001054
Tal Einatede0b6f2018-12-31 17:12:08 +02001055Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001056
Tal Einatede0b6f2018-12-31 17:12:08 +02001057The recursion limit is the maximum depth of the Python interpreter
1058stack. This limit prevents infinite recursion from causing an overflow
1059of the C stack and crashing Python.
1060[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001061
1062static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001063sys_getrecursionlimit_impl(PyObject *module)
1064/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001065{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001067}
1068
Mark Hammond8696ebc2002-10-08 02:44:31 +00001069#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001070
Eric Smithf7bb5782010-01-27 00:44:57 +00001071static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1072
1073static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 {"major", "Major version number"},
1075 {"minor", "Minor version number"},
1076 {"build", "Build number"},
1077 {"platform", "Operating system platform"},
1078 {"service_pack", "Latest Service Pack installed on the system"},
1079 {"service_pack_major", "Service Pack major version number"},
1080 {"service_pack_minor", "Service Pack minor version number"},
1081 {"suite_mask", "Bit mask identifying available product suites"},
1082 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001083 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001085};
1086
1087static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001088 "sys.getwindowsversion", /* name */
1089 sys_getwindowsversion__doc__, /* doc */
1090 windows_version_fields, /* fields */
1091 5 /* For backward compatibility,
1092 only the first 5 items are accessible
1093 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001094};
1095
Steve Dower3e96f322015-03-02 08:01:10 -08001096/* Disable deprecation warnings about GetVersionEx as the result is
1097 being passed straight through to the caller, who is responsible for
1098 using it correctly. */
1099#pragma warning(push)
1100#pragma warning(disable:4996)
1101
Tal Einatede0b6f2018-12-31 17:12:08 +02001102/*[clinic input]
1103sys.getwindowsversion
1104
1105Return info about the running version of Windows as a named tuple.
1106
1107The members are named: major, minor, build, platform, service_pack,
1108service_pack_major, service_pack_minor, suite_mask, product_type and
1109platform_version. For backward compatibility, only the first 5 items
1110are available by indexing. All elements are numbers, except
1111service_pack and platform_type which are strings, and platform_version
1112which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1113workstation, 2 for a domain controller, 3 for a server.
1114Platform_version is a 3-tuple containing a version number that is
1115intended for identifying the OS rather than feature detection.
1116[clinic start generated code]*/
1117
Mark Hammond8696ebc2002-10-08 02:44:31 +00001118static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001119sys_getwindowsversion_impl(PyObject *module)
1120/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001121{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001122 PyObject *version;
1123 int pos = 0;
1124 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001125 DWORD realMajor, realMinor, realBuild;
1126 HANDLE hKernel32;
1127 wchar_t kernel32_path[MAX_PATH];
1128 LPVOID verblock;
1129 DWORD verblock_size;
1130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001131 ver.dwOSVersionInfoSize = sizeof(ver);
1132 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1133 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001134
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 version = PyStructSequence_New(&WindowsVersionType);
1136 if (version == NULL)
1137 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1140 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1141 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1142 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1143 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1144 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1145 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1146 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1147 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001148
Steve Dower74f4af72016-09-17 17:27:48 -07001149 realMajor = ver.dwMajorVersion;
1150 realMinor = ver.dwMinorVersion;
1151 realBuild = ver.dwBuildNumber;
1152
1153 // GetVersion will lie if we are running in a compatibility mode.
1154 // We need to read the version info from a system file resource
1155 // to accurately identify the OS version. If we fail for any reason,
1156 // just return whatever GetVersion said.
1157 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1158 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1159 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1160 (verblock = PyMem_RawMalloc(verblock_size))) {
1161 VS_FIXEDFILEINFO *ffi;
1162 UINT ffi_len;
1163
1164 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1165 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1166 realMajor = HIWORD(ffi->dwProductVersionMS);
1167 realMinor = LOWORD(ffi->dwProductVersionMS);
1168 realBuild = HIWORD(ffi->dwProductVersionLS);
1169 }
1170 PyMem_RawFree(verblock);
1171 }
Segev Finer48fb7662017-06-04 20:52:27 +03001172 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1173 realMajor,
1174 realMinor,
1175 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001176 ));
1177
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001178 if (PyErr_Occurred()) {
1179 Py_DECREF(version);
1180 return NULL;
1181 }
Steve Dower74f4af72016-09-17 17:27:48 -07001182
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001183 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001184}
1185
Steve Dower3e96f322015-03-02 08:01:10 -08001186#pragma warning(pop)
1187
Tal Einatede0b6f2018-12-31 17:12:08 +02001188/*[clinic input]
1189sys._enablelegacywindowsfsencoding
1190
1191Changes the default filesystem encoding to mbcs:replace.
1192
1193This is done for consistency with earlier versions of Python. See PEP
1194529 for more information.
1195
1196This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1197environment variable before launching Python.
1198[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001199
1200static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001201sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1202/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001203{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001204 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1205 _PyCoreConfig *config = &interp->core_config;
1206
1207 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1208 char *encoding = _PyMem_RawStrdup("mbcs");
1209 char *errors = _PyMem_RawStrdup("replace");
1210 if (encoding == NULL || errors == NULL) {
1211 PyMem_Free(encoding);
1212 PyMem_Free(errors);
1213 PyErr_NoMemory();
1214 return NULL;
1215 }
1216
1217 PyMem_RawFree(config->filesystem_encoding);
1218 config->filesystem_encoding = encoding;
1219 PyMem_RawFree(config->filesystem_errors);
1220 config->filesystem_errors = errors;
1221
1222 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1223 config->filesystem_errors) < 0) {
1224 PyErr_NoMemory();
1225 return NULL;
1226 }
1227
Steve Dowercc16be82016-09-08 10:35:16 -07001228 Py_RETURN_NONE;
1229}
1230
Mark Hammond8696ebc2002-10-08 02:44:31 +00001231#endif /* MS_WINDOWS */
1232
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001233#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001234
1235/*[clinic input]
1236sys.setdlopenflags
1237
1238 flags as new_val: int
1239 /
1240
1241Set the flags used by the interpreter for dlopen calls.
1242
1243This is used, for example, when the interpreter loads extension
1244modules. Among other things, this will enable a lazy resolving of
1245symbols when importing a module, if called as sys.setdlopenflags(0).
1246To share symbols across extension modules, call as
1247sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1248modules can be found in the os module (RTLD_xxx constants, e.g.
1249os.RTLD_LAZY).
1250[clinic start generated code]*/
1251
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001252static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001253sys_setdlopenflags_impl(PyObject *module, int new_val)
1254/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001255{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001256 PyInterpreterState *interp = _PyInterpreterState_Get();
1257 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001258 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001259}
1260
Tal Einatede0b6f2018-12-31 17:12:08 +02001261
1262/*[clinic input]
1263sys.getdlopenflags
1264
1265Return the current value of the flags that are used for dlopen calls.
1266
1267The flag constants are defined in the os module.
1268[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001269
1270static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001271sys_getdlopenflags_impl(PyObject *module)
1272/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001273{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001274 PyInterpreterState *interp = _PyInterpreterState_Get();
1275 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001276}
1277
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001279
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001280#ifdef USE_MALLOPT
1281/* Link with -lmalloc (or -lmpc) on an SGI */
1282#include <malloc.h>
1283
Tal Einatede0b6f2018-12-31 17:12:08 +02001284/*[clinic input]
1285sys.mdebug
1286
1287 flag: int
1288 /
1289[clinic start generated code]*/
1290
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001291static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001292sys_mdebug_impl(PyObject *module, int flag)
1293/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001297 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001298}
1299#endif /* USE_MALLOPT */
1300
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001301size_t
1302_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001306 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 /* Make sure the type is initialized. float gets initialized late */
1309 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001310 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001311
Benjamin Petersonce798522012-01-22 11:24:29 -05001312 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 if (method == NULL) {
1314 if (!PyErr_Occurred())
1315 PyErr_Format(PyExc_TypeError,
1316 "Type %.100s doesn't define __sizeof__",
1317 Py_TYPE(o)->tp_name);
1318 }
1319 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001320 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 Py_DECREF(method);
1322 }
1323
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001324 if (res == NULL)
1325 return (size_t)-1;
1326
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001327 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001328 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001329 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001330 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001332 if (size < 0) {
1333 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1334 return (size_t)-1;
1335 }
1336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001338 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001339 return ((size_t)size) + sizeof(PyGC_Head);
1340 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001341}
1342
1343static PyObject *
1344sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1345{
1346 static char *kwlist[] = {"object", "default", 0};
1347 size_t size;
1348 PyObject *o, *dflt = NULL;
1349
1350 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1351 kwlist, &o, &dflt))
1352 return NULL;
1353
1354 size = _PySys_GetSizeOf(o);
1355
1356 if (size == (size_t)-1 && PyErr_Occurred()) {
1357 /* Has a default value been given */
1358 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1359 PyErr_Clear();
1360 Py_INCREF(dflt);
1361 return dflt;
1362 }
1363 else
1364 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001365 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001366
1367 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001368}
1369
1370PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001371"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001372\n\
1373Return the size of object in bytes.");
1374
Tal Einatede0b6f2018-12-31 17:12:08 +02001375/*[clinic input]
1376sys.getrefcount -> Py_ssize_t
1377
1378 object: object
1379 /
1380
1381Return the reference count of object.
1382
1383The count returned is generally one higher than you might expect,
1384because it includes the (temporary) reference as an argument to
1385getrefcount().
1386[clinic start generated code]*/
1387
1388static Py_ssize_t
1389sys_getrefcount_impl(PyObject *module, PyObject *object)
1390/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001391{
Tal Einatede0b6f2018-12-31 17:12:08 +02001392 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001393}
1394
Tim Peters4be93d02002-07-07 19:59:50 +00001395#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001396/*[clinic input]
1397sys.gettotalrefcount -> Py_ssize_t
1398[clinic start generated code]*/
1399
1400static Py_ssize_t
1401sys_gettotalrefcount_impl(PyObject *module)
1402/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001403{
Tal Einatede0b6f2018-12-31 17:12:08 +02001404 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001405}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001406#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001407
Tal Einatede0b6f2018-12-31 17:12:08 +02001408/*[clinic input]
1409sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001410
Tal Einatede0b6f2018-12-31 17:12:08 +02001411Return the number of memory blocks currently allocated.
1412[clinic start generated code]*/
1413
1414static Py_ssize_t
1415sys_getallocatedblocks_impl(PyObject *module)
1416/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001417{
Tal Einatede0b6f2018-12-31 17:12:08 +02001418 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001419}
1420
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001421#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001422/*[clinic input]
1423sys.getcounts
1424[clinic start generated code]*/
1425
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001426static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001427sys_getcounts_impl(PyObject *module)
1428/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001429{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001430 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001431
Pablo Galindo49c75a82018-10-28 15:02:17 +00001432 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001433}
1434#endif
1435
Tal Einatede0b6f2018-12-31 17:12:08 +02001436/*[clinic input]
1437sys._getframe
1438
1439 depth: int = 0
1440 /
1441
1442Return a frame object from the call stack.
1443
1444If optional integer depth is given, return the frame object that many
1445calls below the top of the stack. If that is deeper than the call
1446stack, ValueError is raised. The default for depth is zero, returning
1447the frame at the top of the call stack.
1448
1449This function should be used for internal and specialized purposes
1450only.
1451[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001452
1453static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001454sys__getframe_impl(PyObject *module, int depth)
1455/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001456{
Victor Stinner50b48572018-11-01 01:51:40 +01001457 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001458
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 while (depth > 0 && f != NULL) {
1460 f = f->f_back;
1461 --depth;
1462 }
1463 if (f == NULL) {
1464 PyErr_SetString(PyExc_ValueError,
1465 "call stack is not deep enough");
1466 return NULL;
1467 }
1468 Py_INCREF(f);
1469 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001470}
1471
Tal Einatede0b6f2018-12-31 17:12:08 +02001472/*[clinic input]
1473sys._current_frames
1474
1475Return a dict mapping each thread's thread id to its current stack frame.
1476
1477This function should be used for specialized purposes only.
1478[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001479
1480static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001481sys__current_frames_impl(PyObject *module)
1482/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001483{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001484 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001485}
1486
Tal Einatede0b6f2018-12-31 17:12:08 +02001487/*[clinic input]
1488sys.call_tracing
1489
1490 func: object
1491 args as funcargs: object(subclass_of='&PyTuple_Type')
1492 /
1493
1494Call func(*args), while tracing is enabled.
1495
1496The tracing state is saved, and restored afterwards. This is intended
1497to be called from a debugger from a checkpoint, to recursively debug
1498some other code.
1499[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001500
1501static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001502sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1503/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001504{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001506}
1507
Tal Einatede0b6f2018-12-31 17:12:08 +02001508/*[clinic input]
1509sys.callstats
1510
1511Return a tuple of function call statistics.
1512
1513A tuple is returned only if CALL_PROFILE was defined when Python was
1514built. Otherwise, this returns None.
1515
1516When enabled, this function returns detailed, implementation-specific
1517details about the number of function calls executed. The return value
1518is a 11-tuple where the entries in the tuple are counts of:
15190. all function calls
15201. calls to PyFunction_Type objects
15212. PyFunction calls that do not create an argument tuple
15223. PyFunction calls that do not create an argument tuple
1523 and bypass PyEval_EvalCodeEx()
15244. PyMethod calls
15255. PyMethod calls on bound methods
15266. PyType calls
15277. PyCFunction calls
15288. generator calls
15299. All other calls
153010. Number of stack pops performed by call_function()
1531[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001532
Victor Stinner048afd92016-11-28 11:59:04 +01001533static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001534sys_callstats_impl(PyObject *module)
1535/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001536{
1537 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1538 "sys.callstats() has been deprecated in Python 3.7 "
1539 "and will be removed in the future", 1) < 0) {
1540 return NULL;
1541 }
1542
1543 Py_RETURN_NONE;
1544}
1545
1546
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001547#ifdef __cplusplus
1548extern "C" {
1549#endif
1550
Tal Einatede0b6f2018-12-31 17:12:08 +02001551/*[clinic input]
1552sys._debugmallocstats
1553
1554Print summary info to stderr about the state of pymalloc's structures.
1555
1556In Py_DEBUG mode, also perform some expensive internal consistency
1557checks.
1558[clinic start generated code]*/
1559
David Malcolm49526f42012-06-22 14:55:41 -04001560static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001561sys__debugmallocstats_impl(PyObject *module)
1562/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001563{
1564#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001565 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001566 fputc('\n', stderr);
1567 }
David Malcolm49526f42012-06-22 14:55:41 -04001568#endif
1569 _PyObject_DebugTypeStats(stderr);
1570
1571 Py_RETURN_NONE;
1572}
David Malcolm49526f42012-06-22 14:55:41 -04001573
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001574#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001575/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001576extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001577#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001578
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001579#ifdef DYNAMIC_EXECUTION_PROFILE
1580/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001581extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001582#endif
1583
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001584#ifdef __cplusplus
1585}
1586#endif
1587
Tal Einatede0b6f2018-12-31 17:12:08 +02001588
1589/*[clinic input]
1590sys._clear_type_cache
1591
1592Clear the internal type lookup cache.
1593[clinic start generated code]*/
1594
Christian Heimes15ebc882008-02-04 18:48:49 +00001595static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001596sys__clear_type_cache_impl(PyObject *module)
1597/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 PyType_ClearCache();
1600 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001601}
1602
Tal Einatede0b6f2018-12-31 17:12:08 +02001603/*[clinic input]
1604sys.is_finalizing
1605
1606Return True if Python is exiting.
1607[clinic start generated code]*/
1608
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001609static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001610sys_is_finalizing_impl(PyObject *module)
1611/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001612{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001613 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001614}
1615
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001616#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001617/*[clinic input]
1618sys.getandroidapilevel
1619
1620Return the build time API version of Android as an integer.
1621[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001622
1623static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001624sys_getandroidapilevel_impl(PyObject *module)
1625/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001626{
1627 return PyLong_FromLong(ANDROID_API_LEVEL);
1628}
1629#endif /* ANDROID_API_LEVEL */
1630
1631
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001632static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001634 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001635 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001636 SYS_CALLSTATS_METHODDEF
1637 SYS__CLEAR_TYPE_CACHE_METHODDEF
1638 SYS__CURRENT_FRAMES_METHODDEF
1639 SYS_DISPLAYHOOK_METHODDEF
1640 SYS_EXC_INFO_METHODDEF
1641 SYS_EXCEPTHOOK_METHODDEF
1642 SYS_EXIT_METHODDEF
1643 SYS_GETDEFAULTENCODING_METHODDEF
1644 SYS_GETDLOPENFLAGS_METHODDEF
1645 SYS_GETALLOCATEDBLOCKS_METHODDEF
1646 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001647#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001649#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001650 SYS_GETFILESYSTEMENCODING_METHODDEF
1651 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001652#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001654#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001655 SYS_GETTOTALREFCOUNT_METHODDEF
1656 SYS_GETREFCOUNT_METHODDEF
1657 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001658 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001660 SYS__GETFRAME_METHODDEF
1661 SYS_GETWINDOWSVERSION_METHODDEF
1662 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1663 SYS_INTERN_METHODDEF
1664 SYS_IS_FINALIZING_METHODDEF
1665 SYS_MDEBUG_METHODDEF
1666 SYS_SETCHECKINTERVAL_METHODDEF
1667 SYS_GETCHECKINTERVAL_METHODDEF
1668 SYS_SETSWITCHINTERVAL_METHODDEF
1669 SYS_GETSWITCHINTERVAL_METHODDEF
1670 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001671 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001672 SYS_GETPROFILE_METHODDEF
1673 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001675 SYS_GETTRACE_METHODDEF
1676 SYS_CALL_TRACING_METHODDEF
1677 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001678 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1679 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001680 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1681 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001682 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001683 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001684 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1685 SYS_GETANDROIDAPILEVEL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001687};
1688
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001689static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001690list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 PyObject *list = PyList_New(0);
1693 int i;
1694 if (list == NULL)
1695 return NULL;
1696 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1697 PyObject *name = PyUnicode_FromString(
1698 PyImport_Inittab[i].name);
1699 if (name == NULL)
1700 break;
1701 PyList_Append(list, name);
1702 Py_DECREF(name);
1703 }
1704 if (PyList_Sort(list) != 0) {
1705 Py_DECREF(list);
1706 list = NULL;
1707 }
1708 if (list) {
1709 PyObject *v = PyList_AsTuple(list);
1710 Py_DECREF(list);
1711 list = v;
1712 }
1713 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001714}
1715
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001716/* Pre-initialization support for sys.warnoptions and sys._xoptions
1717 *
1718 * Modern internal code paths:
1719 * These APIs get called after _Py_InitializeCore and get to use the
1720 * regular CPython list, dict, and unicode APIs.
1721 *
1722 * Legacy embedding code paths:
1723 * The multi-phase initialization API isn't public yet, so embedding
1724 * apps still need to be able configure sys.warnoptions and sys._xoptions
1725 * before they call Py_Initialize. To support this, we stash copies of
1726 * the supplied wchar * sequences in linked lists, and then migrate the
1727 * contents of those lists to the sys module in _PyInitializeCore.
1728 *
1729 */
1730
1731struct _preinit_entry {
1732 wchar_t *value;
1733 struct _preinit_entry *next;
1734};
1735
1736typedef struct _preinit_entry *_Py_PreInitEntry;
1737
1738static _Py_PreInitEntry _preinit_warnoptions = NULL;
1739static _Py_PreInitEntry _preinit_xoptions = NULL;
1740
1741static _Py_PreInitEntry
1742_alloc_preinit_entry(const wchar_t *value)
1743{
1744 /* To get this to work, we have to initialize the runtime implicitly */
1745 _PyRuntime_Initialize();
1746
1747 /* Force default allocator, so we can ensure that it also gets used to
1748 * destroy the linked list in _clear_preinit_entries.
1749 */
1750 PyMemAllocatorEx old_alloc;
1751 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1752
1753 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1754 if (node != NULL) {
1755 node->value = _PyMem_RawWcsdup(value);
1756 if (node->value == NULL) {
1757 PyMem_RawFree(node);
1758 node = NULL;
1759 };
1760 };
1761
1762 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1763 return node;
1764};
1765
1766static int
1767_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1768{
1769 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1770 if (new_entry == NULL) {
1771 return -1;
1772 }
1773 /* We maintain the linked list in this order so it's easy to play back
1774 * the add commands in the same order later on in _Py_InitializeCore
1775 */
1776 _Py_PreInitEntry last_entry = *optionlist;
1777 if (last_entry == NULL) {
1778 *optionlist = new_entry;
1779 } else {
1780 while (last_entry->next != NULL) {
1781 last_entry = last_entry->next;
1782 }
1783 last_entry->next = new_entry;
1784 }
1785 return 0;
1786};
1787
1788static void
1789_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1790{
1791 _Py_PreInitEntry current = *optionlist;
1792 *optionlist = NULL;
1793 /* Deallocate the nodes and their contents using the default allocator */
1794 PyMemAllocatorEx old_alloc;
1795 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1796 while (current != NULL) {
1797 _Py_PreInitEntry next = current->next;
1798 PyMem_RawFree(current->value);
1799 PyMem_RawFree(current);
1800 current = next;
1801 }
1802 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1803};
1804
1805static void
1806_clear_all_preinit_options(void)
1807{
1808 _clear_preinit_entries(&_preinit_warnoptions);
1809 _clear_preinit_entries(&_preinit_xoptions);
1810}
1811
1812static int
1813_PySys_ReadPreInitOptions(void)
1814{
1815 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001816 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001817 if (tstate == NULL) {
1818 /* Still don't have a thread state, so something is wrong! */
1819 return -1;
1820 }
1821 _Py_PreInitEntry entry = _preinit_warnoptions;
1822 while (entry != NULL) {
1823 PySys_AddWarnOption(entry->value);
1824 entry = entry->next;
1825 }
1826 entry = _preinit_xoptions;
1827 while (entry != NULL) {
1828 PySys_AddXOption(entry->value);
1829 entry = entry->next;
1830 }
1831
1832 _clear_all_preinit_options();
1833 return 0;
1834};
1835
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001836static PyObject *
1837get_warnoptions(void)
1838{
Eric Snowdae02762017-09-14 00:35:58 -07001839 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001840 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001841 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1842 * interpreter config. When that happens, we need to properly set
1843 * the `warnoptions` reference in the main interpreter config as well.
1844 *
1845 * For Python 3.7, we shouldn't be able to get here due to the
1846 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1847 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1848 * call optional for embedding applications, thus making this
1849 * reachable again.
1850 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001851 warnoptions = PyList_New(0);
1852 if (warnoptions == NULL)
1853 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001854 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1855 Py_DECREF(warnoptions);
1856 return NULL;
1857 }
1858 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001859 }
1860 return warnoptions;
1861}
Guido van Rossum23fff912000-12-15 22:02:05 +00001862
1863void
1864PySys_ResetWarnOptions(void)
1865{
Victor Stinner50b48572018-11-01 01:51:40 +01001866 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001867 if (tstate == NULL) {
1868 _clear_preinit_entries(&_preinit_warnoptions);
1869 return;
1870 }
1871
Eric Snowdae02762017-09-14 00:35:58 -07001872 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001873 if (warnoptions == NULL || !PyList_Check(warnoptions))
1874 return;
1875 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001876}
1877
Victor Stinnere1b29952018-10-30 14:31:42 +01001878static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001879_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001880{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001881 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001882 if (warnoptions == NULL) {
1883 return -1;
1884 }
1885 if (PyList_Append(warnoptions, option)) {
1886 return -1;
1887 }
1888 return 0;
1889}
1890
1891void
1892PySys_AddWarnOptionUnicode(PyObject *option)
1893{
Victor Stinnere1b29952018-10-30 14:31:42 +01001894 if (_PySys_AddWarnOptionWithError(option) < 0) {
1895 /* No return value, therefore clear error state if possible */
1896 if (_PyThreadState_UncheckedGet()) {
1897 PyErr_Clear();
1898 }
1899 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001900}
1901
1902void
1903PySys_AddWarnOption(const wchar_t *s)
1904{
Victor Stinner50b48572018-11-01 01:51:40 +01001905 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001906 if (tstate == NULL) {
1907 _append_preinit_entry(&_preinit_warnoptions, s);
1908 return;
1909 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001910 PyObject *unicode;
1911 unicode = PyUnicode_FromWideChar(s, -1);
1912 if (unicode == NULL)
1913 return;
1914 PySys_AddWarnOptionUnicode(unicode);
1915 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001916}
1917
Christian Heimes33fe8092008-04-13 13:53:33 +00001918int
1919PySys_HasWarnOptions(void)
1920{
Eric Snowdae02762017-09-14 00:35:58 -07001921 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001922 return (warnoptions != NULL && PyList_Check(warnoptions)
1923 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001924}
1925
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001926static PyObject *
1927get_xoptions(void)
1928{
Eric Snowdae02762017-09-14 00:35:58 -07001929 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001930 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001931 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1932 * interpreter config. When that happens, we need to properly set
1933 * the `xoptions` reference in the main interpreter config as well.
1934 *
1935 * For Python 3.7, we shouldn't be able to get here due to the
1936 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1937 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1938 * call optional for embedding applications, thus making this
1939 * reachable again.
1940 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001941 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001942 if (xoptions == NULL)
1943 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001944 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1945 Py_DECREF(xoptions);
1946 return NULL;
1947 }
1948 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001949 }
1950 return xoptions;
1951}
1952
Victor Stinnere1b29952018-10-30 14:31:42 +01001953static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001954_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001955{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001956 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001957
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001958 PyObject *opts = get_xoptions();
1959 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001960 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001961 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001962
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001963 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001964 if (!name_end) {
1965 name = PyUnicode_FromWideChar(s, -1);
1966 value = Py_True;
1967 Py_INCREF(value);
1968 }
1969 else {
1970 name = PyUnicode_FromWideChar(s, name_end - s);
1971 value = PyUnicode_FromWideChar(name_end + 1, -1);
1972 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001974 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975 }
1976 if (PyDict_SetItem(opts, name, value) < 0) {
1977 goto error;
1978 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001979 Py_DECREF(name);
1980 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001981 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001982
1983error:
1984 Py_XDECREF(name);
1985 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001986 return -1;
1987}
1988
1989void
1990PySys_AddXOption(const wchar_t *s)
1991{
Victor Stinner50b48572018-11-01 01:51:40 +01001992 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001993 if (tstate == NULL) {
1994 _append_preinit_entry(&_preinit_xoptions, s);
1995 return;
1996 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001997 if (_PySys_AddXOptionWithError(s) < 0) {
1998 /* No return value, therefore clear error state if possible */
1999 if (_PyThreadState_UncheckedGet()) {
2000 PyErr_Clear();
2001 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002002 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002003}
2004
2005PyObject *
2006PySys_GetXOptions(void)
2007{
2008 return get_xoptions();
2009}
2010
Guido van Rossum40552d01998-08-06 03:34:39 +00002011/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2012 Two literals concatenated works just fine. If you have a K&R compiler
2013 or other abomination that however *does* understand longer strings,
2014 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002015PyDoc_VAR(sys_doc) =
2016PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002017"This module provides access to some objects used or maintained by the\n\
2018interpreter and to functions that interact strongly with the interpreter.\n\
2019\n\
2020Dynamic objects:\n\
2021\n\
2022argv -- command line arguments; argv[0] is the script pathname if known\n\
2023path -- module search path; path[0] is the script directory, else ''\n\
2024modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002025\n\
2026displayhook -- called to show results in an interactive session\n\
2027excepthook -- called to handle any uncaught exception other than SystemExit\n\
2028 To customize printing in an interactive session or to install a custom\n\
2029 top-level exception handler, assign other functions to replace these.\n\
2030\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002031stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002032stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002033stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002034 By assigning other file objects (or objects that behave like files)\n\
2035 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002036\n\
2037last_type -- type of last uncaught exception\n\
2038last_value -- value of last uncaught exception\n\
2039last_traceback -- traceback of last uncaught exception\n\
2040 These three are only available in an interactive session after a\n\
2041 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002042"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002043)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002044/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002045PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002046"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002047Static objects:\n\
2048\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002049builtin_module_names -- tuple of module names built into this interpreter\n\
2050copyright -- copyright notice pertaining to this interpreter\n\
2051exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002052executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002053float_info -- a struct sequence with information about the float implementation.\n\
2054float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002055hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002056hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002057implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002058int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002059maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002060maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002061platform -- platform identifier\n\
2062prefix -- prefix used to find the Python library\n\
2063thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002064version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002065version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002066"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002067)
Steve Dowercc16be82016-09-08 10:35:16 -07002068#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002069/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002070PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002071"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002072winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002073"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002074)
Steve Dowercc16be82016-09-08 10:35:16 -07002075#endif /* MS_COREDLL */
2076#ifdef MS_WINDOWS
2077/* concatenating string here */
2078PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002079"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002080"
2081)
2082#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002083PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002084"__stdin__ -- the original stdin; don't touch!\n\
2085__stdout__ -- the original stdout; don't touch!\n\
2086__stderr__ -- the original stderr; don't touch!\n\
2087__displayhook__ -- the original displayhook; don't touch!\n\
2088__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002089\n\
2090Functions:\n\
2091\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002092displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002093excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002094exc_info() -- return thread-safe information about the current exception\n\
2095exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002096getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002097getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002098getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002099getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002100getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002101gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002102setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002103setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002104setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002105setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002106settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002107"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002108)
Fred Drakeccede592000-08-14 20:59:57 +00002109/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002110
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002111
2112PyDoc_STRVAR(flags__doc__,
2113"sys.flags\n\
2114\n\
2115Flags provided through command line arguments or environment vars.");
2116
2117static PyTypeObject FlagsType;
2118
2119static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 {"inspect", "-i"},
2122 {"interactive", "-i"},
2123 {"optimize", "-O or -OO"},
2124 {"dont_write_bytecode", "-B"},
2125 {"no_user_site", "-s"},
2126 {"no_site", "-S"},
2127 {"ignore_environment", "-E"},
2128 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 /* {"unbuffered", "-u"}, */
2130 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002131 {"bytes_warning", "-b"},
2132 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002133 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002134 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002135 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002136 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002138};
2139
2140static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 "sys.flags", /* name */
2142 flags__doc__, /* doc */
2143 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002144 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002145};
2146
2147static PyObject*
2148make_flags(void)
2149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 int pos = 0;
2151 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002152 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002153
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 seq = PyStructSequence_New(&FlagsType);
2155 if (seq == NULL)
2156 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002157
2158#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002160
Victor Stinnerfbca9082018-08-30 00:50:45 +02002161 SetFlag(config->parser_debug);
2162 SetFlag(config->inspect);
2163 SetFlag(config->interactive);
2164 SetFlag(config->optimization_level);
2165 SetFlag(!config->write_bytecode);
2166 SetFlag(!config->user_site_directory);
2167 SetFlag(!config->site_import);
2168 SetFlag(!config->use_environment);
2169 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 /* SetFlag(saw_unbuffered_flag); */
2171 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002172 SetFlag(config->bytes_warning);
2173 SetFlag(config->quiet);
2174 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2175 SetFlag(config->isolated);
2176 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2177 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002178#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002179
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002181 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 return NULL;
2183 }
2184 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002185}
2186
Eric Smith0e5b5622009-02-06 01:32:42 +00002187PyDoc_STRVAR(version_info__doc__,
2188"sys.version_info\n\
2189\n\
2190Version information as a named tuple.");
2191
2192static PyTypeObject VersionInfoType;
2193
2194static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 {"major", "Major release number"},
2196 {"minor", "Minor release number"},
2197 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002198 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002199 {"serial", "Serial release number"},
2200 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002201};
2202
2203static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 "sys.version_info", /* name */
2205 version_info__doc__, /* doc */
2206 version_info_fields, /* fields */
2207 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002208};
2209
2210static PyObject *
2211make_version_info(void)
2212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 PyObject *version_info;
2214 char *s;
2215 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 version_info = PyStructSequence_New(&VersionInfoType);
2218 if (version_info == NULL) {
2219 return NULL;
2220 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 /*
2223 * These release level checks are mutually exclusive and cover
2224 * the field, so don't get too fancy with the pre-processor!
2225 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002226#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002228#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002230#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002232#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002234#endif
2235
2236#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002238#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 SetIntItem(PY_MAJOR_VERSION);
2242 SetIntItem(PY_MINOR_VERSION);
2243 SetIntItem(PY_MICRO_VERSION);
2244 SetStrItem(s);
2245 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002246#undef SetIntItem
2247#undef SetStrItem
2248
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 if (PyErr_Occurred()) {
2250 Py_CLEAR(version_info);
2251 return NULL;
2252 }
2253 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002254}
2255
Brett Cannon3adc7b72012-07-09 14:22:12 -04002256/* sys.implementation values */
2257#define NAME "cpython"
2258const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002259#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2260#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002261#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002262const char *_PySys_ImplCacheTag = TAG;
2263#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002264#undef MAJOR
2265#undef MINOR
2266#undef TAG
2267
Barry Warsaw409da152012-06-03 16:18:47 -04002268static PyObject *
2269make_impl_info(PyObject *version_info)
2270{
2271 int res;
2272 PyObject *impl_info, *value, *ns;
2273
2274 impl_info = PyDict_New();
2275 if (impl_info == NULL)
2276 return NULL;
2277
2278 /* populate the dict */
2279
Brett Cannon3adc7b72012-07-09 14:22:12 -04002280 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002281 if (value == NULL)
2282 goto error;
2283 res = PyDict_SetItemString(impl_info, "name", value);
2284 Py_DECREF(value);
2285 if (res < 0)
2286 goto error;
2287
Brett Cannon3adc7b72012-07-09 14:22:12 -04002288 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002289 if (value == NULL)
2290 goto error;
2291 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2292 Py_DECREF(value);
2293 if (res < 0)
2294 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002295
2296 res = PyDict_SetItemString(impl_info, "version", version_info);
2297 if (res < 0)
2298 goto error;
2299
2300 value = PyLong_FromLong(PY_VERSION_HEX);
2301 if (value == NULL)
2302 goto error;
2303 res = PyDict_SetItemString(impl_info, "hexversion", value);
2304 Py_DECREF(value);
2305 if (res < 0)
2306 goto error;
2307
doko@ubuntu.com55532312016-06-14 08:55:19 +02002308#ifdef MULTIARCH
2309 value = PyUnicode_FromString(MULTIARCH);
2310 if (value == NULL)
2311 goto error;
2312 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2313 Py_DECREF(value);
2314 if (res < 0)
2315 goto error;
2316#endif
2317
Barry Warsaw409da152012-06-03 16:18:47 -04002318 /* dict ready */
2319
2320 ns = _PyNamespace_New(impl_info);
2321 Py_DECREF(impl_info);
2322 return ns;
2323
2324error:
2325 Py_CLEAR(impl_info);
2326 return NULL;
2327}
2328
Martin v. Löwis1a214512008-06-11 05:26:20 +00002329static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002330 PyModuleDef_HEAD_INIT,
2331 "sys",
2332 sys_doc,
2333 -1, /* multiple "initialization" just copies the module dict. */
2334 sys_methods,
2335 NULL,
2336 NULL,
2337 NULL,
2338 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002339};
2340
Eric Snow6b4be192017-05-22 21:36:03 -07002341/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002342#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002343 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002344 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002345 if (v == NULL) { \
2346 goto err_occurred; \
2347 } \
Victor Stinner58049602013-07-22 22:40:00 +02002348 res = PyDict_SetItemString(sysdict, key, v); \
2349 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002350 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002351 } \
2352 } while (0)
2353#define SET_SYS_FROM_STRING(key, value) \
2354 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002355 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002356 if (v == NULL) { \
2357 goto err_occurred; \
2358 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002359 res = PyDict_SetItemString(sysdict, key, v); \
2360 Py_DECREF(v); \
2361 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002362 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002363 } \
2364 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002365
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002366
2367_PyInitError
2368_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002369{
2370 PyObject *m, *sysdict, *version_info;
2371 int res;
2372
Eric Snowd393c1b2017-09-14 12:18:12 -06002373 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002374 if (m == NULL) {
2375 return _Py_INIT_ERR("failed to create a module object");
2376 }
Eric Snow6b4be192017-05-22 21:36:03 -07002377 sysdict = PyModule_GetDict(m);
2378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002380 Using shell redirection, you can redirect stdin to a directory,
2381 crashing the Python interpreter. Catch this common mistake here
2382 and output a useful error message. Note that under MS Windows,
2383 the shell already prevents that. */
2384#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002386 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002387 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002388 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002389 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2390 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 }
2392 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002393#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002394
Nick Coghland6009512014-11-20 21:39:37 +10002395 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002396
Victor Stinner8fea2522013-10-27 17:15:42 +01002397 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2398 PyDict_GetItemString(sysdict, "displayhook"));
2399 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2400 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002401 SET_SYS_FROM_STRING_BORROW(
2402 "__breakpointhook__",
2403 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002404 SET_SYS_FROM_STRING("version",
2405 PyUnicode_FromString(Py_GetVersion()));
2406 SET_SYS_FROM_STRING("hexversion",
2407 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002408 SET_SYS_FROM_STRING("_git",
2409 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2410 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002411 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 SET_SYS_FROM_STRING("api_version",
2413 PyLong_FromLong(PYTHON_API_VERSION));
2414 SET_SYS_FROM_STRING("copyright",
2415 PyUnicode_FromString(Py_GetCopyright()));
2416 SET_SYS_FROM_STRING("platform",
2417 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002418 SET_SYS_FROM_STRING("maxsize",
2419 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2420 SET_SYS_FROM_STRING("float_info",
2421 PyFloat_GetInfo());
2422 SET_SYS_FROM_STRING("int_info",
2423 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002424 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002425 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002426 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2427 goto type_init_failed;
2428 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002429 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002430 SET_SYS_FROM_STRING("hash_info",
2431 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002433 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002434 SET_SYS_FROM_STRING("builtin_module_names",
2435 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002436#if PY_BIG_ENDIAN
2437 SET_SYS_FROM_STRING("byteorder",
2438 PyUnicode_FromString("big"));
2439#else
2440 SET_SYS_FROM_STRING("byteorder",
2441 PyUnicode_FromString("little"));
2442#endif
Fred Drake099325e2000-08-14 15:47:03 +00002443
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002444#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002445 SET_SYS_FROM_STRING("dllhandle",
2446 PyLong_FromVoidPtr(PyWin_DLLhModule));
2447 SET_SYS_FROM_STRING("winver",
2448 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002449#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002450#ifdef ABIFLAGS
2451 SET_SYS_FROM_STRING("abiflags",
2452 PyUnicode_FromString(ABIFLAGS));
2453#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002454
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002455 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002456 if (VersionInfoType.tp_name == NULL) {
2457 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002458 &version_info_desc) < 0) {
2459 goto type_init_failed;
2460 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002461 }
Barry Warsaw409da152012-06-03 16:18:47 -04002462 version_info = make_version_info();
2463 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 /* prevent user from creating new instances */
2465 VersionInfoType.tp_init = NULL;
2466 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002467 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2468 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2469 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002470
Barry Warsaw409da152012-06-03 16:18:47 -04002471 /* implementation */
2472 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002475 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002476 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2477 goto type_init_failed;
2478 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002479 }
Eric Snow6b4be192017-05-22 21:36:03 -07002480 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002481 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002482
2483#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 /* getwindowsversion */
2485 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002486 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002487 &windows_version_desc) < 0) {
2488 goto type_init_failed;
2489 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 /* prevent user from creating new instances */
2491 WindowsVersionType.tp_init = NULL;
2492 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002493 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002494 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002495 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002496 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002497 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002498#endif
2499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002500 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002501#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002502 SET_SYS_FROM_STRING("float_repr_style",
2503 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002504#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002505 SET_SYS_FROM_STRING("float_repr_style",
2506 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002507#endif
2508
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002509 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002510
Yury Selivanoveb636452016-09-08 22:01:51 -07002511 /* initialize asyncgen_hooks */
2512 if (AsyncGenHooksType.tp_name == NULL) {
2513 if (PyStructSequence_InitType2(
2514 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002515 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002516 }
2517 }
2518
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002519 if (PyErr_Occurred()) {
2520 goto err_occurred;
2521 }
2522
2523 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002524
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002525 return _Py_INIT_OK();
2526
2527type_init_failed:
2528 return _Py_INIT_ERR("failed to initialize a type");
2529
2530err_occurred:
2531 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002532}
2533
Eric Snow6b4be192017-05-22 21:36:03 -07002534#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002535
2536/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002537#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2538 do { \
2539 PyObject *v = (value); \
2540 if (v == NULL) \
2541 return -1; \
2542 res = PyDict_SetItemString(sysdict, key, v); \
2543 Py_DECREF(v); \
2544 if (res < 0) { \
2545 return res; \
2546 } \
2547 } while (0)
2548
2549int
Victor Stinnerfbca9082018-08-30 00:50:45 +02002550_PySys_EndInit(PyObject *sysdict, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002551{
Victor Stinnerfbca9082018-08-30 00:50:45 +02002552 const _PyCoreConfig *core_config = &interp->core_config;
2553 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002554 int res;
2555
Victor Stinner41264f12017-12-15 02:05:29 +01002556 /* _PyMainInterpreterConfig_Read() must set all these variables */
2557 assert(config->module_search_path != NULL);
2558 assert(config->executable != NULL);
2559 assert(config->prefix != NULL);
2560 assert(config->base_prefix != NULL);
2561 assert(config->exec_prefix != NULL);
2562 assert(config->base_exec_prefix != NULL);
2563
Victor Stinner37cd9822018-11-16 11:55:35 +01002564#define COPY_LIST(KEY, ATTR) \
2565 do { \
2566 assert(PyList_Check(config->ATTR)); \
2567 PyObject *list = PyList_GetSlice(config->ATTR, \
2568 0, PyList_GET_SIZE(config->ATTR)); \
2569 if (list == NULL) { \
2570 return -1; \
2571 } \
2572 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2573 Py_DECREF(list); \
2574 } while (0)
2575
2576 COPY_LIST("path", module_search_path);
2577
Victor Stinner41264f12017-12-15 02:05:29 +01002578 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2579 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2580 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2581 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2582 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2583
Carl Meyerb193fa92018-06-15 22:40:56 -06002584 if (config->pycache_prefix != NULL) {
2585 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2586 } else {
2587 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2588 }
2589
Victor Stinner41264f12017-12-15 02:05:29 +01002590 if (config->argv != NULL) {
2591 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2592 }
2593 if (config->warnoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002594 COPY_LIST("warnoptions", warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002595 }
2596 if (config->xoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002597 PyObject *dict = PyDict_Copy(config->xoptions);
2598 if (dict == NULL) {
2599 return -1;
2600 }
2601 SET_SYS_FROM_STRING_BORROW("_xoptions", dict);
2602 Py_DECREF(dict);
Victor Stinner41264f12017-12-15 02:05:29 +01002603 }
2604
Victor Stinner37cd9822018-11-16 11:55:35 +01002605#undef COPY_LIST
2606
Eric Snow6b4be192017-05-22 21:36:03 -07002607 /* Set flags to their final values */
2608 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2609 /* prevent user from creating new instances */
2610 FlagsType.tp_init = NULL;
2611 FlagsType.tp_new = NULL;
2612 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2613 if (res < 0) {
2614 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2615 return res;
2616 }
2617 PyErr_Clear();
2618 }
2619
2620 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002621 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002622
Eric Snowdae02762017-09-14 00:35:58 -07002623 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002624 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002625
Eric Snowdae02762017-09-14 00:35:58 -07002626 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002627 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002628
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002629 /* Transfer any sys.warnoptions and sys._xoptions set directly
2630 * by an embedding application from the linked list to the module. */
2631 if (_PySys_ReadPreInitOptions() != 0)
2632 return -1;
2633
Eric Snow6b4be192017-05-22 21:36:03 -07002634 if (PyErr_Occurred())
2635 return -1;
2636 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002637
2638err_occurred:
2639 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002640}
2641
Victor Stinner41264f12017-12-15 02:05:29 +01002642#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002643#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002644
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002645static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002646makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002647{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002648 int i, n;
2649 const wchar_t *p;
2650 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002651
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 n = 1;
2653 p = path;
2654 while ((p = wcschr(p, delim)) != NULL) {
2655 n++;
2656 p++;
2657 }
2658 v = PyList_New(n);
2659 if (v == NULL)
2660 return NULL;
2661 for (i = 0; ; i++) {
2662 p = wcschr(path, delim);
2663 if (p == NULL)
2664 p = path + wcslen(path); /* End of string */
2665 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2666 if (w == NULL) {
2667 Py_DECREF(v);
2668 return NULL;
2669 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002670 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002671 if (*p == '\0')
2672 break;
2673 path = p+1;
2674 }
2675 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002676}
2677
2678void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002679PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002681 PyObject *v;
2682 if ((v = makepathobject(path, DELIM)) == NULL)
2683 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002684 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 Py_FatalError("can't assign sys.path");
2686 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002687}
2688
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002689static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002690makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002692 PyObject *av;
2693 if (argc <= 0 || argv == NULL) {
2694 /* Ensure at least one (empty) argument is seen */
2695 static wchar_t *empty_argv[1] = {L""};
2696 argv = empty_argv;
2697 argc = 1;
2698 }
2699 av = PyList_New(argc);
2700 if (av != NULL) {
2701 int i;
2702 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 if (v == NULL) {
2705 Py_DECREF(av);
2706 av = NULL;
2707 break;
2708 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002709 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 }
2711 }
2712 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002713}
2714
Victor Stinner11a247d2017-12-13 21:05:57 +01002715void
2716PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002717{
2718 PyObject *av = makeargvobject(argc, argv);
2719 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002720 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002721 }
2722 if (PySys_SetObject("argv", av) != 0) {
2723 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002724 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002725 }
2726 Py_DECREF(av);
2727
2728 if (updatepath) {
2729 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2730 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002731 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2732 if (argv0 == NULL) {
2733 Py_FatalError("can't compute path0 from argv");
2734 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002735
Victor Stinner11a247d2017-12-13 21:05:57 +01002736 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2737 if (sys_path != NULL) {
2738 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2739 Py_DECREF(argv0);
2740 Py_FatalError("can't prepend path0 to sys.path");
2741 }
2742 }
2743 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002744 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002745}
Guido van Rossuma890e681998-05-12 14:59:24 +00002746
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002747void
2748PySys_SetArgv(int argc, wchar_t **argv)
2749{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002750 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002751}
2752
Victor Stinner14284c22010-04-23 12:02:30 +00002753/* Reimplementation of PyFile_WriteString() no calling indirectly
2754 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2755
2756static int
Victor Stinner79766632010-08-16 17:36:42 +00002757sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002758{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002759 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002761
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002762 if (file == NULL)
2763 return -1;
2764
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002765 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002766 if (writer == NULL)
2767 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002768
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002769 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 if (result == NULL) {
2771 goto error;
2772 } else {
2773 err = 0;
2774 goto finally;
2775 }
Victor Stinner14284c22010-04-23 12:02:30 +00002776
2777error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002779finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 Py_XDECREF(result);
2782 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002783}
2784
Victor Stinner79766632010-08-16 17:36:42 +00002785static int
2786sys_pyfile_write(const char *text, PyObject *file)
2787{
2788 PyObject *unicode = NULL;
2789 int err;
2790
2791 if (file == NULL)
2792 return -1;
2793
2794 unicode = PyUnicode_FromString(text);
2795 if (unicode == NULL)
2796 return -1;
2797
2798 err = sys_pyfile_write_unicode(unicode, file);
2799 Py_DECREF(unicode);
2800 return err;
2801}
Guido van Rossuma890e681998-05-12 14:59:24 +00002802
2803/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2804 Adapted from code submitted by Just van Rossum.
2805
2806 PySys_WriteStdout(format, ...)
2807 PySys_WriteStderr(format, ...)
2808
2809 The first function writes to sys.stdout; the second to sys.stderr. When
2810 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002811 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002812
Victor Stinner14284c22010-04-23 12:02:30 +00002813 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002814 signal handlers: they may raise a new exception whereas sys_write()
2815 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002816
Guido van Rossuma890e681998-05-12 14:59:24 +00002817 Both take a printf-style format string as their first argument followed
2818 by a variable length argument list determined by the format string.
2819
2820 *** WARNING ***
2821
2822 The format should limit the total size of the formatted output string to
2823 1000 bytes. In particular, this means that no unrestricted "%s" formats
2824 should occur; these should be limited using "%.<N>s where <N> is a
2825 decimal number calculated so that <N> plus the maximum size of other
2826 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2827 which can print hundreds of digits for very large numbers.
2828
2829 */
2830
2831static void
Victor Stinner09054372013-11-06 22:41:44 +01002832sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002833{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002834 PyObject *file;
2835 PyObject *error_type, *error_value, *error_traceback;
2836 char buffer[1001];
2837 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002838
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002840 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002841 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2842 if (sys_pyfile_write(buffer, file) != 0) {
2843 PyErr_Clear();
2844 fputs(buffer, fp);
2845 }
2846 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2847 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002848 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002849 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002850 }
2851 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002852}
2853
2854void
Guido van Rossuma890e681998-05-12 14:59:24 +00002855PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002858
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002859 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002860 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002862}
2863
2864void
Guido van Rossuma890e681998-05-12 14:59:24 +00002865PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002866{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002867 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002868
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002870 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002871 va_end(va);
2872}
2873
2874static void
Victor Stinner09054372013-11-06 22:41:44 +01002875sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002876{
2877 PyObject *file, *message;
2878 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002879 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002880
2881 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002882 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002883 message = PyUnicode_FromFormatV(format, va);
2884 if (message != NULL) {
2885 if (sys_pyfile_write_unicode(message, file) != 0) {
2886 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002887 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002888 if (utf8 != NULL)
2889 fputs(utf8, fp);
2890 }
2891 Py_DECREF(message);
2892 }
2893 PyErr_Restore(error_type, error_value, error_traceback);
2894}
2895
2896void
2897PySys_FormatStdout(const char *format, ...)
2898{
2899 va_list va;
2900
2901 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002902 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002903 va_end(va);
2904}
2905
2906void
2907PySys_FormatStderr(const char *format, ...)
2908{
2909 va_list va;
2910
2911 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002912 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002913 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002914}