blob: 10707fd23fc628f860ee55dbe6f59884a61be551 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010020#include "pycore_pylifecycle.h"
21#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010022#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010023#include "pycore_pystate.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020024#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000025
Guido van Rossume2437a11992-03-23 18:20:18 +000026#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020027#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000028
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#ifdef MS_WINDOWS
30#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000031#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000032#endif /* MS_WINDOWS */
33
Guido van Rossum9b38a141996-09-11 23:12:24 +000034#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000035extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000036/* A string loaded from the DLL at startup: */
37extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000038#endif
39
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080040/*[clinic input]
41module sys
42[clinic start generated code]*/
43/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
44
45#include "clinic/sysmodule.c.h"
46
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(_);
48_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070049_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(buffer);
51_Py_IDENTIFIER(builtins);
52_Py_IDENTIFIER(encoding);
53_Py_IDENTIFIER(path);
54_Py_IDENTIFIER(stdout);
55_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070056_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010057_Py_IDENTIFIER(write);
58
Guido van Rossum65bf9f21997-04-29 18:33:38 +000059PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010060_PySys_GetObjectId(_Py_Identifier *key)
61{
Victor Stinnercaba55b2018-08-03 15:33:52 +020062 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
63 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010064 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020065 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010066 return _PyDict_GetItemId(sd, key);
67}
68
69PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000070PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071{
Victor Stinnercaba55b2018-08-03 15:33:52 +020072 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
73 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077}
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079int
Victor Stinnerd67bd452013-11-06 22:36:40 +010080_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
81{
Victor Stinnercaba55b2018-08-03 15:33:52 +020082 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010083 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020084 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010085 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020086 }
87 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010090 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020091 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010092 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020093 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010094}
95
96int
Neal Norwitzf3081322007-08-25 00:32:45 +000097PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Victor Stinnercaba55b2018-08-03 15:33:52 +020099 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200101 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200103 }
104 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200108 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200110 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111}
112
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400113static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200114sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400115{
116 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300117 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400118
119 if (envar == NULL || strlen(envar) == 0) {
120 envar = "pdb.set_trace";
121 }
122 else if (!strcmp(envar, "0")) {
123 /* The breakpoint is explicitly no-op'd. */
124 Py_RETURN_NONE;
125 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300126 /* According to POSIX the string returned by getenv() might be invalidated
127 * or the string content might be overwritten by a subsequent call to
128 * getenv(). Since importing a module can performs the getenv() calls,
129 * we need to save a copy of envar. */
130 envar = _PyMem_RawStrdup(envar);
131 if (envar == NULL) {
132 PyErr_NoMemory();
133 return NULL;
134 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200135 const char *last_dot = strrchr(envar, '.');
136 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400137 PyObject *modulepath = NULL;
138
139 if (last_dot == NULL) {
140 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
141 modulepath = PyUnicode_FromString("builtins");
142 attrname = envar;
143 }
144 else {
145 /* Split on the last dot; */
146 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
147 attrname = last_dot + 1;
148 }
149 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300150 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400151 return NULL;
152 }
153
Anthony Sottiledce345c2018-11-01 10:25:05 -0700154 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400155 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400156
157 if (module == NULL) {
158 goto error;
159 }
160
161 PyObject *hook = PyObject_GetAttrString(module, attrname);
162 Py_DECREF(module);
163
164 if (hook == NULL) {
165 goto error;
166 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300167 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400168 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
169 Py_DECREF(hook);
170 return retval;
171
172 error:
173 /* If any of the imports went wrong, then warn and ignore. */
174 PyErr_Clear();
175 int status = PyErr_WarnFormat(
176 PyExc_RuntimeWarning, 0,
177 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300178 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400179 if (status < 0) {
180 /* Printing the warning raised an exception. */
181 return NULL;
182 }
183 /* The warning was (probably) issued. */
184 Py_RETURN_NONE;
185}
186
187PyDoc_STRVAR(breakpointhook_doc,
188"breakpointhook(*args, **kws)\n"
189"\n"
190"This hook function is called by built-in breakpoint().\n"
191);
192
Victor Stinner13d49ee2010-12-04 17:24:33 +0000193/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
194 error handler. If sys.stdout has a buffer attribute, use
195 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
196 sys.stdout.write(redecoded).
197
198 Helper function for sys_displayhook(). */
199static int
200sys_displayhook_unencodable(PyObject *outf, PyObject *o)
201{
202 PyObject *stdout_encoding = NULL;
203 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200204 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000205 int ret;
206
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200207 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000208 if (stdout_encoding == NULL)
209 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200210 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000211 if (stdout_encoding_str == NULL)
212 goto error;
213
214 repr_str = PyObject_Repr(o);
215 if (repr_str == NULL)
216 goto error;
217 encoded = PyUnicode_AsEncodedString(repr_str,
218 stdout_encoding_str,
219 "backslashreplace");
220 Py_DECREF(repr_str);
221 if (encoded == NULL)
222 goto error;
223
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200224 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000225 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100226 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000227 Py_DECREF(buffer);
228 Py_DECREF(encoded);
229 if (result == NULL)
230 goto error;
231 Py_DECREF(result);
232 }
233 else {
234 PyErr_Clear();
235 escaped_str = PyUnicode_FromEncodedObject(encoded,
236 stdout_encoding_str,
237 "strict");
238 Py_DECREF(encoded);
239 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
240 Py_DECREF(escaped_str);
241 goto error;
242 }
243 Py_DECREF(escaped_str);
244 }
245 ret = 0;
246 goto finally;
247
248error:
249 ret = -1;
250finally:
251 Py_XDECREF(stdout_encoding);
252 return ret;
253}
254
Tal Einatede0b6f2018-12-31 17:12:08 +0200255/*[clinic input]
256sys.displayhook
257
258 object as o: object
259 /
260
261Print an object to sys.stdout and also save it in builtins._
262[clinic start generated code]*/
263
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000264static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200265sys_displayhook(PyObject *module, PyObject *o)
266/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100269 PyObject *builtins;
270 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000271 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000272
Eric Snow3f9eee62017-09-15 16:35:20 -0600273 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 if (builtins == NULL) {
275 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
276 return NULL;
277 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600278 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 /* Print value except if None */
281 /* After printing, also assign to '_' */
282 /* Before, set '_' to None to avoid recursion */
283 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200284 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200286 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100288 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 if (outf == NULL || outf == Py_None) {
290 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
291 return NULL;
292 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000293 if (PyFile_WriteObject(o, outf, 0) != 0) {
294 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
295 /* repr(o) is not encodable to sys.stdout.encoding with
296 * sys.stdout.errors error handler (which is probably 'strict') */
297 PyErr_Clear();
298 err = sys_displayhook_unencodable(outf, o);
299 if (err)
300 return NULL;
301 }
302 else {
303 return NULL;
304 }
305 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100306 if (newline == NULL) {
307 newline = PyUnicode_FromString("\n");
308 if (newline == NULL)
309 return NULL;
310 }
311 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000312 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200313 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200315 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000316}
317
Tal Einatede0b6f2018-12-31 17:12:08 +0200318
319/*[clinic input]
320sys.excepthook
321
322 exctype: object
323 value: object
324 traceback: object
325 /
326
327Handle an exception by displaying it with a traceback on sys.stderr.
328[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000329
330static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200331sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
332 PyObject *traceback)
333/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000334{
Tal Einatede0b6f2018-12-31 17:12:08 +0200335 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200336 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000337}
338
Tal Einatede0b6f2018-12-31 17:12:08 +0200339
340/*[clinic input]
341sys.exc_info
342
343Return current exception information: (type, value, traceback).
344
345Return information about the most recent exception caught by an except
346clause in the current stack frame or in an older stack frame.
347[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000348
349static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200350sys_exc_info_impl(PyObject *module)
351/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000352{
Victor Stinner50b48572018-11-01 01:51:40 +0100353 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000354 return Py_BuildValue(
355 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100356 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
357 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
358 err_info->exc_traceback != NULL ?
359 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000360}
361
Tal Einatede0b6f2018-12-31 17:12:08 +0200362
363/*[clinic input]
364sys.exit
365
366 status: object = NULL
367 /
368
369Exit the interpreter by raising SystemExit(status).
370
371If the status is omitted or None, it defaults to zero (i.e., success).
372If the status is an integer, it will be used as the system exit status.
373If it is another kind of object, it will be printed and the system
374exit status will be one (i.e., failure).
375[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000376
377static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200378sys_exit_impl(PyObject *module, PyObject *status)
379/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000380{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200382 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000384}
385
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000386
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000387
Tal Einatede0b6f2018-12-31 17:12:08 +0200388/*[clinic input]
389sys.getdefaultencoding
390
391Return the current default encoding used by the Unicode implementation.
392[clinic start generated code]*/
393
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000394static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200395sys_getdefaultencoding_impl(PyObject *module)
396/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000399}
400
Tal Einatede0b6f2018-12-31 17:12:08 +0200401/*[clinic input]
402sys.getfilesystemencoding
403
404Return the encoding used to convert Unicode filenames to OS filenames.
405[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000406
407static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200408sys_getfilesystemencoding_impl(PyObject *module)
409/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000410{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200411 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
412 const _PyCoreConfig *config = &interp->core_config;
413 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000414}
415
Tal Einatede0b6f2018-12-31 17:12:08 +0200416/*[clinic input]
417sys.getfilesystemencodeerrors
418
419Return the error mode used Unicode to OS filename conversion.
420[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000421
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000422static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200423sys_getfilesystemencodeerrors_impl(PyObject *module)
424/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700425{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200426 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
427 const _PyCoreConfig *config = &interp->core_config;
428 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700429}
430
Tal Einatede0b6f2018-12-31 17:12:08 +0200431/*[clinic input]
432sys.intern
433
434 string as s: unicode
435 /
436
437``Intern'' the given string.
438
439This enters the string in the (global) table of interned strings whose
440purpose is to speed up dictionary lookups. Return the string itself or
441the previously interned string object with the same value.
442[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700443
444static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200445sys_intern_impl(PyObject *module, PyObject *s)
446/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000447{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 if (PyUnicode_CheckExact(s)) {
449 Py_INCREF(s);
450 PyUnicode_InternInPlace(&s);
451 return s;
452 }
453 else {
454 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200455 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 return NULL;
457 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000458}
459
Georg Brandl66a796e2006-12-19 20:50:34 +0000460
Fred Drake5755ce62001-06-27 19:19:46 +0000461/*
462 * Cached interned string objects used for calling the profile and
463 * trace functions. Initialized by trace_init().
464 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000465static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000466
467static int
468trace_init(void)
469{
Nick Coghlan5a851672017-09-08 10:14:16 +1000470 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200471 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000472 "c_call", "c_exception", "c_return",
473 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200474 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 PyObject *name;
476 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000477 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 if (whatstrings[i] == NULL) {
479 name = PyUnicode_InternFromString(whatnames[i]);
480 if (name == NULL)
481 return -1;
482 whatstrings[i] = name;
483 }
484 }
485 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000486}
487
488
489static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100490call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200494 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000495
Victor Stinner78da82b2016-08-20 01:22:57 +0200496 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200498 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100499
Victor Stinner78da82b2016-08-20 01:22:57 +0200500 stack[0] = (PyObject *)frame;
501 stack[1] = whatstrings[what];
502 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200505 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000506
Victor Stinner78da82b2016-08-20 01:22:57 +0200507 PyFrame_LocalsToFast(frame, 1);
508 if (result == NULL) {
509 PyTraceBack_Here(frame);
510 }
511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000513}
514
515static int
516profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000518{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000520
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (arg == NULL)
522 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100523 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000524 if (result == NULL) {
525 PyEval_SetProfile(NULL, NULL);
526 return -1;
527 }
528 Py_DECREF(result);
529 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000530}
531
532static int
533trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 PyObject *callback;
537 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000539 if (what == PyTrace_CALL)
540 callback = self;
541 else
542 callback = frame->f_trace;
543 if (callback == NULL)
544 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100545 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000546 if (result == NULL) {
547 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200548 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 return -1;
550 }
551 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300552 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 }
554 else {
555 Py_DECREF(result);
556 }
557 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000558}
Fred Draked0838392001-06-16 21:02:31 +0000559
Fred Drake8b4d01d2000-05-09 19:57:01 +0000560static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000561sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000562{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 if (trace_init() == -1)
564 return NULL;
565 if (args == Py_None)
566 PyEval_SetTrace(NULL, NULL);
567 else
568 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200569 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000570}
571
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000572PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000573"settrace(function)\n\
574\n\
575Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000576function call. See the debugger chapter in the library manual."
577);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000578
Tal Einatede0b6f2018-12-31 17:12:08 +0200579/*[clinic input]
580sys.gettrace
581
582Return the global debug tracing function set with sys.settrace.
583
584See the debugger chapter in the library manual.
585[clinic start generated code]*/
586
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000587static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200588sys_gettrace_impl(PyObject *module)
589/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000590{
Victor Stinner50b48572018-11-01 01:51:40 +0100591 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000592 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 if (temp == NULL)
595 temp = Py_None;
596 Py_INCREF(temp);
597 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000598}
599
Christian Heimes9bd667a2008-01-20 15:14:11 +0000600static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000601sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 if (trace_init() == -1)
604 return NULL;
605 if (args == Py_None)
606 PyEval_SetProfile(NULL, NULL);
607 else
608 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200609 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000610}
611
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000612PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000613"setprofile(function)\n\
614\n\
615Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000616and return. See the profiler chapter in the library manual."
617);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000618
Tal Einatede0b6f2018-12-31 17:12:08 +0200619/*[clinic input]
620sys.getprofile
621
622Return the profiling function set with sys.setprofile.
623
624See the profiler chapter in the library manual.
625[clinic start generated code]*/
626
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000627static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200628sys_getprofile_impl(PyObject *module)
629/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000630{
Victor Stinner50b48572018-11-01 01:51:40 +0100631 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 if (temp == NULL)
635 temp = Py_None;
636 Py_INCREF(temp);
637 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000638}
639
Tal Einatede0b6f2018-12-31 17:12:08 +0200640/*[clinic input]
641sys.setcheckinterval
642
643 n: int
644 /
645
646Set the async event check interval to n instructions.
647
648This tells the Python interpreter to check for asynchronous events
649every n instructions.
650
651This also affects how often thread switches occur.
652[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000653
654static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200655sys_setcheckinterval_impl(PyObject *module, int n)
656/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (PyErr_WarnEx(PyExc_DeprecationWarning,
659 "sys.getcheckinterval() and sys.setcheckinterval() "
660 "are deprecated. Use sys.setswitchinterval() "
661 "instead.", 1) < 0)
662 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200663
Victor Stinnercaba55b2018-08-03 15:33:52 +0200664 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +0200665 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200666 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000667}
668
Tal Einatede0b6f2018-12-31 17:12:08 +0200669/*[clinic input]
670sys.getcheckinterval
671
672Return the current check interval; see sys.setcheckinterval().
673[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000674
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000675static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200676sys_getcheckinterval_impl(PyObject *module)
677/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000678{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000679 if (PyErr_WarnEx(PyExc_DeprecationWarning,
680 "sys.getcheckinterval() and sys.setcheckinterval() "
681 "are deprecated. Use sys.getswitchinterval() "
682 "instead.", 1) < 0)
683 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200684 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600685 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000686}
687
Tal Einatede0b6f2018-12-31 17:12:08 +0200688/*[clinic input]
689sys.setswitchinterval
690
691 interval: double
692 /
693
694Set the ideal thread switching delay inside the Python interpreter.
695
696The actual frequency of switching threads can be lower if the
697interpreter executes long sequences of uninterruptible code
698(this is implementation-specific and workload-dependent).
699
700The parameter must represent the desired switching delay in seconds
701A typical value is 0.005 (5 milliseconds).
702[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000703
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000704static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200705sys_setswitchinterval_impl(PyObject *module, double interval)
706/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000707{
Tal Einatede0b6f2018-12-31 17:12:08 +0200708 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 PyErr_SetString(PyExc_ValueError,
710 "switch interval must be strictly positive");
711 return NULL;
712 }
Tal Einatede0b6f2018-12-31 17:12:08 +0200713 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200714 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000715}
716
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000717
Tal Einatede0b6f2018-12-31 17:12:08 +0200718/*[clinic input]
719sys.getswitchinterval -> double
720
721Return the current thread switch interval; see sys.setswitchinterval().
722[clinic start generated code]*/
723
724static double
725sys_getswitchinterval_impl(PyObject *module)
726/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000727{
Tal Einatede0b6f2018-12-31 17:12:08 +0200728 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000729}
730
Tal Einatede0b6f2018-12-31 17:12:08 +0200731/*[clinic input]
732sys.setrecursionlimit
733
734 limit as new_limit: int
735 /
736
737Set the maximum depth of the Python interpreter stack to n.
738
739This limit prevents infinite recursion from causing an overflow of the C
740stack and crashing Python. The highest possible limit is platform-
741dependent.
742[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000743
Tim Peterse5e065b2003-07-06 18:36:54 +0000744static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200745sys_setrecursionlimit_impl(PyObject *module, int new_limit)
746/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000747{
Tal Einatede0b6f2018-12-31 17:12:08 +0200748 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +0200749 PyThreadState *tstate;
750
Victor Stinner50856d52015-10-13 00:11:21 +0200751 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200753 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 return NULL;
755 }
Victor Stinner50856d52015-10-13 00:11:21 +0200756
757 /* Issue #25274: When the recursion depth hits the recursion limit in
758 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
759 set to 1 and a RecursionError is raised. The overflowed flag is reset
760 to 0 when the recursion depth goes below the low-water mark: see
761 Py_LeaveRecursiveCall().
762
763 Reject too low new limit if the current recursion depth is higher than
764 the new low-water mark. Otherwise it may not be possible anymore to
765 reset the overflowed flag to 0. */
766 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100767 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200768 if (tstate->recursion_depth >= mark) {
769 PyErr_Format(PyExc_RecursionError,
770 "cannot set the recursion limit to %i at "
771 "the recursion depth %i: the limit is too low",
772 new_limit, tstate->recursion_depth);
773 return NULL;
774 }
775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200777 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000778}
779
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800780/*[clinic input]
781sys.set_coroutine_origin_tracking_depth
782
783 depth: int
784
785Enable or disable origin tracking for coroutine objects in this thread.
786
Tal Einatede0b6f2018-12-31 17:12:08 +0200787Coroutine objects will track 'depth' frames of traceback information
788about where they came from, available in their cr_origin attribute.
789
790Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800791[clinic start generated code]*/
792
793static PyObject *
794sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +0200795/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800796{
797 if (depth < 0) {
798 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
799 return NULL;
800 }
801 _PyEval_SetCoroutineOriginTrackingDepth(depth);
802 Py_RETURN_NONE;
803}
804
805/*[clinic input]
806sys.get_coroutine_origin_tracking_depth -> int
807
808Check status of origin tracking for coroutine objects in this thread.
809[clinic start generated code]*/
810
811static int
812sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
813/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
814{
815 return _PyEval_GetCoroutineOriginTrackingDepth();
816}
817
Tal Einatede0b6f2018-12-31 17:12:08 +0200818/*[clinic input]
819sys.set_coroutine_wrapper
820
821 wrapper: object
822 /
823
824Set a wrapper for coroutine objects.
825[clinic start generated code]*/
826
Yury Selivanov75445082015-05-11 22:57:16 -0400827static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200828sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
829/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400830{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800831 if (PyErr_WarnEx(PyExc_DeprecationWarning,
832 "set_coroutine_wrapper is deprecated", 1) < 0) {
833 return NULL;
834 }
835
Yury Selivanov75445082015-05-11 22:57:16 -0400836 if (wrapper != Py_None) {
837 if (!PyCallable_Check(wrapper)) {
838 PyErr_Format(PyExc_TypeError,
839 "callable expected, got %.50s",
840 Py_TYPE(wrapper)->tp_name);
841 return NULL;
842 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400843 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400844 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400845 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400846 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400847 }
Yury Selivanov75445082015-05-11 22:57:16 -0400848 Py_RETURN_NONE;
849}
850
Tal Einatede0b6f2018-12-31 17:12:08 +0200851/*[clinic input]
852sys.get_coroutine_wrapper
853
854Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
855[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400856
857static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200858sys_get_coroutine_wrapper_impl(PyObject *module)
859/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400860{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800861 if (PyErr_WarnEx(PyExc_DeprecationWarning,
862 "get_coroutine_wrapper is deprecated", 1) < 0) {
863 return NULL;
864 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400865 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400866 if (wrapper == NULL) {
867 wrapper = Py_None;
868 }
869 Py_INCREF(wrapper);
870 return wrapper;
871}
872
Yury Selivanov75445082015-05-11 22:57:16 -0400873
Yury Selivanoveb636452016-09-08 22:01:51 -0700874static PyTypeObject AsyncGenHooksType;
875
876PyDoc_STRVAR(asyncgen_hooks_doc,
877"asyncgen_hooks\n\
878\n\
879A struct sequence providing information about asynhronous\n\
880generators hooks. The attributes are read only.");
881
882static PyStructSequence_Field asyncgen_hooks_fields[] = {
883 {"firstiter", "Hook to intercept first iteration"},
884 {"finalizer", "Hook to intercept finalization"},
885 {0}
886};
887
888static PyStructSequence_Desc asyncgen_hooks_desc = {
889 "asyncgen_hooks", /* name */
890 asyncgen_hooks_doc, /* doc */
891 asyncgen_hooks_fields , /* fields */
892 2
893};
894
Yury Selivanoveb636452016-09-08 22:01:51 -0700895static PyObject *
896sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
897{
898 static char *keywords[] = {"firstiter", "finalizer", NULL};
899 PyObject *firstiter = NULL;
900 PyObject *finalizer = NULL;
901
902 if (!PyArg_ParseTupleAndKeywords(
903 args, kw, "|OO", keywords,
904 &firstiter, &finalizer)) {
905 return NULL;
906 }
907
908 if (finalizer && finalizer != Py_None) {
909 if (!PyCallable_Check(finalizer)) {
910 PyErr_Format(PyExc_TypeError,
911 "callable finalizer expected, got %.50s",
912 Py_TYPE(finalizer)->tp_name);
913 return NULL;
914 }
915 _PyEval_SetAsyncGenFinalizer(finalizer);
916 }
917 else if (finalizer == Py_None) {
918 _PyEval_SetAsyncGenFinalizer(NULL);
919 }
920
921 if (firstiter && firstiter != Py_None) {
922 if (!PyCallable_Check(firstiter)) {
923 PyErr_Format(PyExc_TypeError,
924 "callable firstiter expected, got %.50s",
925 Py_TYPE(firstiter)->tp_name);
926 return NULL;
927 }
928 _PyEval_SetAsyncGenFirstiter(firstiter);
929 }
930 else if (firstiter == Py_None) {
931 _PyEval_SetAsyncGenFirstiter(NULL);
932 }
933
934 Py_RETURN_NONE;
935}
936
937PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +0200938"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -0700939\n\
940Set a finalizer for async generators objects."
941);
942
Tal Einatede0b6f2018-12-31 17:12:08 +0200943/*[clinic input]
944sys.get_asyncgen_hooks
945
946Return the installed asynchronous generators hooks.
947
948This returns a namedtuple of the form (firstiter, finalizer).
949[clinic start generated code]*/
950
Yury Selivanoveb636452016-09-08 22:01:51 -0700951static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200952sys_get_asyncgen_hooks_impl(PyObject *module)
953/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -0700954{
955 PyObject *res;
956 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
957 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
958
959 res = PyStructSequence_New(&AsyncGenHooksType);
960 if (res == NULL) {
961 return NULL;
962 }
963
964 if (firstiter == NULL) {
965 firstiter = Py_None;
966 }
967
968 if (finalizer == NULL) {
969 finalizer = Py_None;
970 }
971
972 Py_INCREF(firstiter);
973 PyStructSequence_SET_ITEM(res, 0, firstiter);
974
975 Py_INCREF(finalizer);
976 PyStructSequence_SET_ITEM(res, 1, finalizer);
977
978 return res;
979}
980
Yury Selivanoveb636452016-09-08 22:01:51 -0700981
Mark Dickinsondc787d22010-05-23 13:33:13 +0000982static PyTypeObject Hash_InfoType;
983
984PyDoc_STRVAR(hash_info_doc,
985"hash_info\n\
986\n\
987A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100988hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000989
990static PyStructSequence_Field hash_info_fields[] = {
991 {"width", "width of the type used for hashing, in bits"},
992 {"modulus", "prime number giving the modulus on which the hash "
993 "function is based"},
994 {"inf", "value to be used for hash of a positive infinity"},
995 {"nan", "value to be used for hash of a nan"},
996 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100997 {"algorithm", "name of the algorithm for hashing of str, bytes and "
998 "memoryviews"},
999 {"hash_bits", "internal output size of hash algorithm"},
1000 {"seed_bits", "seed size of hash algorithm"},
1001 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001002 {NULL, NULL}
1003};
1004
1005static PyStructSequence_Desc hash_info_desc = {
1006 "sys.hash_info",
1007 hash_info_doc,
1008 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001009 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001010};
1011
Matthias Klosed885e952010-07-06 10:53:30 +00001012static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001013get_hash_info(void)
1014{
1015 PyObject *hash_info;
1016 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001017 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001018 hash_info = PyStructSequence_New(&Hash_InfoType);
1019 if (hash_info == NULL)
1020 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001021 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001022 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001023 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001024 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001025 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001026 PyStructSequence_SET_ITEM(hash_info, field++,
1027 PyLong_FromLong(_PyHASH_INF));
1028 PyStructSequence_SET_ITEM(hash_info, field++,
1029 PyLong_FromLong(_PyHASH_NAN));
1030 PyStructSequence_SET_ITEM(hash_info, field++,
1031 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001032 PyStructSequence_SET_ITEM(hash_info, field++,
1033 PyUnicode_FromString(hashfunc->name));
1034 PyStructSequence_SET_ITEM(hash_info, field++,
1035 PyLong_FromLong(hashfunc->hash_bits));
1036 PyStructSequence_SET_ITEM(hash_info, field++,
1037 PyLong_FromLong(hashfunc->seed_bits));
1038 PyStructSequence_SET_ITEM(hash_info, field++,
1039 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001040 if (PyErr_Occurred()) {
1041 Py_CLEAR(hash_info);
1042 return NULL;
1043 }
1044 return hash_info;
1045}
Tal Einatede0b6f2018-12-31 17:12:08 +02001046/*[clinic input]
1047sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001048
Tal Einatede0b6f2018-12-31 17:12:08 +02001049Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001050
Tal Einatede0b6f2018-12-31 17:12:08 +02001051The recursion limit is the maximum depth of the Python interpreter
1052stack. This limit prevents infinite recursion from causing an overflow
1053of the C stack and crashing Python.
1054[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001055
1056static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001057sys_getrecursionlimit_impl(PyObject *module)
1058/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001059{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001061}
1062
Mark Hammond8696ebc2002-10-08 02:44:31 +00001063#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001064
Eric Smithf7bb5782010-01-27 00:44:57 +00001065static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1066
1067static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 {"major", "Major version number"},
1069 {"minor", "Minor version number"},
1070 {"build", "Build number"},
1071 {"platform", "Operating system platform"},
1072 {"service_pack", "Latest Service Pack installed on the system"},
1073 {"service_pack_major", "Service Pack major version number"},
1074 {"service_pack_minor", "Service Pack minor version number"},
1075 {"suite_mask", "Bit mask identifying available product suites"},
1076 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001077 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001078 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001079};
1080
1081static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001082 "sys.getwindowsversion", /* name */
1083 sys_getwindowsversion__doc__, /* doc */
1084 windows_version_fields, /* fields */
1085 5 /* For backward compatibility,
1086 only the first 5 items are accessible
1087 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001088};
1089
Steve Dower3e96f322015-03-02 08:01:10 -08001090/* Disable deprecation warnings about GetVersionEx as the result is
1091 being passed straight through to the caller, who is responsible for
1092 using it correctly. */
1093#pragma warning(push)
1094#pragma warning(disable:4996)
1095
Tal Einatede0b6f2018-12-31 17:12:08 +02001096/*[clinic input]
1097sys.getwindowsversion
1098
1099Return info about the running version of Windows as a named tuple.
1100
1101The members are named: major, minor, build, platform, service_pack,
1102service_pack_major, service_pack_minor, suite_mask, product_type and
1103platform_version. For backward compatibility, only the first 5 items
1104are available by indexing. All elements are numbers, except
1105service_pack and platform_type which are strings, and platform_version
1106which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1107workstation, 2 for a domain controller, 3 for a server.
1108Platform_version is a 3-tuple containing a version number that is
1109intended for identifying the OS rather than feature detection.
1110[clinic start generated code]*/
1111
Mark Hammond8696ebc2002-10-08 02:44:31 +00001112static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001113sys_getwindowsversion_impl(PyObject *module)
1114/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 PyObject *version;
1117 int pos = 0;
1118 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001119 DWORD realMajor, realMinor, realBuild;
1120 HANDLE hKernel32;
1121 wchar_t kernel32_path[MAX_PATH];
1122 LPVOID verblock;
1123 DWORD verblock_size;
1124
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 ver.dwOSVersionInfoSize = sizeof(ver);
1126 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1127 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 version = PyStructSequence_New(&WindowsVersionType);
1130 if (version == NULL)
1131 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001132
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001133 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1134 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1135 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1136 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1137 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1138 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1139 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1140 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1141 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001142
Steve Dower74f4af72016-09-17 17:27:48 -07001143 realMajor = ver.dwMajorVersion;
1144 realMinor = ver.dwMinorVersion;
1145 realBuild = ver.dwBuildNumber;
1146
1147 // GetVersion will lie if we are running in a compatibility mode.
1148 // We need to read the version info from a system file resource
1149 // to accurately identify the OS version. If we fail for any reason,
1150 // just return whatever GetVersion said.
1151 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1152 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1153 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1154 (verblock = PyMem_RawMalloc(verblock_size))) {
1155 VS_FIXEDFILEINFO *ffi;
1156 UINT ffi_len;
1157
1158 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1159 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1160 realMajor = HIWORD(ffi->dwProductVersionMS);
1161 realMinor = LOWORD(ffi->dwProductVersionMS);
1162 realBuild = HIWORD(ffi->dwProductVersionLS);
1163 }
1164 PyMem_RawFree(verblock);
1165 }
Segev Finer48fb7662017-06-04 20:52:27 +03001166 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1167 realMajor,
1168 realMinor,
1169 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001170 ));
1171
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001172 if (PyErr_Occurred()) {
1173 Py_DECREF(version);
1174 return NULL;
1175 }
Steve Dower74f4af72016-09-17 17:27:48 -07001176
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001178}
1179
Steve Dower3e96f322015-03-02 08:01:10 -08001180#pragma warning(pop)
1181
Tal Einatede0b6f2018-12-31 17:12:08 +02001182/*[clinic input]
1183sys._enablelegacywindowsfsencoding
1184
1185Changes the default filesystem encoding to mbcs:replace.
1186
1187This is done for consistency with earlier versions of Python. See PEP
1188529 for more information.
1189
1190This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1191environment variable before launching Python.
1192[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001193
1194static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001195sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1196/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001197{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001198 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1199 _PyCoreConfig *config = &interp->core_config;
1200
1201 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1202 char *encoding = _PyMem_RawStrdup("mbcs");
1203 char *errors = _PyMem_RawStrdup("replace");
1204 if (encoding == NULL || errors == NULL) {
1205 PyMem_Free(encoding);
1206 PyMem_Free(errors);
1207 PyErr_NoMemory();
1208 return NULL;
1209 }
1210
1211 PyMem_RawFree(config->filesystem_encoding);
1212 config->filesystem_encoding = encoding;
1213 PyMem_RawFree(config->filesystem_errors);
1214 config->filesystem_errors = errors;
1215
1216 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1217 config->filesystem_errors) < 0) {
1218 PyErr_NoMemory();
1219 return NULL;
1220 }
1221
Steve Dowercc16be82016-09-08 10:35:16 -07001222 Py_RETURN_NONE;
1223}
1224
Mark Hammond8696ebc2002-10-08 02:44:31 +00001225#endif /* MS_WINDOWS */
1226
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001227#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001228
1229/*[clinic input]
1230sys.setdlopenflags
1231
1232 flags as new_val: int
1233 /
1234
1235Set the flags used by the interpreter for dlopen calls.
1236
1237This is used, for example, when the interpreter loads extension
1238modules. Among other things, this will enable a lazy resolving of
1239symbols when importing a module, if called as sys.setdlopenflags(0).
1240To share symbols across extension modules, call as
1241sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1242modules can be found in the os module (RTLD_xxx constants, e.g.
1243os.RTLD_LAZY).
1244[clinic start generated code]*/
1245
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001246static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001247sys_setdlopenflags_impl(PyObject *module, int new_val)
1248/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001249{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001250 PyInterpreterState *interp = _PyInterpreterState_Get();
1251 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001252 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001253}
1254
Tal Einatede0b6f2018-12-31 17:12:08 +02001255
1256/*[clinic input]
1257sys.getdlopenflags
1258
1259Return the current value of the flags that are used for dlopen calls.
1260
1261The flag constants are defined in the os module.
1262[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001263
1264static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001265sys_getdlopenflags_impl(PyObject *module)
1266/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001267{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001268 PyInterpreterState *interp = _PyInterpreterState_Get();
1269 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001270}
1271
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001272#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001273
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001274#ifdef USE_MALLOPT
1275/* Link with -lmalloc (or -lmpc) on an SGI */
1276#include <malloc.h>
1277
Tal Einatede0b6f2018-12-31 17:12:08 +02001278/*[clinic input]
1279sys.mdebug
1280
1281 flag: int
1282 /
1283[clinic start generated code]*/
1284
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001285static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001286sys_mdebug_impl(PyObject *module, int flag)
1287/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001288{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001291 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001292}
1293#endif /* USE_MALLOPT */
1294
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001295size_t
1296_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001300 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001301
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 /* Make sure the type is initialized. float gets initialized late */
1303 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001304 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001305
Benjamin Petersonce798522012-01-22 11:24:29 -05001306 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 if (method == NULL) {
1308 if (!PyErr_Occurred())
1309 PyErr_Format(PyExc_TypeError,
1310 "Type %.100s doesn't define __sizeof__",
1311 Py_TYPE(o)->tp_name);
1312 }
1313 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001314 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 Py_DECREF(method);
1316 }
1317
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001318 if (res == NULL)
1319 return (size_t)-1;
1320
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001321 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001322 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001323 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001324 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001326 if (size < 0) {
1327 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1328 return (size_t)-1;
1329 }
1330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001332 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001333 return ((size_t)size) + sizeof(PyGC_Head);
1334 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001335}
1336
1337static PyObject *
1338sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1339{
1340 static char *kwlist[] = {"object", "default", 0};
1341 size_t size;
1342 PyObject *o, *dflt = NULL;
1343
1344 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1345 kwlist, &o, &dflt))
1346 return NULL;
1347
1348 size = _PySys_GetSizeOf(o);
1349
1350 if (size == (size_t)-1 && PyErr_Occurred()) {
1351 /* Has a default value been given */
1352 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1353 PyErr_Clear();
1354 Py_INCREF(dflt);
1355 return dflt;
1356 }
1357 else
1358 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001360
1361 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001362}
1363
1364PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001365"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001366\n\
1367Return the size of object in bytes.");
1368
Tal Einatede0b6f2018-12-31 17:12:08 +02001369/*[clinic input]
1370sys.getrefcount -> Py_ssize_t
1371
1372 object: object
1373 /
1374
1375Return the reference count of object.
1376
1377The count returned is generally one higher than you might expect,
1378because it includes the (temporary) reference as an argument to
1379getrefcount().
1380[clinic start generated code]*/
1381
1382static Py_ssize_t
1383sys_getrefcount_impl(PyObject *module, PyObject *object)
1384/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001385{
Tal Einatede0b6f2018-12-31 17:12:08 +02001386 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001387}
1388
Tim Peters4be93d02002-07-07 19:59:50 +00001389#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001390/*[clinic input]
1391sys.gettotalrefcount -> Py_ssize_t
1392[clinic start generated code]*/
1393
1394static Py_ssize_t
1395sys_gettotalrefcount_impl(PyObject *module)
1396/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001397{
Tal Einatede0b6f2018-12-31 17:12:08 +02001398 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001399}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001400#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001401
Tal Einatede0b6f2018-12-31 17:12:08 +02001402/*[clinic input]
1403sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001404
Tal Einatede0b6f2018-12-31 17:12:08 +02001405Return the number of memory blocks currently allocated.
1406[clinic start generated code]*/
1407
1408static Py_ssize_t
1409sys_getallocatedblocks_impl(PyObject *module)
1410/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001411{
Tal Einatede0b6f2018-12-31 17:12:08 +02001412 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001413}
1414
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001415#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001416/*[clinic input]
1417sys.getcounts
1418[clinic start generated code]*/
1419
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001420static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001421sys_getcounts_impl(PyObject *module)
1422/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001423{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001424 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001425
Pablo Galindo49c75a82018-10-28 15:02:17 +00001426 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001427}
1428#endif
1429
Tal Einatede0b6f2018-12-31 17:12:08 +02001430/*[clinic input]
1431sys._getframe
1432
1433 depth: int = 0
1434 /
1435
1436Return a frame object from the call stack.
1437
1438If optional integer depth is given, return the frame object that many
1439calls below the top of the stack. If that is deeper than the call
1440stack, ValueError is raised. The default for depth is zero, returning
1441the frame at the top of the call stack.
1442
1443This function should be used for internal and specialized purposes
1444only.
1445[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001446
1447static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001448sys__getframe_impl(PyObject *module, int depth)
1449/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001450{
Victor Stinner50b48572018-11-01 01:51:40 +01001451 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 while (depth > 0 && f != NULL) {
1454 f = f->f_back;
1455 --depth;
1456 }
1457 if (f == NULL) {
1458 PyErr_SetString(PyExc_ValueError,
1459 "call stack is not deep enough");
1460 return NULL;
1461 }
1462 Py_INCREF(f);
1463 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001464}
1465
Tal Einatede0b6f2018-12-31 17:12:08 +02001466/*[clinic input]
1467sys._current_frames
1468
1469Return a dict mapping each thread's thread id to its current stack frame.
1470
1471This function should be used for specialized purposes only.
1472[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001473
1474static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001475sys__current_frames_impl(PyObject *module)
1476/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001478 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001479}
1480
Tal Einatede0b6f2018-12-31 17:12:08 +02001481/*[clinic input]
1482sys.call_tracing
1483
1484 func: object
1485 args as funcargs: object(subclass_of='&PyTuple_Type')
1486 /
1487
1488Call func(*args), while tracing is enabled.
1489
1490The tracing state is saved, and restored afterwards. This is intended
1491to be called from a debugger from a checkpoint, to recursively debug
1492some other code.
1493[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001494
1495static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001496sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1497/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001500}
1501
Tal Einatede0b6f2018-12-31 17:12:08 +02001502/*[clinic input]
1503sys.callstats
1504
1505Return a tuple of function call statistics.
1506
1507A tuple is returned only if CALL_PROFILE was defined when Python was
1508built. Otherwise, this returns None.
1509
1510When enabled, this function returns detailed, implementation-specific
1511details about the number of function calls executed. The return value
1512is a 11-tuple where the entries in the tuple are counts of:
15130. all function calls
15141. calls to PyFunction_Type objects
15152. PyFunction calls that do not create an argument tuple
15163. PyFunction calls that do not create an argument tuple
1517 and bypass PyEval_EvalCodeEx()
15184. PyMethod calls
15195. PyMethod calls on bound methods
15206. PyType calls
15217. PyCFunction calls
15228. generator calls
15239. All other calls
152410. Number of stack pops performed by call_function()
1525[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001526
Victor Stinner048afd92016-11-28 11:59:04 +01001527static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001528sys_callstats_impl(PyObject *module)
1529/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001530{
1531 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1532 "sys.callstats() has been deprecated in Python 3.7 "
1533 "and will be removed in the future", 1) < 0) {
1534 return NULL;
1535 }
1536
1537 Py_RETURN_NONE;
1538}
1539
1540
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001541#ifdef __cplusplus
1542extern "C" {
1543#endif
1544
Tal Einatede0b6f2018-12-31 17:12:08 +02001545/*[clinic input]
1546sys._debugmallocstats
1547
1548Print summary info to stderr about the state of pymalloc's structures.
1549
1550In Py_DEBUG mode, also perform some expensive internal consistency
1551checks.
1552[clinic start generated code]*/
1553
David Malcolm49526f42012-06-22 14:55:41 -04001554static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001555sys__debugmallocstats_impl(PyObject *module)
1556/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001557{
1558#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001559 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001560 fputc('\n', stderr);
1561 }
David Malcolm49526f42012-06-22 14:55:41 -04001562#endif
1563 _PyObject_DebugTypeStats(stderr);
1564
1565 Py_RETURN_NONE;
1566}
David Malcolm49526f42012-06-22 14:55:41 -04001567
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001568#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001569/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001570extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001571#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001572
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001573#ifdef DYNAMIC_EXECUTION_PROFILE
1574/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001575extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001576#endif
1577
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001578#ifdef __cplusplus
1579}
1580#endif
1581
Tal Einatede0b6f2018-12-31 17:12:08 +02001582
1583/*[clinic input]
1584sys._clear_type_cache
1585
1586Clear the internal type lookup cache.
1587[clinic start generated code]*/
1588
Christian Heimes15ebc882008-02-04 18:48:49 +00001589static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001590sys__clear_type_cache_impl(PyObject *module)
1591/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001592{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 PyType_ClearCache();
1594 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001595}
1596
Tal Einatede0b6f2018-12-31 17:12:08 +02001597/*[clinic input]
1598sys.is_finalizing
1599
1600Return True if Python is exiting.
1601[clinic start generated code]*/
1602
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001603static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001604sys_is_finalizing_impl(PyObject *module)
1605/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001606{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001607 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001608}
1609
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001610#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001611/*[clinic input]
1612sys.getandroidapilevel
1613
1614Return the build time API version of Android as an integer.
1615[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001616
1617static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001618sys_getandroidapilevel_impl(PyObject *module)
1619/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001620{
1621 return PyLong_FromLong(ANDROID_API_LEVEL);
1622}
1623#endif /* ANDROID_API_LEVEL */
1624
1625
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001626static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001628 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001629 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001630 SYS_CALLSTATS_METHODDEF
1631 SYS__CLEAR_TYPE_CACHE_METHODDEF
1632 SYS__CURRENT_FRAMES_METHODDEF
1633 SYS_DISPLAYHOOK_METHODDEF
1634 SYS_EXC_INFO_METHODDEF
1635 SYS_EXCEPTHOOK_METHODDEF
1636 SYS_EXIT_METHODDEF
1637 SYS_GETDEFAULTENCODING_METHODDEF
1638 SYS_GETDLOPENFLAGS_METHODDEF
1639 SYS_GETALLOCATEDBLOCKS_METHODDEF
1640 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001641#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001643#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001644 SYS_GETFILESYSTEMENCODING_METHODDEF
1645 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001646#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001648#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001649 SYS_GETTOTALREFCOUNT_METHODDEF
1650 SYS_GETREFCOUNT_METHODDEF
1651 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001652 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001654 SYS__GETFRAME_METHODDEF
1655 SYS_GETWINDOWSVERSION_METHODDEF
1656 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1657 SYS_INTERN_METHODDEF
1658 SYS_IS_FINALIZING_METHODDEF
1659 SYS_MDEBUG_METHODDEF
1660 SYS_SETCHECKINTERVAL_METHODDEF
1661 SYS_GETCHECKINTERVAL_METHODDEF
1662 SYS_SETSWITCHINTERVAL_METHODDEF
1663 SYS_GETSWITCHINTERVAL_METHODDEF
1664 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001666 SYS_GETPROFILE_METHODDEF
1667 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001669 SYS_GETTRACE_METHODDEF
1670 SYS_CALL_TRACING_METHODDEF
1671 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001672 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1673 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001674 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1675 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001676 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001677 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001678 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1679 SYS_GETANDROIDAPILEVEL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001681};
1682
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001683static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001684list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001686 PyObject *list = PyList_New(0);
1687 int i;
1688 if (list == NULL)
1689 return NULL;
1690 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1691 PyObject *name = PyUnicode_FromString(
1692 PyImport_Inittab[i].name);
1693 if (name == NULL)
1694 break;
1695 PyList_Append(list, name);
1696 Py_DECREF(name);
1697 }
1698 if (PyList_Sort(list) != 0) {
1699 Py_DECREF(list);
1700 list = NULL;
1701 }
1702 if (list) {
1703 PyObject *v = PyList_AsTuple(list);
1704 Py_DECREF(list);
1705 list = v;
1706 }
1707 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001708}
1709
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001710/* Pre-initialization support for sys.warnoptions and sys._xoptions
1711 *
1712 * Modern internal code paths:
1713 * These APIs get called after _Py_InitializeCore and get to use the
1714 * regular CPython list, dict, and unicode APIs.
1715 *
1716 * Legacy embedding code paths:
1717 * The multi-phase initialization API isn't public yet, so embedding
1718 * apps still need to be able configure sys.warnoptions and sys._xoptions
1719 * before they call Py_Initialize. To support this, we stash copies of
1720 * the supplied wchar * sequences in linked lists, and then migrate the
1721 * contents of those lists to the sys module in _PyInitializeCore.
1722 *
1723 */
1724
1725struct _preinit_entry {
1726 wchar_t *value;
1727 struct _preinit_entry *next;
1728};
1729
1730typedef struct _preinit_entry *_Py_PreInitEntry;
1731
1732static _Py_PreInitEntry _preinit_warnoptions = NULL;
1733static _Py_PreInitEntry _preinit_xoptions = NULL;
1734
1735static _Py_PreInitEntry
1736_alloc_preinit_entry(const wchar_t *value)
1737{
1738 /* To get this to work, we have to initialize the runtime implicitly */
1739 _PyRuntime_Initialize();
1740
1741 /* Force default allocator, so we can ensure that it also gets used to
1742 * destroy the linked list in _clear_preinit_entries.
1743 */
1744 PyMemAllocatorEx old_alloc;
1745 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1746
1747 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1748 if (node != NULL) {
1749 node->value = _PyMem_RawWcsdup(value);
1750 if (node->value == NULL) {
1751 PyMem_RawFree(node);
1752 node = NULL;
1753 };
1754 };
1755
1756 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1757 return node;
1758};
1759
1760static int
1761_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1762{
1763 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1764 if (new_entry == NULL) {
1765 return -1;
1766 }
1767 /* We maintain the linked list in this order so it's easy to play back
1768 * the add commands in the same order later on in _Py_InitializeCore
1769 */
1770 _Py_PreInitEntry last_entry = *optionlist;
1771 if (last_entry == NULL) {
1772 *optionlist = new_entry;
1773 } else {
1774 while (last_entry->next != NULL) {
1775 last_entry = last_entry->next;
1776 }
1777 last_entry->next = new_entry;
1778 }
1779 return 0;
1780};
1781
1782static void
1783_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1784{
1785 _Py_PreInitEntry current = *optionlist;
1786 *optionlist = NULL;
1787 /* Deallocate the nodes and their contents using the default allocator */
1788 PyMemAllocatorEx old_alloc;
1789 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1790 while (current != NULL) {
1791 _Py_PreInitEntry next = current->next;
1792 PyMem_RawFree(current->value);
1793 PyMem_RawFree(current);
1794 current = next;
1795 }
1796 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1797};
1798
1799static void
1800_clear_all_preinit_options(void)
1801{
1802 _clear_preinit_entries(&_preinit_warnoptions);
1803 _clear_preinit_entries(&_preinit_xoptions);
1804}
1805
1806static int
1807_PySys_ReadPreInitOptions(void)
1808{
1809 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001810 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001811 if (tstate == NULL) {
1812 /* Still don't have a thread state, so something is wrong! */
1813 return -1;
1814 }
1815 _Py_PreInitEntry entry = _preinit_warnoptions;
1816 while (entry != NULL) {
1817 PySys_AddWarnOption(entry->value);
1818 entry = entry->next;
1819 }
1820 entry = _preinit_xoptions;
1821 while (entry != NULL) {
1822 PySys_AddXOption(entry->value);
1823 entry = entry->next;
1824 }
1825
1826 _clear_all_preinit_options();
1827 return 0;
1828};
1829
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001830static PyObject *
1831get_warnoptions(void)
1832{
Eric Snowdae02762017-09-14 00:35:58 -07001833 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001834 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001835 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1836 * interpreter config. When that happens, we need to properly set
1837 * the `warnoptions` reference in the main interpreter config as well.
1838 *
1839 * For Python 3.7, we shouldn't be able to get here due to the
1840 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1841 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1842 * call optional for embedding applications, thus making this
1843 * reachable again.
1844 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001845 warnoptions = PyList_New(0);
1846 if (warnoptions == NULL)
1847 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001848 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1849 Py_DECREF(warnoptions);
1850 return NULL;
1851 }
1852 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001853 }
1854 return warnoptions;
1855}
Guido van Rossum23fff912000-12-15 22:02:05 +00001856
1857void
1858PySys_ResetWarnOptions(void)
1859{
Victor Stinner50b48572018-11-01 01:51:40 +01001860 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001861 if (tstate == NULL) {
1862 _clear_preinit_entries(&_preinit_warnoptions);
1863 return;
1864 }
1865
Eric Snowdae02762017-09-14 00:35:58 -07001866 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 if (warnoptions == NULL || !PyList_Check(warnoptions))
1868 return;
1869 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001870}
1871
Victor Stinnere1b29952018-10-30 14:31:42 +01001872static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001873_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001874{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001875 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001876 if (warnoptions == NULL) {
1877 return -1;
1878 }
1879 if (PyList_Append(warnoptions, option)) {
1880 return -1;
1881 }
1882 return 0;
1883}
1884
1885void
1886PySys_AddWarnOptionUnicode(PyObject *option)
1887{
Victor Stinnere1b29952018-10-30 14:31:42 +01001888 if (_PySys_AddWarnOptionWithError(option) < 0) {
1889 /* No return value, therefore clear error state if possible */
1890 if (_PyThreadState_UncheckedGet()) {
1891 PyErr_Clear();
1892 }
1893 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001894}
1895
1896void
1897PySys_AddWarnOption(const wchar_t *s)
1898{
Victor Stinner50b48572018-11-01 01:51:40 +01001899 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001900 if (tstate == NULL) {
1901 _append_preinit_entry(&_preinit_warnoptions, s);
1902 return;
1903 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001904 PyObject *unicode;
1905 unicode = PyUnicode_FromWideChar(s, -1);
1906 if (unicode == NULL)
1907 return;
1908 PySys_AddWarnOptionUnicode(unicode);
1909 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001910}
1911
Christian Heimes33fe8092008-04-13 13:53:33 +00001912int
1913PySys_HasWarnOptions(void)
1914{
Eric Snowdae02762017-09-14 00:35:58 -07001915 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001916 return (warnoptions != NULL && PyList_Check(warnoptions)
1917 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001918}
1919
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001920static PyObject *
1921get_xoptions(void)
1922{
Eric Snowdae02762017-09-14 00:35:58 -07001923 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001924 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001925 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1926 * interpreter config. When that happens, we need to properly set
1927 * the `xoptions` reference in the main interpreter config as well.
1928 *
1929 * For Python 3.7, we shouldn't be able to get here due to the
1930 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1931 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1932 * call optional for embedding applications, thus making this
1933 * reachable again.
1934 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001935 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001936 if (xoptions == NULL)
1937 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001938 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1939 Py_DECREF(xoptions);
1940 return NULL;
1941 }
1942 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001943 }
1944 return xoptions;
1945}
1946
Victor Stinnere1b29952018-10-30 14:31:42 +01001947static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001948_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001949{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001950 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001951
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001952 PyObject *opts = get_xoptions();
1953 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001954 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001955 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001956
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001957 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001958 if (!name_end) {
1959 name = PyUnicode_FromWideChar(s, -1);
1960 value = Py_True;
1961 Py_INCREF(value);
1962 }
1963 else {
1964 name = PyUnicode_FromWideChar(s, name_end - s);
1965 value = PyUnicode_FromWideChar(name_end + 1, -1);
1966 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001967 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001968 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001969 }
1970 if (PyDict_SetItem(opts, name, value) < 0) {
1971 goto error;
1972 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001973 Py_DECREF(name);
1974 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001976
1977error:
1978 Py_XDECREF(name);
1979 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001980 return -1;
1981}
1982
1983void
1984PySys_AddXOption(const wchar_t *s)
1985{
Victor Stinner50b48572018-11-01 01:51:40 +01001986 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001987 if (tstate == NULL) {
1988 _append_preinit_entry(&_preinit_xoptions, s);
1989 return;
1990 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001991 if (_PySys_AddXOptionWithError(s) < 0) {
1992 /* No return value, therefore clear error state if possible */
1993 if (_PyThreadState_UncheckedGet()) {
1994 PyErr_Clear();
1995 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001996 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001997}
1998
1999PyObject *
2000PySys_GetXOptions(void)
2001{
2002 return get_xoptions();
2003}
2004
Guido van Rossum40552d01998-08-06 03:34:39 +00002005/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2006 Two literals concatenated works just fine. If you have a K&R compiler
2007 or other abomination that however *does* understand longer strings,
2008 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002009PyDoc_VAR(sys_doc) =
2010PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002011"This module provides access to some objects used or maintained by the\n\
2012interpreter and to functions that interact strongly with the interpreter.\n\
2013\n\
2014Dynamic objects:\n\
2015\n\
2016argv -- command line arguments; argv[0] is the script pathname if known\n\
2017path -- module search path; path[0] is the script directory, else ''\n\
2018modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002019\n\
2020displayhook -- called to show results in an interactive session\n\
2021excepthook -- called to handle any uncaught exception other than SystemExit\n\
2022 To customize printing in an interactive session or to install a custom\n\
2023 top-level exception handler, assign other functions to replace these.\n\
2024\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002025stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002026stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002027stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002028 By assigning other file objects (or objects that behave like files)\n\
2029 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002030\n\
2031last_type -- type of last uncaught exception\n\
2032last_value -- value of last uncaught exception\n\
2033last_traceback -- traceback of last uncaught exception\n\
2034 These three are only available in an interactive session after a\n\
2035 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002036"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002037)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002038/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002039PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002040"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002041Static objects:\n\
2042\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002043builtin_module_names -- tuple of module names built into this interpreter\n\
2044copyright -- copyright notice pertaining to this interpreter\n\
2045exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002046executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002047float_info -- a struct sequence with information about the float implementation.\n\
2048float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002049hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002050hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002051implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002052int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002053maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002054maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002055platform -- platform identifier\n\
2056prefix -- prefix used to find the Python library\n\
2057thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002058version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002059version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002060"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002061)
Steve Dowercc16be82016-09-08 10:35:16 -07002062#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002063/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002064PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002065"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002066winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002067"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002068)
Steve Dowercc16be82016-09-08 10:35:16 -07002069#endif /* MS_COREDLL */
2070#ifdef MS_WINDOWS
2071/* concatenating string here */
2072PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002073"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002074"
2075)
2076#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002077PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002078"__stdin__ -- the original stdin; don't touch!\n\
2079__stdout__ -- the original stdout; don't touch!\n\
2080__stderr__ -- the original stderr; don't touch!\n\
2081__displayhook__ -- the original displayhook; don't touch!\n\
2082__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002083\n\
2084Functions:\n\
2085\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002086displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002087excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002088exc_info() -- return thread-safe information about the current exception\n\
2089exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002090getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002091getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002092getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002093getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002094getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002095gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002096setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002097setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002098setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002099setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002100settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002101"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002102)
Fred Drakeccede592000-08-14 20:59:57 +00002103/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002104
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002105
2106PyDoc_STRVAR(flags__doc__,
2107"sys.flags\n\
2108\n\
2109Flags provided through command line arguments or environment vars.");
2110
2111static PyTypeObject FlagsType;
2112
2113static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 {"inspect", "-i"},
2116 {"interactive", "-i"},
2117 {"optimize", "-O or -OO"},
2118 {"dont_write_bytecode", "-B"},
2119 {"no_user_site", "-s"},
2120 {"no_site", "-S"},
2121 {"ignore_environment", "-E"},
2122 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 /* {"unbuffered", "-u"}, */
2124 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002125 {"bytes_warning", "-b"},
2126 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002127 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002128 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002129 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002130 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002132};
2133
2134static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 "sys.flags", /* name */
2136 flags__doc__, /* doc */
2137 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002138 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002139};
2140
2141static PyObject*
2142make_flags(void)
2143{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 int pos = 0;
2145 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002146 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002147
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 seq = PyStructSequence_New(&FlagsType);
2149 if (seq == NULL)
2150 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002151
2152#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002153 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002154
Victor Stinnerfbca9082018-08-30 00:50:45 +02002155 SetFlag(config->parser_debug);
2156 SetFlag(config->inspect);
2157 SetFlag(config->interactive);
2158 SetFlag(config->optimization_level);
2159 SetFlag(!config->write_bytecode);
2160 SetFlag(!config->user_site_directory);
2161 SetFlag(!config->site_import);
2162 SetFlag(!config->use_environment);
2163 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 /* SetFlag(saw_unbuffered_flag); */
2165 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002166 SetFlag(config->bytes_warning);
2167 SetFlag(config->quiet);
2168 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2169 SetFlag(config->isolated);
2170 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2171 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002172#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002173
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002175 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002176 return NULL;
2177 }
2178 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002179}
2180
Eric Smith0e5b5622009-02-06 01:32:42 +00002181PyDoc_STRVAR(version_info__doc__,
2182"sys.version_info\n\
2183\n\
2184Version information as a named tuple.");
2185
2186static PyTypeObject VersionInfoType;
2187
2188static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 {"major", "Major release number"},
2190 {"minor", "Minor release number"},
2191 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002192 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 {"serial", "Serial release number"},
2194 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002195};
2196
2197static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002198 "sys.version_info", /* name */
2199 version_info__doc__, /* doc */
2200 version_info_fields, /* fields */
2201 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002202};
2203
2204static PyObject *
2205make_version_info(void)
2206{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 PyObject *version_info;
2208 char *s;
2209 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002210
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002211 version_info = PyStructSequence_New(&VersionInfoType);
2212 if (version_info == NULL) {
2213 return NULL;
2214 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002215
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002216 /*
2217 * These release level checks are mutually exclusive and cover
2218 * the field, so don't get too fancy with the pre-processor!
2219 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002220#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002222#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002224#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002226#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002228#endif
2229
2230#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002232#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002234
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 SetIntItem(PY_MAJOR_VERSION);
2236 SetIntItem(PY_MINOR_VERSION);
2237 SetIntItem(PY_MICRO_VERSION);
2238 SetStrItem(s);
2239 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002240#undef SetIntItem
2241#undef SetStrItem
2242
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 if (PyErr_Occurred()) {
2244 Py_CLEAR(version_info);
2245 return NULL;
2246 }
2247 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002248}
2249
Brett Cannon3adc7b72012-07-09 14:22:12 -04002250/* sys.implementation values */
2251#define NAME "cpython"
2252const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002253#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2254#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002255#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002256const char *_PySys_ImplCacheTag = TAG;
2257#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002258#undef MAJOR
2259#undef MINOR
2260#undef TAG
2261
Barry Warsaw409da152012-06-03 16:18:47 -04002262static PyObject *
2263make_impl_info(PyObject *version_info)
2264{
2265 int res;
2266 PyObject *impl_info, *value, *ns;
2267
2268 impl_info = PyDict_New();
2269 if (impl_info == NULL)
2270 return NULL;
2271
2272 /* populate the dict */
2273
Brett Cannon3adc7b72012-07-09 14:22:12 -04002274 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002275 if (value == NULL)
2276 goto error;
2277 res = PyDict_SetItemString(impl_info, "name", value);
2278 Py_DECREF(value);
2279 if (res < 0)
2280 goto error;
2281
Brett Cannon3adc7b72012-07-09 14:22:12 -04002282 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002283 if (value == NULL)
2284 goto error;
2285 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2286 Py_DECREF(value);
2287 if (res < 0)
2288 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002289
2290 res = PyDict_SetItemString(impl_info, "version", version_info);
2291 if (res < 0)
2292 goto error;
2293
2294 value = PyLong_FromLong(PY_VERSION_HEX);
2295 if (value == NULL)
2296 goto error;
2297 res = PyDict_SetItemString(impl_info, "hexversion", value);
2298 Py_DECREF(value);
2299 if (res < 0)
2300 goto error;
2301
doko@ubuntu.com55532312016-06-14 08:55:19 +02002302#ifdef MULTIARCH
2303 value = PyUnicode_FromString(MULTIARCH);
2304 if (value == NULL)
2305 goto error;
2306 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2307 Py_DECREF(value);
2308 if (res < 0)
2309 goto error;
2310#endif
2311
Barry Warsaw409da152012-06-03 16:18:47 -04002312 /* dict ready */
2313
2314 ns = _PyNamespace_New(impl_info);
2315 Py_DECREF(impl_info);
2316 return ns;
2317
2318error:
2319 Py_CLEAR(impl_info);
2320 return NULL;
2321}
2322
Martin v. Löwis1a214512008-06-11 05:26:20 +00002323static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002324 PyModuleDef_HEAD_INIT,
2325 "sys",
2326 sys_doc,
2327 -1, /* multiple "initialization" just copies the module dict. */
2328 sys_methods,
2329 NULL,
2330 NULL,
2331 NULL,
2332 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002333};
2334
Eric Snow6b4be192017-05-22 21:36:03 -07002335/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002336#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002337 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002338 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002339 if (v == NULL) { \
2340 goto err_occurred; \
2341 } \
Victor Stinner58049602013-07-22 22:40:00 +02002342 res = PyDict_SetItemString(sysdict, key, v); \
2343 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002344 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002345 } \
2346 } while (0)
2347#define SET_SYS_FROM_STRING(key, value) \
2348 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002349 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002350 if (v == NULL) { \
2351 goto err_occurred; \
2352 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002353 res = PyDict_SetItemString(sysdict, key, v); \
2354 Py_DECREF(v); \
2355 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002356 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002357 } \
2358 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002359
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002360
2361_PyInitError
2362_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002363{
2364 PyObject *m, *sysdict, *version_info;
2365 int res;
2366
Eric Snowd393c1b2017-09-14 12:18:12 -06002367 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002368 if (m == NULL) {
2369 return _Py_INIT_ERR("failed to create a module object");
2370 }
Eric Snow6b4be192017-05-22 21:36:03 -07002371 sysdict = PyModule_GetDict(m);
2372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002373 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002374 Using shell redirection, you can redirect stdin to a directory,
2375 crashing the Python interpreter. Catch this common mistake here
2376 and output a useful error message. Note that under MS Windows,
2377 the shell already prevents that. */
2378#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002380 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002381 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002382 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002383 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2384 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002385 }
2386 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002387#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002388
Nick Coghland6009512014-11-20 21:39:37 +10002389 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002390
Victor Stinner8fea2522013-10-27 17:15:42 +01002391 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2392 PyDict_GetItemString(sysdict, "displayhook"));
2393 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2394 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002395 SET_SYS_FROM_STRING_BORROW(
2396 "__breakpointhook__",
2397 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 SET_SYS_FROM_STRING("version",
2399 PyUnicode_FromString(Py_GetVersion()));
2400 SET_SYS_FROM_STRING("hexversion",
2401 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002402 SET_SYS_FROM_STRING("_git",
2403 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2404 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002405 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 SET_SYS_FROM_STRING("api_version",
2407 PyLong_FromLong(PYTHON_API_VERSION));
2408 SET_SYS_FROM_STRING("copyright",
2409 PyUnicode_FromString(Py_GetCopyright()));
2410 SET_SYS_FROM_STRING("platform",
2411 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002412 SET_SYS_FROM_STRING("maxsize",
2413 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2414 SET_SYS_FROM_STRING("float_info",
2415 PyFloat_GetInfo());
2416 SET_SYS_FROM_STRING("int_info",
2417 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002418 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002419 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002420 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2421 goto type_init_failed;
2422 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002423 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002424 SET_SYS_FROM_STRING("hash_info",
2425 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002426 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002427 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 SET_SYS_FROM_STRING("builtin_module_names",
2429 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002430#if PY_BIG_ENDIAN
2431 SET_SYS_FROM_STRING("byteorder",
2432 PyUnicode_FromString("big"));
2433#else
2434 SET_SYS_FROM_STRING("byteorder",
2435 PyUnicode_FromString("little"));
2436#endif
Fred Drake099325e2000-08-14 15:47:03 +00002437
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002438#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002439 SET_SYS_FROM_STRING("dllhandle",
2440 PyLong_FromVoidPtr(PyWin_DLLhModule));
2441 SET_SYS_FROM_STRING("winver",
2442 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002443#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002444#ifdef ABIFLAGS
2445 SET_SYS_FROM_STRING("abiflags",
2446 PyUnicode_FromString(ABIFLAGS));
2447#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002449 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002450 if (VersionInfoType.tp_name == NULL) {
2451 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002452 &version_info_desc) < 0) {
2453 goto type_init_failed;
2454 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002455 }
Barry Warsaw409da152012-06-03 16:18:47 -04002456 version_info = make_version_info();
2457 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* prevent user from creating new instances */
2459 VersionInfoType.tp_init = NULL;
2460 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002461 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2462 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2463 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002464
Barry Warsaw409da152012-06-03 16:18:47 -04002465 /* implementation */
2466 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002469 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002470 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2471 goto type_init_failed;
2472 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002473 }
Eric Snow6b4be192017-05-22 21:36:03 -07002474 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002475 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002476
2477#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* getwindowsversion */
2479 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002480 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002481 &windows_version_desc) < 0) {
2482 goto type_init_failed;
2483 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 /* prevent user from creating new instances */
2485 WindowsVersionType.tp_init = NULL;
2486 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002487 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002488 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002489 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002490 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002491 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002492#endif
2493
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002494 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002495#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 SET_SYS_FROM_STRING("float_repr_style",
2497 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002498#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 SET_SYS_FROM_STRING("float_repr_style",
2500 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002501#endif
2502
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002503 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002504
Yury Selivanoveb636452016-09-08 22:01:51 -07002505 /* initialize asyncgen_hooks */
2506 if (AsyncGenHooksType.tp_name == NULL) {
2507 if (PyStructSequence_InitType2(
2508 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002509 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002510 }
2511 }
2512
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002513 if (PyErr_Occurred()) {
2514 goto err_occurred;
2515 }
2516
2517 *sysmod = m;
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002518
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002519 return _Py_INIT_OK();
2520
2521type_init_failed:
2522 return _Py_INIT_ERR("failed to initialize a type");
2523
2524err_occurred:
2525 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002526}
2527
Eric Snow6b4be192017-05-22 21:36:03 -07002528#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002529
2530/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002531#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2532 do { \
2533 PyObject *v = (value); \
2534 if (v == NULL) \
2535 return -1; \
2536 res = PyDict_SetItemString(sysdict, key, v); \
2537 Py_DECREF(v); \
2538 if (res < 0) { \
2539 return res; \
2540 } \
2541 } while (0)
2542
2543int
Victor Stinnerfbca9082018-08-30 00:50:45 +02002544_PySys_EndInit(PyObject *sysdict, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002545{
Victor Stinnerfbca9082018-08-30 00:50:45 +02002546 const _PyCoreConfig *core_config = &interp->core_config;
2547 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002548 int res;
2549
Victor Stinner41264f12017-12-15 02:05:29 +01002550 /* _PyMainInterpreterConfig_Read() must set all these variables */
2551 assert(config->module_search_path != NULL);
2552 assert(config->executable != NULL);
2553 assert(config->prefix != NULL);
2554 assert(config->base_prefix != NULL);
2555 assert(config->exec_prefix != NULL);
2556 assert(config->base_exec_prefix != NULL);
2557
Victor Stinner37cd9822018-11-16 11:55:35 +01002558#define COPY_LIST(KEY, ATTR) \
2559 do { \
2560 assert(PyList_Check(config->ATTR)); \
2561 PyObject *list = PyList_GetSlice(config->ATTR, \
2562 0, PyList_GET_SIZE(config->ATTR)); \
2563 if (list == NULL) { \
2564 return -1; \
2565 } \
2566 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2567 Py_DECREF(list); \
2568 } while (0)
2569
2570 COPY_LIST("path", module_search_path);
2571
Victor Stinner41264f12017-12-15 02:05:29 +01002572 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2573 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2574 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2575 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2576 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2577
Carl Meyerb193fa92018-06-15 22:40:56 -06002578 if (config->pycache_prefix != NULL) {
2579 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2580 } else {
2581 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2582 }
2583
Victor Stinner41264f12017-12-15 02:05:29 +01002584 if (config->argv != NULL) {
2585 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2586 }
2587 if (config->warnoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002588 COPY_LIST("warnoptions", warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002589 }
2590 if (config->xoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002591 PyObject *dict = PyDict_Copy(config->xoptions);
2592 if (dict == NULL) {
2593 return -1;
2594 }
2595 SET_SYS_FROM_STRING_BORROW("_xoptions", dict);
2596 Py_DECREF(dict);
Victor Stinner41264f12017-12-15 02:05:29 +01002597 }
2598
Victor Stinner37cd9822018-11-16 11:55:35 +01002599#undef COPY_LIST
2600
Eric Snow6b4be192017-05-22 21:36:03 -07002601 /* Set flags to their final values */
2602 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2603 /* prevent user from creating new instances */
2604 FlagsType.tp_init = NULL;
2605 FlagsType.tp_new = NULL;
2606 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2607 if (res < 0) {
2608 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2609 return res;
2610 }
2611 PyErr_Clear();
2612 }
2613
2614 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002615 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002616
Eric Snowdae02762017-09-14 00:35:58 -07002617 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002618 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002619
Eric Snowdae02762017-09-14 00:35:58 -07002620 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002621 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002622
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002623 /* Transfer any sys.warnoptions and sys._xoptions set directly
2624 * by an embedding application from the linked list to the module. */
2625 if (_PySys_ReadPreInitOptions() != 0)
2626 return -1;
2627
Eric Snow6b4be192017-05-22 21:36:03 -07002628 if (PyErr_Occurred())
2629 return -1;
2630 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002631
2632err_occurred:
2633 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002634}
2635
Victor Stinner41264f12017-12-15 02:05:29 +01002636#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002637#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002638
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002639static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002640makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002642 int i, n;
2643 const wchar_t *p;
2644 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002645
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002646 n = 1;
2647 p = path;
2648 while ((p = wcschr(p, delim)) != NULL) {
2649 n++;
2650 p++;
2651 }
2652 v = PyList_New(n);
2653 if (v == NULL)
2654 return NULL;
2655 for (i = 0; ; i++) {
2656 p = wcschr(path, delim);
2657 if (p == NULL)
2658 p = path + wcslen(path); /* End of string */
2659 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2660 if (w == NULL) {
2661 Py_DECREF(v);
2662 return NULL;
2663 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002664 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 if (*p == '\0')
2666 break;
2667 path = p+1;
2668 }
2669 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002670}
2671
2672void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002673PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002674{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002675 PyObject *v;
2676 if ((v = makepathobject(path, DELIM)) == NULL)
2677 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002678 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002679 Py_FatalError("can't assign sys.path");
2680 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002681}
2682
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002683static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002684makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002686 PyObject *av;
2687 if (argc <= 0 || argv == NULL) {
2688 /* Ensure at least one (empty) argument is seen */
2689 static wchar_t *empty_argv[1] = {L""};
2690 argv = empty_argv;
2691 argc = 1;
2692 }
2693 av = PyList_New(argc);
2694 if (av != NULL) {
2695 int i;
2696 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002697 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 if (v == NULL) {
2699 Py_DECREF(av);
2700 av = NULL;
2701 break;
2702 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002703 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002704 }
2705 }
2706 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002707}
2708
Victor Stinner11a247d2017-12-13 21:05:57 +01002709void
2710PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002711{
2712 PyObject *av = makeargvobject(argc, argv);
2713 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002714 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002715 }
2716 if (PySys_SetObject("argv", av) != 0) {
2717 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002718 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002719 }
2720 Py_DECREF(av);
2721
2722 if (updatepath) {
2723 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2724 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002725 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2726 if (argv0 == NULL) {
2727 Py_FatalError("can't compute path0 from argv");
2728 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002729
Victor Stinner11a247d2017-12-13 21:05:57 +01002730 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2731 if (sys_path != NULL) {
2732 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2733 Py_DECREF(argv0);
2734 Py_FatalError("can't prepend path0 to sys.path");
2735 }
2736 }
2737 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002738 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002739}
Guido van Rossuma890e681998-05-12 14:59:24 +00002740
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002741void
2742PySys_SetArgv(int argc, wchar_t **argv)
2743{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002744 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002745}
2746
Victor Stinner14284c22010-04-23 12:02:30 +00002747/* Reimplementation of PyFile_WriteString() no calling indirectly
2748 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2749
2750static int
Victor Stinner79766632010-08-16 17:36:42 +00002751sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002752{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002753 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002755
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002756 if (file == NULL)
2757 return -1;
2758
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002759 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 if (writer == NULL)
2761 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002762
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002763 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 if (result == NULL) {
2765 goto error;
2766 } else {
2767 err = 0;
2768 goto finally;
2769 }
Victor Stinner14284c22010-04-23 12:02:30 +00002770
2771error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002772 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002773finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002774 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002775 Py_XDECREF(result);
2776 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002777}
2778
Victor Stinner79766632010-08-16 17:36:42 +00002779static int
2780sys_pyfile_write(const char *text, PyObject *file)
2781{
2782 PyObject *unicode = NULL;
2783 int err;
2784
2785 if (file == NULL)
2786 return -1;
2787
2788 unicode = PyUnicode_FromString(text);
2789 if (unicode == NULL)
2790 return -1;
2791
2792 err = sys_pyfile_write_unicode(unicode, file);
2793 Py_DECREF(unicode);
2794 return err;
2795}
Guido van Rossuma890e681998-05-12 14:59:24 +00002796
2797/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2798 Adapted from code submitted by Just van Rossum.
2799
2800 PySys_WriteStdout(format, ...)
2801 PySys_WriteStderr(format, ...)
2802
2803 The first function writes to sys.stdout; the second to sys.stderr. When
2804 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002805 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002806
Victor Stinner14284c22010-04-23 12:02:30 +00002807 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002808 signal handlers: they may raise a new exception whereas sys_write()
2809 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002810
Guido van Rossuma890e681998-05-12 14:59:24 +00002811 Both take a printf-style format string as their first argument followed
2812 by a variable length argument list determined by the format string.
2813
2814 *** WARNING ***
2815
2816 The format should limit the total size of the formatted output string to
2817 1000 bytes. In particular, this means that no unrestricted "%s" formats
2818 should occur; these should be limited using "%.<N>s where <N> is a
2819 decimal number calculated so that <N> plus the maximum size of other
2820 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2821 which can print hundreds of digits for very large numbers.
2822
2823 */
2824
2825static void
Victor Stinner09054372013-11-06 22:41:44 +01002826sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 PyObject *file;
2829 PyObject *error_type, *error_value, *error_traceback;
2830 char buffer[1001];
2831 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002833 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002834 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002835 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2836 if (sys_pyfile_write(buffer, file) != 0) {
2837 PyErr_Clear();
2838 fputs(buffer, fp);
2839 }
2840 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2841 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002842 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002843 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002844 }
2845 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002846}
2847
2848void
Guido van Rossuma890e681998-05-12 14:59:24 +00002849PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002850{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002853 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002854 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002855 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002856}
2857
2858void
Guido van Rossuma890e681998-05-12 14:59:24 +00002859PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002863 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002864 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002865 va_end(va);
2866}
2867
2868static void
Victor Stinner09054372013-11-06 22:41:44 +01002869sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002870{
2871 PyObject *file, *message;
2872 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002873 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002874
2875 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002876 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002877 message = PyUnicode_FromFormatV(format, va);
2878 if (message != NULL) {
2879 if (sys_pyfile_write_unicode(message, file) != 0) {
2880 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002881 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002882 if (utf8 != NULL)
2883 fputs(utf8, fp);
2884 }
2885 Py_DECREF(message);
2886 }
2887 PyErr_Restore(error_type, error_value, error_traceback);
2888}
2889
2890void
2891PySys_FormatStdout(const char *format, ...)
2892{
2893 va_list va;
2894
2895 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002896 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002897 va_end(va);
2898}
2899
2900void
2901PySys_FormatStderr(const char *format, ...)
2902{
2903 va_list va;
2904
2905 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002906 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002908}