blob: c170bd5889f58ab66cda47c88e58a8e76fb51ee6 [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 *
Georg Brandl66a796e2006-12-19 20:50:34 +0000314sys_intern(PyObject *self, PyObject *args)
315{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 PyObject *s;
317 if (!PyArg_ParseTuple(args, "U:intern", &s))
318 return NULL;
319 if (PyUnicode_CheckExact(s)) {
320 Py_INCREF(s);
321 PyUnicode_InternInPlace(&s);
322 return s;
323 }
324 else {
325 PyErr_Format(PyExc_TypeError,
326 "can't intern %.400s", s->ob_type->tp_name);
327 return NULL;
328 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000329}
330
331PyDoc_STRVAR(intern_doc,
332"intern(string) -> string\n\
333\n\
334``Intern'' the given string. This enters the string in the (global)\n\
335table of interned strings whose purpose is to speed up dictionary lookups.\n\
336Return the string itself or the previously interned string object with the\n\
337same value.");
338
339
Fred Drake5755ce62001-06-27 19:19:46 +0000340/*
341 * Cached interned string objects used for calling the profile and
342 * trace functions. Initialized by trace_init().
343 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000344static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000345
346static int
347trace_init(void)
348{
Serhiy Storchaka2d06e842015-12-25 19:53:18 +0200349 static const char * const whatnames[7] = {
350 "call", "exception", "line", "return",
351 "c_call", "c_exception", "c_return"
352 };
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyObject *name;
354 int i;
355 for (i = 0; i < 7; ++i) {
356 if (whatstrings[i] == NULL) {
357 name = PyUnicode_InternFromString(whatnames[i]);
358 if (name == NULL)
359 return -1;
360 whatstrings[i] = name;
361 }
362 }
363 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000364}
365
366
367static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100368call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000369 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000370{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyObject *result;
Victor Stinner78da82b2016-08-20 01:22:57 +0200372 PyObject *stack[3];
Fred Drake5755ce62001-06-27 19:19:46 +0000373
Victor Stinner78da82b2016-08-20 01:22:57 +0200374 if (PyFrame_FastToLocalsWithError(frame) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000375 return NULL;
Victor Stinner78da82b2016-08-20 01:22:57 +0200376 }
Victor Stinner41bb43a2013-10-29 01:19:37 +0100377
Victor Stinner78da82b2016-08-20 01:22:57 +0200378 stack[0] = (PyObject *)frame;
379 stack[1] = whatstrings[what];
380 stack[2] = (arg != NULL) ? arg : Py_None;
Fred Drake5755ce62001-06-27 19:19:46 +0000381
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000382 /* call the Python-level function */
Victor Stinner559bb6a2016-08-22 22:48:54 +0200383 result = _PyObject_FastCall(callback, stack, 3);
Fred Drake5755ce62001-06-27 19:19:46 +0000384
Victor Stinner78da82b2016-08-20 01:22:57 +0200385 PyFrame_LocalsToFast(frame, 1);
386 if (result == NULL) {
387 PyTraceBack_Here(frame);
388 }
389
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000391}
392
393static int
394profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (arg == NULL)
400 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100401 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (result == NULL) {
403 PyEval_SetProfile(NULL, NULL);
404 return -1;
405 }
406 Py_DECREF(result);
407 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000408}
409
410static int
411trace_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 *callback;
415 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000416
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 if (what == PyTrace_CALL)
418 callback = self;
419 else
420 callback = frame->f_trace;
421 if (callback == NULL)
422 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100423 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (result == NULL) {
425 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200426 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000427 return -1;
428 }
429 if (result != Py_None) {
Serhiy Storchakaec397562016-04-06 09:50:03 +0300430 Py_XSETREF(frame->f_trace, result);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 }
432 else {
433 Py_DECREF(result);
434 }
435 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000436}
Fred Draked0838392001-06-16 21:02:31 +0000437
Fred Drake8b4d01d2000-05-09 19:57:01 +0000438static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000439sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000440{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000441 if (trace_init() == -1)
442 return NULL;
443 if (args == Py_None)
444 PyEval_SetTrace(NULL, NULL);
445 else
446 PyEval_SetTrace(trace_trampoline, args);
447 Py_INCREF(Py_None);
448 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000449}
450
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000451PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000452"settrace(function)\n\
453\n\
454Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000455function call. See the debugger chapter in the library manual."
456);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000457
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000458static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000459sys_gettrace(PyObject *self, PyObject *args)
460{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000461 PyThreadState *tstate = PyThreadState_GET();
462 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000463
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 if (temp == NULL)
465 temp = Py_None;
466 Py_INCREF(temp);
467 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000468}
469
470PyDoc_STRVAR(gettrace_doc,
471"gettrace()\n\
472\n\
473Return the global debug tracing function set with sys.settrace.\n\
474See the debugger chapter in the library manual."
475);
476
477static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000478sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000479{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000480 if (trace_init() == -1)
481 return NULL;
482 if (args == Py_None)
483 PyEval_SetProfile(NULL, NULL);
484 else
485 PyEval_SetProfile(profile_trampoline, args);
486 Py_INCREF(Py_None);
487 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000488}
489
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000490PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000491"setprofile(function)\n\
492\n\
493Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000494and return. See the profiler chapter in the library manual."
495);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000496
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000497static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000498sys_getprofile(PyObject *self, PyObject *args)
499{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000500 PyThreadState *tstate = PyThreadState_GET();
501 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 if (temp == NULL)
504 temp = Py_None;
505 Py_INCREF(temp);
506 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000507}
508
509PyDoc_STRVAR(getprofile_doc,
510"getprofile()\n\
511\n\
512Return the profiling function set with sys.setprofile.\n\
513See the profiler chapter in the library manual."
514);
515
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000516static int _check_interval = 100;
517
Christian Heimes9bd667a2008-01-20 15:14:11 +0000518static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000519sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 if (PyErr_WarnEx(PyExc_DeprecationWarning,
522 "sys.getcheckinterval() and sys.setcheckinterval() "
523 "are deprecated. Use sys.setswitchinterval() "
524 "instead.", 1) < 0)
525 return NULL;
526 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
527 return NULL;
528 Py_INCREF(Py_None);
529 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000530}
531
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000532PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000533"setcheckinterval(n)\n\
534\n\
535Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000536n instructions. This also affects how often thread switches occur."
537);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000538
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000539static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000540sys_getcheckinterval(PyObject *self, PyObject *args)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 if (PyErr_WarnEx(PyExc_DeprecationWarning,
543 "sys.getcheckinterval() and sys.setcheckinterval() "
544 "are deprecated. Use sys.getswitchinterval() "
545 "instead.", 1) < 0)
546 return NULL;
547 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000548}
549
550PyDoc_STRVAR(getcheckinterval_doc,
551"getcheckinterval() -> current check interval; see setcheckinterval()."
552);
553
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000554#ifdef WITH_THREAD
555static PyObject *
556sys_setswitchinterval(PyObject *self, PyObject *args)
557{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000558 double d;
559 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
560 return NULL;
561 if (d <= 0.0) {
562 PyErr_SetString(PyExc_ValueError,
563 "switch interval must be strictly positive");
564 return NULL;
565 }
566 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
567 Py_INCREF(Py_None);
568 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000569}
570
571PyDoc_STRVAR(setswitchinterval_doc,
572"setswitchinterval(n)\n\
573\n\
574Set the ideal thread switching delay inside the Python interpreter\n\
575The actual frequency of switching threads can be lower if the\n\
576interpreter executes long sequences of uninterruptible code\n\
577(this is implementation-specific and workload-dependent).\n\
578\n\
579The parameter must represent the desired switching delay in seconds\n\
580A typical value is 0.005 (5 milliseconds)."
581);
582
583static PyObject *
584sys_getswitchinterval(PyObject *self, PyObject *args)
585{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000586 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000587}
588
589PyDoc_STRVAR(getswitchinterval_doc,
590"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
591);
592
593#endif /* WITH_THREAD */
594
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000595#ifdef WITH_TSC
596static PyObject *
597sys_settscdump(PyObject *self, PyObject *args)
598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000599 int bool;
600 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000602 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
603 return NULL;
604 if (bool)
605 tstate->interp->tscdump = 1;
606 else
607 tstate->interp->tscdump = 0;
608 Py_INCREF(Py_None);
609 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000610
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000611}
612
Tim Peters216b78b2006-01-06 02:40:53 +0000613PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000614"settscdump(bool)\n\
615\n\
616If true, tell the Python interpreter to dump VM measurements to\n\
617stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000618processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000619);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000620#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000621
Tim Peterse5e065b2003-07-06 18:36:54 +0000622static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000623sys_setrecursionlimit(PyObject *self, PyObject *args)
624{
Victor Stinner50856d52015-10-13 00:11:21 +0200625 int new_limit, mark;
626 PyThreadState *tstate;
627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000628 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
629 return NULL;
Victor Stinner50856d52015-10-13 00:11:21 +0200630
631 if (new_limit < 1) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 PyErr_SetString(PyExc_ValueError,
Victor Stinner50856d52015-10-13 00:11:21 +0200633 "recursion limit must be greater or equal than 1");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000634 return NULL;
635 }
Victor Stinner50856d52015-10-13 00:11:21 +0200636
637 /* Issue #25274: When the recursion depth hits the recursion limit in
638 _Py_CheckRecursiveCall(), the overflowed flag of the thread state is
639 set to 1 and a RecursionError is raised. The overflowed flag is reset
640 to 0 when the recursion depth goes below the low-water mark: see
641 Py_LeaveRecursiveCall().
642
643 Reject too low new limit if the current recursion depth is higher than
644 the new low-water mark. Otherwise it may not be possible anymore to
645 reset the overflowed flag to 0. */
646 mark = _Py_RecursionLimitLowerWaterMark(new_limit);
647 tstate = PyThreadState_GET();
648 if (tstate->recursion_depth >= mark) {
649 PyErr_Format(PyExc_RecursionError,
650 "cannot set the recursion limit to %i at "
651 "the recursion depth %i: the limit is too low",
652 new_limit, tstate->recursion_depth);
653 return NULL;
654 }
655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000656 Py_SetRecursionLimit(new_limit);
657 Py_INCREF(Py_None);
658 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000659}
660
Yury Selivanov75445082015-05-11 22:57:16 -0400661static PyObject *
662sys_set_coroutine_wrapper(PyObject *self, PyObject *wrapper)
663{
664 if (wrapper != Py_None) {
665 if (!PyCallable_Check(wrapper)) {
666 PyErr_Format(PyExc_TypeError,
667 "callable expected, got %.50s",
668 Py_TYPE(wrapper)->tp_name);
669 return NULL;
670 }
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400671 _PyEval_SetCoroutineWrapper(wrapper);
Yury Selivanov75445082015-05-11 22:57:16 -0400672 }
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400673 else {
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400674 _PyEval_SetCoroutineWrapper(NULL);
Benjamin Petersonbaa2e562015-05-12 11:32:41 -0400675 }
Yury Selivanov75445082015-05-11 22:57:16 -0400676 Py_RETURN_NONE;
677}
678
679PyDoc_STRVAR(set_coroutine_wrapper_doc,
680"set_coroutine_wrapper(wrapper)\n\
681\n\
682Set a wrapper for coroutine objects."
683);
684
685static PyObject *
686sys_get_coroutine_wrapper(PyObject *self, PyObject *args)
687{
Yury Selivanovd8cf3822015-06-01 12:15:23 -0400688 PyObject *wrapper = _PyEval_GetCoroutineWrapper();
Yury Selivanov75445082015-05-11 22:57:16 -0400689 if (wrapper == NULL) {
690 wrapper = Py_None;
691 }
692 Py_INCREF(wrapper);
693 return wrapper;
694}
695
696PyDoc_STRVAR(get_coroutine_wrapper_doc,
697"get_coroutine_wrapper()\n\
698\n\
699Return the wrapper for coroutine objects set by sys.set_coroutine_wrapper."
700);
701
702
Mark Dickinsondc787d22010-05-23 13:33:13 +0000703static PyTypeObject Hash_InfoType;
704
705PyDoc_STRVAR(hash_info_doc,
706"hash_info\n\
707\n\
708A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100709hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000710
711static PyStructSequence_Field hash_info_fields[] = {
712 {"width", "width of the type used for hashing, in bits"},
713 {"modulus", "prime number giving the modulus on which the hash "
714 "function is based"},
715 {"inf", "value to be used for hash of a positive infinity"},
716 {"nan", "value to be used for hash of a nan"},
717 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100718 {"algorithm", "name of the algorithm for hashing of str, bytes and "
719 "memoryviews"},
720 {"hash_bits", "internal output size of hash algorithm"},
721 {"seed_bits", "seed size of hash algorithm"},
722 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000723 {NULL, NULL}
724};
725
726static PyStructSequence_Desc hash_info_desc = {
727 "sys.hash_info",
728 hash_info_doc,
729 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100730 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000731};
732
Matthias Klosed885e952010-07-06 10:53:30 +0000733static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000734get_hash_info(void)
735{
736 PyObject *hash_info;
737 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100738 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000739 hash_info = PyStructSequence_New(&Hash_InfoType);
740 if (hash_info == NULL)
741 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100742 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000743 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000744 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000745 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000746 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000747 PyStructSequence_SET_ITEM(hash_info, field++,
748 PyLong_FromLong(_PyHASH_INF));
749 PyStructSequence_SET_ITEM(hash_info, field++,
750 PyLong_FromLong(_PyHASH_NAN));
751 PyStructSequence_SET_ITEM(hash_info, field++,
752 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100753 PyStructSequence_SET_ITEM(hash_info, field++,
754 PyUnicode_FromString(hashfunc->name));
755 PyStructSequence_SET_ITEM(hash_info, field++,
756 PyLong_FromLong(hashfunc->hash_bits));
757 PyStructSequence_SET_ITEM(hash_info, field++,
758 PyLong_FromLong(hashfunc->seed_bits));
759 PyStructSequence_SET_ITEM(hash_info, field++,
760 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000761 if (PyErr_Occurred()) {
762 Py_CLEAR(hash_info);
763 return NULL;
764 }
765 return hash_info;
766}
767
768
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000769PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000770"setrecursionlimit(n)\n\
771\n\
772Set the maximum depth of the Python interpreter stack to n. This\n\
773limit prevents infinite recursion from causing an overflow of the C\n\
774stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000775dependent."
776);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000777
778static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000779sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000782}
783
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000784PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000785"getrecursionlimit()\n\
786\n\
787Return the current value of the recursion limit, the maximum depth\n\
788of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000789recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000790);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000791
Mark Hammond8696ebc2002-10-08 02:44:31 +0000792#ifdef MS_WINDOWS
793PyDoc_STRVAR(getwindowsversion_doc,
794"getwindowsversion()\n\
795\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000796Return information about the running version of Windows as a named tuple.\n\
797The members are named: major, minor, build, platform, service_pack,\n\
798service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200799backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000800All elements are numbers, except service_pack which is a string. Platform\n\
801may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
8023 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
803controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000804);
805
Eric Smithf7bb5782010-01-27 00:44:57 +0000806static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
807
808static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000809 {"major", "Major version number"},
810 {"minor", "Minor version number"},
811 {"build", "Build number"},
812 {"platform", "Operating system platform"},
813 {"service_pack", "Latest Service Pack installed on the system"},
814 {"service_pack_major", "Service Pack major version number"},
815 {"service_pack_minor", "Service Pack minor version number"},
816 {"suite_mask", "Bit mask identifying available product suites"},
817 {"product_type", "System product type"},
818 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000819};
820
821static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 "sys.getwindowsversion", /* name */
823 getwindowsversion_doc, /* doc */
824 windows_version_fields, /* fields */
825 5 /* For backward compatibility,
826 only the first 5 items are accessible
827 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000828};
829
Steve Dower3e96f322015-03-02 08:01:10 -0800830/* Disable deprecation warnings about GetVersionEx as the result is
831 being passed straight through to the caller, who is responsible for
832 using it correctly. */
833#pragma warning(push)
834#pragma warning(disable:4996)
835
Mark Hammond8696ebc2002-10-08 02:44:31 +0000836static PyObject *
837sys_getwindowsversion(PyObject *self)
838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyObject *version;
840 int pos = 0;
841 OSVERSIONINFOEX ver;
842 ver.dwOSVersionInfoSize = sizeof(ver);
843 if (!GetVersionEx((OSVERSIONINFO*) &ver))
844 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 version = PyStructSequence_New(&WindowsVersionType);
847 if (version == NULL)
848 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000849
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000850 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
851 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
852 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
853 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
854 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
855 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
856 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
857 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
858 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000859
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200860 if (PyErr_Occurred()) {
861 Py_DECREF(version);
862 return NULL;
863 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000865}
866
Steve Dower3e96f322015-03-02 08:01:10 -0800867#pragma warning(pop)
868
Mark Hammond8696ebc2002-10-08 02:44:31 +0000869#endif /* MS_WINDOWS */
870
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000871#ifdef HAVE_DLOPEN
872static PyObject *
873sys_setdlopenflags(PyObject *self, PyObject *args)
874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 int new_val;
876 PyThreadState *tstate = PyThreadState_GET();
877 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
878 return NULL;
879 if (!tstate)
880 return NULL;
881 tstate->interp->dlopenflags = new_val;
882 Py_INCREF(Py_None);
883 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000884}
885
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000886PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000887"setdlopenflags(n) -> None\n\
888\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000889Set the flags used by the interpreter for dlopen calls, such as when the\n\
890interpreter loads extension modules. Among other things, this will enable\n\
891a lazy resolving of symbols when importing a module, if called as\n\
892sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400893sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100894can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000895
896static PyObject *
897sys_getdlopenflags(PyObject *self, PyObject *args)
898{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 PyThreadState *tstate = PyThreadState_GET();
900 if (!tstate)
901 return NULL;
902 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000903}
904
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000905PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000906"getdlopenflags() -> int\n\
907\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000908Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400909The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000910
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000911#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000912
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000913#ifdef USE_MALLOPT
914/* Link with -lmalloc (or -lmpc) on an SGI */
915#include <malloc.h>
916
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000917static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000918sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000919{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 int flag;
921 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
922 return NULL;
923 mallopt(M_DEBUG, flag);
924 Py_INCREF(Py_None);
925 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000926}
927#endif /* USE_MALLOPT */
928
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300929size_t
930_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000931{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000932 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 PyObject *method;
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200934 Py_ssize_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +0000935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 /* Make sure the type is initialized. float gets initialized late */
937 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300938 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000939
Benjamin Petersonce798522012-01-22 11:24:29 -0500940 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000941 if (method == NULL) {
942 if (!PyErr_Occurred())
943 PyErr_Format(PyExc_TypeError,
944 "Type %.100s doesn't define __sizeof__",
945 Py_TYPE(o)->tp_name);
946 }
947 else {
948 res = PyObject_CallFunctionObjArgs(method, NULL);
949 Py_DECREF(method);
950 }
951
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300952 if (res == NULL)
953 return (size_t)-1;
954
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200955 size = PyLong_AsSsize_t(res);
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300956 Py_DECREF(res);
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200957 if (size == -1 && PyErr_Occurred())
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300958 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000959
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200960 if (size < 0) {
961 PyErr_SetString(PyExc_ValueError, "__sizeof__() should return >= 0");
962 return (size_t)-1;
963 }
964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300966 if (PyObject_IS_GC(o))
Serhiy Storchaka030e92d2014-11-15 13:21:37 +0200967 return ((size_t)size) + sizeof(PyGC_Head);
968 return (size_t)size;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300969}
970
971static PyObject *
972sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
973{
974 static char *kwlist[] = {"object", "default", 0};
975 size_t size;
976 PyObject *o, *dflt = NULL;
977
978 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
979 kwlist, &o, &dflt))
980 return NULL;
981
982 size = _PySys_GetSizeOf(o);
983
984 if (size == (size_t)-1 && PyErr_Occurred()) {
985 /* Has a default value been given */
986 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
987 PyErr_Clear();
988 Py_INCREF(dflt);
989 return dflt;
990 }
991 else
992 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300994
995 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000996}
997
998PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000999"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001000\n\
1001Return the size of object in bytes.");
1002
1003static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +00001004sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001005{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001007}
1008
Tim Peters4be93d02002-07-07 19:59:50 +00001009#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +00001010static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001011sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +00001012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +00001014}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001015#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +00001016
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001017PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001018"getrefcount(object) -> integer\n\
1019\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +00001020Return the reference count of object. The count returned is generally\n\
1021one higher than you might expect, because it includes the (temporary)\n\
1022reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001023);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001024
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001025static PyObject *
1026sys_getallocatedblocks(PyObject *self)
1027{
1028 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
1029}
1030
1031PyDoc_STRVAR(getallocatedblocks_doc,
1032"getallocatedblocks() -> integer\n\
1033\n\
1034Return the number of memory blocks currently allocated, regardless of their\n\
1035size."
1036);
1037
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001038#ifdef COUNT_ALLOCS
1039static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +00001040sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001043
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001045}
1046#endif
1047
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001048PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +00001049"_getframe([depth]) -> frameobject\n\
1050\n\
1051Return a frame object from the call stack. If optional integer depth is\n\
1052given, return the frame object that many calls below the top of the stack.\n\
1053If that is deeper than the call stack, ValueError is raised. The default\n\
1054for depth is zero, returning the frame at the top of the call stack.\n\
1055\n\
1056This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001057purposes only."
1058);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001059
1060static PyObject *
1061sys_getframe(PyObject *self, PyObject *args)
1062{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001063 PyFrameObject *f = PyThreadState_GET()->frame;
1064 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001065
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
1067 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001068
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 while (depth > 0 && f != NULL) {
1070 f = f->f_back;
1071 --depth;
1072 }
1073 if (f == NULL) {
1074 PyErr_SetString(PyExc_ValueError,
1075 "call stack is not deep enough");
1076 return NULL;
1077 }
1078 Py_INCREF(f);
1079 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001080}
1081
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001082PyDoc_STRVAR(current_frames_doc,
1083"_current_frames() -> dictionary\n\
1084\n\
1085Return a dictionary mapping each current thread T's thread id to T's\n\
1086current stack frame.\n\
1087\n\
1088This function should be used for specialized purposes only."
1089);
1090
1091static PyObject *
1092sys_current_frames(PyObject *self, PyObject *noargs)
1093{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001094 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001095}
1096
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001097PyDoc_STRVAR(call_tracing_doc,
1098"call_tracing(func, args) -> object\n\
1099\n\
1100Call func(*args), while tracing is enabled. The tracing state is\n\
1101saved, and restored afterwards. This is intended to be called from\n\
1102a debugger from a checkpoint, to recursively debug some other code."
1103);
1104
1105static PyObject *
1106sys_call_tracing(PyObject *self, PyObject *args)
1107{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001108 PyObject *func, *funcargs;
1109 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1110 return NULL;
1111 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001112}
1113
Jeremy Hylton985eba52003-02-05 23:13:00 +00001114PyDoc_STRVAR(callstats_doc,
1115"callstats() -> tuple of integers\n\
1116\n\
1117Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1118when Python was built. Otherwise, return None.\n\
1119\n\
1120When enabled, this function returns detailed, implementation-specific\n\
1121details about the number of function calls executed. The return value is\n\
1122a 11-tuple where the entries in the tuple are counts of:\n\
11230. all function calls\n\
11241. calls to PyFunction_Type objects\n\
11252. PyFunction calls that do not create an argument tuple\n\
11263. PyFunction calls that do not create an argument tuple\n\
1127 and bypass PyEval_EvalCodeEx()\n\
11284. PyMethod calls\n\
11295. PyMethod calls on bound methods\n\
11306. PyType calls\n\
11317. PyCFunction calls\n\
11328. generator calls\n\
11339. All other calls\n\
113410. Number of stack pops performed by call_function()"
1135);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001136
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001137#ifdef __cplusplus
1138extern "C" {
1139#endif
1140
David Malcolm49526f42012-06-22 14:55:41 -04001141static PyObject *
1142sys_debugmallocstats(PyObject *self, PyObject *args)
1143{
1144#ifdef WITH_PYMALLOC
Victor Stinner34be8072016-03-14 12:04:26 +01001145 if (_PyMem_PymallocEnabled()) {
1146 _PyObject_DebugMallocStats(stderr);
1147 fputc('\n', stderr);
1148 }
David Malcolm49526f42012-06-22 14:55:41 -04001149#endif
1150 _PyObject_DebugTypeStats(stderr);
1151
1152 Py_RETURN_NONE;
1153}
1154PyDoc_STRVAR(debugmallocstats_doc,
1155"_debugmallocstats()\n\
1156\n\
1157Print summary info to stderr about the state of\n\
1158pymalloc's structures.\n\
1159\n\
1160In Py_DEBUG mode, also perform some expensive internal consistency\n\
1161checks.\n\
1162");
1163
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001164#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001165/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001166extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001167#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001168
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001169#ifdef DYNAMIC_EXECUTION_PROFILE
1170/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001171extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001172#endif
1173
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001174#ifdef __cplusplus
1175}
1176#endif
1177
Christian Heimes15ebc882008-02-04 18:48:49 +00001178static PyObject *
1179sys_clear_type_cache(PyObject* self, PyObject* args)
1180{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001181 PyType_ClearCache();
1182 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001183}
1184
1185PyDoc_STRVAR(sys_clear_type_cache__doc__,
1186"_clear_type_cache() -> None\n\
1187Clear the internal type lookup cache.");
1188
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001189static PyObject *
1190sys_is_finalizing(PyObject* self, PyObject* args)
1191{
1192 return PyBool_FromLong(_Py_Finalizing != NULL);
1193}
1194
1195PyDoc_STRVAR(is_finalizing_doc,
1196"is_finalizing()\n\
1197Return True if Python is exiting.");
1198
Christian Heimes15ebc882008-02-04 18:48:49 +00001199
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001200static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001201 /* Might as well keep this in alphabetic order */
1202 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1203 callstats_doc},
1204 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1205 sys_clear_type_cache__doc__},
1206 {"_current_frames", sys_current_frames, METH_NOARGS,
1207 current_frames_doc},
1208 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1209 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1210 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1211 {"exit", sys_exit, METH_VARARGS, exit_doc},
1212 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1213 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001214#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001215 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1216 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001217#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001218 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1219 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001220#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001221 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001222#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001223#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001225#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001226 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1227 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001228#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001230#endif
1231#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001233#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1235 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1236 getrecursionlimit_doc},
1237 {"getsizeof", (PyCFunction)sys_getsizeof,
1238 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1239 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001240#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001241 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1242 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001243#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 {"intern", sys_intern, METH_VARARGS, intern_doc},
Antoine Pitrou5db1bb82014-12-07 01:28:27 +01001245 {"is_finalizing", sys_is_finalizing, METH_NOARGS, is_finalizing_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001246#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001247 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001248#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001249 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1250 setcheckinterval_doc},
1251 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1252 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001253#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1255 setswitchinterval_doc},
1256 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1257 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001258#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001259#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1261 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001262#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001263 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1264 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1265 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1266 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001267#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001268 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001269#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 {"settrace", sys_settrace, METH_O, settrace_doc},
1271 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1272 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001273 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001274 debugmallocstats_doc},
Yury Selivanov75445082015-05-11 22:57:16 -04001275 {"set_coroutine_wrapper", sys_set_coroutine_wrapper, METH_O,
1276 set_coroutine_wrapper_doc},
1277 {"get_coroutine_wrapper", sys_get_coroutine_wrapper, METH_NOARGS,
1278 get_coroutine_wrapper_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001280};
1281
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001282static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001283list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 PyObject *list = PyList_New(0);
1286 int i;
1287 if (list == NULL)
1288 return NULL;
1289 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1290 PyObject *name = PyUnicode_FromString(
1291 PyImport_Inittab[i].name);
1292 if (name == NULL)
1293 break;
1294 PyList_Append(list, name);
1295 Py_DECREF(name);
1296 }
1297 if (PyList_Sort(list) != 0) {
1298 Py_DECREF(list);
1299 list = NULL;
1300 }
1301 if (list) {
1302 PyObject *v = PyList_AsTuple(list);
1303 Py_DECREF(list);
1304 list = v;
1305 }
1306 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001307}
1308
Guido van Rossum23fff912000-12-15 22:02:05 +00001309static PyObject *warnoptions = NULL;
1310
1311void
1312PySys_ResetWarnOptions(void)
1313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001314 if (warnoptions == NULL || !PyList_Check(warnoptions))
1315 return;
1316 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001317}
1318
1319void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001320PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001321{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1323 Py_XDECREF(warnoptions);
1324 warnoptions = PyList_New(0);
1325 if (warnoptions == NULL)
1326 return;
1327 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001328 PyList_Append(warnoptions, unicode);
1329}
1330
1331void
1332PySys_AddWarnOption(const wchar_t *s)
1333{
1334 PyObject *unicode;
1335 unicode = PyUnicode_FromWideChar(s, -1);
1336 if (unicode == NULL)
1337 return;
1338 PySys_AddWarnOptionUnicode(unicode);
1339 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001340}
1341
Christian Heimes33fe8092008-04-13 13:53:33 +00001342int
1343PySys_HasWarnOptions(void)
1344{
1345 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1346}
1347
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001348static PyObject *xoptions = NULL;
1349
1350static PyObject *
1351get_xoptions(void)
1352{
1353 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1354 Py_XDECREF(xoptions);
1355 xoptions = PyDict_New();
1356 }
1357 return xoptions;
1358}
1359
1360void
1361PySys_AddXOption(const wchar_t *s)
1362{
1363 PyObject *opts;
1364 PyObject *name = NULL, *value = NULL;
1365 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001366
1367 opts = get_xoptions();
1368 if (opts == NULL)
1369 goto error;
1370
1371 name_end = wcschr(s, L'=');
1372 if (!name_end) {
1373 name = PyUnicode_FromWideChar(s, -1);
1374 value = Py_True;
1375 Py_INCREF(value);
1376 }
1377 else {
1378 name = PyUnicode_FromWideChar(s, name_end - s);
1379 value = PyUnicode_FromWideChar(name_end + 1, -1);
1380 }
1381 if (name == NULL || value == NULL)
1382 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001383 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001384 Py_DECREF(name);
1385 Py_DECREF(value);
1386 return;
1387
1388error:
1389 Py_XDECREF(name);
1390 Py_XDECREF(value);
1391 /* No return value, therefore clear error state if possible */
Victor Stinnerbfd316e2016-01-20 11:12:38 +01001392 if (_PyThreadState_UncheckedGet())
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001393 PyErr_Clear();
1394}
1395
1396PyObject *
1397PySys_GetXOptions(void)
1398{
1399 return get_xoptions();
1400}
1401
Guido van Rossum40552d01998-08-06 03:34:39 +00001402/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1403 Two literals concatenated works just fine. If you have a K&R compiler
1404 or other abomination that however *does* understand longer strings,
1405 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001406PyDoc_VAR(sys_doc) =
1407PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001408"This module provides access to some objects used or maintained by the\n\
1409interpreter and to functions that interact strongly with the interpreter.\n\
1410\n\
1411Dynamic objects:\n\
1412\n\
1413argv -- command line arguments; argv[0] is the script pathname if known\n\
1414path -- module search path; path[0] is the script directory, else ''\n\
1415modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001416\n\
1417displayhook -- called to show results in an interactive session\n\
1418excepthook -- called to handle any uncaught exception other than SystemExit\n\
1419 To customize printing in an interactive session or to install a custom\n\
1420 top-level exception handler, assign other functions to replace these.\n\
1421\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001422stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001423stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001424stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001425 By assigning other file objects (or objects that behave like files)\n\
1426 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001427\n\
1428last_type -- type of last uncaught exception\n\
1429last_value -- value of last uncaught exception\n\
1430last_traceback -- traceback of last uncaught exception\n\
1431 These three are only available in an interactive session after a\n\
1432 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001433"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001434)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001435/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001436PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001437"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001438Static objects:\n\
1439\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001440builtin_module_names -- tuple of module names built into this interpreter\n\
1441copyright -- copyright notice pertaining to this interpreter\n\
1442exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001443executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001444float_info -- a struct sequence with information about the float implementation.\n\
1445float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001446hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001447hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001448implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001449int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001450maxsize -- the largest supported length of containers.\n\
Serhiy Storchakad3faf432015-01-18 11:28:37 +02001451maxunicode -- the value of the largest Unicode code point\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001452platform -- platform identifier\n\
1453prefix -- prefix used to find the Python library\n\
1454thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001455version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001456version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001457"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001458)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001459#ifdef MS_WINDOWS
1460/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001461PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001462"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001463winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001464"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001465)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001466#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001467PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001468"__stdin__ -- the original stdin; don't touch!\n\
1469__stdout__ -- the original stdout; don't touch!\n\
1470__stderr__ -- the original stderr; don't touch!\n\
1471__displayhook__ -- the original displayhook; don't touch!\n\
1472__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001473\n\
1474Functions:\n\
1475\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001476displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001477excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001478exc_info() -- return thread-safe information about the current exception\n\
1479exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001480getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001481getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001482getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001483getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001484getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001485gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001486setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001487setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001488setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001489setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001490settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001491"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001492)
Fred Drakeccede592000-08-14 20:59:57 +00001493/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001494
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001495
1496PyDoc_STRVAR(flags__doc__,
1497"sys.flags\n\
1498\n\
1499Flags provided through command line arguments or environment vars.");
1500
1501static PyTypeObject FlagsType;
1502
1503static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001504 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 {"inspect", "-i"},
1506 {"interactive", "-i"},
1507 {"optimize", "-O or -OO"},
1508 {"dont_write_bytecode", "-B"},
1509 {"no_user_site", "-s"},
1510 {"no_site", "-S"},
1511 {"ignore_environment", "-E"},
1512 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 /* {"unbuffered", "-u"}, */
1514 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001515 {"bytes_warning", "-b"},
1516 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001517 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001518 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001520};
1521
1522static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 "sys.flags", /* name */
1524 flags__doc__, /* doc */
1525 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001526 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001527};
1528
1529static PyObject*
1530make_flags(void)
1531{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 int pos = 0;
1533 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 seq = PyStructSequence_New(&FlagsType);
1536 if (seq == NULL)
1537 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001538
1539#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001541
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001542 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 SetFlag(Py_InspectFlag);
1544 SetFlag(Py_InteractiveFlag);
1545 SetFlag(Py_OptimizeFlag);
1546 SetFlag(Py_DontWriteBytecodeFlag);
1547 SetFlag(Py_NoUserSiteDirectory);
1548 SetFlag(Py_NoSiteFlag);
1549 SetFlag(Py_IgnoreEnvironmentFlag);
1550 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 /* SetFlag(saw_unbuffered_flag); */
1552 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001553 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001554 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001555 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001556 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001557#undef SetFlag
1558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001560 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 return NULL;
1562 }
1563 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001564}
1565
Eric Smith0e5b5622009-02-06 01:32:42 +00001566PyDoc_STRVAR(version_info__doc__,
1567"sys.version_info\n\
1568\n\
1569Version information as a named tuple.");
1570
1571static PyTypeObject VersionInfoType;
1572
1573static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 {"major", "Major release number"},
1575 {"minor", "Minor release number"},
1576 {"micro", "Patch release number"},
1577 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1578 {"serial", "Serial release number"},
1579 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001580};
1581
1582static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 "sys.version_info", /* name */
1584 version_info__doc__, /* doc */
1585 version_info_fields, /* fields */
1586 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001587};
1588
1589static PyObject *
1590make_version_info(void)
1591{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyObject *version_info;
1593 char *s;
1594 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001595
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001596 version_info = PyStructSequence_New(&VersionInfoType);
1597 if (version_info == NULL) {
1598 return NULL;
1599 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /*
1602 * These release level checks are mutually exclusive and cover
1603 * the field, so don't get too fancy with the pre-processor!
1604 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001605#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001607#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001608 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001609#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001611#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001613#endif
1614
1615#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001617#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001619
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001620 SetIntItem(PY_MAJOR_VERSION);
1621 SetIntItem(PY_MINOR_VERSION);
1622 SetIntItem(PY_MICRO_VERSION);
1623 SetStrItem(s);
1624 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001625#undef SetIntItem
1626#undef SetStrItem
1627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 if (PyErr_Occurred()) {
1629 Py_CLEAR(version_info);
1630 return NULL;
1631 }
1632 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001633}
1634
Brett Cannon3adc7b72012-07-09 14:22:12 -04001635/* sys.implementation values */
1636#define NAME "cpython"
1637const char *_PySys_ImplName = NAME;
Victor Stinnercf01b682015-11-05 11:21:38 +01001638#define MAJOR Py_STRINGIFY(PY_MAJOR_VERSION)
1639#define MINOR Py_STRINGIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001640#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001641const char *_PySys_ImplCacheTag = TAG;
1642#undef NAME
Brett Cannon3adc7b72012-07-09 14:22:12 -04001643#undef MAJOR
1644#undef MINOR
1645#undef TAG
1646
Barry Warsaw409da152012-06-03 16:18:47 -04001647static PyObject *
1648make_impl_info(PyObject *version_info)
1649{
1650 int res;
1651 PyObject *impl_info, *value, *ns;
1652
1653 impl_info = PyDict_New();
1654 if (impl_info == NULL)
1655 return NULL;
1656
1657 /* populate the dict */
1658
Brett Cannon3adc7b72012-07-09 14:22:12 -04001659 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001660 if (value == NULL)
1661 goto error;
1662 res = PyDict_SetItemString(impl_info, "name", value);
1663 Py_DECREF(value);
1664 if (res < 0)
1665 goto error;
1666
Brett Cannon3adc7b72012-07-09 14:22:12 -04001667 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001668 if (value == NULL)
1669 goto error;
1670 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1671 Py_DECREF(value);
1672 if (res < 0)
1673 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001674
1675 res = PyDict_SetItemString(impl_info, "version", version_info);
1676 if (res < 0)
1677 goto error;
1678
1679 value = PyLong_FromLong(PY_VERSION_HEX);
1680 if (value == NULL)
1681 goto error;
1682 res = PyDict_SetItemString(impl_info, "hexversion", value);
1683 Py_DECREF(value);
1684 if (res < 0)
1685 goto error;
1686
doko@ubuntu.com55532312016-06-14 08:55:19 +02001687#ifdef MULTIARCH
1688 value = PyUnicode_FromString(MULTIARCH);
1689 if (value == NULL)
1690 goto error;
1691 res = PyDict_SetItemString(impl_info, "_multiarch", value);
1692 Py_DECREF(value);
1693 if (res < 0)
1694 goto error;
1695#endif
1696
Barry Warsaw409da152012-06-03 16:18:47 -04001697 /* dict ready */
1698
1699 ns = _PyNamespace_New(impl_info);
1700 Py_DECREF(impl_info);
1701 return ns;
1702
1703error:
1704 Py_CLEAR(impl_info);
1705 return NULL;
1706}
1707
Martin v. Löwis1a214512008-06-11 05:26:20 +00001708static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001709 PyModuleDef_HEAD_INIT,
1710 "sys",
1711 sys_doc,
1712 -1, /* multiple "initialization" just copies the module dict. */
1713 sys_methods,
1714 NULL,
1715 NULL,
1716 NULL,
1717 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001718};
1719
Guido van Rossum25ce5661997-08-02 03:10:38 +00001720PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001721_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001722{
Victor Stinner58049602013-07-22 22:40:00 +02001723 PyObject *m, *sysdict, *version_info;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001724 int res;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001725
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 m = PyModule_Create(&sysmodule);
1727 if (m == NULL)
1728 return NULL;
1729 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001730#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001731 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001732 PyObject *v = (value); \
1733 if (v == NULL) \
1734 return NULL; \
1735 res = PyDict_SetItemString(sysdict, key, v); \
1736 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001737 return NULL; \
1738 } \
1739 } while (0)
1740#define SET_SYS_FROM_STRING(key, value) \
1741 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001742 PyObject *v = (value); \
1743 if (v == NULL) \
1744 return NULL; \
1745 res = PyDict_SetItemString(sysdict, key, v); \
1746 Py_DECREF(v); \
1747 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001748 return NULL; \
1749 } \
1750 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001751
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001752 /* Check that stdin is not a directory
1753 Using shell redirection, you can redirect stdin to a directory,
1754 crashing the Python interpreter. Catch this common mistake here
1755 and output a useful error message. Note that under MS Windows,
1756 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001757#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 {
Steve Dowerf2f373f2015-02-21 08:44:05 -08001759 struct _Py_stat_struct sb;
Victor Stinnere134a7f2015-03-30 10:09:31 +02001760 if (_Py_fstat_noraise(fileno(stdin), &sb) == 0 &&
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 S_ISDIR(sb.st_mode)) {
1762 /* There's nothing more we can do. */
1763 /* Py_FatalError() will core dump, so just exit. */
1764 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1765 exit(EXIT_FAILURE);
1766 }
1767 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001768#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001769
Nick Coghland6009512014-11-20 21:39:37 +10001770 /* stdin/stdout/stderr are set in pylifecycle.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001771
Victor Stinner8fea2522013-10-27 17:15:42 +01001772 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1773 PyDict_GetItemString(sysdict, "displayhook"));
1774 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1775 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 SET_SYS_FROM_STRING("version",
1777 PyUnicode_FromString(Py_GetVersion()));
1778 SET_SYS_FROM_STRING("hexversion",
1779 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001780 SET_SYS_FROM_STRING("_mercurial",
1781 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1782 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 SET_SYS_FROM_STRING("dont_write_bytecode",
1784 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1785 SET_SYS_FROM_STRING("api_version",
1786 PyLong_FromLong(PYTHON_API_VERSION));
1787 SET_SYS_FROM_STRING("copyright",
1788 PyUnicode_FromString(Py_GetCopyright()));
1789 SET_SYS_FROM_STRING("platform",
1790 PyUnicode_FromString(Py_GetPlatform()));
1791 SET_SYS_FROM_STRING("executable",
1792 PyUnicode_FromWideChar(
1793 Py_GetProgramFullPath(), -1));
1794 SET_SYS_FROM_STRING("prefix",
1795 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1796 SET_SYS_FROM_STRING("exec_prefix",
1797 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001798 SET_SYS_FROM_STRING("base_prefix",
1799 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1800 SET_SYS_FROM_STRING("base_exec_prefix",
1801 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 SET_SYS_FROM_STRING("maxsize",
1803 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1804 SET_SYS_FROM_STRING("float_info",
1805 PyFloat_GetInfo());
1806 SET_SYS_FROM_STRING("int_info",
1807 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001808 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001809 if (Hash_InfoType.tp_name == NULL) {
1810 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1811 return NULL;
1812 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001813 SET_SYS_FROM_STRING("hash_info",
1814 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001815 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001816 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001817 SET_SYS_FROM_STRING("builtin_module_names",
1818 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001819#if PY_BIG_ENDIAN
1820 SET_SYS_FROM_STRING("byteorder",
1821 PyUnicode_FromString("big"));
1822#else
1823 SET_SYS_FROM_STRING("byteorder",
1824 PyUnicode_FromString("little"));
1825#endif
Fred Drake099325e2000-08-14 15:47:03 +00001826
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001827#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 SET_SYS_FROM_STRING("dllhandle",
1829 PyLong_FromVoidPtr(PyWin_DLLhModule));
1830 SET_SYS_FROM_STRING("winver",
1831 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001832#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001833#ifdef ABIFLAGS
1834 SET_SYS_FROM_STRING("abiflags",
1835 PyUnicode_FromString(ABIFLAGS));
1836#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 if (warnoptions == NULL) {
1838 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02001839 if (warnoptions == NULL)
1840 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001841 }
1842 else {
1843 Py_INCREF(warnoptions);
1844 }
Victor Stinner8fea2522013-10-27 17:15:42 +01001845 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00001846
Victor Stinner8fea2522013-10-27 17:15:42 +01001847 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001850 if (VersionInfoType.tp_name == NULL) {
1851 if (PyStructSequence_InitType2(&VersionInfoType,
1852 &version_info_desc) < 0)
1853 return NULL;
1854 }
Barry Warsaw409da152012-06-03 16:18:47 -04001855 version_info = make_version_info();
1856 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 /* prevent user from creating new instances */
1858 VersionInfoType.tp_init = NULL;
1859 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001860 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
1861 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1862 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00001863
Barry Warsaw409da152012-06-03 16:18:47 -04001864 /* implementation */
1865 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1866
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001868 if (FlagsType.tp_name == 0) {
1869 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
1870 return NULL;
1871 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001872 SET_SYS_FROM_STRING("flags", make_flags());
1873 /* prevent user from creating new instances */
1874 FlagsType.tp_init = NULL;
1875 FlagsType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001876 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
1877 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1878 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00001879
1880#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 /* getwindowsversion */
1882 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02001883 if (PyStructSequence_InitType2(&WindowsVersionType,
1884 &windows_version_desc) < 0)
1885 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 /* prevent user from creating new instances */
1887 WindowsVersionType.tp_init = NULL;
1888 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001889 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
1890 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1891 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00001892#endif
1893
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001894 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001895#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 SET_SYS_FROM_STRING("float_repr_style",
1897 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001898#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001899 SET_SYS_FROM_STRING("float_repr_style",
1900 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001901#endif
1902
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001903#ifdef WITH_THREAD
1904 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1905#endif
1906
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001907#undef SET_SYS_FROM_STRING
Benjamin Peterson93813432014-03-28 18:52:45 -04001908#undef SET_SYS_FROM_STRING_BORROW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (PyErr_Occurred())
1910 return NULL;
1911 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001912}
1913
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001914static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001915makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001916{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001917 int i, n;
1918 const wchar_t *p;
1919 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001921 n = 1;
1922 p = path;
1923 while ((p = wcschr(p, delim)) != NULL) {
1924 n++;
1925 p++;
1926 }
1927 v = PyList_New(n);
1928 if (v == NULL)
1929 return NULL;
1930 for (i = 0; ; i++) {
1931 p = wcschr(path, delim);
1932 if (p == NULL)
1933 p = path + wcslen(path); /* End of string */
1934 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1935 if (w == NULL) {
1936 Py_DECREF(v);
1937 return NULL;
1938 }
1939 PyList_SetItem(v, i, w);
1940 if (*p == '\0')
1941 break;
1942 path = p+1;
1943 }
1944 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001945}
1946
1947void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001948PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 PyObject *v;
1951 if ((v = makepathobject(path, DELIM)) == NULL)
1952 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01001953 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 Py_FatalError("can't assign sys.path");
1955 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001956}
1957
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001958static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001959makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001960{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 PyObject *av;
1962 if (argc <= 0 || argv == NULL) {
1963 /* Ensure at least one (empty) argument is seen */
1964 static wchar_t *empty_argv[1] = {L""};
1965 argv = empty_argv;
1966 argc = 1;
1967 }
1968 av = PyList_New(argc);
1969 if (av != NULL) {
1970 int i;
1971 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001972 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001973 if (v == NULL) {
1974 Py_DECREF(av);
1975 av = NULL;
1976 break;
1977 }
1978 PyList_SetItem(av, i, v);
1979 }
1980 }
1981 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001982}
1983
Nick Coghland26c18a2010-08-17 13:06:11 +00001984#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1985 (argc > 0 && argv0 != NULL && \
1986 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001987
1988static void
1989sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001990{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001991 wchar_t *argv0;
1992 wchar_t *p = NULL;
1993 Py_ssize_t n = 0;
1994 PyObject *a;
1995 PyObject *path;
1996#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001997 wchar_t link[MAXPATHLEN+1];
1998 wchar_t argv0copy[2*MAXPATHLEN+1];
1999 int nr = 0;
2000#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00002001#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00002003#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00002005#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002006
Victor Stinnerbd303c12013-11-07 23:07:29 +01002007 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002008 if (path == NULL)
2009 return;
2010
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002011 argv0 = argv[0];
2012
2013#ifdef HAVE_READLINK
2014 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
2015 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
2016 if (nr > 0) {
2017 /* It's a symlink */
2018 link[nr] = '\0';
2019 if (link[0] == SEP)
2020 argv0 = link; /* Link to absolute path */
2021 else if (wcschr(link, SEP) == NULL)
2022 ; /* Link without path */
2023 else {
2024 /* Must join(dirname(argv0), link) */
2025 wchar_t *q = wcsrchr(argv0, SEP);
2026 if (q == NULL)
2027 argv0 = link; /* argv0 without path */
2028 else {
Christian Heimes60a60672013-07-22 12:53:32 +02002029 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
2030 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002031 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02002032 wcsncpy(q+1, link, MAXPATHLEN);
2033 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002034 argv0 = argv0copy;
2035 }
2036 }
2037 }
2038#endif /* HAVE_READLINK */
2039#if SEP == '\\' /* Special case for MS filename syntax */
2040 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2041 wchar_t *q;
2042#if defined(MS_WINDOWS) && !defined(MS_WINCE)
2043 /* This code here replaces the first element in argv with the full
2044 path that it represents. Under CE, there are no relative paths so
2045 the argument must be the full path anyway. */
2046 wchar_t *ptemp;
2047 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02002048 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002049 fullpath,
2050 &ptemp)) {
2051 argv0 = fullpath;
2052 }
2053#endif
2054 p = wcsrchr(argv0, SEP);
2055 /* Test for alternate separator */
2056 q = wcsrchr(p ? p : argv0, '/');
2057 if (q != NULL)
2058 p = q;
2059 if (p != NULL) {
2060 n = p + 1 - argv0;
2061 if (n > 1 && p[-1] != ':')
2062 n--; /* Drop trailing separator */
2063 }
2064 }
2065#else /* All other filename syntaxes */
2066 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
2067#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01002068 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002069 argv0 = fullpath;
2070 }
2071#endif
2072 p = wcsrchr(argv0, SEP);
2073 }
2074 if (p != NULL) {
2075 n = p + 1 - argv0;
2076#if SEP == '/' /* Special case for Unix filename syntax */
2077 if (n > 1)
2078 n--; /* Drop trailing separator */
2079#endif /* Unix */
2080 }
2081#endif /* All others */
2082 a = PyUnicode_FromWideChar(argv0, n);
2083 if (a == NULL)
2084 Py_FatalError("no mem for sys.path insertion");
2085 if (PyList_Insert(path, 0, a) < 0)
2086 Py_FatalError("sys.path.insert(0) failed");
2087 Py_DECREF(a);
2088}
2089
2090void
2091PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2092{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002094 if (av == NULL)
2095 Py_FatalError("no mem for sys.argv");
2096 if (PySys_SetObject("argv", av) != 0)
2097 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002098 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002099 if (updatepath)
2100 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002101}
Guido van Rossuma890e681998-05-12 14:59:24 +00002102
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002103void
2104PySys_SetArgv(int argc, wchar_t **argv)
2105{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002106 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002107}
2108
Victor Stinner14284c22010-04-23 12:02:30 +00002109/* Reimplementation of PyFile_WriteString() no calling indirectly
2110 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2111
2112static int
Victor Stinner79766632010-08-16 17:36:42 +00002113sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002114{
Victor Stinnerc3ccaae2016-08-20 01:24:22 +02002115 PyObject *writer = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002116 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002117
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002118 if (file == NULL)
2119 return -1;
2120
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002121 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002122 if (writer == NULL)
2123 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002124
Victor Stinner559bb6a2016-08-22 22:48:54 +02002125 result = _PyObject_CallArg1(writer, unicode);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 if (result == NULL) {
2127 goto error;
2128 } else {
2129 err = 0;
2130 goto finally;
2131 }
Victor Stinner14284c22010-04-23 12:02:30 +00002132
2133error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002135finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 Py_XDECREF(writer);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 Py_XDECREF(result);
2138 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002139}
2140
Victor Stinner79766632010-08-16 17:36:42 +00002141static int
2142sys_pyfile_write(const char *text, PyObject *file)
2143{
2144 PyObject *unicode = NULL;
2145 int err;
2146
2147 if (file == NULL)
2148 return -1;
2149
2150 unicode = PyUnicode_FromString(text);
2151 if (unicode == NULL)
2152 return -1;
2153
2154 err = sys_pyfile_write_unicode(unicode, file);
2155 Py_DECREF(unicode);
2156 return err;
2157}
Guido van Rossuma890e681998-05-12 14:59:24 +00002158
2159/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2160 Adapted from code submitted by Just van Rossum.
2161
2162 PySys_WriteStdout(format, ...)
2163 PySys_WriteStderr(format, ...)
2164
2165 The first function writes to sys.stdout; the second to sys.stderr. When
2166 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002167 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002168
Victor Stinner14284c22010-04-23 12:02:30 +00002169 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002170 signal handlers: they may raise a new exception whereas sys_write()
2171 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002172
Guido van Rossuma890e681998-05-12 14:59:24 +00002173 Both take a printf-style format string as their first argument followed
2174 by a variable length argument list determined by the format string.
2175
2176 *** WARNING ***
2177
2178 The format should limit the total size of the formatted output string to
2179 1000 bytes. In particular, this means that no unrestricted "%s" formats
2180 should occur; these should be limited using "%.<N>s where <N> is a
2181 decimal number calculated so that <N> plus the maximum size of other
2182 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2183 which can print hundreds of digits for very large numbers.
2184
2185 */
2186
2187static void
Victor Stinner09054372013-11-06 22:41:44 +01002188sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002189{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002190 PyObject *file;
2191 PyObject *error_type, *error_value, *error_traceback;
2192 char buffer[1001];
2193 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002196 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002197 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2198 if (sys_pyfile_write(buffer, file) != 0) {
2199 PyErr_Clear();
2200 fputs(buffer, fp);
2201 }
2202 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2203 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002204 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002205 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002206 }
2207 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002208}
2209
2210void
Guido van Rossuma890e681998-05-12 14:59:24 +00002211PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002213 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002214
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002215 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002216 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002217 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002218}
2219
2220void
Guido van Rossuma890e681998-05-12 14:59:24 +00002221PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002223 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002224
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002225 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002226 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002227 va_end(va);
2228}
2229
2230static void
Victor Stinner09054372013-11-06 22:41:44 +01002231sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002232{
2233 PyObject *file, *message;
2234 PyObject *error_type, *error_value, *error_traceback;
2235 char *utf8;
2236
2237 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002238 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002239 message = PyUnicode_FromFormatV(format, va);
2240 if (message != NULL) {
2241 if (sys_pyfile_write_unicode(message, file) != 0) {
2242 PyErr_Clear();
2243 utf8 = _PyUnicode_AsString(message);
2244 if (utf8 != NULL)
2245 fputs(utf8, fp);
2246 }
2247 Py_DECREF(message);
2248 }
2249 PyErr_Restore(error_type, error_value, error_traceback);
2250}
2251
2252void
2253PySys_FormatStdout(const char *format, ...)
2254{
2255 va_list va;
2256
2257 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002258 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002259 va_end(va);
2260}
2261
2262void
2263PySys_FormatStderr(const char *format, ...)
2264{
2265 va_list va;
2266
2267 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002268 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002269 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002270}