blob: 0fe76b7a74d0e62612d12553123304f9fb48bfcb [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
Guido van Rossum3f5da241990-12-20 15:06:42 +00007Function member:
Guido van Rossumcc8914f1995-03-20 15:09:40 +00008- exit(sts): raise SystemExit
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009Data members:
10- stdin, stdout, stderr: standard file objects
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000011- modules: the table of modules (dictionary)
Guido van Rossum3f5da241990-12-20 15:06:42 +000012- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000015*/
16
Guido van Rossum65bf9f21997-04-29 18:33:38 +000017#include "Python.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000018#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000019#include "frameobject.h"
Victor Stinnerd5c355c2011-04-30 14:53:09 +020020#include "pythread.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000021
Guido van Rossume2437a11992-03-23 18:20:18 +000022#include "osdefs.h"
Stefan Krah1845d142016-04-25 21:38:53 +020023#include <locale.h>
Guido van Rossum3f5da241990-12-20 15:06:42 +000024
Mark Hammond8696ebc2002-10-08 02:44:31 +000025#ifdef MS_WINDOWS
26#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000027#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000028#endif /* MS_WINDOWS */
29
Guido van Rossum9b38a141996-09-11 23:12:24 +000030#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000031extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000032/* A string loaded from the DLL at startup: */
33extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000034#endif
35
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000036#ifdef HAVE_LANGINFO_H
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000037#include <langinfo.h>
38#endif
39
Victor Stinnerbd303c12013-11-07 23:07:29 +010040_Py_IDENTIFIER(_);
41_Py_IDENTIFIER(__sizeof__);
42_Py_IDENTIFIER(buffer);
43_Py_IDENTIFIER(builtins);
44_Py_IDENTIFIER(encoding);
45_Py_IDENTIFIER(path);
46_Py_IDENTIFIER(stdout);
47_Py_IDENTIFIER(stderr);
48_Py_IDENTIFIER(write);
49
Guido van Rossum65bf9f21997-04-29 18:33:38 +000050PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010051_PySys_GetObjectId(_Py_Identifier *key)
52{
53 PyThreadState *tstate = PyThreadState_GET();
54 PyObject *sd = tstate->interp->sysdict;
55 if (sd == NULL)
56 return NULL;
57 return _PyDict_GetItemId(sd, key);
58}
59
60PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000061PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000063 PyThreadState *tstate = PyThreadState_GET();
64 PyObject *sd = tstate->interp->sysdict;
65 if (sd == NULL)
66 return NULL;
67 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068}
69
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000070int
Victor Stinnerd67bd452013-11-06 22:36:40 +010071_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
72{
73 PyThreadState *tstate = PyThreadState_GET();
74 PyObject *sd = tstate->interp->sysdict;
75 if (v == NULL) {
76 if (_PyDict_GetItemId(sd, key) == NULL)
77 return 0;
78 else
79 return _PyDict_DelItemId(sd, key);
80 }
81 else
82 return _PyDict_SetItemId(sd, key, v);
83}
84
85int
Neal Norwitzf3081322007-08-25 00:32:45 +000086PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000087{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000088 PyThreadState *tstate = PyThreadState_GET();
89 PyObject *sd = tstate->interp->sysdict;
90 if (v == NULL) {
91 if (PyDict_GetItemString(sd, name) == NULL)
92 return 0;
93 else
94 return PyDict_DelItemString(sd, name);
95 }
96 else
97 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000098}
99
Victor Stinner13d49ee2010-12-04 17:24:33 +0000100/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
101 error handler. If sys.stdout has a buffer attribute, use
102 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
103 sys.stdout.write(redecoded).
104
105 Helper function for sys_displayhook(). */
106static int
107sys_displayhook_unencodable(PyObject *outf, PyObject *o)
108{
109 PyObject *stdout_encoding = NULL;
110 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
111 char *stdout_encoding_str;
112 int ret;
113
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200114 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000115 if (stdout_encoding == NULL)
116 goto error;
117 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
118 if (stdout_encoding_str == NULL)
119 goto error;
120
121 repr_str = PyObject_Repr(o);
122 if (repr_str == NULL)
123 goto error;
124 encoded = PyUnicode_AsEncodedString(repr_str,
125 stdout_encoding_str,
126 "backslashreplace");
127 Py_DECREF(repr_str);
128 if (encoded == NULL)
129 goto error;
130
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200131 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000132 if (buffer) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200133 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000134 Py_DECREF(buffer);
135 Py_DECREF(encoded);
136 if (result == NULL)
137 goto error;
138 Py_DECREF(result);
139 }
140 else {
141 PyErr_Clear();
142 escaped_str = PyUnicode_FromEncodedObject(encoded,
143 stdout_encoding_str,
144 "strict");
145 Py_DECREF(encoded);
146 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
147 Py_DECREF(escaped_str);
148 goto error;
149 }
150 Py_DECREF(escaped_str);
151 }
152 ret = 0;
153 goto finally;
154
155error:
156 ret = -1;
157finally:
158 Py_XDECREF(stdout_encoding);
159 return ret;
160}
161
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000162static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000163sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000164{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 PyObject *outf;
166 PyInterpreterState *interp = PyThreadState_GET()->interp;
167 PyObject *modules = interp->modules;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100168 PyObject *builtins;
169 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000170 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000171
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100172 builtins = _PyDict_GetItemId(modules, &PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000173 if (builtins == NULL) {
174 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
175 return NULL;
176 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000177
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000178 /* Print value except if None */
179 /* After printing, also assign to '_' */
180 /* Before, set '_' to None to avoid recursion */
181 if (o == Py_None) {
182 Py_INCREF(Py_None);
183 return Py_None;
184 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200185 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000186 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100187 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (outf == NULL || outf == Py_None) {
189 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
190 return NULL;
191 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000192 if (PyFile_WriteObject(o, outf, 0) != 0) {
193 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
194 /* repr(o) is not encodable to sys.stdout.encoding with
195 * sys.stdout.errors error handler (which is probably 'strict') */
196 PyErr_Clear();
197 err = sys_displayhook_unencodable(outf, o);
198 if (err)
199 return NULL;
200 }
201 else {
202 return NULL;
203 }
204 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100205 if (newline == NULL) {
206 newline = PyUnicode_FromString("\n");
207 if (newline == NULL)
208 return NULL;
209 }
210 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000211 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200212 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000213 return NULL;
214 Py_INCREF(Py_None);
215 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000216}
217
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000218PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000219"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000220"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000221"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000222);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000223
224static PyObject *
225sys_excepthook(PyObject* self, PyObject* args)
226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 PyObject *exc, *value, *tb;
228 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
229 return NULL;
230 PyErr_Display(exc, value, tb);
231 Py_INCREF(Py_None);
232 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000233}
234
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000235PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000236"excepthook(exctype, value, traceback) -> None\n"
237"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000238"Handle an exception by displaying it with a traceback on sys.stderr.\n"
239);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000240
241static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000242sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000244 PyThreadState *tstate;
245 tstate = PyThreadState_GET();
246 return Py_BuildValue(
247 "(OOO)",
248 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
249 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
250 tstate->exc_traceback != NULL ?
251 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000252}
253
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000254PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000255"exc_info() -> (type, value, traceback)\n\
256\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000257Return information about the most recent exception caught by an except\n\
258clause in the current stack frame or in an older stack frame."
259);
260
261static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000262sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000263{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 PyObject *exit_code = 0;
265 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
266 return NULL;
267 /* Raise SystemExit so callers may catch it or clean up. */
268 PyErr_SetObject(PyExc_SystemExit, exit_code);
269 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000270}
271
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000272PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000273"exit([status])\n\
274\n\
275Exit the interpreter by raising SystemExit(status).\n\
276If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300277If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000278If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000279exit status will be one (i.e., failure)."
280);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000281
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000282
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000283static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000284sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000286 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000287}
288
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000289PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000290"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000291\n\
292Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000293implementation."
294);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000295
296static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000297sys_getfilesystemencoding(PyObject *self)
298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 if (Py_FileSystemDefaultEncoding)
300 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200301 PyErr_SetString(PyExc_RuntimeError,
302 "filesystem encoding is not initialized");
303 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000304}
305
306PyDoc_STRVAR(getfilesystemencoding_doc,
307"getfilesystemencoding() -> string\n\
308\n\
309Return the encoding used to convert Unicode filenames in\n\
310operating system filenames."
311);
312
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000313static PyObject *
Steve Dowercc16be82016-09-08 10:35:16 -0700314sys_getfilesystemencodeerrors(PyObject *self)
315{
316 if (Py_FileSystemDefaultEncodeErrors)
317 return PyUnicode_FromString(Py_FileSystemDefaultEncodeErrors);
318 PyErr_SetString(PyExc_RuntimeError,
319 "filesystem encoding is not initialized");
320 return NULL;
321}
322
323PyDoc_STRVAR(getfilesystemencodeerrors_doc,
324 "getfilesystemencodeerrors() -> string\n\
325\n\
326Return the error mode used to convert Unicode filenames in\n\
327operating system filenames."
328);
329
330static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000331sys_intern(PyObject *self, PyObject *args)
332{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 PyObject *s;
334 if (!PyArg_ParseTuple(args, "U:intern", &s))
335 return NULL;
336 if (PyUnicode_CheckExact(s)) {
337 Py_INCREF(s);
338 PyUnicode_InternInPlace(&s);
339 return s;
340 }
341 else {
342 PyErr_Format(PyExc_TypeError,
343 "can't intern %.400s", s->ob_type->tp_name);
344 return NULL;
345 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000346}
347
348PyDoc_STRVAR(intern_doc,
349"intern(string) -> string\n\
350\n\
351``Intern'' the given string. This enters the string in the (global)\n\
352table of interned strings whose purpose is to speed up dictionary lookups.\n\
353Return the string itself or the previously interned string object with the\n\
354same value.");
355
356
Fred Drake5755ce62001-06-27 19:19:46 +0000357/*
358 * Cached interned string objects used for calling the profile and
359 * trace functions. Initialized by trace_init().
360 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000361static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000362
363static int
364trace_init(void)
365{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200366 static const char * const whatnames[7] = {
367 "call", "exception", "line", "return",
368 "c_call", "c_exception", "c_return"
369 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *name;
371 int i;
372 for (i = 0; i < 7; ++i) {
373 if (whatstrings[i] == NULL) {
374 name = PyUnicode_InternFromString(whatnames[i]);
375 if (name == NULL)
376 return -1;
377 whatstrings[i] = name;
378 }
379 }
380 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000381}
382
383
384static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100385call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000386 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000387{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000388 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200389 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000390
Victor Stinner78da82b2016-08-20 01:22:57 +0200391 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000392 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200393 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100394
Victor Stinner78da82b2016-08-20 01:22:57 +0200395 stack[0] = (PyObject *)frame;
396 stack[1] = whatstrings[what];
397 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200400 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000401
Victor Stinner78da82b2016-08-20 01:22:57 +0200402 PyFrame_LocalsToFast(frame, 1);
403 if (result == NULL) {
404 PyTraceBack_Here(frame);
405 }
406
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000408}
409
410static int
411profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000413{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000414 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 if (arg == NULL)
417 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100418 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 if (result == NULL) {
420 PyEval_SetProfile(NULL, NULL);
421 return -1;
422 }
423 Py_DECREF(result);
424 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000425}
426
427static int
428trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyObject *callback;
432 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (what == PyTrace_CALL)
435 callback = self;
436 else
437 callback = frame->f_trace;
438 if (callback == NULL)
439 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100440 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (result == NULL) {
442 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200443 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000444 return -1;
445 }
446 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300447 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 }
449 else {
450 Py_DECREF(result);
451 }
452 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000453}
Fred Draked0838392001-06-16 21:02:31 +0000454
Fred Drake8b4d01d2000-05-09 19:57:01 +0000455static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000456sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (trace_init() == -1)
459 return NULL;
460 if (args == Py_None)
461 PyEval_SetTrace(NULL, NULL);
462 else
463 PyEval_SetTrace(trace_trampoline, args);
464 Py_INCREF(Py_None);
465 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000466}
467
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000468PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000469"settrace(function)\n\
470\n\
471Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000472function call. See the debugger chapter in the library manual."
473);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000474
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000475static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000476sys_gettrace(PyObject *self, PyObject *args)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyThreadState *tstate = PyThreadState_GET();
479 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (temp == NULL)
482 temp = Py_None;
483 Py_INCREF(temp);
484 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000485}
486
487PyDoc_STRVAR(gettrace_doc,
488"gettrace()\n\
489\n\
490Return the global debug tracing function set with sys.settrace.\n\
491See the debugger chapter in the library manual."
492);
493
494static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000495sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (trace_init() == -1)
498 return NULL;
499 if (args == Py_None)
500 PyEval_SetProfile(NULL, NULL);
501 else
502 PyEval_SetProfile(profile_trampoline, args);
503 Py_INCREF(Py_None);
504 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000505}
506
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000507PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508"setprofile(function)\n\
509\n\
510Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000511and return. See the profiler chapter in the library manual."
512);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000513
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000514static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000515sys_getprofile(PyObject *self, PyObject *args)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyThreadState *tstate = PyThreadState_GET();
518 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (temp == NULL)
521 temp = Py_None;
522 Py_INCREF(temp);
523 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000524}
525
526PyDoc_STRVAR(getprofile_doc,
527"getprofile()\n\
528\n\
529Return the profiling function set with sys.setprofile.\n\
530See the profiler chapter in the library manual."
531);
532
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000533static int _check_interval = 100;
534
Christian Heimes9bd667a2008-01-20 15:14:11 +0000535static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (PyErr_WarnEx(PyExc_DeprecationWarning,
539 "sys.getcheckinterval() and sys.setcheckinterval() "
540 "are deprecated. Use sys.setswitchinterval() "
541 "instead.", 1) < 0)
542 return NULL;
543 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
544 return NULL;
545 Py_INCREF(Py_None);
546 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000547}
548
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000549PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000550"setcheckinterval(n)\n\
551\n\
552Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000553n instructions. This also affects how often thread switches occur."
554);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000555
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000556static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000557sys_getcheckinterval(PyObject *self, PyObject *args)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (PyErr_WarnEx(PyExc_DeprecationWarning,
560 "sys.getcheckinterval() and sys.setcheckinterval() "
561 "are deprecated. Use sys.getswitchinterval() "
562 "instead.", 1) < 0)
563 return NULL;
564 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000565}
566
567PyDoc_STRVAR(getcheckinterval_doc,
568"getcheckinterval() -> current check interval; see setcheckinterval()."
569);
570
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000571#ifdef WITH_THREAD
572static PyObject *
573sys_setswitchinterval(PyObject *self, PyObject *args)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double d;
576 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
577 return NULL;
578 if (d <= 0.0) {
579 PyErr_SetString(PyExc_ValueError,
580 "switch interval must be strictly positive");
581 return NULL;
582 }
583 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
584 Py_INCREF(Py_None);
585 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000586}
587
588PyDoc_STRVAR(setswitchinterval_doc,
589"setswitchinterval(n)\n\
590\n\
591Set the ideal thread switching delay inside the Python interpreter\n\
592The actual frequency of switching threads can be lower if the\n\
593interpreter executes long sequences of uninterruptible code\n\
594(this is implementation-specific and workload-dependent).\n\
595\n\
596The parameter must represent the desired switching delay in seconds\n\
597A typical value is 0.005 (5 milliseconds)."
598);
599
600static PyObject *
601sys_getswitchinterval(PyObject *self, PyObject *args)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000604}
605
606PyDoc_STRVAR(getswitchinterval_doc,
607"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
608);
609
610#endif /* WITH_THREAD */
611
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000612#ifdef WITH_TSC
613static PyObject *
614sys_settscdump(PyObject *self, PyObject *args)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 int bool;
617 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
620 return NULL;
621 if (bool)
622 tstate->interp->tscdump = 1;
623 else
624 tstate->interp->tscdump = 0;
625 Py_INCREF(Py_None);
626 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000627
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000628}
629
Tim Peters216b78b2006-01-06 02:40:53 +0000630PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000631"settscdump(bool)\n\
632\n\
633If true, tell the Python interpreter to dump VM measurements to\n\
634stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000635processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000636);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000637#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000638
Tim Peterse5e065b2003-07-06 18:36:54 +0000639static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000640sys_setrecursionlimit(PyObject *self, PyObject *args)
641{
Victor Stinner50856d52015-10-13 00:11:21 +0200642 int new_limit, mark;
643 PyThreadState *tstate;
644
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000645 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
646 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200647
648 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000649 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200650 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 return NULL;
652 }
Victor Stinner50856d52015-10-13 00:11:21 +0200653
654 /* Issue #25274: When the recursion depth hits the recursion limit in
655 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
656 set to 1 and a RecursionError is raised. The overflowed flag is reset
657 to 0 when the recursion depth goes below the low-water mark: see
658 Py_LeaveRecursiveCall().
659
660 Reject too low new limit if the current recursion depth is higher than
661 the new low-water mark. Otherwise it may not be possible anymore to
662 reset the overflowed flag to 0. */
663 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
664 tstate = PyThreadState_GET();
665 if (tstate->recursion_depth >= mark) {
666 PyErr_Format(PyExc_RecursionError,
667 "cannot set the recursion limit to %i at "
668 "the recursion depth %i: the limit is too low",
669 new_limit, tstate->recursion_depth);
670 return NULL;
671 }
672
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000673 Py_SetRecursionLimit(new_limit);
674 Py_INCREF(Py_None);
675 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000676}
677
Yury Selivanov75445082015-05-11 22:57:16 -0400678static PyObject *
679sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
680{
681 if (wrapper != Py_None) {
682 if (!PyCallable_Check(wrapper)) {
683 PyErr_Format(PyExc_TypeError,
684 "callable expected, got %.50s",
685 Py_TYPE(wrapper)->tp_name);
686 return NULL;
687 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400688 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400689 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400690 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400691 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400692 }
Yury Selivanov75445082015-05-11 22:57:16 -0400693 Py_RETURN_NONE;
694}
695
696PyDoc_STRVAR(set_coroutine_wrapper_doc,
697"set_coroutine_wrapper(wrapper)\n\
698\n\
699Set a wrapper for coroutine objects."
700);
701
702static PyObject *
703sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
704{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400705 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400706 if (wrapper == NULL) {
707 wrapper = Py_None;
708 }
709 Py_INCREF(wrapper);
710 return wrapper;
711}
712
713PyDoc_STRVAR(get_coroutine_wrapper_doc,
714"get_coroutine_wrapper()\n\
715\n\
716Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
717);
718
719
Mark Dickinsondc787d22010-05-23 13:33:13 +0000720static PyTypeObject Hash_InfoType;
721
722PyDoc_STRVAR(hash_info_doc,
723"hash_info\n\
724\n\
725A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100726hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000727
728static PyStructSequence_Field hash_info_fields[] = {
729 {"width", "width of the type used for hashing, in bits"},
730 {"modulus", "prime number giving the modulus on which the hash "
731 "function is based"},
732 {"inf", "value to be used for hash of a positive infinity"},
733 {"nan", "value to be used for hash of a nan"},
734 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100735 {"algorithm", "name of the algorithm for hashing of str, bytes and "
736 "memoryviews"},
737 {"hash_bits", "internal output size of hash algorithm"},
738 {"seed_bits", "seed size of hash algorithm"},
739 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000740 {NULL, NULL}
741};
742
743static PyStructSequence_Desc hash_info_desc = {
744 "sys.hash_info",
745 hash_info_doc,
746 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100747 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000748};
749
Matthias Klosed885e952010-07-06 10:53:30 +0000750static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000751get_hash_info(void)
752{
753 PyObject *hash_info;
754 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100755 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000756 hash_info = PyStructSequence_New(&Hash_InfoType);
757 if (hash_info == NULL)
758 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100759 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000760 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000761 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000762 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000763 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000764 PyStructSequence_SET_ITEM(hash_info, field++,
765 PyLong_FromLong(_PyHASH_INF));
766 PyStructSequence_SET_ITEM(hash_info, field++,
767 PyLong_FromLong(_PyHASH_NAN));
768 PyStructSequence_SET_ITEM(hash_info, field++,
769 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100770 PyStructSequence_SET_ITEM(hash_info, field++,
771 PyUnicode_FromString(hashfunc->name));
772 PyStructSequence_SET_ITEM(hash_info, field++,
773 PyLong_FromLong(hashfunc->hash_bits));
774 PyStructSequence_SET_ITEM(hash_info, field++,
775 PyLong_FromLong(hashfunc->seed_bits));
776 PyStructSequence_SET_ITEM(hash_info, field++,
777 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000778 if (PyErr_Occurred()) {
779 Py_CLEAR(hash_info);
780 return NULL;
781 }
782 return hash_info;
783}
784
785
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000786PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000787"setrecursionlimit(n)\n\
788\n\
789Set the maximum depth of the Python interpreter stack to n. This\n\
790limit prevents infinite recursion from causing an overflow of the C\n\
791stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000792dependent."
793);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000794
795static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000796sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000799}
800
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000801PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000802"getrecursionlimit()\n\
803\n\
804Return the current value of the recursion limit, the maximum depth\n\
805of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000806recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000807);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000808
Mark Hammond8696ebc2002-10-08 02:44:31 +0000809#ifdef MS_WINDOWS
810PyDoc_STRVAR(getwindowsversion_doc,
811"getwindowsversion()\n\
812\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000813Return information about the running version of Windows as a named tuple.\n\
814The members are named: major, minor, build, platform, service_pack,\n\
815service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200816backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000817All elements are numbers, except service_pack which is a string. Platform\n\
818may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
8193 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
820controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000821);
822
Eric Smithf7bb5782010-01-27 00:44:57 +0000823static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
824
825static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 {"major", "Major version number"},
827 {"minor", "Minor version number"},
828 {"build", "Build number"},
829 {"platform", "Operating system platform"},
830 {"service_pack", "Latest Service Pack installed on the system"},
831 {"service_pack_major", "Service Pack major version number"},
832 {"service_pack_minor", "Service Pack minor version number"},
833 {"suite_mask", "Bit mask identifying available product suites"},
834 {"product_type", "System product type"},
835 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000836};
837
838static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 "sys.getwindowsversion", /* name */
840 getwindowsversion_doc, /* doc */
841 windows_version_fields, /* fields */
842 5 /* For backward compatibility,
843 only the first 5 items are accessible
844 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000845};
846
Steve Dower3e96f322015-03-02 08:01:10 -0800847/* Disable deprecation warnings about GetVersionEx as the result is
848 being passed straight through to the caller, who is responsible for
849 using it correctly. */
850#pragma warning(push)
851#pragma warning(disable:4996)
852
Mark Hammond8696ebc2002-10-08 02:44:31 +0000853static PyObject *
854sys_getwindowsversion(PyObject *self)
855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000856 PyObject *version;
857 int pos = 0;
858 OSVERSIONINFOEX ver;
859 ver.dwOSVersionInfoSize = sizeof(ver);
860 if (!GetVersionEx((OSVERSIONINFO*) &ver))
861 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000862
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 version = PyStructSequence_New(&WindowsVersionType);
864 if (version == NULL)
865 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000867 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
868 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
869 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
870 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
871 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
872 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
873 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
874 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
875 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000876
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200877 if (PyErr_Occurred()) {
878 Py_DECREF(version);
879 return NULL;
880 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000882}
883
Steve Dower3e96f322015-03-02 08:01:10 -0800884#pragma warning(pop)
885
Steve Dowercc16be82016-09-08 10:35:16 -0700886PyDoc_STRVAR(enablelegacywindowsfsencoding_doc,
887"_enablelegacywindowsfsencoding()\n\
888\n\
889Changes the default filesystem encoding to mbcs:replace for consistency\n\
890with earlier versions of Python. See PEP 529 for more information.\n\
891\n\
892This is equivalent to defining the PYTHONLEGACYWINDOWSFSENCODING \n\
893environment variable before launching Python."
894);
895
896static PyObject *
897sys_enablelegacywindowsfsencoding(PyObject *self)
898{
899 Py_FileSystemDefaultEncoding = "mbcs";
900 Py_FileSystemDefaultEncodeErrors = "replace";
901 Py_RETURN_NONE;
902}
903
Mark Hammond8696ebc2002-10-08 02:44:31 +0000904#endif /* MS_WINDOWS */
905
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000906#ifdef HAVE_DLOPEN
907static PyObject *
908sys_setdlopenflags(PyObject *self, PyObject *args)
909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 int new_val;
911 PyThreadState *tstate = PyThreadState_GET();
912 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
913 return NULL;
914 if (!tstate)
915 return NULL;
916 tstate->interp->dlopenflags = new_val;
917 Py_INCREF(Py_None);
918 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000919}
920
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000921PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000922"setdlopenflags(n) -> None\n\
923\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000924Set the flags used by the interpreter for dlopen calls, such as when the\n\
925interpreter loads extension modules. Among other things, this will enable\n\
926a lazy resolving of symbols when importing a module, if called as\n\
927sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400928sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100929can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000930
931static PyObject *
932sys_getdlopenflags(PyObject *self, PyObject *args)
933{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000934 PyThreadState *tstate = PyThreadState_GET();
935 if (!tstate)
936 return NULL;
937 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000938}
939
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000940PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000941"getdlopenflags() -> int\n\
942\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000943Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400944The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000946#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000947
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000948#ifdef USE_MALLOPT
949/* Link with -lmalloc (or -lmpc) on an SGI */
950#include <malloc.h>
951
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000952static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000953sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000954{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000955 int flag;
956 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
957 return NULL;
958 mallopt(M_DEBUG, flag);
959 Py_INCREF(Py_None);
960 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000961}
962#endif /* USE_MALLOPT */
963
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300964size_t
965_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000968 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200969 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 /* Make sure the type is initialized. float gets initialized late */
972 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300973 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000974
Benjamin Petersonce798522012-01-22 11:24:29 -0500975 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 if (method == NULL) {
977 if (!PyErr_Occurred())
978 PyErr_Format(PyExc_TypeError,
979 "Type %.100s doesn't define __sizeof__",
980 Py_TYPE(o)->tp_name);
981 }
982 else {
983 res = PyObject_CallFunctionObjArgs(method, NULL);
984 Py_DECREF(method);
985 }
986
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300987 if (res == NULL)
988 return (size_t)-1;
989
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200990 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300991 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200992 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300993 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200995 if (size < 0) {
996 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
997 return (size_t)-1;
998 }
999
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001000 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001001 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +02001002 return ((size_t)size) + sizeof(PyGC_Head);
1003 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001004}
1005
1006static PyObject *
1007sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
1008{
1009 static char *kwlist[] = {"object", "default", 0};
1010 size_t size;
1011 PyObject *o, *dflt = NULL;
1012
1013 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
1014 kwlist, &o, &dflt))
1015 return NULL;
1016
1017 size = _PySys_GetSizeOf(o);
1018
1019 if (size == (size_t)-1 && PyErr_Occurred()) {
1020 /* Has a default value been given */
1021 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
1022 PyErr_Clear();
1023 Py_INCREF(dflt);
1024 return dflt;
1025 }
1026 else
1027 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +03001029
1030 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001031}
1032
1033PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +00001034"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001035\n\
1036Return the size of object in bytes.");
1037
1038static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001039sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001040{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001042}
1043
Tim Peters4be93d02002-07-07 19:59:50 +00001044#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001045static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001046sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001049}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001050#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001051
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001052PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001053"getrefcount(object) -> integer\n\
1054\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001055Return the reference count of object. The count returned is generally\n\
1056one higher than you might expect, because it includes the (temporary)\n\
1057reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001058);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001059
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001060static PyObject *
1061sys_getallocatedblocks(PyObject *self)
1062{
1063 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1064}
1065
1066PyDoc_STRVAR(getallocatedblocks_doc,
1067"getallocatedblocks() -> integer\n\
1068\n\
1069Return the number of memory blocks currently allocated, regardless of their\n\
1070size."
1071);
1072
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001073#ifdef COUNT_ALLOCS
1074static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001075sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001076{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001077 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001080}
1081#endif
1082
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001083PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001084"_getframe([depth]) -> frameobject\n\
1085\n\
1086Return a frame object from the call stack. If optional integer depth is\n\
1087given, return the frame object that many calls below the top of the stack.\n\
1088If that is deeper than the call stack, ValueError is raised. The default\n\
1089for depth is zero, returning the frame at the top of the call stack.\n\
1090\n\
1091This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001092purposes only."
1093);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001094
1095static PyObject *
1096sys_getframe(PyObject *self, PyObject *args)
1097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyFrameObject *f = PyThreadState_GET()->frame;
1099 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001100
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001101 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1102 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001103
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 while (depth > 0 && f != NULL) {
1105 f = f->f_back;
1106 --depth;
1107 }
1108 if (f == NULL) {
1109 PyErr_SetString(PyExc_ValueError,
1110 "call stack is not deep enough");
1111 return NULL;
1112 }
1113 Py_INCREF(f);
1114 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001115}
1116
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001117PyDoc_STRVAR(current_frames_doc,
1118"_current_frames() -> dictionary\n\
1119\n\
1120Return a dictionary mapping each current thread T's thread id to T's\n\
1121current stack frame.\n\
1122\n\
1123This function should be used for specialized purposes only."
1124);
1125
1126static PyObject *
1127sys_current_frames(PyObject *self, PyObject *noargs)
1128{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001129 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001130}
1131
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001132PyDoc_STRVAR(call_tracing_doc,
1133"call_tracing(func, args) -> object\n\
1134\n\
1135Call func(*args), while tracing is enabled. The tracing state is\n\
1136saved, and restored afterwards. This is intended to be called from\n\
1137a debugger from a checkpoint, to recursively debug some other code."
1138);
1139
1140static PyObject *
1141sys_call_tracing(PyObject *self, PyObject *args)
1142{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001143 PyObject *func, *funcargs;
1144 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1145 return NULL;
1146 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001147}
1148
Jeremy Hylton985eba52003-02-05 23:13:00 +00001149PyDoc_STRVAR(callstats_doc,
1150"callstats() -> tuple of integers\n\
1151\n\
1152Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1153when Python was built. Otherwise, return None.\n\
1154\n\
1155When enabled, this function returns detailed, implementation-specific\n\
1156details about the number of function calls executed. The return value is\n\
1157a 11-tuple where the entries in the tuple are counts of:\n\
11580. all function calls\n\
11591. calls to PyFunction_Type objects\n\
11602. PyFunction calls that do not create an argument tuple\n\
11613. PyFunction calls that do not create an argument tuple\n\
1162 and bypass PyEval_EvalCodeEx()\n\
11634. PyMethod calls\n\
11645. PyMethod calls on bound methods\n\
11656. PyType calls\n\
11667. PyCFunction calls\n\
11678. generator calls\n\
11689. All other calls\n\
116910. Number of stack pops performed by call_function()"
1170);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001171
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001172#ifdef __cplusplus
1173extern "C" {
1174#endif
1175
David Malcolm49526f42012-06-22 14:55:41 -04001176static PyObject *
1177sys_debugmallocstats(PyObject *self, PyObject *args)
1178{
1179#ifdef WITH_PYMALLOC
Victor Stinner34be807c2016-03-14 12:04:26 +01001180 if (_PyMem_PymallocEnabled()) {
1181 _PyObject_DebugMallocStats(stderr);
1182 fputc('\n', stderr);
1183 }
David Malcolm49526f42012-06-22 14:55:41 -04001184#endif
1185 _PyObject_DebugTypeStats(stderr);
1186
1187 Py_RETURN_NONE;
1188}
1189PyDoc_STRVAR(debugmallocstats_doc,
1190"_debugmallocstats()\n\
1191\n\
1192Print summary info to stderr about the state of\n\
1193pymalloc's structures.\n\
1194\n\
1195In Py_DEBUG mode, also perform some expensive internal consistency\n\
1196checks.\n\
1197");
1198
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001199#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001200/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001201extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001202#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001203
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001204#ifdef DYNAMIC_EXECUTION_PROFILE
1205/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001206extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001207#endif
1208
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001209#ifdef __cplusplus
1210}
1211#endif
1212
Christian Heimes15ebc882008-02-04 18:48:49 +00001213static PyObject *
1214sys_clear_type_cache(PyObject* self, PyObject* args)
1215{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001216 PyType_ClearCache();
1217 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001218}
1219
1220PyDoc_STRVAR(sys_clear_type_cache__doc__,
1221"_clear_type_cache() -> None\n\
1222Clear the internal type lookup cache.");
1223
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001224static PyObject *
1225sys_is_finalizing(PyObject* self, PyObject* args)
1226{
1227 return PyBool_FromLong(_Py_Finalizing != NULL);
1228}
1229
1230PyDoc_STRVAR(is_finalizing_doc,
1231"is_finalizing()\n\
1232Return True if Python is exiting.");
1233
Christian Heimes15ebc882008-02-04 18:48:49 +00001234
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001235static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001236 /* Might as well keep this in alphabetic order */
1237 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1238 callstats_doc},
1239 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1240 sys_clear_type_cache__doc__},
1241 {"_current_frames", sys_current_frames, METH_NOARGS,
1242 current_frames_doc},
1243 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1244 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1245 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1246 {"exit", sys_exit, METH_VARARGS, exit_doc},
1247 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1248 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001249#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1251 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001252#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001253 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1254 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001255#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001256 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001257#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001258#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001259 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001260#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001261 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1262 METH_NOARGS, getfilesystemencoding_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001263 { "getfilesystemencodeerrors", (PyCFunction)sys_getfilesystemencodeerrors,
1264 METH_NOARGS, getfilesystemencodeerrors_doc },
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001265#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001267#endif
1268#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001270#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001271 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1272 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1273 getrecursionlimit_doc},
1274 {"getsizeof", (PyCFunction)sys_getsizeof,
1275 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1276 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001277#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001278 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1279 getwindowsversion_doc},
Steve Dowercc16be82016-09-08 10:35:16 -07001280 {"_enablelegacywindowsfsencoding", (PyCFunction)sys_enablelegacywindowsfsencoding,
1281 METH_NOARGS, enablelegacywindowsfsencoding_doc },
Mark Hammond8696ebc2002-10-08 02:44:31 +00001282#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001283 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001284 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001285#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001287#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001288 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1289 setcheckinterval_doc},
1290 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1291 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001292#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001293 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1294 setswitchinterval_doc},
1295 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1296 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001297#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001298#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1300 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001301#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001302 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1303 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1304 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1305 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001306#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001307 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001308#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001309 {"settrace", sys_settrace, METH_O, settrace_doc},
1310 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1311 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001312 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001313 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001314 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1315 set_coroutine_wrapper_doc},
1316 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1317 get_coroutine_wrapper_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001319};
1320
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001321static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001322list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001323{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 PyObject *list = PyList_New(0);
1325 int i;
1326 if (list == NULL)
1327 return NULL;
1328 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1329 PyObject *name = PyUnicode_FromString(
1330 PyImport_Inittab[i].name);
1331 if (name == NULL)
1332 break;
1333 PyList_Append(list, name);
1334 Py_DECREF(name);
1335 }
1336 if (PyList_Sort(list) != 0) {
1337 Py_DECREF(list);
1338 list = NULL;
1339 }
1340 if (list) {
1341 PyObject *v = PyList_AsTuple(list);
1342 Py_DECREF(list);
1343 list = v;
1344 }
1345 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001346}
1347
Guido van Rossum23fff912000-12-15 22:02:05 +00001348static PyObject *warnoptions = NULL;
1349
1350void
1351PySys_ResetWarnOptions(void)
1352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 if (warnoptions == NULL || !PyList_Check(warnoptions))
1354 return;
1355 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001356}
1357
1358void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001359PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001361 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1362 Py_XDECREF(warnoptions);
1363 warnoptions = PyList_New(0);
1364 if (warnoptions == NULL)
1365 return;
1366 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001367 PyList_Append(warnoptions, unicode);
1368}
1369
1370void
1371PySys_AddWarnOption(const wchar_t *s)
1372{
1373 PyObject *unicode;
1374 unicode = PyUnicode_FromWideChar(s, -1);
1375 if (unicode == NULL)
1376 return;
1377 PySys_AddWarnOptionUnicode(unicode);
1378 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001379}
1380
Christian Heimes33fe8092008-04-13 13:53:33 +00001381int
1382PySys_HasWarnOptions(void)
1383{
1384 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1385}
1386
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001387static PyObject *xoptions = NULL;
1388
1389static PyObject *
1390get_xoptions(void)
1391{
1392 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1393 Py_XDECREF(xoptions);
1394 xoptions = PyDict_New();
1395 }
1396 return xoptions;
1397}
1398
1399void
1400PySys_AddXOption(const wchar_t *s)
1401{
1402 PyObject *opts;
1403 PyObject *name = NULL, *value = NULL;
1404 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001405
1406 opts = get_xoptions();
1407 if (opts == NULL)
1408 goto error;
1409
1410 name_end = wcschr(s, L'=');
1411 if (!name_end) {
1412 name = PyUnicode_FromWideChar(s, -1);
1413 value = Py_True;
1414 Py_INCREF(value);
1415 }
1416 else {
1417 name = PyUnicode_FromWideChar(s, name_end - s);
1418 value = PyUnicode_FromWideChar(name_end + 1, -1);
1419 }
1420 if (name == NULL || value == NULL)
1421 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001422 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001423 Py_DECREF(name);
1424 Py_DECREF(value);
1425 return;
1426
1427error:
1428 Py_XDECREF(name);
1429 Py_XDECREF(value);
1430 /* No return value, therefore clear error state if possible */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001431 if (_PyThreadState_UncheckedGet())
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001432 PyErr_Clear();
1433}
1434
1435PyObject *
1436PySys_GetXOptions(void)
1437{
1438 return get_xoptions();
1439}
1440
Guido van Rossum40552d01998-08-06 03:34:39 +00001441/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1442 Two literals concatenated works just fine. If you have a K&R compiler
1443 or other abomination that however *does* understand longer strings,
1444 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001445PyDoc_VAR(sys_doc) =
1446PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001447"This module provides access to some objects used or maintained by the\n\
1448interpreter and to functions that interact strongly with the interpreter.\n\
1449\n\
1450Dynamic objects:\n\
1451\n\
1452argv -- command line arguments; argv[0] is the script pathname if known\n\
1453path -- module search path; path[0] is the script directory, else ''\n\
1454modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001455\n\
1456displayhook -- called to show results in an interactive session\n\
1457excepthook -- called to handle any uncaught exception other than SystemExit\n\
1458 To customize printing in an interactive session or to install a custom\n\
1459 top-level exception handler, assign other functions to replace these.\n\
1460\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001461stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001462stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001463stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001464 By assigning other file objects (or objects that behave like files)\n\
1465 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001466\n\
1467last_type -- type of last uncaught exception\n\
1468last_value -- value of last uncaught exception\n\
1469last_traceback -- traceback of last uncaught exception\n\
1470 These three are only available in an interactive session after a\n\
1471 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001472"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001473)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001474/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001475PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001476"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001477Static objects:\n\
1478\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001479builtin_module_names -- tuple of module names built into this interpreter\n\
1480copyright -- copyright notice pertaining to this interpreter\n\
1481exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001482executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001483float_info -- a struct sequence with information about the float implementation.\n\
1484float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001485hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001486hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001487implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001488int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001489maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001490maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001491platform -- platform identifier\n\
1492prefix -- prefix used to find the Python library\n\
1493thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001494version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001495version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001496"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001497)
Steve Dowercc16be82016-09-08 10:35:16 -07001498#ifdef MS_COREDLL
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001499/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001500PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001501"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001502winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001503"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001504)
Steve Dowercc16be82016-09-08 10:35:16 -07001505#endif /* MS_COREDLL */
1506#ifdef MS_WINDOWS
1507/* concatenating string here */
1508PyDoc_STR(
1509"_enablelegacywindowsfsencoding -- [Windows only] \n\
1510"
1511)
1512#endif
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001513PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001514"__stdin__ -- the original stdin; don't touch!\n\
1515__stdout__ -- the original stdout; don't touch!\n\
1516__stderr__ -- the original stderr; don't touch!\n\
1517__displayhook__ -- the original displayhook; don't touch!\n\
1518__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001519\n\
1520Functions:\n\
1521\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001522displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001523excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001524exc_info() -- return thread-safe information about the current exception\n\
1525exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001526getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001527getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001528getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001529getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001530getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001531gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001532setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001533setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001534setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001535setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001536settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001537"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001538)
Fred Drakeccede592000-08-14 20:59:57 +00001539/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001540
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001541
1542PyDoc_STRVAR(flags__doc__,
1543"sys.flags\n\
1544\n\
1545Flags provided through command line arguments or environment vars.");
1546
1547static PyTypeObject FlagsType;
1548
1549static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 {"inspect", "-i"},
1552 {"interactive", "-i"},
1553 {"optimize", "-O or -OO"},
1554 {"dont_write_bytecode", "-B"},
1555 {"no_user_site", "-s"},
1556 {"no_site", "-S"},
1557 {"ignore_environment", "-E"},
1558 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 /* {"unbuffered", "-u"}, */
1560 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001561 {"bytes_warning", "-b"},
1562 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001563 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001564 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001566};
1567
1568static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001569 "sys.flags", /* name */
1570 flags__doc__, /* doc */
1571 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001572 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001573};
1574
1575static PyObject*
1576make_flags(void)
1577{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 int pos = 0;
1579 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 seq = PyStructSequence_New(&FlagsType);
1582 if (seq == NULL)
1583 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001584
1585#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 SetFlag(Py_InspectFlag);
1590 SetFlag(Py_InteractiveFlag);
1591 SetFlag(Py_OptimizeFlag);
1592 SetFlag(Py_DontWriteBytecodeFlag);
1593 SetFlag(Py_NoUserSiteDirectory);
1594 SetFlag(Py_NoSiteFlag);
1595 SetFlag(Py_IgnoreEnvironmentFlag);
1596 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 /* SetFlag(saw_unbuffered_flag); */
1598 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001599 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001600 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001601 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001602 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001603#undef SetFlag
1604
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001606 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 return NULL;
1608 }
1609 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001610}
1611
Eric Smith0e5b5622009-02-06 01:32:42 +00001612PyDoc_STRVAR(version_info__doc__,
1613"sys.version_info\n\
1614\n\
1615Version information as a named tuple.");
1616
1617static PyTypeObject VersionInfoType;
1618
1619static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 {"major", "Major release number"},
1621 {"minor", "Minor release number"},
1622 {"micro", "Patch release number"},
1623 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1624 {"serial", "Serial release number"},
1625 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001626};
1627
1628static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001629 "sys.version_info", /* name */
1630 version_info__doc__, /* doc */
1631 version_info_fields, /* fields */
1632 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001633};
1634
1635static PyObject *
1636make_version_info(void)
1637{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001638 PyObject *version_info;
1639 char *s;
1640 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 version_info = PyStructSequence_New(&VersionInfoType);
1643 if (version_info == NULL) {
1644 return NULL;
1645 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001646
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001647 /*
1648 * These release level checks are mutually exclusive and cover
1649 * the field, so don't get too fancy with the pre-processor!
1650 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001651#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001653#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001655#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001657#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001658 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001659#endif
1660
1661#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001663#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001665
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001666 SetIntItem(PY_MAJOR_VERSION);
1667 SetIntItem(PY_MINOR_VERSION);
1668 SetIntItem(PY_MICRO_VERSION);
1669 SetStrItem(s);
1670 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001671#undef SetIntItem
1672#undef SetStrItem
1673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 if (PyErr_Occurred()) {
1675 Py_CLEAR(version_info);
1676 return NULL;
1677 }
1678 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001679}
1680
Brett Cannon3adc7b72012-07-09 14:22:12 -04001681/* sys.implementation values */
1682#define NAME "cpython"
1683const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001684#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1685#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001686#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001687const char *_PySys_ImplCacheTag = TAG;
1688#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001689#undef MAJOR
1690#undef MINOR
1691#undef TAG
1692
Barry Warsaw409da152012-06-03 16:18:47 -04001693static PyObject *
1694make_impl_info(PyObject *version_info)
1695{
1696 int res;
1697 PyObject *impl_info, *value, *ns;
1698
1699 impl_info = PyDict_New();
1700 if (impl_info == NULL)
1701 return NULL;
1702
1703 /* populate the dict */
1704
Brett Cannon3adc7b72012-07-09 14:22:12 -04001705 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001706 if (value == NULL)
1707 goto error;
1708 res = PyDict_SetItemString(impl_info, "name", value);
1709 Py_DECREF(value);
1710 if (res < 0)
1711 goto error;
1712
Brett Cannon3adc7b72012-07-09 14:22:12 -04001713 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001714 if (value == NULL)
1715 goto error;
1716 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1717 Py_DECREF(value);
1718 if (res < 0)
1719 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001720
1721 res = PyDict_SetItemString(impl_info, "version", version_info);
1722 if (res < 0)
1723 goto error;
1724
1725 value = PyLong_FromLong(PY_VERSION_HEX);
1726 if (value == NULL)
1727 goto error;
1728 res = PyDict_SetItemString(impl_info, "hexversion", value);
1729 Py_DECREF(value);
1730 if (res < 0)
1731 goto error;
1732
doko@ubuntu.com55532312016-06-14 08:55:19 +02001733#ifdef MULTIARCH
1734 value = PyUnicode_FromString(MULTIARCH);
1735 if (value == NULL)
1736 goto error;
1737 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1738 Py_DECREF(value);
1739 if (res < 0)
1740 goto error;
1741#endif
1742
Barry Warsaw409da152012-06-03 16:18:47 -04001743 /* dict ready */
1744
1745 ns = _PyNamespace_New(impl_info);
1746 Py_DECREF(impl_info);
1747 return ns;
1748
1749error:
1750 Py_CLEAR(impl_info);
1751 return NULL;
1752}
1753
Martin v. Löwis1a214512008-06-11 05:26:20 +00001754static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 PyModuleDef_HEAD_INIT,
1756 "sys",
1757 sys_doc,
1758 -1, /* multiple "initialization" just copies the module dict. */
1759 sys_methods,
1760 NULL,
1761 NULL,
1762 NULL,
1763 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001764};
1765
Guido van Rossum25ce5661997-08-02 03:10:38 +00001766PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001767_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001768{
Victor Stinner58049602013-07-22 22:40:00 +02001769 PyObject *m, *sysdict, *version_info;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001770 int res;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001771
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 m = PyModule_Create(&sysmodule);
1773 if (m == NULL)
1774 return NULL;
1775 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001776#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001777 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001778 PyObject *v = (value); \
1779 if (v == NULL) \
1780 return NULL; \
1781 res = PyDict_SetItemString(sysdict, key, v); \
1782 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001783 return NULL; \
1784 } \
1785 } while (0)
1786#define SET_SYS_FROM_STRING(key, value) \
1787 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001788 PyObject *v = (value); \
1789 if (v == NULL) \
1790 return NULL; \
1791 res = PyDict_SetItemString(sysdict, key, v); \
1792 Py_DECREF(v); \
1793 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001794 return NULL; \
1795 } \
1796 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001798 /* Check that stdin is not a directory
1799 Using shell redirection, you can redirect stdin to a directory,
1800 crashing the Python interpreter. Catch this common mistake here
1801 and output a useful error message. Note that under MS Windows,
1802 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001803#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001805 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001806 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 S_ISDIR(sb.st_mode)) {
1808 /* There's nothing more we can do. */
1809 /* Py_FatalError() will core dump, so just exit. */
1810 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1811 exit(EXIT_FAILURE);
1812 }
1813 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001814#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001815
Nick Coghland6009512014-11-20 21:39:37 +10001816 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001817
Victor Stinner8fea2522013-10-27 17:15:42 +01001818 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1819 PyDict_GetItemString(sysdict, "displayhook"));
1820 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1821 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 SET_SYS_FROM_STRING("version",
1823 PyUnicode_FromString(Py_GetVersion()));
1824 SET_SYS_FROM_STRING("hexversion",
1825 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001826 SET_SYS_FROM_STRING("_mercurial",
1827 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1828 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 SET_SYS_FROM_STRING("dont_write_bytecode",
1830 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1831 SET_SYS_FROM_STRING("api_version",
1832 PyLong_FromLong(PYTHON_API_VERSION));
1833 SET_SYS_FROM_STRING("copyright",
1834 PyUnicode_FromString(Py_GetCopyright()));
1835 SET_SYS_FROM_STRING("platform",
1836 PyUnicode_FromString(Py_GetPlatform()));
1837 SET_SYS_FROM_STRING("executable",
1838 PyUnicode_FromWideChar(
1839 Py_GetProgramFullPath(), -1));
1840 SET_SYS_FROM_STRING("prefix",
1841 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1842 SET_SYS_FROM_STRING("exec_prefix",
1843 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001844 SET_SYS_FROM_STRING("base_prefix",
1845 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1846 SET_SYS_FROM_STRING("base_exec_prefix",
1847 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 SET_SYS_FROM_STRING("maxsize",
1849 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1850 SET_SYS_FROM_STRING("float_info",
1851 PyFloat_GetInfo());
1852 SET_SYS_FROM_STRING("int_info",
1853 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001854 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001855 if (Hash_InfoType.tp_name == NULL) {
1856 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1857 return NULL;
1858 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001859 SET_SYS_FROM_STRING("hash_info",
1860 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001862 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 SET_SYS_FROM_STRING("builtin_module_names",
1864 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001865#if PY_BIG_ENDIAN
1866 SET_SYS_FROM_STRING("byteorder",
1867 PyUnicode_FromString("big"));
1868#else
1869 SET_SYS_FROM_STRING("byteorder",
1870 PyUnicode_FromString("little"));
1871#endif
Fred Drake099325e2000-08-14 15:47:03 +00001872
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001873#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001874 SET_SYS_FROM_STRING("dllhandle",
1875 PyLong_FromVoidPtr(PyWin_DLLhModule));
1876 SET_SYS_FROM_STRING("winver",
1877 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001878#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001879#ifdef ABIFLAGS
1880 SET_SYS_FROM_STRING("abiflags",
1881 PyUnicode_FromString(ABIFLAGS));
1882#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (warnoptions == NULL) {
1884 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02001885 if (warnoptions == NULL)
1886 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 }
1888 else {
1889 Py_INCREF(warnoptions);
1890 }
Victor Stinner8fea2522013-10-27 17:15:42 +01001891 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00001892
Victor Stinner8fea2522013-10-27 17:15:42 +01001893 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001894
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001896 if (VersionInfoType.tp_name == NULL) {
1897 if (PyStructSequence_InitType2(&VersionInfoType,
1898 &version_info_desc) < 0)
1899 return NULL;
1900 }
Barry Warsaw409da152012-06-03 16:18:47 -04001901 version_info = make_version_info();
1902 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 /* prevent user from creating new instances */
1904 VersionInfoType.tp_init = NULL;
1905 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001906 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
1907 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1908 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00001909
Barry Warsaw409da152012-06-03 16:18:47 -04001910 /* implementation */
1911 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001914 if (FlagsType.tp_name == 0) {
1915 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
1916 return NULL;
1917 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 SET_SYS_FROM_STRING("flags", make_flags());
1919 /* prevent user from creating new instances */
1920 FlagsType.tp_init = NULL;
1921 FlagsType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001922 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
1923 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1924 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00001925
1926#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 /* getwindowsversion */
1928 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02001929 if (PyStructSequence_InitType2(&WindowsVersionType,
1930 &windows_version_desc) < 0)
1931 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001932 /* prevent user from creating new instances */
1933 WindowsVersionType.tp_init = NULL;
1934 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001935 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
1936 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1937 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00001938#endif
1939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001941#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 SET_SYS_FROM_STRING("float_repr_style",
1943 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001944#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001945 SET_SYS_FROM_STRING("float_repr_style",
1946 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001947#endif
1948
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001949#ifdef WITH_THREAD
1950 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1951#endif
1952
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001953#undef SET_SYS_FROM_STRING
Benjamin Peterson93813432014-03-28 18:52:45 -04001954#undef SET_SYS_FROM_STRING_BORROW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (PyErr_Occurred())
1956 return NULL;
1957 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001958}
1959
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001960static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001961makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 int i, n;
1964 const wchar_t *p;
1965 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001966
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001967 n = 1;
1968 p = path;
1969 while ((p = wcschr(p, delim)) != NULL) {
1970 n++;
1971 p++;
1972 }
1973 v = PyList_New(n);
1974 if (v == NULL)
1975 return NULL;
1976 for (i = 0; ; i++) {
1977 p = wcschr(path, delim);
1978 if (p == NULL)
1979 p = path + wcslen(path); /* End of string */
1980 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1981 if (w == NULL) {
1982 Py_DECREF(v);
1983 return NULL;
1984 }
1985 PyList_SetItem(v, i, w);
1986 if (*p == '\0')
1987 break;
1988 path = p+1;
1989 }
1990 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001991}
1992
1993void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001994PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001995{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001996 PyObject *v;
1997 if ((v = makepathobject(path, DELIM)) == NULL)
1998 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01001999 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002000 Py_FatalError("can't assign sys.path");
2001 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00002002}
2003
Guido van Rossum65bf9f21997-04-29 18:33:38 +00002004static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00002005makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002006{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 PyObject *av;
2008 if (argc <= 0 || argv == NULL) {
2009 /* Ensure at least one (empty) argument is seen */
2010 static wchar_t *empty_argv[1] = {L""};
2011 argv = empty_argv;
2012 argc = 1;
2013 }
2014 av = PyList_New(argc);
2015 if (av != NULL) {
2016 int i;
2017 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 if (v == NULL) {
2020 Py_DECREF(av);
2021 av = NULL;
2022 break;
2023 }
2024 PyList_SetItem(av, i, v);
2025 }
2026 }
2027 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00002028}
2029
Nick Coghland26c18a2010-08-17 13:06:11 +00002030#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
2031 (argc > 0 && argv0 != NULL && \
2032 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002033
2034static void
2035sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00002036{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002037 wchar_t *argv0;
2038 wchar_t *p = NULL;
2039 Py_ssize_t n = 0;
2040 PyObject *a;
2041 PyObject *path;
2042#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002043 wchar_t link[MAXPATHLEN+1];
2044 wchar_t argv0copy[2*MAXPATHLEN+1];
2045 int nr = 0;
2046#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002047#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 wchar_t fullpath[MAXPATHLEN];
Larry Hastings10108a72016-09-05 15:11:23 -07002049#elif defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002051#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002052
Victor Stinnerbd303c12013-11-07 23:07:29 +01002053 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002054 if (path == NULL)
2055 return;
2056
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002057 argv0 = argv[0];
2058
2059#ifdef HAVE_READLINK
2060 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2061 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2062 if (nr > 0) {
2063 /* It's a symlink */
2064 link[nr] = '\0';
2065 if (link[0] == SEP)
2066 argv0 = link; /* Link to absolute path */
2067 else if (wcschr(link, SEP) == NULL)
2068 ; /* Link without path */
2069 else {
2070 /* Must join(dirname(argv0), link) */
2071 wchar_t *q = wcsrchr(argv0, SEP);
2072 if (q == NULL)
2073 argv0 = link; /* argv0 without path */
2074 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002075 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2076 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002077 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002078 wcsncpy(q+1, link, MAXPATHLEN);
2079 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002080 argv0 = argv0copy;
2081 }
2082 }
2083 }
2084#endif /* HAVE_READLINK */
2085#if SEP == '\\' /* Special case for MS filename syntax */
2086 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2087 wchar_t *q;
Larry Hastings10108a72016-09-05 15:11:23 -07002088#if defined(MS_WINDOWS)
2089 /* Replace the first element in argv with the full path. */
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002090 wchar_t *ptemp;
2091 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002092 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002093 fullpath,
2094 &ptemp)) {
2095 argv0 = fullpath;
2096 }
2097#endif
2098 p = wcsrchr(argv0, SEP);
2099 /* Test for alternate separator */
2100 q = wcsrchr(p ? p : argv0, '/');
2101 if (q != NULL)
2102 p = q;
2103 if (p != NULL) {
2104 n = p + 1 - argv0;
2105 if (n > 1 && p[-1] != ':')
2106 n--; /* Drop trailing separator */
2107 }
2108 }
2109#else /* All other filename syntaxes */
2110 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2111#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002112 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002113 argv0 = fullpath;
2114 }
2115#endif
2116 p = wcsrchr(argv0, SEP);
2117 }
2118 if (p != NULL) {
2119 n = p + 1 - argv0;
2120#if SEP == '/' /* Special case for Unix filename syntax */
2121 if (n > 1)
2122 n--; /* Drop trailing separator */
2123#endif /* Unix */
2124 }
2125#endif /* All others */
2126 a = PyUnicode_FromWideChar(argv0, n);
2127 if (a == NULL)
2128 Py_FatalError("no mem for sys.path insertion");
2129 if (PyList_Insert(path, 0, a) < 0)
2130 Py_FatalError("sys.path.insert(0) failed");
2131 Py_DECREF(a);
2132}
2133
2134void
2135PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 if (av == NULL)
2139 Py_FatalError("no mem for sys.argv");
2140 if (PySys_SetObject("argv", av) != 0)
2141 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002143 if (updatepath)
2144 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002145}
Guido van Rossuma890e681998-05-12 14:59:24 +00002146
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002147void
2148PySys_SetArgv(int argc, wchar_t **argv)
2149{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002150 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002151}
2152
Victor Stinner14284c22010-04-23 12:02:30 +00002153/* Reimplementation of PyFile_WriteString() no calling indirectly
2154 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2155
2156static int
Victor Stinner79766632010-08-16 17:36:42 +00002157sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002158{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002159 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002160 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002161
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002162 if (file == NULL)
2163 return -1;
2164
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002165 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002166 if (writer == NULL)
2167 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002168
Victor Stinner559bb6a2016-08-22 22:48:54 +02002169 result = _PyObject_CallArg1(writer, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002170 if (result == NULL) {
2171 goto error;
2172 } else {
2173 err = 0;
2174 goto finally;
2175 }
Victor Stinner14284c22010-04-23 12:02:30 +00002176
2177error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002179finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002181 Py_XDECREF(result);
2182 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002183}
2184
Victor Stinner79766632010-08-16 17:36:42 +00002185static int
2186sys_pyfile_write(const char *text, PyObject *file)
2187{
2188 PyObject *unicode = NULL;
2189 int err;
2190
2191 if (file == NULL)
2192 return -1;
2193
2194 unicode = PyUnicode_FromString(text);
2195 if (unicode == NULL)
2196 return -1;
2197
2198 err = sys_pyfile_write_unicode(unicode, file);
2199 Py_DECREF(unicode);
2200 return err;
2201}
Guido van Rossuma890e681998-05-12 14:59:24 +00002202
2203/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2204 Adapted from code submitted by Just van Rossum.
2205
2206 PySys_WriteStdout(format, ...)
2207 PySys_WriteStderr(format, ...)
2208
2209 The first function writes to sys.stdout; the second to sys.stderr. When
2210 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002211 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002212
Victor Stinner14284c22010-04-23 12:02:30 +00002213 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002214 signal handlers: they may raise a new exception whereas sys_write()
2215 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002216
Guido van Rossuma890e681998-05-12 14:59:24 +00002217 Both take a printf-style format string as their first argument followed
2218 by a variable length argument list determined by the format string.
2219
2220 *** WARNING ***
2221
2222 The format should limit the total size of the formatted output string to
2223 1000 bytes. In particular, this means that no unrestricted "%s" formats
2224 should occur; these should be limited using "%.<N>s where <N> is a
2225 decimal number calculated so that <N> plus the maximum size of other
2226 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2227 which can print hundreds of digits for very large numbers.
2228
2229 */
2230
2231static void
Victor Stinner09054372013-11-06 22:41:44 +01002232sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002234 PyObject *file;
2235 PyObject *error_type, *error_value, *error_traceback;
2236 char buffer[1001];
2237 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002238
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002239 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002240 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2242 if (sys_pyfile_write(buffer, file) != 0) {
2243 PyErr_Clear();
2244 fputs(buffer, fp);
2245 }
2246 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2247 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002248 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002249 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002250 }
2251 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002252}
2253
2254void
Guido van Rossuma890e681998-05-12 14:59:24 +00002255PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002256{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002257 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002259 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002260 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002261 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002262}
2263
2264void
Guido van Rossuma890e681998-05-12 14:59:24 +00002265PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002266{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002267 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002270 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002271 va_end(va);
2272}
2273
2274static void
Victor Stinner09054372013-11-06 22:41:44 +01002275sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002276{
2277 PyObject *file, *message;
2278 PyObject *error_type, *error_value, *error_traceback;
2279 char *utf8;
2280
2281 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002282 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002283 message = PyUnicode_FromFormatV(format, va);
2284 if (message != NULL) {
2285 if (sys_pyfile_write_unicode(message, file) != 0) {
2286 PyErr_Clear();
2287 utf8 = _PyUnicode_AsString(message);
2288 if (utf8 != NULL)
2289 fputs(utf8, fp);
2290 }
2291 Py_DECREF(message);
2292 }
2293 PyErr_Restore(error_type, error_value, error_traceback);
2294}
2295
2296void
2297PySys_FormatStdout(const char *format, ...)
2298{
2299 va_list va;
2300
2301 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002302 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002303 va_end(va);
2304}
2305
2306void
2307PySys_FormatStderr(const char *format, ...)
2308{
2309 va_list va;
2310
2311 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002312 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002313 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002314}