blob: cdc2edf038a13967705f824e25f1291d3cc28a42 [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) {
277 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
278 return NULL;
279 }
Eric Snow3f9eee62017-09-15 16:35:20 -0600280 Py_DECREF(builtins);
Moshe Zadka03897ea2001-07-23 13:32:43 +0000281
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000282 /* Print value except if None */
283 /* After printing, also assign to '_' */
284 /* Before, set '_' to None to avoid recursion */
285 if (o == Py_None) {
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200286 Py_RETURN_NONE;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000287 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200288 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000289 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100290 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000291 if (outf == NULL || outf == Py_None) {
292 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
293 return NULL;
294 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000295 if (PyFile_WriteObject(o, outf, 0) != 0) {
296 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
297 /* repr(o) is not encodable to sys.stdout.encoding with
298 * sys.stdout.errors error handler (which is probably 'strict') */
299 PyErr_Clear();
300 err = sys_displayhook_unencodable(outf, o);
301 if (err)
302 return NULL;
303 }
304 else {
305 return NULL;
306 }
307 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100308 if (newline == NULL) {
309 newline = PyUnicode_FromString("\n");
310 if (newline == NULL)
311 return NULL;
312 }
313 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200315 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200317 Py_RETURN_NONE;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000318}
319
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000320PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000321"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000322"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000323"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000324);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000325
326static PyObject *
327sys_excepthook(PyObject* self, PyObject* args)
328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject *exc, *value, *tb;
330 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
331 return NULL;
332 PyErr_Display(exc, value, tb);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200333 Py_RETURN_NONE;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000334}
335
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000336PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000337"excepthook(exctype, value, traceback) -> None\n"
338"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000339"Handle an exception by displaying it with a traceback on sys.stderr.\n"
340);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000341
342static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000343sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000344{
Mark Shannonae3087c2017-10-22 22:41:51 +0100345 _PyErr_StackItem *err_info = _PyErr_GetTopmostException(PyThreadState_GET());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 return Py_BuildValue(
347 "(OOO)",
Mark Shannonae3087c2017-10-22 22:41:51 +0100348 err_info->exc_type != NULL ? err_info->exc_type : Py_None,
349 err_info->exc_value != NULL ? err_info->exc_value : Py_None,
350 err_info->exc_traceback != NULL ?
351 err_info->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000352}
353
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000354PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000355"exc_info() -> (type, value, traceback)\n\
356\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000357Return information about the most recent exception caught by an except\n\
358clause in the current stack frame or in an older stack frame."
359);
360
361static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000362sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000363{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 PyObject *exit_code = 0;
365 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
366 return NULL;
367 /* Raise SystemExit so callers may catch it or clean up. */
368 PyErr_SetObject(PyExc_SystemExit, exit_code);
369 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000370}
371
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000372PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000373"exit([status])\n\
374\n\
375Exit the interpreter by raising SystemExit(status).\n\
376If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300377If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000378If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000379exit status will be one (i.e., failure)."
380);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000381
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000382
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000383static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000384sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000387}
388
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000389PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000390"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000391\n\
392Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000393implementation."
394);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000395
396static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000397sys_getfilesystemencoding(PyObject *self)
398{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (Py_FileSystemDefaultEncoding)
400 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200401 PyErr_SetString(PyExc_RuntimeError,
402 "filesystem encoding is not initialized");
403 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000404}
405
406PyDoc_STRVAR(getfilesystemencoding_doc,
407"getfilesystemencoding() -> string\n\
408\n\
409Return the encoding used to convert Unicode filenames in\n\
410operating system filenames."
411);
412
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000413static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700414sys_getfilesystemencodeerrors(PyObject *self)
415{
416 if (Py_FileSystemDefaultEncodeErrors)
417 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
418 PyErr_SetString(PyExc_RuntimeError,
419 "filesystem encoding is not initialized");
420 return NULL;
421}
422
423PyDoc_STRVAR(getfilesystemencodeerrors_doc,
424 "getfilesystemencodeerrors() -> string\n\
425\n\
426Return the error mode used to convert Unicode filenames in\n\
427operating system filenames."
428);
429
430static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000431sys_intern(PyObject *self, PyObject *args)
432{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000433 PyObject *s;
434 if (!PyArg_ParseTuple(args, "U:intern", &s))
435 return NULL;
436 if (PyUnicode_CheckExact(s)) {
437 Py_INCREF(s);
438 PyUnicode_InternInPlace(&s);
439 return s;
440 }
441 else {
442 PyErr_Format(PyExc_TypeError,
443 "can't intern %.400s", s->ob_type->tp_name);
444 return NULL;
445 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000446}
447
448PyDoc_STRVAR(intern_doc,
449"intern(string) -> string\n\
450\n\
451``Intern'' the given string. This enters the string in the (global)\n\
452table of interned strings whose purpose is to speed up dictionary lookups.\n\
453Return the string itself or the previously interned string object with the\n\
454same value.");
455
456
Fred Drake5755ce62001-06-27 19:19:46 +0000457/*
458 * Cached interned string objects used for calling the profile and
459 * trace functions. Initialized by trace_init().
460 */
Nick Coghlan5a851672017-09-08 10:14:16 +1000461static PyObject *whatstrings[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000462
463static int
464trace_init(void)
465{
Nick Coghlan5a851672017-09-08 10:14:16 +1000466 static const char * const whatnames[8] = {
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200467 "call", "exception", "line", "return",
Nick Coghlan5a851672017-09-08 10:14:16 +1000468 "c_call", "c_exception", "c_return",
469 "opcode"
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200470 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyObject *name;
472 int i;
Nick Coghlan5a851672017-09-08 10:14:16 +1000473 for (i = 0; i < 8; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (whatstrings[i] == NULL) {
475 name = PyUnicode_InternFromString(whatnames[i]);
476 if (name == NULL)
477 return -1;
478 whatstrings[i] = name;
479 }
480 }
481 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000482}
483
484
485static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100486call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000487 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000488{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000489 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200490 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000491
Victor Stinner78da82b2016-08-20 01:22:57 +0200492 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200494 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100495
Victor Stinner78da82b2016-08-20 01:22:57 +0200496 stack[0] = (PyObject *)frame;
497 stack[1] = whatstrings[what];
498 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000499
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200501 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000502
Victor Stinner78da82b2016-08-20 01:22:57 +0200503 PyFrame_LocalsToFast(frame, 1);
504 if (result == NULL) {
505 PyTraceBack_Here(frame);
506 }
507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000508 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000509}
510
511static int
512profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 if (arg == NULL)
518 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100519 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (result == NULL) {
521 PyEval_SetProfile(NULL, NULL);
522 return -1;
523 }
524 Py_DECREF(result);
525 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000526}
527
528static int
529trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000530 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000532 PyObject *callback;
533 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000535 if (what == PyTrace_CALL)
536 callback = self;
537 else
538 callback = frame->f_trace;
539 if (callback == NULL)
540 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100541 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (result == NULL) {
543 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200544 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000545 return -1;
546 }
547 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300548 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000549 }
550 else {
551 Py_DECREF(result);
552 }
553 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000554}
Fred Draked0838392001-06-16 21:02:31 +0000555
Fred Drake8b4d01d2000-05-09 19:57:01 +0000556static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000557sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (trace_init() == -1)
560 return NULL;
561 if (args == Py_None)
562 PyEval_SetTrace(NULL, NULL);
563 else
564 PyEval_SetTrace(trace_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200565 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000566}
567
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000568PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000569"settrace(function)\n\
570\n\
571Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000572function call. See the debugger chapter in the library manual."
573);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000574
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000575static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000576sys_gettrace(PyObject *self, PyObject *args)
577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000578 PyThreadState *tstate = PyThreadState_GET();
579 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000581 if (temp == NULL)
582 temp = Py_None;
583 Py_INCREF(temp);
584 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000585}
586
587PyDoc_STRVAR(gettrace_doc,
588"gettrace()\n\
589\n\
590Return the global debug tracing function set with sys.settrace.\n\
591See the debugger chapter in the library manual."
592);
593
594static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000595sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000596{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000597 if (trace_init() == -1)
598 return NULL;
599 if (args == Py_None)
600 PyEval_SetProfile(NULL, NULL);
601 else
602 PyEval_SetProfile(profile_trampoline, args);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200603 Py_RETURN_NONE;
Guido van Rossume2437a11992-03-23 18:20:18 +0000604}
605
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000606PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000607"setprofile(function)\n\
608\n\
609Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000610and return. See the profiler chapter in the library manual."
611);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000612
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000613static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000614sys_getprofile(PyObject *self, PyObject *args)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 PyThreadState *tstate = PyThreadState_GET();
617 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (temp == NULL)
620 temp = Py_None;
621 Py_INCREF(temp);
622 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000623}
624
625PyDoc_STRVAR(getprofile_doc,
626"getprofile()\n\
627\n\
628Return the profiling function set with sys.setprofile.\n\
629See the profiler chapter in the library manual."
630);
631
632static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000633sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 if (PyErr_WarnEx(PyExc_DeprecationWarning,
636 "sys.getcheckinterval() and sys.setcheckinterval() "
637 "are deprecated. Use sys.setswitchinterval() "
638 "instead.", 1) < 0)
639 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600640 PyInterpreterState *interp = PyThreadState_GET()->interp;
641 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &interp->check_interval))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200643 Py_RETURN_NONE;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000644}
645
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000646PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000647"setcheckinterval(n)\n\
648\n\
649Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000650n instructions. This also affects how often thread switches occur."
651);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000652
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000653static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000654sys_getcheckinterval(PyObject *self, PyObject *args)
655{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 if (PyErr_WarnEx(PyExc_DeprecationWarning,
657 "sys.getcheckinterval() and sys.setcheckinterval() "
658 "are deprecated. Use sys.getswitchinterval() "
659 "instead.", 1) < 0)
660 return NULL;
Eric Snow2ebc5ce2017-09-07 23:51:28 -0600661 PyInterpreterState *interp = PyThreadState_GET()->interp;
662 return PyLong_FromLong(interp->check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000663}
664
665PyDoc_STRVAR(getcheckinterval_doc,
666"getcheckinterval() -> current check interval; see setcheckinterval()."
667);
668
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000669static PyObject *
670sys_setswitchinterval(PyObject *self, PyObject *args)
671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 double d;
673 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
674 return NULL;
675 if (d <= 0.0) {
676 PyErr_SetString(PyExc_ValueError,
677 "switch interval must be strictly positive");
678 return NULL;
679 }
680 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200681 Py_RETURN_NONE;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000682}
683
684PyDoc_STRVAR(setswitchinterval_doc,
685"setswitchinterval(n)\n\
686\n\
687Set the ideal thread switching delay inside the Python interpreter\n\
688The actual frequency of switching threads can be lower if the\n\
689interpreter executes long sequences of uninterruptible code\n\
690(this is implementation-specific and workload-dependent).\n\
691\n\
692The parameter must represent the desired switching delay in seconds\n\
693A typical value is 0.005 (5 milliseconds)."
694);
695
696static PyObject *
697sys_getswitchinterval(PyObject *self, PyObject *args)
698{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000700}
701
702PyDoc_STRVAR(getswitchinterval_doc,
703"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
704);
705
Tim Peterse5e065b2003-07-06 18:36:54 +0000706static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000707sys_setrecursionlimit(PyObject *self, PyObject *args)
708{
Victor Stinner50856d52015-10-13 00:11:21 +0200709 int new_limit, mark;
710 PyThreadState *tstate;
711
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
713 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200714
715 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000716 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200717 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 return NULL;
719 }
Victor Stinner50856d52015-10-13 00:11:21 +0200720
721 /* Issue #25274: When the recursion depth hits the recursion limit in
722 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
723 set to 1 and a RecursionError is raised. The overflowed flag is reset
724 to 0 when the recursion depth goes below the low-water mark: see
725 Py_LeaveRecursiveCall().
726
727 Reject too low new limit if the current recursion depth is higher than
728 the new low-water mark. Otherwise it may not be possible anymore to
729 reset the overflowed flag to 0. */
730 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
731 tstate = PyThreadState_GET();
732 if (tstate->recursion_depth >= mark) {
733 PyErr_Format(PyExc_RecursionError,
734 "cannot set the recursion limit to %i at "
735 "the recursion depth %i: the limit is too low",
736 new_limit, tstate->recursion_depth);
737 return NULL;
738 }
739
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000740 Py_SetRecursionLimit(new_limit);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200741 Py_RETURN_NONE;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000742}
743
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800744/*[clinic input]
745sys.set_coroutine_origin_tracking_depth
746
747 depth: int
748
749Enable or disable origin tracking for coroutine objects in this thread.
750
751Coroutine objects will track 'depth' frames of traceback information about
752where they came from, available in their cr_origin attribute. Set depth of 0
753to disable.
754[clinic start generated code]*/
755
756static PyObject *
757sys_set_coroutine_origin_tracking_depth_impl(PyObject *module, int depth)
758/*[clinic end generated code: output=0a2123c1cc6759c5 input=9083112cccc1bdcb]*/
759{
760 if (depth < 0) {
761 PyErr_SetString(PyExc_ValueError, "depth must be >= 0");
762 return NULL;
763 }
764 _PyEval_SetCoroutineOriginTrackingDepth(depth);
765 Py_RETURN_NONE;
766}
767
768/*[clinic input]
769sys.get_coroutine_origin_tracking_depth -> int
770
771Check status of origin tracking for coroutine objects in this thread.
772[clinic start generated code]*/
773
774static int
775sys_get_coroutine_origin_tracking_depth_impl(PyObject *module)
776/*[clinic end generated code: output=3699f7be95a3afb8 input=335266a71205b61a]*/
777{
778 return _PyEval_GetCoroutineOriginTrackingDepth();
779}
780
Yury Selivanov75445082015-05-11 22:57:16 -0400781static PyObject *
782sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
783{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800784 if (PyErr_WarnEx(PyExc_DeprecationWarning,
785 "set_coroutine_wrapper is deprecated", 1) < 0) {
786 return NULL;
787 }
788
Yury Selivanov75445082015-05-11 22:57:16 -0400789 if (wrapper != Py_None) {
790 if (!PyCallable_Check(wrapper)) {
791 PyErr_Format(PyExc_TypeError,
792 "callable expected, got %.50s",
793 Py_TYPE(wrapper)->tp_name);
794 return NULL;
795 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400796 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400797 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400798 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400799 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400800 }
Yury Selivanov75445082015-05-11 22:57:16 -0400801 Py_RETURN_NONE;
802}
803
804PyDoc_STRVAR(set_coroutine_wrapper_doc,
805"set_coroutine_wrapper(wrapper)\n\
806\n\
807Set a wrapper for coroutine objects."
808);
809
810static PyObject *
811sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
812{
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -0800813 if (PyErr_WarnEx(PyExc_DeprecationWarning,
814 "get_coroutine_wrapper is deprecated", 1) < 0) {
815 return NULL;
816 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400817 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400818 if (wrapper == NULL) {
819 wrapper = Py_None;
820 }
821 Py_INCREF(wrapper);
822 return wrapper;
823}
824
825PyDoc_STRVAR(get_coroutine_wrapper_doc,
826"get_coroutine_wrapper()\n\
827\n\
828Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
829);
830
831
Yury Selivanoveb636452016-09-08 22:01:51 -0700832static PyTypeObject AsyncGenHooksType;
833
834PyDoc_STRVAR(asyncgen_hooks_doc,
835"asyncgen_hooks\n\
836\n\
837A struct sequence providing information about asynhronous\n\
838generators hooks. The attributes are read only.");
839
840static PyStructSequence_Field asyncgen_hooks_fields[] = {
841 {"firstiter", "Hook to intercept first iteration"},
842 {"finalizer", "Hook to intercept finalization"},
843 {0}
844};
845
846static PyStructSequence_Desc asyncgen_hooks_desc = {
847 "asyncgen_hooks", /* name */
848 asyncgen_hooks_doc, /* doc */
849 asyncgen_hooks_fields , /* fields */
850 2
851};
852
853
854static PyObject *
855sys_set_asyncgen_hooks(PyObject *self, PyObject *args, PyObject *kw)
856{
857 static char *keywords[] = {"firstiter", "finalizer", NULL};
858 PyObject *firstiter = NULL;
859 PyObject *finalizer = NULL;
860
861 if (!PyArg_ParseTupleAndKeywords(
862 args, kw, "|OO", keywords,
863 &firstiter, &finalizer)) {
864 return NULL;
865 }
866
867 if (finalizer && finalizer != Py_None) {
868 if (!PyCallable_Check(finalizer)) {
869 PyErr_Format(PyExc_TypeError,
870 "callable finalizer expected, got %.50s",
871 Py_TYPE(finalizer)->tp_name);
872 return NULL;
873 }
874 _PyEval_SetAsyncGenFinalizer(finalizer);
875 }
876 else if (finalizer == Py_None) {
877 _PyEval_SetAsyncGenFinalizer(NULL);
878 }
879
880 if (firstiter && firstiter != Py_None) {
881 if (!PyCallable_Check(firstiter)) {
882 PyErr_Format(PyExc_TypeError,
883 "callable firstiter expected, got %.50s",
884 Py_TYPE(firstiter)->tp_name);
885 return NULL;
886 }
887 _PyEval_SetAsyncGenFirstiter(firstiter);
888 }
889 else if (firstiter == Py_None) {
890 _PyEval_SetAsyncGenFirstiter(NULL);
891 }
892
893 Py_RETURN_NONE;
894}
895
896PyDoc_STRVAR(set_asyncgen_hooks_doc,
897"set_asyncgen_hooks(*, firstiter=None, finalizer=None)\n\
898\n\
899Set a finalizer for async generators objects."
900);
901
902static PyObject *
903sys_get_asyncgen_hooks(PyObject *self, PyObject *args)
904{
905 PyObject *res;
906 PyObject *firstiter = _PyEval_GetAsyncGenFirstiter();
907 PyObject *finalizer = _PyEval_GetAsyncGenFinalizer();
908
909 res = PyStructSequence_New(&AsyncGenHooksType);
910 if (res == NULL) {
911 return NULL;
912 }
913
914 if (firstiter == NULL) {
915 firstiter = Py_None;
916 }
917
918 if (finalizer == NULL) {
919 finalizer = Py_None;
920 }
921
922 Py_INCREF(firstiter);
923 PyStructSequence_SET_ITEM(res, 0, firstiter);
924
925 Py_INCREF(finalizer);
926 PyStructSequence_SET_ITEM(res, 1, finalizer);
927
928 return res;
929}
930
931PyDoc_STRVAR(get_asyncgen_hooks_doc,
932"get_asyncgen_hooks()\n\
933\n\
934Return a namedtuple of installed asynchronous generators hooks \
935(firstiter, finalizer)."
936);
937
938
Mark Dickinsondc787d22010-05-23 13:33:13 +0000939static PyTypeObject Hash_InfoType;
940
941PyDoc_STRVAR(hash_info_doc,
942"hash_info\n\
943\n\
944A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100945hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000946
947static PyStructSequence_Field hash_info_fields[] = {
948 {"width", "width of the type used for hashing, in bits"},
949 {"modulus", "prime number giving the modulus on which the hash "
950 "function is based"},
951 {"inf", "value to be used for hash of a positive infinity"},
952 {"nan", "value to be used for hash of a nan"},
953 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100954 {"algorithm", "name of the algorithm for hashing of str, bytes and "
955 "memoryviews"},
956 {"hash_bits", "internal output size of hash algorithm"},
957 {"seed_bits", "seed size of hash algorithm"},
958 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000959 {NULL, NULL}
960};
961
962static PyStructSequence_Desc hash_info_desc = {
963 "sys.hash_info",
964 hash_info_doc,
965 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100966 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000967};
968
Matthias Klosed885e952010-07-06 10:53:30 +0000969static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000970get_hash_info(void)
971{
972 PyObject *hash_info;
973 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100974 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000975 hash_info = PyStructSequence_New(&Hash_InfoType);
976 if (hash_info == NULL)
977 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100978 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000979 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000980 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000981 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000982 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000983 PyStructSequence_SET_ITEM(hash_info, field++,
984 PyLong_FromLong(_PyHASH_INF));
985 PyStructSequence_SET_ITEM(hash_info, field++,
986 PyLong_FromLong(_PyHASH_NAN));
987 PyStructSequence_SET_ITEM(hash_info, field++,
988 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100989 PyStructSequence_SET_ITEM(hash_info, field++,
990 PyUnicode_FromString(hashfunc->name));
991 PyStructSequence_SET_ITEM(hash_info, field++,
992 PyLong_FromLong(hashfunc->hash_bits));
993 PyStructSequence_SET_ITEM(hash_info, field++,
994 PyLong_FromLong(hashfunc->seed_bits));
995 PyStructSequence_SET_ITEM(hash_info, field++,
996 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000997 if (PyErr_Occurred()) {
998 Py_CLEAR(hash_info);
999 return NULL;
1000 }
1001 return hash_info;
1002}
1003
1004
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001005PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001006"setrecursionlimit(n)\n\
1007\n\
1008Set the maximum depth of the Python interpreter stack to n. This\n\
1009limit prevents infinite recursion from causing an overflow of the C\n\
1010stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001011dependent."
1012);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001013
1014static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001015sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001016{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001018}
1019
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001020PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001021"getrecursionlimit()\n\
1022\n\
1023Return the current value of the recursion limit, the maximum depth\n\
1024of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +00001025recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001026);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001027
Mark Hammond8696ebc2002-10-08 02:44:31 +00001028#ifdef MS_WINDOWS
1029PyDoc_STRVAR(getwindowsversion_doc,
1030"getwindowsversion()\n\
1031\n\
Eric Smithf7bb5782010-01-27 00:44:57 +00001032Return information about the running version of Windows as a named tuple.\n\
1033The members are named: major, minor, build, platform, service_pack,\n\
1034service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +02001035backward compatibility, only the first 5 items are available by indexing.\n\
Steve Dower74f4af72016-09-17 17:27:48 -07001036All elements are numbers, except service_pack and platform_type which are\n\
1037strings, and platform_version which is a 3-tuple. Platform is always 2.\n\
1038Product_type may be 1 for a workstation, 2 for a domain controller, 3 for a\n\
1039server. Platform_version is a 3-tuple containing a version number that is\n\
1040intended for identifying the OS rather than feature detection."
Mark Hammond8696ebc2002-10-08 02:44:31 +00001041);
1042
Eric Smithf7bb5782010-01-27 00:44:57 +00001043static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
1044
1045static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 {"major", "Major version number"},
1047 {"minor", "Minor version number"},
1048 {"build", "Build number"},
1049 {"platform", "Operating system platform"},
1050 {"service_pack", "Latest Service Pack installed on the system"},
1051 {"service_pack_major", "Service Pack major version number"},
1052 {"service_pack_minor", "Service Pack minor version number"},
1053 {"suite_mask", "Bit mask identifying available product suites"},
1054 {"product_type", "System product type"},
Steve Dower74f4af72016-09-17 17:27:48 -07001055 {"platform_version", "Diagnostic version number"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +00001057};
1058
1059static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001060 "sys.getwindowsversion", /* name */
1061 getwindowsversion_doc, /* doc */
1062 windows_version_fields, /* fields */
1063 5 /* For backward compatibility,
1064 only the first 5 items are accessible
1065 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +00001066};
1067
Steve Dower3e96f322015-03-02 08:01:10 -08001068/* Disable deprecation warnings about GetVersionEx as the result is
1069 being passed straight through to the caller, who is responsible for
1070 using it correctly. */
1071#pragma warning(push)
1072#pragma warning(disable:4996)
1073
Mark Hammond8696ebc2002-10-08 02:44:31 +00001074static PyObject *
1075sys_getwindowsversion(PyObject *self)
1076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 PyObject *version;
1078 int pos = 0;
1079 OSVERSIONINFOEX ver;
Steve Dower74f4af72016-09-17 17:27:48 -07001080 DWORD realMajor, realMinor, realBuild;
1081 HANDLE hKernel32;
1082 wchar_t kernel32_path[MAX_PATH];
1083 LPVOID verblock;
1084 DWORD verblock_size;
1085
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 ver.dwOSVersionInfoSize = sizeof(ver);
1087 if (!GetVersionEx((OSVERSIONINFO*) &ver))
1088 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +00001089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 version = PyStructSequence_New(&WindowsVersionType);
1091 if (version == NULL)
1092 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001093
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
1095 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
1096 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
1097 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
1098 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
1099 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
1100 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
1101 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
1102 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +00001103
Steve Dower74f4af72016-09-17 17:27:48 -07001104 realMajor = ver.dwMajorVersion;
1105 realMinor = ver.dwMinorVersion;
1106 realBuild = ver.dwBuildNumber;
1107
1108 // GetVersion will lie if we are running in a compatibility mode.
1109 // We need to read the version info from a system file resource
1110 // to accurately identify the OS version. If we fail for any reason,
1111 // just return whatever GetVersion said.
1112 hKernel32 = GetModuleHandleW(L"kernel32.dll");
1113 if (hKernel32 && GetModuleFileNameW(hKernel32, kernel32_path, MAX_PATH) &&
1114 (verblock_size = GetFileVersionInfoSizeW(kernel32_path, NULL)) &&
1115 (verblock = PyMem_RawMalloc(verblock_size))) {
1116 VS_FIXEDFILEINFO *ffi;
1117 UINT ffi_len;
1118
1119 if (GetFileVersionInfoW(kernel32_path, 0, verblock_size, verblock) &&
1120 VerQueryValueW(verblock, L"", (LPVOID)&ffi, &ffi_len)) {
1121 realMajor = HIWORD(ffi->dwProductVersionMS);
1122 realMinor = LOWORD(ffi->dwProductVersionMS);
1123 realBuild = HIWORD(ffi->dwProductVersionLS);
1124 }
1125 PyMem_RawFree(verblock);
1126 }
Segev Finer48fb7662017-06-04 20:52:27 +03001127 PyStructSequence_SET_ITEM(version, pos++, Py_BuildValue("(kkk)",
1128 realMajor,
1129 realMinor,
1130 realBuild
Steve Dower74f4af72016-09-17 17:27:48 -07001131 ));
1132
Serhiy Storchaka48d761e2013-12-17 15:11:24 +02001133 if (PyErr_Occurred()) {
1134 Py_DECREF(version);
1135 return NULL;
1136 }
Steve Dower74f4af72016-09-17 17:27:48 -07001137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001138 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +00001139}
1140
Steve Dower3e96f322015-03-02 08:01:10 -08001141#pragma warning(pop)
1142
Steve Dowercc16be82016-09-08 10:35:16 -07001143PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
1144"_enablelegacywindowsfsencoding()\n\
1145\n\
1146Changes the default filesystem encoding to mbcs:replace for consistency\n\
1147with earlier versions of Python. See PEP 529 for more information.\n\
1148\n\
1149This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
1150environment variable before launching Python."
1151);
1152
1153static PyObject *
1154sys_enablelegacywindowsfsencoding(PyObject *self)
1155{
1156 Py_FileSystemDefaultEncoding = "mbcs";
1157 Py_FileSystemDefaultEncodeErrors = "replace";
1158 Py_RETURN_NONE;
1159}
1160
Mark Hammond8696ebc2002-10-08 02:44:31 +00001161#endif /* MS_WINDOWS */
1162
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001163#ifdef HAVE_DLOPEN
1164static PyObject *
1165sys_setdlopenflags(PyObject *self, PyObject *args)
1166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001167 int new_val;
1168 PyThreadState *tstate = PyThreadState_GET();
1169 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
1170 return NULL;
1171 if (!tstate)
1172 return NULL;
1173 tstate->interp->dlopenflags = new_val;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001174 Py_RETURN_NONE;
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001175}
1176
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001177PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001178"setdlopenflags(n) -> None\n\
1179\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001180Set the flags used by the interpreter for dlopen calls, such as when the\n\
1181interpreter loads extension modules. Among other things, this will enable\n\
1182a lazy resolving of symbols when importing a module, if called as\n\
1183sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001184sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +01001185can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001186
1187static PyObject *
1188sys_getdlopenflags(PyObject *self, PyObject *args)
1189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001190 PyThreadState *tstate = PyThreadState_GET();
1191 if (!tstate)
1192 return NULL;
1193 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001194}
1195
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001196PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001197"getdlopenflags() -> int\n\
1198\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001199Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -04001200The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +00001201
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001202#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001203
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001204#ifdef USE_MALLOPT
1205/* Link with -lmalloc (or -lmpc) on an SGI */
1206#include <malloc.h>
1207
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001208static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001209sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001210{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001211 int flag;
1212 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
1213 return NULL;
1214 mallopt(M_DEBUG, flag);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001215 Py_RETURN_NONE;
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001216}
1217#endif /* USE_MALLOPT */
1218
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001219size_t
1220_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001223 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001224 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +00001225
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 /* Make sure the type is initialized. float gets initialized late */
1227 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001228 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001229
Benjamin Petersonce798522012-01-22 11:24:29 -05001230 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001231 if (method == NULL) {
1232 if (!PyErr_Occurred())
1233 PyErr_Format(PyExc_TypeError,
1234 "Type %.100s doesn't define __sizeof__",
1235 Py_TYPE(o)->tp_name);
1236 }
1237 else {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01001238 res = _PyObject_CallNoArg(method);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001239 Py_DECREF(method);
1240 }
1241
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001242 if (res == NULL)
1243 return (size_t)-1;
1244
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001245 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001246 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001247 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001248 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001250 if (size < 0) {
1251 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
1252 return (size_t)-1;
1253 }
1254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001256 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001257 return ((size_t)size) + sizeof(PyGC_Head);
1258 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001259}
1260
1261static PyObject *
1262sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1263{
1264 static char *kwlist[] = {"object", "default", 0};
1265 size_t size;
1266 PyObject *o, *dflt = NULL;
1267
1268 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1269 kwlist, &o, &dflt))
1270 return NULL;
1271
1272 size = _PySys_GetSizeOf(o);
1273
1274 if (size == (size_t)-1 && PyErr_Occurred()) {
1275 /* Has a default value been given */
1276 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1277 PyErr_Clear();
1278 Py_INCREF(dflt);
1279 return dflt;
1280 }
1281 else
1282 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001284
1285 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001286}
1287
1288PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001289"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001290\n\
1291Return the size of object in bytes.");
1292
1293static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001294sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001295{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001296 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001297}
1298
Tim Peters4be93d02002-07-07 19:59:50 +00001299#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001300static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001301sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001303 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001304}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001305#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001306
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001307PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001308"getrefcount(object) -> integer\n\
1309\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001310Return the reference count of object. The count returned is generally\n\
1311one higher than you might expect, because it includes the (temporary)\n\
1312reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001313);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001314
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001315static PyObject *
1316sys_getallocatedblocks(PyObject *self)
1317{
1318 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1319}
1320
1321PyDoc_STRVAR(getallocatedblocks_doc,
1322"getallocatedblocks() -> integer\n\
1323\n\
1324Return the number of memory blocks currently allocated, regardless of their\n\
1325size."
1326);
1327
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001328#ifdef COUNT_ALLOCS
1329static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001330sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001334 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001335}
1336#endif
1337
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001338PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001339"_getframe([depth]) -> frameobject\n\
1340\n\
1341Return a frame object from the call stack. If optional integer depth is\n\
1342given, return the frame object that many calls below the top of the stack.\n\
1343If that is deeper than the call stack, ValueError is raised. The default\n\
1344for depth is zero, returning the frame at the top of the call stack.\n\
1345\n\
1346This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001347purposes only."
1348);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001349
1350static PyObject *
1351sys_getframe(PyObject *self, PyObject *args)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 PyFrameObject *f = PyThreadState_GET()->frame;
1354 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001355
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001356 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1357 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001358
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 while (depth > 0 && f != NULL) {
1360 f = f->f_back;
1361 --depth;
1362 }
1363 if (f == NULL) {
1364 PyErr_SetString(PyExc_ValueError,
1365 "call stack is not deep enough");
1366 return NULL;
1367 }
1368 Py_INCREF(f);
1369 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001370}
1371
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001372PyDoc_STRVAR(current_frames_doc,
1373"_current_frames() -> dictionary\n\
1374\n\
1375Return a dictionary mapping each current thread T's thread id to T's\n\
1376current stack frame.\n\
1377\n\
1378This function should be used for specialized purposes only."
1379);
1380
1381static PyObject *
1382sys_current_frames(PyObject *self, PyObject *noargs)
1383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001385}
1386
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001387PyDoc_STRVAR(call_tracing_doc,
1388"call_tracing(func, args) -> object\n\
1389\n\
1390Call func(*args), while tracing is enabled. The tracing state is\n\
1391saved, and restored afterwards. This is intended to be called from\n\
1392a debugger from a checkpoint, to recursively debug some other code."
1393);
1394
1395static PyObject *
1396sys_call_tracing(PyObject *self, PyObject *args)
1397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyObject *func, *funcargs;
1399 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1400 return NULL;
1401 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001402}
1403
Jeremy Hylton985eba52003-02-05 23:13:00 +00001404PyDoc_STRVAR(callstats_doc,
1405"callstats() -> tuple of integers\n\
1406\n\
1407Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1408when Python was built. Otherwise, return None.\n\
1409\n\
1410When enabled, this function returns detailed, implementation-specific\n\
1411details about the number of function calls executed. The return value is\n\
1412a 11-tuple where the entries in the tuple are counts of:\n\
14130. all function calls\n\
14141. calls to PyFunction_Type objects\n\
14152. PyFunction calls that do not create an argument tuple\n\
14163. PyFunction calls that do not create an argument tuple\n\
1417 and bypass PyEval_EvalCodeEx()\n\
14184. PyMethod calls\n\
14195. PyMethod calls on bound methods\n\
14206. PyType calls\n\
14217. PyCFunction calls\n\
14228. generator calls\n\
14239. All other calls\n\
142410. Number of stack pops performed by call_function()"
1425);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001426
Victor Stinner048afd92016-11-28 11:59:04 +01001427static PyObject *
1428sys_callstats(PyObject *self)
1429{
1430 if (PyErr_WarnEx(PyExc_DeprecationWarning,
1431 "sys.callstats() has been deprecated in Python 3.7 "
1432 "and will be removed in the future", 1) < 0) {
1433 return NULL;
1434 }
1435
1436 Py_RETURN_NONE;
1437}
1438
1439
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001440#ifdef __cplusplus
1441extern "C" {
1442#endif
1443
David Malcolm49526f42012-06-22 14:55:41 -04001444static PyObject *
1445sys_debugmallocstats(PyObject *self, PyObject *args)
1446{
1447#ifdef WITH_PYMALLOC
Victor Stinner6bf992a2017-12-06 17:26:10 +01001448 if (_PyObject_DebugMallocStats(stderr)) {
Victor Stinner34be8072016-03-14 12:04:26 +01001449 fputc('\n', stderr);
1450 }
David Malcolm49526f42012-06-22 14:55:41 -04001451#endif
1452 _PyObject_DebugTypeStats(stderr);
1453
1454 Py_RETURN_NONE;
1455}
1456PyDoc_STRVAR(debugmallocstats_doc,
1457"_debugmallocstats()\n\
1458\n\
1459Print summary info to stderr about the state of\n\
1460pymalloc's structures.\n\
1461\n\
1462In Py_DEBUG mode, also perform some expensive internal consistency\n\
1463checks.\n\
1464");
1465
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001466#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001467/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001468extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001469#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001470
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001471#ifdef DYNAMIC_EXECUTION_PROFILE
1472/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001473extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001474#endif
1475
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001476#ifdef __cplusplus
1477}
1478#endif
1479
Christian Heimes15ebc882008-02-04 18:48:49 +00001480static PyObject *
1481sys_clear_type_cache(PyObject* self, PyObject* args)
1482{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyType_ClearCache();
1484 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001485}
1486
1487PyDoc_STRVAR(sys_clear_type_cache__doc__,
1488"_clear_type_cache() -> None\n\
1489Clear the internal type lookup cache.");
1490
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001491static PyObject *
1492sys_is_finalizing(PyObject* self, PyObject* args)
1493{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001494 return PyBool_FromLong(_Py_IsFinalizing());
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001495}
1496
1497PyDoc_STRVAR(is_finalizing_doc,
1498"is_finalizing()\n\
1499Return True if Python is exiting.");
1500
Christian Heimes15ebc882008-02-04 18:48:49 +00001501
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001502#ifdef ANDROID_API_LEVEL
1503PyDoc_STRVAR(getandroidapilevel_doc,
1504"getandroidapilevel()\n\
1505\n\
1506Return the build time API version of Android as an integer.");
1507
1508static PyObject *
1509sys_getandroidapilevel(PyObject *self)
1510{
1511 return PyLong_FromLong(ANDROID_API_LEVEL);
1512}
1513#endif /* ANDROID_API_LEVEL */
1514
1515
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001516static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 /* Might as well keep this in alphabetic order */
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04001518 {"breakpointhook", (PyCFunction)sys_breakpointhook,
1519 METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc},
Victor Stinner048afd92016-11-28 11:59:04 +01001520 {"callstats", (PyCFunction)sys_callstats, METH_NOARGS,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 callstats_doc},
1522 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1523 sys_clear_type_cache__doc__},
1524 {"_current_frames", sys_current_frames, METH_NOARGS,
1525 current_frames_doc},
1526 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1527 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1528 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1529 {"exit", sys_exit, METH_VARARGS, exit_doc},
1530 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1531 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001532#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1534 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001535#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001536 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1537 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001538#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001539 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001540#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001541#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001543#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1545 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001546 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1547 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001548#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001550#endif
1551#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001553#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001554 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1555 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1556 getrecursionlimit_doc},
1557 {"getsizeof", (PyCFunction)sys_getsizeof,
1558 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1559 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001560#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1562 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001563 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1564 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001565#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001566 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001567 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001568#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001570#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1572 setcheckinterval_doc},
1573 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1574 getcheckinterval_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1576 setswitchinterval_doc},
1577 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1578 getswitchinterval_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001579#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1581 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001582#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1584 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1585 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1586 setrecursionlimit_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001587 {"settrace", sys_settrace, METH_O, settrace_doc},
1588 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1589 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001590 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001591 debugmallocstats_doc},
Nathaniel J. Smithfc2f4072018-01-21 06:44:07 -08001592 SYS_SET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
1593 SYS_GET_COROUTINE_ORIGIN_TRACKING_DEPTH_METHODDEF
Yury Selivanov75445082015-05-11 22:57:16 -04001594 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1595 set_coroutine_wrapper_doc},
1596 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1597 get_coroutine_wrapper_doc},
Yury Selivanov87672d72016-09-09 00:05:42 -07001598 {"set_asyncgen_hooks", (PyCFunction)sys_set_asyncgen_hooks,
Yury Selivanoveb636452016-09-08 22:01:51 -07001599 METH_VARARGS | METH_KEYWORDS, set_asyncgen_hooks_doc},
1600 {"get_asyncgen_hooks", sys_get_asyncgen_hooks, METH_NOARGS,
1601 get_asyncgen_hooks_doc},
Victor Stinnerd6958ac2016-12-02 01:13:46 +01001602#ifdef ANDROID_API_LEVEL
1603 {"getandroidapilevel", (PyCFunction)sys_getandroidapilevel, METH_NOARGS,
1604 getandroidapilevel_doc},
1605#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001607};
1608
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001609static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001610list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001611{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyObject *list = PyList_New(0);
1613 int i;
1614 if (list == NULL)
1615 return NULL;
1616 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1617 PyObject *name = PyUnicode_FromString(
1618 PyImport_Inittab[i].name);
1619 if (name == NULL)
1620 break;
1621 PyList_Append(list, name);
1622 Py_DECREF(name);
1623 }
1624 if (PyList_Sort(list) != 0) {
1625 Py_DECREF(list);
1626 list = NULL;
1627 }
1628 if (list) {
1629 PyObject *v = PyList_AsTuple(list);
1630 Py_DECREF(list);
1631 list = v;
1632 }
1633 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001634}
1635
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001636/* Pre-initialization support for sys.warnoptions and sys._xoptions
1637 *
1638 * Modern internal code paths:
1639 * These APIs get called after _Py_InitializeCore and get to use the
1640 * regular CPython list, dict, and unicode APIs.
1641 *
1642 * Legacy embedding code paths:
1643 * The multi-phase initialization API isn't public yet, so embedding
1644 * apps still need to be able configure sys.warnoptions and sys._xoptions
1645 * before they call Py_Initialize. To support this, we stash copies of
1646 * the supplied wchar * sequences in linked lists, and then migrate the
1647 * contents of those lists to the sys module in _PyInitializeCore.
1648 *
1649 */
1650
1651struct _preinit_entry {
1652 wchar_t *value;
1653 struct _preinit_entry *next;
1654};
1655
1656typedef struct _preinit_entry *_Py_PreInitEntry;
1657
1658static _Py_PreInitEntry _preinit_warnoptions = NULL;
1659static _Py_PreInitEntry _preinit_xoptions = NULL;
1660
1661static _Py_PreInitEntry
1662_alloc_preinit_entry(const wchar_t *value)
1663{
1664 /* To get this to work, we have to initialize the runtime implicitly */
1665 _PyRuntime_Initialize();
1666
1667 /* Force default allocator, so we can ensure that it also gets used to
1668 * destroy the linked list in _clear_preinit_entries.
1669 */
1670 PyMemAllocatorEx old_alloc;
1671 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1672
1673 _Py_PreInitEntry node = PyMem_RawCalloc(1, sizeof(*node));
1674 if (node != NULL) {
1675 node->value = _PyMem_RawWcsdup(value);
1676 if (node->value == NULL) {
1677 PyMem_RawFree(node);
1678 node = NULL;
1679 };
1680 };
1681
1682 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1683 return node;
1684};
1685
1686static int
1687_append_preinit_entry(_Py_PreInitEntry *optionlist, const wchar_t *value)
1688{
1689 _Py_PreInitEntry new_entry = _alloc_preinit_entry(value);
1690 if (new_entry == NULL) {
1691 return -1;
1692 }
1693 /* We maintain the linked list in this order so it's easy to play back
1694 * the add commands in the same order later on in _Py_InitializeCore
1695 */
1696 _Py_PreInitEntry last_entry = *optionlist;
1697 if (last_entry == NULL) {
1698 *optionlist = new_entry;
1699 } else {
1700 while (last_entry->next != NULL) {
1701 last_entry = last_entry->next;
1702 }
1703 last_entry->next = new_entry;
1704 }
1705 return 0;
1706};
1707
1708static void
1709_clear_preinit_entries(_Py_PreInitEntry *optionlist)
1710{
1711 _Py_PreInitEntry current = *optionlist;
1712 *optionlist = NULL;
1713 /* Deallocate the nodes and their contents using the default allocator */
1714 PyMemAllocatorEx old_alloc;
1715 _PyMem_SetDefaultAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1716 while (current != NULL) {
1717 _Py_PreInitEntry next = current->next;
1718 PyMem_RawFree(current->value);
1719 PyMem_RawFree(current);
1720 current = next;
1721 }
1722 PyMem_SetAllocator(PYMEM_DOMAIN_RAW, &old_alloc);
1723};
1724
1725static void
1726_clear_all_preinit_options(void)
1727{
1728 _clear_preinit_entries(&_preinit_warnoptions);
1729 _clear_preinit_entries(&_preinit_xoptions);
1730}
1731
1732static int
1733_PySys_ReadPreInitOptions(void)
1734{
1735 /* Rerun the add commands with the actual sys module available */
1736 PyThreadState *tstate = PyThreadState_GET();
1737 if (tstate == NULL) {
1738 /* Still don't have a thread state, so something is wrong! */
1739 return -1;
1740 }
1741 _Py_PreInitEntry entry = _preinit_warnoptions;
1742 while (entry != NULL) {
1743 PySys_AddWarnOption(entry->value);
1744 entry = entry->next;
1745 }
1746 entry = _preinit_xoptions;
1747 while (entry != NULL) {
1748 PySys_AddXOption(entry->value);
1749 entry = entry->next;
1750 }
1751
1752 _clear_all_preinit_options();
1753 return 0;
1754};
1755
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001756static PyObject *
1757get_warnoptions(void)
1758{
Eric Snowdae02762017-09-14 00:35:58 -07001759 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001760 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001761 /* PEP432 TODO: we can reach this if warnoptions is NULL in the main
1762 * interpreter config. When that happens, we need to properly set
1763 * the `warnoptions` reference in the main interpreter config as well.
1764 *
1765 * For Python 3.7, we shouldn't be able to get here due to the
1766 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1767 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1768 * call optional for embedding applications, thus making this
1769 * reachable again.
1770 */
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001771 warnoptions = PyList_New(0);
1772 if (warnoptions == NULL)
1773 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001774 if (_PySys_SetObjectId(&PyId_warnoptions, warnoptions)) {
1775 Py_DECREF(warnoptions);
1776 return NULL;
1777 }
1778 Py_DECREF(warnoptions);
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001779 }
1780 return warnoptions;
1781}
Guido van Rossum23fff912000-12-15 22:02:05 +00001782
1783void
1784PySys_ResetWarnOptions(void)
1785{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001786 PyThreadState *tstate = PyThreadState_GET();
1787 if (tstate == NULL) {
1788 _clear_preinit_entries(&_preinit_warnoptions);
1789 return;
1790 }
1791
Eric Snowdae02762017-09-14 00:35:58 -07001792 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 if (warnoptions == NULL || !PyList_Check(warnoptions))
1794 return;
1795 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001796}
1797
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001798int
1799_PySys_AddWarnOptionWithError(PyObject *option)
Guido van Rossum23fff912000-12-15 22:02:05 +00001800{
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001801 PyObject *warnoptions = get_warnoptions();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001802 if (warnoptions == NULL) {
1803 return -1;
1804 }
1805 if (PyList_Append(warnoptions, option)) {
1806 return -1;
1807 }
1808 return 0;
1809}
1810
1811void
1812PySys_AddWarnOptionUnicode(PyObject *option)
1813{
1814 (void)_PySys_AddWarnOptionWithError(option);
Victor Stinner9ca9c252010-05-19 16:53:30 +00001815}
1816
1817void
1818PySys_AddWarnOption(const wchar_t *s)
1819{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001820 PyThreadState *tstate = PyThreadState_GET();
1821 if (tstate == NULL) {
1822 _append_preinit_entry(&_preinit_warnoptions, s);
1823 return;
1824 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001825 PyObject *unicode;
1826 unicode = PyUnicode_FromWideChar(s, -1);
1827 if (unicode == NULL)
1828 return;
1829 PySys_AddWarnOptionUnicode(unicode);
1830 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001831}
1832
Christian Heimes33fe8092008-04-13 13:53:33 +00001833int
1834PySys_HasWarnOptions(void)
1835{
Eric Snowdae02762017-09-14 00:35:58 -07001836 PyObject *warnoptions = _PySys_GetObjectId(&PyId_warnoptions);
Miss Islington (bot)ea773eb2018-12-10 04:37:09 -08001837 return (warnoptions != NULL && PyList_Check(warnoptions)
1838 && PyList_GET_SIZE(warnoptions) > 0);
Christian Heimes33fe8092008-04-13 13:53:33 +00001839}
1840
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001841static PyObject *
1842get_xoptions(void)
1843{
Eric Snowdae02762017-09-14 00:35:58 -07001844 PyObject *xoptions = _PySys_GetObjectId(&PyId__xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001845 if (xoptions == NULL || !PyDict_Check(xoptions)) {
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001846 /* PEP432 TODO: we can reach this if xoptions is NULL in the main
1847 * interpreter config. When that happens, we need to properly set
1848 * the `xoptions` reference in the main interpreter config as well.
1849 *
1850 * For Python 3.7, we shouldn't be able to get here due to the
1851 * combination of how _PyMainInterpreter_ReadConfig and _PySys_EndInit
1852 * work, but we expect 3.8+ to make the _PyMainInterpreter_ReadConfig
1853 * call optional for embedding applications, thus making this
1854 * reachable again.
1855 */
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001856 xoptions = PyDict_New();
Eric Snow2ebc5ce2017-09-07 23:51:28 -06001857 if (xoptions == NULL)
1858 return NULL;
Eric Snowdae02762017-09-14 00:35:58 -07001859 if (_PySys_SetObjectId(&PyId__xoptions, xoptions)) {
1860 Py_DECREF(xoptions);
1861 return NULL;
1862 }
1863 Py_DECREF(xoptions);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001864 }
1865 return xoptions;
1866}
1867
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001868int
1869_PySys_AddXOptionWithError(const wchar_t *s)
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001870{
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001871 PyObject *name = NULL, *value = NULL;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001872
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001873 PyObject *opts = get_xoptions();
1874 if (opts == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001875 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001876 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001877
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001878 const wchar_t *name_end = wcschr(s, L'=');
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001879 if (!name_end) {
1880 name = PyUnicode_FromWideChar(s, -1);
1881 value = Py_True;
1882 Py_INCREF(value);
1883 }
1884 else {
1885 name = PyUnicode_FromWideChar(s, name_end - s);
1886 value = PyUnicode_FromWideChar(name_end + 1, -1);
1887 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001888 if (name == NULL || value == NULL) {
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001889 goto error;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001890 }
1891 if (PyDict_SetItem(opts, name, value) < 0) {
1892 goto error;
1893 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001894 Py_DECREF(name);
1895 Py_DECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001896 return 0;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001897
1898error:
1899 Py_XDECREF(name);
1900 Py_XDECREF(value);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001901 return -1;
1902}
1903
1904void
1905PySys_AddXOption(const wchar_t *s)
1906{
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07001907 PyThreadState *tstate = PyThreadState_GET();
1908 if (tstate == NULL) {
1909 _append_preinit_entry(&_preinit_xoptions, s);
1910 return;
1911 }
Victor Stinnerf7e5b562017-11-15 15:48:08 -08001912 if (_PySys_AddXOptionWithError(s) < 0) {
1913 /* No return value, therefore clear error state if possible */
1914 if (_PyThreadState_UncheckedGet()) {
1915 PyErr_Clear();
1916 }
Victor Stinner0cae6092016-11-11 01:43:56 +01001917 }
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001918}
1919
1920PyObject *
1921PySys_GetXOptions(void)
1922{
1923 return get_xoptions();
1924}
1925
Guido van Rossum40552d01998-08-06 03:34:39 +00001926/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1927 Two literals concatenated works just fine. If you have a K&R compiler
1928 or other abomination that however *does* understand longer strings,
1929 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001930PyDoc_VAR(sys_doc) =
1931PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001932"This module provides access to some objects used or maintained by the\n\
1933interpreter and to functions that interact strongly with the interpreter.\n\
1934\n\
1935Dynamic objects:\n\
1936\n\
1937argv -- command line arguments; argv[0] is the script pathname if known\n\
1938path -- module search path; path[0] is the script directory, else ''\n\
1939modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001940\n\
1941displayhook -- called to show results in an interactive session\n\
1942excepthook -- called to handle any uncaught exception other than SystemExit\n\
1943 To customize printing in an interactive session or to install a custom\n\
1944 top-level exception handler, assign other functions to replace these.\n\
1945\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001946stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001947stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001948stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001949 By assigning other file objects (or objects that behave like files)\n\
1950 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001951\n\
1952last_type -- type of last uncaught exception\n\
1953last_value -- value of last uncaught exception\n\
1954last_traceback -- traceback of last uncaught exception\n\
1955 These three are only available in an interactive session after a\n\
1956 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001957"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001958)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001959/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001960PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001961"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001962Static objects:\n\
1963\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001964builtin_module_names -- tuple of module names built into this interpreter\n\
1965copyright -- copyright notice pertaining to this interpreter\n\
1966exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001967executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001968float_info -- a struct sequence with information about the float implementation.\n\
1969float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001970hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001971hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001972implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001973int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001974maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001975maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001976platform -- platform identifier\n\
1977prefix -- prefix used to find the Python library\n\
1978thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001979version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001980version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001981"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001982)
Steve Dowercc16be82016-09-08 10:35:16 -07001983#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001984/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001985PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001986"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001987winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001988"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001989)
Steve Dowercc16be82016-09-08 10:35:16 -07001990#endif /* MS_COREDLL */
1991#ifdef MS_WINDOWS
1992/* concatenating string here */
1993PyDoc_STR(
1994"_enablelegacywindowsfsencoding -- [Windows only] \n\
1995"
1996)
1997#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001998PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001999"__stdin__ -- the original stdin; don't touch!\n\
2000__stdout__ -- the original stdout; don't touch!\n\
2001__stderr__ -- the original stderr; don't touch!\n\
2002__displayhook__ -- the original displayhook; don't touch!\n\
2003__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002004\n\
2005Functions:\n\
2006\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00002007displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00002008excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002009exc_info() -- return thread-safe information about the current exception\n\
2010exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002011getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002012getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002013getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002014getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00002015getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00002016gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002017setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00002018setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002019setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00002020setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002021settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00002022"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00002023)
Fred Drakeccede592000-08-14 20:59:57 +00002024/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00002025
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002026
2027PyDoc_STRVAR(flags__doc__,
2028"sys.flags\n\
2029\n\
2030Flags provided through command line arguments or environment vars.");
2031
2032static PyTypeObject FlagsType;
2033
2034static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002036 {"inspect", "-i"},
2037 {"interactive", "-i"},
2038 {"optimize", "-O or -OO"},
2039 {"dont_write_bytecode", "-B"},
2040 {"no_user_site", "-s"},
2041 {"no_site", "-S"},
2042 {"ignore_environment", "-E"},
2043 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002044 /* {"unbuffered", "-u"}, */
2045 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00002046 {"bytes_warning", "-b"},
2047 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01002048 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02002049 {"isolated", "-I"},
Victor Stinner5e3806f2017-11-30 11:40:24 +01002050 {"dev_mode", "-X dev"},
Victor Stinner91106cd2017-12-13 12:29:09 +01002051 {"utf8_mode", "-X utf8"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002053};
2054
2055static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002056 "sys.flags", /* name */
2057 flags__doc__, /* doc */
2058 flags_fields, /* fields */
Victor Stinner91106cd2017-12-13 12:29:09 +01002059 15
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002060};
2061
2062static PyObject*
2063make_flags(void)
2064{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002065 int pos = 0;
2066 PyObject *seq;
Victor Stinner5e3806f2017-11-30 11:40:24 +01002067 _PyCoreConfig *core_config = &_PyGILState_GetInterpreterStateUnsafe()->core_config;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002069 seq = PyStructSequence_New(&FlagsType);
2070 if (seq == NULL)
2071 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002072
2073#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002074 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002077 SetFlag(Py_InspectFlag);
2078 SetFlag(Py_InteractiveFlag);
2079 SetFlag(Py_OptimizeFlag);
2080 SetFlag(Py_DontWriteBytecodeFlag);
2081 SetFlag(Py_NoUserSiteDirectory);
2082 SetFlag(Py_NoSiteFlag);
2083 SetFlag(Py_IgnoreEnvironmentFlag);
2084 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002085 /* SetFlag(saw_unbuffered_flag); */
2086 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00002087 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00002088 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01002089 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02002090 SetFlag(Py_IsolatedFlag);
Victor Stinner5e3806f2017-11-30 11:40:24 +01002091 PyStructSequence_SET_ITEM(seq, pos++, PyBool_FromLong(core_config->dev_mode));
Victor Stinner91106cd2017-12-13 12:29:09 +01002092 SetFlag(Py_UTF8Mode);
2093#undef SetFlag
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002094
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002095 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02002096 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002097 return NULL;
2098 }
2099 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00002100}
2101
Eric Smith0e5b5622009-02-06 01:32:42 +00002102PyDoc_STRVAR(version_info__doc__,
2103"sys.version_info\n\
2104\n\
2105Version information as a named tuple.");
2106
2107static PyTypeObject VersionInfoType;
2108
2109static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 {"major", "Major release number"},
2111 {"minor", "Minor release number"},
2112 {"micro", "Patch release number"},
Ned Deilyda4887a2016-11-04 17:03:34 -04002113 {"releaselevel", "'alpha', 'beta', 'candidate', or 'final'"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002114 {"serial", "Serial release number"},
2115 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00002116};
2117
2118static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 "sys.version_info", /* name */
2120 version_info__doc__, /* doc */
2121 version_info_fields, /* fields */
2122 5
Eric Smith0e5b5622009-02-06 01:32:42 +00002123};
2124
2125static PyObject *
2126make_version_info(void)
2127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 PyObject *version_info;
2129 char *s;
2130 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 version_info = PyStructSequence_New(&VersionInfoType);
2133 if (version_info == NULL) {
2134 return NULL;
2135 }
Eric Smith0e5b5622009-02-06 01:32:42 +00002136
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 /*
2138 * These release level checks are mutually exclusive and cover
2139 * the field, so don't get too fancy with the pre-processor!
2140 */
Eric Smith0e5b5622009-02-06 01:32:42 +00002141#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00002143#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002144 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00002145#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00002147#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002148 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00002149#endif
2150
2151#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002152 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002153#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002154 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00002155
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002156 SetIntItem(PY_MAJOR_VERSION);
2157 SetIntItem(PY_MINOR_VERSION);
2158 SetIntItem(PY_MICRO_VERSION);
2159 SetStrItem(s);
2160 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00002161#undef SetIntItem
2162#undef SetStrItem
2163
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002164 if (PyErr_Occurred()) {
2165 Py_CLEAR(version_info);
2166 return NULL;
2167 }
2168 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00002169}
2170
Brett Cannon3adc7b72012-07-09 14:22:12 -04002171/* sys.implementation values */
2172#define NAME "cpython"
2173const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01002174#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
2175#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07002176#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04002177const char *_PySys_ImplCacheTag = TAG;
2178#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04002179#undef MAJOR
2180#undef MINOR
2181#undef TAG
2182
Barry Warsaw409da152012-06-03 16:18:47 -04002183static PyObject *
2184make_impl_info(PyObject *version_info)
2185{
2186 int res;
2187 PyObject *impl_info, *value, *ns;
2188
2189 impl_info = PyDict_New();
2190 if (impl_info == NULL)
2191 return NULL;
2192
2193 /* populate the dict */
2194
Brett Cannon3adc7b72012-07-09 14:22:12 -04002195 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04002196 if (value == NULL)
2197 goto error;
2198 res = PyDict_SetItemString(impl_info, "name", value);
2199 Py_DECREF(value);
2200 if (res < 0)
2201 goto error;
2202
Brett Cannon3adc7b72012-07-09 14:22:12 -04002203 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04002204 if (value == NULL)
2205 goto error;
2206 res = PyDict_SetItemString(impl_info, "cache_tag", value);
2207 Py_DECREF(value);
2208 if (res < 0)
2209 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04002210
2211 res = PyDict_SetItemString(impl_info, "version", version_info);
2212 if (res < 0)
2213 goto error;
2214
2215 value = PyLong_FromLong(PY_VERSION_HEX);
2216 if (value == NULL)
2217 goto error;
2218 res = PyDict_SetItemString(impl_info, "hexversion", value);
2219 Py_DECREF(value);
2220 if (res < 0)
2221 goto error;
2222
doko@ubuntu.com55532312016-06-14 08:55:19 +02002223#ifdef MULTIARCH
2224 value = PyUnicode_FromString(MULTIARCH);
2225 if (value == NULL)
2226 goto error;
2227 res = PyDict_SetItemString(impl_info, "_multiarch", value);
2228 Py_DECREF(value);
2229 if (res < 0)
2230 goto error;
2231#endif
2232
Barry Warsaw409da152012-06-03 16:18:47 -04002233 /* dict ready */
2234
2235 ns = _PyNamespace_New(impl_info);
2236 Py_DECREF(impl_info);
2237 return ns;
2238
2239error:
2240 Py_CLEAR(impl_info);
2241 return NULL;
2242}
2243
Martin v. Löwis1a214512008-06-11 05:26:20 +00002244static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002245 PyModuleDef_HEAD_INIT,
2246 "sys",
2247 sys_doc,
2248 -1, /* multiple "initialization" just copies the module dict. */
2249 sys_methods,
2250 NULL,
2251 NULL,
2252 NULL,
2253 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00002254};
2255
Eric Snow6b4be192017-05-22 21:36:03 -07002256/* Updating the sys namespace, returning NULL pointer on error */
Victor Stinner8fea2522013-10-27 17:15:42 +01002257#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02002258 do { \
Victor Stinner58049602013-07-22 22:40:00 +02002259 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002260 if (v == NULL) { \
2261 goto err_occurred; \
2262 } \
Victor Stinner58049602013-07-22 22:40:00 +02002263 res = PyDict_SetItemString(sysdict, key, v); \
2264 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002265 goto err_occurred; \
Victor Stinner8fea2522013-10-27 17:15:42 +01002266 } \
2267 } while (0)
2268#define SET_SYS_FROM_STRING(key, value) \
2269 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01002270 PyObject *v = (value); \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002271 if (v == NULL) { \
2272 goto err_occurred; \
2273 } \
Victor Stinner8fea2522013-10-27 17:15:42 +01002274 res = PyDict_SetItemString(sysdict, key, v); \
2275 Py_DECREF(v); \
2276 if (res < 0) { \
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002277 goto err_occurred; \
Victor Stinner58049602013-07-22 22:40:00 +02002278 } \
2279 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00002280
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002281
2282_PyInitError
2283_PySys_BeginInit(PyObject **sysmod)
Eric Snow6b4be192017-05-22 21:36:03 -07002284{
2285 PyObject *m, *sysdict, *version_info;
2286 int res;
2287
Eric Snowd393c1b2017-09-14 12:18:12 -06002288 m = _PyModule_CreateInitialized(&sysmodule, PYTHON_API_VERSION);
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002289 if (m == NULL) {
2290 return _Py_INIT_ERR("failed to create a module object");
2291 }
Eric Snow6b4be192017-05-22 21:36:03 -07002292 sysdict = PyModule_GetDict(m);
2293
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002294 /* Check that stdin is not a directory
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002295 Using shell redirection, you can redirect stdin to a directory,
2296 crashing the Python interpreter. Catch this common mistake here
2297 and output a useful error message. Note that under MS Windows,
2298 the shell already prevents that. */
2299#ifndef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002300 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08002301 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02002302 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002303 S_ISDIR(sb.st_mode)) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002304 return _Py_INIT_USER_ERR("<stdin> is a directory, "
2305 "cannot continue");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002306 }
2307 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00002308#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00002309
Nick Coghland6009512014-11-20 21:39:37 +10002310 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00002311
Victor Stinner8fea2522013-10-27 17:15:42 +01002312 SET_SYS_FROM_STRING_BORROW("__displayhook__",
2313 PyDict_GetItemString(sysdict, "displayhook"));
2314 SET_SYS_FROM_STRING_BORROW("__excepthook__",
2315 PyDict_GetItemString(sysdict, "excepthook"));
Barry Warsaw36c1d1f2017-10-05 12:11:18 -04002316 SET_SYS_FROM_STRING_BORROW(
2317 "__breakpointhook__",
2318 PyDict_GetItemString(sysdict, "breakpointhook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002319 SET_SYS_FROM_STRING("version",
2320 PyUnicode_FromString(Py_GetVersion()));
2321 SET_SYS_FROM_STRING("hexversion",
2322 PyLong_FromLong(PY_VERSION_HEX));
Ned Deily5c4b0d02017-03-04 00:19:55 -05002323 SET_SYS_FROM_STRING("_git",
2324 Py_BuildValue("(szz)", "CPython", _Py_gitidentifier(),
2325 _Py_gitversion()));
INADA Naoki6b42eb12017-06-29 15:31:38 +09002326 SET_SYS_FROM_STRING("_framework", PyUnicode_FromString(_PYTHONFRAMEWORK));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002327 SET_SYS_FROM_STRING("api_version",
2328 PyLong_FromLong(PYTHON_API_VERSION));
2329 SET_SYS_FROM_STRING("copyright",
2330 PyUnicode_FromString(Py_GetCopyright()));
2331 SET_SYS_FROM_STRING("platform",
2332 PyUnicode_FromString(Py_GetPlatform()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002333 SET_SYS_FROM_STRING("maxsize",
2334 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
2335 SET_SYS_FROM_STRING("float_info",
2336 PyFloat_GetInfo());
2337 SET_SYS_FROM_STRING("int_info",
2338 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00002339 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002340 if (Hash_InfoType.tp_name == NULL) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002341 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0) {
2342 goto type_init_failed;
2343 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002344 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00002345 SET_SYS_FROM_STRING("hash_info",
2346 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002347 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03002348 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002349 SET_SYS_FROM_STRING("builtin_module_names",
2350 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02002351#if PY_BIG_ENDIAN
2352 SET_SYS_FROM_STRING("byteorder",
2353 PyUnicode_FromString("big"));
2354#else
2355 SET_SYS_FROM_STRING("byteorder",
2356 PyUnicode_FromString("little"));
2357#endif
Fred Drake099325e2000-08-14 15:47:03 +00002358
Guido van Rossum8b9ea871996-08-23 18:14:47 +00002359#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002360 SET_SYS_FROM_STRING("dllhandle",
2361 PyLong_FromVoidPtr(PyWin_DLLhModule));
2362 SET_SYS_FROM_STRING("winver",
2363 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00002364#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00002365#ifdef ABIFLAGS
2366 SET_SYS_FROM_STRING("abiflags",
2367 PyUnicode_FromString(ABIFLAGS));
2368#endif
Antoine Pitrou9583cac2010-10-21 13:42:28 +00002369
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002370 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002371 if (VersionInfoType.tp_name == NULL) {
2372 if (PyStructSequence_InitType2(&VersionInfoType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002373 &version_info_desc) < 0) {
2374 goto type_init_failed;
2375 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002376 }
Barry Warsaw409da152012-06-03 16:18:47 -04002377 version_info = make_version_info();
2378 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 /* prevent user from creating new instances */
2380 VersionInfoType.tp_init = NULL;
2381 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002382 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
2383 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
2384 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00002385
Barry Warsaw409da152012-06-03 16:18:47 -04002386 /* implementation */
2387 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
2388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002389 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02002390 if (FlagsType.tp_name == 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002391 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0) {
2392 goto type_init_failed;
2393 }
Victor Stinner1c8f0592013-07-22 22:24:54 +02002394 }
Eric Snow6b4be192017-05-22 21:36:03 -07002395 /* Set flags to their default values */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002396 SET_SYS_FROM_STRING("flags", make_flags());
Eric Smithf7bb5782010-01-27 00:44:57 +00002397
2398#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 /* getwindowsversion */
2400 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02002401 if (PyStructSequence_InitType2(&WindowsVersionType,
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002402 &windows_version_desc) < 0) {
2403 goto type_init_failed;
2404 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 /* prevent user from creating new instances */
2406 WindowsVersionType.tp_init = NULL;
2407 WindowsVersionType.tp_new = NULL;
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002408 assert(!PyErr_Occurred());
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002409 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002410 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) {
Antoine Pitrou871dfc42014-04-28 13:07:06 +02002411 PyErr_Clear();
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002412 }
Eric Smithf7bb5782010-01-27 00:44:57 +00002413#endif
2414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002416#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002417 SET_SYS_FROM_STRING("float_repr_style",
2418 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002419#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002420 SET_SYS_FROM_STRING("float_repr_style",
2421 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00002422#endif
2423
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002424 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
Victor Stinnerd5c355c2011-04-30 14:53:09 +02002425
Yury Selivanoveb636452016-09-08 22:01:51 -07002426 /* initialize asyncgen_hooks */
2427 if (AsyncGenHooksType.tp_name == NULL) {
2428 if (PyStructSequence_InitType2(
2429 &AsyncGenHooksType, &asyncgen_hooks_desc) < 0) {
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002430 goto type_init_failed;
Yury Selivanoveb636452016-09-08 22:01:51 -07002431 }
2432 }
2433
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002434 if (PyErr_Occurred()) {
2435 goto err_occurred;
2436 }
2437
2438 *sysmod = m;
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002439
Victor Stinnerf7e5b562017-11-15 15:48:08 -08002440 return _Py_INIT_OK();
2441
2442type_init_failed:
2443 return _Py_INIT_ERR("failed to initialize a type");
2444
2445err_occurred:
2446 return _Py_INIT_ERR("can't initialize sys module");
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002447}
2448
Eric Snow6b4be192017-05-22 21:36:03 -07002449#undef SET_SYS_FROM_STRING
Eric Snow6b4be192017-05-22 21:36:03 -07002450
2451/* Updating the sys namespace, returning integer error codes */
Eric Snow6b4be192017-05-22 21:36:03 -07002452#define SET_SYS_FROM_STRING_INT_RESULT(key, value) \
2453 do { \
2454 PyObject *v = (value); \
2455 if (v == NULL) \
2456 return -1; \
2457 res = PyDict_SetItemString(sysdict, key, v); \
2458 Py_DECREF(v); \
2459 if (res < 0) { \
2460 return res; \
2461 } \
2462 } while (0)
2463
2464int
Victor Stinner41264f12017-12-15 02:05:29 +01002465_PySys_EndInit(PyObject *sysdict, _PyMainInterpreterConfig *config)
Eric Snow6b4be192017-05-22 21:36:03 -07002466{
2467 int res;
2468
Victor Stinner41264f12017-12-15 02:05:29 +01002469 /* _PyMainInterpreterConfig_Read() must set all these variables */
2470 assert(config->module_search_path != NULL);
2471 assert(config->executable != NULL);
2472 assert(config->prefix != NULL);
2473 assert(config->base_prefix != NULL);
2474 assert(config->exec_prefix != NULL);
2475 assert(config->base_exec_prefix != NULL);
2476
Victor Stinnera5194112018-11-22 16:11:15 +01002477 SET_SYS_FROM_STRING_BORROW("path", config->module_search_path);
Victor Stinner41264f12017-12-15 02:05:29 +01002478 SET_SYS_FROM_STRING_BORROW("executable", config->executable);
2479 SET_SYS_FROM_STRING_BORROW("prefix", config->prefix);
2480 SET_SYS_FROM_STRING_BORROW("base_prefix", config->base_prefix);
2481 SET_SYS_FROM_STRING_BORROW("exec_prefix", config->exec_prefix);
2482 SET_SYS_FROM_STRING_BORROW("base_exec_prefix", config->base_exec_prefix);
2483
2484 if (config->argv != NULL) {
2485 SET_SYS_FROM_STRING_BORROW("argv", config->argv);
2486 }
2487 if (config->warnoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002488 SET_SYS_FROM_STRING_BORROW("warnoptions", config->warnoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002489 }
2490 if (config->xoptions != NULL) {
Victor Stinnera5194112018-11-22 16:11:15 +01002491 SET_SYS_FROM_STRING_BORROW("_xoptions", config->xoptions);
Victor Stinner41264f12017-12-15 02:05:29 +01002492 }
2493
Eric Snow6b4be192017-05-22 21:36:03 -07002494 /* Set flags to their final values */
2495 SET_SYS_FROM_STRING_INT_RESULT("flags", make_flags());
2496 /* prevent user from creating new instances */
2497 FlagsType.tp_init = NULL;
2498 FlagsType.tp_new = NULL;
2499 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
2500 if (res < 0) {
2501 if (!PyErr_ExceptionMatches(PyExc_KeyError)) {
2502 return res;
2503 }
2504 PyErr_Clear();
2505 }
2506
2507 SET_SYS_FROM_STRING_INT_RESULT("dont_write_bytecode",
2508 PyBool_FromLong(Py_DontWriteBytecodeFlag));
Eric Snow6b4be192017-05-22 21:36:03 -07002509
Eric Snowdae02762017-09-14 00:35:58 -07002510 if (get_warnoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002511 return -1;
Victor Stinner865de272017-06-08 13:27:47 +02002512
Eric Snowdae02762017-09-14 00:35:58 -07002513 if (get_xoptions() == NULL)
Eric Snow2ebc5ce2017-09-07 23:51:28 -06002514 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002515
Miss Islington (bot)c6d94c32018-03-25 04:27:57 -07002516 /* Transfer any sys.warnoptions and sys._xoptions set directly
2517 * by an embedding application from the linked list to the module. */
2518 if (_PySys_ReadPreInitOptions() != 0)
2519 return -1;
2520
Eric Snow6b4be192017-05-22 21:36:03 -07002521 if (PyErr_Occurred())
2522 return -1;
2523 return 0;
Victor Stinner41264f12017-12-15 02:05:29 +01002524
2525err_occurred:
2526 return -1;
Eric Snow6b4be192017-05-22 21:36:03 -07002527}
2528
Victor Stinner41264f12017-12-15 02:05:29 +01002529#undef SET_SYS_FROM_STRING_BORROW
Eric Snow6b4be192017-05-22 21:36:03 -07002530#undef SET_SYS_FROM_STRING_INT_RESULT
Eric Snow6b4be192017-05-22 21:36:03 -07002531
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002532static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002533makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00002534{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 int i, n;
2536 const wchar_t *p;
2537 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00002538
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 n = 1;
2540 p = path;
2541 while ((p = wcschr(p, delim)) != NULL) {
2542 n++;
2543 p++;
2544 }
2545 v = PyList_New(n);
2546 if (v == NULL)
2547 return NULL;
2548 for (i = 0; ; i++) {
2549 p = wcschr(path, delim);
2550 if (p == NULL)
2551 p = path + wcslen(path); /* End of string */
2552 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
2553 if (w == NULL) {
2554 Py_DECREF(v);
2555 return NULL;
2556 }
Miss Islington (bot)8b7d8ac2018-12-08 06:34:49 -08002557 PyList_SET_ITEM(v, i, w);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002558 if (*p == '\0')
2559 break;
2560 path = p+1;
2561 }
2562 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002563}
2564
2565void
Martin v. Löwis790465f2008-04-05 20:41:37 +00002566PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002568 PyObject *v;
2569 if ((v = makepathobject(path, DELIM)) == NULL)
2570 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01002571 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002572 Py_FatalError("can't assign sys.path");
2573 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002574}
2575
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002576static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002577makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002578{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002579 PyObject *av;
2580 if (argc <= 0 || argv == NULL) {
2581 /* Ensure at least one (empty) argument is seen */
2582 static wchar_t *empty_argv[1] = {L""};
2583 argv = empty_argv;
2584 argc = 1;
2585 }
2586 av = PyList_New(argc);
2587 if (av != NULL) {
2588 int i;
2589 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002590 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002591 if (v == NULL) {
2592 Py_DECREF(av);
2593 av = NULL;
2594 break;
2595 }
Victor Stinner11a247d2017-12-13 21:05:57 +01002596 PyList_SET_ITEM(av, i, v);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002597 }
2598 }
2599 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002600}
2601
Victor Stinner11a247d2017-12-13 21:05:57 +01002602void
2603PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Victor Stinnerd5dda982017-12-13 17:31:16 +01002604{
2605 PyObject *av = makeargvobject(argc, argv);
2606 if (av == NULL) {
Victor Stinner11a247d2017-12-13 21:05:57 +01002607 Py_FatalError("no mem for sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002608 }
2609 if (PySys_SetObject("argv", av) != 0) {
2610 Py_DECREF(av);
Victor Stinner11a247d2017-12-13 21:05:57 +01002611 Py_FatalError("can't assign sys.argv");
Victor Stinnerd5dda982017-12-13 17:31:16 +01002612 }
2613 Py_DECREF(av);
2614
2615 if (updatepath) {
2616 /* If argv[0] is not '-c' nor '-m', prepend argv[0] to sys.path.
2617 If argv[0] is a symlink, use the real path. */
Victor Stinner11a247d2017-12-13 21:05:57 +01002618 PyObject *argv0 = _PyPathConfig_ComputeArgv0(argc, argv);
2619 if (argv0 == NULL) {
2620 Py_FatalError("can't compute path0 from argv");
2621 }
Victor Stinnerd5dda982017-12-13 17:31:16 +01002622
Victor Stinner11a247d2017-12-13 21:05:57 +01002623 PyObject *sys_path = _PySys_GetObjectId(&PyId_path);
2624 if (sys_path != NULL) {
2625 if (PyList_Insert(sys_path, 0, argv0) < 0) {
2626 Py_DECREF(argv0);
2627 Py_FatalError("can't prepend path0 to sys.path");
2628 }
2629 }
2630 Py_DECREF(argv0);
Victor Stinnerd5dda982017-12-13 17:31:16 +01002631 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002632}
Guido van Rossuma890e681998-05-12 14:59:24 +00002633
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002634void
2635PySys_SetArgv(int argc, wchar_t **argv)
2636{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002637 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002638}
2639
Victor Stinner14284c22010-04-23 12:02:30 +00002640/* Reimplementation of PyFile_WriteString() no calling indirectly
2641 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2642
2643static int
Victor Stinner79766632010-08-16 17:36:42 +00002644sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002645{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002646 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002647 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002648
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002649 if (file == NULL)
2650 return -1;
2651
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002652 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002653 if (writer == NULL)
2654 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002655
Victor Stinner7bfb42d2016-12-05 17:04:32 +01002656 result = PyObject_CallFunctionObjArgs(writer, unicode, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002657 if (result == NULL) {
2658 goto error;
2659 } else {
2660 err = 0;
2661 goto finally;
2662 }
Victor Stinner14284c22010-04-23 12:02:30 +00002663
2664error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002665 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002666finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002667 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002668 Py_XDECREF(result);
2669 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002670}
2671
Victor Stinner79766632010-08-16 17:36:42 +00002672static int
2673sys_pyfile_write(const char *text, PyObject *file)
2674{
2675 PyObject *unicode = NULL;
2676 int err;
2677
2678 if (file == NULL)
2679 return -1;
2680
2681 unicode = PyUnicode_FromString(text);
2682 if (unicode == NULL)
2683 return -1;
2684
2685 err = sys_pyfile_write_unicode(unicode, file);
2686 Py_DECREF(unicode);
2687 return err;
2688}
Guido van Rossuma890e681998-05-12 14:59:24 +00002689
2690/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2691 Adapted from code submitted by Just van Rossum.
2692
2693 PySys_WriteStdout(format, ...)
2694 PySys_WriteStderr(format, ...)
2695
2696 The first function writes to sys.stdout; the second to sys.stderr. When
2697 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002698 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002699
Victor Stinner14284c22010-04-23 12:02:30 +00002700 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002701 signal handlers: they may raise a new exception whereas sys_write()
2702 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002703
Guido van Rossuma890e681998-05-12 14:59:24 +00002704 Both take a printf-style format string as their first argument followed
2705 by a variable length argument list determined by the format string.
2706
2707 *** WARNING ***
2708
2709 The format should limit the total size of the formatted output string to
2710 1000 bytes. In particular, this means that no unrestricted "%s" formats
2711 should occur; these should be limited using "%.<N>s where <N> is a
2712 decimal number calculated so that <N> plus the maximum size of other
2713 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2714 which can print hundreds of digits for very large numbers.
2715
2716 */
2717
2718static void
Victor Stinner09054372013-11-06 22:41:44 +01002719sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002721 PyObject *file;
2722 PyObject *error_type, *error_value, *error_traceback;
2723 char buffer[1001];
2724 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002726 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002727 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002728 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2729 if (sys_pyfile_write(buffer, file) != 0) {
2730 PyErr_Clear();
2731 fputs(buffer, fp);
2732 }
2733 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2734 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002735 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002737 }
2738 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002739}
2740
2741void
Guido van Rossuma890e681998-05-12 14:59:24 +00002742PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002745
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002746 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002747 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002749}
2750
2751void
Guido van Rossuma890e681998-05-12 14:59:24 +00002752PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002754 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002757 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002758 va_end(va);
2759}
2760
2761static void
Victor Stinner09054372013-11-06 22:41:44 +01002762sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002763{
2764 PyObject *file, *message;
2765 PyObject *error_type, *error_value, *error_traceback;
Serhiy Storchaka85b0f5b2016-11-20 10:16:47 +02002766 const char *utf8;
Victor Stinner79766632010-08-16 17:36:42 +00002767
2768 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002769 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002770 message = PyUnicode_FromFormatV(format, va);
2771 if (message != NULL) {
2772 if (sys_pyfile_write_unicode(message, file) != 0) {
2773 PyErr_Clear();
Serhiy Storchaka06515832016-11-20 09:13:07 +02002774 utf8 = PyUnicode_AsUTF8(message);
Victor Stinner79766632010-08-16 17:36:42 +00002775 if (utf8 != NULL)
2776 fputs(utf8, fp);
2777 }
2778 Py_DECREF(message);
2779 }
2780 PyErr_Restore(error_type, error_value, error_traceback);
2781}
2782
2783void
2784PySys_FormatStdout(const char *format, ...)
2785{
2786 va_list va;
2787
2788 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002789 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002790 va_end(va);
2791}
2792
2793void
2794PySys_FormatStderr(const char *format, ...)
2795{
2796 va_list va;
2797
2798 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002799 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002800 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002801}