blob: f1cd74ebeccfa1e202a0249ee1b06a0aaec8391e [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010020#include "pycore_pylifecycle.h"
21#include "pycore_pymem.h"
Victor Stinnera1c249c2018-11-01 03:15:58 +010022#include "pycore_pathconfig.h"
Victor Stinner621cebe2018-11-12 16:53:38 +010023#include "pycore_pystate.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020024#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000025
Guido van Rossume2437a11992-03-23 18:20:18 +000026#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020027#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000028
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#ifdef MS_WINDOWS
30#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000031#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000032#endif /* MS_WINDOWS */
33
Guido van Rossum9b38a141996-09-11 23:12:24 +000034#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000035extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000036/* A string loaded from the DLL at startup: */
37extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000038#endif
39
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080040/*[clinic input]
41module sys
42[clinic start generated code]*/
43/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
44
45#include "clinic/sysmodule.c.h"
46
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(_);
48_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070049_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010050_Py_IDENTIFIER(buffer);
51_Py_IDENTIFIER(builtins);
52_Py_IDENTIFIER(encoding);
53_Py_IDENTIFIER(path);
54_Py_IDENTIFIER(stdout);
55_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070056_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010057_Py_IDENTIFIER(write);
58
Guido van Rossum65bf9f21997-04-29 18:33:38 +000059PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010060_PySys_GetObjectId(_Py_Identifier *key)
61{
Victor Stinnercaba55b2018-08-03 15:33:52 +020062 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
63 if (sd == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010064 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020065 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010066 return _PyDict_GetItemId(sd, key);
67}
68
69PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000070PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000071{
Victor Stinnercaba55b2018-08-03 15:33:52 +020072 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
73 if (sd == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +020075 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000076 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000077}
78
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000079int
Victor Stinnerd67bd452013-11-06 22:36:40 +010080_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
81{
Victor Stinnercaba55b2018-08-03 15:33:52 +020082 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Victor Stinnerd67bd452013-11-06 22:36:40 +010083 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +020084 if (_PyDict_GetItemId(sd, key) == NULL) {
Victor Stinnerd67bd452013-11-06 22:36:40 +010085 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +020086 }
87 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010088 return _PyDict_DelItemId(sd, key);
Victor Stinnercaba55b2018-08-03 15:33:52 +020089 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010090 }
Victor Stinnercaba55b2018-08-03 15:33:52 +020091 else {
Victor Stinnerd67bd452013-11-06 22:36:40 +010092 return _PyDict_SetItemId(sd, key, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +020093 }
Victor Stinnerd67bd452013-11-06 22:36:40 +010094}
95
96int
Neal Norwitzf3081322007-08-25 00:32:45 +000097PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098{
Victor Stinnercaba55b2018-08-03 15:33:52 +020099 PyObject *sd = _PyInterpreterState_GET_UNSAFE()->sysdict;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000100 if (v == NULL) {
Victor Stinnercaba55b2018-08-03 15:33:52 +0200101 if (PyDict_GetItemString(sd, name) == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000102 return 0;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200103 }
104 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000105 return PyDict_DelItemString(sd, name);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200106 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000107 }
Victor Stinnercaba55b2018-08-03 15:33:52 +0200108 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000109 return PyDict_SetItemString(sd, name, v);
Victor Stinnercaba55b2018-08-03 15:33:52 +0200110 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000111}
112
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400113static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200114sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400115{
116 assert(!PyErr_Occurred());
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300117 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400118
119 if (envar == NULL || strlen(envar) == 0) {
120 envar = "pdb.set_trace";
121 }
122 else if (!strcmp(envar, "0")) {
123 /* The breakpoint is explicitly no-op'd. */
124 Py_RETURN_NONE;
125 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300126 /* According to POSIX the string returned by getenv() might be invalidated
127 * or the string content might be overwritten by a subsequent call to
128 * getenv(). Since importing a module can performs the getenv() calls,
129 * we need to save a copy of envar. */
130 envar = _PyMem_RawStrdup(envar);
131 if (envar == NULL) {
132 PyErr_NoMemory();
133 return NULL;
134 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200135 const char *last_dot = strrchr(envar, '.');
136 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400137 PyObject *modulepath = NULL;
138
139 if (last_dot == NULL) {
140 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
141 modulepath = PyUnicode_FromString("builtins");
142 attrname = envar;
143 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200144 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400145 /* Split on the last dot; */
146 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
147 attrname = last_dot + 1;
148 }
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200149 else {
150 goto warn;
151 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400152 if (modulepath == NULL) {
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300153 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400154 return NULL;
155 }
156
Anthony Sottiledce345c2018-11-01 10:25:05 -0700157 PyObject *module = PyImport_Import(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400158 Py_DECREF(modulepath);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400159
160 if (module == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200161 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
162 goto warn;
163 }
164 PyMem_RawFree(envar);
165 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400166 }
167
168 PyObject *hook = PyObject_GetAttrString(module, attrname);
169 Py_DECREF(module);
170
171 if (hook == NULL) {
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200172 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
173 goto warn;
174 }
175 PyMem_RawFree(envar);
176 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400177 }
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300178 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400179 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
180 Py_DECREF(hook);
181 return retval;
182
Serhiy Storchaka3607ef42019-01-15 13:26:38 +0200183 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400184 /* If any of the imports went wrong, then warn and ignore. */
185 PyErr_Clear();
186 int status = PyErr_WarnFormat(
187 PyExc_RuntimeWarning, 0,
188 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Serhiy Storchakaf60bf0e2018-07-09 21:46:51 +0300189 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400190 if (status < 0) {
191 /* Printing the warning raised an exception. */
192 return NULL;
193 }
194 /* The warning was (probably) issued. */
195 Py_RETURN_NONE;
196}
197
198PyDoc_STRVAR(breakpointhook_doc,
199"breakpointhook(*args, **kws)\n"
200"\n"
201"This hook function is called by built-in breakpoint().\n"
202);
203
Victor Stinner13d49ee2010-12-04 17:24:33 +0000204/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
205 error handler. If sys.stdout has a buffer attribute, use
206 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
207 sys.stdout.write(redecoded).
208
209 Helper function for sys_displayhook(). */
210static int
211sys_displayhook_unencodable(PyObject *outf, PyObject *o)
212{
213 PyObject *stdout_encoding = NULL;
214 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200215 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000216 int ret;
217
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200218 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000219 if (stdout_encoding == NULL)
220 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200221 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000222 if (stdout_encoding_str == NULL)
223 goto error;
224
225 repr_str = PyObject_Repr(o);
226 if (repr_str == NULL)
227 goto error;
228 encoded = PyUnicode_AsEncodedString(repr_str,
229 stdout_encoding_str,
230 "backslashreplace");
231 Py_DECREF(repr_str);
232 if (encoded == NULL)
233 goto error;
234
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200235 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000236 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100237 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000238 Py_DECREF(buffer);
239 Py_DECREF(encoded);
240 if (result == NULL)
241 goto error;
242 Py_DECREF(result);
243 }
244 else {
245 PyErr_Clear();
246 escaped_str = PyUnicode_FromEncodedObject(encoded,
247 stdout_encoding_str,
248 "strict");
249 Py_DECREF(encoded);
250 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
251 Py_DECREF(escaped_str);
252 goto error;
253 }
254 Py_DECREF(escaped_str);
255 }
256 ret = 0;
257 goto finally;
258
259error:
260 ret = -1;
261finally:
262 Py_XDECREF(stdout_encoding);
263 return ret;
264}
265
Tal Einatede0b6f2018-12-31 17:12:08 +0200266/*[clinic input]
267sys.displayhook
268
269 object as o: object
270 /
271
272Print an object to sys.stdout and also save it in builtins._
273[clinic start generated code]*/
274
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000275static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200276sys_displayhook(PyObject *module, PyObject *o)
277/*[clinic end generated code: output=347477d006df92ed input=08ba730166d7ef72]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000279 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100280 PyObject *builtins;
281 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000282 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000283
Eric Snow3f9eee62017-09-15 16:35:20 -0600284 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000285 if (builtins == NULL) {
286 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
287 return NULL;
288 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600289 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000290
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 /* Print value except if None */
292 /* After printing, also assign to '_' */
293 /* Before, set '_' to None to avoid recursion */
294 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200295 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000296 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200297 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100299 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (outf == NULL || outf == Py_None) {
301 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
302 return NULL;
303 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000304 if (PyFile_WriteObject(o, outf, 0) != 0) {
305 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
306 /* repr(o) is not encodable to sys.stdout.encoding with
307 * sys.stdout.errors error handler (which is probably 'strict') */
308 PyErr_Clear();
309 err = sys_displayhook_unencodable(outf, o);
310 if (err)
311 return NULL;
312 }
313 else {
314 return NULL;
315 }
316 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100317 if (newline == NULL) {
318 newline = PyUnicode_FromString("\n");
319 if (newline == NULL)
320 return NULL;
321 }
322 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200324 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000325 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200326 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000327}
328
Tal Einatede0b6f2018-12-31 17:12:08 +0200329
330/*[clinic input]
331sys.excepthook
332
333 exctype: object
334 value: object
335 traceback: object
336 /
337
338Handle an exception by displaying it with a traceback on sys.stderr.
339[clinic start generated code]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000340
341static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200342sys_excepthook_impl(PyObject *module, PyObject *exctype, PyObject *value,
343 PyObject *traceback)
344/*[clinic end generated code: output=18d99fdda21b6b5e input=ecf606fa826f19d9]*/
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000345{
Tal Einatede0b6f2018-12-31 17:12:08 +0200346 PyErr_Display(exctype, value, traceback);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200347 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000348}
349
Tal Einatede0b6f2018-12-31 17:12:08 +0200350
351/*[clinic input]
352sys.exc_info
353
354Return current exception information: (type, value, traceback).
355
356Return information about the most recent exception caught by an except
357clause in the current stack frame or in an older stack frame.
358[clinic start generated code]*/
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000359
360static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200361sys_exc_info_impl(PyObject *module)
362/*[clinic end generated code: output=3afd0940cf3a4d30 input=b5c5bf077788a3e5]*/
Guido van Rossuma027efa1997-05-05 20:56:21 +0000363{
Victor Stinner50b48572018-11-01 01:51:40 +0100364 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(_PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 return Py_BuildValue(
366 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100367 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
368 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
369 err_info->exc_traceback != NULL ?
370 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000371}
372
Tal Einatede0b6f2018-12-31 17:12:08 +0200373
374/*[clinic input]
375sys.exit
376
377 status: object = NULL
378 /
379
380Exit the interpreter by raising SystemExit(status).
381
382If the status is omitted or None, it defaults to zero (i.e., success).
383If the status is an integer, it will be used as the system exit status.
384If it is another kind of object, it will be printed and the system
385exit status will be one (i.e., failure).
386[clinic start generated code]*/
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000387
388static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200389sys_exit_impl(PyObject *module, PyObject *status)
390/*[clinic end generated code: output=13870986c1ab2ec0 input=a737351f86685e9c]*/
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 /* Raise SystemExit so callers may catch it or clean up. */
Tal Einatede0b6f2018-12-31 17:12:08 +0200393 PyErr_SetObject(PyExc_SystemExit, status);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000395}
396
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000397
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000398
Tal Einatede0b6f2018-12-31 17:12:08 +0200399/*[clinic input]
400sys.getdefaultencoding
401
402Return the current default encoding used by the Unicode implementation.
403[clinic start generated code]*/
404
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000405static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200406sys_getdefaultencoding_impl(PyObject *module)
407/*[clinic end generated code: output=256d19dfcc0711e6 input=d416856ddbef6909]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000408{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000410}
411
Tal Einatede0b6f2018-12-31 17:12:08 +0200412/*[clinic input]
413sys.getfilesystemencoding
414
415Return the encoding used to convert Unicode filenames to OS filenames.
416[clinic start generated code]*/
Fred Drake8b4d01d2000-05-09 19:57:01 +0000417
418static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200419sys_getfilesystemencoding_impl(PyObject *module)
420/*[clinic end generated code: output=1dc4bdbe9be44aa7 input=8475f8649b8c7d8c]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000421{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200422 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
423 const _PyCoreConfig *config = &interp->core_config;
424 return PyUnicode_FromString(config->filesystem_encoding);
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000425}
426
Tal Einatede0b6f2018-12-31 17:12:08 +0200427/*[clinic input]
428sys.getfilesystemencodeerrors
429
430Return the error mode used Unicode to OS filename conversion.
431[clinic start generated code]*/
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000432
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000433static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200434sys_getfilesystemencodeerrors_impl(PyObject *module)
435/*[clinic end generated code: output=ba77b36bbf7c96f5 input=22a1e8365566f1e5]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700436{
Victor Stinnerb2457ef2018-08-29 13:25:36 +0200437 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
438 const _PyCoreConfig *config = &interp->core_config;
439 return PyUnicode_FromString(config->filesystem_errors);
Steve Dowercc16be82016-09-08 10:35:16 -0700440}
441
Tal Einatede0b6f2018-12-31 17:12:08 +0200442/*[clinic input]
443sys.intern
444
445 string as s: unicode
446 /
447
448``Intern'' the given string.
449
450This enters the string in the (global) table of interned strings whose
451purpose is to speed up dictionary lookups. Return the string itself or
452the previously interned string object with the same value.
453[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -0700454
455static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200456sys_intern_impl(PyObject *module, PyObject *s)
457/*[clinic end generated code: output=be680c24f5c9e5d6 input=849483c006924e2f]*/
Georg Brandl66a796e2006-12-19 20:50:34 +0000458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (PyUnicode_CheckExact(s)) {
460 Py_INCREF(s);
461 PyUnicode_InternInPlace(&s);
462 return s;
463 }
464 else {
465 PyErr_Format(PyExc_TypeError,
Tal Einatede0b6f2018-12-31 17:12:08 +0200466 "can't intern %.400s", s->ob_type->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000467 return NULL;
468 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000469}
470
Georg Brandl66a796e2006-12-19 20:50:34 +0000471
Fred Drake5755ce62001-06-27 19:19:46 +0000472/*
473 * Cached interned string objects used for calling the profile and
474 * trace functions. Initialized by trace_init().
475 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000476static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000477
478static int
479trace_init(void)
480{
Nick Coghlan5a851672017-09-08 10:14:16 +1000481 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200482 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000483 "c_call", "c_exception", "c_return",
484 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200485 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000486 PyObject *name;
487 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000488 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 if (whatstrings[i] == NULL) {
490 name = PyUnicode_InternFromString(whatnames[i]);
491 if (name == NULL)
492 return -1;
493 whatstrings[i] = name;
494 }
495 }
496 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000497}
498
499
500static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100501call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200505 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000506
Victor Stinner78da82b2016-08-20 01:22:57 +0200507 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200509 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100510
Victor Stinner78da82b2016-08-20 01:22:57 +0200511 stack[0] = (PyObject *)frame;
512 stack[1] = whatstrings[what];
513 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000514
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200516 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000517
Victor Stinner78da82b2016-08-20 01:22:57 +0200518 PyFrame_LocalsToFast(frame, 1);
519 if (result == NULL) {
520 PyTraceBack_Here(frame);
521 }
522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000523 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000524}
525
526static int
527profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000529{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 if (arg == NULL)
533 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100534 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (result == NULL) {
536 PyEval_SetProfile(NULL, NULL);
537 return -1;
538 }
539 Py_DECREF(result);
540 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000541}
542
543static int
544trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000546{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 PyObject *callback;
548 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000550 if (what == PyTrace_CALL)
551 callback = self;
552 else
553 callback = frame->f_trace;
554 if (callback == NULL)
555 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100556 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (result == NULL) {
558 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200559 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 return -1;
561 }
562 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300563 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 }
565 else {
566 Py_DECREF(result);
567 }
568 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000569}
Fred Draked0838392001-06-16 21:02:31 +0000570
Fred Drake8b4d01d2000-05-09 19:57:01 +0000571static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000572sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000573{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000574 if (trace_init() == -1)
575 return NULL;
576 if (args == Py_None)
577 PyEval_SetTrace(NULL, NULL);
578 else
579 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200580 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000581}
582
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000583PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000584"settrace(function)\n\
585\n\
586Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000587function call. See the debugger chapter in the library manual."
588);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000589
Tal Einatede0b6f2018-12-31 17:12:08 +0200590/*[clinic input]
591sys.gettrace
592
593Return the global debug tracing function set with sys.settrace.
594
595See the debugger chapter in the library manual.
596[clinic start generated code]*/
597
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000598static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200599sys_gettrace_impl(PyObject *module)
600/*[clinic end generated code: output=e97e3a4d8c971b6e input=373b51bb2147f4d8]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000601{
Victor Stinner50b48572018-11-01 01:51:40 +0100602 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 if (temp == NULL)
606 temp = Py_None;
607 Py_INCREF(temp);
608 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000609}
610
Christian Heimes9bd667a2008-01-20 15:14:11 +0000611static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000612sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 if (trace_init() == -1)
615 return NULL;
616 if (args == Py_None)
617 PyEval_SetProfile(NULL, NULL);
618 else
619 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200620 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000621}
622
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000623PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000624"setprofile(function)\n\
625\n\
626Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000627and return. See the profiler chapter in the library manual."
628);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000629
Tal Einatede0b6f2018-12-31 17:12:08 +0200630/*[clinic input]
631sys.getprofile
632
633Return the profiling function set with sys.setprofile.
634
635See the profiler chapter in the library manual.
636[clinic start generated code]*/
637
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000638static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200639sys_getprofile_impl(PyObject *module)
640/*[clinic end generated code: output=579b96b373448188 input=1b3209d89a32965d]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000641{
Victor Stinner50b48572018-11-01 01:51:40 +0100642 PyThreadState *tstate = _PyThreadState_GET();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000643 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (temp == NULL)
646 temp = Py_None;
647 Py_INCREF(temp);
648 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000649}
650
Tal Einatede0b6f2018-12-31 17:12:08 +0200651/*[clinic input]
652sys.setcheckinterval
653
654 n: int
655 /
656
657Set the async event check interval to n instructions.
658
659This tells the Python interpreter to check for asynchronous events
660every n instructions.
661
662This also affects how often thread switches occur.
663[clinic start generated code]*/
Christian Heimes9bd667a2008-01-20 15:14:11 +0000664
665static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200666sys_setcheckinterval_impl(PyObject *module, int n)
667/*[clinic end generated code: output=3f686cef07e6e178 input=7a35b17bf22a6227]*/
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000668{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000669 if (PyErr_WarnEx(PyExc_DeprecationWarning,
670 "sys.getcheckinterval() and sys.setcheckinterval() "
671 "are deprecated. Use sys.setswitchinterval() "
672 "instead.", 1) < 0)
673 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200674
Victor Stinnercaba55b2018-08-03 15:33:52 +0200675 PyInterpreterState *interp = _PyInterpreterState_Get();
Tal Einatede0b6f2018-12-31 17:12:08 +0200676 interp->check_interval = n;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200677 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000678}
679
Tal Einatede0b6f2018-12-31 17:12:08 +0200680/*[clinic input]
681sys.getcheckinterval
682
683Return the current check interval; see sys.setcheckinterval().
684[clinic start generated code]*/
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000685
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000686static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200687sys_getcheckinterval_impl(PyObject *module)
688/*[clinic end generated code: output=1b5060bf2b23a47c input=4b6589cbcca1db4e]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000689{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000690 if (PyErr_WarnEx(PyExc_DeprecationWarning,
691 "sys.getcheckinterval() and sys.setcheckinterval() "
692 "are deprecated. Use sys.getswitchinterval() "
693 "instead.", 1) < 0)
694 return NULL;
Victor Stinnercaba55b2018-08-03 15:33:52 +0200695 PyInterpreterState *interp = _PyInterpreterState_Get();
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600696 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000697}
698
Tal Einatede0b6f2018-12-31 17:12:08 +0200699/*[clinic input]
700sys.setswitchinterval
701
702 interval: double
703 /
704
705Set the ideal thread switching delay inside the Python interpreter.
706
707The actual frequency of switching threads can be lower if the
708interpreter executes long sequences of uninterruptible code
709(this is implementation-specific and workload-dependent).
710
711The parameter must represent the desired switching delay in seconds
712A typical value is 0.005 (5 milliseconds).
713[clinic start generated code]*/
Tim Peterse5e065b2003-07-06 18:36:54 +0000714
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000715static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200716sys_setswitchinterval_impl(PyObject *module, double interval)
717/*[clinic end generated code: output=65a19629e5153983 input=561b477134df91d9]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000718{
Tal Einatede0b6f2018-12-31 17:12:08 +0200719 if (interval <= 0.0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 PyErr_SetString(PyExc_ValueError,
721 "switch interval must be strictly positive");
722 return NULL;
723 }
Tal Einatede0b6f2018-12-31 17:12:08 +0200724 _PyEval_SetSwitchInterval((unsigned long) (1e6 * interval));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200725 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000726}
727
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000728
Tal Einatede0b6f2018-12-31 17:12:08 +0200729/*[clinic input]
730sys.getswitchinterval -> double
731
732Return the current thread switch interval; see sys.setswitchinterval().
733[clinic start generated code]*/
734
735static double
736sys_getswitchinterval_impl(PyObject *module)
737/*[clinic end generated code: output=a38c277c85b5096d input=bdf9d39c0ebbbb6f]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000738{
Tal Einatede0b6f2018-12-31 17:12:08 +0200739 return 1e-6 * _PyEval_GetSwitchInterval();
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000740}
741
Tal Einatede0b6f2018-12-31 17:12:08 +0200742/*[clinic input]
743sys.setrecursionlimit
744
745 limit as new_limit: int
746 /
747
748Set the maximum depth of the Python interpreter stack to n.
749
750This limit prevents infinite recursion from causing an overflow of the C
751stack and crashing Python. The highest possible limit is platform-
752dependent.
753[clinic start generated code]*/
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000754
Tim Peterse5e065b2003-07-06 18:36:54 +0000755static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200756sys_setrecursionlimit_impl(PyObject *module, int new_limit)
757/*[clinic end generated code: output=35e1c64754800ace input=b0f7a23393924af3]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000758{
Tal Einatede0b6f2018-12-31 17:12:08 +0200759 int mark;
Victor Stinner50856d52015-10-13 00:11:21 +0200760 PyThreadState *tstate;
761
Victor Stinner50856d52015-10-13 00:11:21 +0200762 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000763 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200764 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 return NULL;
766 }
Victor Stinner50856d52015-10-13 00:11:21 +0200767
768 /* Issue #25274: When the recursion depth hits the recursion limit in
769 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
770 set to 1 and a RecursionError is raised. The overflowed flag is reset
771 to 0 when the recursion depth goes below the low-water mark: see
772 Py_LeaveRecursiveCall().
773
774 Reject too low new limit if the current recursion depth is higher than
775 the new low-water mark. Otherwise it may not be possible anymore to
776 reset the overflowed flag to 0. */
777 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
Victor Stinner50b48572018-11-01 01:51:40 +0100778 tstate = _PyThreadState_GET();
Victor Stinner50856d52015-10-13 00:11:21 +0200779 if (tstate->recursion_depth >= mark) {
780 PyErr_Format(PyExc_RecursionError,
781 "cannot set the recursion limit to %i at "
782 "the recursion depth %i: the limit is too low",
783 new_limit, tstate->recursion_depth);
784 return NULL;
785 }
786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200788 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000789}
790
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800791/*[clinic input]
792sys.set_coroutine_origin_tracking_depth
793
794 depth: int
795
796Enable or disable origin tracking for coroutine objects in this thread.
797
Tal Einatede0b6f2018-12-31 17:12:08 +0200798Coroutine objects will track 'depth' frames of traceback information
799about where they came from, available in their cr_origin attribute.
800
801Set a depth of 0 to disable.
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800802[clinic start generated code]*/
803
804static PyObject *
805sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
Tal Einatede0b6f2018-12-31 17:12:08 +0200806/*[clinic end generated code: output=0a2123c1cc6759c5 input=a1d0a05f89d2c426]*/
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800807{
808 if (depth < 0) {
809 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
810 return NULL;
811 }
812 _PyEval_SetCoroutineOriginTrackingDepth(depth);
813 Py_RETURN_NONE;
814}
815
816/*[clinic input]
817sys.get_coroutine_origin_tracking_depth -> int
818
819Check status of origin tracking for coroutine objects in this thread.
820[clinic start generated code]*/
821
822static int
823sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
824/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
825{
826 return _PyEval_GetCoroutineOriginTrackingDepth();
827}
828
Tal Einatede0b6f2018-12-31 17:12:08 +0200829/*[clinic input]
830sys.set_coroutine_wrapper
831
832 wrapper: object
833 /
834
835Set a wrapper for coroutine objects.
836[clinic start generated code]*/
837
Yury Selivanov75445082015-05-11 22:57:16 -0400838static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200839sys_set_coroutine_wrapper(PyObject *module, PyObject *wrapper)
840/*[clinic end generated code: output=9c7db52d65f6b188 input=df6ac09a06afef34]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400841{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800842 if (PyErr_WarnEx(PyExc_DeprecationWarning,
843 "set_coroutine_wrapper is deprecated", 1) < 0) {
844 return NULL;
845 }
846
Yury Selivanov75445082015-05-11 22:57:16 -0400847 if (wrapper != Py_None) {
848 if (!PyCallable_Check(wrapper)) {
849 PyErr_Format(PyExc_TypeError,
850 "callable expected, got %.50s",
851 Py_TYPE(wrapper)->tp_name);
852 return NULL;
853 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400854 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400855 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400856 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400857 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400858 }
Yury Selivanov75445082015-05-11 22:57:16 -0400859 Py_RETURN_NONE;
860}
861
Tal Einatede0b6f2018-12-31 17:12:08 +0200862/*[clinic input]
863sys.get_coroutine_wrapper
864
865Return the wrapper for coroutines set by sys.set_coroutine_wrapper.
866[clinic start generated code]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400867
868static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200869sys_get_coroutine_wrapper_impl(PyObject *module)
870/*[clinic end generated code: output=b74a7e4b14fe898e input=ef0351fb9ece0bb4]*/
Yury Selivanov75445082015-05-11 22:57:16 -0400871{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800872 if (PyErr_WarnEx(PyExc_DeprecationWarning,
873 "get_coroutine_wrapper is deprecated", 1) < 0) {
874 return NULL;
875 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400876 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400877 if (wrapper == NULL) {
878 wrapper = Py_None;
879 }
880 Py_INCREF(wrapper);
881 return wrapper;
882}
883
Yury Selivanov75445082015-05-11 22:57:16 -0400884
Yury Selivanoveb636452016-09-08 22:01:51 -0700885static PyTypeObject AsyncGenHooksType;
886
887PyDoc_STRVAR(asyncgen_hooks_doc,
888"asyncgen_hooks\n\
889\n\
890A struct sequence providing information about asynhronous\n\
891generators hooks. The attributes are read only.");
892
893static PyStructSequence_Field asyncgen_hooks_fields[] = {
894 {"firstiter", "Hook to intercept first iteration"},
895 {"finalizer", "Hook to intercept finalization"},
896 {0}
897};
898
899static PyStructSequence_Desc asyncgen_hooks_desc = {
900 "asyncgen_hooks", /* name */
901 asyncgen_hooks_doc, /* doc */
902 asyncgen_hooks_fields , /* fields */
903 2
904};
905
Yury Selivanoveb636452016-09-08 22:01:51 -0700906static PyObject *
907sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
908{
909 static char *keywords[] = {"firstiter", "finalizer", NULL};
910 PyObject *firstiter = NULL;
911 PyObject *finalizer = NULL;
912
913 if (!PyArg_ParseTupleAndKeywords(
914 args, kw, "|OO", keywords,
915 &firstiter, &finalizer)) {
916 return NULL;
917 }
918
919 if (finalizer && finalizer != Py_None) {
920 if (!PyCallable_Check(finalizer)) {
921 PyErr_Format(PyExc_TypeError,
922 "callable finalizer expected, got %.50s",
923 Py_TYPE(finalizer)->tp_name);
924 return NULL;
925 }
926 _PyEval_SetAsyncGenFinalizer(finalizer);
927 }
928 else if (finalizer == Py_None) {
929 _PyEval_SetAsyncGenFinalizer(NULL);
930 }
931
932 if (firstiter && firstiter != Py_None) {
933 if (!PyCallable_Check(firstiter)) {
934 PyErr_Format(PyExc_TypeError,
935 "callable firstiter expected, got %.50s",
936 Py_TYPE(firstiter)->tp_name);
937 return NULL;
938 }
939 _PyEval_SetAsyncGenFirstiter(firstiter);
940 }
941 else if (firstiter == Py_None) {
942 _PyEval_SetAsyncGenFirstiter(NULL);
943 }
944
945 Py_RETURN_NONE;
946}
947
948PyDoc_STRVAR(set_asyncgen_hooks_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +0200949"set_asyncgen_hooks(* [, firstiter] [, finalizer])\n\
Yury Selivanoveb636452016-09-08 22:01:51 -0700950\n\
951Set a finalizer for async generators objects."
952);
953
Tal Einatede0b6f2018-12-31 17:12:08 +0200954/*[clinic input]
955sys.get_asyncgen_hooks
956
957Return the installed asynchronous generators hooks.
958
959This returns a namedtuple of the form (firstiter, finalizer).
960[clinic start generated code]*/
961
Yury Selivanoveb636452016-09-08 22:01:51 -0700962static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +0200963sys_get_asyncgen_hooks_impl(PyObject *module)
964/*[clinic end generated code: output=53a253707146f6cf input=3676b9ea62b14625]*/
Yury Selivanoveb636452016-09-08 22:01:51 -0700965{
966 PyObject *res;
967 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
968 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
969
970 res = PyStructSequence_New(&AsyncGenHooksType);
971 if (res == NULL) {
972 return NULL;
973 }
974
975 if (firstiter == NULL) {
976 firstiter = Py_None;
977 }
978
979 if (finalizer == NULL) {
980 finalizer = Py_None;
981 }
982
983 Py_INCREF(firstiter);
984 PyStructSequence_SET_ITEM(res, 0, firstiter);
985
986 Py_INCREF(finalizer);
987 PyStructSequence_SET_ITEM(res, 1, finalizer);
988
989 return res;
990}
991
Yury Selivanoveb636452016-09-08 22:01:51 -0700992
Mark Dickinsondc787d22010-05-23 13:33:13 +0000993static PyTypeObject Hash_InfoType;
994
995PyDoc_STRVAR(hash_info_doc,
996"hash_info\n\
997\n\
998A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100999hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +00001000
1001static PyStructSequence_Field hash_info_fields[] = {
1002 {"width", "width of the type used for hashing, in bits"},
1003 {"modulus", "prime number giving the modulus on which the hash "
1004 "function is based"},
1005 {"inf", "value to be used for hash of a positive infinity"},
1006 {"nan", "value to be used for hash of a nan"},
1007 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +01001008 {"algorithm", "name of the algorithm for hashing of str, bytes and "
1009 "memoryviews"},
1010 {"hash_bits", "internal output size of hash algorithm"},
1011 {"seed_bits", "seed size of hash algorithm"},
1012 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +00001013 {NULL, NULL}
1014};
1015
1016static PyStructSequence_Desc hash_info_desc = {
1017 "sys.hash_info",
1018 hash_info_doc,
1019 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +01001020 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +00001021};
1022
Matthias Klosed885e952010-07-06 10:53:30 +00001023static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +00001024get_hash_info(void)
1025{
1026 PyObject *hash_info;
1027 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001028 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +00001029 hash_info = PyStructSequence_New(&Hash_InfoType);
1030 if (hash_info == NULL)
1031 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +01001032 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +00001033 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +00001034 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001035 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +00001036 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001037 PyStructSequence_SET_ITEM(hash_info, field++,
1038 PyLong_FromLong(_PyHASH_INF));
1039 PyStructSequence_SET_ITEM(hash_info, field++,
1040 PyLong_FromLong(_PyHASH_NAN));
1041 PyStructSequence_SET_ITEM(hash_info, field++,
1042 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +01001043 PyStructSequence_SET_ITEM(hash_info, field++,
1044 PyUnicode_FromString(hashfunc->name));
1045 PyStructSequence_SET_ITEM(hash_info, field++,
1046 PyLong_FromLong(hashfunc->hash_bits));
1047 PyStructSequence_SET_ITEM(hash_info, field++,
1048 PyLong_FromLong(hashfunc->seed_bits));
1049 PyStructSequence_SET_ITEM(hash_info, field++,
1050 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +00001051 if (PyErr_Occurred()) {
1052 Py_CLEAR(hash_info);
1053 return NULL;
1054 }
1055 return hash_info;
1056}
Tal Einatede0b6f2018-12-31 17:12:08 +02001057/*[clinic input]
1058sys.getrecursionlimit
Mark Dickinsondc787d22010-05-23 13:33:13 +00001059
Tal Einatede0b6f2018-12-31 17:12:08 +02001060Return the current value of the recursion limit.
Mark Dickinsondc787d22010-05-23 13:33:13 +00001061
Tal Einatede0b6f2018-12-31 17:12:08 +02001062The recursion limit is the maximum depth of the Python interpreter
1063stack. This limit prevents infinite recursion from causing an overflow
1064of the C stack and crashing Python.
1065[clinic start generated code]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001066
1067static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001068sys_getrecursionlimit_impl(PyObject *module)
1069/*[clinic end generated code: output=d571fb6b4549ef2e input=1c6129fd2efaeea8]*/
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001070{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001071 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001072}
1073
Mark Hammond8696ebc2002-10-08 02:44:31 +00001074#ifdef MS_WINDOWS
Mark Hammond8696ebc2002-10-08 02:44:31 +00001075
Eric Smithf7bb5782010-01-27 00:44:57 +00001076static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1077
1078static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 {"major", "Major version number"},
1080 {"minor", "Minor version number"},
1081 {"build", "Build number"},
1082 {"platform", "Operating system platform"},
1083 {"service_pack", "Latest Service Pack installed on the system"},
1084 {"service_pack_major", "Service Pack major version number"},
1085 {"service_pack_minor", "Service Pack minor version number"},
1086 {"suite_mask", "Bit mask identifying available product suites"},
1087 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001088 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001090};
1091
1092static PyStructSequence_Desc windows_version_desc = {
Tal Einatede0b6f2018-12-31 17:12:08 +02001093 "sys.getwindowsversion", /* name */
1094 sys_getwindowsversion__doc__, /* doc */
1095 windows_version_fields, /* fields */
1096 5 /* For backward compatibility,
1097 only the first 5 items are accessible
1098 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001099};
1100
Steve Dower3e96f322015-03-02 08:01:10 -08001101/* Disable deprecation warnings about GetVersionEx as the result is
1102 being passed straight through to the caller, who is responsible for
1103 using it correctly. */
1104#pragma warning(push)
1105#pragma warning(disable:4996)
1106
Tal Einatede0b6f2018-12-31 17:12:08 +02001107/*[clinic input]
1108sys.getwindowsversion
1109
1110Return info about the running version of Windows as a named tuple.
1111
1112The members are named: major, minor, build, platform, service_pack,
1113service_pack_major, service_pack_minor, suite_mask, product_type and
1114platform_version. For backward compatibility, only the first 5 items
1115are available by indexing. All elements are numbers, except
1116service_pack and platform_type which are strings, and platform_version
1117which is a 3-tuple. Platform is always 2. Product_type may be 1 for a
1118workstation, 2 for a domain controller, 3 for a server.
1119Platform_version is a 3-tuple containing a version number that is
1120intended for identifying the OS rather than feature detection.
1121[clinic start generated code]*/
1122
Mark Hammond8696ebc2002-10-08 02:44:31 +00001123static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001124sys_getwindowsversion_impl(PyObject *module)
1125/*[clinic end generated code: output=1ec063280b932857 input=73a228a328fee63a]*/
Mark Hammond8696ebc2002-10-08 02:44:31 +00001126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 PyObject *version;
1128 int pos = 0;
1129 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001130 DWORD realMajor, realMinor, realBuild;
1131 HANDLE hKernel32;
1132 wchar_t kernel32_path[MAX_PATH];
1133 LPVOID verblock;
1134 DWORD verblock_size;
1135
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 ver.dwOSVersionInfoSize = sizeof(ver);
1137 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1138 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 version = PyStructSequence_New(&WindowsVersionType);
1141 if (version == NULL)
1142 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1145 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1146 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1147 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1148 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1149 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1150 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1151 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1152 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001153
Steve Dower74f4af72016-09-17 17:27:48 -07001154 realMajor = ver.dwMajorVersion;
1155 realMinor = ver.dwMinorVersion;
1156 realBuild = ver.dwBuildNumber;
1157
1158 // GetVersion will lie if we are running in a compatibility mode.
1159 // We need to read the version info from a system file resource
1160 // to accurately identify the OS version. If we fail for any reason,
1161 // just return whatever GetVersion said.
1162 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1163 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1164 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1165 (verblock = PyMem_RawMalloc(verblock_size))) {
1166 VS_FIXEDFILEINFO *ffi;
1167 UINT ffi_len;
1168
1169 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1170 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1171 realMajor = HIWORD(ffi->dwProductVersionMS);
1172 realMinor = LOWORD(ffi->dwProductVersionMS);
1173 realBuild = HIWORD(ffi->dwProductVersionLS);
1174 }
1175 PyMem_RawFree(verblock);
1176 }
Segev Finer48fb7662017-06-04 20:52:27 +03001177 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1178 realMajor,
1179 realMinor,
1180 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001181 ));
1182
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001183 if (PyErr_Occurred()) {
1184 Py_DECREF(version);
1185 return NULL;
1186 }
Steve Dower74f4af72016-09-17 17:27:48 -07001187
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001188 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001189}
1190
Steve Dower3e96f322015-03-02 08:01:10 -08001191#pragma warning(pop)
1192
Tal Einatede0b6f2018-12-31 17:12:08 +02001193/*[clinic input]
1194sys._enablelegacywindowsfsencoding
1195
1196Changes the default filesystem encoding to mbcs:replace.
1197
1198This is done for consistency with earlier versions of Python. See PEP
1199529 for more information.
1200
1201This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING
1202environment variable before launching Python.
1203[clinic start generated code]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001204
1205static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001206sys__enablelegacywindowsfsencoding_impl(PyObject *module)
1207/*[clinic end generated code: output=f5c3855b45e24fe9 input=2bfa931a20704492]*/
Steve Dowercc16be82016-09-08 10:35:16 -07001208{
Victor Stinnerb2457ef2018-08-29 13:25:36 +02001209 PyInterpreterState *interp = _PyInterpreterState_GET_UNSAFE();
1210 _PyCoreConfig *config = &interp->core_config;
1211
1212 /* Set the filesystem encoding to mbcs/replace (PEP 529) */
1213 char *encoding = _PyMem_RawStrdup("mbcs");
1214 char *errors = _PyMem_RawStrdup("replace");
1215 if (encoding == NULL || errors == NULL) {
1216 PyMem_Free(encoding);
1217 PyMem_Free(errors);
1218 PyErr_NoMemory();
1219 return NULL;
1220 }
1221
1222 PyMem_RawFree(config->filesystem_encoding);
1223 config->filesystem_encoding = encoding;
1224 PyMem_RawFree(config->filesystem_errors);
1225 config->filesystem_errors = errors;
1226
1227 if (_Py_SetFileSystemEncoding(config->filesystem_encoding,
1228 config->filesystem_errors) < 0) {
1229 PyErr_NoMemory();
1230 return NULL;
1231 }
1232
Steve Dowercc16be82016-09-08 10:35:16 -07001233 Py_RETURN_NONE;
1234}
1235
Mark Hammond8696ebc2002-10-08 02:44:31 +00001236#endif /* MS_WINDOWS */
1237
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001238#ifdef HAVE_DLOPEN
Tal Einatede0b6f2018-12-31 17:12:08 +02001239
1240/*[clinic input]
1241sys.setdlopenflags
1242
1243 flags as new_val: int
1244 /
1245
1246Set the flags used by the interpreter for dlopen calls.
1247
1248This is used, for example, when the interpreter loads extension
1249modules. Among other things, this will enable a lazy resolving of
1250symbols when importing a module, if called as sys.setdlopenflags(0).
1251To share symbols across extension modules, call as
1252sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag
1253modules can be found in the os module (RTLD_xxx constants, e.g.
1254os.RTLD_LAZY).
1255[clinic start generated code]*/
1256
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001257static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001258sys_setdlopenflags_impl(PyObject *module, int new_val)
1259/*[clinic end generated code: output=ec918b7fe0a37281 input=4c838211e857a77f]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001260{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001261 PyInterpreterState *interp = _PyInterpreterState_Get();
1262 interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001263 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001264}
1265
Tal Einatede0b6f2018-12-31 17:12:08 +02001266
1267/*[clinic input]
1268sys.getdlopenflags
1269
1270Return the current value of the flags that are used for dlopen calls.
1271
1272The flag constants are defined in the os module.
1273[clinic start generated code]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001274
1275static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001276sys_getdlopenflags_impl(PyObject *module)
1277/*[clinic end generated code: output=e92cd1bc5005da6e input=dc4ea0899c53b4b6]*/
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001278{
Victor Stinnercaba55b2018-08-03 15:33:52 +02001279 PyInterpreterState *interp = _PyInterpreterState_Get();
1280 return PyLong_FromLong(interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001281}
1282
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001284
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001285#ifdef USE_MALLOPT
1286/* Link with -lmalloc (or -lmpc) on an SGI */
1287#include <malloc.h>
1288
Tal Einatede0b6f2018-12-31 17:12:08 +02001289/*[clinic input]
1290sys.mdebug
1291
1292 flag: int
1293 /
1294[clinic start generated code]*/
1295
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001296static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001297sys_mdebug_impl(PyObject *module, int flag)
1298/*[clinic end generated code: output=5431d545847c3637 input=151d150ae1636f8a]*/
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001299{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001300 int flag;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001302 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001303}
1304#endif /* USE_MALLOPT */
1305
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001306size_t
1307_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001311 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001312
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001313 /* Make sure the type is initialized. float gets initialized late */
1314 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001315 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001316
Benjamin Petersonce798522012-01-22 11:24:29 -05001317 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 if (method == NULL) {
1319 if (!PyErr_Occurred())
1320 PyErr_Format(PyExc_TypeError,
1321 "Type %.100s doesn't define __sizeof__",
1322 Py_TYPE(o)->tp_name);
1323 }
1324 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001325 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 Py_DECREF(method);
1327 }
1328
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001329 if (res == NULL)
1330 return (size_t)-1;
1331
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001332 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001333 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001334 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001335 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001337 if (size < 0) {
1338 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1339 return (size_t)-1;
1340 }
1341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001343 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001344 return ((size_t)size) + sizeof(PyGC_Head);
1345 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001346}
1347
1348static PyObject *
1349sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1350{
1351 static char *kwlist[] = {"object", "default", 0};
1352 size_t size;
1353 PyObject *o, *dflt = NULL;
1354
1355 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1356 kwlist, &o, &dflt))
1357 return NULL;
1358
1359 size = _PySys_GetSizeOf(o);
1360
1361 if (size == (size_t)-1 && PyErr_Occurred()) {
1362 /* Has a default value been given */
1363 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1364 PyErr_Clear();
1365 Py_INCREF(dflt);
1366 return dflt;
1367 }
1368 else
1369 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001370 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001371
1372 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001373}
1374
1375PyDoc_STRVAR(getsizeof_doc,
Tal Einatede0b6f2018-12-31 17:12:08 +02001376"getsizeof(object [, default]) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001377\n\
1378Return the size of object in bytes.");
1379
Tal Einatede0b6f2018-12-31 17:12:08 +02001380/*[clinic input]
1381sys.getrefcount -> Py_ssize_t
1382
1383 object: object
1384 /
1385
1386Return the reference count of object.
1387
1388The count returned is generally one higher than you might expect,
1389because it includes the (temporary) reference as an argument to
1390getrefcount().
1391[clinic start generated code]*/
1392
1393static Py_ssize_t
1394sys_getrefcount_impl(PyObject *module, PyObject *object)
1395/*[clinic end generated code: output=5fd477f2264b85b2 input=bf474efd50a21535]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001396{
Tal Einatede0b6f2018-12-31 17:12:08 +02001397 return object->ob_refcnt;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001398}
1399
Tim Peters4be93d02002-07-07 19:59:50 +00001400#ifdef Py_REF_DEBUG
Tal Einatede0b6f2018-12-31 17:12:08 +02001401/*[clinic input]
1402sys.gettotalrefcount -> Py_ssize_t
1403[clinic start generated code]*/
1404
1405static Py_ssize_t
1406sys_gettotalrefcount_impl(PyObject *module)
1407/*[clinic end generated code: output=4103886cf17c25bc input=53b744faa5d2e4f6]*/
Mark Hammond440d8982000-06-20 08:12:48 +00001408{
Tal Einatede0b6f2018-12-31 17:12:08 +02001409 return _Py_GetRefTotal();
Mark Hammond440d8982000-06-20 08:12:48 +00001410}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001411#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001412
Tal Einatede0b6f2018-12-31 17:12:08 +02001413/*[clinic input]
1414sys.getallocatedblocks -> Py_ssize_t
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001415
Tal Einatede0b6f2018-12-31 17:12:08 +02001416Return the number of memory blocks currently allocated.
1417[clinic start generated code]*/
1418
1419static Py_ssize_t
1420sys_getallocatedblocks_impl(PyObject *module)
1421/*[clinic end generated code: output=f0c4e873f0b6dcf7 input=dab13ee346a0673e]*/
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001422{
Tal Einatede0b6f2018-12-31 17:12:08 +02001423 return _Py_GetAllocatedBlocks();
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001424}
1425
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001426#ifdef COUNT_ALLOCS
Tal Einatede0b6f2018-12-31 17:12:08 +02001427/*[clinic input]
1428sys.getcounts
1429[clinic start generated code]*/
1430
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001431static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001432sys_getcounts_impl(PyObject *module)
1433/*[clinic end generated code: output=20df00bc164f43cb input=ad2ec7bda5424953]*/
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001434{
Pablo Galindo49c75a82018-10-28 15:02:17 +00001435 extern PyObject *_Py_get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001436
Pablo Galindo49c75a82018-10-28 15:02:17 +00001437 return _Py_get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001438}
1439#endif
1440
Tal Einatede0b6f2018-12-31 17:12:08 +02001441/*[clinic input]
1442sys._getframe
1443
1444 depth: int = 0
1445 /
1446
1447Return a frame object from the call stack.
1448
1449If optional integer depth is given, return the frame object that many
1450calls below the top of the stack. If that is deeper than the call
1451stack, ValueError is raised. The default for depth is zero, returning
1452the frame at the top of the call stack.
1453
1454This function should be used for internal and specialized purposes
1455only.
1456[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001457
1458static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001459sys__getframe_impl(PyObject *module, int depth)
1460/*[clinic end generated code: output=d438776c04d59804 input=c1be8a6464b11ee5]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001461{
Victor Stinner50b48572018-11-01 01:51:40 +01001462 PyFrameObject *f = _PyThreadState_GET()->frame;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001464 while (depth > 0 && f != NULL) {
1465 f = f->f_back;
1466 --depth;
1467 }
1468 if (f == NULL) {
1469 PyErr_SetString(PyExc_ValueError,
1470 "call stack is not deep enough");
1471 return NULL;
1472 }
1473 Py_INCREF(f);
1474 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001475}
1476
Tal Einatede0b6f2018-12-31 17:12:08 +02001477/*[clinic input]
1478sys._current_frames
1479
1480Return a dict mapping each thread's thread id to its current stack frame.
1481
1482This function should be used for specialized purposes only.
1483[clinic start generated code]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001484
1485static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001486sys__current_frames_impl(PyObject *module)
1487/*[clinic end generated code: output=d2a41ac0a0a3809a input=2a9049c5f5033691]*/
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001490}
1491
Tal Einatede0b6f2018-12-31 17:12:08 +02001492/*[clinic input]
1493sys.call_tracing
1494
1495 func: object
1496 args as funcargs: object(subclass_of='&PyTuple_Type')
1497 /
1498
1499Call func(*args), while tracing is enabled.
1500
1501The tracing state is saved, and restored afterwards. This is intended
1502to be called from a debugger from a checkpoint, to recursively debug
1503some other code.
1504[clinic start generated code]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001505
1506static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001507sys_call_tracing_impl(PyObject *module, PyObject *func, PyObject *funcargs)
1508/*[clinic end generated code: output=7e4999853cd4e5a6 input=5102e8b11049f92f]*/
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001511}
1512
Tal Einatede0b6f2018-12-31 17:12:08 +02001513/*[clinic input]
1514sys.callstats
1515
1516Return a tuple of function call statistics.
1517
1518A tuple is returned only if CALL_PROFILE was defined when Python was
1519built. Otherwise, this returns None.
1520
1521When enabled, this function returns detailed, implementation-specific
1522details about the number of function calls executed. The return value
1523is a 11-tuple where the entries in the tuple are counts of:
15240. all function calls
15251. calls to PyFunction_Type objects
15262. PyFunction calls that do not create an argument tuple
15273. PyFunction calls that do not create an argument tuple
1528 and bypass PyEval_EvalCodeEx()
15294. PyMethod calls
15305. PyMethod calls on bound methods
15316. PyType calls
15327. PyCFunction calls
15338. generator calls
15349. All other calls
153510. Number of stack pops performed by call_function()
1536[clinic start generated code]*/
Barry Warsawb6a54d22000-12-06 21:47:46 +00001537
Victor Stinner048afd92016-11-28 11:59:04 +01001538static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001539sys_callstats_impl(PyObject *module)
1540/*[clinic end generated code: output=edc4a74957fa8def input=d447d8d224d5d175]*/
Victor Stinner048afd92016-11-28 11:59:04 +01001541{
1542 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1543 "sys.callstats() has been deprecated in Python 3.7 "
1544 "and will be removed in the future", 1) < 0) {
1545 return NULL;
1546 }
1547
1548 Py_RETURN_NONE;
1549}
1550
1551
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001552#ifdef __cplusplus
1553extern "C" {
1554#endif
1555
Tal Einatede0b6f2018-12-31 17:12:08 +02001556/*[clinic input]
1557sys._debugmallocstats
1558
1559Print summary info to stderr about the state of pymalloc's structures.
1560
1561In Py_DEBUG mode, also perform some expensive internal consistency
1562checks.
1563[clinic start generated code]*/
1564
David Malcolm49526f42012-06-22 14:55:41 -04001565static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001566sys__debugmallocstats_impl(PyObject *module)
1567/*[clinic end generated code: output=ec3565f8c7cee46a input=33c0c9c416f98424]*/
David Malcolm49526f42012-06-22 14:55:41 -04001568{
1569#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001570 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001571 fputc('\n', stderr);
1572 }
David Malcolm49526f42012-06-22 14:55:41 -04001573#endif
1574 _PyObject_DebugTypeStats(stderr);
1575
1576 Py_RETURN_NONE;
1577}
David Malcolm49526f42012-06-22 14:55:41 -04001578
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001579#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001580/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001581extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001582#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001583
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001584#ifdef DYNAMIC_EXECUTION_PROFILE
1585/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001586extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001587#endif
1588
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001589#ifdef __cplusplus
1590}
1591#endif
1592
Tal Einatede0b6f2018-12-31 17:12:08 +02001593
1594/*[clinic input]
1595sys._clear_type_cache
1596
1597Clear the internal type lookup cache.
1598[clinic start generated code]*/
1599
Christian Heimes15ebc882008-02-04 18:48:49 +00001600static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001601sys__clear_type_cache_impl(PyObject *module)
1602/*[clinic end generated code: output=20e48ca54a6f6971 input=127f3e04a8d9b555]*/
Christian Heimes15ebc882008-02-04 18:48:49 +00001603{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 PyType_ClearCache();
1605 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001606}
1607
Tal Einatede0b6f2018-12-31 17:12:08 +02001608/*[clinic input]
1609sys.is_finalizing
1610
1611Return True if Python is exiting.
1612[clinic start generated code]*/
1613
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001614static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001615sys_is_finalizing_impl(PyObject *module)
1616/*[clinic end generated code: output=735b5ff7962ab281 input=f0df747a039948a5]*/
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001617{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001618 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001619}
1620
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001621#ifdef ANDROID_API_LEVEL
Tal Einatede0b6f2018-12-31 17:12:08 +02001622/*[clinic input]
1623sys.getandroidapilevel
1624
1625Return the build time API version of Android as an integer.
1626[clinic start generated code]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001627
1628static PyObject *
Tal Einatede0b6f2018-12-31 17:12:08 +02001629sys_getandroidapilevel_impl(PyObject *module)
1630/*[clinic end generated code: output=214abf183a1c70c1 input=3e6d6c9fcdd24ac6]*/
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001631{
1632 return PyLong_FromLong(ANDROID_API_LEVEL);
1633}
1634#endif /* ANDROID_API_LEVEL */
1635
1636
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001637static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 /* Might as well keep this in alphabetic order */
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001639 {"breakpointhook", (PyCFunction)(void(*)(void))sys_breakpointhook,
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001640 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001641 SYS_CALLSTATS_METHODDEF
1642 SYS__CLEAR_TYPE_CACHE_METHODDEF
1643 SYS__CURRENT_FRAMES_METHODDEF
1644 SYS_DISPLAYHOOK_METHODDEF
1645 SYS_EXC_INFO_METHODDEF
1646 SYS_EXCEPTHOOK_METHODDEF
1647 SYS_EXIT_METHODDEF
1648 SYS_GETDEFAULTENCODING_METHODDEF
1649 SYS_GETDLOPENFLAGS_METHODDEF
1650 SYS_GETALLOCATEDBLOCKS_METHODDEF
1651 SYS_GETCOUNTS_METHODDEF
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001652#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001654#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001655 SYS_GETFILESYSTEMENCODING_METHODDEF
1656 SYS_GETFILESYSTEMENCODEERRORS_METHODDEF
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001657#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001659#endif
Tal Einatede0b6f2018-12-31 17:12:08 +02001660 SYS_GETTOTALREFCOUNT_METHODDEF
1661 SYS_GETREFCOUNT_METHODDEF
1662 SYS_GETRECURSIONLIMIT_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001663 {"getsizeof", (PyCFunction)(void(*)(void))sys_getsizeof,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001665 SYS__GETFRAME_METHODDEF
1666 SYS_GETWINDOWSVERSION_METHODDEF
1667 SYS__ENABLELEGACYWINDOWSFSENCODING_METHODDEF
1668 SYS_INTERN_METHODDEF
1669 SYS_IS_FINALIZING_METHODDEF
1670 SYS_MDEBUG_METHODDEF
1671 SYS_SETCHECKINTERVAL_METHODDEF
1672 SYS_GETCHECKINTERVAL_METHODDEF
1673 SYS_SETSWITCHINTERVAL_METHODDEF
1674 SYS_GETSWITCHINTERVAL_METHODDEF
1675 SYS_SETDLOPENFLAGS_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001677 SYS_GETPROFILE_METHODDEF
1678 SYS_SETRECURSIONLIMIT_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 {"settrace", sys_settrace, METH_O, settrace_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001680 SYS_GETTRACE_METHODDEF
1681 SYS_CALL_TRACING_METHODDEF
1682 SYS__DEBUGMALLOCSTATS_METHODDEF
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001683 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1684 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Tal Einatede0b6f2018-12-31 17:12:08 +02001685 SYS_SET_COROUTINE_WRAPPER_METHODDEF
1686 SYS_GET_COROUTINE_WRAPPER_METHODDEF
Serhiy Storchaka62be7422018-11-27 13:27:31 +02001687 {"set_asyncgen_hooks", (PyCFunction)(void(*)(void))sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001688 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
Tal Einatede0b6f2018-12-31 17:12:08 +02001689 SYS_GET_ASYNCGEN_HOOKS_METHODDEF
1690 SYS_GETANDROIDAPILEVEL_METHODDEF
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001691 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001692};
1693
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001694static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001695list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001696{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001697 PyObject *list = PyList_New(0);
1698 int i;
1699 if (list == NULL)
1700 return NULL;
1701 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1702 PyObject *name = PyUnicode_FromString(
1703 PyImport_Inittab[i].name);
1704 if (name == NULL)
1705 break;
1706 PyList_Append(list, name);
1707 Py_DECREF(name);
1708 }
1709 if (PyList_Sort(list) != 0) {
1710 Py_DECREF(list);
1711 list = NULL;
1712 }
1713 if (list) {
1714 PyObject *v = PyList_AsTuple(list);
1715 Py_DECREF(list);
1716 list = v;
1717 }
1718 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001719}
1720
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001721/* Pre-initialization support for sys.warnoptions and sys._xoptions
1722 *
1723 * Modern internal code paths:
1724 * These APIs get called after _Py_InitializeCore and get to use the
1725 * regular CPython list, dict, and unicode APIs.
1726 *
1727 * Legacy embedding code paths:
1728 * The multi-phase initialization API isn't public yet, so embedding
1729 * apps still need to be able configure sys.warnoptions and sys._xoptions
1730 * before they call Py_Initialize. To support this, we stash copies of
1731 * the supplied wchar * sequences in linked lists, and then migrate the
1732 * contents of those lists to the sys module in _PyInitializeCore.
1733 *
1734 */
1735
1736struct _preinit_entry {
1737 wchar_t *value;
1738 struct _preinit_entry *next;
1739};
1740
1741typedef struct _preinit_entry *_Py_PreInitEntry;
1742
1743static _Py_PreInitEntry _preinit_warnoptions = NULL;
1744static _Py_PreInitEntry _preinit_xoptions = NULL;
1745
1746static _Py_PreInitEntry
1747_alloc_preinit_entry(const wchar_t *value)
1748{
1749 /* To get this to work, we have to initialize the runtime implicitly */
1750 _PyRuntime_Initialize();
1751
1752 /* Force default allocator, so we can ensure that it also gets used to
1753 * destroy the linked list in _clear_preinit_entries.
1754 */
1755 PyMemAllocatorEx old_alloc;
1756 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1757
1758 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1759 if (node != NULL) {
1760 node->value = _PyMem_RawWcsdup(value);
1761 if (node->value == NULL) {
1762 PyMem_RawFree(node);
1763 node = NULL;
1764 };
1765 };
1766
1767 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1768 return node;
1769};
1770
1771static int
1772_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1773{
1774 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1775 if (new_entry == NULL) {
1776 return -1;
1777 }
1778 /* We maintain the linked list in this order so it's easy to play back
1779 * the add commands in the same order later on in _Py_InitializeCore
1780 */
1781 _Py_PreInitEntry last_entry = *optionlist;
1782 if (last_entry == NULL) {
1783 *optionlist = new_entry;
1784 } else {
1785 while (last_entry->next != NULL) {
1786 last_entry = last_entry->next;
1787 }
1788 last_entry->next = new_entry;
1789 }
1790 return 0;
1791};
1792
1793static void
1794_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1795{
1796 _Py_PreInitEntry current = *optionlist;
1797 *optionlist = NULL;
1798 /* Deallocate the nodes and their contents using the default allocator */
1799 PyMemAllocatorEx old_alloc;
1800 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1801 while (current != NULL) {
1802 _Py_PreInitEntry next = current->next;
1803 PyMem_RawFree(current->value);
1804 PyMem_RawFree(current);
1805 current = next;
1806 }
1807 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1808};
1809
1810static void
1811_clear_all_preinit_options(void)
1812{
1813 _clear_preinit_entries(&_preinit_warnoptions);
1814 _clear_preinit_entries(&_preinit_xoptions);
1815}
1816
1817static int
1818_PySys_ReadPreInitOptions(void)
1819{
1820 /* Rerun the add commands with the actual sys module available */
Victor Stinner50b48572018-11-01 01:51:40 +01001821 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001822 if (tstate == NULL) {
1823 /* Still don't have a thread state, so something is wrong! */
1824 return -1;
1825 }
1826 _Py_PreInitEntry entry = _preinit_warnoptions;
1827 while (entry != NULL) {
1828 PySys_AddWarnOption(entry->value);
1829 entry = entry->next;
1830 }
1831 entry = _preinit_xoptions;
1832 while (entry != NULL) {
1833 PySys_AddXOption(entry->value);
1834 entry = entry->next;
1835 }
1836
1837 _clear_all_preinit_options();
1838 return 0;
1839};
1840
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001841static PyObject *
1842get_warnoptions(void)
1843{
Eric Snowdae02762017-09-14 00:35:58 -07001844 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001845 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001846 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1847 * interpreter config. When that happens, we need to properly set
1848 * the `warnoptions` reference in the main interpreter config as well.
1849 *
1850 * For Python 3.7, we shouldn't be able to get here due to the
1851 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1852 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1853 * call optional for embedding applications, thus making this
1854 * reachable again.
1855 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001856 warnoptions = PyList_New(0);
1857 if (warnoptions == NULL)
1858 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001859 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1860 Py_DECREF(warnoptions);
1861 return NULL;
1862 }
1863 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001864 }
1865 return warnoptions;
1866}
Guido van Rossum23fff912000-12-15 22:02:05 +00001867
1868void
1869PySys_ResetWarnOptions(void)
1870{
Victor Stinner50b48572018-11-01 01:51:40 +01001871 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001872 if (tstate == NULL) {
1873 _clear_preinit_entries(&_preinit_warnoptions);
1874 return;
1875 }
1876
Eric Snowdae02762017-09-14 00:35:58 -07001877 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 if (warnoptions == NULL || !PyList_Check(warnoptions))
1879 return;
1880 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001881}
1882
Victor Stinnere1b29952018-10-30 14:31:42 +01001883static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001884_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001885{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001886 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001887 if (warnoptions == NULL) {
1888 return -1;
1889 }
1890 if (PyList_Append(warnoptions, option)) {
1891 return -1;
1892 }
1893 return 0;
1894}
1895
1896void
1897PySys_AddWarnOptionUnicode(PyObject *option)
1898{
Victor Stinnere1b29952018-10-30 14:31:42 +01001899 if (_PySys_AddWarnOptionWithError(option) < 0) {
1900 /* No return value, therefore clear error state if possible */
1901 if (_PyThreadState_UncheckedGet()) {
1902 PyErr_Clear();
1903 }
1904 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001905}
1906
1907void
1908PySys_AddWarnOption(const wchar_t *s)
1909{
Victor Stinner50b48572018-11-01 01:51:40 +01001910 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001911 if (tstate == NULL) {
1912 _append_preinit_entry(&_preinit_warnoptions, s);
1913 return;
1914 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001915 PyObject *unicode;
1916 unicode = PyUnicode_FromWideChar(s, -1);
1917 if (unicode == NULL)
1918 return;
1919 PySys_AddWarnOptionUnicode(unicode);
1920 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001921}
1922
Christian Heimes33fe8092008-04-13 13:53:33 +00001923int
1924PySys_HasWarnOptions(void)
1925{
Eric Snowdae02762017-09-14 00:35:58 -07001926 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Serhiy Storchakadffccc62018-12-10 13:50:22 +02001927 return (warnoptions != NULL && PyList_Check(warnoptions)
1928 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001929}
1930
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001931static PyObject *
1932get_xoptions(void)
1933{
Eric Snowdae02762017-09-14 00:35:58 -07001934 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001935 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001936 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1937 * interpreter config. When that happens, we need to properly set
1938 * the `xoptions` reference in the main interpreter config as well.
1939 *
1940 * For Python 3.7, we shouldn't be able to get here due to the
1941 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1942 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1943 * call optional for embedding applications, thus making this
1944 * reachable again.
1945 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001946 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001947 if (xoptions == NULL)
1948 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001949 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1950 Py_DECREF(xoptions);
1951 return NULL;
1952 }
1953 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001954 }
1955 return xoptions;
1956}
1957
Victor Stinnere1b29952018-10-30 14:31:42 +01001958static int
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001959_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001960{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001961 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001962
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001963 PyObject *opts = get_xoptions();
1964 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001965 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001966 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001967
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001968 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001969 if (!name_end) {
1970 name = PyUnicode_FromWideChar(s, -1);
1971 value = Py_True;
1972 Py_INCREF(value);
1973 }
1974 else {
1975 name = PyUnicode_FromWideChar(s, name_end - s);
1976 value = PyUnicode_FromWideChar(name_end + 1, -1);
1977 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001978 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001979 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001980 }
1981 if (PyDict_SetItem(opts, name, value) < 0) {
1982 goto error;
1983 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001984 Py_DECREF(name);
1985 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001986 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001987
1988error:
1989 Py_XDECREF(name);
1990 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001991 return -1;
1992}
1993
1994void
1995PySys_AddXOption(const wchar_t *s)
1996{
Victor Stinner50b48572018-11-01 01:51:40 +01001997 PyThreadState *tstate = _PyThreadState_GET();
Nick Coghlanbc77eff2018-03-25 20:44:30 +10001998 if (tstate == NULL) {
1999 _append_preinit_entry(&_preinit_xoptions, s);
2000 return;
2001 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002002 if (_PySys_AddXOptionWithError(s) < 0) {
2003 /* No return value, therefore clear error state if possible */
2004 if (_PyThreadState_UncheckedGet()) {
2005 PyErr_Clear();
2006 }
Victor Stinner0cae6092016-11-11 01:43:56 +01002007 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002008}
2009
2010PyObject *
2011PySys_GetXOptions(void)
2012{
2013 return get_xoptions();
2014}
2015
Guido van Rossum40552d01998-08-06 03:34:39 +00002016/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
2017 Two literals concatenated works just fine. If you have a K&R compiler
2018 or other abomination that however *does* understand longer strings,
2019 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002020PyDoc_VAR(sys_doc) =
2021PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002022"This module provides access to some objects used or maintained by the\n\
2023interpreter and to functions that interact strongly with the interpreter.\n\
2024\n\
2025Dynamic objects:\n\
2026\n\
2027argv -- command line arguments; argv[0] is the script pathname if known\n\
2028path -- module search path; path[0] is the script directory, else ''\n\
2029modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002030\n\
2031displayhook -- called to show results in an interactive session\n\
2032excepthook -- called to handle any uncaught exception other than SystemExit\n\
2033 To customize printing in an interactive session or to install a custom\n\
2034 top-level exception handler, assign other functions to replace these.\n\
2035\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00002036stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00002037stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002038stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002039 By assigning other file objects (or objects that behave like files)\n\
2040 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002041\n\
2042last_type -- type of last uncaught exception\n\
2043last_value -- value of last uncaught exception\n\
2044last_traceback -- traceback of last uncaught exception\n\
2045 These three are only available in an interactive session after a\n\
2046 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002047"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002048)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002049/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002050PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00002051"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002052Static objects:\n\
2053\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002054builtin_module_names -- tuple of module names built into this interpreter\n\
2055copyright -- copyright notice pertaining to this interpreter\n\
2056exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02002057executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002058float_info -- a struct sequence with information about the float implementation.\n\
2059float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01002060hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002061hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04002062implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00002063int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00002064maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02002065maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002066platform -- platform identifier\n\
2067prefix -- prefix used to find the Python library\n\
2068thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00002069version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00002070version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002071"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002072)
Steve Dowercc16be82016-09-08 10:35:16 -07002073#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002074/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002075PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002076"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002077winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002078"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002079)
Steve Dowercc16be82016-09-08 10:35:16 -07002080#endif /* MS_COREDLL */
2081#ifdef MS_WINDOWS
2082/* concatenating string here */
2083PyDoc_STR(
oldkaa0735f2018-02-02 16:52:55 +08002084"_enablelegacywindowsfsencoding -- [Windows only]\n\
Steve Dowercc16be82016-09-08 10:35:16 -07002085"
2086)
2087#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002088PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002089"__stdin__ -- the original stdin; don't touch!\n\
2090__stdout__ -- the original stdout; don't touch!\n\
2091__stderr__ -- the original stderr; don't touch!\n\
2092__displayhook__ -- the original displayhook; don't touch!\n\
2093__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002094\n\
2095Functions:\n\
2096\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002097displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002098excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002099exc_info() -- return thread-safe information about the current exception\n\
2100exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002101getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002102getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002103getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002104getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002105getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002106gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002107setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002108setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002109setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002110setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002111settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002112"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002113)
Fred Drakeccede592000-08-14 20:59:57 +00002114/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002115
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002116
2117PyDoc_STRVAR(flags__doc__,
2118"sys.flags\n\
2119\n\
2120Flags provided through command line arguments or environment vars.");
2121
2122static PyTypeObject FlagsType;
2123
2124static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002125 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 {"inspect", "-i"},
2127 {"interactive", "-i"},
2128 {"optimize", "-O or -OO"},
2129 {"dont_write_bytecode", "-B"},
2130 {"no_user_site", "-s"},
2131 {"no_site", "-S"},
2132 {"ignore_environment", "-E"},
2133 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 /* {"unbuffered", "-u"}, */
2135 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002136 {"bytes_warning", "-b"},
2137 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002138 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002139 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002140 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002141 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002143};
2144
2145static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 "sys.flags", /* name */
2147 flags__doc__, /* doc */
2148 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002149 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002150};
2151
2152static PyObject*
2153make_flags(void)
2154{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002155 int pos = 0;
2156 PyObject *seq;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002157 const _PyCoreConfig *config = &_PyInterpreterState_GET_UNSAFE()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002158
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 seq = PyStructSequence_New(&FlagsType);
2160 if (seq == NULL)
2161 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002162
2163#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002165
Victor Stinnerfbca9082018-08-30 00:50:45 +02002166 SetFlag(config->parser_debug);
2167 SetFlag(config->inspect);
2168 SetFlag(config->interactive);
2169 SetFlag(config->optimization_level);
2170 SetFlag(!config->write_bytecode);
2171 SetFlag(!config->user_site_directory);
2172 SetFlag(!config->site_import);
2173 SetFlag(!config->use_environment);
2174 SetFlag(config->verbose);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002175 /* SetFlag(saw_unbuffered_flag); */
2176 /* SetFlag(skipfirstline); */
Victor Stinnerfbca9082018-08-30 00:50:45 +02002177 SetFlag(config->bytes_warning);
2178 SetFlag(config->quiet);
2179 SetFlag(config->use_hash_seed == 0 || config->hash_seed != 0);
2180 SetFlag(config->isolated);
2181 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(config->dev_mode));
2182 SetFlag(config->utf8_mode);
Victor Stinner91106cd2017-12-13 12:29:09 +01002183#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002184
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002185 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002186 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002187 return NULL;
2188 }
2189 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002190}
2191
Eric Smith0e5b5622009-02-06 01:32:42 +00002192PyDoc_STRVAR(version_info__doc__,
2193"sys.version_info\n\
2194\n\
2195Version information as a named tuple.");
2196
2197static PyTypeObject VersionInfoType;
2198
2199static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002200 {"major", "Major release number"},
2201 {"minor", "Minor release number"},
2202 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002203 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002204 {"serial", "Serial release number"},
2205 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002206};
2207
2208static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002209 "sys.version_info", /* name */
2210 version_info__doc__, /* doc */
2211 version_info_fields, /* fields */
2212 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002213};
2214
2215static PyObject *
2216make_version_info(void)
2217{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002218 PyObject *version_info;
2219 char *s;
2220 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002221
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002222 version_info = PyStructSequence_New(&VersionInfoType);
2223 if (version_info == NULL) {
2224 return NULL;
2225 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 /*
2228 * These release level checks are mutually exclusive and cover
2229 * the field, so don't get too fancy with the pre-processor!
2230 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002231#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002232 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002233#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002235#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002236 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002237#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002239#endif
2240
2241#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002242 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002243#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002245
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002246 SetIntItem(PY_MAJOR_VERSION);
2247 SetIntItem(PY_MINOR_VERSION);
2248 SetIntItem(PY_MICRO_VERSION);
2249 SetStrItem(s);
2250 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002251#undef SetIntItem
2252#undef SetStrItem
2253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002254 if (PyErr_Occurred()) {
2255 Py_CLEAR(version_info);
2256 return NULL;
2257 }
2258 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002259}
2260
Brett Cannon3adc7b72012-07-09 14:22:12 -04002261/* sys.implementation values */
2262#define NAME "cpython"
2263const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002264#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2265#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002266#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002267const char *_PySys_ImplCacheTag = TAG;
2268#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002269#undef MAJOR
2270#undef MINOR
2271#undef TAG
2272
Barry Warsaw409da152012-06-03 16:18:47 -04002273static PyObject *
2274make_impl_info(PyObject *version_info)
2275{
2276 int res;
2277 PyObject *impl_info, *value, *ns;
2278
2279 impl_info = PyDict_New();
2280 if (impl_info == NULL)
2281 return NULL;
2282
2283 /* populate the dict */
2284
Brett Cannon3adc7b72012-07-09 14:22:12 -04002285 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002286 if (value == NULL)
2287 goto error;
2288 res = PyDict_SetItemString(impl_info, "name", value);
2289 Py_DECREF(value);
2290 if (res < 0)
2291 goto error;
2292
Brett Cannon3adc7b72012-07-09 14:22:12 -04002293 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002294 if (value == NULL)
2295 goto error;
2296 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2297 Py_DECREF(value);
2298 if (res < 0)
2299 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002300
2301 res = PyDict_SetItemString(impl_info, "version", version_info);
2302 if (res < 0)
2303 goto error;
2304
2305 value = PyLong_FromLong(PY_VERSION_HEX);
2306 if (value == NULL)
2307 goto error;
2308 res = PyDict_SetItemString(impl_info, "hexversion", value);
2309 Py_DECREF(value);
2310 if (res < 0)
2311 goto error;
2312
doko@ubuntu.com55532312016-06-14 08:55:19 +02002313#ifdef MULTIARCH
2314 value = PyUnicode_FromString(MULTIARCH);
2315 if (value == NULL)
2316 goto error;
2317 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2318 Py_DECREF(value);
2319 if (res < 0)
2320 goto error;
2321#endif
2322
Barry Warsaw409da152012-06-03 16:18:47 -04002323 /* dict ready */
2324
2325 ns = _PyNamespace_New(impl_info);
2326 Py_DECREF(impl_info);
2327 return ns;
2328
2329error:
2330 Py_CLEAR(impl_info);
2331 return NULL;
2332}
2333
Martin v. Löwis1a214512008-06-11 05:26:20 +00002334static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 PyModuleDef_HEAD_INIT,
2336 "sys",
2337 sys_doc,
2338 -1, /* multiple "initialization" just copies the module dict. */
2339 sys_methods,
2340 NULL,
2341 NULL,
2342 NULL,
2343 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002344};
2345
Eric Snow6b4be192017-05-22 21:36:03 -07002346/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002347#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002348 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002349 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002350 if (v == NULL) { \
2351 goto err_occurred; \
2352 } \
Victor Stinner58049602013-07-22 22:40:00 +02002353 res = PyDict_SetItemString(sysdict, key, v); \
2354 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002355 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002356 } \
2357 } while (0)
2358#define SET_SYS_FROM_STRING(key, value) \
2359 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002360 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002361 if (v == NULL) { \
2362 goto err_occurred; \
2363 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002364 res = PyDict_SetItemString(sysdict, key, v); \
2365 Py_DECREF(v); \
2366 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002367 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002368 } \
2369 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002370
Victor Stinnerab672812019-01-23 15:04:40 +01002371static _PyInitError
2372_PySys_InitCore(PyObject *sysdict)
Eric Snow6b4be192017-05-22 21:36:03 -07002373{
Victor Stinnerab672812019-01-23 15:04:40 +01002374 PyObject *version_info;
Eric Snow6b4be192017-05-22 21:36:03 -07002375 int res;
2376
Nick Coghland6009512014-11-20 21:39:37 +10002377 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002378
Victor Stinner8fea2522013-10-27 17:15:42 +01002379 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2380 PyDict_GetItemString(sysdict, "displayhook"));
2381 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2382 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002383 SET_SYS_FROM_STRING_BORROW(
2384 "__breakpointhook__",
2385 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002386 SET_SYS_FROM_STRING("version",
2387 PyUnicode_FromString(Py_GetVersion()));
2388 SET_SYS_FROM_STRING("hexversion",
2389 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002390 SET_SYS_FROM_STRING("_git",
2391 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2392 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002393 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002394 SET_SYS_FROM_STRING("api_version",
2395 PyLong_FromLong(PYTHON_API_VERSION));
2396 SET_SYS_FROM_STRING("copyright",
2397 PyUnicode_FromString(Py_GetCopyright()));
2398 SET_SYS_FROM_STRING("platform",
2399 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002400 SET_SYS_FROM_STRING("maxsize",
2401 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2402 SET_SYS_FROM_STRING("float_info",
2403 PyFloat_GetInfo());
2404 SET_SYS_FROM_STRING("int_info",
2405 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002406 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002407 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002408 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2409 goto type_init_failed;
2410 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002411 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002412 SET_SYS_FROM_STRING("hash_info",
2413 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002415 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002416 SET_SYS_FROM_STRING("builtin_module_names",
2417 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002418#if PY_BIG_ENDIAN
2419 SET_SYS_FROM_STRING("byteorder",
2420 PyUnicode_FromString("big"));
2421#else
2422 SET_SYS_FROM_STRING("byteorder",
2423 PyUnicode_FromString("little"));
2424#endif
Fred Drake099325e2000-08-14 15:47:03 +00002425
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002426#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002427 SET_SYS_FROM_STRING("dllhandle",
2428 PyLong_FromVoidPtr(PyWin_DLLhModule));
2429 SET_SYS_FROM_STRING("winver",
2430 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002431#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002432#ifdef ABIFLAGS
2433 SET_SYS_FROM_STRING("abiflags",
2434 PyUnicode_FromString(ABIFLAGS));
2435#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002436
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002437 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002438 if (VersionInfoType.tp_name == NULL) {
2439 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002440 &version_info_desc) < 0) {
2441 goto type_init_failed;
2442 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002443 }
Barry Warsaw409da152012-06-03 16:18:47 -04002444 version_info = make_version_info();
2445 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002446 /* prevent user from creating new instances */
2447 VersionInfoType.tp_init = NULL;
2448 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002449 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2450 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2451 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002452
Barry Warsaw409da152012-06-03 16:18:47 -04002453 /* implementation */
2454 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2455
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002456 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002457 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002458 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2459 goto type_init_failed;
2460 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002461 }
Eric Snow6b4be192017-05-22 21:36:03 -07002462 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002463 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002464
2465#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002466 /* getwindowsversion */
2467 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002468 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002469 &windows_version_desc) < 0) {
2470 goto type_init_failed;
2471 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 /* prevent user from creating new instances */
2473 WindowsVersionType.tp_init = NULL;
2474 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002475 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002476 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002477 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002478 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002479 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002480#endif
2481
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002483#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 SET_SYS_FROM_STRING("float_repr_style",
2485 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002486#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002487 SET_SYS_FROM_STRING("float_repr_style",
2488 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002489#endif
2490
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002491 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002492
Yury Selivanoveb636452016-09-08 22:01:51 -07002493 /* initialize asyncgen_hooks */
2494 if (AsyncGenHooksType.tp_name == NULL) {
2495 if (PyStructSequence_InitType2(
2496 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002497 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002498 }
2499 }
2500
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002501 if (PyErr_Occurred()) {
2502 goto err_occurred;
2503 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002504 return _Py_INIT_OK();
2505
2506type_init_failed:
2507 return _Py_INIT_ERR("failed to initialize a type");
2508
2509err_occurred:
2510 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002511}
2512
Eric Snow6b4be192017-05-22 21:36:03 -07002513#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002514
2515/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002516#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2517 do { \
2518 PyObject *v = (value); \
2519 if (v == NULL) \
2520 return -1; \
2521 res = PyDict_SetItemString(sysdict, key, v); \
2522 Py_DECREF(v); \
2523 if (res < 0) { \
2524 return res; \
2525 } \
2526 } while (0)
2527
2528int
Victor Stinnerab672812019-01-23 15:04:40 +01002529_PySys_InitMain(PyInterpreterState *interp)
Eric Snow6b4be192017-05-22 21:36:03 -07002530{
Victor Stinnerab672812019-01-23 15:04:40 +01002531 PyObject *sysdict = interp->sysdict;
Victor Stinnerfbca9082018-08-30 00:50:45 +02002532 const _PyCoreConfig *core_config = &interp->core_config;
2533 const _PyMainInterpreterConfig *config = &interp->config;
Eric Snow6b4be192017-05-22 21:36:03 -07002534 int res;
2535
Victor Stinner41264f12017-12-15 02:05:29 +01002536 /* _PyMainInterpreterConfig_Read() must set all these variables */
2537 assert(config->module_search_path != NULL);
2538 assert(config->executable != NULL);
2539 assert(config->prefix != NULL);
2540 assert(config->base_prefix != NULL);
2541 assert(config->exec_prefix != NULL);
2542 assert(config->base_exec_prefix != NULL);
2543
Victor Stinner37cd9822018-11-16 11:55:35 +01002544#define COPY_LIST(KEY, ATTR) \
2545 do { \
Victor Stinnerab672812019-01-23 15:04:40 +01002546 assert(PyList_Check(ATTR)); \
2547 PyObject *list = PyList_GetSlice(ATTR, 0, PyList_GET_SIZE(ATTR)); \
Victor Stinner37cd9822018-11-16 11:55:35 +01002548 if (list == NULL) { \
2549 return -1; \
2550 } \
2551 SET_SYS_FROM_STRING_BORROW(KEY, list); \
2552 Py_DECREF(list); \
2553 } while (0)
2554
Victor Stinnerab672812019-01-23 15:04:40 +01002555 COPY_LIST("path", config->module_search_path);
Victor Stinner37cd9822018-11-16 11:55:35 +01002556
Victor Stinner41264f12017-12-15 02:05:29 +01002557 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2558 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2559 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2560 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2561 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2562
Carl Meyerb193fa92018-06-15 22:40:56 -06002563 if (config->pycache_prefix != NULL) {
2564 SET_SYS_FROM_STRING_BORROW("pycache_prefix", config->pycache_prefix);
2565 } else {
2566 PyDict_SetItemString(sysdict, "pycache_prefix", Py_None);
2567 }
2568
Victor Stinner41264f12017-12-15 02:05:29 +01002569 if (config->argv != NULL) {
2570 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2571 }
2572 if (config->warnoptions != NULL) {
Victor Stinnerab672812019-01-23 15:04:40 +01002573 COPY_LIST("warnoptions", config->warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002574 }
2575 if (config->xoptions != NULL) {
Victor Stinner37cd9822018-11-16 11:55:35 +01002576 PyObject *dict = PyDict_Copy(config->xoptions);
2577 if (dict == NULL) {
2578 return -1;
2579 }
2580 SET_SYS_FROM_STRING_BORROW("_xoptions", dict);
2581 Py_DECREF(dict);
Victor Stinner41264f12017-12-15 02:05:29 +01002582 }
2583
Victor Stinner37cd9822018-11-16 11:55:35 +01002584#undef COPY_LIST
2585
Eric Snow6b4be192017-05-22 21:36:03 -07002586 /* Set flags to their final values */
2587 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2588 /* prevent user from creating new instances */
2589 FlagsType.tp_init = NULL;
2590 FlagsType.tp_new = NULL;
2591 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2592 if (res < 0) {
2593 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2594 return res;
2595 }
2596 PyErr_Clear();
2597 }
2598
2599 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
Victor Stinnerfbca9082018-08-30 00:50:45 +02002600 PyBool_FromLong(!core_config->write_bytecode));
Eric Snow6b4be192017-05-22 21:36:03 -07002601
Eric Snowdae02762017-09-14 00:35:58 -07002602 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002603 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002604
Eric Snowdae02762017-09-14 00:35:58 -07002605 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002606 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002607
Nick Coghlanbc77eff2018-03-25 20:44:30 +10002608 /* Transfer any sys.warnoptions and sys._xoptions set directly
2609 * by an embedding application from the linked list to the module. */
2610 if (_PySys_ReadPreInitOptions() != 0)
2611 return -1;
2612
Eric Snow6b4be192017-05-22 21:36:03 -07002613 if (PyErr_Occurred())
2614 return -1;
2615 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002616
2617err_occurred:
2618 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002619}
2620
Victor Stinner41264f12017-12-15 02:05:29 +01002621#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002622#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002623
Victor Stinnerab672812019-01-23 15:04:40 +01002624
2625/* Set up a preliminary stderr printer until we have enough
2626 infrastructure for the io module in place.
2627
2628 Use UTF-8/surrogateescape and ignore EAGAIN errors. */
2629_PyInitError
2630_PySys_SetPreliminaryStderr(PyObject *sysdict)
2631{
2632 PyObject *pstderr = PyFile_NewStdPrinter(fileno(stderr));
2633 if (pstderr == NULL) {
2634 goto error;
2635 }
2636 if (_PyDict_SetItemId(sysdict, &PyId_stderr, pstderr) < 0) {
2637 goto error;
2638 }
2639 if (PyDict_SetItemString(sysdict, "__stderr__", pstderr) < 0) {
2640 goto error;
2641 }
2642 Py_DECREF(pstderr);
2643 return _Py_INIT_OK();
2644
2645error:
2646 Py_XDECREF(pstderr);
2647 return _Py_INIT_ERR("can't set preliminary stderr");
2648}
2649
2650
2651/* Create sys module without all attributes: _PySys_InitMain() should be called
2652 later to add remaining attributes. */
2653_PyInitError
2654_PySys_Create(PyInterpreterState *interp, PyObject **sysmod_p)
2655{
2656 PyObject *modules = PyDict_New();
2657 if (modules == NULL) {
2658 return _Py_INIT_ERR("can't make modules dictionary");
2659 }
2660 interp->modules = modules;
2661
2662 PyObject *sysmod = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
2663 if (sysmod == NULL) {
2664 return _Py_INIT_ERR("failed to create a module object");
2665 }
2666
2667 PyObject *sysdict = PyModule_GetDict(sysmod);
2668 if (sysdict == NULL) {
2669 return _Py_INIT_ERR("can't initialize sys dict");
2670 }
2671 Py_INCREF(sysdict);
2672 interp->sysdict = sysdict;
2673
2674 if (PyDict_SetItemString(sysdict, "modules", interp->modules) < 0) {
2675 return _Py_INIT_ERR("can't initialize sys module");
2676 }
2677
2678 _PyInitError err = _PySys_SetPreliminaryStderr(sysdict);
2679 if (_Py_INIT_FAILED(err)) {
2680 return err;
2681 }
2682
2683 err = _PySys_InitCore(sysdict);
2684 if (_Py_INIT_FAILED(err)) {
2685 return err;
2686 }
2687
2688 _PyImport_FixupBuiltin(sysmod, "sys", interp->modules);
2689
2690 *sysmod_p = sysmod;
2691 return _Py_INIT_OK();
2692}
2693
2694
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002695static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002696makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002697{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002698 int i, n;
2699 const wchar_t *p;
2700 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002702 n = 1;
2703 p = path;
2704 while ((p = wcschr(p, delim)) != NULL) {
2705 n++;
2706 p++;
2707 }
2708 v = PyList_New(n);
2709 if (v == NULL)
2710 return NULL;
2711 for (i = 0; ; i++) {
2712 p = wcschr(path, delim);
2713 if (p == NULL)
2714 p = path + wcslen(path); /* End of string */
2715 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2716 if (w == NULL) {
2717 Py_DECREF(v);
2718 return NULL;
2719 }
Zackery Spytz99d56b52018-12-08 07:16:55 -07002720 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 if (*p == '\0')
2722 break;
2723 path = p+1;
2724 }
2725 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002726}
2727
2728void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002729PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyObject *v;
2732 if ((v = makepathobject(path, DELIM)) == NULL)
2733 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002734 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002735 Py_FatalError("can't assign sys.path");
2736 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002737}
2738
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002739static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002740makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002741{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 PyObject *av;
2743 if (argc <= 0 || argv == NULL) {
2744 /* Ensure at least one (empty) argument is seen */
2745 static wchar_t *empty_argv[1] = {L""};
2746 argv = empty_argv;
2747 argc = 1;
2748 }
2749 av = PyList_New(argc);
2750 if (av != NULL) {
2751 int i;
2752 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 if (v == NULL) {
2755 Py_DECREF(av);
2756 av = NULL;
2757 break;
2758 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002759 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002760 }
2761 }
2762 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002763}
2764
Victor Stinner11a247d2017-12-13 21:05:57 +01002765void
2766PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002767{
2768 PyObject *av = makeargvobject(argc, argv);
2769 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002770 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002771 }
2772 if (PySys_SetObject("argv", av) != 0) {
2773 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002774 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002775 }
2776 Py_DECREF(av);
2777
2778 if (updatepath) {
2779 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2780 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002781 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2782 if (argv0 == NULL) {
2783 Py_FatalError("can't compute path0 from argv");
2784 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002785
Victor Stinner11a247d2017-12-13 21:05:57 +01002786 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2787 if (sys_path != NULL) {
2788 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2789 Py_DECREF(argv0);
2790 Py_FatalError("can't prepend path0 to sys.path");
2791 }
2792 }
2793 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002794 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002795}
Guido van Rossuma890e681998-05-12 14:59:24 +00002796
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002797void
2798PySys_SetArgv(int argc, wchar_t **argv)
2799{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002800 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002801}
2802
Victor Stinner14284c22010-04-23 12:02:30 +00002803/* Reimplementation of PyFile_WriteString() no calling indirectly
2804 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2805
2806static int
Victor Stinner79766632010-08-16 17:36:42 +00002807sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002808{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002809 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002810 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002811
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002812 if (file == NULL)
2813 return -1;
2814
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002815 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002816 if (writer == NULL)
2817 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002818
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002819 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002820 if (result == NULL) {
2821 goto error;
2822 } else {
2823 err = 0;
2824 goto finally;
2825 }
Victor Stinner14284c22010-04-23 12:02:30 +00002826
2827error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002828 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002829finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002830 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002831 Py_XDECREF(result);
2832 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002833}
2834
Victor Stinner79766632010-08-16 17:36:42 +00002835static int
2836sys_pyfile_write(const char *text, PyObject *file)
2837{
2838 PyObject *unicode = NULL;
2839 int err;
2840
2841 if (file == NULL)
2842 return -1;
2843
2844 unicode = PyUnicode_FromString(text);
2845 if (unicode == NULL)
2846 return -1;
2847
2848 err = sys_pyfile_write_unicode(unicode, file);
2849 Py_DECREF(unicode);
2850 return err;
2851}
Guido van Rossuma890e681998-05-12 14:59:24 +00002852
2853/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2854 Adapted from code submitted by Just van Rossum.
2855
2856 PySys_WriteStdout(format, ...)
2857 PySys_WriteStderr(format, ...)
2858
2859 The first function writes to sys.stdout; the second to sys.stderr. When
2860 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002861 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002862
Victor Stinner14284c22010-04-23 12:02:30 +00002863 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002864 signal handlers: they may raise a new exception whereas sys_write()
2865 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002866
Guido van Rossuma890e681998-05-12 14:59:24 +00002867 Both take a printf-style format string as their first argument followed
2868 by a variable length argument list determined by the format string.
2869
2870 *** WARNING ***
2871
2872 The format should limit the total size of the formatted output string to
2873 1000 bytes. In particular, this means that no unrestricted "%s" formats
2874 should occur; these should be limited using "%.<N>s where <N> is a
2875 decimal number calculated so that <N> plus the maximum size of other
2876 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2877 which can print hundreds of digits for very large numbers.
2878
2879 */
2880
2881static void
Victor Stinner09054372013-11-06 22:41:44 +01002882sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002883{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002884 PyObject *file;
2885 PyObject *error_type, *error_value, *error_traceback;
2886 char buffer[1001];
2887 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002889 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002890 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002891 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2892 if (sys_pyfile_write(buffer, file) != 0) {
2893 PyErr_Clear();
2894 fputs(buffer, fp);
2895 }
2896 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2897 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002898 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002899 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002900 }
2901 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002902}
2903
2904void
Guido van Rossuma890e681998-05-12 14:59:24 +00002905PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002906{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002907 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002908
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002909 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002910 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002911 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002912}
2913
2914void
Guido van Rossuma890e681998-05-12 14:59:24 +00002915PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002917 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002918
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002919 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002920 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002921 va_end(va);
2922}
2923
2924static void
Victor Stinner09054372013-11-06 22:41:44 +01002925sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002926{
2927 PyObject *file, *message;
2928 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002929 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002930
2931 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002932 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002933 message = PyUnicode_FromFormatV(format, va);
2934 if (message != NULL) {
2935 if (sys_pyfile_write_unicode(message, file) != 0) {
2936 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002937 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002938 if (utf8 != NULL)
2939 fputs(utf8, fp);
2940 }
2941 Py_DECREF(message);
2942 }
2943 PyErr_Restore(error_type, error_value, error_traceback);
2944}
2945
2946void
2947PySys_FormatStdout(const char *format, ...)
2948{
2949 va_list va;
2950
2951 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002952 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002953 va_end(va);
2954}
2955
2956void
2957PySys_FormatStderr(const char *format, ...)
2958{
2959 va_list va;
2960
2961 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002962 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002963 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002964}