blob: d87b4e2c01b36be8499eef57ef19586079ac1fa1 [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"
Eric Snow2ebc5ce2017-09-07 23:51:28 -060018#include "internal/pystate.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000019#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000020#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020021#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossume2437a11992-03-23 18:20:18 +000023#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020024#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000025
Mark Hammond8696ebc2002-10-08 02:44:31 +000026#ifdef MS_WINDOWS
27#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000028#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000029#endif /* MS_WINDOWS */
30
Guido van Rossum9b38a141996-09-11 23:12:24 +000031#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000032extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000033/* A string loaded from the DLL at startup: */
34extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000035#endif
36
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -080037/*[clinic input]
38module sys
39[clinic start generated code]*/
40/*[clinic end generated code: output=da39a3ee5e6b4b0d input=3726b388feee8cea]*/
41
42#include "clinic/sysmodule.c.h"
43
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(_);
45_Py_IDENTIFIER(__sizeof__);
Eric Snowdae02762017-09-14 00:35:58 -070046_Py_IDENTIFIER(_xoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010047_Py_IDENTIFIER(buffer);
48_Py_IDENTIFIER(builtins);
49_Py_IDENTIFIER(encoding);
50_Py_IDENTIFIER(path);
51_Py_IDENTIFIER(stdout);
52_Py_IDENTIFIER(stderr);
Eric Snowdae02762017-09-14 00:35:58 -070053_Py_IDENTIFIER(warnoptions);
Victor Stinnerbd303c12013-11-07 23:07:29 +010054_Py_IDENTIFIER(write);
55
Guido van Rossum65bf9f21997-04-29 18:33:38 +000056PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010057_PySys_GetObjectId(_Py_Identifier *key)
58{
59 PyThreadState *tstate = PyThreadState_GET();
60 PyObject *sd = tstate->interp->sysdict;
61 if (sd == NULL)
62 return NULL;
63 return _PyDict_GetItemId(sd, key);
64}
65
66PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000067PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000069 PyThreadState *tstate = PyThreadState_GET();
70 PyObject *sd = tstate->interp->sysdict;
71 if (sd == NULL)
72 return NULL;
73 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074}
75
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000076int
Victor Stinnerd67bd452013-11-06 22:36:40 +010077_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
78{
79 PyThreadState *tstate = PyThreadState_GET();
80 PyObject *sd = tstate->interp->sysdict;
81 if (v == NULL) {
82 if (_PyDict_GetItemId(sd, key) == NULL)
83 return 0;
84 else
85 return _PyDict_DelItemId(sd, key);
86 }
87 else
88 return _PyDict_SetItemId(sd, key, v);
89}
90
91int
Neal Norwitzf3081322007-08-25 00:32:45 +000092PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000094 PyThreadState *tstate = PyThreadState_GET();
95 PyObject *sd = tstate->interp->sysdict;
96 if (v == NULL) {
97 if (PyDict_GetItemString(sd, name) == NULL)
98 return 0;
99 else
100 return PyDict_DelItemString(sd, name);
101 }
102 else
103 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000104}
105
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400106static PyObject *
Serhiy Storchakaa5552f02017-12-15 13:11:11 +0200107sys_breakpointhook(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *keywords)
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400108{
109 assert(!PyErr_Occurred());
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700110 char *envar = Py_GETENV("PYTHONBREAKPOINT");
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400111
112 if (envar == NULL || strlen(envar) == 0) {
113 envar = "pdb.set_trace";
114 }
115 else if (!strcmp(envar, "0")) {
116 /* The breakpoint is explicitly no-op'd. */
117 Py_RETURN_NONE;
118 }
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700119 /* According to POSIX the string returned by getenv() might be invalidated
120 * or the string content might be overwritten by a subsequent call to
121 * getenv(). Since importing a module can performs the getenv() calls,
122 * we need to save a copy of envar. */
123 envar = _PyMem_RawStrdup(envar);
124 if (envar == NULL) {
125 PyErr_NoMemory();
126 return NULL;
127 }
Serhiy Storchaka4ae06c52017-12-12 13:55:04 +0200128 const char *last_dot = strrchr(envar, '.');
129 const char *attrname = NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400130 PyObject *modulepath = NULL;
131
132 if (last_dot == NULL) {
133 /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */
134 modulepath = PyUnicode_FromString("builtins");
135 attrname = envar;
136 }
Miss Islington (bot)97d6a562019-01-15 03:45:57 -0800137 else if (last_dot != envar) {
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400138 /* Split on the last dot; */
139 modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar);
140 attrname = last_dot + 1;
141 }
Miss Islington (bot)97d6a562019-01-15 03:45:57 -0800142 else {
143 goto warn;
144 }
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400145 if (modulepath == NULL) {
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700146 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400147 return NULL;
148 }
149
150 PyObject *fromlist = Py_BuildValue("(s)", attrname);
151 if (fromlist == NULL) {
152 Py_DECREF(modulepath);
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700153 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400154 return NULL;
155 }
156 PyObject *module = PyImport_ImportModuleLevelObject(
157 modulepath, NULL, NULL, fromlist, 0);
158 Py_DECREF(modulepath);
159 Py_DECREF(fromlist);
160
161 if (module == NULL) {
Miss Islington (bot)97d6a562019-01-15 03:45:57 -0800162 if (PyErr_ExceptionMatches(PyExc_ImportError)) {
163 goto warn;
164 }
165 PyMem_RawFree(envar);
166 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400167 }
168
169 PyObject *hook = PyObject_GetAttrString(module, attrname);
170 Py_DECREF(module);
171
172 if (hook == NULL) {
Miss Islington (bot)97d6a562019-01-15 03:45:57 -0800173 if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
174 goto warn;
175 }
176 PyMem_RawFree(envar);
177 return NULL;
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400178 }
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700179 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400180 PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords);
181 Py_DECREF(hook);
182 return retval;
183
Miss Islington (bot)97d6a562019-01-15 03:45:57 -0800184 warn:
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400185 /* If any of the imports went wrong, then warn and ignore. */
186 PyErr_Clear();
187 int status = PyErr_WarnFormat(
188 PyExc_RuntimeWarning, 0,
189 "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar);
Miss Islington (bot)6f4fbf82018-07-09 12:06:02 -0700190 PyMem_RawFree(envar);
Barry Warsaw36c1d1f2017-10-05 12:11:18 -0400191 if (status < 0) {
192 /* Printing the warning raised an exception. */
193 return NULL;
194 }
195 /* The warning was (probably) issued. */
196 Py_RETURN_NONE;
197}
198
199PyDoc_STRVAR(breakpointhook_doc,
200"breakpointhook(*args, **kws)\n"
201"\n"
202"This hook function is called by built-in breakpoint().\n"
203);
204
Victor Stinner13d49ee2010-12-04 17:24:33 +0000205/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
206 error handler. If sys.stdout has a buffer attribute, use
207 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
208 sys.stdout.write(redecoded).
209
210 Helper function for sys_displayhook(). */
211static int
212sys_displayhook_unencodable(PyObject *outf, PyObject *o)
213{
214 PyObject *stdout_encoding = NULL;
215 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +0200216 const char *stdout_encoding_str;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000217 int ret;
218
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200219 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000220 if (stdout_encoding == NULL)
221 goto error;
Serhiy Storchaka06515832016-11-20 09:13:07 +0200222 stdout_encoding_str = PyUnicode_AsUTF8(stdout_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000223 if (stdout_encoding_str == NULL)
224 goto error;
225
226 repr_str = PyObject_Repr(o);
227 if (repr_str == NULL)
228 goto error;
229 encoded = PyUnicode_AsEncodedString(repr_str,
230 stdout_encoding_str,
231 "backslashreplace");
232 Py_DECREF(repr_str);
233 if (encoded == NULL)
234 goto error;
235
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200236 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000237 if (buffer) {
Victor Stinner7e425412016-12-09 00:36:19 +0100238 result = _PyObject_CallMethodIdObjArgs(buffer, &PyId_write, encoded, NULL);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000239 Py_DECREF(buffer);
240 Py_DECREF(encoded);
241 if (result == NULL)
242 goto error;
243 Py_DECREF(result);
244 }
245 else {
246 PyErr_Clear();
247 escaped_str = PyUnicode_FromEncodedObject(encoded,
248 stdout_encoding_str,
249 "strict");
250 Py_DECREF(encoded);
251 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
252 Py_DECREF(escaped_str);
253 goto error;
254 }
255 Py_DECREF(escaped_str);
256 }
257 ret = 0;
258 goto finally;
259
260error:
261 ret = -1;
262finally:
263 Py_XDECREF(stdout_encoding);
264 return ret;
265}
266
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000267static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000268sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000269{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000270 PyObject *outf;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100271 PyObject *builtins;
272 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000273 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000274
Eric Snow3f9eee62017-09-15 16:35:20 -0600275 builtins = _PyImport_GetModuleId(&PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 if (builtins == NULL) {
Miss Islington (bot)cdd8d4d2019-03-25 14:36:43 -0700277 if (!PyErr_Occurred()) {
278 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
279 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 return NULL;
281 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600282 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000284 /* Print value except if None */
285 /* After printing, also assign to '_' */
286 /* Before, set '_' to None to avoid recursion */
287 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200288 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200290 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100292 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000293 if (outf == NULL || outf == Py_None) {
294 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
295 return NULL;
296 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000297 if (PyFile_WriteObject(o, outf, 0) != 0) {
298 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
299 /* repr(o) is not encodable to sys.stdout.encoding with
300 * sys.stdout.errors error handler (which is probably 'strict') */
301 PyErr_Clear();
302 err = sys_displayhook_unencodable(outf, o);
303 if (err)
304 return NULL;
305 }
306 else {
307 return NULL;
308 }
309 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100310 if (newline == NULL) {
311 newline = PyUnicode_FromString("\n");
312 if (newline == NULL)
313 return NULL;
314 }
315 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200317 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000318 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200319 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000320}
321
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000322PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000323"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000324"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000325"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000326);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000327
328static PyObject *
329sys_excepthook(PyObject* self, PyObject* args)
330{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000331 PyObject *exc, *value, *tb;
332 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
333 return NULL;
334 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200335 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000336}
337
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000338PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000339"excepthook(exctype, value, traceback) -> None\n"
340"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000341"Handle an exception by displaying it with a traceback on sys.stderr.\n"
342);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000343
344static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000345sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000346{
Mark Shannonae3087c2017-10-22 22:41:51 +0100347 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 return Py_BuildValue(
349 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100350 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
351 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
352 err_info->exc_traceback != NULL ?
353 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000354}
355
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000356PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000357"exc_info() -> (type, value, traceback)\n\
358\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000359Return information about the most recent exception caught by an except\n\
360clause in the current stack frame or in an older stack frame."
361);
362
363static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000364sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000365{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000366 PyObject *exit_code = 0;
367 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
368 return NULL;
369 /* Raise SystemExit so callers may catch it or clean up. */
370 PyErr_SetObject(PyExc_SystemExit, exit_code);
371 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000372}
373
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000374PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000375"exit([status])\n\
376\n\
377Exit the interpreter by raising SystemExit(status).\n\
378If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300379If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000380If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000381exit status will be one (i.e., failure)."
382);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000383
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000384
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000385static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000386sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000389}
390
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000391PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000392"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000393\n\
394Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000395implementation."
396);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000397
398static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000399sys_getfilesystemencoding(PyObject *self)
400{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000401 if (Py_FileSystemDefaultEncoding)
402 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200403 PyErr_SetString(PyExc_RuntimeError,
404 "filesystem encoding is not initialized");
405 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000406}
407
408PyDoc_STRVAR(getfilesystemencoding_doc,
409"getfilesystemencoding() -> string\n\
410\n\
411Return the encoding used to convert Unicode filenames in\n\
412operating system filenames."
413);
414
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000415static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700416sys_getfilesystemencodeerrors(PyObject *self)
417{
418 if (Py_FileSystemDefaultEncodeErrors)
419 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
420 PyErr_SetString(PyExc_RuntimeError,
421 "filesystem encoding is not initialized");
422 return NULL;
423}
424
425PyDoc_STRVAR(getfilesystemencodeerrors_doc,
426 "getfilesystemencodeerrors() -> string\n\
427\n\
428Return the error mode used to convert Unicode filenames in\n\
429operating system filenames."
430);
431
432static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000433sys_intern(PyObject *self, PyObject *args)
434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyObject *s;
436 if (!PyArg_ParseTuple(args, "U:intern", &s))
437 return NULL;
438 if (PyUnicode_CheckExact(s)) {
439 Py_INCREF(s);
440 PyUnicode_InternInPlace(&s);
441 return s;
442 }
443 else {
444 PyErr_Format(PyExc_TypeError,
445 "can't intern %.400s", s->ob_type->tp_name);
446 return NULL;
447 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000448}
449
450PyDoc_STRVAR(intern_doc,
451"intern(string) -> string\n\
452\n\
453``Intern'' the given string. This enters the string in the (global)\n\
454table of interned strings whose purpose is to speed up dictionary lookups.\n\
455Return the string itself or the previously interned string object with the\n\
456same value.");
457
458
Fred Drake5755ce62001-06-27 19:19:46 +0000459/*
460 * Cached interned string objects used for calling the profile and
461 * trace functions. Initialized by trace_init().
462 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000463static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000464
465static int
466trace_init(void)
467{
Nick Coghlan5a851672017-09-08 10:14:16 +1000468 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200469 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000470 "c_call", "c_exception", "c_return",
471 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200472 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 PyObject *name;
474 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000475 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 if (whatstrings[i] == NULL) {
477 name = PyUnicode_InternFromString(whatnames[i]);
478 if (name == NULL)
479 return -1;
480 whatstrings[i] = name;
481 }
482 }
483 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000484}
485
486
487static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100488call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200492 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000493
Victor Stinner78da82b2016-08-20 01:22:57 +0200494 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200496 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100497
Victor Stinner78da82b2016-08-20 01:22:57 +0200498 stack[0] = (PyObject *)frame;
499 stack[1] = whatstrings[what];
500 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000501
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000502 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200503 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000504
Victor Stinner78da82b2016-08-20 01:22:57 +0200505 PyFrame_LocalsToFast(frame, 1);
506 if (result == NULL) {
507 PyTraceBack_Here(frame);
508 }
509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000511}
512
513static int
514profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (arg == NULL)
520 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100521 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000522 if (result == NULL) {
523 PyEval_SetProfile(NULL, NULL);
524 return -1;
525 }
526 Py_DECREF(result);
527 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000528}
529
530static int
531trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 PyObject *callback;
535 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (what == PyTrace_CALL)
538 callback = self;
539 else
540 callback = frame->f_trace;
541 if (callback == NULL)
542 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100543 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000544 if (result == NULL) {
545 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200546 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000547 return -1;
548 }
549 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300550 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000551 }
552 else {
553 Py_DECREF(result);
554 }
555 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000556}
Fred Draked0838392001-06-16 21:02:31 +0000557
Fred Drake8b4d01d2000-05-09 19:57:01 +0000558static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000559sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000560{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000561 if (trace_init() == -1)
562 return NULL;
563 if (args == Py_None)
564 PyEval_SetTrace(NULL, NULL);
565 else
566 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200567 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000568}
569
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000570PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000571"settrace(function)\n\
572\n\
573Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000574function call. See the debugger chapter in the library manual."
575);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000576
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000577static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000578sys_gettrace(PyObject *self, PyObject *args)
579{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 PyThreadState *tstate = PyThreadState_GET();
581 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000583 if (temp == NULL)
584 temp = Py_None;
585 Py_INCREF(temp);
586 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000587}
588
589PyDoc_STRVAR(gettrace_doc,
590"gettrace()\n\
591\n\
592Return the global debug tracing function set with sys.settrace.\n\
593See the debugger chapter in the library manual."
594);
595
596static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000597sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 if (trace_init() == -1)
600 return NULL;
601 if (args == Py_None)
602 PyEval_SetProfile(NULL, NULL);
603 else
604 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200605 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000606}
607
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000608PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000609"setprofile(function)\n\
610\n\
611Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000612and return. See the profiler chapter in the library manual."
613);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000614
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000615static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000616sys_getprofile(PyObject *self, PyObject *args)
617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 PyThreadState *tstate = PyThreadState_GET();
619 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 if (temp == NULL)
622 temp = Py_None;
623 Py_INCREF(temp);
624 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000625}
626
627PyDoc_STRVAR(getprofile_doc,
628"getprofile()\n\
629\n\
630Return the profiling function set with sys.setprofile.\n\
631See the profiler chapter in the library manual."
632);
633
634static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000635sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000636{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000637 if (PyErr_WarnEx(PyExc_DeprecationWarning,
638 "sys.getcheckinterval() and sys.setcheckinterval() "
639 "are deprecated. Use sys.setswitchinterval() "
640 "instead.", 1) < 0)
641 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600642 PyInterpreterState *interp = PyThreadState_GET()->interp;
643 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000644 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200645 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000646}
647
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000648PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000649"setcheckinterval(n)\n\
650\n\
651Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000652n instructions. This also affects how often thread switches occur."
653);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000654
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000655static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000656sys_getcheckinterval(PyObject *self, PyObject *args)
657{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000658 if (PyErr_WarnEx(PyExc_DeprecationWarning,
659 "sys.getcheckinterval() and sys.setcheckinterval() "
660 "are deprecated. Use sys.getswitchinterval() "
661 "instead.", 1) < 0)
662 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600663 PyInterpreterState *interp = PyThreadState_GET()->interp;
664 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000665}
666
667PyDoc_STRVAR(getcheckinterval_doc,
668"getcheckinterval() -> current check interval; see setcheckinterval()."
669);
670
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000671static PyObject *
672sys_setswitchinterval(PyObject *self, PyObject *args)
673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000674 double d;
675 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
676 return NULL;
677 if (d <= 0.0) {
678 PyErr_SetString(PyExc_ValueError,
679 "switch interval must be strictly positive");
680 return NULL;
681 }
682 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200683 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000684}
685
686PyDoc_STRVAR(setswitchinterval_doc,
687"setswitchinterval(n)\n\
688\n\
689Set the ideal thread switching delay inside the Python interpreter\n\
690The actual frequency of switching threads can be lower if the\n\
691interpreter executes long sequences of uninterruptible code\n\
692(this is implementation-specific and workload-dependent).\n\
693\n\
694The parameter must represent the desired switching delay in seconds\n\
695A typical value is 0.005 (5 milliseconds)."
696);
697
698static PyObject *
699sys_getswitchinterval(PyObject *self, PyObject *args)
700{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000702}
703
704PyDoc_STRVAR(getswitchinterval_doc,
705"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
706);
707
Tim Peterse5e065b2003-07-06 18:36:54 +0000708static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000709sys_setrecursionlimit(PyObject *self, PyObject *args)
710{
Victor Stinner50856d52015-10-13 00:11:21 +0200711 int new_limit, mark;
712 PyThreadState *tstate;
713
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000714 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
715 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200716
717 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200719 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000720 return NULL;
721 }
Victor Stinner50856d52015-10-13 00:11:21 +0200722
723 /* Issue #25274: When the recursion depth hits the recursion limit in
724 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
725 set to 1 and a RecursionError is raised. The overflowed flag is reset
726 to 0 when the recursion depth goes below the low-water mark: see
727 Py_LeaveRecursiveCall().
728
729 Reject too low new limit if the current recursion depth is higher than
730 the new low-water mark. Otherwise it may not be possible anymore to
731 reset the overflowed flag to 0. */
732 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
733 tstate = PyThreadState_GET();
734 if (tstate->recursion_depth >= mark) {
735 PyErr_Format(PyExc_RecursionError,
736 "cannot set the recursion limit to %i at "
737 "the recursion depth %i: the limit is too low",
738 new_limit, tstate->recursion_depth);
739 return NULL;
740 }
741
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000742 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200743 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000744}
745
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800746/*[clinic input]
747sys.set_coroutine_origin_tracking_depth
748
749 depth: int
750
751Enable or disable origin tracking for coroutine objects in this thread.
752
753Coroutine objects will track 'depth' frames of traceback information about
754where they came from, available in their cr_origin attribute. Set depth of 0
755to disable.
756[clinic start generated code]*/
757
758static PyObject *
759sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
760/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
761{
762 if (depth < 0) {
763 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
764 return NULL;
765 }
766 _PyEval_SetCoroutineOriginTrackingDepth(depth);
767 Py_RETURN_NONE;
768}
769
770/*[clinic input]
771sys.get_coroutine_origin_tracking_depth -> int
772
773Check status of origin tracking for coroutine objects in this thread.
774[clinic start generated code]*/
775
776static int
777sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
778/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
779{
780 return _PyEval_GetCoroutineOriginTrackingDepth();
781}
782
Yury Selivanov75445082015-05-11 22:57:16 -0400783static PyObject *
784sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
785{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800786 if (PyErr_WarnEx(PyExc_DeprecationWarning,
787 "set_coroutine_wrapper is deprecated", 1) < 0) {
788 return NULL;
789 }
790
Yury Selivanov75445082015-05-11 22:57:16 -0400791 if (wrapper != Py_None) {
792 if (!PyCallable_Check(wrapper)) {
793 PyErr_Format(PyExc_TypeError,
794 "callable expected, got %.50s",
795 Py_TYPE(wrapper)->tp_name);
796 return NULL;
797 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400798 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400799 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400800 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400801 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400802 }
Yury Selivanov75445082015-05-11 22:57:16 -0400803 Py_RETURN_NONE;
804}
805
806PyDoc_STRVAR(set_coroutine_wrapper_doc,
807"set_coroutine_wrapper(wrapper)\n\
808\n\
809Set a wrapper for coroutine objects."
810);
811
812static PyObject *
813sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
814{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800815 if (PyErr_WarnEx(PyExc_DeprecationWarning,
816 "get_coroutine_wrapper is deprecated", 1) < 0) {
817 return NULL;
818 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400819 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400820 if (wrapper == NULL) {
821 wrapper = Py_None;
822 }
823 Py_INCREF(wrapper);
824 return wrapper;
825}
826
827PyDoc_STRVAR(get_coroutine_wrapper_doc,
828"get_coroutine_wrapper()\n\
829\n\
830Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
831);
832
833
Yury Selivanoveb636452016-09-08 22:01:51 -0700834static PyTypeObject AsyncGenHooksType;
835
836PyDoc_STRVAR(asyncgen_hooks_doc,
837"asyncgen_hooks\n\
838\n\
839A struct sequence providing information about asynhronous\n\
840generators hooks. The attributes are read only.");
841
842static PyStructSequence_Field asyncgen_hooks_fields[] = {
843 {"firstiter", "Hook to intercept first iteration"},
844 {"finalizer", "Hook to intercept finalization"},
845 {0}
846};
847
848static PyStructSequence_Desc asyncgen_hooks_desc = {
849 "asyncgen_hooks", /* name */
850 asyncgen_hooks_doc, /* doc */
851 asyncgen_hooks_fields , /* fields */
852 2
853};
854
855
856static PyObject *
857sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
858{
859 static char *keywords[] = {"firstiter", "finalizer", NULL};
860 PyObject *firstiter = NULL;
861 PyObject *finalizer = NULL;
862
863 if (!PyArg_ParseTupleAndKeywords(
864 args, kw, "|OO", keywords,
865 &firstiter, &finalizer)) {
866 return NULL;
867 }
868
869 if (finalizer && finalizer != Py_None) {
870 if (!PyCallable_Check(finalizer)) {
871 PyErr_Format(PyExc_TypeError,
872 "callable finalizer expected, got %.50s",
873 Py_TYPE(finalizer)->tp_name);
874 return NULL;
875 }
876 _PyEval_SetAsyncGenFinalizer(finalizer);
877 }
878 else if (finalizer == Py_None) {
879 _PyEval_SetAsyncGenFinalizer(NULL);
880 }
881
882 if (firstiter && firstiter != Py_None) {
883 if (!PyCallable_Check(firstiter)) {
884 PyErr_Format(PyExc_TypeError,
885 "callable firstiter expected, got %.50s",
886 Py_TYPE(firstiter)->tp_name);
887 return NULL;
888 }
889 _PyEval_SetAsyncGenFirstiter(firstiter);
890 }
891 else if (firstiter == Py_None) {
892 _PyEval_SetAsyncGenFirstiter(NULL);
893 }
894
895 Py_RETURN_NONE;
896}
897
898PyDoc_STRVAR(set_asyncgen_hooks_doc,
899"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
900\n\
901Set a finalizer for async generators objects."
902);
903
904static PyObject *
905sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
906{
907 PyObject *res;
908 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
909 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
910
911 res = PyStructSequence_New(&AsyncGenHooksType);
912 if (res == NULL) {
913 return NULL;
914 }
915
916 if (firstiter == NULL) {
917 firstiter = Py_None;
918 }
919
920 if (finalizer == NULL) {
921 finalizer = Py_None;
922 }
923
924 Py_INCREF(firstiter);
925 PyStructSequence_SET_ITEM(res, 0, firstiter);
926
927 Py_INCREF(finalizer);
928 PyStructSequence_SET_ITEM(res, 1, finalizer);
929
930 return res;
931}
932
933PyDoc_STRVAR(get_asyncgen_hooks_doc,
934"get_asyncgen_hooks()\n\
935\n\
936Return a namedtuple of installed asynchronous generators hooks \
937(firstiter, finalizer)."
938);
939
940
Mark Dickinsondc787d22010-05-23 13:33:13 +0000941static PyTypeObject Hash_InfoType;
942
943PyDoc_STRVAR(hash_info_doc,
944"hash_info\n\
945\n\
946A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100947hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000948
949static PyStructSequence_Field hash_info_fields[] = {
950 {"width", "width of the type used for hashing, in bits"},
951 {"modulus", "prime number giving the modulus on which the hash "
952 "function is based"},
953 {"inf", "value to be used for hash of a positive infinity"},
954 {"nan", "value to be used for hash of a nan"},
955 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100956 {"algorithm", "name of the algorithm for hashing of str, bytes and "
957 "memoryviews"},
958 {"hash_bits", "internal output size of hash algorithm"},
959 {"seed_bits", "seed size of hash algorithm"},
960 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000961 {NULL, NULL}
962};
963
964static PyStructSequence_Desc hash_info_desc = {
965 "sys.hash_info",
966 hash_info_doc,
967 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100968 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000969};
970
Matthias Klosed885e952010-07-06 10:53:30 +0000971static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000972get_hash_info(void)
973{
974 PyObject *hash_info;
975 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100976 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000977 hash_info = PyStructSequence_New(&Hash_InfoType);
978 if (hash_info == NULL)
979 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100980 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000981 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000982 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000983 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000984 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000985 PyStructSequence_SET_ITEM(hash_info, field++,
986 PyLong_FromLong(_PyHASH_INF));
987 PyStructSequence_SET_ITEM(hash_info, field++,
988 PyLong_FromLong(_PyHASH_NAN));
989 PyStructSequence_SET_ITEM(hash_info, field++,
990 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100991 PyStructSequence_SET_ITEM(hash_info, field++,
992 PyUnicode_FromString(hashfunc->name));
993 PyStructSequence_SET_ITEM(hash_info, field++,
994 PyLong_FromLong(hashfunc->hash_bits));
995 PyStructSequence_SET_ITEM(hash_info, field++,
996 PyLong_FromLong(hashfunc->seed_bits));
997 PyStructSequence_SET_ITEM(hash_info, field++,
998 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000999 if (PyErr_Occurred()) {
1000 Py_CLEAR(hash_info);
1001 return NULL;
1002 }
1003 return hash_info;
1004}
1005
1006
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001007PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001008"setrecursionlimit(n)\n\
1009\n\
1010Set the maximum depth of the Python interpreter stack to n. This\n\
1011limit prevents infinite recursion from causing an overflow of the C\n\
1012stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001013dependent."
1014);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001015
1016static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001017sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001020}
1021
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001022PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001023"getrecursionlimit()\n\
1024\n\
1025Return the current value of the recursion limit, the maximum depth\n\
1026of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001027recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001028);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001029
Mark Hammond8696ebc2002-10-08 02:44:31 +00001030#ifdef MS_WINDOWS
1031PyDoc_STRVAR(getwindowsversion_doc,
1032"getwindowsversion()\n\
1033\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001034Return information about the running version of Windows as a named tuple.\n\
1035The members are named: major, minor, build, platform, service_pack,\n\
1036service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001037backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001038All elements are numbers, except service_pack and platform_type which are\n\
1039strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1040Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1041server. Platform_version is a 3-tuple containing a version number that is\n\
1042intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001043);
1044
Eric Smithf7bb5782010-01-27 00:44:57 +00001045static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1046
1047static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 {"major", "Major version number"},
1049 {"minor", "Minor version number"},
1050 {"build", "Build number"},
1051 {"platform", "Operating system platform"},
1052 {"service_pack", "Latest Service Pack installed on the system"},
1053 {"service_pack_major", "Service Pack major version number"},
1054 {"service_pack_minor", "Service Pack minor version number"},
1055 {"suite_mask", "Bit mask identifying available product suites"},
1056 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001057 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001059};
1060
1061static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 "sys.getwindowsversion", /* name */
1063 getwindowsversion_doc, /* doc */
1064 windows_version_fields, /* fields */
1065 5 /* For backward compatibility,
1066 only the first 5 items are accessible
1067 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001068};
1069
Steve Dower3e96f322015-03-02 08:01:10 -08001070/* Disable deprecation warnings about GetVersionEx as the result is
1071 being passed straight through to the caller, who is responsible for
1072 using it correctly. */
1073#pragma warning(push)
1074#pragma warning(disable:4996)
1075
Mark Hammond8696ebc2002-10-08 02:44:31 +00001076static PyObject *
1077sys_getwindowsversion(PyObject *self)
1078{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 PyObject *version;
1080 int pos = 0;
1081 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001082 DWORD realMajor, realMinor, realBuild;
1083 HANDLE hKernel32;
1084 wchar_t kernel32_path[MAX_PATH];
1085 LPVOID verblock;
1086 DWORD verblock_size;
1087
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 ver.dwOSVersionInfoSize = sizeof(ver);
1089 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1090 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001091
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 version = PyStructSequence_New(&WindowsVersionType);
1093 if (version == NULL)
1094 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001095
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1097 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1098 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1099 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1100 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1101 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1102 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1103 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1104 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001105
Steve Dower74f4af72016-09-17 17:27:48 -07001106 realMajor = ver.dwMajorVersion;
1107 realMinor = ver.dwMinorVersion;
1108 realBuild = ver.dwBuildNumber;
1109
1110 // GetVersion will lie if we are running in a compatibility mode.
1111 // We need to read the version info from a system file resource
1112 // to accurately identify the OS version. If we fail for any reason,
1113 // just return whatever GetVersion said.
1114 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1115 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1116 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1117 (verblock = PyMem_RawMalloc(verblock_size))) {
1118 VS_FIXEDFILEINFO *ffi;
1119 UINT ffi_len;
1120
1121 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1122 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1123 realMajor = HIWORD(ffi->dwProductVersionMS);
1124 realMinor = LOWORD(ffi->dwProductVersionMS);
1125 realBuild = HIWORD(ffi->dwProductVersionLS);
1126 }
1127 PyMem_RawFree(verblock);
1128 }
Segev Finer48fb7662017-06-04 20:52:27 +03001129 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1130 realMajor,
1131 realMinor,
1132 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001133 ));
1134
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001135 if (PyErr_Occurred()) {
1136 Py_DECREF(version);
1137 return NULL;
1138 }
Steve Dower74f4af72016-09-17 17:27:48 -07001139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001140 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001141}
1142
Steve Dower3e96f322015-03-02 08:01:10 -08001143#pragma warning(pop)
1144
Steve Dowercc16be82016-09-08 10:35:16 -07001145PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1146"_enablelegacywindowsfsencoding()\n\
1147\n\
1148Changes the default filesystem encoding to mbcs:replace for consistency\n\
1149with earlier versions of Python. See PEP 529 for more information.\n\
1150\n\
1151This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1152environment variable before launching Python."
1153);
1154
1155static PyObject *
1156sys_enablelegacywindowsfsencoding(PyObject *self)
1157{
1158 Py_FileSystemDefaultEncoding = "mbcs";
1159 Py_FileSystemDefaultEncodeErrors = "replace";
1160 Py_RETURN_NONE;
1161}
1162
Mark Hammond8696ebc2002-10-08 02:44:31 +00001163#endif /* MS_WINDOWS */
1164
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001165#ifdef HAVE_DLOPEN
1166static PyObject *
1167sys_setdlopenflags(PyObject *self, PyObject *args)
1168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001169 int new_val;
1170 PyThreadState *tstate = PyThreadState_GET();
1171 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1172 return NULL;
1173 if (!tstate)
1174 return NULL;
1175 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001176 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001177}
1178
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001179PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001180"setdlopenflags(n) -> None\n\
1181\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001182Set the flags used by the interpreter for dlopen calls, such as when the\n\
1183interpreter loads extension modules. Among other things, this will enable\n\
1184a lazy resolving of symbols when importing a module, if called as\n\
1185sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001186sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001187can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001188
1189static PyObject *
1190sys_getdlopenflags(PyObject *self, PyObject *args)
1191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyThreadState *tstate = PyThreadState_GET();
1193 if (!tstate)
1194 return NULL;
1195 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001196}
1197
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001198PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001199"getdlopenflags() -> int\n\
1200\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001201Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001202The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001204#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001205
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001206#ifdef USE_MALLOPT
1207/* Link with -lmalloc (or -lmpc) on an SGI */
1208#include <malloc.h>
1209
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001210static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001211sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 int flag;
1214 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1215 return NULL;
1216 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001217 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001218}
1219#endif /* USE_MALLOPT */
1220
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001221size_t
1222_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001225 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001226 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001227
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 /* Make sure the type is initialized. float gets initialized late */
1229 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001230 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001231
Benjamin Petersonce798522012-01-22 11:24:29 -05001232 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 if (method == NULL) {
1234 if (!PyErr_Occurred())
1235 PyErr_Format(PyExc_TypeError,
1236 "Type %.100s doesn't define __sizeof__",
1237 Py_TYPE(o)->tp_name);
1238 }
1239 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001240 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 Py_DECREF(method);
1242 }
1243
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001244 if (res == NULL)
1245 return (size_t)-1;
1246
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001247 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001248 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001249 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001250 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001251
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001252 if (size < 0) {
1253 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1254 return (size_t)-1;
1255 }
1256
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001258 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001259 return ((size_t)size) + sizeof(PyGC_Head);
1260 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001261}
1262
1263static PyObject *
1264sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1265{
1266 static char *kwlist[] = {"object", "default", 0};
1267 size_t size;
1268 PyObject *o, *dflt = NULL;
1269
1270 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1271 kwlist, &o, &dflt))
1272 return NULL;
1273
1274 size = _PySys_GetSizeOf(o);
1275
1276 if (size == (size_t)-1 && PyErr_Occurred()) {
1277 /* Has a default value been given */
1278 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1279 PyErr_Clear();
1280 Py_INCREF(dflt);
1281 return dflt;
1282 }
1283 else
1284 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001286
1287 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001288}
1289
1290PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001291"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001292\n\
1293Return the size of object in bytes.");
1294
1295static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001296sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001299}
1300
Tim Peters4be93d02002-07-07 19:59:50 +00001301#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001302static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001303sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001304{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001306}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001307#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001308
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001309PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001310"getrefcount(object) -> integer\n\
1311\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001312Return the reference count of object. The count returned is generally\n\
1313one higher than you might expect, because it includes the (temporary)\n\
1314reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001315);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001316
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001317static PyObject *
1318sys_getallocatedblocks(PyObject *self)
1319{
1320 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1321}
1322
1323PyDoc_STRVAR(getallocatedblocks_doc,
1324"getallocatedblocks() -> integer\n\
1325\n\
1326Return the number of memory blocks currently allocated, regardless of their\n\
1327size."
1328);
1329
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001330#ifdef COUNT_ALLOCS
1331static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001332sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001333{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001335
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001337}
1338#endif
1339
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001340PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001341"_getframe([depth]) -> frameobject\n\
1342\n\
1343Return a frame object from the call stack. If optional integer depth is\n\
1344given, return the frame object that many calls below the top of the stack.\n\
1345If that is deeper than the call stack, ValueError is raised. The default\n\
1346for depth is zero, returning the frame at the top of the call stack.\n\
1347\n\
1348This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001349purposes only."
1350);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001351
1352static PyObject *
1353sys_getframe(PyObject *self, PyObject *args)
1354{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 PyFrameObject *f = PyThreadState_GET()->frame;
1356 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001357
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1359 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001360
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 while (depth > 0 && f != NULL) {
1362 f = f->f_back;
1363 --depth;
1364 }
1365 if (f == NULL) {
1366 PyErr_SetString(PyExc_ValueError,
1367 "call stack is not deep enough");
1368 return NULL;
1369 }
1370 Py_INCREF(f);
1371 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001372}
1373
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001374PyDoc_STRVAR(current_frames_doc,
1375"_current_frames() -> dictionary\n\
1376\n\
1377Return a dictionary mapping each current thread T's thread id to T's\n\
1378current stack frame.\n\
1379\n\
1380This function should be used for specialized purposes only."
1381);
1382
1383static PyObject *
1384sys_current_frames(PyObject *self, PyObject *noargs)
1385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001387}
1388
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001389PyDoc_STRVAR(call_tracing_doc,
1390"call_tracing(func, args) -> object\n\
1391\n\
1392Call func(*args), while tracing is enabled. The tracing state is\n\
1393saved, and restored afterwards. This is intended to be called from\n\
1394a debugger from a checkpoint, to recursively debug some other code."
1395);
1396
1397static PyObject *
1398sys_call_tracing(PyObject *self, PyObject *args)
1399{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001400 PyObject *func, *funcargs;
1401 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1402 return NULL;
1403 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001404}
1405
Jeremy Hylton985eba52003-02-05 23:13:00 +00001406PyDoc_STRVAR(callstats_doc,
1407"callstats() -> tuple of integers\n\
1408\n\
1409Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1410when Python was built. Otherwise, return None.\n\
1411\n\
1412When enabled, this function returns detailed, implementation-specific\n\
1413details about the number of function calls executed. The return value is\n\
1414a 11-tuple where the entries in the tuple are counts of:\n\
14150. all function calls\n\
14161. calls to PyFunction_Type objects\n\
14172. PyFunction calls that do not create an argument tuple\n\
14183. PyFunction calls that do not create an argument tuple\n\
1419 and bypass PyEval_EvalCodeEx()\n\
14204. PyMethod calls\n\
14215. PyMethod calls on bound methods\n\
14226. PyType calls\n\
14237. PyCFunction calls\n\
14248. generator calls\n\
14259. All other calls\n\
142610. Number of stack pops performed by call_function()"
1427);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001428
Victor Stinner048afd92016-11-28 11:59:04 +01001429static PyObject *
1430sys_callstats(PyObject *self)
1431{
1432 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1433 "sys.callstats() has been deprecated in Python 3.7 "
1434 "and will be removed in the future", 1) < 0) {
1435 return NULL;
1436 }
1437
1438 Py_RETURN_NONE;
1439}
1440
1441
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001442#ifdef __cplusplus
1443extern "C" {
1444#endif
1445
David Malcolm49526f42012-06-22 14:55:41 -04001446static PyObject *
1447sys_debugmallocstats(PyObject *self, PyObject *args)
1448{
1449#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001450 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be807c2016-03-14 12:04:26 +01001451 fputc('\n', stderr);
1452 }
David Malcolm49526f42012-06-22 14:55:41 -04001453#endif
1454 _PyObject_DebugTypeStats(stderr);
1455
1456 Py_RETURN_NONE;
1457}
1458PyDoc_STRVAR(debugmallocstats_doc,
1459"_debugmallocstats()\n\
1460\n\
1461Print summary info to stderr about the state of\n\
1462pymalloc's structures.\n\
1463\n\
1464In Py_DEBUG mode, also perform some expensive internal consistency\n\
1465checks.\n\
1466");
1467
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001468#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001469/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001470extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001471#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001472
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001473#ifdef DYNAMIC_EXECUTION_PROFILE
1474/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001475extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001476#endif
1477
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001478#ifdef __cplusplus
1479}
1480#endif
1481
Christian Heimes15ebc882008-02-04 18:48:49 +00001482static PyObject *
1483sys_clear_type_cache(PyObject* self, PyObject* args)
1484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 PyType_ClearCache();
1486 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001487}
1488
1489PyDoc_STRVAR(sys_clear_type_cache__doc__,
1490"_clear_type_cache() -> None\n\
1491Clear the internal type lookup cache.");
1492
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001493static PyObject *
1494sys_is_finalizing(PyObject* self, PyObject* args)
1495{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001496 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001497}
1498
1499PyDoc_STRVAR(is_finalizing_doc,
1500"is_finalizing()\n\
1501Return True if Python is exiting.");
1502
Christian Heimes15ebc882008-02-04 18:48:49 +00001503
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001504#ifdef ANDROID_API_LEVEL
1505PyDoc_STRVAR(getandroidapilevel_doc,
1506"getandroidapilevel()\n\
1507\n\
1508Return the build time API version of Android as an integer.");
1509
1510static PyObject *
1511sys_getandroidapilevel(PyObject *self)
1512{
1513 return PyLong_FromLong(ANDROID_API_LEVEL);
1514}
1515#endif /* ANDROID_API_LEVEL */
1516
1517
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001518static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001520 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1521 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Victor Stinner048afd92016-11-28 11:59:04 +01001522 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 callstats_doc},
1524 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1525 sys_clear_type_cache__doc__},
1526 {"_current_frames", sys_current_frames, METH_NOARGS,
1527 current_frames_doc},
1528 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1529 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1530 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1531 {"exit", sys_exit, METH_VARARGS, exit_doc},
1532 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1533 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001534#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1536 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001537#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001538 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1539 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001540#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001542#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001543#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001545#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1547 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001548 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1549 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001550#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001552#endif
1553#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001555#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1557 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1558 getrecursionlimit_doc},
1559 {"getsizeof", (PyCFunction)sys_getsizeof,
1560 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1561 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001562#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1564 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001565 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1566 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001567#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001569 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001570#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001572#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1574 setcheckinterval_doc},
1575 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1576 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1578 setswitchinterval_doc},
1579 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1580 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001581#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1583 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001584#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1586 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1587 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1588 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 {"settrace", sys_settrace, METH_O, settrace_doc},
1590 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1591 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001592 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001593 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001594 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1595 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001596 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1597 set_coroutine_wrapper_doc},
1598 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1599 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001600 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001601 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1602 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1603 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001604#ifdef ANDROID_API_LEVEL
1605 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1606 getandroidapilevel_doc},
1607#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001609};
1610
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001611static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001612list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001614 PyObject *list = PyList_New(0);
1615 int i;
1616 if (list == NULL)
1617 return NULL;
1618 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1619 PyObject *name = PyUnicode_FromString(
1620 PyImport_Inittab[i].name);
1621 if (name == NULL)
1622 break;
1623 PyList_Append(list, name);
1624 Py_DECREF(name);
1625 }
1626 if (PyList_Sort(list) != 0) {
1627 Py_DECREF(list);
1628 list = NULL;
1629 }
1630 if (list) {
1631 PyObject *v = PyList_AsTuple(list);
1632 Py_DECREF(list);
1633 list = v;
1634 }
1635 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001636}
1637
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001638/* Pre-initialization support for sys.warnoptions and sys._xoptions
1639 *
1640 * Modern internal code paths:
1641 * These APIs get called after _Py_InitializeCore and get to use the
1642 * regular CPython list, dict, and unicode APIs.
1643 *
1644 * Legacy embedding code paths:
1645 * The multi-phase initialization API isn't public yet, so embedding
1646 * apps still need to be able configure sys.warnoptions and sys._xoptions
1647 * before they call Py_Initialize. To support this, we stash copies of
1648 * the supplied wchar * sequences in linked lists, and then migrate the
1649 * contents of those lists to the sys module in _PyInitializeCore.
1650 *
1651 */
1652
1653struct _preinit_entry {
1654 wchar_t *value;
1655 struct _preinit_entry *next;
1656};
1657
1658typedef struct _preinit_entry *_Py_PreInitEntry;
1659
1660static _Py_PreInitEntry _preinit_warnoptions = NULL;
1661static _Py_PreInitEntry _preinit_xoptions = NULL;
1662
1663static _Py_PreInitEntry
1664_alloc_preinit_entry(const wchar_t *value)
1665{
1666 /* To get this to work, we have to initialize the runtime implicitly */
1667 _PyRuntime_Initialize();
1668
1669 /* Force default allocator, so we can ensure that it also gets used to
1670 * destroy the linked list in _clear_preinit_entries.
1671 */
1672 PyMemAllocatorEx old_alloc;
1673 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1674
1675 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1676 if (node != NULL) {
1677 node->value = _PyMem_RawWcsdup(value);
1678 if (node->value == NULL) {
1679 PyMem_RawFree(node);
1680 node = NULL;
1681 };
1682 };
1683
1684 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1685 return node;
1686};
1687
1688static int
1689_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1690{
1691 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1692 if (new_entry == NULL) {
1693 return -1;
1694 }
1695 /* We maintain the linked list in this order so it's easy to play back
1696 * the add commands in the same order later on in _Py_InitializeCore
1697 */
1698 _Py_PreInitEntry last_entry = *optionlist;
1699 if (last_entry == NULL) {
1700 *optionlist = new_entry;
1701 } else {
1702 while (last_entry->next != NULL) {
1703 last_entry = last_entry->next;
1704 }
1705 last_entry->next = new_entry;
1706 }
1707 return 0;
1708};
1709
1710static void
1711_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1712{
1713 _Py_PreInitEntry current = *optionlist;
1714 *optionlist = NULL;
1715 /* Deallocate the nodes and their contents using the default allocator */
1716 PyMemAllocatorEx old_alloc;
1717 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1718 while (current != NULL) {
1719 _Py_PreInitEntry next = current->next;
1720 PyMem_RawFree(current->value);
1721 PyMem_RawFree(current);
1722 current = next;
1723 }
1724 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1725};
1726
1727static void
1728_clear_all_preinit_options(void)
1729{
1730 _clear_preinit_entries(&_preinit_warnoptions);
1731 _clear_preinit_entries(&_preinit_xoptions);
1732}
1733
1734static int
1735_PySys_ReadPreInitOptions(void)
1736{
1737 /* Rerun the add commands with the actual sys module available */
1738 PyThreadState *tstate = PyThreadState_GET();
1739 if (tstate == NULL) {
1740 /* Still don't have a thread state, so something is wrong! */
1741 return -1;
1742 }
1743 _Py_PreInitEntry entry = _preinit_warnoptions;
1744 while (entry != NULL) {
1745 PySys_AddWarnOption(entry->value);
1746 entry = entry->next;
1747 }
1748 entry = _preinit_xoptions;
1749 while (entry != NULL) {
1750 PySys_AddXOption(entry->value);
1751 entry = entry->next;
1752 }
1753
1754 _clear_all_preinit_options();
1755 return 0;
1756};
1757
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001758static PyObject *
1759get_warnoptions(void)
1760{
Eric Snowdae02762017-09-14 00:35:58 -07001761 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001762 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001763 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1764 * interpreter config. When that happens, we need to properly set
1765 * the `warnoptions` reference in the main interpreter config as well.
1766 *
1767 * For Python 3.7, we shouldn't be able to get here due to the
1768 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1769 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1770 * call optional for embedding applications, thus making this
1771 * reachable again.
1772 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001773 warnoptions = PyList_New(0);
1774 if (warnoptions == NULL)
1775 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001776 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1777 Py_DECREF(warnoptions);
1778 return NULL;
1779 }
1780 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001781 }
1782 return warnoptions;
1783}
Guido van Rossum23fff912000-12-15 22:02:05 +00001784
1785void
1786PySys_ResetWarnOptions(void)
1787{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001788 PyThreadState *tstate = PyThreadState_GET();
1789 if (tstate == NULL) {
1790 _clear_preinit_entries(&_preinit_warnoptions);
1791 return;
1792 }
1793
Eric Snowdae02762017-09-14 00:35:58 -07001794 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 if (warnoptions == NULL || !PyList_Check(warnoptions))
1796 return;
1797 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001798}
1799
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001800int
1801_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001802{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001803 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001804 if (warnoptions == NULL) {
1805 return -1;
1806 }
1807 if (PyList_Append(warnoptions, option)) {
1808 return -1;
1809 }
1810 return 0;
1811}
1812
1813void
1814PySys_AddWarnOptionUnicode(PyObject *option)
1815{
1816 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001817}
1818
1819void
1820PySys_AddWarnOption(const wchar_t *s)
1821{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001822 PyThreadState *tstate = PyThreadState_GET();
1823 if (tstate == NULL) {
1824 _append_preinit_entry(&_preinit_warnoptions, s);
1825 return;
1826 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001827 PyObject *unicode;
1828 unicode = PyUnicode_FromWideChar(s, -1);
1829 if (unicode == NULL)
1830 return;
1831 PySys_AddWarnOptionUnicode(unicode);
1832 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001833}
1834
Christian Heimes33fe8092008-04-13 13:53:33 +00001835int
1836PySys_HasWarnOptions(void)
1837{
Eric Snowdae02762017-09-14 00:35:58 -07001838 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Miss Islington (bot)ea773eb2018-12-10 04:37:09 -08001839 return (warnoptions != NULL && PyList_Check(warnoptions)
1840 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001841}
1842
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001843static PyObject *
1844get_xoptions(void)
1845{
Eric Snowdae02762017-09-14 00:35:58 -07001846 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001847 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001848 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1849 * interpreter config. When that happens, we need to properly set
1850 * the `xoptions` reference in the main interpreter config as well.
1851 *
1852 * For Python 3.7, we shouldn't be able to get here due to the
1853 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1854 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1855 * call optional for embedding applications, thus making this
1856 * reachable again.
1857 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001858 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001859 if (xoptions == NULL)
1860 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001861 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1862 Py_DECREF(xoptions);
1863 return NULL;
1864 }
1865 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001866 }
1867 return xoptions;
1868}
1869
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001870int
1871_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001872{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001873 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001874
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001875 PyObject *opts = get_xoptions();
1876 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001877 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001878 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001879
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001880 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001881 if (!name_end) {
1882 name = PyUnicode_FromWideChar(s, -1);
1883 value = Py_True;
1884 Py_INCREF(value);
1885 }
1886 else {
1887 name = PyUnicode_FromWideChar(s, name_end - s);
1888 value = PyUnicode_FromWideChar(name_end + 1, -1);
1889 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001890 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001891 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001892 }
1893 if (PyDict_SetItem(opts, name, value) < 0) {
1894 goto error;
1895 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001896 Py_DECREF(name);
1897 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001898 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001899
1900error:
1901 Py_XDECREF(name);
1902 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001903 return -1;
1904}
1905
1906void
1907PySys_AddXOption(const wchar_t *s)
1908{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001909 PyThreadState *tstate = PyThreadState_GET();
1910 if (tstate == NULL) {
1911 _append_preinit_entry(&_preinit_xoptions, s);
1912 return;
1913 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001914 if (_PySys_AddXOptionWithError(s) < 0) {
1915 /* No return value, therefore clear error state if possible */
1916 if (_PyThreadState_UncheckedGet()) {
1917 PyErr_Clear();
1918 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001919 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001920}
1921
1922PyObject *
1923PySys_GetXOptions(void)
1924{
1925 return get_xoptions();
1926}
1927
Guido van Rossum40552d01998-08-06 03:34:39 +00001928/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1929 Two literals concatenated works just fine. If you have a K&R compiler
1930 or other abomination that however *does* understand longer strings,
1931 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001932PyDoc_VAR(sys_doc) =
1933PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001934"This module provides access to some objects used or maintained by the\n\
1935interpreter and to functions that interact strongly with the interpreter.\n\
1936\n\
1937Dynamic objects:\n\
1938\n\
1939argv -- command line arguments; argv[0] is the script pathname if known\n\
1940path -- module search path; path[0] is the script directory, else ''\n\
1941modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001942\n\
1943displayhook -- called to show results in an interactive session\n\
1944excepthook -- called to handle any uncaught exception other than SystemExit\n\
1945 To customize printing in an interactive session or to install a custom\n\
1946 top-level exception handler, assign other functions to replace these.\n\
1947\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001948stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001949stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001950stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001951 By assigning other file objects (or objects that behave like files)\n\
1952 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001953\n\
1954last_type -- type of last uncaught exception\n\
1955last_value -- value of last uncaught exception\n\
1956last_traceback -- traceback of last uncaught exception\n\
1957 These three are only available in an interactive session after a\n\
1958 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001959"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001960)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001961/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001962PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001963"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001964Static objects:\n\
1965\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001966builtin_module_names -- tuple of module names built into this interpreter\n\
1967copyright -- copyright notice pertaining to this interpreter\n\
1968exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001969executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001970float_info -- a struct sequence with information about the float implementation.\n\
1971float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001972hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001973hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001974implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001975int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001976maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001977maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001978platform -- platform identifier\n\
1979prefix -- prefix used to find the Python library\n\
1980thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001981version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001982version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001983"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001984)
Steve Dowercc16be82016-09-08 10:35:16 -07001985#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001986/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001987PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001988"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001989winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001990"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001991)
Steve Dowercc16be82016-09-08 10:35:16 -07001992#endif /* MS_COREDLL */
1993#ifdef MS_WINDOWS
1994/* concatenating string here */
1995PyDoc_STR(
1996"_enablelegacywindowsfsencoding -- [Windows only] \n\
1997"
1998)
1999#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002000PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002001"__stdin__ -- the original stdin; don't touch!\n\
2002__stdout__ -- the original stdout; don't touch!\n\
2003__stderr__ -- the original stderr; don't touch!\n\
2004__displayhook__ -- the original displayhook; don't touch!\n\
2005__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002006\n\
2007Functions:\n\
2008\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002009displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002010excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002011exc_info() -- return thread-safe information about the current exception\n\
2012exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002013getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002014getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002015getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002016getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002017getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002018gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002019setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002020setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002021setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002022setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002023settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002024"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002025)
Fred Drakeccede592000-08-14 20:59:57 +00002026/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002027
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002028
2029PyDoc_STRVAR(flags__doc__,
2030"sys.flags\n\
2031\n\
2032Flags provided through command line arguments or environment vars.");
2033
2034static PyTypeObject FlagsType;
2035
2036static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 {"inspect", "-i"},
2039 {"interactive", "-i"},
2040 {"optimize", "-O or -OO"},
2041 {"dont_write_bytecode", "-B"},
2042 {"no_user_site", "-s"},
2043 {"no_site", "-S"},
2044 {"ignore_environment", "-E"},
2045 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 /* {"unbuffered", "-u"}, */
2047 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002048 {"bytes_warning", "-b"},
2049 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002050 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002051 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002052 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002053 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002054 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002055};
2056
2057static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002058 "sys.flags", /* name */
2059 flags__doc__, /* doc */
2060 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002061 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002062};
2063
2064static PyObject*
2065make_flags(void)
2066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 int pos = 0;
2068 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01002069 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 seq = PyStructSequence_New(&FlagsType);
2072 if (seq == NULL)
2073 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002074
2075#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002078 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 SetFlag(Py_InspectFlag);
2080 SetFlag(Py_InteractiveFlag);
2081 SetFlag(Py_OptimizeFlag);
2082 SetFlag(Py_DontWriteBytecodeFlag);
2083 SetFlag(Py_NoUserSiteDirectory);
2084 SetFlag(Py_NoSiteFlag);
2085 SetFlag(Py_IgnoreEnvironmentFlag);
2086 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002087 /* SetFlag(saw_unbuffered_flag); */
2088 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00002089 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00002090 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002091 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02002092 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01002093 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01002094 SetFlag(Py_UTF8Mode);
2095#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002096
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002098 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002099 return NULL;
2100 }
2101 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002102}
2103
Eric Smith0e5b5622009-02-06 01:32:42 +00002104PyDoc_STRVAR(version_info__doc__,
2105"sys.version_info\n\
2106\n\
2107Version information as a named tuple.");
2108
2109static PyTypeObject VersionInfoType;
2110
2111static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 {"major", "Major release number"},
2113 {"minor", "Minor release number"},
2114 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002115 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 {"serial", "Serial release number"},
2117 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002118};
2119
2120static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 "sys.version_info", /* name */
2122 version_info__doc__, /* doc */
2123 version_info_fields, /* fields */
2124 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002125};
2126
2127static PyObject *
2128make_version_info(void)
2129{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 PyObject *version_info;
2131 char *s;
2132 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 version_info = PyStructSequence_New(&VersionInfoType);
2135 if (version_info == NULL) {
2136 return NULL;
2137 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 /*
2140 * These release level checks are mutually exclusive and cover
2141 * the field, so don't get too fancy with the pre-processor!
2142 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002143#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002145#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002147#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002149#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002151#endif
2152
2153#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002155#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002157
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 SetIntItem(PY_MAJOR_VERSION);
2159 SetIntItem(PY_MINOR_VERSION);
2160 SetIntItem(PY_MICRO_VERSION);
2161 SetStrItem(s);
2162 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002163#undef SetIntItem
2164#undef SetStrItem
2165
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (PyErr_Occurred()) {
2167 Py_CLEAR(version_info);
2168 return NULL;
2169 }
2170 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002171}
2172
Brett Cannon3adc7b72012-07-09 14:22:12 -04002173/* sys.implementation values */
2174#define NAME "cpython"
2175const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002176#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2177#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002178#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002179const char *_PySys_ImplCacheTag = TAG;
2180#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002181#undef MAJOR
2182#undef MINOR
2183#undef TAG
2184
Barry Warsaw409da152012-06-03 16:18:47 -04002185static PyObject *
2186make_impl_info(PyObject *version_info)
2187{
2188 int res;
2189 PyObject *impl_info, *value, *ns;
2190
2191 impl_info = PyDict_New();
2192 if (impl_info == NULL)
2193 return NULL;
2194
2195 /* populate the dict */
2196
Brett Cannon3adc7b72012-07-09 14:22:12 -04002197 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002198 if (value == NULL)
2199 goto error;
2200 res = PyDict_SetItemString(impl_info, "name", value);
2201 Py_DECREF(value);
2202 if (res < 0)
2203 goto error;
2204
Brett Cannon3adc7b72012-07-09 14:22:12 -04002205 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002206 if (value == NULL)
2207 goto error;
2208 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2209 Py_DECREF(value);
2210 if (res < 0)
2211 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002212
2213 res = PyDict_SetItemString(impl_info, "version", version_info);
2214 if (res < 0)
2215 goto error;
2216
2217 value = PyLong_FromLong(PY_VERSION_HEX);
2218 if (value == NULL)
2219 goto error;
2220 res = PyDict_SetItemString(impl_info, "hexversion", value);
2221 Py_DECREF(value);
2222 if (res < 0)
2223 goto error;
2224
doko@ubuntu.com55532312016-06-14 08:55:19 +02002225#ifdef MULTIARCH
2226 value = PyUnicode_FromString(MULTIARCH);
2227 if (value == NULL)
2228 goto error;
2229 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2230 Py_DECREF(value);
2231 if (res < 0)
2232 goto error;
2233#endif
2234
Barry Warsaw409da152012-06-03 16:18:47 -04002235 /* dict ready */
2236
2237 ns = _PyNamespace_New(impl_info);
2238 Py_DECREF(impl_info);
2239 return ns;
2240
2241error:
2242 Py_CLEAR(impl_info);
2243 return NULL;
2244}
2245
Martin v. Löwis1a214512008-06-11 05:26:20 +00002246static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 PyModuleDef_HEAD_INIT,
2248 "sys",
2249 sys_doc,
2250 -1, /* multiple "initialization" just copies the module dict. */
2251 sys_methods,
2252 NULL,
2253 NULL,
2254 NULL,
2255 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002256};
2257
Eric Snow6b4be192017-05-22 21:36:03 -07002258/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002259#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002260 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002261 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002262 if (v == NULL) { \
2263 goto err_occurred; \
2264 } \
Victor Stinner58049602013-07-22 22:40:00 +02002265 res = PyDict_SetItemString(sysdict, key, v); \
2266 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002267 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002268 } \
2269 } while (0)
2270#define SET_SYS_FROM_STRING(key, value) \
2271 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002272 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002273 if (v == NULL) { \
2274 goto err_occurred; \
2275 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002276 res = PyDict_SetItemString(sysdict, key, v); \
2277 Py_DECREF(v); \
2278 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002279 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002280 } \
2281 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002282
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002283
2284_PyInitError
2285_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002286{
2287 PyObject *m, *sysdict, *version_info;
2288 int res;
2289
Eric Snowd393c1b2017-09-14 12:18:12 -06002290 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002291 if (m == NULL) {
2292 return _Py_INIT_ERR("failed to create a module object");
2293 }
Eric Snow6b4be192017-05-22 21:36:03 -07002294 sysdict = PyModule_GetDict(m);
2295
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002296 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002297 Using shell redirection, you can redirect stdin to a directory,
2298 crashing the Python interpreter. Catch this common mistake here
2299 and output a useful error message. Note that under MS Windows,
2300 the shell already prevents that. */
2301#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002302 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002303 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002304 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002305 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002306 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2307 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002308 }
2309 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002310#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002311
Nick Coghland6009512014-11-20 21:39:37 +10002312 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002313
Victor Stinner8fea2522013-10-27 17:15:42 +01002314 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2315 PyDict_GetItemString(sysdict, "displayhook"));
2316 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2317 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002318 SET_SYS_FROM_STRING_BORROW(
2319 "__breakpointhook__",
2320 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002321 SET_SYS_FROM_STRING("version",
2322 PyUnicode_FromString(Py_GetVersion()));
2323 SET_SYS_FROM_STRING("hexversion",
2324 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002325 SET_SYS_FROM_STRING("_git",
2326 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2327 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002328 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002329 SET_SYS_FROM_STRING("api_version",
2330 PyLong_FromLong(PYTHON_API_VERSION));
2331 SET_SYS_FROM_STRING("copyright",
2332 PyUnicode_FromString(Py_GetCopyright()));
2333 SET_SYS_FROM_STRING("platform",
2334 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002335 SET_SYS_FROM_STRING("maxsize",
2336 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2337 SET_SYS_FROM_STRING("float_info",
2338 PyFloat_GetInfo());
2339 SET_SYS_FROM_STRING("int_info",
2340 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002341 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002342 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002343 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2344 goto type_init_failed;
2345 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002346 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002347 SET_SYS_FROM_STRING("hash_info",
2348 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002350 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002351 SET_SYS_FROM_STRING("builtin_module_names",
2352 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002353#if PY_BIG_ENDIAN
2354 SET_SYS_FROM_STRING("byteorder",
2355 PyUnicode_FromString("big"));
2356#else
2357 SET_SYS_FROM_STRING("byteorder",
2358 PyUnicode_FromString("little"));
2359#endif
Fred Drake099325e2000-08-14 15:47:03 +00002360
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002361#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002362 SET_SYS_FROM_STRING("dllhandle",
2363 PyLong_FromVoidPtr(PyWin_DLLhModule));
2364 SET_SYS_FROM_STRING("winver",
2365 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002366#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002367#ifdef ABIFLAGS
2368 SET_SYS_FROM_STRING("abiflags",
2369 PyUnicode_FromString(ABIFLAGS));
2370#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002371
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002372 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002373 if (VersionInfoType.tp_name == NULL) {
2374 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002375 &version_info_desc) < 0) {
2376 goto type_init_failed;
2377 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002378 }
Barry Warsaw409da152012-06-03 16:18:47 -04002379 version_info = make_version_info();
2380 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002381 /* prevent user from creating new instances */
2382 VersionInfoType.tp_init = NULL;
2383 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002384 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2385 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2386 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002387
Barry Warsaw409da152012-06-03 16:18:47 -04002388 /* implementation */
2389 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002392 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002393 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2394 goto type_init_failed;
2395 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002396 }
Eric Snow6b4be192017-05-22 21:36:03 -07002397 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002398 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002399
2400#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 /* getwindowsversion */
2402 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002403 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002404 &windows_version_desc) < 0) {
2405 goto type_init_failed;
2406 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 /* prevent user from creating new instances */
2408 WindowsVersionType.tp_init = NULL;
2409 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002410 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002411 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002412 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002413 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002414 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002415#endif
2416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002418#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 SET_SYS_FROM_STRING("float_repr_style",
2420 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002421#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 SET_SYS_FROM_STRING("float_repr_style",
2423 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002424#endif
2425
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002426 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002427
Yury Selivanoveb636452016-09-08 22:01:51 -07002428 /* initialize asyncgen_hooks */
2429 if (AsyncGenHooksType.tp_name == NULL) {
2430 if (PyStructSequence_InitType2(
2431 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002432 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002433 }
2434 }
2435
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002436 if (PyErr_Occurred()) {
2437 goto err_occurred;
2438 }
2439
2440 *sysmod = m;
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002441
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002442 return _Py_INIT_OK();
2443
2444type_init_failed:
2445 return _Py_INIT_ERR("failed to initialize a type");
2446
2447err_occurred:
2448 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002449}
2450
Eric Snow6b4be192017-05-22 21:36:03 -07002451#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002452
2453/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002454#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2455 do { \
2456 PyObject *v = (value); \
2457 if (v == NULL) \
2458 return -1; \
2459 res = PyDict_SetItemString(sysdict, key, v); \
2460 Py_DECREF(v); \
2461 if (res < 0) { \
2462 return res; \
2463 } \
2464 } while (0)
2465
2466int
Victor Stinner41264f12017-12-15 02:05:29 +01002467_PySys_EndInit(PyObject *sysdict, _PyMainInterpreterConfig *config)
Eric Snow6b4be192017-05-22 21:36:03 -07002468{
2469 int res;
2470
Victor Stinner41264f12017-12-15 02:05:29 +01002471 /* _PyMainInterpreterConfig_Read() must set all these variables */
2472 assert(config->module_search_path != NULL);
2473 assert(config->executable != NULL);
2474 assert(config->prefix != NULL);
2475 assert(config->base_prefix != NULL);
2476 assert(config->exec_prefix != NULL);
2477 assert(config->base_exec_prefix != NULL);
2478
Victor Stinnera5194112018-11-22 16:11:15 +01002479 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
Victor Stinner41264f12017-12-15 02:05:29 +01002480 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2481 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2482 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2483 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2484 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2485
2486 if (config->argv != NULL) {
2487 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2488 }
2489 if (config->warnoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002490 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002491 }
2492 if (config->xoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002493 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002494 }
2495
Eric Snow6b4be192017-05-22 21:36:03 -07002496 /* Set flags to their final values */
2497 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2498 /* prevent user from creating new instances */
2499 FlagsType.tp_init = NULL;
2500 FlagsType.tp_new = NULL;
2501 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2502 if (res < 0) {
2503 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2504 return res;
2505 }
2506 PyErr_Clear();
2507 }
2508
2509 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2510 PyBool_FromLong(Py_DontWriteBytecodeFlag));
Eric Snow6b4be192017-05-22 21:36:03 -07002511
Eric Snowdae02762017-09-14 00:35:58 -07002512 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002513 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002514
Eric Snowdae02762017-09-14 00:35:58 -07002515 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002516 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002517
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002518 /* Transfer any sys.warnoptions and sys._xoptions set directly
2519 * by an embedding application from the linked list to the module. */
2520 if (_PySys_ReadPreInitOptions() != 0)
2521 return -1;
2522
Eric Snow6b4be192017-05-22 21:36:03 -07002523 if (PyErr_Occurred())
2524 return -1;
2525 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002526
2527err_occurred:
2528 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002529}
2530
Victor Stinner41264f12017-12-15 02:05:29 +01002531#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002532#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002533
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002534static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002535makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 int i, n;
2538 const wchar_t *p;
2539 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002541 n = 1;
2542 p = path;
2543 while ((p = wcschr(p, delim)) != NULL) {
2544 n++;
2545 p++;
2546 }
2547 v = PyList_New(n);
2548 if (v == NULL)
2549 return NULL;
2550 for (i = 0; ; i++) {
2551 p = wcschr(path, delim);
2552 if (p == NULL)
2553 p = path + wcslen(path); /* End of string */
2554 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2555 if (w == NULL) {
2556 Py_DECREF(v);
2557 return NULL;
2558 }
Miss Islington (bot)8b7d8ac2018-12-08 06:34:49 -08002559 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002560 if (*p == '\0')
2561 break;
2562 path = p+1;
2563 }
2564 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002565}
2566
2567void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002568PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570 PyObject *v;
2571 if ((v = makepathobject(path, DELIM)) == NULL)
2572 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002573 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002574 Py_FatalError("can't assign sys.path");
2575 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002576}
2577
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002578static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002579makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 PyObject *av;
2582 if (argc <= 0 || argv == NULL) {
2583 /* Ensure at least one (empty) argument is seen */
2584 static wchar_t *empty_argv[1] = {L""};
2585 argv = empty_argv;
2586 argc = 1;
2587 }
2588 av = PyList_New(argc);
2589 if (av != NULL) {
2590 int i;
2591 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 if (v == NULL) {
2594 Py_DECREF(av);
2595 av = NULL;
2596 break;
2597 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002598 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002599 }
2600 }
2601 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002602}
2603
Victor Stinner11a247d2017-12-13 21:05:57 +01002604void
2605PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002606{
2607 PyObject *av = makeargvobject(argc, argv);
2608 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002609 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002610 }
2611 if (PySys_SetObject("argv", av) != 0) {
2612 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002613 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002614 }
2615 Py_DECREF(av);
2616
2617 if (updatepath) {
2618 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2619 If argv[0] is a symlink, use the real path. */
Victor Stinnerf7959a92019-03-20 00:30:45 +01002620 PyObject *argv0 = NULL;
2621 if (!_PyPathConfig_ComputeArgv0(argc, argv, &argv0)) {
2622 return;
2623 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002624 if (argv0 == NULL) {
2625 Py_FatalError("can't compute path0 from argv");
2626 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002627
Victor Stinner11a247d2017-12-13 21:05:57 +01002628 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2629 if (sys_path != NULL) {
2630 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2631 Py_DECREF(argv0);
2632 Py_FatalError("can't prepend path0 to sys.path");
2633 }
2634 }
2635 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002636 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002637}
Guido van Rossuma890e681998-05-12 14:59:24 +00002638
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002639void
2640PySys_SetArgv(int argc, wchar_t **argv)
2641{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002642 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002643}
2644
Victor Stinner14284c22010-04-23 12:02:30 +00002645/* Reimplementation of PyFile_WriteString() no calling indirectly
2646 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2647
2648static int
Victor Stinner79766632010-08-16 17:36:42 +00002649sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002650{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002651 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002652 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002653
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002654 if (file == NULL)
2655 return -1;
2656
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002657 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002658 if (writer == NULL)
2659 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002660
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002661 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 if (result == NULL) {
2663 goto error;
2664 } else {
2665 err = 0;
2666 goto finally;
2667 }
Victor Stinner14284c22010-04-23 12:02:30 +00002668
2669error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002671finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002673 Py_XDECREF(result);
2674 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002675}
2676
Victor Stinner79766632010-08-16 17:36:42 +00002677static int
2678sys_pyfile_write(const char *text, PyObject *file)
2679{
2680 PyObject *unicode = NULL;
2681 int err;
2682
2683 if (file == NULL)
2684 return -1;
2685
2686 unicode = PyUnicode_FromString(text);
2687 if (unicode == NULL)
2688 return -1;
2689
2690 err = sys_pyfile_write_unicode(unicode, file);
2691 Py_DECREF(unicode);
2692 return err;
2693}
Guido van Rossuma890e681998-05-12 14:59:24 +00002694
2695/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2696 Adapted from code submitted by Just van Rossum.
2697
2698 PySys_WriteStdout(format, ...)
2699 PySys_WriteStderr(format, ...)
2700
2701 The first function writes to sys.stdout; the second to sys.stderr. When
2702 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002703 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002704
Victor Stinner14284c22010-04-23 12:02:30 +00002705 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002706 signal handlers: they may raise a new exception whereas sys_write()
2707 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002708
Guido van Rossuma890e681998-05-12 14:59:24 +00002709 Both take a printf-style format string as their first argument followed
2710 by a variable length argument list determined by the format string.
2711
2712 *** WARNING ***
2713
2714 The format should limit the total size of the formatted output string to
2715 1000 bytes. In particular, this means that no unrestricted "%s" formats
2716 should occur; these should be limited using "%.<N>s where <N> is a
2717 decimal number calculated so that <N> plus the maximum size of other
2718 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2719 which can print hundreds of digits for very large numbers.
2720
2721 */
2722
2723static void
Victor Stinner09054372013-11-06 22:41:44 +01002724sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyObject *file;
2727 PyObject *error_type, *error_value, *error_traceback;
2728 char buffer[1001];
2729 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002732 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002733 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2734 if (sys_pyfile_write(buffer, file) != 0) {
2735 PyErr_Clear();
2736 fputs(buffer, fp);
2737 }
2738 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2739 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002740 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002741 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002742 }
2743 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002744}
2745
2746void
Guido van Rossuma890e681998-05-12 14:59:24 +00002747PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002748{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002749 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002751 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002752 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002753 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002754}
2755
2756void
Guido van Rossuma890e681998-05-12 14:59:24 +00002757PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002759 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002760
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002761 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002762 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002763 va_end(va);
2764}
2765
2766static void
Victor Stinner09054372013-11-06 22:41:44 +01002767sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002768{
2769 PyObject *file, *message;
2770 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002771 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002772
2773 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002774 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002775 message = PyUnicode_FromFormatV(format, va);
2776 if (message != NULL) {
2777 if (sys_pyfile_write_unicode(message, file) != 0) {
2778 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002779 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002780 if (utf8 != NULL)
2781 fputs(utf8, fp);
2782 }
2783 Py_DECREF(message);
2784 }
2785 PyErr_Restore(error_type, error_value, error_traceback);
2786}
2787
2788void
2789PySys_FormatStdout(const char *format, ...)
2790{
2791 va_list va;
2792
2793 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002794 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002795 va_end(va);
2796}
2797
2798void
2799PySys_FormatStderr(const char *format, ...)
2800{
2801 va_list va;
2802
2803 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002804 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002805 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002806}