blob: 1735b90b33b95583ec7b5ae1c928590fa0a4b57e [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]
Victor Stinneref9d9b62019-05-22 11:28:22 +0200378sys.unraisablehook
379
380 unraisable: object
381 /
382
383Handle an unraisable exception.
384
385The unraisable argument has the following attributes:
386
387* exc_type: Exception type.
388* exc_value: Exception value.
389* exc_tb: Exception traceback, can be None.
390* obj: Object causing the exception, can be None.
391[clinic start generated code]*/
392
393static PyObject *
394sys_unraisablehook(PyObject *module, PyObject *unraisable)
395/*[clinic end generated code: output=bb92838b32abaa14 input=fdbdb47fdd0bee06]*/
396{
397 return _PyErr_WriteUnraisableDefaultHook(unraisable);
398}
399
400
401/*[clinic input]
Tal Einatede0b6f2018-12-31 17:12:08 +0200402sys.exit
403
404 status: object = NULL
405 /
406
407Exit the interpreter by raising SystemExit(status).
408
409If the status is omitted or None, it defaults to zero (i.e., success).
410If the status is an integer, it will be used as the system exit status.
411If it is another kind of object, it will be printed and the system
412exit status will be one (i.e., failure).
413[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000414
415static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200416sys_exit_impl(PyObject *module, PyObject *status)
417/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000418{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200420 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000422}
423
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000424
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000425
Tal Einatede0b6f2018-12-31 17:12:08 +0200426/*[clinic input]
427sys.getdefaultencoding
428
429Return the current default encoding used by the Unicode implementation.
430[clinic start generated code]*/
431
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000432static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200433sys_getdefaultencoding_impl(PyObject *module)
434/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000435{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000436 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000437}
438
Tal Einatede0b6f2018-12-31 17:12:08 +0200439/*[clinic input]
440sys.getfilesystemencoding
441
442Return the encoding used to convert Unicode filenames to OS filenames.
443[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000444
445static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200446sys_getfilesystemencoding_impl(PyObject *module)
447/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000448{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200449 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
450 const _PyCoreConfig *config = &interp->core_config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400451 return PyUnicode_FromWideChar(config->filesystem_encoding, -1);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000452}
453
Tal Einatede0b6f2018-12-31 17:12:08 +0200454/*[clinic input]
455sys.getfilesystemencodeerrors
456
457Return the error mode used Unicode to OS filename conversion.
458[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000459
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000460static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200461sys_getfilesystemencodeerrors_impl(PyObject *module)
462/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700463{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200464 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
465 const _PyCoreConfig *config = &interp->core_config;
Victor Stinner709d23d2019-05-02 14:56:30 -0400466 return PyUnicode_FromWideChar(config->filesystem_errors, -1);
Steve Dowercc16be82016-09-08 10:35:16 -0700467}
468
Tal Einatede0b6f2018-12-31 17:12:08 +0200469/*[clinic input]
470sys.intern
471
472 string as s: unicode
473 /
474
475``Intern'' the given string.
476
477This enters the string in the (global) table of interned strings whose
478purpose is to speed up dictionary lookups. Return the string itself or
479the previously interned string object with the same value.
480[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700481
482static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200483sys_intern_impl(PyObject *module, PyObject *s)
484/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 if (PyUnicode_CheckExact(s)) {
487 Py_INCREF(s);
488 PyUnicode_InternInPlace(&s);
489 return s;
490 }
491 else {
492 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200493 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000494 return NULL;
495 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000496}
497
Georg Brandl66a796e2006-12-19 20:50:34 +0000498
Fred Drake5755ce62001-06-27 19:19:46 +0000499/*
500 * Cached interned string objects used for calling the profile and
501 * trace functions. Initialized by trace_init().
502 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000503static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000504
505static int
506trace_init(void)
507{
Nick Coghlan5a851672017-09-08 10:14:16 +1000508 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200509 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000510 "c_call", "c_exception", "c_return",
511 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200512 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 PyObject *name;
514 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000515 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 if (whatstrings[i] == NULL) {
517 name = PyUnicode_InternFromString(whatnames[i]);
518 if (name == NULL)
519 return -1;
520 whatstrings[i] = name;
521 }
522 }
523 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000524}
525
526
527static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100528call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200532 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000533
Victor Stinner78da82b2016-08-20 01:22:57 +0200534 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200536 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100537
Victor Stinner78da82b2016-08-20 01:22:57 +0200538 stack[0] = (PyObject *)frame;
539 stack[1] = whatstrings[what];
540 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200543 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000544
Victor Stinner78da82b2016-08-20 01:22:57 +0200545 PyFrame_LocalsToFast(frame, 1);
546 if (result == NULL) {
547 PyTraceBack_Here(frame);
548 }
549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000551}
552
553static int
554profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000555 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (arg == NULL)
560 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100561 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 if (result == NULL) {
563 PyEval_SetProfile(NULL, NULL);
564 return -1;
565 }
566 Py_DECREF(result);
567 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000568}
569
570static int
571trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 PyObject *callback;
575 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 if (what == PyTrace_CALL)
578 callback = self;
579 else
580 callback = frame->f_trace;
581 if (callback == NULL)
582 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100583 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000584 if (result == NULL) {
585 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200586 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000587 return -1;
588 }
589 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300590 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 }
592 else {
593 Py_DECREF(result);
594 }
595 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000596}
Fred Draked0838392001-06-16 21:02:31 +0000597
Fred Drake8b4d01d2000-05-09 19:57:01 +0000598static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000599sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 if (trace_init() == -1)
602 return NULL;
603 if (args == Py_None)
604 PyEval_SetTrace(NULL, NULL);
605 else
606 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200607 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000608}
609
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000610PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000611"settrace(function)\n\
612\n\
613Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000614function call. See the debugger chapter in the library manual."
615);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000616
Tal Einatede0b6f2018-12-31 17:12:08 +0200617/*[clinic input]
618sys.gettrace
619
620Return the global debug tracing function set with sys.settrace.
621
622See the debugger chapter in the library manual.
623[clinic start generated code]*/
624
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000625static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200626sys_gettrace_impl(PyObject *module)
627/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000628{
Victor Stinner50b48572018-11-01 01:51:40 +0100629 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000630 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (temp == NULL)
633 temp = Py_None;
634 Py_INCREF(temp);
635 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000636}
637
Christian Heimes9bd667a2008-01-20 15:14:11 +0000638static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000639sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000640{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000641 if (trace_init() == -1)
642 return NULL;
643 if (args == Py_None)
644 PyEval_SetProfile(NULL, NULL);
645 else
646 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200647 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000648}
649
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000650PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000651"setprofile(function)\n\
652\n\
653Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000654and return. See the profiler chapter in the library manual."
655);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000656
Tal Einatede0b6f2018-12-31 17:12:08 +0200657/*[clinic input]
658sys.getprofile
659
660Return the profiling function set with sys.setprofile.
661
662See the profiler chapter in the library manual.
663[clinic start generated code]*/
664
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000665static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200666sys_getprofile_impl(PyObject *module)
667/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000668{
Victor Stinner50b48572018-11-01 01:51:40 +0100669 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 if (temp == NULL)
673 temp = Py_None;
674 Py_INCREF(temp);
675 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000676}
677
Tal Einatede0b6f2018-12-31 17:12:08 +0200678/*[clinic input]
679sys.setcheckinterval
680
681 n: int
682 /
683
684Set the async event check interval to n instructions.
685
686This tells the Python interpreter to check for asynchronous events
687every n instructions.
688
689This also affects how often thread switches occur.
690[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000691
692static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200693sys_setcheckinterval_impl(PyObject *module, int n)
694/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000695{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (PyErr_WarnEx(PyExc_DeprecationWarning,
697 "sys.getcheckinterval() and sys.setcheckinterval() "
698 "are deprecated. Use sys.setswitchinterval() "
699 "instead.", 1) < 0)
700 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200701
Victor Stinnercaba55b2018-08-03 15:33:52 +0200702 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +0200703 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200704 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000705}
706
Tal Einatede0b6f2018-12-31 17:12:08 +0200707/*[clinic input]
708sys.getcheckinterval
709
710Return the current check interval; see sys.setcheckinterval().
711[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000712
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000713static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200714sys_getcheckinterval_impl(PyObject *module)
715/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000716{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000717 if (PyErr_WarnEx(PyExc_DeprecationWarning,
718 "sys.getcheckinterval() and sys.setcheckinterval() "
719 "are deprecated. Use sys.getswitchinterval() "
720 "instead.", 1) < 0)
721 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200722 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600723 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000724}
725
Tal Einatede0b6f2018-12-31 17:12:08 +0200726/*[clinic input]
727sys.setswitchinterval
728
729 interval: double
730 /
731
732Set the ideal thread switching delay inside the Python interpreter.
733
734The actual frequency of switching threads can be lower if the
735interpreter executes long sequences of uninterruptible code
736(this is implementation-specific and workload-dependent).
737
738The parameter must represent the desired switching delay in seconds
739A typical value is 0.005 (5 milliseconds).
740[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000741
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000742static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200743sys_setswitchinterval_impl(PyObject *module, double interval)
744/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000745{
Tal Einatede0b6f2018-12-31 17:12:08 +0200746 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyErr_SetString(PyExc_ValueError,
748 "switch interval must be strictly positive");
749 return NULL;
750 }
Tal Einatede0b6f2018-12-31 17:12:08 +0200751 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200752 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000753}
754
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000755
Tal Einatede0b6f2018-12-31 17:12:08 +0200756/*[clinic input]
757sys.getswitchinterval -> double
758
759Return the current thread switch interval; see sys.setswitchinterval().
760[clinic start generated code]*/
761
762static double
763sys_getswitchinterval_impl(PyObject *module)
764/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000765{
Tal Einatede0b6f2018-12-31 17:12:08 +0200766 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000767}
768
Tal Einatede0b6f2018-12-31 17:12:08 +0200769/*[clinic input]
770sys.setrecursionlimit
771
772 limit as new_limit: int
773 /
774
775Set the maximum depth of the Python interpreter stack to n.
776
777This limit prevents infinite recursion from causing an overflow of the C
778stack and crashing Python. The highest possible limit is platform-
779dependent.
780[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000781
Tim Peterse5e065b2003-07-06 18:36:54 +0000782static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200783sys_setrecursionlimit_impl(PyObject *module, int new_limit)
784/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000785{
Tal Einatede0b6f2018-12-31 17:12:08 +0200786 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +0200787 PyThreadState *tstate;
788
Victor Stinner50856d52015-10-13 00:11:21 +0200789 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200791 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 return NULL;
793 }
Victor Stinner50856d52015-10-13 00:11:21 +0200794
795 /* Issue #25274: When the recursion depth hits the recursion limit in
796 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
797 set to 1 and a RecursionError is raised. The overflowed flag is reset
798 to 0 when the recursion depth goes below the low-water mark: see
799 Py_LeaveRecursiveCall().
800
801 Reject too low new limit if the current recursion depth is higher than
802 the new low-water mark. Otherwise it may not be possible anymore to
803 reset the overflowed flag to 0. */
804 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100805 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200806 if (tstate->recursion_depth >= mark) {
807 PyErr_Format(PyExc_RecursionError,
808 "cannot set the recursion limit to %i at "
809 "the recursion depth %i: the limit is too low",
810 new_limit, tstate->recursion_depth);
811 return NULL;
812 }
813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000814 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200815 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000816}
817
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800818/*[clinic input]
819sys.set_coroutine_origin_tracking_depth
820
821 depth: int
822
823Enable or disable origin tracking for coroutine objects in this thread.
824
Tal Einatede0b6f2018-12-31 17:12:08 +0200825Coroutine objects will track 'depth' frames of traceback information
826about where they came from, available in their cr_origin attribute.
827
828Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800829[clinic start generated code]*/
830
831static PyObject *
832sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +0200833/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800834{
835 if (depth < 0) {
836 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
837 return NULL;
838 }
839 _PyEval_SetCoroutineOriginTrackingDepth(depth);
840 Py_RETURN_NONE;
841}
842
843/*[clinic input]
844sys.get_coroutine_origin_tracking_depth -> int
845
846Check status of origin tracking for coroutine objects in this thread.
847[clinic start generated code]*/
848
849static int
850sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
851/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
852{
853 return _PyEval_GetCoroutineOriginTrackingDepth();
854}
855
Tal Einatede0b6f2018-12-31 17:12:08 +0200856/*[clinic input]
857sys.set_coroutine_wrapper
858
859 wrapper: object
860 /
861
862Set a wrapper for coroutine objects.
863[clinic start generated code]*/
864
Yury Selivanov75445082015-05-11 22:57:16 -0400865static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200866sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
867/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400868{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800869 if (PyErr_WarnEx(PyExc_DeprecationWarning,
870 "set_coroutine_wrapper is deprecated", 1) < 0) {
871 return NULL;
872 }
873
Yury Selivanov75445082015-05-11 22:57:16 -0400874 if (wrapper != Py_None) {
875 if (!PyCallable_Check(wrapper)) {
876 PyErr_Format(PyExc_TypeError,
877 "callable expected, got %.50s",
878 Py_TYPE(wrapper)->tp_name);
879 return NULL;
880 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400881 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400882 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400883 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400884 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400885 }
Yury Selivanov75445082015-05-11 22:57:16 -0400886 Py_RETURN_NONE;
887}
888
Tal Einatede0b6f2018-12-31 17:12:08 +0200889/*[clinic input]
890sys.get_coroutine_wrapper
891
892Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
893[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400894
895static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200896sys_get_coroutine_wrapper_impl(PyObject *module)
897/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400898{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800899 if (PyErr_WarnEx(PyExc_DeprecationWarning,
900 "get_coroutine_wrapper is deprecated", 1) < 0) {
901 return NULL;
902 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400903 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400904 if (wrapper == NULL) {
905 wrapper = Py_None;
906 }
907 Py_INCREF(wrapper);
908 return wrapper;
909}
910
Yury Selivanov75445082015-05-11 22:57:16 -0400911
Yury Selivanoveb636452016-09-08 22:01:51 -0700912static PyTypeObject AsyncGenHooksType;
913
914PyDoc_STRVAR(asyncgen_hooks_doc,
915"asyncgen_hooks\n\
916\n\
917A struct sequence providing information about asynhronous\n\
918generators hooks. The attributes are read only.");
919
920static PyStructSequence_Field asyncgen_hooks_fields[] = {
921 {"firstiter", "Hook to intercept first iteration"},
922 {"finalizer", "Hook to intercept finalization"},
923 {0}
924};
925
926static PyStructSequence_Desc asyncgen_hooks_desc = {
927 "asyncgen_hooks", /* name */
928 asyncgen_hooks_doc, /* doc */
929 asyncgen_hooks_fields , /* fields */
930 2
931};
932
Yury Selivanoveb636452016-09-08 22:01:51 -0700933static PyObject *
934sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
935{
936 static char *keywords[] = {"firstiter", "finalizer", NULL};
937 PyObject *firstiter = NULL;
938 PyObject *finalizer = NULL;
939
940 if (!PyArg_ParseTupleAndKeywords(
941 args, kw, "|OO", keywords,
942 &firstiter, &finalizer)) {
943 return NULL;
944 }
945
946 if (finalizer && finalizer != Py_None) {
947 if (!PyCallable_Check(finalizer)) {
948 PyErr_Format(PyExc_TypeError,
949 "callable finalizer expected, got %.50s",
950 Py_TYPE(finalizer)->tp_name);
951 return NULL;
952 }
953 _PyEval_SetAsyncGenFinalizer(finalizer);
954 }
955 else if (finalizer == Py_None) {
956 _PyEval_SetAsyncGenFinalizer(NULL);
957 }
958
959 if (firstiter && firstiter != Py_None) {
960 if (!PyCallable_Check(firstiter)) {
961 PyErr_Format(PyExc_TypeError,
962 "callable firstiter expected, got %.50s",
963 Py_TYPE(firstiter)->tp_name);
964 return NULL;
965 }
966 _PyEval_SetAsyncGenFirstiter(firstiter);
967 }
968 else if (firstiter == Py_None) {
969 _PyEval_SetAsyncGenFirstiter(NULL);
970 }
971
972 Py_RETURN_NONE;
973}
974
975PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +0200976"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -0700977\n\
978Set a finalizer for async generators objects."
979);
980
Tal Einatede0b6f2018-12-31 17:12:08 +0200981/*[clinic input]
982sys.get_asyncgen_hooks
983
984Return the installed asynchronous generators hooks.
985
986This returns a namedtuple of the form (firstiter, finalizer).
987[clinic start generated code]*/
988
Yury Selivanoveb636452016-09-08 22:01:51 -0700989static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200990sys_get_asyncgen_hooks_impl(PyObject *module)
991/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -0700992{
993 PyObject *res;
994 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
995 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
996
997 res = PyStructSequence_New(&AsyncGenHooksType);
998 if (res == NULL) {
999 return NULL;
1000 }
1001
1002 if (firstiter == NULL) {
1003 firstiter = Py_None;
1004 }
1005
1006 if (finalizer == NULL) {
1007 finalizer = Py_None;
1008 }
1009
1010 Py_INCREF(firstiter);
1011 PyStructSequence_SET_ITEM(res, 0, firstiter);
1012
1013 Py_INCREF(finalizer);
1014 PyStructSequence_SET_ITEM(res, 1, finalizer);
1015
1016 return res;
1017}
1018
Yury Selivanoveb636452016-09-08 22:01:51 -07001019
Mark Dickinsondc787d22010-05-23 13:33:13 +00001020static PyTypeObject Hash_InfoType;
1021
1022PyDoc_STRVAR(hash_info_doc,
1023"hash_info\n\
1024\n\
1025A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001026hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001027
1028static PyStructSequence_Field hash_info_fields[] = {
1029 {"width", "width of the type used for hashing, in bits"},
1030 {"modulus", "prime number giving the modulus on which the hash "
1031 "function is based"},
1032 {"inf", "value to be used for hash of a positive infinity"},
1033 {"nan", "value to be used for hash of a nan"},
1034 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001035 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1036 "memoryviews"},
1037 {"hash_bits", "internal output size of hash algorithm"},
1038 {"seed_bits", "seed size of hash algorithm"},
1039 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001040 {NULL, NULL}
1041};
1042
1043static PyStructSequence_Desc hash_info_desc = {
1044 "sys.hash_info",
1045 hash_info_doc,
1046 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001047 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001048};
1049
Matthias Klosed885e952010-07-06 10:53:30 +00001050static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001051get_hash_info(void)
1052{
1053 PyObject *hash_info;
1054 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001055 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001056 hash_info = PyStructSequence_New(&Hash_InfoType);
1057 if (hash_info == NULL)
1058 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001059 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001060 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001061 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001062 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001063 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001064 PyStructSequence_SET_ITEM(hash_info, field++,
1065 PyLong_FromLong(_PyHASH_INF));
1066 PyStructSequence_SET_ITEM(hash_info, field++,
1067 PyLong_FromLong(_PyHASH_NAN));
1068 PyStructSequence_SET_ITEM(hash_info, field++,
1069 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001070 PyStructSequence_SET_ITEM(hash_info, field++,
1071 PyUnicode_FromString(hashfunc->name));
1072 PyStructSequence_SET_ITEM(hash_info, field++,
1073 PyLong_FromLong(hashfunc->hash_bits));
1074 PyStructSequence_SET_ITEM(hash_info, field++,
1075 PyLong_FromLong(hashfunc->seed_bits));
1076 PyStructSequence_SET_ITEM(hash_info, field++,
1077 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001078 if (PyErr_Occurred()) {
1079 Py_CLEAR(hash_info);
1080 return NULL;
1081 }
1082 return hash_info;
1083}
Tal Einatede0b6f2018-12-31 17:12:08 +02001084/*[clinic input]
1085sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001086
Tal Einatede0b6f2018-12-31 17:12:08 +02001087Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001088
Tal Einatede0b6f2018-12-31 17:12:08 +02001089The recursion limit is the maximum depth of the Python interpreter
1090stack. This limit prevents infinite recursion from causing an overflow
1091of the C stack and crashing Python.
1092[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001093
1094static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001095sys_getrecursionlimit_impl(PyObject *module)
1096/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001099}
1100
Mark Hammond8696ebc2002-10-08 02:44:31 +00001101#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001102
Eric Smithf7bb5782010-01-27 00:44:57 +00001103static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1104
1105static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 {"major", "Major version number"},
1107 {"minor", "Minor version number"},
1108 {"build", "Build number"},
1109 {"platform", "Operating system platform"},
1110 {"service_pack", "Latest Service Pack installed on the system"},
1111 {"service_pack_major", "Service Pack major version number"},
1112 {"service_pack_minor", "Service Pack minor version number"},
1113 {"suite_mask", "Bit mask identifying available product suites"},
1114 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001115 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001117};
1118
1119static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001120 "sys.getwindowsversion", /* name */
1121 sys_getwindowsversion__doc__, /* doc */
1122 windows_version_fields, /* fields */
1123 5 /* For backward compatibility,
1124 only the first 5 items are accessible
1125 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001126};
1127
Steve Dower3e96f322015-03-02 08:01:10 -08001128/* Disable deprecation warnings about GetVersionEx as the result is
1129 being passed straight through to the caller, who is responsible for
1130 using it correctly. */
1131#pragma warning(push)
1132#pragma warning(disable:4996)
1133
Tal Einatede0b6f2018-12-31 17:12:08 +02001134/*[clinic input]
1135sys.getwindowsversion
1136
1137Return info about the running version of Windows as a named tuple.
1138
1139The members are named: major, minor, build, platform, service_pack,
1140service_pack_major, service_pack_minor, suite_mask, product_type and
1141platform_version. For backward compatibility, only the first 5 items
1142are available by indexing. All elements are numbers, except
1143service_pack and platform_type which are strings, and platform_version
1144which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1145workstation, 2 for a domain controller, 3 for a server.
1146Platform_version is a 3-tuple containing a version number that is
1147intended for identifying the OS rather than feature detection.
1148[clinic start generated code]*/
1149
Mark Hammond8696ebc2002-10-08 02:44:31 +00001150static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001151sys_getwindowsversion_impl(PyObject *module)
1152/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001153{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 PyObject *version;
1155 int pos = 0;
Minmin Gong8ebc6452019-02-02 20:26:55 -08001156 OSVERSIONINFOEXW ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001157 DWORD realMajor, realMinor, realBuild;
1158 HANDLE hKernel32;
1159 wchar_t kernel32_path[MAX_PATH];
1160 LPVOID verblock;
1161 DWORD verblock_size;
1162
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 ver.dwOSVersionInfoSize = sizeof(ver);
Minmin Gong8ebc6452019-02-02 20:26:55 -08001164 if (!GetVersionExW((OSVERSIONINFOW*) &ver))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001165 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001166
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 version = PyStructSequence_New(&WindowsVersionType);
1168 if (version == NULL)
1169 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001170
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1172 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1173 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1174 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
Minmin Gong8ebc6452019-02-02 20:26:55 -08001175 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromWideChar(ver.szCSDVersion, -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001176 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1177 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1178 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1179 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001180
Steve Dower74f4af72016-09-17 17:27:48 -07001181 realMajor = ver.dwMajorVersion;
1182 realMinor = ver.dwMinorVersion;
1183 realBuild = ver.dwBuildNumber;
1184
1185 // GetVersion will lie if we are running in a compatibility mode.
1186 // We need to read the version info from a system file resource
1187 // to accurately identify the OS version. If we fail for any reason,
1188 // just return whatever GetVersion said.
Tony Roberts4860f012019-02-02 18:16:42 +01001189 Py_BEGIN_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001190 hKernel32 = GetModuleHandleW(L"kernel32.dll");
Tony Roberts4860f012019-02-02 18:16:42 +01001191 Py_END_ALLOW_THREADS
Steve Dower74f4af72016-09-17 17:27:48 -07001192 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1193 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1194 (verblock = PyMem_RawMalloc(verblock_size))) {
1195 VS_FIXEDFILEINFO *ffi;
1196 UINT ffi_len;
1197
1198 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1199 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1200 realMajor = HIWORD(ffi->dwProductVersionMS);
1201 realMinor = LOWORD(ffi->dwProductVersionMS);
1202 realBuild = HIWORD(ffi->dwProductVersionLS);
1203 }
1204 PyMem_RawFree(verblock);
1205 }
Segev Finer48fb7662017-06-04 20:52:27 +03001206 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1207 realMajor,
1208 realMinor,
1209 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001210 ));
1211
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001212 if (PyErr_Occurred()) {
1213 Py_DECREF(version);
1214 return NULL;
1215 }
Steve Dower74f4af72016-09-17 17:27:48 -07001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001218}
1219
Steve Dower3e96f322015-03-02 08:01:10 -08001220#pragma warning(pop)
1221
Tal Einatede0b6f2018-12-31 17:12:08 +02001222/*[clinic input]
1223sys._enablelegacywindowsfsencoding
1224
1225Changes the default filesystem encoding to mbcs:replace.
1226
1227This is done for consistency with earlier versions of Python. See PEP
1228529 for more information.
1229
1230This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1231environment variable before launching Python.
1232[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001233
1234static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001235sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1236/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001237{
Victor Stinner709d23d2019-05-02 14:56:30 -04001238 if (_PyUnicode_EnableLegacyWindowsFSEncoding() < 0) {
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001239 return NULL;
1240 }
Steve Dowercc16be82016-09-08 10:35:16 -07001241 Py_RETURN_NONE;
1242}
1243
Mark Hammond8696ebc2002-10-08 02:44:31 +00001244#endif /* MS_WINDOWS */
1245
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001246#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001247
1248/*[clinic input]
1249sys.setdlopenflags
1250
1251 flags as new_val: int
1252 /
1253
1254Set the flags used by the interpreter for dlopen calls.
1255
1256This is used, for example, when the interpreter loads extension
1257modules. Among other things, this will enable a lazy resolving of
1258symbols when importing a module, if called as sys.setdlopenflags(0).
1259To share symbols across extension modules, call as
1260sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1261modules can be found in the os module (RTLD_xxx constants, e.g.
1262os.RTLD_LAZY).
1263[clinic start generated code]*/
1264
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001265static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001266sys_setdlopenflags_impl(PyObject *module, int new_val)
1267/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001268{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001269 PyInterpreterState *interp = _PyInterpreterState_Get();
1270 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001271 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001272}
1273
Tal Einatede0b6f2018-12-31 17:12:08 +02001274
1275/*[clinic input]
1276sys.getdlopenflags
1277
1278Return the current value of the flags that are used for dlopen calls.
1279
1280The flag constants are defined in the os module.
1281[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001282
1283static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001284sys_getdlopenflags_impl(PyObject *module)
1285/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001286{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001287 PyInterpreterState *interp = _PyInterpreterState_Get();
1288 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001289}
1290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001291#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001292
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001293#ifdef USE_MALLOPT
1294/* Link with -lmalloc (or -lmpc) on an SGI */
1295#include <malloc.h>
1296
Tal Einatede0b6f2018-12-31 17:12:08 +02001297/*[clinic input]
1298sys.mdebug
1299
1300 flag: int
1301 /
1302[clinic start generated code]*/
1303
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001304static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001305sys_mdebug_impl(PyObject *module, int flag)
1306/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001310 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001311}
1312#endif /* USE_MALLOPT */
1313
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001314size_t
1315_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001316{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001317 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001319 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001320
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001321 /* Make sure the type is initialized. float gets initialized late */
1322 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001323 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001324
Benjamin Petersonce798522012-01-22 11:24:29 -05001325 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 if (method == NULL) {
1327 if (!PyErr_Occurred())
1328 PyErr_Format(PyExc_TypeError,
1329 "Type %.100s doesn't define __sizeof__",
1330 Py_TYPE(o)->tp_name);
1331 }
1332 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001333 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 Py_DECREF(method);
1335 }
1336
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001337 if (res == NULL)
1338 return (size_t)-1;
1339
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001340 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001341 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001342 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001343 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001345 if (size < 0) {
1346 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1347 return (size_t)-1;
1348 }
1349
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001350 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001351 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001352 return ((size_t)size) + sizeof(PyGC_Head);
1353 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001354}
1355
1356static PyObject *
1357sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1358{
1359 static char *kwlist[] = {"object", "default", 0};
1360 size_t size;
1361 PyObject *o, *dflt = NULL;
1362
1363 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1364 kwlist, &o, &dflt))
1365 return NULL;
1366
1367 size = _PySys_GetSizeOf(o);
1368
1369 if (size == (size_t)-1 && PyErr_Occurred()) {
1370 /* Has a default value been given */
1371 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1372 PyErr_Clear();
1373 Py_INCREF(dflt);
1374 return dflt;
1375 }
1376 else
1377 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001379
1380 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001381}
1382
1383PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001384"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001385\n\
1386Return the size of object in bytes.");
1387
Tal Einatede0b6f2018-12-31 17:12:08 +02001388/*[clinic input]
1389sys.getrefcount -> Py_ssize_t
1390
1391 object: object
1392 /
1393
1394Return the reference count of object.
1395
1396The count returned is generally one higher than you might expect,
1397because it includes the (temporary) reference as an argument to
1398getrefcount().
1399[clinic start generated code]*/
1400
1401static Py_ssize_t
1402sys_getrefcount_impl(PyObject *module, PyObject *object)
1403/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001404{
Tal Einatede0b6f2018-12-31 17:12:08 +02001405 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001406}
1407
Tim Peters4be93d02002-07-07 19:59:50 +00001408#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001409/*[clinic input]
1410sys.gettotalrefcount -> Py_ssize_t
1411[clinic start generated code]*/
1412
1413static Py_ssize_t
1414sys_gettotalrefcount_impl(PyObject *module)
1415/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001416{
Tal Einatede0b6f2018-12-31 17:12:08 +02001417 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001418}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001419#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001420
Tal Einatede0b6f2018-12-31 17:12:08 +02001421/*[clinic input]
1422sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001423
Tal Einatede0b6f2018-12-31 17:12:08 +02001424Return the number of memory blocks currently allocated.
1425[clinic start generated code]*/
1426
1427static Py_ssize_t
1428sys_getallocatedblocks_impl(PyObject *module)
1429/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001430{
Tal Einatede0b6f2018-12-31 17:12:08 +02001431 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001432}
1433
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001434#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001435/*[clinic input]
1436sys.getcounts
1437[clinic start generated code]*/
1438
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001439static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001440sys_getcounts_impl(PyObject *module)
1441/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001442{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001443 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001444
Pablo Galindo49c75a82018-10-28 15:02:17 +00001445 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001446}
1447#endif
1448
Tal Einatede0b6f2018-12-31 17:12:08 +02001449/*[clinic input]
1450sys._getframe
1451
1452 depth: int = 0
1453 /
1454
1455Return a frame object from the call stack.
1456
1457If optional integer depth is given, return the frame object that many
1458calls below the top of the stack. If that is deeper than the call
1459stack, ValueError is raised. The default for depth is zero, returning
1460the frame at the top of the call stack.
1461
1462This function should be used for internal and specialized purposes
1463only.
1464[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001465
1466static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001467sys__getframe_impl(PyObject *module, int depth)
1468/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001469{
Victor Stinner50b48572018-11-01 01:51:40 +01001470 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001471
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 while (depth > 0 && f != NULL) {
1473 f = f->f_back;
1474 --depth;
1475 }
1476 if (f == NULL) {
1477 PyErr_SetString(PyExc_ValueError,
1478 "call stack is not deep enough");
1479 return NULL;
1480 }
1481 Py_INCREF(f);
1482 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001483}
1484
Tal Einatede0b6f2018-12-31 17:12:08 +02001485/*[clinic input]
1486sys._current_frames
1487
1488Return a dict mapping each thread's thread id to its current stack frame.
1489
1490This function should be used for specialized purposes only.
1491[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001492
1493static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001494sys__current_frames_impl(PyObject *module)
1495/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001497 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001498}
1499
Tal Einatede0b6f2018-12-31 17:12:08 +02001500/*[clinic input]
1501sys.call_tracing
1502
1503 func: object
1504 args as funcargs: object(subclass_of='&PyTuple_Type')
1505 /
1506
1507Call func(*args), while tracing is enabled.
1508
1509The tracing state is saved, and restored afterwards. This is intended
1510to be called from a debugger from a checkpoint, to recursively debug
1511some other code.
1512[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001513
1514static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001515sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1516/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001517{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001518 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001519}
1520
Tal Einatede0b6f2018-12-31 17:12:08 +02001521/*[clinic input]
1522sys.callstats
1523
1524Return a tuple of function call statistics.
1525
1526A tuple is returned only if CALL_PROFILE was defined when Python was
1527built. Otherwise, this returns None.
1528
1529When enabled, this function returns detailed, implementation-specific
1530details about the number of function calls executed. The return value
1531is a 11-tuple where the entries in the tuple are counts of:
15320. all function calls
15331. calls to PyFunction_Type objects
15342. PyFunction calls that do not create an argument tuple
15353. PyFunction calls that do not create an argument tuple
1536 and bypass PyEval_EvalCodeEx()
15374. PyMethod calls
15385. PyMethod calls on bound methods
15396. PyType calls
15407. PyCFunction calls
15418. generator calls
15429. All other calls
154310. Number of stack pops performed by call_function()
1544[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001545
Victor Stinner048afd92016-11-28 11:59:04 +01001546static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001547sys_callstats_impl(PyObject *module)
1548/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001549{
1550 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1551 "sys.callstats() has been deprecated in Python 3.7 "
1552 "and will be removed in the future", 1) < 0) {
1553 return NULL;
1554 }
1555
1556 Py_RETURN_NONE;
1557}
1558
1559
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001560#ifdef __cplusplus
1561extern "C" {
1562#endif
1563
Tal Einatede0b6f2018-12-31 17:12:08 +02001564/*[clinic input]
1565sys._debugmallocstats
1566
1567Print summary info to stderr about the state of pymalloc's structures.
1568
1569In Py_DEBUG mode, also perform some expensive internal consistency
1570checks.
1571[clinic start generated code]*/
1572
David Malcolm49526f42012-06-22 14:55:41 -04001573static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001574sys__debugmallocstats_impl(PyObject *module)
1575/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001576{
1577#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001578 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001579 fputc('\n', stderr);
1580 }
David Malcolm49526f42012-06-22 14:55:41 -04001581#endif
1582 _PyObject_DebugTypeStats(stderr);
1583
1584 Py_RETURN_NONE;
1585}
David Malcolm49526f42012-06-22 14:55:41 -04001586
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001587#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001588/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001589extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001590#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001591
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001592#ifdef DYNAMIC_EXECUTION_PROFILE
1593/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001594extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001595#endif
1596
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001597#ifdef __cplusplus
1598}
1599#endif
1600
Tal Einatede0b6f2018-12-31 17:12:08 +02001601
1602/*[clinic input]
1603sys._clear_type_cache
1604
1605Clear the internal type lookup cache.
1606[clinic start generated code]*/
1607
Christian Heimes15ebc882008-02-04 18:48:49 +00001608static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001609sys__clear_type_cache_impl(PyObject *module)
1610/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyType_ClearCache();
1613 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001614}
1615
Tal Einatede0b6f2018-12-31 17:12:08 +02001616/*[clinic input]
1617sys.is_finalizing
1618
1619Return True if Python is exiting.
1620[clinic start generated code]*/
1621
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001622static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001623sys_is_finalizing_impl(PyObject *module)
1624/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001625{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001626 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001627}
1628
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001629#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001630/*[clinic input]
1631sys.getandroidapilevel
1632
1633Return the build time API version of Android as an integer.
1634[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001635
1636static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001637sys_getandroidapilevel_impl(PyObject *module)
1638/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001639{
1640 return PyLong_FromLong(ANDROID_API_LEVEL);
1641}
1642#endif /* ANDROID_API_LEVEL */
1643
1644
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001645static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001646 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001647 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001648 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001649 SYS_CALLSTATS_METHODDEF
1650 SYS__CLEAR_TYPE_CACHE_METHODDEF
1651 SYS__CURRENT_FRAMES_METHODDEF
1652 SYS_DISPLAYHOOK_METHODDEF
1653 SYS_EXC_INFO_METHODDEF
1654 SYS_EXCEPTHOOK_METHODDEF
1655 SYS_EXIT_METHODDEF
1656 SYS_GETDEFAULTENCODING_METHODDEF
1657 SYS_GETDLOPENFLAGS_METHODDEF
1658 SYS_GETALLOCATEDBLOCKS_METHODDEF
1659 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001660#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001662#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001663 SYS_GETFILESYSTEMENCODING_METHODDEF
1664 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001665#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001667#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001668 SYS_GETTOTALREFCOUNT_METHODDEF
1669 SYS_GETREFCOUNT_METHODDEF
1670 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001671 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001673 SYS__GETFRAME_METHODDEF
1674 SYS_GETWINDOWSVERSION_METHODDEF
1675 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1676 SYS_INTERN_METHODDEF
1677 SYS_IS_FINALIZING_METHODDEF
1678 SYS_MDEBUG_METHODDEF
1679 SYS_SETCHECKINTERVAL_METHODDEF
1680 SYS_GETCHECKINTERVAL_METHODDEF
1681 SYS_SETSWITCHINTERVAL_METHODDEF
1682 SYS_GETSWITCHINTERVAL_METHODDEF
1683 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001685 SYS_GETPROFILE_METHODDEF
1686 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001688 SYS_GETTRACE_METHODDEF
1689 SYS_CALL_TRACING_METHODDEF
1690 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001691 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1692 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001693 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1694 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001695 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001696 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001697 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1698 SYS_GETANDROIDAPILEVEL_METHODDEF
Victor Stinneref9d9b62019-05-22 11:28:22 +02001699 SYS_UNRAISABLEHOOK_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001701};
1702
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001703static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001704list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001705{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 PyObject *list = PyList_New(0);
1707 int i;
1708 if (list == NULL)
1709 return NULL;
1710 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1711 PyObject *name = PyUnicode_FromString(
1712 PyImport_Inittab[i].name);
1713 if (name == NULL)
1714 break;
1715 PyList_Append(list, name);
1716 Py_DECREF(name);
1717 }
1718 if (PyList_Sort(list) != 0) {
1719 Py_DECREF(list);
1720 list = NULL;
1721 }
1722 if (list) {
1723 PyObject *v = PyList_AsTuple(list);
1724 Py_DECREF(list);
1725 list = v;
1726 }
1727 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001728}
1729
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001730/* Pre-initialization support for sys.warnoptions and sys._xoptions
1731 *
1732 * Modern internal code paths:
1733 * These APIs get called after _Py_InitializeCore and get to use the
1734 * regular CPython list, dict, and unicode APIs.
1735 *
1736 * Legacy embedding code paths:
1737 * The multi-phase initialization API isn't public yet, so embedding
1738 * apps still need to be able configure sys.warnoptions and sys._xoptions
1739 * before they call Py_Initialize. To support this, we stash copies of
1740 * the supplied wchar * sequences in linked lists, and then migrate the
1741 * contents of those lists to the sys module in _PyInitializeCore.
1742 *
1743 */
1744
1745struct _preinit_entry {
1746 wchar_t *value;
1747 struct _preinit_entry *next;
1748};
1749
1750typedef struct _preinit_entry *_Py_PreInitEntry;
1751
1752static _Py_PreInitEntry _preinit_warnoptions = NULL;
1753static _Py_PreInitEntry _preinit_xoptions = NULL;
1754
1755static _Py_PreInitEntry
1756_alloc_preinit_entry(const wchar_t *value)
1757{
1758 /* To get this to work, we have to initialize the runtime implicitly */
1759 _PyRuntime_Initialize();
1760
1761 /* Force default allocator, so we can ensure that it also gets used to
1762 * destroy the linked list in _clear_preinit_entries.
1763 */
1764 PyMemAllocatorEx old_alloc;
1765 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1766
1767 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1768 if (node != NULL) {
1769 node->value = _PyMem_RawWcsdup(value);
1770 if (node->value == NULL) {
1771 PyMem_RawFree(node);
1772 node = NULL;
1773 };
1774 };
1775
1776 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1777 return node;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001778}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001779
1780static int
1781_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1782{
1783 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1784 if (new_entry == NULL) {
1785 return -1;
1786 }
1787 /* We maintain the linked list in this order so it's easy to play back
1788 * the add commands in the same order later on in _Py_InitializeCore
1789 */
1790 _Py_PreInitEntry last_entry = *optionlist;
1791 if (last_entry == NULL) {
1792 *optionlist = new_entry;
1793 } else {
1794 while (last_entry->next != NULL) {
1795 last_entry = last_entry->next;
1796 }
1797 last_entry->next = new_entry;
1798 }
1799 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001800}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001801
1802static void
1803_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1804{
1805 _Py_PreInitEntry current = *optionlist;
1806 *optionlist = NULL;
1807 /* Deallocate the nodes and their contents using the default allocator */
1808 PyMemAllocatorEx old_alloc;
1809 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1810 while (current != NULL) {
1811 _Py_PreInitEntry next = current->next;
1812 PyMem_RawFree(current->value);
1813 PyMem_RawFree(current);
1814 current = next;
1815 }
1816 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001817}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001818
1819static void
1820_clear_all_preinit_options(void)
1821{
1822 _clear_preinit_entries(&_preinit_warnoptions);
1823 _clear_preinit_entries(&_preinit_xoptions);
1824}
1825
1826static int
1827_PySys_ReadPreInitOptions(void)
1828{
1829 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001830 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001831 if (tstate == NULL) {
1832 /* Still don't have a thread state, so something is wrong! */
1833 return -1;
1834 }
1835 _Py_PreInitEntry entry = _preinit_warnoptions;
1836 while (entry != NULL) {
1837 PySys_AddWarnOption(entry->value);
1838 entry = entry->next;
1839 }
1840 entry = _preinit_xoptions;
1841 while (entry != NULL) {
1842 PySys_AddXOption(entry->value);
1843 entry = entry->next;
1844 }
1845
1846 _clear_all_preinit_options();
1847 return 0;
Zackery Spytz1a2252e2019-05-06 10:56:51 -06001848}
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001849
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001850static PyObject *
1851get_warnoptions(void)
1852{
Eric Snowdae02762017-09-14 00:35:58 -07001853 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001854 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001855 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1856 * interpreter config. When that happens, we need to properly set
1857 * the `warnoptions` reference in the main interpreter config as well.
1858 *
1859 * For Python 3.7, we shouldn't be able to get here due to the
1860 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1861 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1862 * call optional for embedding applications, thus making this
1863 * reachable again.
1864 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001865 warnoptions = PyList_New(0);
1866 if (warnoptions == NULL)
1867 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001868 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1869 Py_DECREF(warnoptions);
1870 return NULL;
1871 }
1872 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001873 }
1874 return warnoptions;
1875}
Guido van Rossum23fff912000-12-15 22:02:05 +00001876
1877void
1878PySys_ResetWarnOptions(void)
1879{
Victor Stinner50b48572018-11-01 01:51:40 +01001880 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001881 if (tstate == NULL) {
1882 _clear_preinit_entries(&_preinit_warnoptions);
1883 return;
1884 }
1885
Eric Snowdae02762017-09-14 00:35:58 -07001886 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 if (warnoptions == NULL || !PyList_Check(warnoptions))
1888 return;
1889 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001890}
1891
Victor Stinnere1b29952018-10-30 14:31:42 +01001892static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001893_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001894{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001895 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896 if (warnoptions == NULL) {
1897 return -1;
1898 }
1899 if (PyList_Append(warnoptions, option)) {
1900 return -1;
1901 }
1902 return 0;
1903}
1904
1905void
1906PySys_AddWarnOptionUnicode(PyObject *option)
1907{
Victor Stinnere1b29952018-10-30 14:31:42 +01001908 if (_PySys_AddWarnOptionWithError(option) < 0) {
1909 /* No return value, therefore clear error state if possible */
1910 if (_PyThreadState_UncheckedGet()) {
1911 PyErr_Clear();
1912 }
1913 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001914}
1915
1916void
1917PySys_AddWarnOption(const wchar_t *s)
1918{
Victor Stinner50b48572018-11-01 01:51:40 +01001919 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001920 if (tstate == NULL) {
1921 _append_preinit_entry(&_preinit_warnoptions, s);
1922 return;
1923 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001924 PyObject *unicode;
1925 unicode = PyUnicode_FromWideChar(s, -1);
1926 if (unicode == NULL)
1927 return;
1928 PySys_AddWarnOptionUnicode(unicode);
1929 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001930}
1931
Christian Heimes33fe8092008-04-13 13:53:33 +00001932int
1933PySys_HasWarnOptions(void)
1934{
Eric Snowdae02762017-09-14 00:35:58 -07001935 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001936 return (warnoptions != NULL && PyList_Check(warnoptions)
1937 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001938}
1939
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001940static PyObject *
1941get_xoptions(void)
1942{
Eric Snowdae02762017-09-14 00:35:58 -07001943 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001944 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001945 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1946 * interpreter config. When that happens, we need to properly set
1947 * the `xoptions` reference in the main interpreter config as well.
1948 *
1949 * For Python 3.7, we shouldn't be able to get here due to the
1950 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1951 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1952 * call optional for embedding applications, thus making this
1953 * reachable again.
1954 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001955 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001956 if (xoptions == NULL)
1957 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001958 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1959 Py_DECREF(xoptions);
1960 return NULL;
1961 }
1962 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001963 }
1964 return xoptions;
1965}
1966
Victor Stinnere1b29952018-10-30 14:31:42 +01001967static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001968_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001969{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001970 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001971
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001972 PyObject *opts = get_xoptions();
1973 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001974 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001975 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001976
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001977 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001978 if (!name_end) {
1979 name = PyUnicode_FromWideChar(s, -1);
1980 value = Py_True;
1981 Py_INCREF(value);
1982 }
1983 else {
1984 name = PyUnicode_FromWideChar(s, name_end - s);
1985 value = PyUnicode_FromWideChar(name_end + 1, -1);
1986 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001987 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001988 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001989 }
1990 if (PyDict_SetItem(opts, name, value) < 0) {
1991 goto error;
1992 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001993 Py_DECREF(name);
1994 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001995 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001996
1997error:
1998 Py_XDECREF(name);
1999 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002000 return -1;
2001}
2002
2003void
2004PySys_AddXOption(const wchar_t *s)
2005{
Victor Stinner50b48572018-11-01 01:51:40 +01002006 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002007 if (tstate == NULL) {
2008 _append_preinit_entry(&_preinit_xoptions, s);
2009 return;
2010 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002011 if (_PySys_AddXOptionWithError(s) < 0) {
2012 /* No return value, therefore clear error state if possible */
2013 if (_PyThreadState_UncheckedGet()) {
2014 PyErr_Clear();
2015 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002016 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002017}
2018
2019PyObject *
2020PySys_GetXOptions(void)
2021{
2022 return get_xoptions();
2023}
2024
Guido van Rossum40552d01998-08-06 03:34:39 +00002025/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2026 Two literals concatenated works just fine. If you have a K&R compiler
2027 or other abomination that however *does* understand longer strings,
2028 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002029PyDoc_VAR(sys_doc) =
2030PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002031"This module provides access to some objects used or maintained by the\n\
2032interpreter and to functions that interact strongly with the interpreter.\n\
2033\n\
2034Dynamic objects:\n\
2035\n\
2036argv -- command line arguments; argv[0] is the script pathname if known\n\
2037path -- module search path; path[0] is the script directory, else ''\n\
2038modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002039\n\
2040displayhook -- called to show results in an interactive session\n\
2041excepthook -- called to handle any uncaught exception other than SystemExit\n\
2042 To customize printing in an interactive session or to install a custom\n\
2043 top-level exception handler, assign other functions to replace these.\n\
2044\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002045stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002046stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002047stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002048 By assigning other file objects (or objects that behave like files)\n\
2049 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002050\n\
2051last_type -- type of last uncaught exception\n\
2052last_value -- value of last uncaught exception\n\
2053last_traceback -- traceback of last uncaught exception\n\
2054 These three are only available in an interactive session after a\n\
2055 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002056"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002057)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002058/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002059PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002060"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002061Static objects:\n\
2062\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002063builtin_module_names -- tuple of module names built into this interpreter\n\
2064copyright -- copyright notice pertaining to this interpreter\n\
2065exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002066executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002067float_info -- a struct sequence with information about the float implementation.\n\
2068float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002069hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002070hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002071implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002072int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002073maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002074maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002075platform -- platform identifier\n\
2076prefix -- prefix used to find the Python library\n\
2077thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002078version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002079version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002080"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002081)
Steve Dowercc16be82016-09-08 10:35:16 -07002082#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002083/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002084PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002085"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002086winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002087"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002088)
Steve Dowercc16be82016-09-08 10:35:16 -07002089#endif /* MS_COREDLL */
2090#ifdef MS_WINDOWS
2091/* concatenating string here */
2092PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002093"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002094"
2095)
2096#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002097PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002098"__stdin__ -- the original stdin; don't touch!\n\
2099__stdout__ -- the original stdout; don't touch!\n\
2100__stderr__ -- the original stderr; don't touch!\n\
2101__displayhook__ -- the original displayhook; don't touch!\n\
2102__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002103\n\
2104Functions:\n\
2105\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002106displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002107excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002108exc_info() -- return thread-safe information about the current exception\n\
2109exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002110getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002111getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002112getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002113getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002114getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002115gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002116setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002117setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002118setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002119setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002120settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002121"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002122)
Fred Drakeccede592000-08-14 20:59:57 +00002123/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002124
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002125
2126PyDoc_STRVAR(flags__doc__,
2127"sys.flags\n\
2128\n\
2129Flags provided through command line arguments or environment vars.");
2130
2131static PyTypeObject FlagsType;
2132
2133static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002135 {"inspect", "-i"},
2136 {"interactive", "-i"},
2137 {"optimize", "-O or -OO"},
2138 {"dont_write_bytecode", "-B"},
2139 {"no_user_site", "-s"},
2140 {"no_site", "-S"},
2141 {"ignore_environment", "-E"},
2142 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002143 /* {"unbuffered", "-u"}, */
2144 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002145 {"bytes_warning", "-b"},
2146 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002147 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002148 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002149 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002150 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002151 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002152};
2153
2154static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 "sys.flags", /* name */
2156 flags__doc__, /* doc */
2157 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002158 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002159};
2160
2161static PyObject*
Victor Stinner43125222019-04-24 18:23:53 +02002162make_flags(_PyRuntimeState *runtime, PyInterpreterState *interp)
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 int pos = 0;
2165 PyObject *seq;
Victor Stinner43125222019-04-24 18:23:53 +02002166 const _PyPreConfig *preconfig = &runtime->preconfig;
2167 const _PyCoreConfig *config = &interp->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002168
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 seq = PyStructSequence_New(&FlagsType);
2170 if (seq == NULL)
2171 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002172
2173#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002174 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002175
Victor Stinnerfbca9082018-08-30 00:50:45 +02002176 SetFlag(config->parser_debug);
2177 SetFlag(config->inspect);
2178 SetFlag(config->interactive);
2179 SetFlag(config->optimization_level);
2180 SetFlag(!config->write_bytecode);
2181 SetFlag(!config->user_site_directory);
2182 SetFlag(!config->site_import);
Victor Stinner20004952019-03-26 02:31:11 +01002183 SetFlag(!config->use_environment);
Victor Stinnerfbca9082018-08-30 00:50:45 +02002184 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 /* SetFlag(saw_unbuffered_flag); */
2186 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002187 SetFlag(config->bytes_warning);
2188 SetFlag(config->quiet);
2189 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
Victor Stinner20004952019-03-26 02:31:11 +01002190 SetFlag(config->isolated);
2191 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2192 SetFlag(preconfig->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002193#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002196 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 return NULL;
2198 }
2199 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002200}
2201
Eric Smith0e5b5622009-02-06 01:32:42 +00002202PyDoc_STRVAR(version_info__doc__,
2203"sys.version_info\n\
2204\n\
2205Version information as a named tuple.");
2206
2207static PyTypeObject VersionInfoType;
2208
2209static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002210 {"major", "Major release number"},
2211 {"minor", "Minor release number"},
2212 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002213 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002214 {"serial", "Serial release number"},
2215 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002216};
2217
2218static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002219 "sys.version_info", /* name */
2220 version_info__doc__, /* doc */
2221 version_info_fields, /* fields */
2222 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002223};
2224
2225static PyObject *
2226make_version_info(void)
2227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 PyObject *version_info;
2229 char *s;
2230 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002231
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 version_info = PyStructSequence_New(&VersionInfoType);
2233 if (version_info == NULL) {
2234 return NULL;
2235 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002237 /*
2238 * These release level checks are mutually exclusive and cover
2239 * the field, so don't get too fancy with the pre-processor!
2240 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002241#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002243#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002245#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002247#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002248 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002249#endif
2250
2251#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002253#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002255
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002256 SetIntItem(PY_MAJOR_VERSION);
2257 SetIntItem(PY_MINOR_VERSION);
2258 SetIntItem(PY_MICRO_VERSION);
2259 SetStrItem(s);
2260 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002261#undef SetIntItem
2262#undef SetStrItem
2263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002264 if (PyErr_Occurred()) {
2265 Py_CLEAR(version_info);
2266 return NULL;
2267 }
2268 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002269}
2270
Brett Cannon3adc7b72012-07-09 14:22:12 -04002271/* sys.implementation values */
2272#define NAME "cpython"
2273const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002274#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2275#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002276#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002277const char *_PySys_ImplCacheTag = TAG;
2278#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002279#undef MAJOR
2280#undef MINOR
2281#undef TAG
2282
Barry Warsaw409da152012-06-03 16:18:47 -04002283static PyObject *
2284make_impl_info(PyObject *version_info)
2285{
2286 int res;
2287 PyObject *impl_info, *value, *ns;
2288
2289 impl_info = PyDict_New();
2290 if (impl_info == NULL)
2291 return NULL;
2292
2293 /* populate the dict */
2294
Brett Cannon3adc7b72012-07-09 14:22:12 -04002295 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002296 if (value == NULL)
2297 goto error;
2298 res = PyDict_SetItemString(impl_info, "name", value);
2299 Py_DECREF(value);
2300 if (res < 0)
2301 goto error;
2302
Brett Cannon3adc7b72012-07-09 14:22:12 -04002303 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002304 if (value == NULL)
2305 goto error;
2306 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2307 Py_DECREF(value);
2308 if (res < 0)
2309 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002310
2311 res = PyDict_SetItemString(impl_info, "version", version_info);
2312 if (res < 0)
2313 goto error;
2314
2315 value = PyLong_FromLong(PY_VERSION_HEX);
2316 if (value == NULL)
2317 goto error;
2318 res = PyDict_SetItemString(impl_info, "hexversion", value);
2319 Py_DECREF(value);
2320 if (res < 0)
2321 goto error;
2322
doko@ubuntu.com55532312016-06-14 08:55:19 +02002323#ifdef MULTIARCH
2324 value = PyUnicode_FromString(MULTIARCH);
2325 if (value == NULL)
2326 goto error;
2327 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2328 Py_DECREF(value);
2329 if (res < 0)
2330 goto error;
2331#endif
2332
Barry Warsaw409da152012-06-03 16:18:47 -04002333 /* dict ready */
2334
2335 ns = _PyNamespace_New(impl_info);
2336 Py_DECREF(impl_info);
2337 return ns;
2338
2339error:
2340 Py_CLEAR(impl_info);
2341 return NULL;
2342}
2343
Martin v. Löwis1a214512008-06-11 05:26:20 +00002344static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002345 PyModuleDef_HEAD_INIT,
2346 "sys",
2347 sys_doc,
2348 -1, /* multiple "initialization" just copies the module dict. */
2349 sys_methods,
2350 NULL,
2351 NULL,
2352 NULL,
2353 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002354};
2355
Eric Snow6b4be192017-05-22 21:36:03 -07002356/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002357#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002358 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002359 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002360 if (v == NULL) { \
2361 goto err_occurred; \
2362 } \
Victor Stinner58049602013-07-22 22:40:00 +02002363 res = PyDict_SetItemString(sysdict, key, v); \
2364 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002365 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002366 } \
2367 } while (0)
2368#define SET_SYS_FROM_STRING(key, value) \
2369 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002370 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002371 if (v == NULL) { \
2372 goto err_occurred; \
2373 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002374 res = PyDict_SetItemString(sysdict, key, v); \
2375 Py_DECREF(v); \
2376 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002377 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002378 } \
2379 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002380
Victor Stinnerab672812019-01-23 15:04:40 +01002381static _PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02002382_PySys_InitCore(_PyRuntimeState *runtime, PyInterpreterState *interp,
2383 PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002384{
Victor Stinnerab672812019-01-23 15:04:40 +01002385 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002386 int res;
2387
Nick Coghland6009512014-11-20 21:39:37 +10002388 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002389
Victor Stinner8fea2522013-10-27 17:15:42 +01002390 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2391 PyDict_GetItemString(sysdict, "displayhook"));
2392 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2393 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002394 SET_SYS_FROM_STRING_BORROW(
2395 "__breakpointhook__",
2396 PyDict_GetItemString(sysdict, "breakpointhook"));
Victor Stinneref9d9b62019-05-22 11:28:22 +02002397 SET_SYS_FROM_STRING_BORROW("__unraisablehook__",
2398 PyDict_GetItemString(sysdict, "unraisablehook"));
2399
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 SET_SYS_FROM_STRING("version",
2401 PyUnicode_FromString(Py_GetVersion()));
2402 SET_SYS_FROM_STRING("hexversion",
2403 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002404 SET_SYS_FROM_STRING("_git",
2405 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2406 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002407 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002408 SET_SYS_FROM_STRING("api_version",
2409 PyLong_FromLong(PYTHON_API_VERSION));
2410 SET_SYS_FROM_STRING("copyright",
2411 PyUnicode_FromString(Py_GetCopyright()));
2412 SET_SYS_FROM_STRING("platform",
2413 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 SET_SYS_FROM_STRING("maxsize",
2415 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2416 SET_SYS_FROM_STRING("float_info",
2417 PyFloat_GetInfo());
2418 SET_SYS_FROM_STRING("int_info",
2419 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002420 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002421 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002422 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2423 goto type_init_failed;
2424 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002425 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002426 SET_SYS_FROM_STRING("hash_info",
2427 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002428 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002429 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 SET_SYS_FROM_STRING("builtin_module_names",
2431 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002432#if PY_BIG_ENDIAN
2433 SET_SYS_FROM_STRING("byteorder",
2434 PyUnicode_FromString("big"));
2435#else
2436 SET_SYS_FROM_STRING("byteorder",
2437 PyUnicode_FromString("little"));
2438#endif
Fred Drake099325e2000-08-14 15:47:03 +00002439
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002440#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002441 SET_SYS_FROM_STRING("dllhandle",
2442 PyLong_FromVoidPtr(PyWin_DLLhModule));
2443 SET_SYS_FROM_STRING("winver",
2444 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002445#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002446#ifdef ABIFLAGS
2447 SET_SYS_FROM_STRING("abiflags",
2448 PyUnicode_FromString(ABIFLAGS));
2449#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002450
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002451 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002452 if (VersionInfoType.tp_name == NULL) {
2453 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002454 &version_info_desc) < 0) {
2455 goto type_init_failed;
2456 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002457 }
Barry Warsaw409da152012-06-03 16:18:47 -04002458 version_info = make_version_info();
2459 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002460 /* prevent user from creating new instances */
2461 VersionInfoType.tp_init = NULL;
2462 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002463 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2464 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2465 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002466
Barry Warsaw409da152012-06-03 16:18:47 -04002467 /* implementation */
2468 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2469
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002470 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002471 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002472 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2473 goto type_init_failed;
2474 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002475 }
Victor Stinner43125222019-04-24 18:23:53 +02002476 /* Set flags to their default values (updated by _PySys_InitMain()) */
2477 SET_SYS_FROM_STRING("flags", make_flags(runtime, interp));
Eric Smithf7bb5782010-01-27 00:44:57 +00002478
2479#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002480 /* getwindowsversion */
2481 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002482 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002483 &windows_version_desc) < 0) {
2484 goto type_init_failed;
2485 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002486 /* prevent user from creating new instances */
2487 WindowsVersionType.tp_init = NULL;
2488 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002489 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002490 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002491 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002492 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002493 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002494#endif
2495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002497#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002498 SET_SYS_FROM_STRING("float_repr_style",
2499 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002500#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002501 SET_SYS_FROM_STRING("float_repr_style",
2502 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002503#endif
2504
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002505 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002506
Yury Selivanoveb636452016-09-08 22:01:51 -07002507 /* initialize asyncgen_hooks */
2508 if (AsyncGenHooksType.tp_name == NULL) {
2509 if (PyStructSequence_InitType2(
2510 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002511 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002512 }
2513 }
2514
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002515 if (PyErr_Occurred()) {
2516 goto err_occurred;
2517 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002518 return _Py_INIT_OK();
2519
2520type_init_failed:
2521 return _Py_INIT_ERR("failed to initialize a type");
2522
2523err_occurred:
2524 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002525}
2526
Eric Snow6b4be192017-05-22 21:36:03 -07002527#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002528
2529/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002530#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2531 do { \
2532 PyObject *v = (value); \
2533 if (v == NULL) \
2534 return -1; \
2535 res = PyDict_SetItemString(sysdict, key, v); \
2536 Py_DECREF(v); \
2537 if (res < 0) { \
2538 return res; \
2539 } \
2540 } while (0)
2541
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002542
2543static int
2544sys_add_xoption(PyObject *opts, const wchar_t *s)
2545{
2546 PyObject *name, *value;
2547
2548 const wchar_t *name_end = wcschr(s, L'=');
2549 if (!name_end) {
2550 name = PyUnicode_FromWideChar(s, -1);
2551 value = Py_True;
2552 Py_INCREF(value);
2553 }
2554 else {
2555 name = PyUnicode_FromWideChar(s, name_end - s);
2556 value = PyUnicode_FromWideChar(name_end + 1, -1);
2557 }
2558 if (name == NULL || value == NULL) {
2559 goto error;
2560 }
2561 if (PyDict_SetItem(opts, name, value) < 0) {
2562 goto error;
2563 }
2564 Py_DECREF(name);
2565 Py_DECREF(value);
2566 return 0;
2567
2568error:
2569 Py_XDECREF(name);
2570 Py_XDECREF(value);
2571 return -1;
2572}
2573
2574
2575static PyObject*
2576sys_create_xoptions_dict(const _PyCoreConfig *config)
2577{
2578 Py_ssize_t nxoption = config->xoptions.length;
2579 wchar_t * const * xoptions = config->xoptions.items;
2580 PyObject *dict = PyDict_New();
2581 if (dict == NULL) {
2582 return NULL;
2583 }
2584
2585 for (Py_ssize_t i=0; i < nxoption; i++) {
2586 const wchar_t *option = xoptions[i];
2587 if (sys_add_xoption(dict, option) < 0) {
2588 Py_DECREF(dict);
2589 return NULL;
2590 }
2591 }
2592
2593 return dict;
2594}
2595
2596
Eric Snow6b4be192017-05-22 21:36:03 -07002597int
Victor Stinner43125222019-04-24 18:23:53 +02002598_PySys_InitMain(_PyRuntimeState *runtime, PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002599{
Victor Stinnerab672812019-01-23 15:04:40 +01002600 PyObject *sysdict = interp->sysdict;
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002601 const _PyCoreConfig *config = &interp->core_config;
Eric Snow6b4be192017-05-22 21:36:03 -07002602 int res;
2603
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002604#define COPY_LIST(KEY, VALUE) \
Victor Stinner37cd9822018-11-16 11:55:35 +01002605 do { \
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002606 PyObject *list = _PyWstrList_AsList(&(VALUE)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002607 if (list == NULL) { \
2608 return -1; \
2609 } \
2610 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2611 Py_DECREF(list); \
2612 } while (0)
2613
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002614#define SET_SYS_FROM_WSTR(KEY, VALUE) \
2615 do { \
2616 PyObject *str = PyUnicode_FromWideChar(VALUE, -1); \
2617 if (str == NULL) { \
2618 return -1; \
2619 } \
2620 SET_SYS_FROM_STRING_BORROW(KEY, str); \
2621 Py_DECREF(str); \
2622 } while (0)
Victor Stinner37cd9822018-11-16 11:55:35 +01002623
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002624 COPY_LIST("path", config->module_search_paths);
2625
2626 SET_SYS_FROM_WSTR("executable", config->executable);
2627 SET_SYS_FROM_WSTR("prefix", config->prefix);
2628 SET_SYS_FROM_WSTR("base_prefix", config->base_prefix);
2629 SET_SYS_FROM_WSTR("exec_prefix", config->exec_prefix);
2630 SET_SYS_FROM_WSTR("base_exec_prefix", config->base_exec_prefix);
Victor Stinner41264f12017-12-15 02:05:29 +01002631
Carl Meyerb193fa92018-06-15 22:40:56 -06002632 if (config->pycache_prefix != NULL) {
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002633 SET_SYS_FROM_WSTR("pycache_prefix", config->pycache_prefix);
Carl Meyerb193fa92018-06-15 22:40:56 -06002634 } else {
2635 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2636 }
2637
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002638 COPY_LIST("argv", config->argv);
2639 COPY_LIST("warnoptions", config->warnoptions);
2640
2641 PyObject *xoptions = sys_create_xoptions_dict(config);
2642 if (xoptions == NULL) {
2643 return -1;
Victor Stinner41264f12017-12-15 02:05:29 +01002644 }
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002645 SET_SYS_FROM_STRING_BORROW("_xoptions", xoptions);
Pablo Galindo34ef64f2019-03-27 12:43:47 +00002646 Py_DECREF(xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002647
Victor Stinner37cd9822018-11-16 11:55:35 +01002648#undef COPY_LIST
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002649#undef SET_SYS_FROM_WSTR
Victor Stinner37cd9822018-11-16 11:55:35 +01002650
Eric Snow6b4be192017-05-22 21:36:03 -07002651 /* Set flags to their final values */
Victor Stinner43125222019-04-24 18:23:53 +02002652 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags(runtime, interp));
Eric Snow6b4be192017-05-22 21:36:03 -07002653 /* prevent user from creating new instances */
2654 FlagsType.tp_init = NULL;
2655 FlagsType.tp_new = NULL;
2656 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2657 if (res < 0) {
2658 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2659 return res;
2660 }
2661 PyErr_Clear();
2662 }
2663
2664 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinner8b9dbc02019-03-27 01:36:16 +01002665 PyBool_FromLong(!config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002666
Eric Snowdae02762017-09-14 00:35:58 -07002667 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002668 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002669
Eric Snowdae02762017-09-14 00:35:58 -07002670 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002671 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002672
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002673 /* Transfer any sys.warnoptions and sys._xoptions set directly
2674 * by an embedding application from the linked list to the module. */
2675 if (_PySys_ReadPreInitOptions() != 0)
2676 return -1;
2677
Eric Snow6b4be192017-05-22 21:36:03 -07002678 if (PyErr_Occurred())
2679 return -1;
2680 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002681
2682err_occurred:
2683 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002684}
2685
Victor Stinner41264f12017-12-15 02:05:29 +01002686#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002687#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002688
Victor Stinnerab672812019-01-23 15:04:40 +01002689
2690/* Set up a preliminary stderr printer until we have enough
2691 infrastructure for the io module in place.
2692
2693 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
2694_PyInitError
2695_PySys_SetPreliminaryStderr(PyObject *sysdict)
2696{
2697 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2698 if (pstderr == NULL) {
2699 goto error;
2700 }
2701 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2702 goto error;
2703 }
2704 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2705 goto error;
2706 }
2707 Py_DECREF(pstderr);
2708 return _Py_INIT_OK();
2709
2710error:
2711 Py_XDECREF(pstderr);
2712 return _Py_INIT_ERR("can't set preliminary stderr");
2713}
2714
2715
2716/* Create sys module without all attributes: _PySys_InitMain() should be called
2717 later to add remaining attributes. */
2718_PyInitError
Victor Stinner43125222019-04-24 18:23:53 +02002719_PySys_Create(_PyRuntimeState *runtime, PyInterpreterState *interp,
2720 PyObject **sysmod_p)
Victor Stinnerab672812019-01-23 15:04:40 +01002721{
2722 PyObject *modules = PyDict_New();
2723 if (modules == NULL) {
2724 return _Py_INIT_ERR("can't make modules dictionary");
2725 }
2726 interp->modules = modules;
2727
2728 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2729 if (sysmod == NULL) {
2730 return _Py_INIT_ERR("failed to create a module object");
2731 }
2732
2733 PyObject *sysdict = PyModule_GetDict(sysmod);
2734 if (sysdict == NULL) {
2735 return _Py_INIT_ERR("can't initialize sys dict");
2736 }
2737 Py_INCREF(sysdict);
2738 interp->sysdict = sysdict;
2739
2740 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
2741 return _Py_INIT_ERR("can't initialize sys module");
2742 }
2743
2744 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
2745 if (_Py_INIT_FAILED(err)) {
2746 return err;
2747 }
2748
Victor Stinner43125222019-04-24 18:23:53 +02002749 err = _PySys_InitCore(runtime, interp, sysdict);
Victor Stinnerab672812019-01-23 15:04:40 +01002750 if (_Py_INIT_FAILED(err)) {
2751 return err;
2752 }
2753
2754 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
2755
2756 *sysmod_p = sysmod;
2757 return _Py_INIT_OK();
2758}
2759
2760
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002761static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002762makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002764 int i, n;
2765 const wchar_t *p;
2766 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 n = 1;
2769 p = path;
2770 while ((p = wcschr(p, delim)) != NULL) {
2771 n++;
2772 p++;
2773 }
2774 v = PyList_New(n);
2775 if (v == NULL)
2776 return NULL;
2777 for (i = 0; ; i++) {
2778 p = wcschr(path, delim);
2779 if (p == NULL)
2780 p = path + wcslen(path); /* End of string */
2781 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2782 if (w == NULL) {
2783 Py_DECREF(v);
2784 return NULL;
2785 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002786 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002787 if (*p == '\0')
2788 break;
2789 path = p+1;
2790 }
2791 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002792}
2793
2794void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002795PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002797 PyObject *v;
2798 if ((v = makepathobject(path, DELIM)) == NULL)
2799 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002800 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 Py_FatalError("can't assign sys.path");
2802 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002803}
2804
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002805static PyObject *
Victor Stinner74f65682019-03-15 15:08:05 +01002806make_sys_argv(int argc, wchar_t * const * argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002807{
Victor Stinner74f65682019-03-15 15:08:05 +01002808 PyObject *list = PyList_New(argc);
2809 if (list == NULL) {
2810 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002811 }
Victor Stinner74f65682019-03-15 15:08:05 +01002812
2813 for (Py_ssize_t i = 0; i < argc; i++) {
2814 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
2815 if (v == NULL) {
2816 Py_DECREF(list);
2817 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002818 }
Victor Stinner74f65682019-03-15 15:08:05 +01002819 PyList_SET_ITEM(list, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 }
Victor Stinner74f65682019-03-15 15:08:05 +01002821 return list;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002822}
2823
Victor Stinner11a247d2017-12-13 21:05:57 +01002824void
2825PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002826{
Victor Stinner74f65682019-03-15 15:08:05 +01002827 if (argc < 1 || argv == NULL) {
2828 /* Ensure at least one (empty) argument is seen */
2829 wchar_t* empty_argv[1] = {L""};
2830 argv = empty_argv;
2831 argc = 1;
2832 }
2833
2834 PyObject *av = make_sys_argv(argc, argv);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002835 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002836 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002837 }
2838 if (PySys_SetObject("argv", av) != 0) {
2839 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002840 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002841 }
2842 Py_DECREF(av);
2843
2844 if (updatepath) {
2845 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2846 If argv[0] is a symlink, use the real path. */
Victor Stinner74f65682019-03-15 15:08:05 +01002847 const _PyWstrList argv_list = {.length = argc, .items = argv};
Victor Stinnerdcf61712019-03-19 16:09:27 +01002848 PyObject *path0 = NULL;
2849 if (_PyPathConfig_ComputeSysPath0(&argv_list, &path0)) {
2850 if (path0 == NULL) {
2851 Py_FatalError("can't compute path0 from argv");
Victor Stinner11a247d2017-12-13 21:05:57 +01002852 }
Victor Stinnerdcf61712019-03-19 16:09:27 +01002853
2854 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2855 if (sys_path != NULL) {
2856 if (PyList_Insert(sys_path, 0, path0) < 0) {
2857 Py_DECREF(path0);
2858 Py_FatalError("can't prepend path0 to sys.path");
2859 }
2860 }
2861 Py_DECREF(path0);
Victor Stinner11a247d2017-12-13 21:05:57 +01002862 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002863 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002864}
Guido van Rossuma890e681998-05-12 14:59:24 +00002865
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002866void
2867PySys_SetArgv(int argc, wchar_t **argv)
2868{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002869 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002870}
2871
Victor Stinner14284c22010-04-23 12:02:30 +00002872/* Reimplementation of PyFile_WriteString() no calling indirectly
2873 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2874
2875static int
Victor Stinner79766632010-08-16 17:36:42 +00002876sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002877{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002878 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002879 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002880
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002881 if (file == NULL)
2882 return -1;
2883
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002884 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002885 if (writer == NULL)
2886 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002887
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002888 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 if (result == NULL) {
2890 goto error;
2891 } else {
2892 err = 0;
2893 goto finally;
2894 }
Victor Stinner14284c22010-04-23 12:02:30 +00002895
2896error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002897 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002898finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 Py_XDECREF(result);
2901 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002902}
2903
Victor Stinner79766632010-08-16 17:36:42 +00002904static int
2905sys_pyfile_write(const char *text, PyObject *file)
2906{
2907 PyObject *unicode = NULL;
2908 int err;
2909
2910 if (file == NULL)
2911 return -1;
2912
2913 unicode = PyUnicode_FromString(text);
2914 if (unicode == NULL)
2915 return -1;
2916
2917 err = sys_pyfile_write_unicode(unicode, file);
2918 Py_DECREF(unicode);
2919 return err;
2920}
Guido van Rossuma890e681998-05-12 14:59:24 +00002921
2922/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2923 Adapted from code submitted by Just van Rossum.
2924
2925 PySys_WriteStdout(format, ...)
2926 PySys_WriteStderr(format, ...)
2927
2928 The first function writes to sys.stdout; the second to sys.stderr. When
2929 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002930 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002931
Victor Stinner14284c22010-04-23 12:02:30 +00002932 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002933 signal handlers: they may raise a new exception whereas sys_write()
2934 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002935
Guido van Rossuma890e681998-05-12 14:59:24 +00002936 Both take a printf-style format string as their first argument followed
2937 by a variable length argument list determined by the format string.
2938
2939 *** WARNING ***
2940
2941 The format should limit the total size of the formatted output string to
2942 1000 bytes. In particular, this means that no unrestricted "%s" formats
2943 should occur; these should be limited using "%.<N>s where <N> is a
2944 decimal number calculated so that <N> plus the maximum size of other
2945 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2946 which can print hundreds of digits for very large numbers.
2947
2948 */
2949
2950static void
Victor Stinner09054372013-11-06 22:41:44 +01002951sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002952{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002953 PyObject *file;
2954 PyObject *error_type, *error_value, *error_traceback;
2955 char buffer[1001];
2956 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002958 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002959 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002960 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2961 if (sys_pyfile_write(buffer, file) != 0) {
2962 PyErr_Clear();
2963 fputs(buffer, fp);
2964 }
2965 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2966 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002967 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002968 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002969 }
2970 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002971}
2972
2973void
Guido van Rossuma890e681998-05-12 14:59:24 +00002974PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002975{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002976 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002977
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002978 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002979 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002980 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002981}
2982
2983void
Guido van Rossuma890e681998-05-12 14:59:24 +00002984PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002985{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002986 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002987
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002988 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002989 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002990 va_end(va);
2991}
2992
2993static void
Victor Stinner09054372013-11-06 22:41:44 +01002994sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002995{
2996 PyObject *file, *message;
2997 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002998 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002999
3000 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01003001 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00003002 message = PyUnicode_FromFormatV(format, va);
3003 if (message != NULL) {
3004 if (sys_pyfile_write_unicode(message, file) != 0) {
3005 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02003006 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00003007 if (utf8 != NULL)
3008 fputs(utf8, fp);
3009 }
3010 Py_DECREF(message);
3011 }
3012 PyErr_Restore(error_type, error_value, error_traceback);
3013}
3014
3015void
3016PySys_FormatStdout(const char *format, ...)
3017{
3018 va_list va;
3019
3020 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003021 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00003022 va_end(va);
3023}
3024
3025void
3026PySys_FormatStderr(const char *format, ...)
3027{
3028 va_list va;
3029
3030 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01003031 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00003032 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00003033}