blob: 12ec7d5918edea2bd5c89a38f0086a25f215ba3e [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 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200144 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400145 /* Split on the last dot; */
146 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
147 attrname = last_dot + 1;
148 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200149 else {
150 goto warn;
151 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400152 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300153 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400154 return NULL;
155 }
156
Anthony Sottiledce345c2018-11-01 10:25:05 -0700157 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400158 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400159
160 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200161 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
162 goto warn;
163 }
164 PyMem_RawFree(envar);
165 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400166 }
167
168 PyObject *hook = PyObject_GetAttrString(module, attrname);
169 Py_DECREF(module);
170
171 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200172 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
173 goto warn;
174 }
175 PyMem_RawFree(envar);
176 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400177 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300178 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400179 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
180 Py_DECREF(hook);
181 return retval;
182
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200183 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400184 /* If any of the imports went wrong, then warn and ignore. */
185 PyErr_Clear();
186 int status = PyErr_WarnFormat(
187 PyExc_RuntimeWarning, 0,
188 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300189 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400190 if (status < 0) {
191 /* Printing the warning raised an exception. */
192 return NULL;
193 }
194 /* The warning was (probably) issued. */
195 Py_RETURN_NONE;
196}
197
198PyDoc_STRVAR(breakpointhook_doc,
199"breakpointhook(*args, **kws)\n"
200"\n"
201"This hook function is called by built-in breakpoint().\n"
202);
203
Victor Stinner13d49ee2010-12-04 17:24:33 +0000204/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
205 error handler. If sys.stdout has a buffer attribute, use
206 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
207 sys.stdout.write(redecoded).
208
209 Helper function for sys_displayhook(). */
210static int
211sys_displayhook_unencodable(PyObject *outf, PyObject *o)
212{
213 PyObject *stdout_encoding = NULL;
214 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200215 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000216 int ret;
217
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200218 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000219 if (stdout_encoding == NULL)
220 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200221 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000222 if (stdout_encoding_str == NULL)
223 goto error;
224
225 repr_str = PyObject_Repr(o);
226 if (repr_str == NULL)
227 goto error;
228 encoded = PyUnicode_AsEncodedString(repr_str,
229 stdout_encoding_str,
230 "backslashreplace");
231 Py_DECREF(repr_str);
232 if (encoded == NULL)
233 goto error;
234
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200235 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000236 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100237 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000238 Py_DECREF(buffer);
239 Py_DECREF(encoded);
240 if (result == NULL)
241 goto error;
242 Py_DECREF(result);
243 }
244 else {
245 PyErr_Clear();
246 escaped_str = PyUnicode_FromEncodedObject(encoded,
247 stdout_encoding_str,
248 "strict");
249 Py_DECREF(encoded);
250 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
251 Py_DECREF(escaped_str);
252 goto error;
253 }
254 Py_DECREF(escaped_str);
255 }
256 ret = 0;
257 goto finally;
258
259error:
260 ret = -1;
261finally:
262 Py_XDECREF(stdout_encoding);
263 return ret;
264}
265
Tal Einatede0b6f2018-12-31 17:12:08 +0200266/*[clinic input]
267sys.displayhook
268
269 object as o: object
270 /
271
272Print an object to sys.stdout and also save it in builtins._
273[clinic start generated code]*/
274
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000275static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200276sys_displayhook(PyObject *module, PyObject *o)
277/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100280 PyObject *builtins;
281 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000282 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000283
Eric Snow3f9eee62017-09-15 16:35:20 -0600284 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (builtins == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +0100286 if (!PyErr_Occurred()) {
287 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
288 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 return NULL;
290 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600291 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000292
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 /* Print value except if None */
294 /* After printing, also assign to '_' */
295 /* Before, set '_' to None to avoid recursion */
296 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200297 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200299 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100301 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000302 if (outf == NULL || outf == Py_None) {
303 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
304 return NULL;
305 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000306 if (PyFile_WriteObject(o, outf, 0) != 0) {
307 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
308 /* repr(o) is not encodable to sys.stdout.encoding with
309 * sys.stdout.errors error handler (which is probably 'strict') */
310 PyErr_Clear();
311 err = sys_displayhook_unencodable(outf, o);
312 if (err)
313 return NULL;
314 }
315 else {
316 return NULL;
317 }
318 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100319 if (newline == NULL) {
320 newline = PyUnicode_FromString("\n");
321 if (newline == NULL)
322 return NULL;
323 }
324 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200326 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200328 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000329}
330
Tal Einatede0b6f2018-12-31 17:12:08 +0200331
332/*[clinic input]
333sys.excepthook
334
335 exctype: object
336 value: object
337 traceback: object
338 /
339
340Handle an exception by displaying it with a traceback on sys.stderr.
341[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000342
343static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200344sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
345 PyObject *traceback)
346/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000347{
Tal Einatede0b6f2018-12-31 17:12:08 +0200348 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200349 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000350}
351
Tal Einatede0b6f2018-12-31 17:12:08 +0200352
353/*[clinic input]
354sys.exc_info
355
356Return current exception information: (type, value, traceback).
357
358Return information about the most recent exception caught by an except
359clause in the current stack frame or in an older stack frame.
360[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000361
362static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200363sys_exc_info_impl(PyObject *module)
364/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000365{
Victor Stinner50b48572018-11-01 01:51:40 +0100366 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 return Py_BuildValue(
368 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100369 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
370 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
371 err_info->exc_traceback != NULL ?
372 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000373}
374
Tal Einatede0b6f2018-12-31 17:12:08 +0200375
376/*[clinic input]
377sys.exit
378
379 status: object = NULL
380 /
381
382Exit the interpreter by raising SystemExit(status).
383
384If the status is omitted or None, it defaults to zero (i.e., success).
385If the status is an integer, it will be used as the system exit status.
386If it is another kind of object, it will be printed and the system
387exit status will be one (i.e., failure).
388[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000389
390static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200391sys_exit_impl(PyObject *module, PyObject *status)
392/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200395 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000397}
398
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000399
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000400
Tal Einatede0b6f2018-12-31 17:12:08 +0200401/*[clinic input]
402sys.getdefaultencoding
403
404Return the current default encoding used by the Unicode implementation.
405[clinic start generated code]*/
406
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000407static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200408sys_getdefaultencoding_impl(PyObject *module)
409/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000412}
413
Tal Einatede0b6f2018-12-31 17:12:08 +0200414/*[clinic input]
415sys.getfilesystemencoding
416
417Return the encoding used to convert Unicode filenames to OS filenames.
418[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000419
420static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200421sys_getfilesystemencoding_impl(PyObject *module)
422/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000423{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200424 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
425 const _PyCoreConfig *config = &interp->core_config;
426 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000427}
428
Tal Einatede0b6f2018-12-31 17:12:08 +0200429/*[clinic input]
430sys.getfilesystemencodeerrors
431
432Return the error mode used Unicode to OS filename conversion.
433[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000434
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000435static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200436sys_getfilesystemencodeerrors_impl(PyObject *module)
437/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700438{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200439 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
440 const _PyCoreConfig *config = &interp->core_config;
441 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700442}
443
Tal Einatede0b6f2018-12-31 17:12:08 +0200444/*[clinic input]
445sys.intern
446
447 string as s: unicode
448 /
449
450``Intern'' the given string.
451
452This enters the string in the (global) table of interned strings whose
453purpose is to speed up dictionary lookups. Return the string itself or
454the previously interned string object with the same value.
455[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700456
457static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200458sys_intern_impl(PyObject *module, PyObject *s)
459/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 if (PyUnicode_CheckExact(s)) {
462 Py_INCREF(s);
463 PyUnicode_InternInPlace(&s);
464 return s;
465 }
466 else {
467 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200468 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000469 return NULL;
470 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000471}
472
Georg Brandl66a796e2006-12-19 20:50:34 +0000473
Fred Drake5755ce62001-06-27 19:19:46 +0000474/*
475 * Cached interned string objects used for calling the profile and
476 * trace functions. Initialized by trace_init().
477 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000478static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000479
480static int
481trace_init(void)
482{
Nick Coghlan5a851672017-09-08 10:14:16 +1000483 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200484 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000485 "c_call", "c_exception", "c_return",
486 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200487 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 PyObject *name;
489 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000490 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (whatstrings[i] == NULL) {
492 name = PyUnicode_InternFromString(whatnames[i]);
493 if (name == NULL)
494 return -1;
495 whatstrings[i] = name;
496 }
497 }
498 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000499}
500
501
502static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100503call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000505{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200507 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000508
Victor Stinner78da82b2016-08-20 01:22:57 +0200509 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200511 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100512
Victor Stinner78da82b2016-08-20 01:22:57 +0200513 stack[0] = (PyObject *)frame;
514 stack[1] = whatstrings[what];
515 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200518 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000519
Victor Stinner78da82b2016-08-20 01:22:57 +0200520 PyFrame_LocalsToFast(frame, 1);
521 if (result == NULL) {
522 PyTraceBack_Here(frame);
523 }
524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000525 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000526}
527
528static int
529profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 if (arg == NULL)
535 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100536 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (result == NULL) {
538 PyEval_SetProfile(NULL, NULL);
539 return -1;
540 }
541 Py_DECREF(result);
542 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000543}
544
545static int
546trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000548{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 PyObject *callback;
550 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (what == PyTrace_CALL)
553 callback = self;
554 else
555 callback = frame->f_trace;
556 if (callback == NULL)
557 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100558 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (result == NULL) {
560 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200561 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 return -1;
563 }
564 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300565 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000566 }
567 else {
568 Py_DECREF(result);
569 }
570 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000571}
Fred Draked0838392001-06-16 21:02:31 +0000572
Fred Drake8b4d01d2000-05-09 19:57:01 +0000573static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000574sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000575{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000576 if (trace_init() == -1)
577 return NULL;
578 if (args == Py_None)
579 PyEval_SetTrace(NULL, NULL);
580 else
581 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200582 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000583}
584
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000585PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000586"settrace(function)\n\
587\n\
588Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000589function call. See the debugger chapter in the library manual."
590);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000591
Tal Einatede0b6f2018-12-31 17:12:08 +0200592/*[clinic input]
593sys.gettrace
594
595Return the global debug tracing function set with sys.settrace.
596
597See the debugger chapter in the library manual.
598[clinic start generated code]*/
599
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000600static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200601sys_gettrace_impl(PyObject *module)
602/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000603{
Victor Stinner50b48572018-11-01 01:51:40 +0100604 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 if (temp == NULL)
608 temp = Py_None;
609 Py_INCREF(temp);
610 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000611}
612
Christian Heimes9bd667a2008-01-20 15:14:11 +0000613static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000614sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 if (trace_init() == -1)
617 return NULL;
618 if (args == Py_None)
619 PyEval_SetProfile(NULL, NULL);
620 else
621 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200622 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000623}
624
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000625PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000626"setprofile(function)\n\
627\n\
628Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000629and return. See the profiler chapter in the library manual."
630);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000631
Tal Einatede0b6f2018-12-31 17:12:08 +0200632/*[clinic input]
633sys.getprofile
634
635Return the profiling function set with sys.setprofile.
636
637See the profiler chapter in the library manual.
638[clinic start generated code]*/
639
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000640static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200641sys_getprofile_impl(PyObject *module)
642/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000643{
Victor Stinner50b48572018-11-01 01:51:40 +0100644 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000647 if (temp == NULL)
648 temp = Py_None;
649 Py_INCREF(temp);
650 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000651}
652
Tal Einatede0b6f2018-12-31 17:12:08 +0200653/*[clinic input]
654sys.setcheckinterval
655
656 n: int
657 /
658
659Set the async event check interval to n instructions.
660
661This tells the Python interpreter to check for asynchronous events
662every n instructions.
663
664This also affects how often thread switches occur.
665[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000666
667static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200668sys_setcheckinterval_impl(PyObject *module, int n)
669/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 if (PyErr_WarnEx(PyExc_DeprecationWarning,
672 "sys.getcheckinterval() and sys.setcheckinterval() "
673 "are deprecated. Use sys.setswitchinterval() "
674 "instead.", 1) < 0)
675 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200676
Victor Stinnercaba55b2018-08-03 15:33:52 +0200677 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +0200678 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200679 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000680}
681
Tal Einatede0b6f2018-12-31 17:12:08 +0200682/*[clinic input]
683sys.getcheckinterval
684
685Return the current check interval; see sys.setcheckinterval().
686[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000687
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000688static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200689sys_getcheckinterval_impl(PyObject *module)
690/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000691{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000692 if (PyErr_WarnEx(PyExc_DeprecationWarning,
693 "sys.getcheckinterval() and sys.setcheckinterval() "
694 "are deprecated. Use sys.getswitchinterval() "
695 "instead.", 1) < 0)
696 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200697 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600698 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000699}
700
Tal Einatede0b6f2018-12-31 17:12:08 +0200701/*[clinic input]
702sys.setswitchinterval
703
704 interval: double
705 /
706
707Set the ideal thread switching delay inside the Python interpreter.
708
709The actual frequency of switching threads can be lower if the
710interpreter executes long sequences of uninterruptible code
711(this is implementation-specific and workload-dependent).
712
713The parameter must represent the desired switching delay in seconds
714A typical value is 0.005 (5 milliseconds).
715[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000716
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000717static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200718sys_setswitchinterval_impl(PyObject *module, double interval)
719/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000720{
Tal Einatede0b6f2018-12-31 17:12:08 +0200721 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 PyErr_SetString(PyExc_ValueError,
723 "switch interval must be strictly positive");
724 return NULL;
725 }
Tal Einatede0b6f2018-12-31 17:12:08 +0200726 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200727 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000728}
729
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000730
Tal Einatede0b6f2018-12-31 17:12:08 +0200731/*[clinic input]
732sys.getswitchinterval -> double
733
734Return the current thread switch interval; see sys.setswitchinterval().
735[clinic start generated code]*/
736
737static double
738sys_getswitchinterval_impl(PyObject *module)
739/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000740{
Tal Einatede0b6f2018-12-31 17:12:08 +0200741 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000742}
743
Tal Einatede0b6f2018-12-31 17:12:08 +0200744/*[clinic input]
745sys.setrecursionlimit
746
747 limit as new_limit: int
748 /
749
750Set the maximum depth of the Python interpreter stack to n.
751
752This limit prevents infinite recursion from causing an overflow of the C
753stack and crashing Python. The highest possible limit is platform-
754dependent.
755[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000756
Tim Peterse5e065b2003-07-06 18:36:54 +0000757static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200758sys_setrecursionlimit_impl(PyObject *module, int new_limit)
759/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000760{
Tal Einatede0b6f2018-12-31 17:12:08 +0200761 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +0200762 PyThreadState *tstate;
763
Victor Stinner50856d52015-10-13 00:11:21 +0200764 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200766 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 return NULL;
768 }
Victor Stinner50856d52015-10-13 00:11:21 +0200769
770 /* Issue #25274: When the recursion depth hits the recursion limit in
771 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
772 set to 1 and a RecursionError is raised. The overflowed flag is reset
773 to 0 when the recursion depth goes below the low-water mark: see
774 Py_LeaveRecursiveCall().
775
776 Reject too low new limit if the current recursion depth is higher than
777 the new low-water mark. Otherwise it may not be possible anymore to
778 reset the overflowed flag to 0. */
779 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100780 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200781 if (tstate->recursion_depth >= mark) {
782 PyErr_Format(PyExc_RecursionError,
783 "cannot set the recursion limit to %i at "
784 "the recursion depth %i: the limit is too low",
785 new_limit, tstate->recursion_depth);
786 return NULL;
787 }
788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200790 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000791}
792
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800793/*[clinic input]
794sys.set_coroutine_origin_tracking_depth
795
796 depth: int
797
798Enable or disable origin tracking for coroutine objects in this thread.
799
Tal Einatede0b6f2018-12-31 17:12:08 +0200800Coroutine objects will track 'depth' frames of traceback information
801about where they came from, available in their cr_origin attribute.
802
803Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800804[clinic start generated code]*/
805
806static PyObject *
807sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +0200808/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800809{
810 if (depth < 0) {
811 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
812 return NULL;
813 }
814 _PyEval_SetCoroutineOriginTrackingDepth(depth);
815 Py_RETURN_NONE;
816}
817
818/*[clinic input]
819sys.get_coroutine_origin_tracking_depth -> int
820
821Check status of origin tracking for coroutine objects in this thread.
822[clinic start generated code]*/
823
824static int
825sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
826/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
827{
828 return _PyEval_GetCoroutineOriginTrackingDepth();
829}
830
Tal Einatede0b6f2018-12-31 17:12:08 +0200831/*[clinic input]
832sys.set_coroutine_wrapper
833
834 wrapper: object
835 /
836
837Set a wrapper for coroutine objects.
838[clinic start generated code]*/
839
Yury Selivanov75445082015-05-11 22:57:16 -0400840static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200841sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
842/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400843{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800844 if (PyErr_WarnEx(PyExc_DeprecationWarning,
845 "set_coroutine_wrapper is deprecated", 1) < 0) {
846 return NULL;
847 }
848
Yury Selivanov75445082015-05-11 22:57:16 -0400849 if (wrapper != Py_None) {
850 if (!PyCallable_Check(wrapper)) {
851 PyErr_Format(PyExc_TypeError,
852 "callable expected, got %.50s",
853 Py_TYPE(wrapper)->tp_name);
854 return NULL;
855 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400856 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400857 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400858 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400859 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400860 }
Yury Selivanov75445082015-05-11 22:57:16 -0400861 Py_RETURN_NONE;
862}
863
Tal Einatede0b6f2018-12-31 17:12:08 +0200864/*[clinic input]
865sys.get_coroutine_wrapper
866
867Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
868[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400869
870static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200871sys_get_coroutine_wrapper_impl(PyObject *module)
872/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400873{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800874 if (PyErr_WarnEx(PyExc_DeprecationWarning,
875 "get_coroutine_wrapper is deprecated", 1) < 0) {
876 return NULL;
877 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400878 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400879 if (wrapper == NULL) {
880 wrapper = Py_None;
881 }
882 Py_INCREF(wrapper);
883 return wrapper;
884}
885
Yury Selivanov75445082015-05-11 22:57:16 -0400886
Yury Selivanoveb636452016-09-08 22:01:51 -0700887static PyTypeObject AsyncGenHooksType;
888
889PyDoc_STRVAR(asyncgen_hooks_doc,
890"asyncgen_hooks\n\
891\n\
892A struct sequence providing information about asynhronous\n\
893generators hooks. The attributes are read only.");
894
895static PyStructSequence_Field asyncgen_hooks_fields[] = {
896 {"firstiter", "Hook to intercept first iteration"},
897 {"finalizer", "Hook to intercept finalization"},
898 {0}
899};
900
901static PyStructSequence_Desc asyncgen_hooks_desc = {
902 "asyncgen_hooks", /* name */
903 asyncgen_hooks_doc, /* doc */
904 asyncgen_hooks_fields , /* fields */
905 2
906};
907
Yury Selivanoveb636452016-09-08 22:01:51 -0700908static PyObject *
909sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
910{
911 static char *keywords[] = {"firstiter", "finalizer", NULL};
912 PyObject *firstiter = NULL;
913 PyObject *finalizer = NULL;
914
915 if (!PyArg_ParseTupleAndKeywords(
916 args, kw, "|OO", keywords,
917 &firstiter, &finalizer)) {
918 return NULL;
919 }
920
921 if (finalizer && finalizer != Py_None) {
922 if (!PyCallable_Check(finalizer)) {
923 PyErr_Format(PyExc_TypeError,
924 "callable finalizer expected, got %.50s",
925 Py_TYPE(finalizer)->tp_name);
926 return NULL;
927 }
928 _PyEval_SetAsyncGenFinalizer(finalizer);
929 }
930 else if (finalizer == Py_None) {
931 _PyEval_SetAsyncGenFinalizer(NULL);
932 }
933
934 if (firstiter && firstiter != Py_None) {
935 if (!PyCallable_Check(firstiter)) {
936 PyErr_Format(PyExc_TypeError,
937 "callable firstiter expected, got %.50s",
938 Py_TYPE(firstiter)->tp_name);
939 return NULL;
940 }
941 _PyEval_SetAsyncGenFirstiter(firstiter);
942 }
943 else if (firstiter == Py_None) {
944 _PyEval_SetAsyncGenFirstiter(NULL);
945 }
946
947 Py_RETURN_NONE;
948}
949
950PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +0200951"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -0700952\n\
953Set a finalizer for async generators objects."
954);
955
Tal Einatede0b6f2018-12-31 17:12:08 +0200956/*[clinic input]
957sys.get_asyncgen_hooks
958
959Return the installed asynchronous generators hooks.
960
961This returns a namedtuple of the form (firstiter, finalizer).
962[clinic start generated code]*/
963
Yury Selivanoveb636452016-09-08 22:01:51 -0700964static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200965sys_get_asyncgen_hooks_impl(PyObject *module)
966/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -0700967{
968 PyObject *res;
969 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
970 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
971
972 res = PyStructSequence_New(&AsyncGenHooksType);
973 if (res == NULL) {
974 return NULL;
975 }
976
977 if (firstiter == NULL) {
978 firstiter = Py_None;
979 }
980
981 if (finalizer == NULL) {
982 finalizer = Py_None;
983 }
984
985 Py_INCREF(firstiter);
986 PyStructSequence_SET_ITEM(res, 0, firstiter);
987
988 Py_INCREF(finalizer);
989 PyStructSequence_SET_ITEM(res, 1, finalizer);
990
991 return res;
992}
993
Yury Selivanoveb636452016-09-08 22:01:51 -0700994
Mark Dickinsondc787d22010-05-23 13:33:13 +0000995static PyTypeObject Hash_InfoType;
996
997PyDoc_STRVAR(hash_info_doc,
998"hash_info\n\
999\n\
1000A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001001hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001002
1003static PyStructSequence_Field hash_info_fields[] = {
1004 {"width", "width of the type used for hashing, in bits"},
1005 {"modulus", "prime number giving the modulus on which the hash "
1006 "function is based"},
1007 {"inf", "value to be used for hash of a positive infinity"},
1008 {"nan", "value to be used for hash of a nan"},
1009 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001010 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1011 "memoryviews"},
1012 {"hash_bits", "internal output size of hash algorithm"},
1013 {"seed_bits", "seed size of hash algorithm"},
1014 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001015 {NULL, NULL}
1016};
1017
1018static PyStructSequence_Desc hash_info_desc = {
1019 "sys.hash_info",
1020 hash_info_doc,
1021 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001022 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001023};
1024
Matthias Klosed885e952010-07-06 10:53:30 +00001025static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001026get_hash_info(void)
1027{
1028 PyObject *hash_info;
1029 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001030 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001031 hash_info = PyStructSequence_New(&Hash_InfoType);
1032 if (hash_info == NULL)
1033 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001034 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001035 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001036 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001037 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001038 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001039 PyStructSequence_SET_ITEM(hash_info, field++,
1040 PyLong_FromLong(_PyHASH_INF));
1041 PyStructSequence_SET_ITEM(hash_info, field++,
1042 PyLong_FromLong(_PyHASH_NAN));
1043 PyStructSequence_SET_ITEM(hash_info, field++,
1044 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001045 PyStructSequence_SET_ITEM(hash_info, field++,
1046 PyUnicode_FromString(hashfunc->name));
1047 PyStructSequence_SET_ITEM(hash_info, field++,
1048 PyLong_FromLong(hashfunc->hash_bits));
1049 PyStructSequence_SET_ITEM(hash_info, field++,
1050 PyLong_FromLong(hashfunc->seed_bits));
1051 PyStructSequence_SET_ITEM(hash_info, field++,
1052 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001053 if (PyErr_Occurred()) {
1054 Py_CLEAR(hash_info);
1055 return NULL;
1056 }
1057 return hash_info;
1058}
Tal Einatede0b6f2018-12-31 17:12:08 +02001059/*[clinic input]
1060sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001061
Tal Einatede0b6f2018-12-31 17:12:08 +02001062Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001063
Tal Einatede0b6f2018-12-31 17:12:08 +02001064The recursion limit is the maximum depth of the Python interpreter
1065stack. This limit prevents infinite recursion from causing an overflow
1066of the C stack and crashing Python.
1067[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001068
1069static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001070sys_getrecursionlimit_impl(PyObject *module)
1071/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001074}
1075
Mark Hammond8696ebc2002-10-08 02:44:31 +00001076#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001077
Eric Smithf7bb5782010-01-27 00:44:57 +00001078static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1079
1080static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001081 {"major", "Major version number"},
1082 {"minor", "Minor version number"},
1083 {"build", "Build number"},
1084 {"platform", "Operating system platform"},
1085 {"service_pack", "Latest Service Pack installed on the system"},
1086 {"service_pack_major", "Service Pack major version number"},
1087 {"service_pack_minor", "Service Pack minor version number"},
1088 {"suite_mask", "Bit mask identifying available product suites"},
1089 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001090 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001091 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001092};
1093
1094static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001095 "sys.getwindowsversion", /* name */
1096 sys_getwindowsversion__doc__, /* doc */
1097 windows_version_fields, /* fields */
1098 5 /* For backward compatibility,
1099 only the first 5 items are accessible
1100 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001101};
1102
Steve Dower3e96f322015-03-02 08:01:10 -08001103/* Disable deprecation warnings about GetVersionEx as the result is
1104 being passed straight through to the caller, who is responsible for
1105 using it correctly. */
1106#pragma warning(push)
1107#pragma warning(disable:4996)
1108
Tal Einatede0b6f2018-12-31 17:12:08 +02001109/*[clinic input]
1110sys.getwindowsversion
1111
1112Return info about the running version of Windows as a named tuple.
1113
1114The members are named: major, minor, build, platform, service_pack,
1115service_pack_major, service_pack_minor, suite_mask, product_type and
1116platform_version. For backward compatibility, only the first 5 items
1117are available by indexing. All elements are numbers, except
1118service_pack and platform_type which are strings, and platform_version
1119which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1120workstation, 2 for a domain controller, 3 for a server.
1121Platform_version is a 3-tuple containing a version number that is
1122intended for identifying the OS rather than feature detection.
1123[clinic start generated code]*/
1124
Mark Hammond8696ebc2002-10-08 02:44:31 +00001125static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001126sys_getwindowsversion_impl(PyObject *module)
1127/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 PyObject *version;
1130 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001131 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001132 DWORD realMajor, realMinor, realBuild;
1133 HANDLE hKernel32;
1134 wchar_t kernel32_path[MAX_PATH];
1135 LPVOID verblock;
1136 DWORD verblock_size;
1137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001139 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 version = PyStructSequence_New(&WindowsVersionType);
1143 if (version == NULL)
1144 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001145
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1147 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1148 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1149 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001150 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001151 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1152 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1153 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1154 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001155
Steve Dower74f4af72016-09-17 17:27:48 -07001156 realMajor = ver.dwMajorVersion;
1157 realMinor = ver.dwMinorVersion;
1158 realBuild = ver.dwBuildNumber;
1159
1160 // GetVersion will lie if we are running in a compatibility mode.
1161 // We need to read the version info from a system file resource
1162 // to accurately identify the OS version. If we fail for any reason,
1163 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001164 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001165 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001166 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001167 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1168 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1169 (verblock = PyMem_RawMalloc(verblock_size))) {
1170 VS_FIXEDFILEINFO *ffi;
1171 UINT ffi_len;
1172
1173 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1174 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1175 realMajor = HIWORD(ffi->dwProductVersionMS);
1176 realMinor = LOWORD(ffi->dwProductVersionMS);
1177 realBuild = HIWORD(ffi->dwProductVersionLS);
1178 }
1179 PyMem_RawFree(verblock);
1180 }
Segev Finer48fb7662017-06-04 20:52:27 +03001181 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1182 realMajor,
1183 realMinor,
1184 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001185 ));
1186
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001187 if (PyErr_Occurred()) {
1188 Py_DECREF(version);
1189 return NULL;
1190 }
Steve Dower74f4af72016-09-17 17:27:48 -07001191
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001193}
1194
Steve Dower3e96f322015-03-02 08:01:10 -08001195#pragma warning(pop)
1196
Tal Einatede0b6f2018-12-31 17:12:08 +02001197/*[clinic input]
1198sys._enablelegacywindowsfsencoding
1199
1200Changes the default filesystem encoding to mbcs:replace.
1201
1202This is done for consistency with earlier versions of Python. See PEP
1203529 for more information.
1204
1205This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1206environment variable before launching Python.
1207[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001208
1209static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001210sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1211/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001212{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001213 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1214 _PyCoreConfig *config = &interp->core_config;
1215
1216 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1217 char *encoding = _PyMem_RawStrdup("mbcs");
1218 char *errors = _PyMem_RawStrdup("replace");
1219 if (encoding == NULL || errors == NULL) {
1220 PyMem_Free(encoding);
1221 PyMem_Free(errors);
1222 PyErr_NoMemory();
1223 return NULL;
1224 }
1225
1226 PyMem_RawFree(config->filesystem_encoding);
1227 config->filesystem_encoding = encoding;
1228 PyMem_RawFree(config->filesystem_errors);
1229 config->filesystem_errors = errors;
1230
1231 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1232 config->filesystem_errors) < 0) {
1233 PyErr_NoMemory();
1234 return NULL;
1235 }
1236
Steve Dowercc16be82016-09-08 10:35:16 -07001237 Py_RETURN_NONE;
1238}
1239
Mark Hammond8696ebc2002-10-08 02:44:31 +00001240#endif /* MS_WINDOWS */
1241
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001242#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001243
1244/*[clinic input]
1245sys.setdlopenflags
1246
1247 flags as new_val: int
1248 /
1249
1250Set the flags used by the interpreter for dlopen calls.
1251
1252This is used, for example, when the interpreter loads extension
1253modules. Among other things, this will enable a lazy resolving of
1254symbols when importing a module, if called as sys.setdlopenflags(0).
1255To share symbols across extension modules, call as
1256sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1257modules can be found in the os module (RTLD_xxx constants, e.g.
1258os.RTLD_LAZY).
1259[clinic start generated code]*/
1260
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001261static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001262sys_setdlopenflags_impl(PyObject *module, int new_val)
1263/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001264{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001265 PyInterpreterState *interp = _PyInterpreterState_Get();
1266 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001267 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001268}
1269
Tal Einatede0b6f2018-12-31 17:12:08 +02001270
1271/*[clinic input]
1272sys.getdlopenflags
1273
1274Return the current value of the flags that are used for dlopen calls.
1275
1276The flag constants are defined in the os module.
1277[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001278
1279static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001280sys_getdlopenflags_impl(PyObject *module)
1281/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001282{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001283 PyInterpreterState *interp = _PyInterpreterState_Get();
1284 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001285}
1286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001288
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001289#ifdef USE_MALLOPT
1290/* Link with -lmalloc (or -lmpc) on an SGI */
1291#include <malloc.h>
1292
Tal Einatede0b6f2018-12-31 17:12:08 +02001293/*[clinic input]
1294sys.mdebug
1295
1296 flag: int
1297 /
1298[clinic start generated code]*/
1299
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001300static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001301sys_mdebug_impl(PyObject *module, int flag)
1302/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001303{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001304 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001306 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001307}
1308#endif /* USE_MALLOPT */
1309
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001310size_t
1311_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001312{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001315 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 /* Make sure the type is initialized. float gets initialized late */
1318 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001319 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001320
Benjamin Petersonce798522012-01-22 11:24:29 -05001321 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (method == NULL) {
1323 if (!PyErr_Occurred())
1324 PyErr_Format(PyExc_TypeError,
1325 "Type %.100s doesn't define __sizeof__",
1326 Py_TYPE(o)->tp_name);
1327 }
1328 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001329 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 Py_DECREF(method);
1331 }
1332
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001333 if (res == NULL)
1334 return (size_t)-1;
1335
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001336 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001337 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001338 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001339 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001341 if (size < 0) {
1342 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1343 return (size_t)-1;
1344 }
1345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001346 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001347 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001348 return ((size_t)size) + sizeof(PyGC_Head);
1349 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001350}
1351
1352static PyObject *
1353sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1354{
1355 static char *kwlist[] = {"object", "default", 0};
1356 size_t size;
1357 PyObject *o, *dflt = NULL;
1358
1359 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1360 kwlist, &o, &dflt))
1361 return NULL;
1362
1363 size = _PySys_GetSizeOf(o);
1364
1365 if (size == (size_t)-1 && PyErr_Occurred()) {
1366 /* Has a default value been given */
1367 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1368 PyErr_Clear();
1369 Py_INCREF(dflt);
1370 return dflt;
1371 }
1372 else
1373 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001375
1376 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001377}
1378
1379PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001380"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001381\n\
1382Return the size of object in bytes.");
1383
Tal Einatede0b6f2018-12-31 17:12:08 +02001384/*[clinic input]
1385sys.getrefcount -> Py_ssize_t
1386
1387 object: object
1388 /
1389
1390Return the reference count of object.
1391
1392The count returned is generally one higher than you might expect,
1393because it includes the (temporary) reference as an argument to
1394getrefcount().
1395[clinic start generated code]*/
1396
1397static Py_ssize_t
1398sys_getrefcount_impl(PyObject *module, PyObject *object)
1399/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001400{
Tal Einatede0b6f2018-12-31 17:12:08 +02001401 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001402}
1403
Tim Peters4be93d02002-07-07 19:59:50 +00001404#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001405/*[clinic input]
1406sys.gettotalrefcount -> Py_ssize_t
1407[clinic start generated code]*/
1408
1409static Py_ssize_t
1410sys_gettotalrefcount_impl(PyObject *module)
1411/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001412{
Tal Einatede0b6f2018-12-31 17:12:08 +02001413 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001414}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001415#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001416
Tal Einatede0b6f2018-12-31 17:12:08 +02001417/*[clinic input]
1418sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001419
Tal Einatede0b6f2018-12-31 17:12:08 +02001420Return the number of memory blocks currently allocated.
1421[clinic start generated code]*/
1422
1423static Py_ssize_t
1424sys_getallocatedblocks_impl(PyObject *module)
1425/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001426{
Tal Einatede0b6f2018-12-31 17:12:08 +02001427 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001428}
1429
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001430#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001431/*[clinic input]
1432sys.getcounts
1433[clinic start generated code]*/
1434
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001435static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001436sys_getcounts_impl(PyObject *module)
1437/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001438{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001439 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001440
Pablo Galindo49c75a82018-10-28 15:02:17 +00001441 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001442}
1443#endif
1444
Tal Einatede0b6f2018-12-31 17:12:08 +02001445/*[clinic input]
1446sys._getframe
1447
1448 depth: int = 0
1449 /
1450
1451Return a frame object from the call stack.
1452
1453If optional integer depth is given, return the frame object that many
1454calls below the top of the stack. If that is deeper than the call
1455stack, ValueError is raised. The default for depth is zero, returning
1456the frame at the top of the call stack.
1457
1458This function should be used for internal and specialized purposes
1459only.
1460[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001461
1462static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001463sys__getframe_impl(PyObject *module, int depth)
1464/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001465{
Victor Stinner50b48572018-11-01 01:51:40 +01001466 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001468 while (depth > 0 && f != NULL) {
1469 f = f->f_back;
1470 --depth;
1471 }
1472 if (f == NULL) {
1473 PyErr_SetString(PyExc_ValueError,
1474 "call stack is not deep enough");
1475 return NULL;
1476 }
1477 Py_INCREF(f);
1478 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001479}
1480
Tal Einatede0b6f2018-12-31 17:12:08 +02001481/*[clinic input]
1482sys._current_frames
1483
1484Return a dict mapping each thread's thread id to its current stack frame.
1485
1486This function should be used for specialized purposes only.
1487[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001488
1489static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001490sys__current_frames_impl(PyObject *module)
1491/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001493 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001494}
1495
Tal Einatede0b6f2018-12-31 17:12:08 +02001496/*[clinic input]
1497sys.call_tracing
1498
1499 func: object
1500 args as funcargs: object(subclass_of='&PyTuple_Type')
1501 /
1502
1503Call func(*args), while tracing is enabled.
1504
1505The tracing state is saved, and restored afterwards. This is intended
1506to be called from a debugger from a checkpoint, to recursively debug
1507some other code.
1508[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001509
1510static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001511sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1512/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001515}
1516
Tal Einatede0b6f2018-12-31 17:12:08 +02001517/*[clinic input]
1518sys.callstats
1519
1520Return a tuple of function call statistics.
1521
1522A tuple is returned only if CALL_PROFILE was defined when Python was
1523built. Otherwise, this returns None.
1524
1525When enabled, this function returns detailed, implementation-specific
1526details about the number of function calls executed. The return value
1527is a 11-tuple where the entries in the tuple are counts of:
15280. all function calls
15291. calls to PyFunction_Type objects
15302. PyFunction calls that do not create an argument tuple
15313. PyFunction calls that do not create an argument tuple
1532 and bypass PyEval_EvalCodeEx()
15334. PyMethod calls
15345. PyMethod calls on bound methods
15356. PyType calls
15367. PyCFunction calls
15378. generator calls
15389. All other calls
153910. Number of stack pops performed by call_function()
1540[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001541
Victor Stinner048afd92016-11-28 11:59:04 +01001542static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001543sys_callstats_impl(PyObject *module)
1544/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001545{
1546 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1547 "sys.callstats() has been deprecated in Python 3.7 "
1548 "and will be removed in the future", 1) < 0) {
1549 return NULL;
1550 }
1551
1552 Py_RETURN_NONE;
1553}
1554
1555
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001556#ifdef __cplusplus
1557extern "C" {
1558#endif
1559
Tal Einatede0b6f2018-12-31 17:12:08 +02001560/*[clinic input]
1561sys._debugmallocstats
1562
1563Print summary info to stderr about the state of pymalloc's structures.
1564
1565In Py_DEBUG mode, also perform some expensive internal consistency
1566checks.
1567[clinic start generated code]*/
1568
David Malcolm49526f42012-06-22 14:55:41 -04001569static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001570sys__debugmallocstats_impl(PyObject *module)
1571/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001572{
1573#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001574 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001575 fputc('\n', stderr);
1576 }
David Malcolm49526f42012-06-22 14:55:41 -04001577#endif
1578 _PyObject_DebugTypeStats(stderr);
1579
1580 Py_RETURN_NONE;
1581}
David Malcolm49526f42012-06-22 14:55:41 -04001582
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001583#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001584/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001585extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001586#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001587
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001588#ifdef DYNAMIC_EXECUTION_PROFILE
1589/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001590extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001591#endif
1592
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001593#ifdef __cplusplus
1594}
1595#endif
1596
Tal Einatede0b6f2018-12-31 17:12:08 +02001597
1598/*[clinic input]
1599sys._clear_type_cache
1600
1601Clear the internal type lookup cache.
1602[clinic start generated code]*/
1603
Christian Heimes15ebc882008-02-04 18:48:49 +00001604static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001605sys__clear_type_cache_impl(PyObject *module)
1606/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001607{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 PyType_ClearCache();
1609 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001610}
1611
Tal Einatede0b6f2018-12-31 17:12:08 +02001612/*[clinic input]
1613sys.is_finalizing
1614
1615Return True if Python is exiting.
1616[clinic start generated code]*/
1617
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001618static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001619sys_is_finalizing_impl(PyObject *module)
1620/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001621{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001622 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001623}
1624
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001625#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001626/*[clinic input]
1627sys.getandroidapilevel
1628
1629Return the build time API version of Android as an integer.
1630[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001631
1632static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001633sys_getandroidapilevel_impl(PyObject *module)
1634/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001635{
1636 return PyLong_FromLong(ANDROID_API_LEVEL);
1637}
1638#endif /* ANDROID_API_LEVEL */
1639
1640
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001641static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001643 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001644 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001645 SYS_CALLSTATS_METHODDEF
1646 SYS__CLEAR_TYPE_CACHE_METHODDEF
1647 SYS__CURRENT_FRAMES_METHODDEF
1648 SYS_DISPLAYHOOK_METHODDEF
1649 SYS_EXC_INFO_METHODDEF
1650 SYS_EXCEPTHOOK_METHODDEF
1651 SYS_EXIT_METHODDEF
1652 SYS_GETDEFAULTENCODING_METHODDEF
1653 SYS_GETDLOPENFLAGS_METHODDEF
1654 SYS_GETALLOCATEDBLOCKS_METHODDEF
1655 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001656#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001658#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001659 SYS_GETFILESYSTEMENCODING_METHODDEF
1660 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001661#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001663#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001664 SYS_GETTOTALREFCOUNT_METHODDEF
1665 SYS_GETREFCOUNT_METHODDEF
1666 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001667 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001669 SYS__GETFRAME_METHODDEF
1670 SYS_GETWINDOWSVERSION_METHODDEF
1671 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1672 SYS_INTERN_METHODDEF
1673 SYS_IS_FINALIZING_METHODDEF
1674 SYS_MDEBUG_METHODDEF
1675 SYS_SETCHECKINTERVAL_METHODDEF
1676 SYS_GETCHECKINTERVAL_METHODDEF
1677 SYS_SETSWITCHINTERVAL_METHODDEF
1678 SYS_GETSWITCHINTERVAL_METHODDEF
1679 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001681 SYS_GETPROFILE_METHODDEF
1682 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001683 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001684 SYS_GETTRACE_METHODDEF
1685 SYS_CALL_TRACING_METHODDEF
1686 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001687 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1688 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001689 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1690 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001691 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001692 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001693 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1694 SYS_GETANDROIDAPILEVEL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001695 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001696};
1697
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001698static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001699list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001701 PyObject *list = PyList_New(0);
1702 int i;
1703 if (list == NULL)
1704 return NULL;
1705 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1706 PyObject *name = PyUnicode_FromString(
1707 PyImport_Inittab[i].name);
1708 if (name == NULL)
1709 break;
1710 PyList_Append(list, name);
1711 Py_DECREF(name);
1712 }
1713 if (PyList_Sort(list) != 0) {
1714 Py_DECREF(list);
1715 list = NULL;
1716 }
1717 if (list) {
1718 PyObject *v = PyList_AsTuple(list);
1719 Py_DECREF(list);
1720 list = v;
1721 }
1722 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001723}
1724
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001725/* Pre-initialization support for sys.warnoptions and sys._xoptions
1726 *
1727 * Modern internal code paths:
1728 * These APIs get called after _Py_InitializeCore and get to use the
1729 * regular CPython list, dict, and unicode APIs.
1730 *
1731 * Legacy embedding code paths:
1732 * The multi-phase initialization API isn't public yet, so embedding
1733 * apps still need to be able configure sys.warnoptions and sys._xoptions
1734 * before they call Py_Initialize. To support this, we stash copies of
1735 * the supplied wchar * sequences in linked lists, and then migrate the
1736 * contents of those lists to the sys module in _PyInitializeCore.
1737 *
1738 */
1739
1740struct _preinit_entry {
1741 wchar_t *value;
1742 struct _preinit_entry *next;
1743};
1744
1745typedef struct _preinit_entry *_Py_PreInitEntry;
1746
1747static _Py_PreInitEntry _preinit_warnoptions = NULL;
1748static _Py_PreInitEntry _preinit_xoptions = NULL;
1749
1750static _Py_PreInitEntry
1751_alloc_preinit_entry(const wchar_t *value)
1752{
1753 /* To get this to work, we have to initialize the runtime implicitly */
1754 _PyRuntime_Initialize();
1755
1756 /* Force default allocator, so we can ensure that it also gets used to
1757 * destroy the linked list in _clear_preinit_entries.
1758 */
1759 PyMemAllocatorEx old_alloc;
1760 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1761
1762 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1763 if (node != NULL) {
1764 node->value = _PyMem_RawWcsdup(value);
1765 if (node->value == NULL) {
1766 PyMem_RawFree(node);
1767 node = NULL;
1768 };
1769 };
1770
1771 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1772 return node;
1773};
1774
1775static int
1776_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1777{
1778 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1779 if (new_entry == NULL) {
1780 return -1;
1781 }
1782 /* We maintain the linked list in this order so it's easy to play back
1783 * the add commands in the same order later on in _Py_InitializeCore
1784 */
1785 _Py_PreInitEntry last_entry = *optionlist;
1786 if (last_entry == NULL) {
1787 *optionlist = new_entry;
1788 } else {
1789 while (last_entry->next != NULL) {
1790 last_entry = last_entry->next;
1791 }
1792 last_entry->next = new_entry;
1793 }
1794 return 0;
1795};
1796
1797static void
1798_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1799{
1800 _Py_PreInitEntry current = *optionlist;
1801 *optionlist = NULL;
1802 /* Deallocate the nodes and their contents using the default allocator */
1803 PyMemAllocatorEx old_alloc;
1804 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1805 while (current != NULL) {
1806 _Py_PreInitEntry next = current->next;
1807 PyMem_RawFree(current->value);
1808 PyMem_RawFree(current);
1809 current = next;
1810 }
1811 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1812};
1813
1814static void
1815_clear_all_preinit_options(void)
1816{
1817 _clear_preinit_entries(&_preinit_warnoptions);
1818 _clear_preinit_entries(&_preinit_xoptions);
1819}
1820
1821static int
1822_PySys_ReadPreInitOptions(void)
1823{
1824 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001825 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001826 if (tstate == NULL) {
1827 /* Still don't have a thread state, so something is wrong! */
1828 return -1;
1829 }
1830 _Py_PreInitEntry entry = _preinit_warnoptions;
1831 while (entry != NULL) {
1832 PySys_AddWarnOption(entry->value);
1833 entry = entry->next;
1834 }
1835 entry = _preinit_xoptions;
1836 while (entry != NULL) {
1837 PySys_AddXOption(entry->value);
1838 entry = entry->next;
1839 }
1840
1841 _clear_all_preinit_options();
1842 return 0;
1843};
1844
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001845static PyObject *
1846get_warnoptions(void)
1847{
Eric Snowdae02762017-09-14 00:35:58 -07001848 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001849 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001850 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1851 * interpreter config. When that happens, we need to properly set
1852 * the `warnoptions` reference in the main interpreter config as well.
1853 *
1854 * For Python 3.7, we shouldn't be able to get here due to the
1855 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1856 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1857 * call optional for embedding applications, thus making this
1858 * reachable again.
1859 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001860 warnoptions = PyList_New(0);
1861 if (warnoptions == NULL)
1862 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001863 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1864 Py_DECREF(warnoptions);
1865 return NULL;
1866 }
1867 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001868 }
1869 return warnoptions;
1870}
Guido van Rossum23fff912000-12-15 22:02:05 +00001871
1872void
1873PySys_ResetWarnOptions(void)
1874{
Victor Stinner50b48572018-11-01 01:51:40 +01001875 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001876 if (tstate == NULL) {
1877 _clear_preinit_entries(&_preinit_warnoptions);
1878 return;
1879 }
1880
Eric Snowdae02762017-09-14 00:35:58 -07001881 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (warnoptions == NULL || !PyList_Check(warnoptions))
1883 return;
1884 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001885}
1886
Victor Stinnere1b29952018-10-30 14:31:42 +01001887static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001888_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001889{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001890 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001891 if (warnoptions == NULL) {
1892 return -1;
1893 }
1894 if (PyList_Append(warnoptions, option)) {
1895 return -1;
1896 }
1897 return 0;
1898}
1899
1900void
1901PySys_AddWarnOptionUnicode(PyObject *option)
1902{
Victor Stinnere1b29952018-10-30 14:31:42 +01001903 if (_PySys_AddWarnOptionWithError(option) < 0) {
1904 /* No return value, therefore clear error state if possible */
1905 if (_PyThreadState_UncheckedGet()) {
1906 PyErr_Clear();
1907 }
1908 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001909}
1910
1911void
1912PySys_AddWarnOption(const wchar_t *s)
1913{
Victor Stinner50b48572018-11-01 01:51:40 +01001914 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001915 if (tstate == NULL) {
1916 _append_preinit_entry(&_preinit_warnoptions, s);
1917 return;
1918 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001919 PyObject *unicode;
1920 unicode = PyUnicode_FromWideChar(s, -1);
1921 if (unicode == NULL)
1922 return;
1923 PySys_AddWarnOptionUnicode(unicode);
1924 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001925}
1926
Christian Heimes33fe8092008-04-13 13:53:33 +00001927int
1928PySys_HasWarnOptions(void)
1929{
Eric Snowdae02762017-09-14 00:35:58 -07001930 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001931 return (warnoptions != NULL && PyList_Check(warnoptions)
1932 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001933}
1934
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001935static PyObject *
1936get_xoptions(void)
1937{
Eric Snowdae02762017-09-14 00:35:58 -07001938 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001939 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001940 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1941 * interpreter config. When that happens, we need to properly set
1942 * the `xoptions` reference in the main interpreter config as well.
1943 *
1944 * For Python 3.7, we shouldn't be able to get here due to the
1945 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1946 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1947 * call optional for embedding applications, thus making this
1948 * reachable again.
1949 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001950 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001951 if (xoptions == NULL)
1952 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001953 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1954 Py_DECREF(xoptions);
1955 return NULL;
1956 }
1957 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001958 }
1959 return xoptions;
1960}
1961
Victor Stinnere1b29952018-10-30 14:31:42 +01001962static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001963_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001964{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001965 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001966
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001967 PyObject *opts = get_xoptions();
1968 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001969 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001970 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001971
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001972 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001973 if (!name_end) {
1974 name = PyUnicode_FromWideChar(s, -1);
1975 value = Py_True;
1976 Py_INCREF(value);
1977 }
1978 else {
1979 name = PyUnicode_FromWideChar(s, name_end - s);
1980 value = PyUnicode_FromWideChar(name_end + 1, -1);
1981 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001982 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001983 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001984 }
1985 if (PyDict_SetItem(opts, name, value) < 0) {
1986 goto error;
1987 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001988 Py_DECREF(name);
1989 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001990 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001991
1992error:
1993 Py_XDECREF(name);
1994 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001995 return -1;
1996}
1997
1998void
1999PySys_AddXOption(const wchar_t *s)
2000{
Victor Stinner50b48572018-11-01 01:51:40 +01002001 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002002 if (tstate == NULL) {
2003 _append_preinit_entry(&_preinit_xoptions, s);
2004 return;
2005 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002006 if (_PySys_AddXOptionWithError(s) < 0) {
2007 /* No return value, therefore clear error state if possible */
2008 if (_PyThreadState_UncheckedGet()) {
2009 PyErr_Clear();
2010 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002011 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002012}
2013
2014PyObject *
2015PySys_GetXOptions(void)
2016{
2017 return get_xoptions();
2018}
2019
Guido van Rossum40552d01998-08-06 03:34:39 +00002020/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2021 Two literals concatenated works just fine. If you have a K&R compiler
2022 or other abomination that however *does* understand longer strings,
2023 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002024PyDoc_VAR(sys_doc) =
2025PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002026"This module provides access to some objects used or maintained by the\n\
2027interpreter and to functions that interact strongly with the interpreter.\n\
2028\n\
2029Dynamic objects:\n\
2030\n\
2031argv -- command line arguments; argv[0] is the script pathname if known\n\
2032path -- module search path; path[0] is the script directory, else ''\n\
2033modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002034\n\
2035displayhook -- called to show results in an interactive session\n\
2036excepthook -- called to handle any uncaught exception other than SystemExit\n\
2037 To customize printing in an interactive session or to install a custom\n\
2038 top-level exception handler, assign other functions to replace these.\n\
2039\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002040stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002041stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002042stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002043 By assigning other file objects (or objects that behave like files)\n\
2044 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002045\n\
2046last_type -- type of last uncaught exception\n\
2047last_value -- value of last uncaught exception\n\
2048last_traceback -- traceback of last uncaught exception\n\
2049 These three are only available in an interactive session after a\n\
2050 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002051"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002052)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002053/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002054PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002055"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002056Static objects:\n\
2057\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002058builtin_module_names -- tuple of module names built into this interpreter\n\
2059copyright -- copyright notice pertaining to this interpreter\n\
2060exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002061executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002062float_info -- a struct sequence with information about the float implementation.\n\
2063float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002064hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002065hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002066implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002067int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002068maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002069maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002070platform -- platform identifier\n\
2071prefix -- prefix used to find the Python library\n\
2072thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002073version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002074version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002075"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002076)
Steve Dowercc16be82016-09-08 10:35:16 -07002077#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002078/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002079PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002080"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002081winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002082"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002083)
Steve Dowercc16be82016-09-08 10:35:16 -07002084#endif /* MS_COREDLL */
2085#ifdef MS_WINDOWS
2086/* concatenating string here */
2087PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002088"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002089"
2090)
2091#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002092PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002093"__stdin__ -- the original stdin; don't touch!\n\
2094__stdout__ -- the original stdout; don't touch!\n\
2095__stderr__ -- the original stderr; don't touch!\n\
2096__displayhook__ -- the original displayhook; don't touch!\n\
2097__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002098\n\
2099Functions:\n\
2100\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002101displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002102excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002103exc_info() -- return thread-safe information about the current exception\n\
2104exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002105getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002106getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002107getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002108getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002109getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002110gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002111setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002112setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002113setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002114setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002115settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002116"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002117)
Fred Drakeccede592000-08-14 20:59:57 +00002118/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002119
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002120
2121PyDoc_STRVAR(flags__doc__,
2122"sys.flags\n\
2123\n\
2124Flags provided through command line arguments or environment vars.");
2125
2126static PyTypeObject FlagsType;
2127
2128static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 {"inspect", "-i"},
2131 {"interactive", "-i"},
2132 {"optimize", "-O or -OO"},
2133 {"dont_write_bytecode", "-B"},
2134 {"no_user_site", "-s"},
2135 {"no_site", "-S"},
2136 {"ignore_environment", "-E"},
2137 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 /* {"unbuffered", "-u"}, */
2139 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002140 {"bytes_warning", "-b"},
2141 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002142 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002143 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002144 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002145 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002147};
2148
2149static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 "sys.flags", /* name */
2151 flags__doc__, /* doc */
2152 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002153 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002154};
2155
2156static PyObject*
2157make_flags(void)
2158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 int pos = 0;
2160 PyObject *seq;
Victor Stinner20004952019-03-26 02:31:11 +01002161 const _PyPreConfig *preconfig = &_PyRuntime.preconfig;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002162 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 seq = PyStructSequence_New(&FlagsType);
2165 if (seq == NULL)
2166 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002167
2168#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002170
Victor Stinnerfbca9082018-08-30 00:50:45 +02002171 SetFlag(config->parser_debug);
2172 SetFlag(config->inspect);
2173 SetFlag(config->interactive);
2174 SetFlag(config->optimization_level);
2175 SetFlag(!config->write_bytecode);
2176 SetFlag(!config->user_site_directory);
2177 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002178 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002179 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 /* SetFlag(saw_unbuffered_flag); */
2181 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002182 SetFlag(config->bytes_warning);
2183 SetFlag(config->quiet);
2184 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002185 SetFlag(config->isolated);
2186 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2187 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002188#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002189
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002191 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002192 return NULL;
2193 }
2194 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002195}
2196
Eric Smith0e5b5622009-02-06 01:32:42 +00002197PyDoc_STRVAR(version_info__doc__,
2198"sys.version_info\n\
2199\n\
2200Version information as a named tuple.");
2201
2202static PyTypeObject VersionInfoType;
2203
2204static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 {"major", "Major release number"},
2206 {"minor", "Minor release number"},
2207 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002208 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 {"serial", "Serial release number"},
2210 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002211};
2212
2213static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 "sys.version_info", /* name */
2215 version_info__doc__, /* doc */
2216 version_info_fields, /* fields */
2217 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002218};
2219
2220static PyObject *
2221make_version_info(void)
2222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 PyObject *version_info;
2224 char *s;
2225 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 version_info = PyStructSequence_New(&VersionInfoType);
2228 if (version_info == NULL) {
2229 return NULL;
2230 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 /*
2233 * These release level checks are mutually exclusive and cover
2234 * the field, so don't get too fancy with the pre-processor!
2235 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002236#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002238#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002240#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002242#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002243 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002244#endif
2245
2246#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002248#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002250
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002251 SetIntItem(PY_MAJOR_VERSION);
2252 SetIntItem(PY_MINOR_VERSION);
2253 SetIntItem(PY_MICRO_VERSION);
2254 SetStrItem(s);
2255 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002256#undef SetIntItem
2257#undef SetStrItem
2258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 if (PyErr_Occurred()) {
2260 Py_CLEAR(version_info);
2261 return NULL;
2262 }
2263 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002264}
2265
Brett Cannon3adc7b72012-07-09 14:22:12 -04002266/* sys.implementation values */
2267#define NAME "cpython"
2268const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002269#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2270#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002271#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002272const char *_PySys_ImplCacheTag = TAG;
2273#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002274#undef MAJOR
2275#undef MINOR
2276#undef TAG
2277
Barry Warsaw409da152012-06-03 16:18:47 -04002278static PyObject *
2279make_impl_info(PyObject *version_info)
2280{
2281 int res;
2282 PyObject *impl_info, *value, *ns;
2283
2284 impl_info = PyDict_New();
2285 if (impl_info == NULL)
2286 return NULL;
2287
2288 /* populate the dict */
2289
Brett Cannon3adc7b72012-07-09 14:22:12 -04002290 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002291 if (value == NULL)
2292 goto error;
2293 res = PyDict_SetItemString(impl_info, "name", value);
2294 Py_DECREF(value);
2295 if (res < 0)
2296 goto error;
2297
Brett Cannon3adc7b72012-07-09 14:22:12 -04002298 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002299 if (value == NULL)
2300 goto error;
2301 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2302 Py_DECREF(value);
2303 if (res < 0)
2304 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002305
2306 res = PyDict_SetItemString(impl_info, "version", version_info);
2307 if (res < 0)
2308 goto error;
2309
2310 value = PyLong_FromLong(PY_VERSION_HEX);
2311 if (value == NULL)
2312 goto error;
2313 res = PyDict_SetItemString(impl_info, "hexversion", value);
2314 Py_DECREF(value);
2315 if (res < 0)
2316 goto error;
2317
doko@ubuntu.com55532312016-06-14 08:55:19 +02002318#ifdef MULTIARCH
2319 value = PyUnicode_FromString(MULTIARCH);
2320 if (value == NULL)
2321 goto error;
2322 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2323 Py_DECREF(value);
2324 if (res < 0)
2325 goto error;
2326#endif
2327
Barry Warsaw409da152012-06-03 16:18:47 -04002328 /* dict ready */
2329
2330 ns = _PyNamespace_New(impl_info);
2331 Py_DECREF(impl_info);
2332 return ns;
2333
2334error:
2335 Py_CLEAR(impl_info);
2336 return NULL;
2337}
2338
Martin v. Löwis1a214512008-06-11 05:26:20 +00002339static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002340 PyModuleDef_HEAD_INIT,
2341 "sys",
2342 sys_doc,
2343 -1, /* multiple "initialization" just copies the module dict. */
2344 sys_methods,
2345 NULL,
2346 NULL,
2347 NULL,
2348 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002349};
2350
Eric Snow6b4be192017-05-22 21:36:03 -07002351/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002352#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002353 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002354 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002355 if (v == NULL) { \
2356 goto err_occurred; \
2357 } \
Victor Stinner58049602013-07-22 22:40:00 +02002358 res = PyDict_SetItemString(sysdict, key, v); \
2359 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002360 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002361 } \
2362 } while (0)
2363#define SET_SYS_FROM_STRING(key, value) \
2364 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002365 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002366 if (v == NULL) { \
2367 goto err_occurred; \
2368 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002369 res = PyDict_SetItemString(sysdict, key, v); \
2370 Py_DECREF(v); \
2371 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002372 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002373 } \
2374 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002375
Victor Stinnerab672812019-01-23 15:04:40 +01002376static _PyInitError
2377_PySys_InitCore(PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002378{
Victor Stinnerab672812019-01-23 15:04:40 +01002379 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002380 int res;
2381
Nick Coghland6009512014-11-20 21:39:37 +10002382 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002383
Victor Stinner8fea2522013-10-27 17:15:42 +01002384 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2385 PyDict_GetItemString(sysdict, "displayhook"));
2386 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2387 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002388 SET_SYS_FROM_STRING_BORROW(
2389 "__breakpointhook__",
2390 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 SET_SYS_FROM_STRING("version",
2392 PyUnicode_FromString(Py_GetVersion()));
2393 SET_SYS_FROM_STRING("hexversion",
2394 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002395 SET_SYS_FROM_STRING("_git",
2396 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2397 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002398 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 SET_SYS_FROM_STRING("api_version",
2400 PyLong_FromLong(PYTHON_API_VERSION));
2401 SET_SYS_FROM_STRING("copyright",
2402 PyUnicode_FromString(Py_GetCopyright()));
2403 SET_SYS_FROM_STRING("platform",
2404 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 SET_SYS_FROM_STRING("maxsize",
2406 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2407 SET_SYS_FROM_STRING("float_info",
2408 PyFloat_GetInfo());
2409 SET_SYS_FROM_STRING("int_info",
2410 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002411 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002412 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002413 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2414 goto type_init_failed;
2415 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002416 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002417 SET_SYS_FROM_STRING("hash_info",
2418 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002420 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002421 SET_SYS_FROM_STRING("builtin_module_names",
2422 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002423#if PY_BIG_ENDIAN
2424 SET_SYS_FROM_STRING("byteorder",
2425 PyUnicode_FromString("big"));
2426#else
2427 SET_SYS_FROM_STRING("byteorder",
2428 PyUnicode_FromString("little"));
2429#endif
Fred Drake099325e2000-08-14 15:47:03 +00002430
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002431#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 SET_SYS_FROM_STRING("dllhandle",
2433 PyLong_FromVoidPtr(PyWin_DLLhModule));
2434 SET_SYS_FROM_STRING("winver",
2435 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002436#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002437#ifdef ABIFLAGS
2438 SET_SYS_FROM_STRING("abiflags",
2439 PyUnicode_FromString(ABIFLAGS));
2440#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002443 if (VersionInfoType.tp_name == NULL) {
2444 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002445 &version_info_desc) < 0) {
2446 goto type_init_failed;
2447 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002448 }
Barry Warsaw409da152012-06-03 16:18:47 -04002449 version_info = make_version_info();
2450 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* prevent user from creating new instances */
2452 VersionInfoType.tp_init = NULL;
2453 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002454 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2455 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2456 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002457
Barry Warsaw409da152012-06-03 16:18:47 -04002458 /* implementation */
2459 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2460
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002461 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002462 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002463 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2464 goto type_init_failed;
2465 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002466 }
Eric Snow6b4be192017-05-22 21:36:03 -07002467 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002469
2470#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002471 /* getwindowsversion */
2472 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002473 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002474 &windows_version_desc) < 0) {
2475 goto type_init_failed;
2476 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002477 /* prevent user from creating new instances */
2478 WindowsVersionType.tp_init = NULL;
2479 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002480 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002481 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002482 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002483 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002484 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002485#endif
2486
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002488#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002489 SET_SYS_FROM_STRING("float_repr_style",
2490 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002491#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002492 SET_SYS_FROM_STRING("float_repr_style",
2493 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002494#endif
2495
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002496 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002497
Yury Selivanoveb636452016-09-08 22:01:51 -07002498 /* initialize asyncgen_hooks */
2499 if (AsyncGenHooksType.tp_name == NULL) {
2500 if (PyStructSequence_InitType2(
2501 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002502 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002503 }
2504 }
2505
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002506 if (PyErr_Occurred()) {
2507 goto err_occurred;
2508 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002509 return _Py_INIT_OK();
2510
2511type_init_failed:
2512 return _Py_INIT_ERR("failed to initialize a type");
2513
2514err_occurred:
2515 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002516}
2517
Eric Snow6b4be192017-05-22 21:36:03 -07002518#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002519
2520/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002521#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2522 do { \
2523 PyObject *v = (value); \
2524 if (v == NULL) \
2525 return -1; \
2526 res = PyDict_SetItemString(sysdict, key, v); \
2527 Py_DECREF(v); \
2528 if (res < 0) { \
2529 return res; \
2530 } \
2531 } while (0)
2532
2533int
Victor Stinnerab672812019-01-23 15:04:40 +01002534_PySys_InitMain(PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002535{
Victor Stinnerab672812019-01-23 15:04:40 +01002536 PyObject *sysdict = interp->sysdict;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002537 const _PyCoreConfig *core_config = &interp->core_config;
2538 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002539 int res;
2540
Victor Stinner41264f12017-12-15 02:05:29 +01002541 /* _PyMainInterpreterConfig_Read() must set all these variables */
2542 assert(config->module_search_path != NULL);
2543 assert(config->executable != NULL);
2544 assert(config->prefix != NULL);
2545 assert(config->base_prefix != NULL);
2546 assert(config->exec_prefix != NULL);
2547 assert(config->base_exec_prefix != NULL);
2548
Victor Stinner37cd9822018-11-16 11:55:35 +01002549#define COPY_LIST(KEY, ATTR) \
2550 do { \
Victor Stinnerab672812019-01-23 15:04:40 +01002551 assert(PyList_Check(ATTR)); \
2552 PyObject *list = PyList_GetSlice(ATTR, 0, PyList_GET_SIZE(ATTR)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002553 if (list == NULL) { \
2554 return -1; \
2555 } \
2556 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2557 Py_DECREF(list); \
2558 } while (0)
2559
Victor Stinnerab672812019-01-23 15:04:40 +01002560 COPY_LIST("path", config->module_search_path);
Victor Stinner37cd9822018-11-16 11:55:35 +01002561
Victor Stinner41264f12017-12-15 02:05:29 +01002562 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2563 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2564 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2565 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2566 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2567
Carl Meyerb193fa92018-06-15 22:40:56 -06002568 if (config->pycache_prefix != NULL) {
2569 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2570 } else {
2571 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2572 }
2573
Victor Stinner41264f12017-12-15 02:05:29 +01002574 if (config->argv != NULL) {
2575 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2576 }
2577 if (config->warnoptions != NULL) {
Victor Stinnerab672812019-01-23 15:04:40 +01002578 COPY_LIST("warnoptions", config->warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002579 }
2580 if (config->xoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002581 PyObject *dict = PyDict_Copy(config->xoptions);
2582 if (dict == NULL) {
2583 return -1;
2584 }
2585 SET_SYS_FROM_STRING_BORROW("_xoptions", dict);
2586 Py_DECREF(dict);
Victor Stinner41264f12017-12-15 02:05:29 +01002587 }
2588
Victor Stinner37cd9822018-11-16 11:55:35 +01002589#undef COPY_LIST
2590
Eric Snow6b4be192017-05-22 21:36:03 -07002591 /* Set flags to their final values */
2592 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2593 /* prevent user from creating new instances */
2594 FlagsType.tp_init = NULL;
2595 FlagsType.tp_new = NULL;
2596 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2597 if (res < 0) {
2598 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2599 return res;
2600 }
2601 PyErr_Clear();
2602 }
2603
2604 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002605 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002606
Eric Snowdae02762017-09-14 00:35:58 -07002607 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002608 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002609
Eric Snowdae02762017-09-14 00:35:58 -07002610 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002611 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002612
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002613 /* Transfer any sys.warnoptions and sys._xoptions set directly
2614 * by an embedding application from the linked list to the module. */
2615 if (_PySys_ReadPreInitOptions() != 0)
2616 return -1;
2617
Eric Snow6b4be192017-05-22 21:36:03 -07002618 if (PyErr_Occurred())
2619 return -1;
2620 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002621
2622err_occurred:
2623 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002624}
2625
Victor Stinner41264f12017-12-15 02:05:29 +01002626#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002627#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002628
Victor Stinnerab672812019-01-23 15:04:40 +01002629
2630/* Set up a preliminary stderr printer until we have enough
2631 infrastructure for the io module in place.
2632
2633 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
2634_PyInitError
2635_PySys_SetPreliminaryStderr(PyObject *sysdict)
2636{
2637 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2638 if (pstderr == NULL) {
2639 goto error;
2640 }
2641 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2642 goto error;
2643 }
2644 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2645 goto error;
2646 }
2647 Py_DECREF(pstderr);
2648 return _Py_INIT_OK();
2649
2650error:
2651 Py_XDECREF(pstderr);
2652 return _Py_INIT_ERR("can't set preliminary stderr");
2653}
2654
2655
2656/* Create sys module without all attributes: _PySys_InitMain() should be called
2657 later to add remaining attributes. */
2658_PyInitError
2659_PySys_Create(PyInterpreterState *interp, PyObject **sysmod_p)
2660{
2661 PyObject *modules = PyDict_New();
2662 if (modules == NULL) {
2663 return _Py_INIT_ERR("can't make modules dictionary");
2664 }
2665 interp->modules = modules;
2666
2667 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2668 if (sysmod == NULL) {
2669 return _Py_INIT_ERR("failed to create a module object");
2670 }
2671
2672 PyObject *sysdict = PyModule_GetDict(sysmod);
2673 if (sysdict == NULL) {
2674 return _Py_INIT_ERR("can't initialize sys dict");
2675 }
2676 Py_INCREF(sysdict);
2677 interp->sysdict = sysdict;
2678
2679 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
2680 return _Py_INIT_ERR("can't initialize sys module");
2681 }
2682
2683 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
2684 if (_Py_INIT_FAILED(err)) {
2685 return err;
2686 }
2687
2688 err = _PySys_InitCore(sysdict);
2689 if (_Py_INIT_FAILED(err)) {
2690 return err;
2691 }
2692
2693 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
2694
2695 *sysmod_p = sysmod;
2696 return _Py_INIT_OK();
2697}
2698
2699
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002700static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002701makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002702{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002703 int i, n;
2704 const wchar_t *p;
2705 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002706
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002707 n = 1;
2708 p = path;
2709 while ((p = wcschr(p, delim)) != NULL) {
2710 n++;
2711 p++;
2712 }
2713 v = PyList_New(n);
2714 if (v == NULL)
2715 return NULL;
2716 for (i = 0; ; i++) {
2717 p = wcschr(path, delim);
2718 if (p == NULL)
2719 p = path + wcslen(path); /* End of string */
2720 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2721 if (w == NULL) {
2722 Py_DECREF(v);
2723 return NULL;
2724 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002725 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 if (*p == '\0')
2727 break;
2728 path = p+1;
2729 }
2730 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002731}
2732
2733void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002734PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 PyObject *v;
2737 if ((v = makepathobject(path, DELIM)) == NULL)
2738 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002739 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 Py_FatalError("can't assign sys.path");
2741 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002742}
2743
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002744static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01002745make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002746{
Victor Stinner74f65682019-03-15 15:08:05 +01002747 PyObject *list = PyList_New(argc);
2748 if (list == NULL) {
2749 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002750 }
Victor Stinner74f65682019-03-15 15:08:05 +01002751
2752 for (Py_ssize_t i = 0; i < argc; i++) {
2753 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
2754 if (v == NULL) {
2755 Py_DECREF(list);
2756 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002757 }
Victor Stinner74f65682019-03-15 15:08:05 +01002758 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 }
Victor Stinner74f65682019-03-15 15:08:05 +01002760 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002761}
2762
Victor Stinner11a247d2017-12-13 21:05:57 +01002763void
2764PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002765{
Victor Stinner74f65682019-03-15 15:08:05 +01002766 if (argc < 1 || argv == NULL) {
2767 /* Ensure at least one (empty) argument is seen */
2768 wchar_t* empty_argv[1] = {L""};
2769 argv = empty_argv;
2770 argc = 1;
2771 }
2772
2773 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002774 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002775 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002776 }
2777 if (PySys_SetObject("argv", av) != 0) {
2778 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002779 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002780 }
2781 Py_DECREF(av);
2782
2783 if (updatepath) {
2784 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2785 If argv[0] is a symlink, use the real path. */
Victor Stinner74f65682019-03-15 15:08:05 +01002786 const _PyWstrList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01002787 PyObject *path0 = NULL;
2788 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
2789 if (path0 == NULL) {
2790 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01002791 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01002792
2793 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2794 if (sys_path != NULL) {
2795 if (PyList_Insert(sys_path, 0, path0) < 0) {
2796 Py_DECREF(path0);
2797 Py_FatalError("can't prepend path0 to sys.path");
2798 }
2799 }
2800 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01002801 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002802 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002803}
Guido van Rossuma890e681998-05-12 14:59:24 +00002804
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002805void
2806PySys_SetArgv(int argc, wchar_t **argv)
2807{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002808 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002809}
2810
Victor Stinner14284c22010-04-23 12:02:30 +00002811/* Reimplementation of PyFile_WriteString() no calling indirectly
2812 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2813
2814static int
Victor Stinner79766632010-08-16 17:36:42 +00002815sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002816{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002817 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002819
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002820 if (file == NULL)
2821 return -1;
2822
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002823 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002824 if (writer == NULL)
2825 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002826
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002827 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 if (result == NULL) {
2829 goto error;
2830 } else {
2831 err = 0;
2832 goto finally;
2833 }
Victor Stinner14284c22010-04-23 12:02:30 +00002834
2835error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002836 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002837finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002838 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002839 Py_XDECREF(result);
2840 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002841}
2842
Victor Stinner79766632010-08-16 17:36:42 +00002843static int
2844sys_pyfile_write(const char *text, PyObject *file)
2845{
2846 PyObject *unicode = NULL;
2847 int err;
2848
2849 if (file == NULL)
2850 return -1;
2851
2852 unicode = PyUnicode_FromString(text);
2853 if (unicode == NULL)
2854 return -1;
2855
2856 err = sys_pyfile_write_unicode(unicode, file);
2857 Py_DECREF(unicode);
2858 return err;
2859}
Guido van Rossuma890e681998-05-12 14:59:24 +00002860
2861/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2862 Adapted from code submitted by Just van Rossum.
2863
2864 PySys_WriteStdout(format, ...)
2865 PySys_WriteStderr(format, ...)
2866
2867 The first function writes to sys.stdout; the second to sys.stderr. When
2868 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002869 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002870
Victor Stinner14284c22010-04-23 12:02:30 +00002871 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002872 signal handlers: they may raise a new exception whereas sys_write()
2873 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002874
Guido van Rossuma890e681998-05-12 14:59:24 +00002875 Both take a printf-style format string as their first argument followed
2876 by a variable length argument list determined by the format string.
2877
2878 *** WARNING ***
2879
2880 The format should limit the total size of the formatted output string to
2881 1000 bytes. In particular, this means that no unrestricted "%s" formats
2882 should occur; these should be limited using "%.<N>s where <N> is a
2883 decimal number calculated so that <N> plus the maximum size of other
2884 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2885 which can print hundreds of digits for very large numbers.
2886
2887 */
2888
2889static void
Victor Stinner09054372013-11-06 22:41:44 +01002890sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002891{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002892 PyObject *file;
2893 PyObject *error_type, *error_value, *error_traceback;
2894 char buffer[1001];
2895 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002896
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002898 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2900 if (sys_pyfile_write(buffer, file) != 0) {
2901 PyErr_Clear();
2902 fputs(buffer, fp);
2903 }
2904 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2905 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002906 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002908 }
2909 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002910}
2911
2912void
Guido van Rossuma890e681998-05-12 14:59:24 +00002913PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002914{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002915 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002916
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002918 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002920}
2921
2922void
Guido van Rossuma890e681998-05-12 14:59:24 +00002923PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002926
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002927 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002928 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002929 va_end(va);
2930}
2931
2932static void
Victor Stinner09054372013-11-06 22:41:44 +01002933sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002934{
2935 PyObject *file, *message;
2936 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002937 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002938
2939 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002940 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002941 message = PyUnicode_FromFormatV(format, va);
2942 if (message != NULL) {
2943 if (sys_pyfile_write_unicode(message, file) != 0) {
2944 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002945 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002946 if (utf8 != NULL)
2947 fputs(utf8, fp);
2948 }
2949 Py_DECREF(message);
2950 }
2951 PyErr_Restore(error_type, error_value, error_traceback);
2952}
2953
2954void
2955PySys_FormatStdout(const char *format, ...)
2956{
2957 va_list va;
2958
2959 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002960 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002961 va_end(va);
2962}
2963
2964void
2965PySys_FormatStderr(const char *format, ...)
2966{
2967 va_list va;
2968
2969 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002970 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002972}