blob: 3de94e8468bee11173bed407033f12f4377f59d0 [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 Stinner8b9dbc02019-03-27 01:36:16 +010020#include "pycore_coreconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010021#include "pycore_pylifecycle.h"
22#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010023#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010024#include "pycore_pystate.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020025#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000026
Guido van Rossume2437a11992-03-23 18:20:18 +000027#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020028#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000029
Mark Hammond8696ebc2002-10-08 02:44:31 +000030#ifdef MS_WINDOWS
31#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000032#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000033#endif /* MS_WINDOWS */
34
Guido van Rossum9b38a141996-09-11 23:12:24 +000035#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000036extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000037/* A string loaded from the DLL at startup: */
38extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000039#endif
40
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080041/*[clinic input]
42module sys
43[clinic start generated code]*/
44/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
45
46#include "clinic/sysmodule.c.h"
47
Victor Stinnerbd303c12013-11-07 23:07:29 +010048_Py_IDENTIFIER(_);
49_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070050_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010051_Py_IDENTIFIER(buffer);
52_Py_IDENTIFIER(builtins);
53_Py_IDENTIFIER(encoding);
54_Py_IDENTIFIER(path);
55_Py_IDENTIFIER(stdout);
56_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070057_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010058_Py_IDENTIFIER(write);
59
Guido van Rossum65bf9f21997-04-29 18:33:38 +000060PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010061_PySys_GetObjectId(_Py_Identifier *key)
62{
Victor Stinnercaba55b2018-08-03 15:33:52 +020063 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
64 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010065 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020066 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010067 return _PyDict_GetItemId(sd, key);
68}
69
70PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000071PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072{
Victor Stinnercaba55b2018-08-03 15:33:52 +020073 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
74 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000075 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020076 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000077 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000078}
79
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000080int
Victor Stinnerd67bd452013-11-06 22:36:40 +010081_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
82{
Victor Stinnercaba55b2018-08-03 15:33:52 +020083 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010084 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020085 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010086 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020087 }
88 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010089 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020090 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010091 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020092 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010093 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020094 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010095}
96
97int
Neal Norwitzf3081322007-08-25 00:32:45 +000098PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000099{
Victor Stinnercaba55b2018-08-03 15:33:52 +0200100 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000101 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200102 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000103 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200104 }
105 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200107 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000108 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200109 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200111 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000112}
113
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400114static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200115sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400116{
117 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300118 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400119
120 if (envar == NULL || strlen(envar) == 0) {
121 envar = "pdb.set_trace";
122 }
123 else if (!strcmp(envar, "0")) {
124 /* The breakpoint is explicitly no-op'd. */
125 Py_RETURN_NONE;
126 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300127 /* According to POSIX the string returned by getenv() might be invalidated
128 * or the string content might be overwritten by a subsequent call to
129 * getenv(). Since importing a module can performs the getenv() calls,
130 * we need to save a copy of envar. */
131 envar = _PyMem_RawStrdup(envar);
132 if (envar == NULL) {
133 PyErr_NoMemory();
134 return NULL;
135 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200136 const char *last_dot = strrchr(envar, '.');
137 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400138 PyObject *modulepath = NULL;
139
140 if (last_dot == NULL) {
141 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
142 modulepath = PyUnicode_FromString("builtins");
143 attrname = envar;
144 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200145 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400146 /* Split on the last dot; */
147 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
148 attrname = last_dot + 1;
149 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200150 else {
151 goto warn;
152 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400153 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300154 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400155 return NULL;
156 }
157
Anthony Sottiledce345c2018-11-01 10:25:05 -0700158 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400159 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400160
161 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200162 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
163 goto warn;
164 }
165 PyMem_RawFree(envar);
166 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400167 }
168
169 PyObject *hook = PyObject_GetAttrString(module, attrname);
170 Py_DECREF(module);
171
172 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200173 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
174 goto warn;
175 }
176 PyMem_RawFree(envar);
177 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400178 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300179 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400180 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
181 Py_DECREF(hook);
182 return retval;
183
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200184 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400185 /* If any of the imports went wrong, then warn and ignore. */
186 PyErr_Clear();
187 int status = PyErr_WarnFormat(
188 PyExc_RuntimeWarning, 0,
189 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300190 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400191 if (status < 0) {
192 /* Printing the warning raised an exception. */
193 return NULL;
194 }
195 /* The warning was (probably) issued. */
196 Py_RETURN_NONE;
197}
198
199PyDoc_STRVAR(breakpointhook_doc,
200"breakpointhook(*args, **kws)\n"
201"\n"
202"This hook function is called by built-in breakpoint().\n"
203);
204
Victor Stinner13d49ee2010-12-04 17:24:33 +0000205/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
206 error handler. If sys.stdout has a buffer attribute, use
207 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
208 sys.stdout.write(redecoded).
209
210 Helper function for sys_displayhook(). */
211static int
212sys_displayhook_unencodable(PyObject *outf, PyObject *o)
213{
214 PyObject *stdout_encoding = NULL;
215 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200216 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000217 int ret;
218
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200219 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000220 if (stdout_encoding == NULL)
221 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200222 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000223 if (stdout_encoding_str == NULL)
224 goto error;
225
226 repr_str = PyObject_Repr(o);
227 if (repr_str == NULL)
228 goto error;
229 encoded = PyUnicode_AsEncodedString(repr_str,
230 stdout_encoding_str,
231 "backslashreplace");
232 Py_DECREF(repr_str);
233 if (encoded == NULL)
234 goto error;
235
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200236 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000237 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100238 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000239 Py_DECREF(buffer);
240 Py_DECREF(encoded);
241 if (result == NULL)
242 goto error;
243 Py_DECREF(result);
244 }
245 else {
246 PyErr_Clear();
247 escaped_str = PyUnicode_FromEncodedObject(encoded,
248 stdout_encoding_str,
249 "strict");
250 Py_DECREF(encoded);
251 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
252 Py_DECREF(escaped_str);
253 goto error;
254 }
255 Py_DECREF(escaped_str);
256 }
257 ret = 0;
258 goto finally;
259
260error:
261 ret = -1;
262finally:
263 Py_XDECREF(stdout_encoding);
264 return ret;
265}
266
Tal Einatede0b6f2018-12-31 17:12:08 +0200267/*[clinic input]
268sys.displayhook
269
270 object as o: object
271 /
272
273Print an object to sys.stdout and also save it in builtins._
274[clinic start generated code]*/
275
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000276static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200277sys_displayhook(PyObject *module, PyObject *o)
278/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000279{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100281 PyObject *builtins;
282 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000283 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000284
Eric Snow3f9eee62017-09-15 16:35:20 -0600285 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 if (builtins == NULL) {
Stefan Krah027b09c2019-03-25 21:50:58 +0100287 if (!PyErr_Occurred()) {
288 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
289 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return NULL;
291 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600292 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 /* Print value except if None */
295 /* After printing, also assign to '_' */
296 /* Before, set '_' to None to avoid recursion */
297 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200298 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200300 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000301 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100302 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (outf == NULL || outf == Py_None) {
304 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
305 return NULL;
306 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000307 if (PyFile_WriteObject(o, outf, 0) != 0) {
308 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
309 /* repr(o) is not encodable to sys.stdout.encoding with
310 * sys.stdout.errors error handler (which is probably 'strict') */
311 PyErr_Clear();
312 err = sys_displayhook_unencodable(outf, o);
313 if (err)
314 return NULL;
315 }
316 else {
317 return NULL;
318 }
319 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100320 if (newline == NULL) {
321 newline = PyUnicode_FromString("\n");
322 if (newline == NULL)
323 return NULL;
324 }
325 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200327 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200329 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000330}
331
Tal Einatede0b6f2018-12-31 17:12:08 +0200332
333/*[clinic input]
334sys.excepthook
335
336 exctype: object
337 value: object
338 traceback: object
339 /
340
341Handle an exception by displaying it with a traceback on sys.stderr.
342[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000343
344static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200345sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
346 PyObject *traceback)
347/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000348{
Tal Einatede0b6f2018-12-31 17:12:08 +0200349 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200350 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000351}
352
Tal Einatede0b6f2018-12-31 17:12:08 +0200353
354/*[clinic input]
355sys.exc_info
356
357Return current exception information: (type, value, traceback).
358
359Return information about the most recent exception caught by an except
360clause in the current stack frame or in an older stack frame.
361[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000362
363static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200364sys_exc_info_impl(PyObject *module)
365/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000366{
Victor Stinner50b48572018-11-01 01:51:40 +0100367 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000368 return Py_BuildValue(
369 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100370 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
371 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
372 err_info->exc_traceback != NULL ?
373 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000374}
375
Tal Einatede0b6f2018-12-31 17:12:08 +0200376
377/*[clinic input]
378sys.exit
379
380 status: object = NULL
381 /
382
383Exit the interpreter by raising SystemExit(status).
384
385If the status is omitted or None, it defaults to zero (i.e., success).
386If the status is an integer, it will be used as the system exit status.
387If it is another kind of object, it will be printed and the system
388exit status will be one (i.e., failure).
389[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000390
391static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200392sys_exit_impl(PyObject *module, PyObject *status)
393/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000394{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200396 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000398}
399
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000400
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000401
Tal Einatede0b6f2018-12-31 17:12:08 +0200402/*[clinic input]
403sys.getdefaultencoding
404
405Return the current default encoding used by the Unicode implementation.
406[clinic start generated code]*/
407
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000408static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200409sys_getdefaultencoding_impl(PyObject *module)
410/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000413}
414
Tal Einatede0b6f2018-12-31 17:12:08 +0200415/*[clinic input]
416sys.getfilesystemencoding
417
418Return the encoding used to convert Unicode filenames to OS filenames.
419[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000420
421static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200422sys_getfilesystemencoding_impl(PyObject *module)
423/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000424{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200425 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
426 const _PyCoreConfig *config = &interp->core_config;
427 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000428}
429
Tal Einatede0b6f2018-12-31 17:12:08 +0200430/*[clinic input]
431sys.getfilesystemencodeerrors
432
433Return the error mode used Unicode to OS filename conversion.
434[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000435
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000436static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200437sys_getfilesystemencodeerrors_impl(PyObject *module)
438/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700439{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200440 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
441 const _PyCoreConfig *config = &interp->core_config;
442 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700443}
444
Tal Einatede0b6f2018-12-31 17:12:08 +0200445/*[clinic input]
446sys.intern
447
448 string as s: unicode
449 /
450
451``Intern'' the given string.
452
453This enters the string in the (global) table of interned strings whose
454purpose is to speed up dictionary lookups. Return the string itself or
455the previously interned string object with the same value.
456[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700457
458static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200459sys_intern_impl(PyObject *module, PyObject *s)
460/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000461{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 if (PyUnicode_CheckExact(s)) {
463 Py_INCREF(s);
464 PyUnicode_InternInPlace(&s);
465 return s;
466 }
467 else {
468 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200469 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 return NULL;
471 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000472}
473
Georg Brandl66a796e2006-12-19 20:50:34 +0000474
Fred Drake5755ce62001-06-27 19:19:46 +0000475/*
476 * Cached interned string objects used for calling the profile and
477 * trace functions. Initialized by trace_init().
478 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000479static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000480
481static int
482trace_init(void)
483{
Nick Coghlan5a851672017-09-08 10:14:16 +1000484 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200485 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000486 "c_call", "c_exception", "c_return",
487 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200488 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyObject *name;
490 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000491 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (whatstrings[i] == NULL) {
493 name = PyUnicode_InternFromString(whatnames[i]);
494 if (name == NULL)
495 return -1;
496 whatstrings[i] = name;
497 }
498 }
499 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000500}
501
502
503static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100504call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000505 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000507 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200508 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000509
Victor Stinner78da82b2016-08-20 01:22:57 +0200510 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000511 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200512 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100513
Victor Stinner78da82b2016-08-20 01:22:57 +0200514 stack[0] = (PyObject *)frame;
515 stack[1] = whatstrings[what];
516 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200519 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000520
Victor Stinner78da82b2016-08-20 01:22:57 +0200521 PyFrame_LocalsToFast(frame, 1);
522 if (result == NULL) {
523 PyTraceBack_Here(frame);
524 }
525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000526 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000527}
528
529static int
530profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000532{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000533 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (arg == NULL)
536 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100537 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (result == NULL) {
539 PyEval_SetProfile(NULL, NULL);
540 return -1;
541 }
542 Py_DECREF(result);
543 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000544}
545
546static int
547trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000548 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000549{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 PyObject *callback;
551 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000553 if (what == PyTrace_CALL)
554 callback = self;
555 else
556 callback = frame->f_trace;
557 if (callback == NULL)
558 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100559 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 if (result == NULL) {
561 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200562 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000563 return -1;
564 }
565 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300566 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 }
568 else {
569 Py_DECREF(result);
570 }
571 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000572}
Fred Draked0838392001-06-16 21:02:31 +0000573
Fred Drake8b4d01d2000-05-09 19:57:01 +0000574static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000575sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000576{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (trace_init() == -1)
578 return NULL;
579 if (args == Py_None)
580 PyEval_SetTrace(NULL, NULL);
581 else
582 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200583 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000584}
585
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000586PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000587"settrace(function)\n\
588\n\
589Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000590function call. See the debugger chapter in the library manual."
591);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000592
Tal Einatede0b6f2018-12-31 17:12:08 +0200593/*[clinic input]
594sys.gettrace
595
596Return the global debug tracing function set with sys.settrace.
597
598See the debugger chapter in the library manual.
599[clinic start generated code]*/
600
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000601static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200602sys_gettrace_impl(PyObject *module)
603/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000604{
Victor Stinner50b48572018-11-01 01:51:40 +0100605 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000606 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000607
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000608 if (temp == NULL)
609 temp = Py_None;
610 Py_INCREF(temp);
611 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000612}
613
Christian Heimes9bd667a2008-01-20 15:14:11 +0000614static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000615sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000616{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (trace_init() == -1)
618 return NULL;
619 if (args == Py_None)
620 PyEval_SetProfile(NULL, NULL);
621 else
622 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200623 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000624}
625
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000626PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000627"setprofile(function)\n\
628\n\
629Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000630and return. See the profiler chapter in the library manual."
631);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000632
Tal Einatede0b6f2018-12-31 17:12:08 +0200633/*[clinic input]
634sys.getprofile
635
636Return the profiling function set with sys.setprofile.
637
638See the profiler chapter in the library manual.
639[clinic start generated code]*/
640
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000641static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200642sys_getprofile_impl(PyObject *module)
643/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000644{
Victor Stinner50b48572018-11-01 01:51:40 +0100645 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000647
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000648 if (temp == NULL)
649 temp = Py_None;
650 Py_INCREF(temp);
651 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000652}
653
Tal Einatede0b6f2018-12-31 17:12:08 +0200654/*[clinic input]
655sys.setcheckinterval
656
657 n: int
658 /
659
660Set the async event check interval to n instructions.
661
662This tells the Python interpreter to check for asynchronous events
663every n instructions.
664
665This also affects how often thread switches occur.
666[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000667
668static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200669sys_setcheckinterval_impl(PyObject *module, int n)
670/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (PyErr_WarnEx(PyExc_DeprecationWarning,
673 "sys.getcheckinterval() and sys.setcheckinterval() "
674 "are deprecated. Use sys.setswitchinterval() "
675 "instead.", 1) < 0)
676 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200677
Victor Stinnercaba55b2018-08-03 15:33:52 +0200678 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +0200679 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200680 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000681}
682
Tal Einatede0b6f2018-12-31 17:12:08 +0200683/*[clinic input]
684sys.getcheckinterval
685
686Return the current check interval; see sys.setcheckinterval().
687[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000688
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000689static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200690sys_getcheckinterval_impl(PyObject *module)
691/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000693 if (PyErr_WarnEx(PyExc_DeprecationWarning,
694 "sys.getcheckinterval() and sys.setcheckinterval() "
695 "are deprecated. Use sys.getswitchinterval() "
696 "instead.", 1) < 0)
697 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200698 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600699 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000700}
701
Tal Einatede0b6f2018-12-31 17:12:08 +0200702/*[clinic input]
703sys.setswitchinterval
704
705 interval: double
706 /
707
708Set the ideal thread switching delay inside the Python interpreter.
709
710The actual frequency of switching threads can be lower if the
711interpreter executes long sequences of uninterruptible code
712(this is implementation-specific and workload-dependent).
713
714The parameter must represent the desired switching delay in seconds
715A typical value is 0.005 (5 milliseconds).
716[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000717
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000718static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200719sys_setswitchinterval_impl(PyObject *module, double interval)
720/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000721{
Tal Einatede0b6f2018-12-31 17:12:08 +0200722 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyErr_SetString(PyExc_ValueError,
724 "switch interval must be strictly positive");
725 return NULL;
726 }
Tal Einatede0b6f2018-12-31 17:12:08 +0200727 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200728 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000729}
730
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000731
Tal Einatede0b6f2018-12-31 17:12:08 +0200732/*[clinic input]
733sys.getswitchinterval -> double
734
735Return the current thread switch interval; see sys.setswitchinterval().
736[clinic start generated code]*/
737
738static double
739sys_getswitchinterval_impl(PyObject *module)
740/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000741{
Tal Einatede0b6f2018-12-31 17:12:08 +0200742 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000743}
744
Tal Einatede0b6f2018-12-31 17:12:08 +0200745/*[clinic input]
746sys.setrecursionlimit
747
748 limit as new_limit: int
749 /
750
751Set the maximum depth of the Python interpreter stack to n.
752
753This limit prevents infinite recursion from causing an overflow of the C
754stack and crashing Python. The highest possible limit is platform-
755dependent.
756[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000757
Tim Peterse5e065b2003-07-06 18:36:54 +0000758static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200759sys_setrecursionlimit_impl(PyObject *module, int new_limit)
760/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000761{
Tal Einatede0b6f2018-12-31 17:12:08 +0200762 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +0200763 PyThreadState *tstate;
764
Victor Stinner50856d52015-10-13 00:11:21 +0200765 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000766 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200767 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000768 return NULL;
769 }
Victor Stinner50856d52015-10-13 00:11:21 +0200770
771 /* Issue #25274: When the recursion depth hits the recursion limit in
772 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
773 set to 1 and a RecursionError is raised. The overflowed flag is reset
774 to 0 when the recursion depth goes below the low-water mark: see
775 Py_LeaveRecursiveCall().
776
777 Reject too low new limit if the current recursion depth is higher than
778 the new low-water mark. Otherwise it may not be possible anymore to
779 reset the overflowed flag to 0. */
780 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100781 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200782 if (tstate->recursion_depth >= mark) {
783 PyErr_Format(PyExc_RecursionError,
784 "cannot set the recursion limit to %i at "
785 "the recursion depth %i: the limit is too low",
786 new_limit, tstate->recursion_depth);
787 return NULL;
788 }
789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200791 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000792}
793
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800794/*[clinic input]
795sys.set_coroutine_origin_tracking_depth
796
797 depth: int
798
799Enable or disable origin tracking for coroutine objects in this thread.
800
Tal Einatede0b6f2018-12-31 17:12:08 +0200801Coroutine objects will track 'depth' frames of traceback information
802about where they came from, available in their cr_origin attribute.
803
804Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800805[clinic start generated code]*/
806
807static PyObject *
808sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +0200809/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800810{
811 if (depth < 0) {
812 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
813 return NULL;
814 }
815 _PyEval_SetCoroutineOriginTrackingDepth(depth);
816 Py_RETURN_NONE;
817}
818
819/*[clinic input]
820sys.get_coroutine_origin_tracking_depth -> int
821
822Check status of origin tracking for coroutine objects in this thread.
823[clinic start generated code]*/
824
825static int
826sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
827/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
828{
829 return _PyEval_GetCoroutineOriginTrackingDepth();
830}
831
Tal Einatede0b6f2018-12-31 17:12:08 +0200832/*[clinic input]
833sys.set_coroutine_wrapper
834
835 wrapper: object
836 /
837
838Set a wrapper for coroutine objects.
839[clinic start generated code]*/
840
Yury Selivanov75445082015-05-11 22:57:16 -0400841static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200842sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
843/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400844{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800845 if (PyErr_WarnEx(PyExc_DeprecationWarning,
846 "set_coroutine_wrapper is deprecated", 1) < 0) {
847 return NULL;
848 }
849
Yury Selivanov75445082015-05-11 22:57:16 -0400850 if (wrapper != Py_None) {
851 if (!PyCallable_Check(wrapper)) {
852 PyErr_Format(PyExc_TypeError,
853 "callable expected, got %.50s",
854 Py_TYPE(wrapper)->tp_name);
855 return NULL;
856 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400857 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400858 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400859 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400860 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400861 }
Yury Selivanov75445082015-05-11 22:57:16 -0400862 Py_RETURN_NONE;
863}
864
Tal Einatede0b6f2018-12-31 17:12:08 +0200865/*[clinic input]
866sys.get_coroutine_wrapper
867
868Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
869[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400870
871static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200872sys_get_coroutine_wrapper_impl(PyObject *module)
873/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400874{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800875 if (PyErr_WarnEx(PyExc_DeprecationWarning,
876 "get_coroutine_wrapper is deprecated", 1) < 0) {
877 return NULL;
878 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400879 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400880 if (wrapper == NULL) {
881 wrapper = Py_None;
882 }
883 Py_INCREF(wrapper);
884 return wrapper;
885}
886
Yury Selivanov75445082015-05-11 22:57:16 -0400887
Yury Selivanoveb636452016-09-08 22:01:51 -0700888static PyTypeObject AsyncGenHooksType;
889
890PyDoc_STRVAR(asyncgen_hooks_doc,
891"asyncgen_hooks\n\
892\n\
893A struct sequence providing information about asynhronous\n\
894generators hooks. The attributes are read only.");
895
896static PyStructSequence_Field asyncgen_hooks_fields[] = {
897 {"firstiter", "Hook to intercept first iteration"},
898 {"finalizer", "Hook to intercept finalization"},
899 {0}
900};
901
902static PyStructSequence_Desc asyncgen_hooks_desc = {
903 "asyncgen_hooks", /* name */
904 asyncgen_hooks_doc, /* doc */
905 asyncgen_hooks_fields , /* fields */
906 2
907};
908
Yury Selivanoveb636452016-09-08 22:01:51 -0700909static PyObject *
910sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
911{
912 static char *keywords[] = {"firstiter", "finalizer", NULL};
913 PyObject *firstiter = NULL;
914 PyObject *finalizer = NULL;
915
916 if (!PyArg_ParseTupleAndKeywords(
917 args, kw, "|OO", keywords,
918 &firstiter, &finalizer)) {
919 return NULL;
920 }
921
922 if (finalizer && finalizer != Py_None) {
923 if (!PyCallable_Check(finalizer)) {
924 PyErr_Format(PyExc_TypeError,
925 "callable finalizer expected, got %.50s",
926 Py_TYPE(finalizer)->tp_name);
927 return NULL;
928 }
929 _PyEval_SetAsyncGenFinalizer(finalizer);
930 }
931 else if (finalizer == Py_None) {
932 _PyEval_SetAsyncGenFinalizer(NULL);
933 }
934
935 if (firstiter && firstiter != Py_None) {
936 if (!PyCallable_Check(firstiter)) {
937 PyErr_Format(PyExc_TypeError,
938 "callable firstiter expected, got %.50s",
939 Py_TYPE(firstiter)->tp_name);
940 return NULL;
941 }
942 _PyEval_SetAsyncGenFirstiter(firstiter);
943 }
944 else if (firstiter == Py_None) {
945 _PyEval_SetAsyncGenFirstiter(NULL);
946 }
947
948 Py_RETURN_NONE;
949}
950
951PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +0200952"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -0700953\n\
954Set a finalizer for async generators objects."
955);
956
Tal Einatede0b6f2018-12-31 17:12:08 +0200957/*[clinic input]
958sys.get_asyncgen_hooks
959
960Return the installed asynchronous generators hooks.
961
962This returns a namedtuple of the form (firstiter, finalizer).
963[clinic start generated code]*/
964
Yury Selivanoveb636452016-09-08 22:01:51 -0700965static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200966sys_get_asyncgen_hooks_impl(PyObject *module)
967/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -0700968{
969 PyObject *res;
970 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
971 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
972
973 res = PyStructSequence_New(&AsyncGenHooksType);
974 if (res == NULL) {
975 return NULL;
976 }
977
978 if (firstiter == NULL) {
979 firstiter = Py_None;
980 }
981
982 if (finalizer == NULL) {
983 finalizer = Py_None;
984 }
985
986 Py_INCREF(firstiter);
987 PyStructSequence_SET_ITEM(res, 0, firstiter);
988
989 Py_INCREF(finalizer);
990 PyStructSequence_SET_ITEM(res, 1, finalizer);
991
992 return res;
993}
994
Yury Selivanoveb636452016-09-08 22:01:51 -0700995
Mark Dickinsondc787d22010-05-23 13:33:13 +0000996static PyTypeObject Hash_InfoType;
997
998PyDoc_STRVAR(hash_info_doc,
999"hash_info\n\
1000\n\
1001A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001002hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001003
1004static PyStructSequence_Field hash_info_fields[] = {
1005 {"width", "width of the type used for hashing, in bits"},
1006 {"modulus", "prime number giving the modulus on which the hash "
1007 "function is based"},
1008 {"inf", "value to be used for hash of a positive infinity"},
1009 {"nan", "value to be used for hash of a nan"},
1010 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001011 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1012 "memoryviews"},
1013 {"hash_bits", "internal output size of hash algorithm"},
1014 {"seed_bits", "seed size of hash algorithm"},
1015 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001016 {NULL, NULL}
1017};
1018
1019static PyStructSequence_Desc hash_info_desc = {
1020 "sys.hash_info",
1021 hash_info_doc,
1022 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001023 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001024};
1025
Matthias Klosed885e952010-07-06 10:53:30 +00001026static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001027get_hash_info(void)
1028{
1029 PyObject *hash_info;
1030 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001031 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001032 hash_info = PyStructSequence_New(&Hash_InfoType);
1033 if (hash_info == NULL)
1034 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001035 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001036 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001037 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001038 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001039 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001040 PyStructSequence_SET_ITEM(hash_info, field++,
1041 PyLong_FromLong(_PyHASH_INF));
1042 PyStructSequence_SET_ITEM(hash_info, field++,
1043 PyLong_FromLong(_PyHASH_NAN));
1044 PyStructSequence_SET_ITEM(hash_info, field++,
1045 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001046 PyStructSequence_SET_ITEM(hash_info, field++,
1047 PyUnicode_FromString(hashfunc->name));
1048 PyStructSequence_SET_ITEM(hash_info, field++,
1049 PyLong_FromLong(hashfunc->hash_bits));
1050 PyStructSequence_SET_ITEM(hash_info, field++,
1051 PyLong_FromLong(hashfunc->seed_bits));
1052 PyStructSequence_SET_ITEM(hash_info, field++,
1053 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001054 if (PyErr_Occurred()) {
1055 Py_CLEAR(hash_info);
1056 return NULL;
1057 }
1058 return hash_info;
1059}
Tal Einatede0b6f2018-12-31 17:12:08 +02001060/*[clinic input]
1061sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001062
Tal Einatede0b6f2018-12-31 17:12:08 +02001063Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001064
Tal Einatede0b6f2018-12-31 17:12:08 +02001065The recursion limit is the maximum depth of the Python interpreter
1066stack. This limit prevents infinite recursion from causing an overflow
1067of the C stack and crashing Python.
1068[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001069
1070static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001071sys_getrecursionlimit_impl(PyObject *module)
1072/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001075}
1076
Mark Hammond8696ebc2002-10-08 02:44:31 +00001077#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001078
Eric Smithf7bb5782010-01-27 00:44:57 +00001079static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1080
1081static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 {"major", "Major version number"},
1083 {"minor", "Minor version number"},
1084 {"build", "Build number"},
1085 {"platform", "Operating system platform"},
1086 {"service_pack", "Latest Service Pack installed on the system"},
1087 {"service_pack_major", "Service Pack major version number"},
1088 {"service_pack_minor", "Service Pack minor version number"},
1089 {"suite_mask", "Bit mask identifying available product suites"},
1090 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001091 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001093};
1094
1095static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001096 "sys.getwindowsversion", /* name */
1097 sys_getwindowsversion__doc__, /* doc */
1098 windows_version_fields, /* fields */
1099 5 /* For backward compatibility,
1100 only the first 5 items are accessible
1101 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001102};
1103
Steve Dower3e96f322015-03-02 08:01:10 -08001104/* Disable deprecation warnings about GetVersionEx as the result is
1105 being passed straight through to the caller, who is responsible for
1106 using it correctly. */
1107#pragma warning(push)
1108#pragma warning(disable:4996)
1109
Tal Einatede0b6f2018-12-31 17:12:08 +02001110/*[clinic input]
1111sys.getwindowsversion
1112
1113Return info about the running version of Windows as a named tuple.
1114
1115The members are named: major, minor, build, platform, service_pack,
1116service_pack_major, service_pack_minor, suite_mask, product_type and
1117platform_version. For backward compatibility, only the first 5 items
1118are available by indexing. All elements are numbers, except
1119service_pack and platform_type which are strings, and platform_version
1120which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1121workstation, 2 for a domain controller, 3 for a server.
1122Platform_version is a 3-tuple containing a version number that is
1123intended for identifying the OS rather than feature detection.
1124[clinic start generated code]*/
1125
Mark Hammond8696ebc2002-10-08 02:44:31 +00001126static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001127sys_getwindowsversion_impl(PyObject *module)
1128/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 PyObject *version;
1131 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001132 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001133 DWORD realMajor, realMinor, realBuild;
1134 HANDLE hKernel32;
1135 wchar_t kernel32_path[MAX_PATH];
1136 LPVOID verblock;
1137 DWORD verblock_size;
1138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001140 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001142
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 version = PyStructSequence_New(&WindowsVersionType);
1144 if (version == NULL)
1145 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001146
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1148 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1149 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1150 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001151 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1153 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1154 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1155 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001156
Steve Dower74f4af72016-09-17 17:27:48 -07001157 realMajor = ver.dwMajorVersion;
1158 realMinor = ver.dwMinorVersion;
1159 realBuild = ver.dwBuildNumber;
1160
1161 // GetVersion will lie if we are running in a compatibility mode.
1162 // We need to read the version info from a system file resource
1163 // to accurately identify the OS version. If we fail for any reason,
1164 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001165 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001166 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001167 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001168 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1169 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1170 (verblock = PyMem_RawMalloc(verblock_size))) {
1171 VS_FIXEDFILEINFO *ffi;
1172 UINT ffi_len;
1173
1174 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1175 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1176 realMajor = HIWORD(ffi->dwProductVersionMS);
1177 realMinor = LOWORD(ffi->dwProductVersionMS);
1178 realBuild = HIWORD(ffi->dwProductVersionLS);
1179 }
1180 PyMem_RawFree(verblock);
1181 }
Segev Finer48fb7662017-06-04 20:52:27 +03001182 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1183 realMajor,
1184 realMinor,
1185 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001186 ));
1187
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001188 if (PyErr_Occurred()) {
1189 Py_DECREF(version);
1190 return NULL;
1191 }
Steve Dower74f4af72016-09-17 17:27:48 -07001192
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001194}
1195
Steve Dower3e96f322015-03-02 08:01:10 -08001196#pragma warning(pop)
1197
Tal Einatede0b6f2018-12-31 17:12:08 +02001198/*[clinic input]
1199sys._enablelegacywindowsfsencoding
1200
1201Changes the default filesystem encoding to mbcs:replace.
1202
1203This is done for consistency with earlier versions of Python. See PEP
1204529 for more information.
1205
1206This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1207environment variable before launching Python.
1208[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001209
1210static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001211sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1212/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001213{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001214 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1215 _PyCoreConfig *config = &interp->core_config;
1216
1217 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1218 char *encoding = _PyMem_RawStrdup("mbcs");
1219 char *errors = _PyMem_RawStrdup("replace");
1220 if (encoding == NULL || errors == NULL) {
1221 PyMem_Free(encoding);
1222 PyMem_Free(errors);
1223 PyErr_NoMemory();
1224 return NULL;
1225 }
1226
1227 PyMem_RawFree(config->filesystem_encoding);
1228 config->filesystem_encoding = encoding;
1229 PyMem_RawFree(config->filesystem_errors);
1230 config->filesystem_errors = errors;
1231
1232 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1233 config->filesystem_errors) < 0) {
1234 PyErr_NoMemory();
1235 return NULL;
1236 }
1237
Steve Dowercc16be82016-09-08 10:35:16 -07001238 Py_RETURN_NONE;
1239}
1240
Mark Hammond8696ebc2002-10-08 02:44:31 +00001241#endif /* MS_WINDOWS */
1242
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001243#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001244
1245/*[clinic input]
1246sys.setdlopenflags
1247
1248 flags as new_val: int
1249 /
1250
1251Set the flags used by the interpreter for dlopen calls.
1252
1253This is used, for example, when the interpreter loads extension
1254modules. Among other things, this will enable a lazy resolving of
1255symbols when importing a module, if called as sys.setdlopenflags(0).
1256To share symbols across extension modules, call as
1257sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1258modules can be found in the os module (RTLD_xxx constants, e.g.
1259os.RTLD_LAZY).
1260[clinic start generated code]*/
1261
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001262static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001263sys_setdlopenflags_impl(PyObject *module, int new_val)
1264/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001265{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001266 PyInterpreterState *interp = _PyInterpreterState_Get();
1267 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001268 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001269}
1270
Tal Einatede0b6f2018-12-31 17:12:08 +02001271
1272/*[clinic input]
1273sys.getdlopenflags
1274
1275Return the current value of the flags that are used for dlopen calls.
1276
1277The flag constants are defined in the os module.
1278[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001279
1280static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001281sys_getdlopenflags_impl(PyObject *module)
1282/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001283{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001284 PyInterpreterState *interp = _PyInterpreterState_Get();
1285 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001286}
1287
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001289
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001290#ifdef USE_MALLOPT
1291/* Link with -lmalloc (or -lmpc) on an SGI */
1292#include <malloc.h>
1293
Tal Einatede0b6f2018-12-31 17:12:08 +02001294/*[clinic input]
1295sys.mdebug
1296
1297 flag: int
1298 /
1299[clinic start generated code]*/
1300
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001301static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001302sys_mdebug_impl(PyObject *module, int flag)
1303/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001307 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001308}
1309#endif /* USE_MALLOPT */
1310
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001311size_t
1312_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001315 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001316 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001317
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 /* Make sure the type is initialized. float gets initialized late */
1319 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001320 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001321
Benjamin Petersonce798522012-01-22 11:24:29 -05001322 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 if (method == NULL) {
1324 if (!PyErr_Occurred())
1325 PyErr_Format(PyExc_TypeError,
1326 "Type %.100s doesn't define __sizeof__",
1327 Py_TYPE(o)->tp_name);
1328 }
1329 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001330 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 Py_DECREF(method);
1332 }
1333
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001334 if (res == NULL)
1335 return (size_t)-1;
1336
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001337 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001338 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001339 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001340 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001342 if (size < 0) {
1343 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1344 return (size_t)-1;
1345 }
1346
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001347 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001348 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001349 return ((size_t)size) + sizeof(PyGC_Head);
1350 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001351}
1352
1353static PyObject *
1354sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1355{
1356 static char *kwlist[] = {"object", "default", 0};
1357 size_t size;
1358 PyObject *o, *dflt = NULL;
1359
1360 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1361 kwlist, &o, &dflt))
1362 return NULL;
1363
1364 size = _PySys_GetSizeOf(o);
1365
1366 if (size == (size_t)-1 && PyErr_Occurred()) {
1367 /* Has a default value been given */
1368 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1369 PyErr_Clear();
1370 Py_INCREF(dflt);
1371 return dflt;
1372 }
1373 else
1374 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001376
1377 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001378}
1379
1380PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001381"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001382\n\
1383Return the size of object in bytes.");
1384
Tal Einatede0b6f2018-12-31 17:12:08 +02001385/*[clinic input]
1386sys.getrefcount -> Py_ssize_t
1387
1388 object: object
1389 /
1390
1391Return the reference count of object.
1392
1393The count returned is generally one higher than you might expect,
1394because it includes the (temporary) reference as an argument to
1395getrefcount().
1396[clinic start generated code]*/
1397
1398static Py_ssize_t
1399sys_getrefcount_impl(PyObject *module, PyObject *object)
1400/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001401{
Tal Einatede0b6f2018-12-31 17:12:08 +02001402 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001403}
1404
Tim Peters4be93d02002-07-07 19:59:50 +00001405#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001406/*[clinic input]
1407sys.gettotalrefcount -> Py_ssize_t
1408[clinic start generated code]*/
1409
1410static Py_ssize_t
1411sys_gettotalrefcount_impl(PyObject *module)
1412/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001413{
Tal Einatede0b6f2018-12-31 17:12:08 +02001414 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001415}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001416#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001417
Tal Einatede0b6f2018-12-31 17:12:08 +02001418/*[clinic input]
1419sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001420
Tal Einatede0b6f2018-12-31 17:12:08 +02001421Return the number of memory blocks currently allocated.
1422[clinic start generated code]*/
1423
1424static Py_ssize_t
1425sys_getallocatedblocks_impl(PyObject *module)
1426/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001427{
Tal Einatede0b6f2018-12-31 17:12:08 +02001428 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001429}
1430
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001431#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001432/*[clinic input]
1433sys.getcounts
1434[clinic start generated code]*/
1435
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001436static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001437sys_getcounts_impl(PyObject *module)
1438/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001439{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001440 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001441
Pablo Galindo49c75a82018-10-28 15:02:17 +00001442 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001443}
1444#endif
1445
Tal Einatede0b6f2018-12-31 17:12:08 +02001446/*[clinic input]
1447sys._getframe
1448
1449 depth: int = 0
1450 /
1451
1452Return a frame object from the call stack.
1453
1454If optional integer depth is given, return the frame object that many
1455calls below the top of the stack. If that is deeper than the call
1456stack, ValueError is raised. The default for depth is zero, returning
1457the frame at the top of the call stack.
1458
1459This function should be used for internal and specialized purposes
1460only.
1461[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001462
1463static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001464sys__getframe_impl(PyObject *module, int depth)
1465/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001466{
Victor Stinner50b48572018-11-01 01:51:40 +01001467 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 while (depth > 0 && f != NULL) {
1470 f = f->f_back;
1471 --depth;
1472 }
1473 if (f == NULL) {
1474 PyErr_SetString(PyExc_ValueError,
1475 "call stack is not deep enough");
1476 return NULL;
1477 }
1478 Py_INCREF(f);
1479 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001480}
1481
Tal Einatede0b6f2018-12-31 17:12:08 +02001482/*[clinic input]
1483sys._current_frames
1484
1485Return a dict mapping each thread's thread id to its current stack frame.
1486
1487This function should be used for specialized purposes only.
1488[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001489
1490static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001491sys__current_frames_impl(PyObject *module)
1492/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001495}
1496
Tal Einatede0b6f2018-12-31 17:12:08 +02001497/*[clinic input]
1498sys.call_tracing
1499
1500 func: object
1501 args as funcargs: object(subclass_of='&PyTuple_Type')
1502 /
1503
1504Call func(*args), while tracing is enabled.
1505
1506The tracing state is saved, and restored afterwards. This is intended
1507to be called from a debugger from a checkpoint, to recursively debug
1508some other code.
1509[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001510
1511static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001512sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1513/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001516}
1517
Tal Einatede0b6f2018-12-31 17:12:08 +02001518/*[clinic input]
1519sys.callstats
1520
1521Return a tuple of function call statistics.
1522
1523A tuple is returned only if CALL_PROFILE was defined when Python was
1524built. Otherwise, this returns None.
1525
1526When enabled, this function returns detailed, implementation-specific
1527details about the number of function calls executed. The return value
1528is a 11-tuple where the entries in the tuple are counts of:
15290. all function calls
15301. calls to PyFunction_Type objects
15312. PyFunction calls that do not create an argument tuple
15323. PyFunction calls that do not create an argument tuple
1533 and bypass PyEval_EvalCodeEx()
15344. PyMethod calls
15355. PyMethod calls on bound methods
15366. PyType calls
15377. PyCFunction calls
15388. generator calls
15399. All other calls
154010. Number of stack pops performed by call_function()
1541[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001542
Victor Stinner048afd92016-11-28 11:59:04 +01001543static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001544sys_callstats_impl(PyObject *module)
1545/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001546{
1547 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1548 "sys.callstats() has been deprecated in Python 3.7 "
1549 "and will be removed in the future", 1) < 0) {
1550 return NULL;
1551 }
1552
1553 Py_RETURN_NONE;
1554}
1555
1556
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001557#ifdef __cplusplus
1558extern "C" {
1559#endif
1560
Tal Einatede0b6f2018-12-31 17:12:08 +02001561/*[clinic input]
1562sys._debugmallocstats
1563
1564Print summary info to stderr about the state of pymalloc's structures.
1565
1566In Py_DEBUG mode, also perform some expensive internal consistency
1567checks.
1568[clinic start generated code]*/
1569
David Malcolm49526f42012-06-22 14:55:41 -04001570static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001571sys__debugmallocstats_impl(PyObject *module)
1572/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001573{
1574#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001575 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001576 fputc('\n', stderr);
1577 }
David Malcolm49526f42012-06-22 14:55:41 -04001578#endif
1579 _PyObject_DebugTypeStats(stderr);
1580
1581 Py_RETURN_NONE;
1582}
David Malcolm49526f42012-06-22 14:55:41 -04001583
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001584#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001585/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001586extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001587#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001588
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001589#ifdef DYNAMIC_EXECUTION_PROFILE
1590/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001591extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001592#endif
1593
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001594#ifdef __cplusplus
1595}
1596#endif
1597
Tal Einatede0b6f2018-12-31 17:12:08 +02001598
1599/*[clinic input]
1600sys._clear_type_cache
1601
1602Clear the internal type lookup cache.
1603[clinic start generated code]*/
1604
Christian Heimes15ebc882008-02-04 18:48:49 +00001605static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001606sys__clear_type_cache_impl(PyObject *module)
1607/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 PyType_ClearCache();
1610 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001611}
1612
Tal Einatede0b6f2018-12-31 17:12:08 +02001613/*[clinic input]
1614sys.is_finalizing
1615
1616Return True if Python is exiting.
1617[clinic start generated code]*/
1618
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001619static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001620sys_is_finalizing_impl(PyObject *module)
1621/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001622{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001623 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001624}
1625
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001626#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001627/*[clinic input]
1628sys.getandroidapilevel
1629
1630Return the build time API version of Android as an integer.
1631[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001632
1633static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001634sys_getandroidapilevel_impl(PyObject *module)
1635/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001636{
1637 return PyLong_FromLong(ANDROID_API_LEVEL);
1638}
1639#endif /* ANDROID_API_LEVEL */
1640
1641
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001642static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001644 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001645 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001646 SYS_CALLSTATS_METHODDEF
1647 SYS__CLEAR_TYPE_CACHE_METHODDEF
1648 SYS__CURRENT_FRAMES_METHODDEF
1649 SYS_DISPLAYHOOK_METHODDEF
1650 SYS_EXC_INFO_METHODDEF
1651 SYS_EXCEPTHOOK_METHODDEF
1652 SYS_EXIT_METHODDEF
1653 SYS_GETDEFAULTENCODING_METHODDEF
1654 SYS_GETDLOPENFLAGS_METHODDEF
1655 SYS_GETALLOCATEDBLOCKS_METHODDEF
1656 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001657#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001659#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001660 SYS_GETFILESYSTEMENCODING_METHODDEF
1661 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001662#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001664#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001665 SYS_GETTOTALREFCOUNT_METHODDEF
1666 SYS_GETREFCOUNT_METHODDEF
1667 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001668 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001669 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001670 SYS__GETFRAME_METHODDEF
1671 SYS_GETWINDOWSVERSION_METHODDEF
1672 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1673 SYS_INTERN_METHODDEF
1674 SYS_IS_FINALIZING_METHODDEF
1675 SYS_MDEBUG_METHODDEF
1676 SYS_SETCHECKINTERVAL_METHODDEF
1677 SYS_GETCHECKINTERVAL_METHODDEF
1678 SYS_SETSWITCHINTERVAL_METHODDEF
1679 SYS_GETSWITCHINTERVAL_METHODDEF
1680 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001682 SYS_GETPROFILE_METHODDEF
1683 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001685 SYS_GETTRACE_METHODDEF
1686 SYS_CALL_TRACING_METHODDEF
1687 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001688 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1689 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001690 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1691 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001692 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001693 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001694 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1695 SYS_GETANDROIDAPILEVEL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001696 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001697};
1698
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001699static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001700list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001701{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 PyObject *list = PyList_New(0);
1703 int i;
1704 if (list == NULL)
1705 return NULL;
1706 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1707 PyObject *name = PyUnicode_FromString(
1708 PyImport_Inittab[i].name);
1709 if (name == NULL)
1710 break;
1711 PyList_Append(list, name);
1712 Py_DECREF(name);
1713 }
1714 if (PyList_Sort(list) != 0) {
1715 Py_DECREF(list);
1716 list = NULL;
1717 }
1718 if (list) {
1719 PyObject *v = PyList_AsTuple(list);
1720 Py_DECREF(list);
1721 list = v;
1722 }
1723 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001724}
1725
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001726/* Pre-initialization support for sys.warnoptions and sys._xoptions
1727 *
1728 * Modern internal code paths:
1729 * These APIs get called after _Py_InitializeCore and get to use the
1730 * regular CPython list, dict, and unicode APIs.
1731 *
1732 * Legacy embedding code paths:
1733 * The multi-phase initialization API isn't public yet, so embedding
1734 * apps still need to be able configure sys.warnoptions and sys._xoptions
1735 * before they call Py_Initialize. To support this, we stash copies of
1736 * the supplied wchar * sequences in linked lists, and then migrate the
1737 * contents of those lists to the sys module in _PyInitializeCore.
1738 *
1739 */
1740
1741struct _preinit_entry {
1742 wchar_t *value;
1743 struct _preinit_entry *next;
1744};
1745
1746typedef struct _preinit_entry *_Py_PreInitEntry;
1747
1748static _Py_PreInitEntry _preinit_warnoptions = NULL;
1749static _Py_PreInitEntry _preinit_xoptions = NULL;
1750
1751static _Py_PreInitEntry
1752_alloc_preinit_entry(const wchar_t *value)
1753{
1754 /* To get this to work, we have to initialize the runtime implicitly */
1755 _PyRuntime_Initialize();
1756
1757 /* Force default allocator, so we can ensure that it also gets used to
1758 * destroy the linked list in _clear_preinit_entries.
1759 */
1760 PyMemAllocatorEx old_alloc;
1761 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1762
1763 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1764 if (node != NULL) {
1765 node->value = _PyMem_RawWcsdup(value);
1766 if (node->value == NULL) {
1767 PyMem_RawFree(node);
1768 node = NULL;
1769 };
1770 };
1771
1772 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1773 return node;
1774};
1775
1776static int
1777_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1778{
1779 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1780 if (new_entry == NULL) {
1781 return -1;
1782 }
1783 /* We maintain the linked list in this order so it's easy to play back
1784 * the add commands in the same order later on in _Py_InitializeCore
1785 */
1786 _Py_PreInitEntry last_entry = *optionlist;
1787 if (last_entry == NULL) {
1788 *optionlist = new_entry;
1789 } else {
1790 while (last_entry->next != NULL) {
1791 last_entry = last_entry->next;
1792 }
1793 last_entry->next = new_entry;
1794 }
1795 return 0;
1796};
1797
1798static void
1799_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1800{
1801 _Py_PreInitEntry current = *optionlist;
1802 *optionlist = NULL;
1803 /* Deallocate the nodes and their contents using the default allocator */
1804 PyMemAllocatorEx old_alloc;
1805 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1806 while (current != NULL) {
1807 _Py_PreInitEntry next = current->next;
1808 PyMem_RawFree(current->value);
1809 PyMem_RawFree(current);
1810 current = next;
1811 }
1812 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1813};
1814
1815static void
1816_clear_all_preinit_options(void)
1817{
1818 _clear_preinit_entries(&_preinit_warnoptions);
1819 _clear_preinit_entries(&_preinit_xoptions);
1820}
1821
1822static int
1823_PySys_ReadPreInitOptions(void)
1824{
1825 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001826 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001827 if (tstate == NULL) {
1828 /* Still don't have a thread state, so something is wrong! */
1829 return -1;
1830 }
1831 _Py_PreInitEntry entry = _preinit_warnoptions;
1832 while (entry != NULL) {
1833 PySys_AddWarnOption(entry->value);
1834 entry = entry->next;
1835 }
1836 entry = _preinit_xoptions;
1837 while (entry != NULL) {
1838 PySys_AddXOption(entry->value);
1839 entry = entry->next;
1840 }
1841
1842 _clear_all_preinit_options();
1843 return 0;
1844};
1845
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001846static PyObject *
1847get_warnoptions(void)
1848{
Eric Snowdae02762017-09-14 00:35:58 -07001849 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001850 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001851 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1852 * interpreter config. When that happens, we need to properly set
1853 * the `warnoptions` reference in the main interpreter config as well.
1854 *
1855 * For Python 3.7, we shouldn't be able to get here due to the
1856 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1857 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1858 * call optional for embedding applications, thus making this
1859 * reachable again.
1860 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001861 warnoptions = PyList_New(0);
1862 if (warnoptions == NULL)
1863 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001864 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1865 Py_DECREF(warnoptions);
1866 return NULL;
1867 }
1868 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001869 }
1870 return warnoptions;
1871}
Guido van Rossum23fff912000-12-15 22:02:05 +00001872
1873void
1874PySys_ResetWarnOptions(void)
1875{
Victor Stinner50b48572018-11-01 01:51:40 +01001876 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001877 if (tstate == NULL) {
1878 _clear_preinit_entries(&_preinit_warnoptions);
1879 return;
1880 }
1881
Eric Snowdae02762017-09-14 00:35:58 -07001882 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (warnoptions == NULL || !PyList_Check(warnoptions))
1884 return;
1885 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001886}
1887
Victor Stinnere1b29952018-10-30 14:31:42 +01001888static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001889_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001890{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001891 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001892 if (warnoptions == NULL) {
1893 return -1;
1894 }
1895 if (PyList_Append(warnoptions, option)) {
1896 return -1;
1897 }
1898 return 0;
1899}
1900
1901void
1902PySys_AddWarnOptionUnicode(PyObject *option)
1903{
Victor Stinnere1b29952018-10-30 14:31:42 +01001904 if (_PySys_AddWarnOptionWithError(option) < 0) {
1905 /* No return value, therefore clear error state if possible */
1906 if (_PyThreadState_UncheckedGet()) {
1907 PyErr_Clear();
1908 }
1909 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001910}
1911
1912void
1913PySys_AddWarnOption(const wchar_t *s)
1914{
Victor Stinner50b48572018-11-01 01:51:40 +01001915 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001916 if (tstate == NULL) {
1917 _append_preinit_entry(&_preinit_warnoptions, s);
1918 return;
1919 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001920 PyObject *unicode;
1921 unicode = PyUnicode_FromWideChar(s, -1);
1922 if (unicode == NULL)
1923 return;
1924 PySys_AddWarnOptionUnicode(unicode);
1925 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001926}
1927
Christian Heimes33fe8092008-04-13 13:53:33 +00001928int
1929PySys_HasWarnOptions(void)
1930{
Eric Snowdae02762017-09-14 00:35:58 -07001931 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001932 return (warnoptions != NULL && PyList_Check(warnoptions)
1933 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001934}
1935
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001936static PyObject *
1937get_xoptions(void)
1938{
Eric Snowdae02762017-09-14 00:35:58 -07001939 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001940 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001941 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1942 * interpreter config. When that happens, we need to properly set
1943 * the `xoptions` reference in the main interpreter config as well.
1944 *
1945 * For Python 3.7, we shouldn't be able to get here due to the
1946 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1947 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1948 * call optional for embedding applications, thus making this
1949 * reachable again.
1950 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001951 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001952 if (xoptions == NULL)
1953 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001954 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1955 Py_DECREF(xoptions);
1956 return NULL;
1957 }
1958 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001959 }
1960 return xoptions;
1961}
1962
Victor Stinnere1b29952018-10-30 14:31:42 +01001963static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001964_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001965{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001966 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001967
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001968 PyObject *opts = get_xoptions();
1969 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001970 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001971 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001972
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001973 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001974 if (!name_end) {
1975 name = PyUnicode_FromWideChar(s, -1);
1976 value = Py_True;
1977 Py_INCREF(value);
1978 }
1979 else {
1980 name = PyUnicode_FromWideChar(s, name_end - s);
1981 value = PyUnicode_FromWideChar(name_end + 1, -1);
1982 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001983 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001984 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001985 }
1986 if (PyDict_SetItem(opts, name, value) < 0) {
1987 goto error;
1988 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001989 Py_DECREF(name);
1990 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001991 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001992
1993error:
1994 Py_XDECREF(name);
1995 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001996 return -1;
1997}
1998
1999void
2000PySys_AddXOption(const wchar_t *s)
2001{
Victor Stinner50b48572018-11-01 01:51:40 +01002002 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002003 if (tstate == NULL) {
2004 _append_preinit_entry(&_preinit_xoptions, s);
2005 return;
2006 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002007 if (_PySys_AddXOptionWithError(s) < 0) {
2008 /* No return value, therefore clear error state if possible */
2009 if (_PyThreadState_UncheckedGet()) {
2010 PyErr_Clear();
2011 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002012 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002013}
2014
2015PyObject *
2016PySys_GetXOptions(void)
2017{
2018 return get_xoptions();
2019}
2020
Guido van Rossum40552d01998-08-06 03:34:39 +00002021/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2022 Two literals concatenated works just fine. If you have a K&R compiler
2023 or other abomination that however *does* understand longer strings,
2024 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002025PyDoc_VAR(sys_doc) =
2026PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002027"This module provides access to some objects used or maintained by the\n\
2028interpreter and to functions that interact strongly with the interpreter.\n\
2029\n\
2030Dynamic objects:\n\
2031\n\
2032argv -- command line arguments; argv[0] is the script pathname if known\n\
2033path -- module search path; path[0] is the script directory, else ''\n\
2034modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002035\n\
2036displayhook -- called to show results in an interactive session\n\
2037excepthook -- called to handle any uncaught exception other than SystemExit\n\
2038 To customize printing in an interactive session or to install a custom\n\
2039 top-level exception handler, assign other functions to replace these.\n\
2040\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002041stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002042stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002043stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002044 By assigning other file objects (or objects that behave like files)\n\
2045 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002046\n\
2047last_type -- type of last uncaught exception\n\
2048last_value -- value of last uncaught exception\n\
2049last_traceback -- traceback of last uncaught exception\n\
2050 These three are only available in an interactive session after a\n\
2051 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002052"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002053)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002054/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002055PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002056"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002057Static objects:\n\
2058\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002059builtin_module_names -- tuple of module names built into this interpreter\n\
2060copyright -- copyright notice pertaining to this interpreter\n\
2061exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002062executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002063float_info -- a struct sequence with information about the float implementation.\n\
2064float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002065hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002066hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002067implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002068int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002069maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002070maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002071platform -- platform identifier\n\
2072prefix -- prefix used to find the Python library\n\
2073thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002074version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002075version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002076"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002077)
Steve Dowercc16be82016-09-08 10:35:16 -07002078#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002079/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002080PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002081"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002082winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002083"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002084)
Steve Dowercc16be82016-09-08 10:35:16 -07002085#endif /* MS_COREDLL */
2086#ifdef MS_WINDOWS
2087/* concatenating string here */
2088PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002089"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002090"
2091)
2092#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002093PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002094"__stdin__ -- the original stdin; don't touch!\n\
2095__stdout__ -- the original stdout; don't touch!\n\
2096__stderr__ -- the original stderr; don't touch!\n\
2097__displayhook__ -- the original displayhook; don't touch!\n\
2098__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002099\n\
2100Functions:\n\
2101\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002102displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002103excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002104exc_info() -- return thread-safe information about the current exception\n\
2105exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002106getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002107getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002108getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002109getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002110getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002111gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002112setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002113setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002114setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002115setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002116settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002117"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002118)
Fred Drakeccede592000-08-14 20:59:57 +00002119/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002120
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002121
2122PyDoc_STRVAR(flags__doc__,
2123"sys.flags\n\
2124\n\
2125Flags provided through command line arguments or environment vars.");
2126
2127static PyTypeObject FlagsType;
2128
2129static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 {"inspect", "-i"},
2132 {"interactive", "-i"},
2133 {"optimize", "-O or -OO"},
2134 {"dont_write_bytecode", "-B"},
2135 {"no_user_site", "-s"},
2136 {"no_site", "-S"},
2137 {"ignore_environment", "-E"},
2138 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 /* {"unbuffered", "-u"}, */
2140 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002141 {"bytes_warning", "-b"},
2142 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002143 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002144 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002145 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002146 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002147 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002148};
2149
2150static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 "sys.flags", /* name */
2152 flags__doc__, /* doc */
2153 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002154 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002155};
2156
2157static PyObject*
2158make_flags(void)
2159{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 int pos = 0;
2161 PyObject *seq;
Victor Stinner20004952019-03-26 02:31:11 +01002162 const _PyPreConfig *preconfig = &_PyRuntime.preconfig;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002163 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002164
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002165 seq = PyStructSequence_New(&FlagsType);
2166 if (seq == NULL)
2167 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002168
2169#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002171
Victor Stinnerfbca9082018-08-30 00:50:45 +02002172 SetFlag(config->parser_debug);
2173 SetFlag(config->inspect);
2174 SetFlag(config->interactive);
2175 SetFlag(config->optimization_level);
2176 SetFlag(!config->write_bytecode);
2177 SetFlag(!config->user_site_directory);
2178 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002179 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002180 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 /* SetFlag(saw_unbuffered_flag); */
2182 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002183 SetFlag(config->bytes_warning);
2184 SetFlag(config->quiet);
2185 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002186 SetFlag(config->isolated);
2187 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2188 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002189#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002190
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002191 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002192 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 return NULL;
2194 }
2195 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002196}
2197
Eric Smith0e5b5622009-02-06 01:32:42 +00002198PyDoc_STRVAR(version_info__doc__,
2199"sys.version_info\n\
2200\n\
2201Version information as a named tuple.");
2202
2203static PyTypeObject VersionInfoType;
2204
2205static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 {"major", "Major release number"},
2207 {"minor", "Minor release number"},
2208 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002209 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 {"serial", "Serial release number"},
2211 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002212};
2213
2214static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 "sys.version_info", /* name */
2216 version_info__doc__, /* doc */
2217 version_info_fields, /* fields */
2218 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002219};
2220
2221static PyObject *
2222make_version_info(void)
2223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002224 PyObject *version_info;
2225 char *s;
2226 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 version_info = PyStructSequence_New(&VersionInfoType);
2229 if (version_info == NULL) {
2230 return NULL;
2231 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 /*
2234 * These release level checks are mutually exclusive and cover
2235 * the field, so don't get too fancy with the pre-processor!
2236 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002237#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002239#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002240 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002241#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002243#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002245#endif
2246
2247#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002249#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 SetIntItem(PY_MAJOR_VERSION);
2253 SetIntItem(PY_MINOR_VERSION);
2254 SetIntItem(PY_MICRO_VERSION);
2255 SetStrItem(s);
2256 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002257#undef SetIntItem
2258#undef SetStrItem
2259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 if (PyErr_Occurred()) {
2261 Py_CLEAR(version_info);
2262 return NULL;
2263 }
2264 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002265}
2266
Brett Cannon3adc7b72012-07-09 14:22:12 -04002267/* sys.implementation values */
2268#define NAME "cpython"
2269const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002270#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2271#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002272#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002273const char *_PySys_ImplCacheTag = TAG;
2274#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002275#undef MAJOR
2276#undef MINOR
2277#undef TAG
2278
Barry Warsaw409da152012-06-03 16:18:47 -04002279static PyObject *
2280make_impl_info(PyObject *version_info)
2281{
2282 int res;
2283 PyObject *impl_info, *value, *ns;
2284
2285 impl_info = PyDict_New();
2286 if (impl_info == NULL)
2287 return NULL;
2288
2289 /* populate the dict */
2290
Brett Cannon3adc7b72012-07-09 14:22:12 -04002291 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002292 if (value == NULL)
2293 goto error;
2294 res = PyDict_SetItemString(impl_info, "name", value);
2295 Py_DECREF(value);
2296 if (res < 0)
2297 goto error;
2298
Brett Cannon3adc7b72012-07-09 14:22:12 -04002299 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002300 if (value == NULL)
2301 goto error;
2302 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2303 Py_DECREF(value);
2304 if (res < 0)
2305 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002306
2307 res = PyDict_SetItemString(impl_info, "version", version_info);
2308 if (res < 0)
2309 goto error;
2310
2311 value = PyLong_FromLong(PY_VERSION_HEX);
2312 if (value == NULL)
2313 goto error;
2314 res = PyDict_SetItemString(impl_info, "hexversion", value);
2315 Py_DECREF(value);
2316 if (res < 0)
2317 goto error;
2318
doko@ubuntu.com55532312016-06-14 08:55:19 +02002319#ifdef MULTIARCH
2320 value = PyUnicode_FromString(MULTIARCH);
2321 if (value == NULL)
2322 goto error;
2323 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2324 Py_DECREF(value);
2325 if (res < 0)
2326 goto error;
2327#endif
2328
Barry Warsaw409da152012-06-03 16:18:47 -04002329 /* dict ready */
2330
2331 ns = _PyNamespace_New(impl_info);
2332 Py_DECREF(impl_info);
2333 return ns;
2334
2335error:
2336 Py_CLEAR(impl_info);
2337 return NULL;
2338}
2339
Martin v. Löwis1a214512008-06-11 05:26:20 +00002340static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002341 PyModuleDef_HEAD_INIT,
2342 "sys",
2343 sys_doc,
2344 -1, /* multiple "initialization" just copies the module dict. */
2345 sys_methods,
2346 NULL,
2347 NULL,
2348 NULL,
2349 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002350};
2351
Eric Snow6b4be192017-05-22 21:36:03 -07002352/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002353#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002354 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002355 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002356 if (v == NULL) { \
2357 goto err_occurred; \
2358 } \
Victor Stinner58049602013-07-22 22:40:00 +02002359 res = PyDict_SetItemString(sysdict, key, v); \
2360 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002361 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002362 } \
2363 } while (0)
2364#define SET_SYS_FROM_STRING(key, value) \
2365 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002366 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002367 if (v == NULL) { \
2368 goto err_occurred; \
2369 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002370 res = PyDict_SetItemString(sysdict, key, v); \
2371 Py_DECREF(v); \
2372 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002373 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002374 } \
2375 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002376
Victor Stinnerab672812019-01-23 15:04:40 +01002377static _PyInitError
2378_PySys_InitCore(PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002379{
Victor Stinnerab672812019-01-23 15:04:40 +01002380 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002381 int res;
2382
Nick Coghland6009512014-11-20 21:39:37 +10002383 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002384
Victor Stinner8fea2522013-10-27 17:15:42 +01002385 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2386 PyDict_GetItemString(sysdict, "displayhook"));
2387 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2388 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002389 SET_SYS_FROM_STRING_BORROW(
2390 "__breakpointhook__",
2391 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002392 SET_SYS_FROM_STRING("version",
2393 PyUnicode_FromString(Py_GetVersion()));
2394 SET_SYS_FROM_STRING("hexversion",
2395 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002396 SET_SYS_FROM_STRING("_git",
2397 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2398 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002399 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 SET_SYS_FROM_STRING("api_version",
2401 PyLong_FromLong(PYTHON_API_VERSION));
2402 SET_SYS_FROM_STRING("copyright",
2403 PyUnicode_FromString(Py_GetCopyright()));
2404 SET_SYS_FROM_STRING("platform",
2405 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002406 SET_SYS_FROM_STRING("maxsize",
2407 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2408 SET_SYS_FROM_STRING("float_info",
2409 PyFloat_GetInfo());
2410 SET_SYS_FROM_STRING("int_info",
2411 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002412 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002413 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002414 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2415 goto type_init_failed;
2416 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002417 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002418 SET_SYS_FROM_STRING("hash_info",
2419 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002421 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 SET_SYS_FROM_STRING("builtin_module_names",
2423 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002424#if PY_BIG_ENDIAN
2425 SET_SYS_FROM_STRING("byteorder",
2426 PyUnicode_FromString("big"));
2427#else
2428 SET_SYS_FROM_STRING("byteorder",
2429 PyUnicode_FromString("little"));
2430#endif
Fred Drake099325e2000-08-14 15:47:03 +00002431
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002432#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002433 SET_SYS_FROM_STRING("dllhandle",
2434 PyLong_FromVoidPtr(PyWin_DLLhModule));
2435 SET_SYS_FROM_STRING("winver",
2436 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002437#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002438#ifdef ABIFLAGS
2439 SET_SYS_FROM_STRING("abiflags",
2440 PyUnicode_FromString(ABIFLAGS));
2441#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002444 if (VersionInfoType.tp_name == NULL) {
2445 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002446 &version_info_desc) < 0) {
2447 goto type_init_failed;
2448 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002449 }
Barry Warsaw409da152012-06-03 16:18:47 -04002450 version_info = make_version_info();
2451 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* prevent user from creating new instances */
2453 VersionInfoType.tp_init = NULL;
2454 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002455 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2456 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2457 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002458
Barry Warsaw409da152012-06-03 16:18:47 -04002459 /* implementation */
2460 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2461
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002462 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002463 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002464 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2465 goto type_init_failed;
2466 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002467 }
Eric Snow6b4be192017-05-22 21:36:03 -07002468 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002469 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002470
2471#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* getwindowsversion */
2473 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002474 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002475 &windows_version_desc) < 0) {
2476 goto type_init_failed;
2477 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002478 /* prevent user from creating new instances */
2479 WindowsVersionType.tp_init = NULL;
2480 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002481 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002482 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002483 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002484 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002485 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002486#endif
2487
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002489#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 SET_SYS_FROM_STRING("float_repr_style",
2491 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002492#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002493 SET_SYS_FROM_STRING("float_repr_style",
2494 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002495#endif
2496
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002497 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002498
Yury Selivanoveb636452016-09-08 22:01:51 -07002499 /* initialize asyncgen_hooks */
2500 if (AsyncGenHooksType.tp_name == NULL) {
2501 if (PyStructSequence_InitType2(
2502 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002503 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002504 }
2505 }
2506
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002507 if (PyErr_Occurred()) {
2508 goto err_occurred;
2509 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002510 return _Py_INIT_OK();
2511
2512type_init_failed:
2513 return _Py_INIT_ERR("failed to initialize a type");
2514
2515err_occurred:
2516 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002517}
2518
Eric Snow6b4be192017-05-22 21:36:03 -07002519#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002520
2521/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002522#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2523 do { \
2524 PyObject *v = (value); \
2525 if (v == NULL) \
2526 return -1; \
2527 res = PyDict_SetItemString(sysdict, key, v); \
2528 Py_DECREF(v); \
2529 if (res < 0) { \
2530 return res; \
2531 } \
2532 } while (0)
2533
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002534
2535static int
2536sys_add_xoption(PyObject *opts, const wchar_t *s)
2537{
2538 PyObject *name, *value;
2539
2540 const wchar_t *name_end = wcschr(s, L'=');
2541 if (!name_end) {
2542 name = PyUnicode_FromWideChar(s, -1);
2543 value = Py_True;
2544 Py_INCREF(value);
2545 }
2546 else {
2547 name = PyUnicode_FromWideChar(s, name_end - s);
2548 value = PyUnicode_FromWideChar(name_end + 1, -1);
2549 }
2550 if (name == NULL || value == NULL) {
2551 goto error;
2552 }
2553 if (PyDict_SetItem(opts, name, value) < 0) {
2554 goto error;
2555 }
2556 Py_DECREF(name);
2557 Py_DECREF(value);
2558 return 0;
2559
2560error:
2561 Py_XDECREF(name);
2562 Py_XDECREF(value);
2563 return -1;
2564}
2565
2566
2567static PyObject*
2568sys_create_xoptions_dict(const _PyCoreConfig *config)
2569{
2570 Py_ssize_t nxoption = config->xoptions.length;
2571 wchar_t * const * xoptions = config->xoptions.items;
2572 PyObject *dict = PyDict_New();
2573 if (dict == NULL) {
2574 return NULL;
2575 }
2576
2577 for (Py_ssize_t i=0; i < nxoption; i++) {
2578 const wchar_t *option = xoptions[i];
2579 if (sys_add_xoption(dict, option) < 0) {
2580 Py_DECREF(dict);
2581 return NULL;
2582 }
2583 }
2584
2585 return dict;
2586}
2587
2588
Eric Snow6b4be192017-05-22 21:36:03 -07002589int
Victor Stinnerab672812019-01-23 15:04:40 +01002590_PySys_InitMain(PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002591{
Victor Stinnerab672812019-01-23 15:04:40 +01002592 PyObject *sysdict = interp->sysdict;
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002593 const _PyCoreConfig *config = &interp->core_config;
Eric Snow6b4be192017-05-22 21:36:03 -07002594 int res;
2595
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002596#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002597 do { \
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002598 PyObject *list = _PyWstrList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002599 if (list == NULL) { \
2600 return -1; \
2601 } \
2602 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2603 Py_DECREF(list); \
2604 } while (0)
2605
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002606#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2607 do { \
2608 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2609 if (str == NULL) { \
2610 return -1; \
2611 } \
2612 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2613 Py_DECREF(str); \
2614 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002615
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002616 COPY_LIST("path", config->module_search_paths);
2617
2618 SET_SYS_FROM_WSTR("executable", config->executable);
2619 SET_SYS_FROM_WSTR("prefix", config->prefix);
2620 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2621 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2622 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002623
Carl Meyerb193fa92018-06-15 22:40:56 -06002624 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002625 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002626 } else {
2627 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2628 }
2629
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002630 COPY_LIST("argv", config->argv);
2631 COPY_LIST("warnoptions", config->warnoptions);
2632
2633 PyObject *xoptions = sys_create_xoptions_dict(config);
2634 if (xoptions == NULL) {
2635 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002636 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002637 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002638 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002639
Victor Stinner37cd9822018-11-16 11:55:35 +01002640#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002641#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002642
Eric Snow6b4be192017-05-22 21:36:03 -07002643 /* Set flags to their final values */
2644 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2645 /* prevent user from creating new instances */
2646 FlagsType.tp_init = NULL;
2647 FlagsType.tp_new = NULL;
2648 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2649 if (res < 0) {
2650 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2651 return res;
2652 }
2653 PyErr_Clear();
2654 }
2655
2656 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002657 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002658
Eric Snowdae02762017-09-14 00:35:58 -07002659 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002660 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002661
Eric Snowdae02762017-09-14 00:35:58 -07002662 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002663 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002664
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002665 /* Transfer any sys.warnoptions and sys._xoptions set directly
2666 * by an embedding application from the linked list to the module. */
2667 if (_PySys_ReadPreInitOptions() != 0)
2668 return -1;
2669
Eric Snow6b4be192017-05-22 21:36:03 -07002670 if (PyErr_Occurred())
2671 return -1;
2672 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002673
2674err_occurred:
2675 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002676}
2677
Victor Stinner41264f12017-12-15 02:05:29 +01002678#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002679#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002680
Victor Stinnerab672812019-01-23 15:04:40 +01002681
2682/* Set up a preliminary stderr printer until we have enough
2683 infrastructure for the io module in place.
2684
2685 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
2686_PyInitError
2687_PySys_SetPreliminaryStderr(PyObject *sysdict)
2688{
2689 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2690 if (pstderr == NULL) {
2691 goto error;
2692 }
2693 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2694 goto error;
2695 }
2696 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2697 goto error;
2698 }
2699 Py_DECREF(pstderr);
2700 return _Py_INIT_OK();
2701
2702error:
2703 Py_XDECREF(pstderr);
2704 return _Py_INIT_ERR("can't set preliminary stderr");
2705}
2706
2707
2708/* Create sys module without all attributes: _PySys_InitMain() should be called
2709 later to add remaining attributes. */
2710_PyInitError
2711_PySys_Create(PyInterpreterState *interp, PyObject **sysmod_p)
2712{
2713 PyObject *modules = PyDict_New();
2714 if (modules == NULL) {
2715 return _Py_INIT_ERR("can't make modules dictionary");
2716 }
2717 interp->modules = modules;
2718
2719 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2720 if (sysmod == NULL) {
2721 return _Py_INIT_ERR("failed to create a module object");
2722 }
2723
2724 PyObject *sysdict = PyModule_GetDict(sysmod);
2725 if (sysdict == NULL) {
2726 return _Py_INIT_ERR("can't initialize sys dict");
2727 }
2728 Py_INCREF(sysdict);
2729 interp->sysdict = sysdict;
2730
2731 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
2732 return _Py_INIT_ERR("can't initialize sys module");
2733 }
2734
2735 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
2736 if (_Py_INIT_FAILED(err)) {
2737 return err;
2738 }
2739
2740 err = _PySys_InitCore(sysdict);
2741 if (_Py_INIT_FAILED(err)) {
2742 return err;
2743 }
2744
2745 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
2746
2747 *sysmod_p = sysmod;
2748 return _Py_INIT_OK();
2749}
2750
2751
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002752static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002753makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002754{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002755 int i, n;
2756 const wchar_t *p;
2757 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002758
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 n = 1;
2760 p = path;
2761 while ((p = wcschr(p, delim)) != NULL) {
2762 n++;
2763 p++;
2764 }
2765 v = PyList_New(n);
2766 if (v == NULL)
2767 return NULL;
2768 for (i = 0; ; i++) {
2769 p = wcschr(path, delim);
2770 if (p == NULL)
2771 p = path + wcslen(path); /* End of string */
2772 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2773 if (w == NULL) {
2774 Py_DECREF(v);
2775 return NULL;
2776 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002777 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002778 if (*p == '\0')
2779 break;
2780 path = p+1;
2781 }
2782 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002783}
2784
2785void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002786PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002787{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 PyObject *v;
2789 if ((v = makepathobject(path, DELIM)) == NULL)
2790 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002791 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 Py_FatalError("can't assign sys.path");
2793 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002794}
2795
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002796static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01002797make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002798{
Victor Stinner74f65682019-03-15 15:08:05 +01002799 PyObject *list = PyList_New(argc);
2800 if (list == NULL) {
2801 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002802 }
Victor Stinner74f65682019-03-15 15:08:05 +01002803
2804 for (Py_ssize_t i = 0; i < argc; i++) {
2805 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
2806 if (v == NULL) {
2807 Py_DECREF(list);
2808 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002809 }
Victor Stinner74f65682019-03-15 15:08:05 +01002810 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 }
Victor Stinner74f65682019-03-15 15:08:05 +01002812 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002813}
2814
Victor Stinner11a247d2017-12-13 21:05:57 +01002815void
2816PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002817{
Victor Stinner74f65682019-03-15 15:08:05 +01002818 if (argc < 1 || argv == NULL) {
2819 /* Ensure at least one (empty) argument is seen */
2820 wchar_t* empty_argv[1] = {L""};
2821 argv = empty_argv;
2822 argc = 1;
2823 }
2824
2825 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002826 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002827 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002828 }
2829 if (PySys_SetObject("argv", av) != 0) {
2830 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002831 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002832 }
2833 Py_DECREF(av);
2834
2835 if (updatepath) {
2836 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2837 If argv[0] is a symlink, use the real path. */
Victor Stinner74f65682019-03-15 15:08:05 +01002838 const _PyWstrList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01002839 PyObject *path0 = NULL;
2840 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
2841 if (path0 == NULL) {
2842 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01002843 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01002844
2845 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2846 if (sys_path != NULL) {
2847 if (PyList_Insert(sys_path, 0, path0) < 0) {
2848 Py_DECREF(path0);
2849 Py_FatalError("can't prepend path0 to sys.path");
2850 }
2851 }
2852 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01002853 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002854 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002855}
Guido van Rossuma890e681998-05-12 14:59:24 +00002856
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002857void
2858PySys_SetArgv(int argc, wchar_t **argv)
2859{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002860 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002861}
2862
Victor Stinner14284c22010-04-23 12:02:30 +00002863/* Reimplementation of PyFile_WriteString() no calling indirectly
2864 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2865
2866static int
Victor Stinner79766632010-08-16 17:36:42 +00002867sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002868{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002869 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002870 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002871
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002872 if (file == NULL)
2873 return -1;
2874
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002875 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002876 if (writer == NULL)
2877 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002878
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002879 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002880 if (result == NULL) {
2881 goto error;
2882 } else {
2883 err = 0;
2884 goto finally;
2885 }
Victor Stinner14284c22010-04-23 12:02:30 +00002886
2887error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002888 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002889finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002890 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 Py_XDECREF(result);
2892 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002893}
2894
Victor Stinner79766632010-08-16 17:36:42 +00002895static int
2896sys_pyfile_write(const char *text, PyObject *file)
2897{
2898 PyObject *unicode = NULL;
2899 int err;
2900
2901 if (file == NULL)
2902 return -1;
2903
2904 unicode = PyUnicode_FromString(text);
2905 if (unicode == NULL)
2906 return -1;
2907
2908 err = sys_pyfile_write_unicode(unicode, file);
2909 Py_DECREF(unicode);
2910 return err;
2911}
Guido van Rossuma890e681998-05-12 14:59:24 +00002912
2913/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2914 Adapted from code submitted by Just van Rossum.
2915
2916 PySys_WriteStdout(format, ...)
2917 PySys_WriteStderr(format, ...)
2918
2919 The first function writes to sys.stdout; the second to sys.stderr. When
2920 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002921 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002922
Victor Stinner14284c22010-04-23 12:02:30 +00002923 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002924 signal handlers: they may raise a new exception whereas sys_write()
2925 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002926
Guido van Rossuma890e681998-05-12 14:59:24 +00002927 Both take a printf-style format string as their first argument followed
2928 by a variable length argument list determined by the format string.
2929
2930 *** WARNING ***
2931
2932 The format should limit the total size of the formatted output string to
2933 1000 bytes. In particular, this means that no unrestricted "%s" formats
2934 should occur; these should be limited using "%.<N>s where <N> is a
2935 decimal number calculated so that <N> plus the maximum size of other
2936 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2937 which can print hundreds of digits for very large numbers.
2938
2939 */
2940
2941static void
Victor Stinner09054372013-11-06 22:41:44 +01002942sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002943{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002944 PyObject *file;
2945 PyObject *error_type, *error_value, *error_traceback;
2946 char buffer[1001];
2947 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002948
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002949 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002950 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002951 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2952 if (sys_pyfile_write(buffer, file) != 0) {
2953 PyErr_Clear();
2954 fputs(buffer, fp);
2955 }
2956 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2957 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002958 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002959 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 }
2961 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002962}
2963
2964void
Guido van Rossuma890e681998-05-12 14:59:24 +00002965PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002967 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002970 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002971 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002972}
2973
2974void
Guido van Rossuma890e681998-05-12 14:59:24 +00002975PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002976{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002977 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002979 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002980 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002981 va_end(va);
2982}
2983
2984static void
Victor Stinner09054372013-11-06 22:41:44 +01002985sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002986{
2987 PyObject *file, *message;
2988 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002989 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002990
2991 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002992 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002993 message = PyUnicode_FromFormatV(format, va);
2994 if (message != NULL) {
2995 if (sys_pyfile_write_unicode(message, file) != 0) {
2996 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002997 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002998 if (utf8 != NULL)
2999 fputs(utf8, fp);
3000 }
3001 Py_DECREF(message);
3002 }
3003 PyErr_Restore(error_type, error_value, error_traceback);
3004}
3005
3006void
3007PySys_FormatStdout(const char *format, ...)
3008{
3009 va_list va;
3010
3011 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003012 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003013 va_end(va);
3014}
3015
3016void
3017PySys_FormatStderr(const char *format, ...)
3018{
3019 va_list va;
3020
3021 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003022 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003023 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003024}