blob: 1290164edbf68d513cd87fa926830f16e4437fb1 [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;
Victor Stinner709d23d2019-05-02 14:56:30 -0400427 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
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;
Victor Stinner709d23d2019-05-02 14:56:30 -0400442 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
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 Stinner709d23d2019-05-02 14:56:30 -04001214 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001215 return NULL;
1216 }
Steve Dowercc16be82016-09-08 10:35:16 -07001217 Py_RETURN_NONE;
1218}
1219
Mark Hammond8696ebc2002-10-08 02:44:31 +00001220#endif /* MS_WINDOWS */
1221
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001222#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001223
1224/*[clinic input]
1225sys.setdlopenflags
1226
1227 flags as new_val: int
1228 /
1229
1230Set the flags used by the interpreter for dlopen calls.
1231
1232This is used, for example, when the interpreter loads extension
1233modules. Among other things, this will enable a lazy resolving of
1234symbols when importing a module, if called as sys.setdlopenflags(0).
1235To share symbols across extension modules, call as
1236sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1237modules can be found in the os module (RTLD_xxx constants, e.g.
1238os.RTLD_LAZY).
1239[clinic start generated code]*/
1240
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001241static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001242sys_setdlopenflags_impl(PyObject *module, int new_val)
1243/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001244{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001245 PyInterpreterState *interp = _PyInterpreterState_Get();
1246 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001247 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001248}
1249
Tal Einatede0b6f2018-12-31 17:12:08 +02001250
1251/*[clinic input]
1252sys.getdlopenflags
1253
1254Return the current value of the flags that are used for dlopen calls.
1255
1256The flag constants are defined in the os module.
1257[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001258
1259static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001260sys_getdlopenflags_impl(PyObject *module)
1261/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001262{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001263 PyInterpreterState *interp = _PyInterpreterState_Get();
1264 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001265}
1266
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001267#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001268
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001269#ifdef USE_MALLOPT
1270/* Link with -lmalloc (or -lmpc) on an SGI */
1271#include <malloc.h>
1272
Tal Einatede0b6f2018-12-31 17:12:08 +02001273/*[clinic input]
1274sys.mdebug
1275
1276 flag: int
1277 /
1278[clinic start generated code]*/
1279
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001280static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001281sys_mdebug_impl(PyObject *module, int flag)
1282/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001283{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001286 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001287}
1288#endif /* USE_MALLOPT */
1289
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001290size_t
1291_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001292{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001294 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001295 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001296
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001297 /* Make sure the type is initialized. float gets initialized late */
1298 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001299 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001300
Benjamin Petersonce798522012-01-22 11:24:29 -05001301 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 if (method == NULL) {
1303 if (!PyErr_Occurred())
1304 PyErr_Format(PyExc_TypeError,
1305 "Type %.100s doesn't define __sizeof__",
1306 Py_TYPE(o)->tp_name);
1307 }
1308 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001309 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 Py_DECREF(method);
1311 }
1312
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001313 if (res == NULL)
1314 return (size_t)-1;
1315
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001316 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001317 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001318 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001319 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001321 if (size < 0) {
1322 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1323 return (size_t)-1;
1324 }
1325
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001327 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001328 return ((size_t)size) + sizeof(PyGC_Head);
1329 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001330}
1331
1332static PyObject *
1333sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1334{
1335 static char *kwlist[] = {"object", "default", 0};
1336 size_t size;
1337 PyObject *o, *dflt = NULL;
1338
1339 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1340 kwlist, &o, &dflt))
1341 return NULL;
1342
1343 size = _PySys_GetSizeOf(o);
1344
1345 if (size == (size_t)-1 && PyErr_Occurred()) {
1346 /* Has a default value been given */
1347 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1348 PyErr_Clear();
1349 Py_INCREF(dflt);
1350 return dflt;
1351 }
1352 else
1353 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001354 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001355
1356 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001357}
1358
1359PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001360"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001361\n\
1362Return the size of object in bytes.");
1363
Tal Einatede0b6f2018-12-31 17:12:08 +02001364/*[clinic input]
1365sys.getrefcount -> Py_ssize_t
1366
1367 object: object
1368 /
1369
1370Return the reference count of object.
1371
1372The count returned is generally one higher than you might expect,
1373because it includes the (temporary) reference as an argument to
1374getrefcount().
1375[clinic start generated code]*/
1376
1377static Py_ssize_t
1378sys_getrefcount_impl(PyObject *module, PyObject *object)
1379/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001380{
Tal Einatede0b6f2018-12-31 17:12:08 +02001381 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001382}
1383
Tim Peters4be93d02002-07-07 19:59:50 +00001384#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001385/*[clinic input]
1386sys.gettotalrefcount -> Py_ssize_t
1387[clinic start generated code]*/
1388
1389static Py_ssize_t
1390sys_gettotalrefcount_impl(PyObject *module)
1391/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001392{
Tal Einatede0b6f2018-12-31 17:12:08 +02001393 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001394}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001395#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001396
Tal Einatede0b6f2018-12-31 17:12:08 +02001397/*[clinic input]
1398sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001399
Tal Einatede0b6f2018-12-31 17:12:08 +02001400Return the number of memory blocks currently allocated.
1401[clinic start generated code]*/
1402
1403static Py_ssize_t
1404sys_getallocatedblocks_impl(PyObject *module)
1405/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001406{
Tal Einatede0b6f2018-12-31 17:12:08 +02001407 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001408}
1409
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001410#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001411/*[clinic input]
1412sys.getcounts
1413[clinic start generated code]*/
1414
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001415static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001416sys_getcounts_impl(PyObject *module)
1417/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001418{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001419 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001420
Pablo Galindo49c75a82018-10-28 15:02:17 +00001421 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001422}
1423#endif
1424
Tal Einatede0b6f2018-12-31 17:12:08 +02001425/*[clinic input]
1426sys._getframe
1427
1428 depth: int = 0
1429 /
1430
1431Return a frame object from the call stack.
1432
1433If optional integer depth is given, return the frame object that many
1434calls below the top of the stack. If that is deeper than the call
1435stack, ValueError is raised. The default for depth is zero, returning
1436the frame at the top of the call stack.
1437
1438This function should be used for internal and specialized purposes
1439only.
1440[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001441
1442static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001443sys__getframe_impl(PyObject *module, int depth)
1444/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001445{
Victor Stinner50b48572018-11-01 01:51:40 +01001446 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 while (depth > 0 && f != NULL) {
1449 f = f->f_back;
1450 --depth;
1451 }
1452 if (f == NULL) {
1453 PyErr_SetString(PyExc_ValueError,
1454 "call stack is not deep enough");
1455 return NULL;
1456 }
1457 Py_INCREF(f);
1458 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001459}
1460
Tal Einatede0b6f2018-12-31 17:12:08 +02001461/*[clinic input]
1462sys._current_frames
1463
1464Return a dict mapping each thread's thread id to its current stack frame.
1465
1466This function should be used for specialized purposes only.
1467[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001468
1469static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001470sys__current_frames_impl(PyObject *module)
1471/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001472{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001474}
1475
Tal Einatede0b6f2018-12-31 17:12:08 +02001476/*[clinic input]
1477sys.call_tracing
1478
1479 func: object
1480 args as funcargs: object(subclass_of='&PyTuple_Type')
1481 /
1482
1483Call func(*args), while tracing is enabled.
1484
1485The tracing state is saved, and restored afterwards. This is intended
1486to be called from a debugger from a checkpoint, to recursively debug
1487some other code.
1488[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001489
1490static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001491sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1492/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001493{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001495}
1496
Tal Einatede0b6f2018-12-31 17:12:08 +02001497/*[clinic input]
1498sys.callstats
1499
1500Return a tuple of function call statistics.
1501
1502A tuple is returned only if CALL_PROFILE was defined when Python was
1503built. Otherwise, this returns None.
1504
1505When enabled, this function returns detailed, implementation-specific
1506details about the number of function calls executed. The return value
1507is a 11-tuple where the entries in the tuple are counts of:
15080. all function calls
15091. calls to PyFunction_Type objects
15102. PyFunction calls that do not create an argument tuple
15113. PyFunction calls that do not create an argument tuple
1512 and bypass PyEval_EvalCodeEx()
15134. PyMethod calls
15145. PyMethod calls on bound methods
15156. PyType calls
15167. PyCFunction calls
15178. generator calls
15189. All other calls
151910. Number of stack pops performed by call_function()
1520[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001521
Victor Stinner048afd92016-11-28 11:59:04 +01001522static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001523sys_callstats_impl(PyObject *module)
1524/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001525{
1526 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1527 "sys.callstats() has been deprecated in Python 3.7 "
1528 "and will be removed in the future", 1) < 0) {
1529 return NULL;
1530 }
1531
1532 Py_RETURN_NONE;
1533}
1534
1535
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001536#ifdef __cplusplus
1537extern "C" {
1538#endif
1539
Tal Einatede0b6f2018-12-31 17:12:08 +02001540/*[clinic input]
1541sys._debugmallocstats
1542
1543Print summary info to stderr about the state of pymalloc's structures.
1544
1545In Py_DEBUG mode, also perform some expensive internal consistency
1546checks.
1547[clinic start generated code]*/
1548
David Malcolm49526f42012-06-22 14:55:41 -04001549static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001550sys__debugmallocstats_impl(PyObject *module)
1551/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001552{
1553#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001554 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001555 fputc('\n', stderr);
1556 }
David Malcolm49526f42012-06-22 14:55:41 -04001557#endif
1558 _PyObject_DebugTypeStats(stderr);
1559
1560 Py_RETURN_NONE;
1561}
David Malcolm49526f42012-06-22 14:55:41 -04001562
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001563#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001564/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001565extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001566#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001567
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001568#ifdef DYNAMIC_EXECUTION_PROFILE
1569/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001570extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001571#endif
1572
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001573#ifdef __cplusplus
1574}
1575#endif
1576
Tal Einatede0b6f2018-12-31 17:12:08 +02001577
1578/*[clinic input]
1579sys._clear_type_cache
1580
1581Clear the internal type lookup cache.
1582[clinic start generated code]*/
1583
Christian Heimes15ebc882008-02-04 18:48:49 +00001584static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001585sys__clear_type_cache_impl(PyObject *module)
1586/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001587{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 PyType_ClearCache();
1589 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001590}
1591
Tal Einatede0b6f2018-12-31 17:12:08 +02001592/*[clinic input]
1593sys.is_finalizing
1594
1595Return True if Python is exiting.
1596[clinic start generated code]*/
1597
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001598static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001599sys_is_finalizing_impl(PyObject *module)
1600/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001601{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001602 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001603}
1604
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001605#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001606/*[clinic input]
1607sys.getandroidapilevel
1608
1609Return the build time API version of Android as an integer.
1610[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001611
1612static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001613sys_getandroidapilevel_impl(PyObject *module)
1614/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001615{
1616 return PyLong_FromLong(ANDROID_API_LEVEL);
1617}
1618#endif /* ANDROID_API_LEVEL */
1619
1620
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001621static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001623 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001624 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001625 SYS_CALLSTATS_METHODDEF
1626 SYS__CLEAR_TYPE_CACHE_METHODDEF
1627 SYS__CURRENT_FRAMES_METHODDEF
1628 SYS_DISPLAYHOOK_METHODDEF
1629 SYS_EXC_INFO_METHODDEF
1630 SYS_EXCEPTHOOK_METHODDEF
1631 SYS_EXIT_METHODDEF
1632 SYS_GETDEFAULTENCODING_METHODDEF
1633 SYS_GETDLOPENFLAGS_METHODDEF
1634 SYS_GETALLOCATEDBLOCKS_METHODDEF
1635 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001636#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001638#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001639 SYS_GETFILESYSTEMENCODING_METHODDEF
1640 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001641#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001643#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001644 SYS_GETTOTALREFCOUNT_METHODDEF
1645 SYS_GETREFCOUNT_METHODDEF
1646 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001647 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001648 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001649 SYS__GETFRAME_METHODDEF
1650 SYS_GETWINDOWSVERSION_METHODDEF
1651 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1652 SYS_INTERN_METHODDEF
1653 SYS_IS_FINALIZING_METHODDEF
1654 SYS_MDEBUG_METHODDEF
1655 SYS_SETCHECKINTERVAL_METHODDEF
1656 SYS_GETCHECKINTERVAL_METHODDEF
1657 SYS_SETSWITCHINTERVAL_METHODDEF
1658 SYS_GETSWITCHINTERVAL_METHODDEF
1659 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001661 SYS_GETPROFILE_METHODDEF
1662 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001664 SYS_GETTRACE_METHODDEF
1665 SYS_CALL_TRACING_METHODDEF
1666 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001667 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1668 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001669 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1670 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001671 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001672 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001673 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1674 SYS_GETANDROIDAPILEVEL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001676};
1677
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001678static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001679list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001680{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 PyObject *list = PyList_New(0);
1682 int i;
1683 if (list == NULL)
1684 return NULL;
1685 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1686 PyObject *name = PyUnicode_FromString(
1687 PyImport_Inittab[i].name);
1688 if (name == NULL)
1689 break;
1690 PyList_Append(list, name);
1691 Py_DECREF(name);
1692 }
1693 if (PyList_Sort(list) != 0) {
1694 Py_DECREF(list);
1695 list = NULL;
1696 }
1697 if (list) {
1698 PyObject *v = PyList_AsTuple(list);
1699 Py_DECREF(list);
1700 list = v;
1701 }
1702 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001703}
1704
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001705/* Pre-initialization support for sys.warnoptions and sys._xoptions
1706 *
1707 * Modern internal code paths:
1708 * These APIs get called after _Py_InitializeCore and get to use the
1709 * regular CPython list, dict, and unicode APIs.
1710 *
1711 * Legacy embedding code paths:
1712 * The multi-phase initialization API isn't public yet, so embedding
1713 * apps still need to be able configure sys.warnoptions and sys._xoptions
1714 * before they call Py_Initialize. To support this, we stash copies of
1715 * the supplied wchar * sequences in linked lists, and then migrate the
1716 * contents of those lists to the sys module in _PyInitializeCore.
1717 *
1718 */
1719
1720struct _preinit_entry {
1721 wchar_t *value;
1722 struct _preinit_entry *next;
1723};
1724
1725typedef struct _preinit_entry *_Py_PreInitEntry;
1726
1727static _Py_PreInitEntry _preinit_warnoptions = NULL;
1728static _Py_PreInitEntry _preinit_xoptions = NULL;
1729
1730static _Py_PreInitEntry
1731_alloc_preinit_entry(const wchar_t *value)
1732{
1733 /* To get this to work, we have to initialize the runtime implicitly */
1734 _PyRuntime_Initialize();
1735
1736 /* Force default allocator, so we can ensure that it also gets used to
1737 * destroy the linked list in _clear_preinit_entries.
1738 */
1739 PyMemAllocatorEx old_alloc;
1740 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1741
1742 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1743 if (node != NULL) {
1744 node->value = _PyMem_RawWcsdup(value);
1745 if (node->value == NULL) {
1746 PyMem_RawFree(node);
1747 node = NULL;
1748 };
1749 };
1750
1751 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1752 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001753}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001754
1755static int
1756_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1757{
1758 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1759 if (new_entry == NULL) {
1760 return -1;
1761 }
1762 /* We maintain the linked list in this order so it's easy to play back
1763 * the add commands in the same order later on in _Py_InitializeCore
1764 */
1765 _Py_PreInitEntry last_entry = *optionlist;
1766 if (last_entry == NULL) {
1767 *optionlist = new_entry;
1768 } else {
1769 while (last_entry->next != NULL) {
1770 last_entry = last_entry->next;
1771 }
1772 last_entry->next = new_entry;
1773 }
1774 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001775}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001776
1777static void
1778_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1779{
1780 _Py_PreInitEntry current = *optionlist;
1781 *optionlist = NULL;
1782 /* Deallocate the nodes and their contents using the default allocator */
1783 PyMemAllocatorEx old_alloc;
1784 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1785 while (current != NULL) {
1786 _Py_PreInitEntry next = current->next;
1787 PyMem_RawFree(current->value);
1788 PyMem_RawFree(current);
1789 current = next;
1790 }
1791 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001792}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001793
1794static void
1795_clear_all_preinit_options(void)
1796{
1797 _clear_preinit_entries(&_preinit_warnoptions);
1798 _clear_preinit_entries(&_preinit_xoptions);
1799}
1800
1801static int
1802_PySys_ReadPreInitOptions(void)
1803{
1804 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001805 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001806 if (tstate == NULL) {
1807 /* Still don't have a thread state, so something is wrong! */
1808 return -1;
1809 }
1810 _Py_PreInitEntry entry = _preinit_warnoptions;
1811 while (entry != NULL) {
1812 PySys_AddWarnOption(entry->value);
1813 entry = entry->next;
1814 }
1815 entry = _preinit_xoptions;
1816 while (entry != NULL) {
1817 PySys_AddXOption(entry->value);
1818 entry = entry->next;
1819 }
1820
1821 _clear_all_preinit_options();
1822 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001823}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001824
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001825static PyObject *
1826get_warnoptions(void)
1827{
Eric Snowdae02762017-09-14 00:35:58 -07001828 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001829 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001830 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1831 * interpreter config. When that happens, we need to properly set
1832 * the `warnoptions` reference in the main interpreter config as well.
1833 *
1834 * For Python 3.7, we shouldn't be able to get here due to the
1835 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1836 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1837 * call optional for embedding applications, thus making this
1838 * reachable again.
1839 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001840 warnoptions = PyList_New(0);
1841 if (warnoptions == NULL)
1842 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001843 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1844 Py_DECREF(warnoptions);
1845 return NULL;
1846 }
1847 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001848 }
1849 return warnoptions;
1850}
Guido van Rossum23fff912000-12-15 22:02:05 +00001851
1852void
1853PySys_ResetWarnOptions(void)
1854{
Victor Stinner50b48572018-11-01 01:51:40 +01001855 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001856 if (tstate == NULL) {
1857 _clear_preinit_entries(&_preinit_warnoptions);
1858 return;
1859 }
1860
Eric Snowdae02762017-09-14 00:35:58 -07001861 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001862 if (warnoptions == NULL || !PyList_Check(warnoptions))
1863 return;
1864 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001865}
1866
Victor Stinnere1b29952018-10-30 14:31:42 +01001867static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001868_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001869{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001870 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001871 if (warnoptions == NULL) {
1872 return -1;
1873 }
1874 if (PyList_Append(warnoptions, option)) {
1875 return -1;
1876 }
1877 return 0;
1878}
1879
1880void
1881PySys_AddWarnOptionUnicode(PyObject *option)
1882{
Victor Stinnere1b29952018-10-30 14:31:42 +01001883 if (_PySys_AddWarnOptionWithError(option) < 0) {
1884 /* No return value, therefore clear error state if possible */
1885 if (_PyThreadState_UncheckedGet()) {
1886 PyErr_Clear();
1887 }
1888 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001889}
1890
1891void
1892PySys_AddWarnOption(const wchar_t *s)
1893{
Victor Stinner50b48572018-11-01 01:51:40 +01001894 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001895 if (tstate == NULL) {
1896 _append_preinit_entry(&_preinit_warnoptions, s);
1897 return;
1898 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001899 PyObject *unicode;
1900 unicode = PyUnicode_FromWideChar(s, -1);
1901 if (unicode == NULL)
1902 return;
1903 PySys_AddWarnOptionUnicode(unicode);
1904 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001905}
1906
Christian Heimes33fe8092008-04-13 13:53:33 +00001907int
1908PySys_HasWarnOptions(void)
1909{
Eric Snowdae02762017-09-14 00:35:58 -07001910 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001911 return (warnoptions != NULL && PyList_Check(warnoptions)
1912 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001913}
1914
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001915static PyObject *
1916get_xoptions(void)
1917{
Eric Snowdae02762017-09-14 00:35:58 -07001918 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001919 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001920 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1921 * interpreter config. When that happens, we need to properly set
1922 * the `xoptions` reference in the main interpreter config as well.
1923 *
1924 * For Python 3.7, we shouldn't be able to get here due to the
1925 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1926 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1927 * call optional for embedding applications, thus making this
1928 * reachable again.
1929 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001930 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001931 if (xoptions == NULL)
1932 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001933 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1934 Py_DECREF(xoptions);
1935 return NULL;
1936 }
1937 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001938 }
1939 return xoptions;
1940}
1941
Victor Stinnere1b29952018-10-30 14:31:42 +01001942static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001943_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001944{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001945 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001946
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001947 PyObject *opts = get_xoptions();
1948 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001949 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001950 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001951
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001952 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001953 if (!name_end) {
1954 name = PyUnicode_FromWideChar(s, -1);
1955 value = Py_True;
1956 Py_INCREF(value);
1957 }
1958 else {
1959 name = PyUnicode_FromWideChar(s, name_end - s);
1960 value = PyUnicode_FromWideChar(name_end + 1, -1);
1961 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001962 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001963 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001964 }
1965 if (PyDict_SetItem(opts, name, value) < 0) {
1966 goto error;
1967 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001968 Py_DECREF(name);
1969 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001970 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001971
1972error:
1973 Py_XDECREF(name);
1974 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975 return -1;
1976}
1977
1978void
1979PySys_AddXOption(const wchar_t *s)
1980{
Victor Stinner50b48572018-11-01 01:51:40 +01001981 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001982 if (tstate == NULL) {
1983 _append_preinit_entry(&_preinit_xoptions, s);
1984 return;
1985 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001986 if (_PySys_AddXOptionWithError(s) < 0) {
1987 /* No return value, therefore clear error state if possible */
1988 if (_PyThreadState_UncheckedGet()) {
1989 PyErr_Clear();
1990 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001991 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001992}
1993
1994PyObject *
1995PySys_GetXOptions(void)
1996{
1997 return get_xoptions();
1998}
1999
Guido van Rossum40552d01998-08-06 03:34:39 +00002000/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2001 Two literals concatenated works just fine. If you have a K&R compiler
2002 or other abomination that however *does* understand longer strings,
2003 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002004PyDoc_VAR(sys_doc) =
2005PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002006"This module provides access to some objects used or maintained by the\n\
2007interpreter and to functions that interact strongly with the interpreter.\n\
2008\n\
2009Dynamic objects:\n\
2010\n\
2011argv -- command line arguments; argv[0] is the script pathname if known\n\
2012path -- module search path; path[0] is the script directory, else ''\n\
2013modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002014\n\
2015displayhook -- called to show results in an interactive session\n\
2016excepthook -- called to handle any uncaught exception other than SystemExit\n\
2017 To customize printing in an interactive session or to install a custom\n\
2018 top-level exception handler, assign other functions to replace these.\n\
2019\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002020stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002021stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002022stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002023 By assigning other file objects (or objects that behave like files)\n\
2024 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002025\n\
2026last_type -- type of last uncaught exception\n\
2027last_value -- value of last uncaught exception\n\
2028last_traceback -- traceback of last uncaught exception\n\
2029 These three are only available in an interactive session after a\n\
2030 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002031"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002032)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002033/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002034PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002035"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002036Static objects:\n\
2037\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002038builtin_module_names -- tuple of module names built into this interpreter\n\
2039copyright -- copyright notice pertaining to this interpreter\n\
2040exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002041executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002042float_info -- a struct sequence with information about the float implementation.\n\
2043float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002044hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002045hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002046implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002047int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002048maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002049maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002050platform -- platform identifier\n\
2051prefix -- prefix used to find the Python library\n\
2052thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002053version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002054version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002055"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002056)
Steve Dowercc16be82016-09-08 10:35:16 -07002057#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002058/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002059PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002060"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002061winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002062"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002063)
Steve Dowercc16be82016-09-08 10:35:16 -07002064#endif /* MS_COREDLL */
2065#ifdef MS_WINDOWS
2066/* concatenating string here */
2067PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002068"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002069"
2070)
2071#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002072PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002073"__stdin__ -- the original stdin; don't touch!\n\
2074__stdout__ -- the original stdout; don't touch!\n\
2075__stderr__ -- the original stderr; don't touch!\n\
2076__displayhook__ -- the original displayhook; don't touch!\n\
2077__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002078\n\
2079Functions:\n\
2080\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002081displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002082excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002083exc_info() -- return thread-safe information about the current exception\n\
2084exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002085getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002086getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002087getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002088getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002089getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002090gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002091setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002092setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002093setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002094setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002095settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002096"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002097)
Fred Drakeccede592000-08-14 20:59:57 +00002098/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002099
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002100
2101PyDoc_STRVAR(flags__doc__,
2102"sys.flags\n\
2103\n\
2104Flags provided through command line arguments or environment vars.");
2105
2106static PyTypeObject FlagsType;
2107
2108static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 {"inspect", "-i"},
2111 {"interactive", "-i"},
2112 {"optimize", "-O or -OO"},
2113 {"dont_write_bytecode", "-B"},
2114 {"no_user_site", "-s"},
2115 {"no_site", "-S"},
2116 {"ignore_environment", "-E"},
2117 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 /* {"unbuffered", "-u"}, */
2119 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002120 {"bytes_warning", "-b"},
2121 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002122 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002123 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002124 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002125 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002127};
2128
2129static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 "sys.flags", /* name */
2131 flags__doc__, /* doc */
2132 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002133 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002134};
2135
2136static PyObject*
Victor Stinner43125222019-04-24 18:23:53 +02002137make_flags(_PyRuntimeState *runtime, PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002138{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 int pos = 0;
2140 PyObject *seq;
Victor Stinner43125222019-04-24 18:23:53 +02002141 const _PyPreConfig *preconfig = &runtime->preconfig;
2142 const _PyCoreConfig *config = &interp->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 seq = PyStructSequence_New(&FlagsType);
2145 if (seq == NULL)
2146 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002147
2148#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002150
Victor Stinnerfbca9082018-08-30 00:50:45 +02002151 SetFlag(config->parser_debug);
2152 SetFlag(config->inspect);
2153 SetFlag(config->interactive);
2154 SetFlag(config->optimization_level);
2155 SetFlag(!config->write_bytecode);
2156 SetFlag(!config->user_site_directory);
2157 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002158 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002159 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 /* SetFlag(saw_unbuffered_flag); */
2161 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002162 SetFlag(config->bytes_warning);
2163 SetFlag(config->quiet);
2164 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002165 SetFlag(config->isolated);
2166 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2167 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002168#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002169
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002171 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return NULL;
2173 }
2174 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002175}
2176
Eric Smith0e5b5622009-02-06 01:32:42 +00002177PyDoc_STRVAR(version_info__doc__,
2178"sys.version_info\n\
2179\n\
2180Version information as a named tuple.");
2181
2182static PyTypeObject VersionInfoType;
2183
2184static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 {"major", "Major release number"},
2186 {"minor", "Minor release number"},
2187 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002188 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002189 {"serial", "Serial release number"},
2190 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002191};
2192
2193static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002194 "sys.version_info", /* name */
2195 version_info__doc__, /* doc */
2196 version_info_fields, /* fields */
2197 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002198};
2199
2200static PyObject *
2201make_version_info(void)
2202{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 PyObject *version_info;
2204 char *s;
2205 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002206
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002207 version_info = PyStructSequence_New(&VersionInfoType);
2208 if (version_info == NULL) {
2209 return NULL;
2210 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002211
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 /*
2213 * These release level checks are mutually exclusive and cover
2214 * the field, so don't get too fancy with the pre-processor!
2215 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002216#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002218#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002220#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002221 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002222#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002224#endif
2225
2226#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002228#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002229 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002230
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002231 SetIntItem(PY_MAJOR_VERSION);
2232 SetIntItem(PY_MINOR_VERSION);
2233 SetIntItem(PY_MICRO_VERSION);
2234 SetStrItem(s);
2235 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002236#undef SetIntItem
2237#undef SetStrItem
2238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 if (PyErr_Occurred()) {
2240 Py_CLEAR(version_info);
2241 return NULL;
2242 }
2243 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002244}
2245
Brett Cannon3adc7b72012-07-09 14:22:12 -04002246/* sys.implementation values */
2247#define NAME "cpython"
2248const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002249#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2250#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002251#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002252const char *_PySys_ImplCacheTag = TAG;
2253#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002254#undef MAJOR
2255#undef MINOR
2256#undef TAG
2257
Barry Warsaw409da152012-06-03 16:18:47 -04002258static PyObject *
2259make_impl_info(PyObject *version_info)
2260{
2261 int res;
2262 PyObject *impl_info, *value, *ns;
2263
2264 impl_info = PyDict_New();
2265 if (impl_info == NULL)
2266 return NULL;
2267
2268 /* populate the dict */
2269
Brett Cannon3adc7b72012-07-09 14:22:12 -04002270 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002271 if (value == NULL)
2272 goto error;
2273 res = PyDict_SetItemString(impl_info, "name", value);
2274 Py_DECREF(value);
2275 if (res < 0)
2276 goto error;
2277
Brett Cannon3adc7b72012-07-09 14:22:12 -04002278 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002279 if (value == NULL)
2280 goto error;
2281 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2282 Py_DECREF(value);
2283 if (res < 0)
2284 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002285
2286 res = PyDict_SetItemString(impl_info, "version", version_info);
2287 if (res < 0)
2288 goto error;
2289
2290 value = PyLong_FromLong(PY_VERSION_HEX);
2291 if (value == NULL)
2292 goto error;
2293 res = PyDict_SetItemString(impl_info, "hexversion", value);
2294 Py_DECREF(value);
2295 if (res < 0)
2296 goto error;
2297
doko@ubuntu.com55532312016-06-14 08:55:19 +02002298#ifdef MULTIARCH
2299 value = PyUnicode_FromString(MULTIARCH);
2300 if (value == NULL)
2301 goto error;
2302 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2303 Py_DECREF(value);
2304 if (res < 0)
2305 goto error;
2306#endif
2307
Barry Warsaw409da152012-06-03 16:18:47 -04002308 /* dict ready */
2309
2310 ns = _PyNamespace_New(impl_info);
2311 Py_DECREF(impl_info);
2312 return ns;
2313
2314error:
2315 Py_CLEAR(impl_info);
2316 return NULL;
2317}
2318
Martin v. Löwis1a214512008-06-11 05:26:20 +00002319static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002320 PyModuleDef_HEAD_INIT,
2321 "sys",
2322 sys_doc,
2323 -1, /* multiple "initialization" just copies the module dict. */
2324 sys_methods,
2325 NULL,
2326 NULL,
2327 NULL,
2328 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002329};
2330
Eric Snow6b4be192017-05-22 21:36:03 -07002331/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002332#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002333 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002334 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002335 if (v == NULL) { \
2336 goto err_occurred; \
2337 } \
Victor Stinner58049602013-07-22 22:40:00 +02002338 res = PyDict_SetItemString(sysdict, key, v); \
2339 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002340 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002341 } \
2342 } while (0)
2343#define SET_SYS_FROM_STRING(key, value) \
2344 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002345 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002346 if (v == NULL) { \
2347 goto err_occurred; \
2348 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002349 res = PyDict_SetItemString(sysdict, key, v); \
2350 Py_DECREF(v); \
2351 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002352 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002353 } \
2354 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002355
Victor Stinnerab672812019-01-23 15:04:40 +01002356static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02002357_PySys_InitCore(_PyRuntimeState *runtime, PyInterpreterState *interp,
2358 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002359{
Victor Stinnerab672812019-01-23 15:04:40 +01002360 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002361 int res;
2362
Nick Coghland6009512014-11-20 21:39:37 +10002363 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002364
Victor Stinner8fea2522013-10-27 17:15:42 +01002365 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2366 PyDict_GetItemString(sysdict, "displayhook"));
2367 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2368 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002369 SET_SYS_FROM_STRING_BORROW(
2370 "__breakpointhook__",
2371 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 SET_SYS_FROM_STRING("version",
2373 PyUnicode_FromString(Py_GetVersion()));
2374 SET_SYS_FROM_STRING("hexversion",
2375 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002376 SET_SYS_FROM_STRING("_git",
2377 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2378 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002379 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002380 SET_SYS_FROM_STRING("api_version",
2381 PyLong_FromLong(PYTHON_API_VERSION));
2382 SET_SYS_FROM_STRING("copyright",
2383 PyUnicode_FromString(Py_GetCopyright()));
2384 SET_SYS_FROM_STRING("platform",
2385 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 SET_SYS_FROM_STRING("maxsize",
2387 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2388 SET_SYS_FROM_STRING("float_info",
2389 PyFloat_GetInfo());
2390 SET_SYS_FROM_STRING("int_info",
2391 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002392 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002393 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002394 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2395 goto type_init_failed;
2396 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002397 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002398 SET_SYS_FROM_STRING("hash_info",
2399 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002401 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002402 SET_SYS_FROM_STRING("builtin_module_names",
2403 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002404#if PY_BIG_ENDIAN
2405 SET_SYS_FROM_STRING("byteorder",
2406 PyUnicode_FromString("big"));
2407#else
2408 SET_SYS_FROM_STRING("byteorder",
2409 PyUnicode_FromString("little"));
2410#endif
Fred Drake099325e2000-08-14 15:47:03 +00002411
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002412#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002413 SET_SYS_FROM_STRING("dllhandle",
2414 PyLong_FromVoidPtr(PyWin_DLLhModule));
2415 SET_SYS_FROM_STRING("winver",
2416 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002417#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002418#ifdef ABIFLAGS
2419 SET_SYS_FROM_STRING("abiflags",
2420 PyUnicode_FromString(ABIFLAGS));
2421#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002423 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002424 if (VersionInfoType.tp_name == NULL) {
2425 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002426 &version_info_desc) < 0) {
2427 goto type_init_failed;
2428 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002429 }
Barry Warsaw409da152012-06-03 16:18:47 -04002430 version_info = make_version_info();
2431 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002432 /* prevent user from creating new instances */
2433 VersionInfoType.tp_init = NULL;
2434 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002435 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2436 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2437 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002438
Barry Warsaw409da152012-06-03 16:18:47 -04002439 /* implementation */
2440 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002442 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002443 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002444 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2445 goto type_init_failed;
2446 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002447 }
Victor Stinner43125222019-04-24 18:23:53 +02002448 /* Set flags to their default values (updated by _PySys_InitMain()) */
2449 SET_SYS_FROM_STRING("flags", make_flags(runtime, interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002450
2451#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002452 /* getwindowsversion */
2453 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002454 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002455 &windows_version_desc) < 0) {
2456 goto type_init_failed;
2457 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 /* prevent user from creating new instances */
2459 WindowsVersionType.tp_init = NULL;
2460 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002461 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002462 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002463 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002464 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002465 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002466#endif
2467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002469#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 SET_SYS_FROM_STRING("float_repr_style",
2471 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002472#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002473 SET_SYS_FROM_STRING("float_repr_style",
2474 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002475#endif
2476
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002477 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002478
Yury Selivanoveb636452016-09-08 22:01:51 -07002479 /* initialize asyncgen_hooks */
2480 if (AsyncGenHooksType.tp_name == NULL) {
2481 if (PyStructSequence_InitType2(
2482 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002483 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002484 }
2485 }
2486
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002487 if (PyErr_Occurred()) {
2488 goto err_occurred;
2489 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002490 return _Py_INIT_OK();
2491
2492type_init_failed:
2493 return _Py_INIT_ERR("failed to initialize a type");
2494
2495err_occurred:
2496 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002497}
2498
Eric Snow6b4be192017-05-22 21:36:03 -07002499#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002500
2501/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002502#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2503 do { \
2504 PyObject *v = (value); \
2505 if (v == NULL) \
2506 return -1; \
2507 res = PyDict_SetItemString(sysdict, key, v); \
2508 Py_DECREF(v); \
2509 if (res < 0) { \
2510 return res; \
2511 } \
2512 } while (0)
2513
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002514
2515static int
2516sys_add_xoption(PyObject *opts, const wchar_t *s)
2517{
2518 PyObject *name, *value;
2519
2520 const wchar_t *name_end = wcschr(s, L'=');
2521 if (!name_end) {
2522 name = PyUnicode_FromWideChar(s, -1);
2523 value = Py_True;
2524 Py_INCREF(value);
2525 }
2526 else {
2527 name = PyUnicode_FromWideChar(s, name_end - s);
2528 value = PyUnicode_FromWideChar(name_end + 1, -1);
2529 }
2530 if (name == NULL || value == NULL) {
2531 goto error;
2532 }
2533 if (PyDict_SetItem(opts, name, value) < 0) {
2534 goto error;
2535 }
2536 Py_DECREF(name);
2537 Py_DECREF(value);
2538 return 0;
2539
2540error:
2541 Py_XDECREF(name);
2542 Py_XDECREF(value);
2543 return -1;
2544}
2545
2546
2547static PyObject*
2548sys_create_xoptions_dict(const _PyCoreConfig *config)
2549{
2550 Py_ssize_t nxoption = config->xoptions.length;
2551 wchar_t * const * xoptions = config->xoptions.items;
2552 PyObject *dict = PyDict_New();
2553 if (dict == NULL) {
2554 return NULL;
2555 }
2556
2557 for (Py_ssize_t i=0; i < nxoption; i++) {
2558 const wchar_t *option = xoptions[i];
2559 if (sys_add_xoption(dict, option) < 0) {
2560 Py_DECREF(dict);
2561 return NULL;
2562 }
2563 }
2564
2565 return dict;
2566}
2567
2568
Eric Snow6b4be192017-05-22 21:36:03 -07002569int
Victor Stinner43125222019-04-24 18:23:53 +02002570_PySys_InitMain(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002571{
Victor Stinnerab672812019-01-23 15:04:40 +01002572 PyObject *sysdict = interp->sysdict;
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002573 const _PyCoreConfig *config = &interp->core_config;
Eric Snow6b4be192017-05-22 21:36:03 -07002574 int res;
2575
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002576#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002577 do { \
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002578 PyObject *list = _PyWstrList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002579 if (list == NULL) { \
2580 return -1; \
2581 } \
2582 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2583 Py_DECREF(list); \
2584 } while (0)
2585
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002586#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2587 do { \
2588 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2589 if (str == NULL) { \
2590 return -1; \
2591 } \
2592 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2593 Py_DECREF(str); \
2594 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002595
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002596 COPY_LIST("path", config->module_search_paths);
2597
2598 SET_SYS_FROM_WSTR("executable", config->executable);
2599 SET_SYS_FROM_WSTR("prefix", config->prefix);
2600 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2601 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2602 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002603
Carl Meyerb193fa92018-06-15 22:40:56 -06002604 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002605 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002606 } else {
2607 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2608 }
2609
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002610 COPY_LIST("argv", config->argv);
2611 COPY_LIST("warnoptions", config->warnoptions);
2612
2613 PyObject *xoptions = sys_create_xoptions_dict(config);
2614 if (xoptions == NULL) {
2615 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002616 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002617 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002618 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002619
Victor Stinner37cd9822018-11-16 11:55:35 +01002620#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002621#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002622
Eric Snow6b4be192017-05-22 21:36:03 -07002623 /* Set flags to their final values */
Victor Stinner43125222019-04-24 18:23:53 +02002624 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002625 /* prevent user from creating new instances */
2626 FlagsType.tp_init = NULL;
2627 FlagsType.tp_new = NULL;
2628 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2629 if (res < 0) {
2630 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2631 return res;
2632 }
2633 PyErr_Clear();
2634 }
2635
2636 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002637 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002638
Eric Snowdae02762017-09-14 00:35:58 -07002639 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002640 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002641
Eric Snowdae02762017-09-14 00:35:58 -07002642 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002643 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002644
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002645 /* Transfer any sys.warnoptions and sys._xoptions set directly
2646 * by an embedding application from the linked list to the module. */
2647 if (_PySys_ReadPreInitOptions() != 0)
2648 return -1;
2649
Eric Snow6b4be192017-05-22 21:36:03 -07002650 if (PyErr_Occurred())
2651 return -1;
2652 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002653
2654err_occurred:
2655 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002656}
2657
Victor Stinner41264f12017-12-15 02:05:29 +01002658#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002659#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002660
Victor Stinnerab672812019-01-23 15:04:40 +01002661
2662/* Set up a preliminary stderr printer until we have enough
2663 infrastructure for the io module in place.
2664
2665 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
2666_PyInitError
2667_PySys_SetPreliminaryStderr(PyObject *sysdict)
2668{
2669 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2670 if (pstderr == NULL) {
2671 goto error;
2672 }
2673 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2674 goto error;
2675 }
2676 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2677 goto error;
2678 }
2679 Py_DECREF(pstderr);
2680 return _Py_INIT_OK();
2681
2682error:
2683 Py_XDECREF(pstderr);
2684 return _Py_INIT_ERR("can't set preliminary stderr");
2685}
2686
2687
2688/* Create sys module without all attributes: _PySys_InitMain() should be called
2689 later to add remaining attributes. */
2690_PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02002691_PySys_Create(_PyRuntimeState *runtime, PyInterpreterState *interp,
2692 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002693{
2694 PyObject *modules = PyDict_New();
2695 if (modules == NULL) {
2696 return _Py_INIT_ERR("can't make modules dictionary");
2697 }
2698 interp->modules = modules;
2699
2700 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2701 if (sysmod == NULL) {
2702 return _Py_INIT_ERR("failed to create a module object");
2703 }
2704
2705 PyObject *sysdict = PyModule_GetDict(sysmod);
2706 if (sysdict == NULL) {
2707 return _Py_INIT_ERR("can't initialize sys dict");
2708 }
2709 Py_INCREF(sysdict);
2710 interp->sysdict = sysdict;
2711
2712 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
2713 return _Py_INIT_ERR("can't initialize sys module");
2714 }
2715
2716 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
2717 if (_Py_INIT_FAILED(err)) {
2718 return err;
2719 }
2720
Victor Stinner43125222019-04-24 18:23:53 +02002721 err = _PySys_InitCore(runtime, interp, sysdict);
Victor Stinnerab672812019-01-23 15:04:40 +01002722 if (_Py_INIT_FAILED(err)) {
2723 return err;
2724 }
2725
2726 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
2727
2728 *sysmod_p = sysmod;
2729 return _Py_INIT_OK();
2730}
2731
2732
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002733static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002734makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002735{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 int i, n;
2737 const wchar_t *p;
2738 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002740 n = 1;
2741 p = path;
2742 while ((p = wcschr(p, delim)) != NULL) {
2743 n++;
2744 p++;
2745 }
2746 v = PyList_New(n);
2747 if (v == NULL)
2748 return NULL;
2749 for (i = 0; ; i++) {
2750 p = wcschr(path, delim);
2751 if (p == NULL)
2752 p = path + wcslen(path); /* End of string */
2753 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2754 if (w == NULL) {
2755 Py_DECREF(v);
2756 return NULL;
2757 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002758 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 if (*p == '\0')
2760 break;
2761 path = p+1;
2762 }
2763 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002764}
2765
2766void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002767PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002768{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002769 PyObject *v;
2770 if ((v = makepathobject(path, DELIM)) == NULL)
2771 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002772 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 Py_FatalError("can't assign sys.path");
2774 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002775}
2776
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002777static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01002778make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002779{
Victor Stinner74f65682019-03-15 15:08:05 +01002780 PyObject *list = PyList_New(argc);
2781 if (list == NULL) {
2782 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002783 }
Victor Stinner74f65682019-03-15 15:08:05 +01002784
2785 for (Py_ssize_t i = 0; i < argc; i++) {
2786 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
2787 if (v == NULL) {
2788 Py_DECREF(list);
2789 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 }
Victor Stinner74f65682019-03-15 15:08:05 +01002791 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002792 }
Victor Stinner74f65682019-03-15 15:08:05 +01002793 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002794}
2795
Victor Stinner11a247d2017-12-13 21:05:57 +01002796void
2797PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002798{
Victor Stinner74f65682019-03-15 15:08:05 +01002799 if (argc < 1 || argv == NULL) {
2800 /* Ensure at least one (empty) argument is seen */
2801 wchar_t* empty_argv[1] = {L""};
2802 argv = empty_argv;
2803 argc = 1;
2804 }
2805
2806 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002807 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002808 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002809 }
2810 if (PySys_SetObject("argv", av) != 0) {
2811 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002812 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002813 }
2814 Py_DECREF(av);
2815
2816 if (updatepath) {
2817 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2818 If argv[0] is a symlink, use the real path. */
Victor Stinner74f65682019-03-15 15:08:05 +01002819 const _PyWstrList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01002820 PyObject *path0 = NULL;
2821 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
2822 if (path0 == NULL) {
2823 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01002824 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01002825
2826 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2827 if (sys_path != NULL) {
2828 if (PyList_Insert(sys_path, 0, path0) < 0) {
2829 Py_DECREF(path0);
2830 Py_FatalError("can't prepend path0 to sys.path");
2831 }
2832 }
2833 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01002834 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002835 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002836}
Guido van Rossuma890e681998-05-12 14:59:24 +00002837
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002838void
2839PySys_SetArgv(int argc, wchar_t **argv)
2840{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002841 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002842}
2843
Victor Stinner14284c22010-04-23 12:02:30 +00002844/* Reimplementation of PyFile_WriteString() no calling indirectly
2845 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2846
2847static int
Victor Stinner79766632010-08-16 17:36:42 +00002848sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002849{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002850 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002851 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002852
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002853 if (file == NULL)
2854 return -1;
2855
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002856 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002857 if (writer == NULL)
2858 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002859
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002860 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002861 if (result == NULL) {
2862 goto error;
2863 } else {
2864 err = 0;
2865 goto finally;
2866 }
Victor Stinner14284c22010-04-23 12:02:30 +00002867
2868error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002869 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002870finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002871 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002872 Py_XDECREF(result);
2873 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002874}
2875
Victor Stinner79766632010-08-16 17:36:42 +00002876static int
2877sys_pyfile_write(const char *text, PyObject *file)
2878{
2879 PyObject *unicode = NULL;
2880 int err;
2881
2882 if (file == NULL)
2883 return -1;
2884
2885 unicode = PyUnicode_FromString(text);
2886 if (unicode == NULL)
2887 return -1;
2888
2889 err = sys_pyfile_write_unicode(unicode, file);
2890 Py_DECREF(unicode);
2891 return err;
2892}
Guido van Rossuma890e681998-05-12 14:59:24 +00002893
2894/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2895 Adapted from code submitted by Just van Rossum.
2896
2897 PySys_WriteStdout(format, ...)
2898 PySys_WriteStderr(format, ...)
2899
2900 The first function writes to sys.stdout; the second to sys.stderr. When
2901 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002902 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002903
Victor Stinner14284c22010-04-23 12:02:30 +00002904 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002905 signal handlers: they may raise a new exception whereas sys_write()
2906 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002907
Guido van Rossuma890e681998-05-12 14:59:24 +00002908 Both take a printf-style format string as their first argument followed
2909 by a variable length argument list determined by the format string.
2910
2911 *** WARNING ***
2912
2913 The format should limit the total size of the formatted output string to
2914 1000 bytes. In particular, this means that no unrestricted "%s" formats
2915 should occur; these should be limited using "%.<N>s where <N> is a
2916 decimal number calculated so that <N> plus the maximum size of other
2917 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2918 which can print hundreds of digits for very large numbers.
2919
2920 */
2921
2922static void
Victor Stinner09054372013-11-06 22:41:44 +01002923sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002924{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002925 PyObject *file;
2926 PyObject *error_type, *error_value, *error_traceback;
2927 char buffer[1001];
2928 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002929
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002930 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002931 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002932 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2933 if (sys_pyfile_write(buffer, file) != 0) {
2934 PyErr_Clear();
2935 fputs(buffer, fp);
2936 }
2937 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2938 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002939 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002940 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002941 }
2942 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002943}
2944
2945void
Guido van Rossuma890e681998-05-12 14:59:24 +00002946PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002947{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002948 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002949
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002950 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002951 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002952 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002953}
2954
2955void
Guido van Rossuma890e681998-05-12 14:59:24 +00002956PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002959
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002961 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002962 va_end(va);
2963}
2964
2965static void
Victor Stinner09054372013-11-06 22:41:44 +01002966sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002967{
2968 PyObject *file, *message;
2969 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002970 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002971
2972 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002973 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002974 message = PyUnicode_FromFormatV(format, va);
2975 if (message != NULL) {
2976 if (sys_pyfile_write_unicode(message, file) != 0) {
2977 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002978 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002979 if (utf8 != NULL)
2980 fputs(utf8, fp);
2981 }
2982 Py_DECREF(message);
2983 }
2984 PyErr_Restore(error_type, error_value, error_traceback);
2985}
2986
2987void
2988PySys_FormatStdout(const char *format, ...)
2989{
2990 va_list va;
2991
2992 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002993 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002994 va_end(va);
2995}
2996
2997void
2998PySys_FormatStderr(const char *format, ...)
2999{
3000 va_list va;
3001
3002 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003003 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003004 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003005}