blob: 39fe53fb7eeb47eb415e09c091ce0f8c7aa0ad60 [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"
Guido van Rossum3f5da241990-12-20 15:06:42 +000023
Mark Hammond8696ebc2002-10-08 02:44:31 +000024#ifdef MS_WINDOWS
25#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000026#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000027#endif /* MS_WINDOWS */
28
Guido van Rossum9b38a141996-09-11 23:12:24 +000029#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000030extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000031/* A string loaded from the DLL at startup: */
32extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000033#endif
34
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000035#ifdef HAVE_LANGINFO_H
36#include <locale.h>
37#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{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 static char *whatnames[7] = {"call", "exception", "line", "return",
350 "c_call", "c_exception", "c_return"};
351 PyObject *name;
352 int i;
353 for (i = 0; i < 7; ++i) {
354 if (whatstrings[i] == NULL) {
355 name = PyUnicode_InternFromString(whatnames[i]);
356 if (name == NULL)
357 return -1;
358 whatstrings[i] = name;
359 }
360 }
361 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000362}
363
364
365static PyObject *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100366call_trampoline(PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000368{
Victor Stinner41bb43a2013-10-29 01:19:37 +0100369 PyObject *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *whatstr;
371 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000372
Victor Stinner41bb43a2013-10-29 01:19:37 +0100373 args = PyTuple_New(3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (args == NULL)
375 return NULL;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100376 if (PyFrame_FastToLocalsWithError(frame) < 0)
377 return NULL;
378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 Py_INCREF(frame);
380 whatstr = whatstrings[what];
381 Py_INCREF(whatstr);
382 if (arg == NULL)
383 arg = Py_None;
384 Py_INCREF(arg);
385 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
386 PyTuple_SET_ITEM(args, 1, whatstr);
387 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 /* call the Python-level function */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000390 result = PyEval_CallObject(callback, args);
391 PyFrame_LocalsToFast(frame, 1);
392 if (result == NULL)
393 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000394
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000395 /* cleanup */
396 Py_DECREF(args);
397 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000398}
399
400static int
401profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000403{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000404 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000405
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 if (arg == NULL)
407 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100408 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000409 if (result == NULL) {
410 PyEval_SetProfile(NULL, NULL);
411 return -1;
412 }
413 Py_DECREF(result);
414 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000415}
416
417static int
418trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000419 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000420{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 PyObject *callback;
422 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 if (what == PyTrace_CALL)
425 callback = self;
426 else
427 callback = frame->f_trace;
428 if (callback == NULL)
429 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100430 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 if (result == NULL) {
432 PyEval_SetTrace(NULL, NULL);
Serhiy Storchaka505ff752014-02-09 13:33:53 +0200433 Py_CLEAR(frame->f_trace);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 return -1;
435 }
436 if (result != Py_None) {
437 PyObject *temp = frame->f_trace;
438 frame->f_trace = NULL;
439 Py_XDECREF(temp);
440 frame->f_trace = result;
441 }
442 else {
443 Py_DECREF(result);
444 }
445 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000446}
Fred Draked0838392001-06-16 21:02:31 +0000447
Fred Drake8b4d01d2000-05-09 19:57:01 +0000448static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000449sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (trace_init() == -1)
452 return NULL;
453 if (args == Py_None)
454 PyEval_SetTrace(NULL, NULL);
455 else
456 PyEval_SetTrace(trace_trampoline, args);
457 Py_INCREF(Py_None);
458 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000459}
460
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000461PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000462"settrace(function)\n\
463\n\
464Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000465function call. See the debugger chapter in the library manual."
466);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000467
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000468static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000469sys_gettrace(PyObject *self, PyObject *args)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyThreadState *tstate = PyThreadState_GET();
472 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (temp == NULL)
475 temp = Py_None;
476 Py_INCREF(temp);
477 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000478}
479
480PyDoc_STRVAR(gettrace_doc,
481"gettrace()\n\
482\n\
483Return the global debug tracing function set with sys.settrace.\n\
484See the debugger chapter in the library manual."
485);
486
487static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000488sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000489{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 if (trace_init() == -1)
491 return NULL;
492 if (args == Py_None)
493 PyEval_SetProfile(NULL, NULL);
494 else
495 PyEval_SetProfile(profile_trampoline, args);
496 Py_INCREF(Py_None);
497 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000498}
499
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000500PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000501"setprofile(function)\n\
502\n\
503Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000504and return. See the profiler chapter in the library manual."
505);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000506
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000507static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000508sys_getprofile(PyObject *self, PyObject *args)
509{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000510 PyThreadState *tstate = PyThreadState_GET();
511 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000512
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (temp == NULL)
514 temp = Py_None;
515 Py_INCREF(temp);
516 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000517}
518
519PyDoc_STRVAR(getprofile_doc,
520"getprofile()\n\
521\n\
522Return the profiling function set with sys.setprofile.\n\
523See the profiler chapter in the library manual."
524);
525
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000526static int _check_interval = 100;
527
Christian Heimes9bd667a2008-01-20 15:14:11 +0000528static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000529sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000530{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000531 if (PyErr_WarnEx(PyExc_DeprecationWarning,
532 "sys.getcheckinterval() and sys.setcheckinterval() "
533 "are deprecated. Use sys.setswitchinterval() "
534 "instead.", 1) < 0)
535 return NULL;
536 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
537 return NULL;
538 Py_INCREF(Py_None);
539 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000540}
541
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000542PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000543"setcheckinterval(n)\n\
544\n\
545Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000546n instructions. This also affects how often thread switches occur."
547);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000548
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000549static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000550sys_getcheckinterval(PyObject *self, PyObject *args)
551{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000552 if (PyErr_WarnEx(PyExc_DeprecationWarning,
553 "sys.getcheckinterval() and sys.setcheckinterval() "
554 "are deprecated. Use sys.getswitchinterval() "
555 "instead.", 1) < 0)
556 return NULL;
557 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000558}
559
560PyDoc_STRVAR(getcheckinterval_doc,
561"getcheckinterval() -> current check interval; see setcheckinterval()."
562);
563
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000564#ifdef WITH_THREAD
565static PyObject *
566sys_setswitchinterval(PyObject *self, PyObject *args)
567{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000568 double d;
569 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
570 return NULL;
571 if (d <= 0.0) {
572 PyErr_SetString(PyExc_ValueError,
573 "switch interval must be strictly positive");
574 return NULL;
575 }
576 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
577 Py_INCREF(Py_None);
578 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000579}
580
581PyDoc_STRVAR(setswitchinterval_doc,
582"setswitchinterval(n)\n\
583\n\
584Set the ideal thread switching delay inside the Python interpreter\n\
585The actual frequency of switching threads can be lower if the\n\
586interpreter executes long sequences of uninterruptible code\n\
587(this is implementation-specific and workload-dependent).\n\
588\n\
589The parameter must represent the desired switching delay in seconds\n\
590A typical value is 0.005 (5 milliseconds)."
591);
592
593static PyObject *
594sys_getswitchinterval(PyObject *self, PyObject *args)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000597}
598
599PyDoc_STRVAR(getswitchinterval_doc,
600"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
601);
602
603#endif /* WITH_THREAD */
604
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000605#ifdef WITH_TSC
606static PyObject *
607sys_settscdump(PyObject *self, PyObject *args)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 int bool;
610 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
613 return NULL;
614 if (bool)
615 tstate->interp->tscdump = 1;
616 else
617 tstate->interp->tscdump = 0;
618 Py_INCREF(Py_None);
619 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000620
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000621}
622
Tim Peters216b78b2006-01-06 02:40:53 +0000623PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000624"settscdump(bool)\n\
625\n\
626If true, tell the Python interpreter to dump VM measurements to\n\
627stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000628processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000629);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000630#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000631
Tim Peterse5e065b2003-07-06 18:36:54 +0000632static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000633sys_setrecursionlimit(PyObject *self, PyObject *args)
634{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000635 int new_limit;
636 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
637 return NULL;
638 if (new_limit <= 0) {
639 PyErr_SetString(PyExc_ValueError,
640 "recursion limit must be positive");
641 return NULL;
642 }
643 Py_SetRecursionLimit(new_limit);
644 Py_INCREF(Py_None);
645 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000646}
647
Mark Dickinsondc787d22010-05-23 13:33:13 +0000648static PyTypeObject Hash_InfoType;
649
650PyDoc_STRVAR(hash_info_doc,
651"hash_info\n\
652\n\
653A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100654hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000655
656static PyStructSequence_Field hash_info_fields[] = {
657 {"width", "width of the type used for hashing, in bits"},
658 {"modulus", "prime number giving the modulus on which the hash "
659 "function is based"},
660 {"inf", "value to be used for hash of a positive infinity"},
661 {"nan", "value to be used for hash of a nan"},
662 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100663 {"algorithm", "name of the algorithm for hashing of str, bytes and "
664 "memoryviews"},
665 {"hash_bits", "internal output size of hash algorithm"},
666 {"seed_bits", "seed size of hash algorithm"},
667 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000668 {NULL, NULL}
669};
670
671static PyStructSequence_Desc hash_info_desc = {
672 "sys.hash_info",
673 hash_info_doc,
674 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100675 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000676};
677
Matthias Klosed885e952010-07-06 10:53:30 +0000678static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000679get_hash_info(void)
680{
681 PyObject *hash_info;
682 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100683 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000684 hash_info = PyStructSequence_New(&Hash_InfoType);
685 if (hash_info == NULL)
686 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100687 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000688 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000689 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000690 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000691 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000692 PyStructSequence_SET_ITEM(hash_info, field++,
693 PyLong_FromLong(_PyHASH_INF));
694 PyStructSequence_SET_ITEM(hash_info, field++,
695 PyLong_FromLong(_PyHASH_NAN));
696 PyStructSequence_SET_ITEM(hash_info, field++,
697 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100698 PyStructSequence_SET_ITEM(hash_info, field++,
699 PyUnicode_FromString(hashfunc->name));
700 PyStructSequence_SET_ITEM(hash_info, field++,
701 PyLong_FromLong(hashfunc->hash_bits));
702 PyStructSequence_SET_ITEM(hash_info, field++,
703 PyLong_FromLong(hashfunc->seed_bits));
704 PyStructSequence_SET_ITEM(hash_info, field++,
705 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000706 if (PyErr_Occurred()) {
707 Py_CLEAR(hash_info);
708 return NULL;
709 }
710 return hash_info;
711}
712
713
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000714PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000715"setrecursionlimit(n)\n\
716\n\
717Set the maximum depth of the Python interpreter stack to n. This\n\
718limit prevents infinite recursion from causing an overflow of the C\n\
719stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000720dependent."
721);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000722
723static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000724sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000727}
728
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000729PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000730"getrecursionlimit()\n\
731\n\
732Return the current value of the recursion limit, the maximum depth\n\
733of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000734recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000735);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000736
Mark Hammond8696ebc2002-10-08 02:44:31 +0000737#ifdef MS_WINDOWS
738PyDoc_STRVAR(getwindowsversion_doc,
739"getwindowsversion()\n\
740\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000741Return information about the running version of Windows as a named tuple.\n\
742The members are named: major, minor, build, platform, service_pack,\n\
743service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200744backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000745All elements are numbers, except service_pack which is a string. Platform\n\
746may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
7473 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
748controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000749);
750
Eric Smithf7bb5782010-01-27 00:44:57 +0000751static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
752
753static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 {"major", "Major version number"},
755 {"minor", "Minor version number"},
756 {"build", "Build number"},
757 {"platform", "Operating system platform"},
758 {"service_pack", "Latest Service Pack installed on the system"},
759 {"service_pack_major", "Service Pack major version number"},
760 {"service_pack_minor", "Service Pack minor version number"},
761 {"suite_mask", "Bit mask identifying available product suites"},
762 {"product_type", "System product type"},
763 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000764};
765
766static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000767 "sys.getwindowsversion", /* name */
768 getwindowsversion_doc, /* doc */
769 windows_version_fields, /* fields */
770 5 /* For backward compatibility,
771 only the first 5 items are accessible
772 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000773};
774
Mark Hammond8696ebc2002-10-08 02:44:31 +0000775static PyObject *
776sys_getwindowsversion(PyObject *self)
777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000778 PyObject *version;
779 int pos = 0;
780 OSVERSIONINFOEX ver;
781 ver.dwOSVersionInfoSize = sizeof(ver);
782 if (!GetVersionEx((OSVERSIONINFO*) &ver))
783 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 version = PyStructSequence_New(&WindowsVersionType);
786 if (version == NULL)
787 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000788
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000789 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
790 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
791 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
792 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
793 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
794 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
795 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
796 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
797 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000798
Serhiy Storchaka48d761e2013-12-17 15:11:24 +0200799 if (PyErr_Occurred()) {
800 Py_DECREF(version);
801 return NULL;
802 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000803 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000804}
805
806#endif /* MS_WINDOWS */
807
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000808#ifdef HAVE_DLOPEN
809static PyObject *
810sys_setdlopenflags(PyObject *self, PyObject *args)
811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 int new_val;
813 PyThreadState *tstate = PyThreadState_GET();
814 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
815 return NULL;
816 if (!tstate)
817 return NULL;
818 tstate->interp->dlopenflags = new_val;
819 Py_INCREF(Py_None);
820 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000821}
822
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000823PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000824"setdlopenflags(n) -> None\n\
825\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000826Set the flags used by the interpreter for dlopen calls, such as when the\n\
827interpreter loads extension modules. Among other things, this will enable\n\
828a lazy resolving of symbols when importing a module, if called as\n\
829sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400830sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100831can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000832
833static PyObject *
834sys_getdlopenflags(PyObject *self, PyObject *args)
835{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000836 PyThreadState *tstate = PyThreadState_GET();
837 if (!tstate)
838 return NULL;
839 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000840}
841
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000842PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000843"getdlopenflags() -> int\n\
844\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000845Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400846The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000847
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000848#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000849
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000850#ifdef USE_MALLOPT
851/* Link with -lmalloc (or -lmpc) on an SGI */
852#include <malloc.h>
853
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000854static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000855sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000856{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000857 int flag;
858 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
859 return NULL;
860 mallopt(M_DEBUG, flag);
861 Py_INCREF(Py_None);
862 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000863}
864#endif /* USE_MALLOPT */
865
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300866size_t
867_PySys_GetSizeOf(PyObject *o)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000869 PyObject *res = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *method;
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300871 size_t size;
Benjamin Petersona5758c02009-05-09 18:15:04 +0000872
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000873 /* Make sure the type is initialized. float gets initialized late */
874 if (PyType_Ready(Py_TYPE(o)) < 0)
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300875 return (size_t)-1;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000876
Benjamin Petersonce798522012-01-22 11:24:29 -0500877 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (method == NULL) {
879 if (!PyErr_Occurred())
880 PyErr_Format(PyExc_TypeError,
881 "Type %.100s doesn't define __sizeof__",
882 Py_TYPE(o)->tp_name);
883 }
884 else {
885 res = PyObject_CallFunctionObjArgs(method, NULL);
886 Py_DECREF(method);
887 }
888
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300889 if (res == NULL)
890 return (size_t)-1;
891
892 size = PyLong_AsSize_t(res);
893 Py_DECREF(res);
894 if (size == (size_t)-1 && PyErr_Occurred())
895 return (size_t)-1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896
897 /* add gc_head size */
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300898 if (PyObject_IS_GC(o))
899 size += sizeof(PyGC_Head);
900 return size;
901}
902
903static PyObject *
904sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
905{
906 static char *kwlist[] = {"object", "default", 0};
907 size_t size;
908 PyObject *o, *dflt = NULL;
909
910 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
911 kwlist, &o, &dflt))
912 return NULL;
913
914 size = _PySys_GetSizeOf(o);
915
916 if (size == (size_t)-1 && PyErr_Occurred()) {
917 /* Has a default value been given */
918 if (dflt != NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
919 PyErr_Clear();
920 Py_INCREF(dflt);
921 return dflt;
922 }
923 else
924 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 }
Serhiy Storchaka547d3bc2014-08-14 22:21:18 +0300926
927 return PyLong_FromSize_t(size);
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000928}
929
930PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000931"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000932\n\
933Return the size of object in bytes.");
934
935static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000936sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000939}
940
Tim Peters4be93d02002-07-07 19:59:50 +0000941#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000942static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000943sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000944{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000945 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000946}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000947#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000948
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000949PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000950"getrefcount(object) -> integer\n\
951\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000952Return the reference count of object. The count returned is generally\n\
953one higher than you might expect, because it includes the (temporary)\n\
954reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000955);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000956
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100957static PyObject *
958sys_getallocatedblocks(PyObject *self)
959{
960 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
961}
962
963PyDoc_STRVAR(getallocatedblocks_doc,
964"getallocatedblocks() -> integer\n\
965\n\
966Return the number of memory blocks currently allocated, regardless of their\n\
967size."
968);
969
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000970#ifdef COUNT_ALLOCS
971static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000972sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000973{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000975
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000976 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000977}
978#endif
979
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000980PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000981"_getframe([depth]) -> frameobject\n\
982\n\
983Return a frame object from the call stack. If optional integer depth is\n\
984given, return the frame object that many calls below the top of the stack.\n\
985If that is deeper than the call stack, ValueError is raised. The default\n\
986for depth is zero, returning the frame at the top of the call stack.\n\
987\n\
988This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000989purposes only."
990);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000991
992static PyObject *
993sys_getframe(PyObject *self, PyObject *args)
994{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000995 PyFrameObject *f = PyThreadState_GET()->frame;
996 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000997
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
999 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001000
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 while (depth > 0 && f != NULL) {
1002 f = f->f_back;
1003 --depth;
1004 }
1005 if (f == NULL) {
1006 PyErr_SetString(PyExc_ValueError,
1007 "call stack is not deep enough");
1008 return NULL;
1009 }
1010 Py_INCREF(f);
1011 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001012}
1013
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001014PyDoc_STRVAR(current_frames_doc,
1015"_current_frames() -> dictionary\n\
1016\n\
1017Return a dictionary mapping each current thread T's thread id to T's\n\
1018current stack frame.\n\
1019\n\
1020This function should be used for specialized purposes only."
1021);
1022
1023static PyObject *
1024sys_current_frames(PyObject *self, PyObject *noargs)
1025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001027}
1028
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001029PyDoc_STRVAR(call_tracing_doc,
1030"call_tracing(func, args) -> object\n\
1031\n\
1032Call func(*args), while tracing is enabled. The tracing state is\n\
1033saved, and restored afterwards. This is intended to be called from\n\
1034a debugger from a checkpoint, to recursively debug some other code."
1035);
1036
1037static PyObject *
1038sys_call_tracing(PyObject *self, PyObject *args)
1039{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001040 PyObject *func, *funcargs;
1041 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1042 return NULL;
1043 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001044}
1045
Jeremy Hylton985eba52003-02-05 23:13:00 +00001046PyDoc_STRVAR(callstats_doc,
1047"callstats() -> tuple of integers\n\
1048\n\
1049Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1050when Python was built. Otherwise, return None.\n\
1051\n\
1052When enabled, this function returns detailed, implementation-specific\n\
1053details about the number of function calls executed. The return value is\n\
1054a 11-tuple where the entries in the tuple are counts of:\n\
10550. all function calls\n\
10561. calls to PyFunction_Type objects\n\
10572. PyFunction calls that do not create an argument tuple\n\
10583. PyFunction calls that do not create an argument tuple\n\
1059 and bypass PyEval_EvalCodeEx()\n\
10604. PyMethod calls\n\
10615. PyMethod calls on bound methods\n\
10626. PyType calls\n\
10637. PyCFunction calls\n\
10648. generator calls\n\
10659. All other calls\n\
106610. Number of stack pops performed by call_function()"
1067);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001068
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001069#ifdef __cplusplus
1070extern "C" {
1071#endif
1072
David Malcolm49526f42012-06-22 14:55:41 -04001073static PyObject *
1074sys_debugmallocstats(PyObject *self, PyObject *args)
1075{
1076#ifdef WITH_PYMALLOC
1077 _PyObject_DebugMallocStats(stderr);
1078 fputc('\n', stderr);
1079#endif
1080 _PyObject_DebugTypeStats(stderr);
1081
1082 Py_RETURN_NONE;
1083}
1084PyDoc_STRVAR(debugmallocstats_doc,
1085"_debugmallocstats()\n\
1086\n\
1087Print summary info to stderr about the state of\n\
1088pymalloc's structures.\n\
1089\n\
1090In Py_DEBUG mode, also perform some expensive internal consistency\n\
1091checks.\n\
1092");
1093
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001094#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001095/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001096extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001097#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001098
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001099#ifdef DYNAMIC_EXECUTION_PROFILE
1100/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001101extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001102#endif
1103
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001104#ifdef __cplusplus
1105}
1106#endif
1107
Christian Heimes15ebc882008-02-04 18:48:49 +00001108static PyObject *
1109sys_clear_type_cache(PyObject* self, PyObject* args)
1110{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001111 PyType_ClearCache();
1112 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001113}
1114
1115PyDoc_STRVAR(sys_clear_type_cache__doc__,
1116"_clear_type_cache() -> None\n\
1117Clear the internal type lookup cache.");
1118
1119
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001120static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 /* Might as well keep this in alphabetic order */
1122 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1123 callstats_doc},
1124 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1125 sys_clear_type_cache__doc__},
1126 {"_current_frames", sys_current_frames, METH_NOARGS,
1127 current_frames_doc},
1128 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1129 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1130 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1131 {"exit", sys_exit, METH_VARARGS, exit_doc},
1132 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1133 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001134#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1136 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001137#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001138 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1139 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001140#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001142#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001143#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001145#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001146 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1147 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001148#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001150#endif
1151#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001152 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001153#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1155 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1156 getrecursionlimit_doc},
1157 {"getsizeof", (PyCFunction)sys_getsizeof,
1158 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1159 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001160#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1162 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001163#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001165#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001167#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1169 setcheckinterval_doc},
1170 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1171 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001172#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001173 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1174 setswitchinterval_doc},
1175 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1176 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001177#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001178#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001179 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1180 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001181#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1183 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1184 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1185 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001186#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001188#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 {"settrace", sys_settrace, METH_O, settrace_doc},
1190 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1191 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
Victor Stinnered0b87d2013-12-19 17:16:42 +01001192 {"_debugmallocstats", sys_debugmallocstats, METH_NOARGS,
David Malcolm49526f42012-06-22 14:55:41 -04001193 debugmallocstats_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001194 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001195};
1196
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001197static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001198list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject *list = PyList_New(0);
1201 int i;
1202 if (list == NULL)
1203 return NULL;
1204 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1205 PyObject *name = PyUnicode_FromString(
1206 PyImport_Inittab[i].name);
1207 if (name == NULL)
1208 break;
1209 PyList_Append(list, name);
1210 Py_DECREF(name);
1211 }
1212 if (PyList_Sort(list) != 0) {
1213 Py_DECREF(list);
1214 list = NULL;
1215 }
1216 if (list) {
1217 PyObject *v = PyList_AsTuple(list);
1218 Py_DECREF(list);
1219 list = v;
1220 }
1221 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001222}
1223
Guido van Rossum23fff912000-12-15 22:02:05 +00001224static PyObject *warnoptions = NULL;
1225
1226void
1227PySys_ResetWarnOptions(void)
1228{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001229 if (warnoptions == NULL || !PyList_Check(warnoptions))
1230 return;
1231 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001232}
1233
1234void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001235PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001236{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1238 Py_XDECREF(warnoptions);
1239 warnoptions = PyList_New(0);
1240 if (warnoptions == NULL)
1241 return;
1242 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001243 PyList_Append(warnoptions, unicode);
1244}
1245
1246void
1247PySys_AddWarnOption(const wchar_t *s)
1248{
1249 PyObject *unicode;
1250 unicode = PyUnicode_FromWideChar(s, -1);
1251 if (unicode == NULL)
1252 return;
1253 PySys_AddWarnOptionUnicode(unicode);
1254 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001255}
1256
Christian Heimes33fe8092008-04-13 13:53:33 +00001257int
1258PySys_HasWarnOptions(void)
1259{
1260 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1261}
1262
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001263static PyObject *xoptions = NULL;
1264
1265static PyObject *
1266get_xoptions(void)
1267{
1268 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1269 Py_XDECREF(xoptions);
1270 xoptions = PyDict_New();
1271 }
1272 return xoptions;
1273}
1274
1275void
1276PySys_AddXOption(const wchar_t *s)
1277{
1278 PyObject *opts;
1279 PyObject *name = NULL, *value = NULL;
1280 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001281
1282 opts = get_xoptions();
1283 if (opts == NULL)
1284 goto error;
1285
1286 name_end = wcschr(s, L'=');
1287 if (!name_end) {
1288 name = PyUnicode_FromWideChar(s, -1);
1289 value = Py_True;
1290 Py_INCREF(value);
1291 }
1292 else {
1293 name = PyUnicode_FromWideChar(s, name_end - s);
1294 value = PyUnicode_FromWideChar(name_end + 1, -1);
1295 }
1296 if (name == NULL || value == NULL)
1297 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001298 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001299 Py_DECREF(name);
1300 Py_DECREF(value);
1301 return;
1302
1303error:
1304 Py_XDECREF(name);
1305 Py_XDECREF(value);
1306 /* No return value, therefore clear error state if possible */
1307 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1308 PyErr_Clear();
1309}
1310
1311PyObject *
1312PySys_GetXOptions(void)
1313{
1314 return get_xoptions();
1315}
1316
Guido van Rossum40552d01998-08-06 03:34:39 +00001317/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1318 Two literals concatenated works just fine. If you have a K&R compiler
1319 or other abomination that however *does* understand longer strings,
1320 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001321PyDoc_VAR(sys_doc) =
1322PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001323"This module provides access to some objects used or maintained by the\n\
1324interpreter and to functions that interact strongly with the interpreter.\n\
1325\n\
1326Dynamic objects:\n\
1327\n\
1328argv -- command line arguments; argv[0] is the script pathname if known\n\
1329path -- module search path; path[0] is the script directory, else ''\n\
1330modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001331\n\
1332displayhook -- called to show results in an interactive session\n\
1333excepthook -- called to handle any uncaught exception other than SystemExit\n\
1334 To customize printing in an interactive session or to install a custom\n\
1335 top-level exception handler, assign other functions to replace these.\n\
1336\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001337stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001338stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001339stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001340 By assigning other file objects (or objects that behave like files)\n\
1341 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001342\n\
1343last_type -- type of last uncaught exception\n\
1344last_value -- value of last uncaught exception\n\
1345last_traceback -- traceback of last uncaught exception\n\
1346 These three are only available in an interactive session after a\n\
1347 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001348"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001349)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001350/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001351PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001352"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001353Static objects:\n\
1354\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001355builtin_module_names -- tuple of module names built into this interpreter\n\
1356copyright -- copyright notice pertaining to this interpreter\n\
1357exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001358executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001359float_info -- a struct sequence with information about the float implementation.\n\
1360float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001361hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001362hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001363implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001364int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001365maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001366maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001367platform -- platform identifier\n\
1368prefix -- prefix used to find the Python library\n\
1369thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001370version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001371version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001372"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001373)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001374#ifdef MS_WINDOWS
1375/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001376PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001377"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001378winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001379"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001380)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001381#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001382PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001383"__stdin__ -- the original stdin; don't touch!\n\
1384__stdout__ -- the original stdout; don't touch!\n\
1385__stderr__ -- the original stderr; don't touch!\n\
1386__displayhook__ -- the original displayhook; don't touch!\n\
1387__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001388\n\
1389Functions:\n\
1390\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001391displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001392excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001393exc_info() -- return thread-safe information about the current exception\n\
1394exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001395getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001396getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001397getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001398getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001399getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001400gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001401setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001402setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001403setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001404setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001405settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001406"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001407)
Fred Drakeccede592000-08-14 20:59:57 +00001408/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001409
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001410
1411PyDoc_STRVAR(flags__doc__,
1412"sys.flags\n\
1413\n\
1414Flags provided through command line arguments or environment vars.");
1415
1416static PyTypeObject FlagsType;
1417
1418static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 {"inspect", "-i"},
1421 {"interactive", "-i"},
1422 {"optimize", "-O or -OO"},
1423 {"dont_write_bytecode", "-B"},
1424 {"no_user_site", "-s"},
1425 {"no_site", "-S"},
1426 {"ignore_environment", "-E"},
1427 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 /* {"unbuffered", "-u"}, */
1429 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001430 {"bytes_warning", "-b"},
1431 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001432 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001433 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001434 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001435};
1436
1437static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 "sys.flags", /* name */
1439 flags__doc__, /* doc */
1440 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001441 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001442};
1443
1444static PyObject*
1445make_flags(void)
1446{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001447 int pos = 0;
1448 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 seq = PyStructSequence_New(&FlagsType);
1451 if (seq == NULL)
1452 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001453
1454#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001455 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001457 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 SetFlag(Py_InspectFlag);
1459 SetFlag(Py_InteractiveFlag);
1460 SetFlag(Py_OptimizeFlag);
1461 SetFlag(Py_DontWriteBytecodeFlag);
1462 SetFlag(Py_NoUserSiteDirectory);
1463 SetFlag(Py_NoSiteFlag);
1464 SetFlag(Py_IgnoreEnvironmentFlag);
1465 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001466 /* SetFlag(saw_unbuffered_flag); */
1467 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001468 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001469 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001470 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001471 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001472#undef SetFlag
1473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 if (PyErr_Occurred()) {
Serhiy Storchaka87a854d2013-12-17 14:59:42 +02001475 Py_DECREF(seq);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001476 return NULL;
1477 }
1478 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001479}
1480
Eric Smith0e5b5622009-02-06 01:32:42 +00001481PyDoc_STRVAR(version_info__doc__,
1482"sys.version_info\n\
1483\n\
1484Version information as a named tuple.");
1485
1486static PyTypeObject VersionInfoType;
1487
1488static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 {"major", "Major release number"},
1490 {"minor", "Minor release number"},
1491 {"micro", "Patch release number"},
1492 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1493 {"serial", "Serial release number"},
1494 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001495};
1496
1497static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 "sys.version_info", /* name */
1499 version_info__doc__, /* doc */
1500 version_info_fields, /* fields */
1501 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001502};
1503
1504static PyObject *
1505make_version_info(void)
1506{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 PyObject *version_info;
1508 char *s;
1509 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001510
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001511 version_info = PyStructSequence_New(&VersionInfoType);
1512 if (version_info == NULL) {
1513 return NULL;
1514 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 /*
1517 * These release level checks are mutually exclusive and cover
1518 * the field, so don't get too fancy with the pre-processor!
1519 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001520#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001522#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001524#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001526#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001528#endif
1529
1530#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001532#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001533 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 SetIntItem(PY_MAJOR_VERSION);
1536 SetIntItem(PY_MINOR_VERSION);
1537 SetIntItem(PY_MICRO_VERSION);
1538 SetStrItem(s);
1539 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001540#undef SetIntItem
1541#undef SetStrItem
1542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 if (PyErr_Occurred()) {
1544 Py_CLEAR(version_info);
1545 return NULL;
1546 }
1547 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001548}
1549
Brett Cannon3adc7b72012-07-09 14:22:12 -04001550/* sys.implementation values */
1551#define NAME "cpython"
1552const char *_PySys_ImplName = NAME;
1553#define QUOTE(arg) #arg
1554#define STRIFY(name) QUOTE(name)
1555#define MAJOR STRIFY(PY_MAJOR_VERSION)
1556#define MINOR STRIFY(PY_MINOR_VERSION)
Ned Deily529ea5d2014-06-30 23:31:14 -07001557#define TAG NAME "-" MAJOR MINOR
Brett Cannon3adc7b72012-07-09 14:22:12 -04001558const char *_PySys_ImplCacheTag = TAG;
1559#undef NAME
1560#undef QUOTE
1561#undef STRIFY
1562#undef MAJOR
1563#undef MINOR
1564#undef TAG
1565
Barry Warsaw409da152012-06-03 16:18:47 -04001566static PyObject *
1567make_impl_info(PyObject *version_info)
1568{
1569 int res;
1570 PyObject *impl_info, *value, *ns;
1571
1572 impl_info = PyDict_New();
1573 if (impl_info == NULL)
1574 return NULL;
1575
1576 /* populate the dict */
1577
Brett Cannon3adc7b72012-07-09 14:22:12 -04001578 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001579 if (value == NULL)
1580 goto error;
1581 res = PyDict_SetItemString(impl_info, "name", value);
1582 Py_DECREF(value);
1583 if (res < 0)
1584 goto error;
1585
Brett Cannon3adc7b72012-07-09 14:22:12 -04001586 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001587 if (value == NULL)
1588 goto error;
1589 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1590 Py_DECREF(value);
1591 if (res < 0)
1592 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001593
1594 res = PyDict_SetItemString(impl_info, "version", version_info);
1595 if (res < 0)
1596 goto error;
1597
1598 value = PyLong_FromLong(PY_VERSION_HEX);
1599 if (value == NULL)
1600 goto error;
1601 res = PyDict_SetItemString(impl_info, "hexversion", value);
1602 Py_DECREF(value);
1603 if (res < 0)
1604 goto error;
1605
1606 /* dict ready */
1607
1608 ns = _PyNamespace_New(impl_info);
1609 Py_DECREF(impl_info);
1610 return ns;
1611
1612error:
1613 Py_CLEAR(impl_info);
1614 return NULL;
1615}
1616
Martin v. Löwis1a214512008-06-11 05:26:20 +00001617static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 PyModuleDef_HEAD_INIT,
1619 "sys",
1620 sys_doc,
1621 -1, /* multiple "initialization" just copies the module dict. */
1622 sys_methods,
1623 NULL,
1624 NULL,
1625 NULL,
1626 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001627};
1628
Guido van Rossum25ce5661997-08-02 03:10:38 +00001629PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001630_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001631{
Victor Stinner58049602013-07-22 22:40:00 +02001632 PyObject *m, *sysdict, *version_info;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001633 int res;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001634
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001635 m = PyModule_Create(&sysmodule);
1636 if (m == NULL)
1637 return NULL;
1638 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001639#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001640 do { \
Victor Stinner58049602013-07-22 22:40:00 +02001641 PyObject *v = (value); \
1642 if (v == NULL) \
1643 return NULL; \
1644 res = PyDict_SetItemString(sysdict, key, v); \
1645 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001646 return NULL; \
1647 } \
1648 } while (0)
1649#define SET_SYS_FROM_STRING(key, value) \
1650 do { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001651 PyObject *v = (value); \
1652 if (v == NULL) \
1653 return NULL; \
1654 res = PyDict_SetItemString(sysdict, key, v); \
1655 Py_DECREF(v); \
1656 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001657 return NULL; \
1658 } \
1659 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001660
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 /* Check that stdin is not a directory
1662 Using shell redirection, you can redirect stdin to a directory,
1663 crashing the Python interpreter. Catch this common mistake here
1664 and output a useful error message. Note that under MS Windows,
1665 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001666#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 {
1668 struct stat sb;
1669 if (fstat(fileno(stdin), &sb) == 0 &&
1670 S_ISDIR(sb.st_mode)) {
1671 /* There's nothing more we can do. */
1672 /* Py_FatalError() will core dump, so just exit. */
1673 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1674 exit(EXIT_FAILURE);
1675 }
1676 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001677#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001678
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001679 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001680
Victor Stinner8fea2522013-10-27 17:15:42 +01001681 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1682 PyDict_GetItemString(sysdict, "displayhook"));
1683 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1684 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 SET_SYS_FROM_STRING("version",
1686 PyUnicode_FromString(Py_GetVersion()));
1687 SET_SYS_FROM_STRING("hexversion",
1688 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001689 SET_SYS_FROM_STRING("_mercurial",
1690 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1691 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 SET_SYS_FROM_STRING("dont_write_bytecode",
1693 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1694 SET_SYS_FROM_STRING("api_version",
1695 PyLong_FromLong(PYTHON_API_VERSION));
1696 SET_SYS_FROM_STRING("copyright",
1697 PyUnicode_FromString(Py_GetCopyright()));
1698 SET_SYS_FROM_STRING("platform",
1699 PyUnicode_FromString(Py_GetPlatform()));
1700 SET_SYS_FROM_STRING("executable",
1701 PyUnicode_FromWideChar(
1702 Py_GetProgramFullPath(), -1));
1703 SET_SYS_FROM_STRING("prefix",
1704 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1705 SET_SYS_FROM_STRING("exec_prefix",
1706 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001707 SET_SYS_FROM_STRING("base_prefix",
1708 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1709 SET_SYS_FROM_STRING("base_exec_prefix",
1710 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 SET_SYS_FROM_STRING("maxsize",
1712 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1713 SET_SYS_FROM_STRING("float_info",
1714 PyFloat_GetInfo());
1715 SET_SYS_FROM_STRING("int_info",
1716 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001717 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001718 if (Hash_InfoType.tp_name == NULL) {
1719 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1720 return NULL;
1721 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001722 SET_SYS_FROM_STRING("hash_info",
1723 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001725 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001726 SET_SYS_FROM_STRING("builtin_module_names",
1727 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001728#if PY_BIG_ENDIAN
1729 SET_SYS_FROM_STRING("byteorder",
1730 PyUnicode_FromString("big"));
1731#else
1732 SET_SYS_FROM_STRING("byteorder",
1733 PyUnicode_FromString("little"));
1734#endif
Fred Drake099325e2000-08-14 15:47:03 +00001735
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001736#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 SET_SYS_FROM_STRING("dllhandle",
1738 PyLong_FromVoidPtr(PyWin_DLLhModule));
1739 SET_SYS_FROM_STRING("winver",
1740 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001741#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001742#ifdef ABIFLAGS
1743 SET_SYS_FROM_STRING("abiflags",
1744 PyUnicode_FromString(ABIFLAGS));
1745#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001746 if (warnoptions == NULL) {
1747 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02001748 if (warnoptions == NULL)
1749 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001750 }
1751 else {
1752 Py_INCREF(warnoptions);
1753 }
Victor Stinner8fea2522013-10-27 17:15:42 +01001754 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00001755
Victor Stinner8fea2522013-10-27 17:15:42 +01001756 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001757
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001758 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001759 if (VersionInfoType.tp_name == NULL) {
1760 if (PyStructSequence_InitType2(&VersionInfoType,
1761 &version_info_desc) < 0)
1762 return NULL;
1763 }
Barry Warsaw409da152012-06-03 16:18:47 -04001764 version_info = make_version_info();
1765 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* prevent user from creating new instances */
1767 VersionInfoType.tp_init = NULL;
1768 VersionInfoType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001769 res = PyDict_DelItemString(VersionInfoType.tp_dict, "__new__");
1770 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1771 PyErr_Clear();
Eric Smith0e5b5622009-02-06 01:32:42 +00001772
Barry Warsaw409da152012-06-03 16:18:47 -04001773 /* implementation */
1774 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001777 if (FlagsType.tp_name == 0) {
1778 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
1779 return NULL;
1780 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001781 SET_SYS_FROM_STRING("flags", make_flags());
1782 /* prevent user from creating new instances */
1783 FlagsType.tp_init = NULL;
1784 FlagsType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001785 res = PyDict_DelItemString(FlagsType.tp_dict, "__new__");
1786 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1787 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00001788
1789#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* getwindowsversion */
1791 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02001792 if (PyStructSequence_InitType2(&WindowsVersionType,
1793 &windows_version_desc) < 0)
1794 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 /* prevent user from creating new instances */
1796 WindowsVersionType.tp_init = NULL;
1797 WindowsVersionType.tp_new = NULL;
Antoine Pitrou871dfc42014-04-28 13:07:06 +02001798 res = PyDict_DelItemString(WindowsVersionType.tp_dict, "__new__");
1799 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1800 PyErr_Clear();
Eric Smithf7bb5782010-01-27 00:44:57 +00001801#endif
1802
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001803 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001804#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 SET_SYS_FROM_STRING("float_repr_style",
1806 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001807#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 SET_SYS_FROM_STRING("float_repr_style",
1809 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001810#endif
1811
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001812#ifdef WITH_THREAD
1813 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1814#endif
1815
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001816#undef SET_SYS_FROM_STRING
Benjamin Peterson93813432014-03-28 18:52:45 -04001817#undef SET_SYS_FROM_STRING_BORROW
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 if (PyErr_Occurred())
1819 return NULL;
1820 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001821}
1822
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001823static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001824makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001825{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 int i, n;
1827 const wchar_t *p;
1828 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001830 n = 1;
1831 p = path;
1832 while ((p = wcschr(p, delim)) != NULL) {
1833 n++;
1834 p++;
1835 }
1836 v = PyList_New(n);
1837 if (v == NULL)
1838 return NULL;
1839 for (i = 0; ; i++) {
1840 p = wcschr(path, delim);
1841 if (p == NULL)
1842 p = path + wcslen(path); /* End of string */
1843 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1844 if (w == NULL) {
1845 Py_DECREF(v);
1846 return NULL;
1847 }
1848 PyList_SetItem(v, i, w);
1849 if (*p == '\0')
1850 break;
1851 path = p+1;
1852 }
1853 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001854}
1855
1856void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001857PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001858{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 PyObject *v;
1860 if ((v = makepathobject(path, DELIM)) == NULL)
1861 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01001862 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001863 Py_FatalError("can't assign sys.path");
1864 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001865}
1866
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001867static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001868makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 PyObject *av;
1871 if (argc <= 0 || argv == NULL) {
1872 /* Ensure at least one (empty) argument is seen */
1873 static wchar_t *empty_argv[1] = {L""};
1874 argv = empty_argv;
1875 argc = 1;
1876 }
1877 av = PyList_New(argc);
1878 if (av != NULL) {
1879 int i;
1880 for (i = 0; i < argc; i++) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 if (v == NULL) {
1883 Py_DECREF(av);
1884 av = NULL;
1885 break;
1886 }
1887 PyList_SetItem(av, i, v);
1888 }
1889 }
1890 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001891}
1892
Nick Coghland26c18a2010-08-17 13:06:11 +00001893#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1894 (argc > 0 && argv0 != NULL && \
1895 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001896
1897static void
1898sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001899{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001900 wchar_t *argv0;
1901 wchar_t *p = NULL;
1902 Py_ssize_t n = 0;
1903 PyObject *a;
1904 PyObject *path;
1905#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001906 wchar_t link[MAXPATHLEN+1];
1907 wchar_t argv0copy[2*MAXPATHLEN+1];
1908 int nr = 0;
1909#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001910#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001912#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001914#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001915
Victor Stinnerbd303c12013-11-07 23:07:29 +01001916 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001917 if (path == NULL)
1918 return;
1919
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001920 argv0 = argv[0];
1921
1922#ifdef HAVE_READLINK
1923 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1924 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1925 if (nr > 0) {
1926 /* It's a symlink */
1927 link[nr] = '\0';
1928 if (link[0] == SEP)
1929 argv0 = link; /* Link to absolute path */
1930 else if (wcschr(link, SEP) == NULL)
1931 ; /* Link without path */
1932 else {
1933 /* Must join(dirname(argv0), link) */
1934 wchar_t *q = wcsrchr(argv0, SEP);
1935 if (q == NULL)
1936 argv0 = link; /* argv0 without path */
1937 else {
Christian Heimes60a60672013-07-22 12:53:32 +02001938 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
1939 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001940 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02001941 wcsncpy(q+1, link, MAXPATHLEN);
1942 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001943 argv0 = argv0copy;
1944 }
1945 }
1946 }
1947#endif /* HAVE_READLINK */
1948#if SEP == '\\' /* Special case for MS filename syntax */
1949 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1950 wchar_t *q;
1951#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1952 /* This code here replaces the first element in argv with the full
1953 path that it represents. Under CE, there are no relative paths so
1954 the argument must be the full path anyway. */
1955 wchar_t *ptemp;
1956 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001957 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001958 fullpath,
1959 &ptemp)) {
1960 argv0 = fullpath;
1961 }
1962#endif
1963 p = wcsrchr(argv0, SEP);
1964 /* Test for alternate separator */
1965 q = wcsrchr(p ? p : argv0, '/');
1966 if (q != NULL)
1967 p = q;
1968 if (p != NULL) {
1969 n = p + 1 - argv0;
1970 if (n > 1 && p[-1] != ':')
1971 n--; /* Drop trailing separator */
1972 }
1973 }
1974#else /* All other filename syntaxes */
1975 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1976#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01001977 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001978 argv0 = fullpath;
1979 }
1980#endif
1981 p = wcsrchr(argv0, SEP);
1982 }
1983 if (p != NULL) {
1984 n = p + 1 - argv0;
1985#if SEP == '/' /* Special case for Unix filename syntax */
1986 if (n > 1)
1987 n--; /* Drop trailing separator */
1988#endif /* Unix */
1989 }
1990#endif /* All others */
1991 a = PyUnicode_FromWideChar(argv0, n);
1992 if (a == NULL)
1993 Py_FatalError("no mem for sys.path insertion");
1994 if (PyList_Insert(path, 0, a) < 0)
1995 Py_FatalError("sys.path.insert(0) failed");
1996 Py_DECREF(a);
1997}
1998
1999void
2000PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2001{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 if (av == NULL)
2004 Py_FatalError("no mem for sys.argv");
2005 if (PySys_SetObject("argv", av) != 0)
2006 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002008 if (updatepath)
2009 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002010}
Guido van Rossuma890e681998-05-12 14:59:24 +00002011
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002012void
2013PySys_SetArgv(int argc, wchar_t **argv)
2014{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002015 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002016}
2017
Victor Stinner14284c22010-04-23 12:02:30 +00002018/* Reimplementation of PyFile_WriteString() no calling indirectly
2019 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2020
2021static int
Victor Stinner79766632010-08-16 17:36:42 +00002022sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002023{
Victor Stinner79766632010-08-16 17:36:42 +00002024 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002026
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002027 if (file == NULL)
2028 return -1;
2029
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002030 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002031 if (writer == NULL)
2032 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002033
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 args = PyTuple_Pack(1, unicode);
2035 if (args == NULL)
2036 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002037
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002038 result = PyEval_CallObject(writer, args);
2039 if (result == NULL) {
2040 goto error;
2041 } else {
2042 err = 0;
2043 goto finally;
2044 }
Victor Stinner14284c22010-04-23 12:02:30 +00002045
2046error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002048finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002049 Py_XDECREF(writer);
2050 Py_XDECREF(args);
2051 Py_XDECREF(result);
2052 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002053}
2054
Victor Stinner79766632010-08-16 17:36:42 +00002055static int
2056sys_pyfile_write(const char *text, PyObject *file)
2057{
2058 PyObject *unicode = NULL;
2059 int err;
2060
2061 if (file == NULL)
2062 return -1;
2063
2064 unicode = PyUnicode_FromString(text);
2065 if (unicode == NULL)
2066 return -1;
2067
2068 err = sys_pyfile_write_unicode(unicode, file);
2069 Py_DECREF(unicode);
2070 return err;
2071}
Guido van Rossuma890e681998-05-12 14:59:24 +00002072
2073/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2074 Adapted from code submitted by Just van Rossum.
2075
2076 PySys_WriteStdout(format, ...)
2077 PySys_WriteStderr(format, ...)
2078
2079 The first function writes to sys.stdout; the second to sys.stderr. When
2080 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002081 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002082
Victor Stinner14284c22010-04-23 12:02:30 +00002083 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002084 signal handlers: they may raise a new exception whereas sys_write()
2085 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002086
Guido van Rossuma890e681998-05-12 14:59:24 +00002087 Both take a printf-style format string as their first argument followed
2088 by a variable length argument list determined by the format string.
2089
2090 *** WARNING ***
2091
2092 The format should limit the total size of the formatted output string to
2093 1000 bytes. In particular, this means that no unrestricted "%s" formats
2094 should occur; these should be limited using "%.<N>s where <N> is a
2095 decimal number calculated so that <N> plus the maximum size of other
2096 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2097 which can print hundreds of digits for very large numbers.
2098
2099 */
2100
2101static void
Victor Stinner09054372013-11-06 22:41:44 +01002102sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002104 PyObject *file;
2105 PyObject *error_type, *error_value, *error_traceback;
2106 char buffer[1001];
2107 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002109 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002110 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002111 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2112 if (sys_pyfile_write(buffer, file) != 0) {
2113 PyErr_Clear();
2114 fputs(buffer, fp);
2115 }
2116 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2117 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002118 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 }
2121 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002122}
2123
2124void
Guido van Rossuma890e681998-05-12 14:59:24 +00002125PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002128
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002130 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002132}
2133
2134void
Guido van Rossuma890e681998-05-12 14:59:24 +00002135PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002136{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002137 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002140 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002141 va_end(va);
2142}
2143
2144static void
Victor Stinner09054372013-11-06 22:41:44 +01002145sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002146{
2147 PyObject *file, *message;
2148 PyObject *error_type, *error_value, *error_traceback;
2149 char *utf8;
2150
2151 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002152 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002153 message = PyUnicode_FromFormatV(format, va);
2154 if (message != NULL) {
2155 if (sys_pyfile_write_unicode(message, file) != 0) {
2156 PyErr_Clear();
2157 utf8 = _PyUnicode_AsString(message);
2158 if (utf8 != NULL)
2159 fputs(utf8, fp);
2160 }
2161 Py_DECREF(message);
2162 }
2163 PyErr_Restore(error_type, error_value, error_traceback);
2164}
2165
2166void
2167PySys_FormatStdout(const char *format, ...)
2168{
2169 va_list va;
2170
2171 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002172 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002173 va_end(va);
2174}
2175
2176void
2177PySys_FormatStderr(const char *format, ...)
2178{
2179 va_list va;
2180
2181 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002182 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002183 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002184}