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