blob: 4028a01dab77aad6bbaec0bab9e8b865f3c77f7e [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öwisc16f3bd2003-05-03 09:14:54 +000035#ifdef __VMS
36#include <unixlib.h>
37#endif
38
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000039#ifdef HAVE_LANGINFO_H
40#include <locale.h>
41#include <langinfo.h>
42#endif
43
Victor Stinnerbd303c12013-11-07 23:07:29 +010044_Py_IDENTIFIER(_);
45_Py_IDENTIFIER(__sizeof__);
46_Py_IDENTIFIER(buffer);
47_Py_IDENTIFIER(builtins);
48_Py_IDENTIFIER(encoding);
49_Py_IDENTIFIER(path);
50_Py_IDENTIFIER(stdout);
51_Py_IDENTIFIER(stderr);
52_Py_IDENTIFIER(write);
53
Guido van Rossum65bf9f21997-04-29 18:33:38 +000054PyObject *
Victor Stinnerd67bd452013-11-06 22:36:40 +010055_PySys_GetObjectId(_Py_Identifier *key)
56{
57 PyThreadState *tstate = PyThreadState_GET();
58 PyObject *sd = tstate->interp->sysdict;
59 if (sd == NULL)
60 return NULL;
61 return _PyDict_GetItemId(sd, key);
62}
63
64PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000065PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 PyThreadState *tstate = PyThreadState_GET();
68 PyObject *sd = tstate->interp->sysdict;
69 if (sd == NULL)
70 return NULL;
71 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000072}
73
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000074int
Victor Stinnerd67bd452013-11-06 22:36:40 +010075_PySys_SetObjectId(_Py_Identifier *key, PyObject *v)
76{
77 PyThreadState *tstate = PyThreadState_GET();
78 PyObject *sd = tstate->interp->sysdict;
79 if (v == NULL) {
80 if (_PyDict_GetItemId(sd, key) == NULL)
81 return 0;
82 else
83 return _PyDict_DelItemId(sd, key);
84 }
85 else
86 return _PyDict_SetItemId(sd, key, v);
87}
88
89int
Neal Norwitzf3081322007-08-25 00:32:45 +000090PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000092 PyThreadState *tstate = PyThreadState_GET();
93 PyObject *sd = tstate->interp->sysdict;
94 if (v == NULL) {
95 if (PyDict_GetItemString(sd, name) == NULL)
96 return 0;
97 else
98 return PyDict_DelItemString(sd, name);
99 }
100 else
101 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000102}
103
Victor Stinner13d49ee2010-12-04 17:24:33 +0000104/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
105 error handler. If sys.stdout has a buffer attribute, use
106 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
107 sys.stdout.write(redecoded).
108
109 Helper function for sys_displayhook(). */
110static int
111sys_displayhook_unencodable(PyObject *outf, PyObject *o)
112{
113 PyObject *stdout_encoding = NULL;
114 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
115 char *stdout_encoding_str;
116 int ret;
117
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200118 stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000119 if (stdout_encoding == NULL)
120 goto error;
121 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
122 if (stdout_encoding_str == NULL)
123 goto error;
124
125 repr_str = PyObject_Repr(o);
126 if (repr_str == NULL)
127 goto error;
128 encoded = PyUnicode_AsEncodedString(repr_str,
129 stdout_encoding_str,
130 "backslashreplace");
131 Py_DECREF(repr_str);
132 if (encoded == NULL)
133 goto error;
134
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +0200135 buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000136 if (buffer) {
Martin v. Löwisafe55bb2011-10-09 10:38:36 +0200137 result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
Victor Stinner13d49ee2010-12-04 17:24:33 +0000138 Py_DECREF(buffer);
139 Py_DECREF(encoded);
140 if (result == NULL)
141 goto error;
142 Py_DECREF(result);
143 }
144 else {
145 PyErr_Clear();
146 escaped_str = PyUnicode_FromEncodedObject(encoded,
147 stdout_encoding_str,
148 "strict");
149 Py_DECREF(encoded);
150 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
151 Py_DECREF(escaped_str);
152 goto error;
153 }
154 Py_DECREF(escaped_str);
155 }
156 ret = 0;
157 goto finally;
158
159error:
160 ret = -1;
161finally:
162 Py_XDECREF(stdout_encoding);
163 return ret;
164}
165
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000166static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000167sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000168{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000169 PyObject *outf;
170 PyInterpreterState *interp = PyThreadState_GET()->interp;
171 PyObject *modules = interp->modules;
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100172 PyObject *builtins;
173 static PyObject *newline = NULL;
Victor Stinner13d49ee2010-12-04 17:24:33 +0000174 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000175
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100176 builtins = _PyDict_GetItemId(modules, &PyId_builtins);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000177 if (builtins == NULL) {
178 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
179 return NULL;
180 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000181
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000182 /* Print value except if None */
183 /* After printing, also assign to '_' */
184 /* Before, set '_' to None to avoid recursion */
185 if (o == Py_None) {
186 Py_INCREF(Py_None);
187 return Py_None;
188 }
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200189 if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000190 return NULL;
Victor Stinnerbd303c12013-11-07 23:07:29 +0100191 outf = _PySys_GetObjectId(&PyId_stdout);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000192 if (outf == NULL || outf == Py_None) {
193 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
194 return NULL;
195 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000196 if (PyFile_WriteObject(o, outf, 0) != 0) {
197 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
198 /* repr(o) is not encodable to sys.stdout.encoding with
199 * sys.stdout.errors error handler (which is probably 'strict') */
200 PyErr_Clear();
201 err = sys_displayhook_unencodable(outf, o);
202 if (err)
203 return NULL;
204 }
205 else {
206 return NULL;
207 }
208 }
Victor Stinnerd02fbb82013-11-06 18:27:13 +0100209 if (newline == NULL) {
210 newline = PyUnicode_FromString("\n");
211 if (newline == NULL)
212 return NULL;
213 }
214 if (PyFile_WriteObject(newline, outf, Py_PRINT_RAW) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000215 return NULL;
Martin v. Löwis1c67dd92011-10-14 15:16:45 +0200216 if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000217 return NULL;
218 Py_INCREF(Py_None);
219 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000220}
221
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000222PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000223"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000224"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000225"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000226);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000227
228static PyObject *
229sys_excepthook(PyObject* self, PyObject* args)
230{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000231 PyObject *exc, *value, *tb;
232 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
233 return NULL;
234 PyErr_Display(exc, value, tb);
235 Py_INCREF(Py_None);
236 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000237}
238
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000239PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000240"excepthook(exctype, value, traceback) -> None\n"
241"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000242"Handle an exception by displaying it with a traceback on sys.stderr.\n"
243);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000244
245static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000246sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000247{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000248 PyThreadState *tstate;
249 tstate = PyThreadState_GET();
250 return Py_BuildValue(
251 "(OOO)",
252 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
253 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
254 tstate->exc_traceback != NULL ?
255 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000256}
257
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000258PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000259"exc_info() -> (type, value, traceback)\n\
260\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000261Return information about the most recent exception caught by an except\n\
262clause in the current stack frame or in an older stack frame."
263);
264
265static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000266sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000267{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000268 PyObject *exit_code = 0;
269 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
270 return NULL;
271 /* Raise SystemExit so callers may catch it or clean up. */
272 PyErr_SetObject(PyExc_SystemExit, exit_code);
273 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000274}
275
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000276PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000277"exit([status])\n\
278\n\
279Exit the interpreter by raising SystemExit(status).\n\
280If the status is omitted or None, it defaults to zero (i.e., success).\n\
Ezio Melotti4af4d272013-08-26 14:00:39 +0300281If the status is an integer, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000282If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000283exit status will be one (i.e., failure)."
284);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000285
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000286
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000287static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000288sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000289{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000290 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000291}
292
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000293PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000294"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000295\n\
296Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000297implementation."
298);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000299
300static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000301sys_getfilesystemencoding(PyObject *self)
302{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (Py_FileSystemDefaultEncoding)
304 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
Victor Stinner27181ac2011-03-31 13:39:03 +0200305 PyErr_SetString(PyExc_RuntimeError,
306 "filesystem encoding is not initialized");
307 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000308}
309
310PyDoc_STRVAR(getfilesystemencoding_doc,
311"getfilesystemencoding() -> string\n\
312\n\
313Return the encoding used to convert Unicode filenames in\n\
314operating system filenames."
315);
316
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000317static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000318sys_intern(PyObject *self, PyObject *args)
319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000320 PyObject *s;
321 if (!PyArg_ParseTuple(args, "U:intern", &s))
322 return NULL;
323 if (PyUnicode_CheckExact(s)) {
324 Py_INCREF(s);
325 PyUnicode_InternInPlace(&s);
326 return s;
327 }
328 else {
329 PyErr_Format(PyExc_TypeError,
330 "can't intern %.400s", s->ob_type->tp_name);
331 return NULL;
332 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000333}
334
335PyDoc_STRVAR(intern_doc,
336"intern(string) -> string\n\
337\n\
338``Intern'' the given string. This enters the string in the (global)\n\
339table of interned strings whose purpose is to speed up dictionary lookups.\n\
340Return the string itself or the previously interned string object with the\n\
341same value.");
342
343
Fred Drake5755ce62001-06-27 19:19:46 +0000344/*
345 * Cached interned string objects used for calling the profile and
346 * trace functions. Initialized by trace_init().
347 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000348static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000349
350static int
351trace_init(void)
352{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 static char *whatnames[7] = {"call", "exception", "line", "return",
354 "c_call", "c_exception", "c_return"};
355 PyObject *name;
356 int i;
357 for (i = 0; i < 7; ++i) {
358 if (whatstrings[i] == NULL) {
359 name = PyUnicode_InternFromString(whatnames[i]);
360 if (name == NULL)
361 return -1;
362 whatstrings[i] = name;
363 }
364 }
365 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000366}
367
368
369static PyObject *
370call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000371 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000372{
Victor Stinner41bb43a2013-10-29 01:19:37 +0100373 PyObject *args;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 PyObject *whatstr;
375 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000376
Victor Stinner41bb43a2013-10-29 01:19:37 +0100377 args = PyTuple_New(3);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 if (args == NULL)
379 return NULL;
Victor Stinner41bb43a2013-10-29 01:19:37 +0100380 if (PyFrame_FastToLocalsWithError(frame) < 0)
381 return NULL;
382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 Py_INCREF(frame);
384 whatstr = whatstrings[what];
385 Py_INCREF(whatstr);
386 if (arg == NULL)
387 arg = Py_None;
388 Py_INCREF(arg);
389 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
390 PyTuple_SET_ITEM(args, 1, whatstr);
391 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000393 /* call the Python-level function */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000394 result = PyEval_CallObject(callback, args);
395 PyFrame_LocalsToFast(frame, 1);
396 if (result == NULL)
397 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 /* cleanup */
400 Py_DECREF(args);
401 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000402}
403
404static int
405profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000406 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000407{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000408 PyThreadState *tstate = frame->f_tstate;
409 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (arg == NULL)
412 arg = Py_None;
413 result = call_trampoline(tstate, self, frame, what, arg);
414 if (result == NULL) {
415 PyEval_SetProfile(NULL, NULL);
416 return -1;
417 }
418 Py_DECREF(result);
419 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000420}
421
422static int
423trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000424 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000425{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000426 PyThreadState *tstate = frame->f_tstate;
427 PyObject *callback;
428 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000430 if (what == PyTrace_CALL)
431 callback = self;
432 else
433 callback = frame->f_trace;
434 if (callback == NULL)
435 return 0;
436 result = call_trampoline(tstate, callback, frame, what, arg);
437 if (result == NULL) {
438 PyEval_SetTrace(NULL, NULL);
439 Py_XDECREF(frame->f_trace);
440 frame->f_trace = NULL;
441 return -1;
442 }
443 if (result != Py_None) {
444 PyObject *temp = frame->f_trace;
445 frame->f_trace = NULL;
446 Py_XDECREF(temp);
447 frame->f_trace = result;
448 }
449 else {
450 Py_DECREF(result);
451 }
452 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000453}
Fred Draked0838392001-06-16 21:02:31 +0000454
Fred Drake8b4d01d2000-05-09 19:57:01 +0000455static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000456sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000458 if (trace_init() == -1)
459 return NULL;
460 if (args == Py_None)
461 PyEval_SetTrace(NULL, NULL);
462 else
463 PyEval_SetTrace(trace_trampoline, args);
464 Py_INCREF(Py_None);
465 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000466}
467
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000468PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000469"settrace(function)\n\
470\n\
471Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000472function call. See the debugger chapter in the library manual."
473);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000474
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000475static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000476sys_gettrace(PyObject *self, PyObject *args)
477{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000478 PyThreadState *tstate = PyThreadState_GET();
479 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000481 if (temp == NULL)
482 temp = Py_None;
483 Py_INCREF(temp);
484 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000485}
486
487PyDoc_STRVAR(gettrace_doc,
488"gettrace()\n\
489\n\
490Return the global debug tracing function set with sys.settrace.\n\
491See the debugger chapter in the library manual."
492);
493
494static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000495sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000496{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000497 if (trace_init() == -1)
498 return NULL;
499 if (args == Py_None)
500 PyEval_SetProfile(NULL, NULL);
501 else
502 PyEval_SetProfile(profile_trampoline, args);
503 Py_INCREF(Py_None);
504 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000505}
506
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000507PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508"setprofile(function)\n\
509\n\
510Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000511and return. See the profiler chapter in the library manual."
512);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000513
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000514static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000515sys_getprofile(PyObject *self, PyObject *args)
516{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000517 PyThreadState *tstate = PyThreadState_GET();
518 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000520 if (temp == NULL)
521 temp = Py_None;
522 Py_INCREF(temp);
523 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000524}
525
526PyDoc_STRVAR(getprofile_doc,
527"getprofile()\n\
528\n\
529Return the profiling function set with sys.setprofile.\n\
530See the profiler chapter in the library manual."
531);
532
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000533static int _check_interval = 100;
534
Christian Heimes9bd667a2008-01-20 15:14:11 +0000535static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000536sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000537{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000538 if (PyErr_WarnEx(PyExc_DeprecationWarning,
539 "sys.getcheckinterval() and sys.setcheckinterval() "
540 "are deprecated. Use sys.setswitchinterval() "
541 "instead.", 1) < 0)
542 return NULL;
543 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
544 return NULL;
545 Py_INCREF(Py_None);
546 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000547}
548
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000549PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000550"setcheckinterval(n)\n\
551\n\
552Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000553n instructions. This also affects how often thread switches occur."
554);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000555
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000556static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000557sys_getcheckinterval(PyObject *self, PyObject *args)
558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000559 if (PyErr_WarnEx(PyExc_DeprecationWarning,
560 "sys.getcheckinterval() and sys.setcheckinterval() "
561 "are deprecated. Use sys.getswitchinterval() "
562 "instead.", 1) < 0)
563 return NULL;
564 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000565}
566
567PyDoc_STRVAR(getcheckinterval_doc,
568"getcheckinterval() -> current check interval; see setcheckinterval()."
569);
570
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000571#ifdef WITH_THREAD
572static PyObject *
573sys_setswitchinterval(PyObject *self, PyObject *args)
574{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000575 double d;
576 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
577 return NULL;
578 if (d <= 0.0) {
579 PyErr_SetString(PyExc_ValueError,
580 "switch interval must be strictly positive");
581 return NULL;
582 }
583 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
584 Py_INCREF(Py_None);
585 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000586}
587
588PyDoc_STRVAR(setswitchinterval_doc,
589"setswitchinterval(n)\n\
590\n\
591Set the ideal thread switching delay inside the Python interpreter\n\
592The actual frequency of switching threads can be lower if the\n\
593interpreter executes long sequences of uninterruptible code\n\
594(this is implementation-specific and workload-dependent).\n\
595\n\
596The parameter must represent the desired switching delay in seconds\n\
597A typical value is 0.005 (5 milliseconds)."
598);
599
600static PyObject *
601sys_getswitchinterval(PyObject *self, PyObject *args)
602{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000603 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000604}
605
606PyDoc_STRVAR(getswitchinterval_doc,
607"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
608);
609
610#endif /* WITH_THREAD */
611
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000612#ifdef WITH_TSC
613static PyObject *
614sys_settscdump(PyObject *self, PyObject *args)
615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000616 int bool;
617 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000619 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
620 return NULL;
621 if (bool)
622 tstate->interp->tscdump = 1;
623 else
624 tstate->interp->tscdump = 0;
625 Py_INCREF(Py_None);
626 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000627
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000628}
629
Tim Peters216b78b2006-01-06 02:40:53 +0000630PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000631"settscdump(bool)\n\
632\n\
633If true, tell the Python interpreter to dump VM measurements to\n\
634stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000635processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000636);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000637#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000638
Tim Peterse5e065b2003-07-06 18:36:54 +0000639static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000640sys_setrecursionlimit(PyObject *self, PyObject *args)
641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000642 int new_limit;
643 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
644 return NULL;
645 if (new_limit <= 0) {
646 PyErr_SetString(PyExc_ValueError,
647 "recursion limit must be positive");
648 return NULL;
649 }
650 Py_SetRecursionLimit(new_limit);
651 Py_INCREF(Py_None);
652 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000653}
654
Mark Dickinsondc787d22010-05-23 13:33:13 +0000655static PyTypeObject Hash_InfoType;
656
657PyDoc_STRVAR(hash_info_doc,
658"hash_info\n\
659\n\
660A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100661hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000662
663static PyStructSequence_Field hash_info_fields[] = {
664 {"width", "width of the type used for hashing, in bits"},
665 {"modulus", "prime number giving the modulus on which the hash "
666 "function is based"},
667 {"inf", "value to be used for hash of a positive infinity"},
668 {"nan", "value to be used for hash of a nan"},
669 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100670 {"algorithm", "name of the algorithm for hashing of str, bytes and "
671 "memoryviews"},
672 {"hash_bits", "internal output size of hash algorithm"},
673 {"seed_bits", "seed size of hash algorithm"},
674 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000675 {NULL, NULL}
676};
677
678static PyStructSequence_Desc hash_info_desc = {
679 "sys.hash_info",
680 hash_info_doc,
681 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100682 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000683};
684
Matthias Klosed885e952010-07-06 10:53:30 +0000685static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000686get_hash_info(void)
687{
688 PyObject *hash_info;
689 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100690 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000691 hash_info = PyStructSequence_New(&Hash_InfoType);
692 if (hash_info == NULL)
693 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100694 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000695 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000696 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000697 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000698 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000699 PyStructSequence_SET_ITEM(hash_info, field++,
700 PyLong_FromLong(_PyHASH_INF));
701 PyStructSequence_SET_ITEM(hash_info, field++,
702 PyLong_FromLong(_PyHASH_NAN));
703 PyStructSequence_SET_ITEM(hash_info, field++,
704 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100705 PyStructSequence_SET_ITEM(hash_info, field++,
706 PyUnicode_FromString(hashfunc->name));
707 PyStructSequence_SET_ITEM(hash_info, field++,
708 PyLong_FromLong(hashfunc->hash_bits));
709 PyStructSequence_SET_ITEM(hash_info, field++,
710 PyLong_FromLong(hashfunc->seed_bits));
711 PyStructSequence_SET_ITEM(hash_info, field++,
712 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000713 if (PyErr_Occurred()) {
714 Py_CLEAR(hash_info);
715 return NULL;
716 }
717 return hash_info;
718}
719
720
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000721PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000722"setrecursionlimit(n)\n\
723\n\
724Set the maximum depth of the Python interpreter stack to n. This\n\
725limit prevents infinite recursion from causing an overflow of the C\n\
726stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000727dependent."
728);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000729
730static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000731sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000732{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000733 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000734}
735
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000736PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000737"getrecursionlimit()\n\
738\n\
739Return the current value of the recursion limit, the maximum depth\n\
740of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000741recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000742);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000743
Mark Hammond8696ebc2002-10-08 02:44:31 +0000744#ifdef MS_WINDOWS
745PyDoc_STRVAR(getwindowsversion_doc,
746"getwindowsversion()\n\
747\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000748Return information about the running version of Windows as a named tuple.\n\
749The members are named: major, minor, build, platform, service_pack,\n\
750service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200751backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000752All elements are numbers, except service_pack which is a string. Platform\n\
753may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
7543 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
755controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000756);
757
Eric Smithf7bb5782010-01-27 00:44:57 +0000758static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
759
760static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000761 {"major", "Major version number"},
762 {"minor", "Minor version number"},
763 {"build", "Build number"},
764 {"platform", "Operating system platform"},
765 {"service_pack", "Latest Service Pack installed on the system"},
766 {"service_pack_major", "Service Pack major version number"},
767 {"service_pack_minor", "Service Pack minor version number"},
768 {"suite_mask", "Bit mask identifying available product suites"},
769 {"product_type", "System product type"},
770 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000771};
772
773static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000774 "sys.getwindowsversion", /* name */
775 getwindowsversion_doc, /* doc */
776 windows_version_fields, /* fields */
777 5 /* For backward compatibility,
778 only the first 5 items are accessible
779 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000780};
781
Mark Hammond8696ebc2002-10-08 02:44:31 +0000782static PyObject *
783sys_getwindowsversion(PyObject *self)
784{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000785 PyObject *version;
786 int pos = 0;
787 OSVERSIONINFOEX ver;
788 ver.dwOSVersionInfoSize = sizeof(ver);
789 if (!GetVersionEx((OSVERSIONINFO*) &ver))
790 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792 version = PyStructSequence_New(&WindowsVersionType);
793 if (version == NULL)
794 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000795
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
797 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
798 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
799 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
800 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
801 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
802 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
803 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
804 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000806 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000807}
808
809#endif /* MS_WINDOWS */
810
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000811#ifdef HAVE_DLOPEN
812static PyObject *
813sys_setdlopenflags(PyObject *self, PyObject *args)
814{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000815 int new_val;
816 PyThreadState *tstate = PyThreadState_GET();
817 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
818 return NULL;
819 if (!tstate)
820 return NULL;
821 tstate->interp->dlopenflags = new_val;
822 Py_INCREF(Py_None);
823 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000824}
825
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000826PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000827"setdlopenflags(n) -> None\n\
828\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000829Set the flags used by the interpreter for dlopen calls, such as when the\n\
830interpreter loads extension modules. Among other things, this will enable\n\
831a lazy resolving of symbols when importing a module, if called as\n\
832sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400833sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100834can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000835
836static PyObject *
837sys_getdlopenflags(PyObject *self, PyObject *args)
838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 PyThreadState *tstate = PyThreadState_GET();
840 if (!tstate)
841 return NULL;
842 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000843}
844
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000845PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000846"getdlopenflags() -> int\n\
847\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000848Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400849The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000850
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000851#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000852
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000853#ifdef USE_MALLOPT
854/* Link with -lmalloc (or -lmpc) on an SGI */
855#include <malloc.h>
856
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000857static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000858sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000859{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000860 int flag;
861 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
862 return NULL;
863 mallopt(M_DEBUG, flag);
864 Py_INCREF(Py_None);
865 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000866}
867#endif /* USE_MALLOPT */
868
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000869static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000870sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000871{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyObject *res = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500873 static PyObject *gc_head_size = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 static char *kwlist[] = {"object", "default", 0};
875 PyObject *o, *dflt = NULL;
876 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000877
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000878 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
879 kwlist, &o, &dflt))
880 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000881
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 /* Initialize static variable for GC head size */
883 if (gc_head_size == NULL) {
884 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
885 if (gc_head_size == NULL)
886 return NULL;
887 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 /* Make sure the type is initialized. float gets initialized late */
890 if (PyType_Ready(Py_TYPE(o)) < 0)
891 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000892
Benjamin Petersonce798522012-01-22 11:24:29 -0500893 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000894 if (method == NULL) {
895 if (!PyErr_Occurred())
896 PyErr_Format(PyExc_TypeError,
897 "Type %.100s doesn't define __sizeof__",
898 Py_TYPE(o)->tp_name);
899 }
900 else {
901 res = PyObject_CallFunctionObjArgs(method, NULL);
902 Py_DECREF(method);
903 }
904
905 /* Has a default value been given */
906 if ((res == NULL) && (dflt != NULL) &&
907 PyErr_ExceptionMatches(PyExc_TypeError))
908 {
909 PyErr_Clear();
910 Py_INCREF(dflt);
911 return dflt;
912 }
913 else if (res == NULL)
914 return res;
915
916 /* add gc_head size */
917 if (PyObject_IS_GC(o)) {
918 PyObject *tmp = res;
919 res = PyNumber_Add(tmp, gc_head_size);
920 Py_DECREF(tmp);
921 }
922 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000923}
924
925PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000926"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000927\n\
928Return the size of object in bytes.");
929
930static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000931sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000932{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000933 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000934}
935
Tim Peters4be93d02002-07-07 19:59:50 +0000936#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000937static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000938sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000939{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000940 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000941}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000942#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000943
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000944PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000945"getrefcount(object) -> integer\n\
946\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000947Return the reference count of object. The count returned is generally\n\
948one higher than you might expect, because it includes the (temporary)\n\
949reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000950);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000951
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100952static PyObject *
953sys_getallocatedblocks(PyObject *self)
954{
955 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
956}
957
958PyDoc_STRVAR(getallocatedblocks_doc,
959"getallocatedblocks() -> integer\n\
960\n\
961Return the number of memory blocks currently allocated, regardless of their\n\
962size."
963);
964
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000965#ifdef COUNT_ALLOCS
966static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000967sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000968{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000970
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000972}
973#endif
974
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000975PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000976"_getframe([depth]) -> frameobject\n\
977\n\
978Return a frame object from the call stack. If optional integer depth is\n\
979given, return the frame object that many calls below the top of the stack.\n\
980If that is deeper than the call stack, ValueError is raised. The default\n\
981for depth is zero, returning the frame at the top of the call stack.\n\
982\n\
983This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000984purposes only."
985);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000986
987static PyObject *
988sys_getframe(PyObject *self, PyObject *args)
989{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 PyFrameObject *f = PyThreadState_GET()->frame;
991 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000992
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
994 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000995
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 while (depth > 0 && f != NULL) {
997 f = f->f_back;
998 --depth;
999 }
1000 if (f == NULL) {
1001 PyErr_SetString(PyExc_ValueError,
1002 "call stack is not deep enough");
1003 return NULL;
1004 }
1005 Py_INCREF(f);
1006 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001007}
1008
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001009PyDoc_STRVAR(current_frames_doc,
1010"_current_frames() -> dictionary\n\
1011\n\
1012Return a dictionary mapping each current thread T's thread id to T's\n\
1013current stack frame.\n\
1014\n\
1015This function should be used for specialized purposes only."
1016);
1017
1018static PyObject *
1019sys_current_frames(PyObject *self, PyObject *noargs)
1020{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001022}
1023
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001024PyDoc_STRVAR(call_tracing_doc,
1025"call_tracing(func, args) -> object\n\
1026\n\
1027Call func(*args), while tracing is enabled. The tracing state is\n\
1028saved, and restored afterwards. This is intended to be called from\n\
1029a debugger from a checkpoint, to recursively debug some other code."
1030);
1031
1032static PyObject *
1033sys_call_tracing(PyObject *self, PyObject *args)
1034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 PyObject *func, *funcargs;
1036 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1037 return NULL;
1038 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001039}
1040
Jeremy Hylton985eba52003-02-05 23:13:00 +00001041PyDoc_STRVAR(callstats_doc,
1042"callstats() -> tuple of integers\n\
1043\n\
1044Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1045when Python was built. Otherwise, return None.\n\
1046\n\
1047When enabled, this function returns detailed, implementation-specific\n\
1048details about the number of function calls executed. The return value is\n\
1049a 11-tuple where the entries in the tuple are counts of:\n\
10500. all function calls\n\
10511. calls to PyFunction_Type objects\n\
10522. PyFunction calls that do not create an argument tuple\n\
10533. PyFunction calls that do not create an argument tuple\n\
1054 and bypass PyEval_EvalCodeEx()\n\
10554. PyMethod calls\n\
10565. PyMethod calls on bound methods\n\
10576. PyType calls\n\
10587. PyCFunction calls\n\
10598. generator calls\n\
10609. All other calls\n\
106110. Number of stack pops performed by call_function()"
1062);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001063
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001064#ifdef __cplusplus
1065extern "C" {
1066#endif
1067
David Malcolm49526f42012-06-22 14:55:41 -04001068static PyObject *
1069sys_debugmallocstats(PyObject *self, PyObject *args)
1070{
1071#ifdef WITH_PYMALLOC
1072 _PyObject_DebugMallocStats(stderr);
1073 fputc('\n', stderr);
1074#endif
1075 _PyObject_DebugTypeStats(stderr);
1076
1077 Py_RETURN_NONE;
1078}
1079PyDoc_STRVAR(debugmallocstats_doc,
1080"_debugmallocstats()\n\
1081\n\
1082Print summary info to stderr about the state of\n\
1083pymalloc's structures.\n\
1084\n\
1085In Py_DEBUG mode, also perform some expensive internal consistency\n\
1086checks.\n\
1087");
1088
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001089#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001090/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001091extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001092#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001093
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001094#ifdef DYNAMIC_EXECUTION_PROFILE
1095/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001096extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001097#endif
1098
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001099#ifdef __cplusplus
1100}
1101#endif
1102
Christian Heimes15ebc882008-02-04 18:48:49 +00001103static PyObject *
1104sys_clear_type_cache(PyObject* self, PyObject* args)
1105{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001106 PyType_ClearCache();
1107 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001108}
1109
1110PyDoc_STRVAR(sys_clear_type_cache__doc__,
1111"_clear_type_cache() -> None\n\
1112Clear the internal type lookup cache.");
1113
1114
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001115static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001116 /* Might as well keep this in alphabetic order */
1117 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1118 callstats_doc},
1119 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1120 sys_clear_type_cache__doc__},
1121 {"_current_frames", sys_current_frames, METH_NOARGS,
1122 current_frames_doc},
1123 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1124 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1125 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1126 {"exit", sys_exit, METH_VARARGS, exit_doc},
1127 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1128 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001129#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1131 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001132#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001133 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1134 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001135#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001137#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001138#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001140#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1142 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001143#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001144 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001145#endif
1146#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001148#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001149 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1150 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1151 getrecursionlimit_doc},
1152 {"getsizeof", (PyCFunction)sys_getsizeof,
1153 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1154 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001155#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001156 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1157 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001158#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001160#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001162#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001163 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1164 setcheckinterval_doc},
1165 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1166 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001167#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001168 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1169 setswitchinterval_doc},
1170 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1171 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001172#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001173#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001174 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1175 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001176#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001177 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1178 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1179 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1180 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001181#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001183#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001184 {"settrace", sys_settrace, METH_O, settrace_doc},
1185 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1186 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
David Malcolm49526f42012-06-22 14:55:41 -04001187 {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
1188 debugmallocstats_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001189 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001190};
1191
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001192static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001193list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001194{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001195 PyObject *list = PyList_New(0);
1196 int i;
1197 if (list == NULL)
1198 return NULL;
1199 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1200 PyObject *name = PyUnicode_FromString(
1201 PyImport_Inittab[i].name);
1202 if (name == NULL)
1203 break;
1204 PyList_Append(list, name);
1205 Py_DECREF(name);
1206 }
1207 if (PyList_Sort(list) != 0) {
1208 Py_DECREF(list);
1209 list = NULL;
1210 }
1211 if (list) {
1212 PyObject *v = PyList_AsTuple(list);
1213 Py_DECREF(list);
1214 list = v;
1215 }
1216 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001217}
1218
Guido van Rossum23fff912000-12-15 22:02:05 +00001219static PyObject *warnoptions = NULL;
1220
1221void
1222PySys_ResetWarnOptions(void)
1223{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001224 if (warnoptions == NULL || !PyList_Check(warnoptions))
1225 return;
1226 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001227}
1228
1229void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001230PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001231{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001232 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1233 Py_XDECREF(warnoptions);
1234 warnoptions = PyList_New(0);
1235 if (warnoptions == NULL)
1236 return;
1237 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001238 PyList_Append(warnoptions, unicode);
1239}
1240
1241void
1242PySys_AddWarnOption(const wchar_t *s)
1243{
1244 PyObject *unicode;
1245 unicode = PyUnicode_FromWideChar(s, -1);
1246 if (unicode == NULL)
1247 return;
1248 PySys_AddWarnOptionUnicode(unicode);
1249 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001250}
1251
Christian Heimes33fe8092008-04-13 13:53:33 +00001252int
1253PySys_HasWarnOptions(void)
1254{
1255 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1256}
1257
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001258static PyObject *xoptions = NULL;
1259
1260static PyObject *
1261get_xoptions(void)
1262{
1263 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1264 Py_XDECREF(xoptions);
1265 xoptions = PyDict_New();
1266 }
1267 return xoptions;
1268}
1269
1270void
1271PySys_AddXOption(const wchar_t *s)
1272{
1273 PyObject *opts;
1274 PyObject *name = NULL, *value = NULL;
1275 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001276
1277 opts = get_xoptions();
1278 if (opts == NULL)
1279 goto error;
1280
1281 name_end = wcschr(s, L'=');
1282 if (!name_end) {
1283 name = PyUnicode_FromWideChar(s, -1);
1284 value = Py_True;
1285 Py_INCREF(value);
1286 }
1287 else {
1288 name = PyUnicode_FromWideChar(s, name_end - s);
1289 value = PyUnicode_FromWideChar(name_end + 1, -1);
1290 }
1291 if (name == NULL || value == NULL)
1292 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001293 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001294 Py_DECREF(name);
1295 Py_DECREF(value);
1296 return;
1297
1298error:
1299 Py_XDECREF(name);
1300 Py_XDECREF(value);
1301 /* No return value, therefore clear error state if possible */
1302 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1303 PyErr_Clear();
1304}
1305
1306PyObject *
1307PySys_GetXOptions(void)
1308{
1309 return get_xoptions();
1310}
1311
Guido van Rossum40552d01998-08-06 03:34:39 +00001312/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1313 Two literals concatenated works just fine. If you have a K&R compiler
1314 or other abomination that however *does* understand longer strings,
1315 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001316PyDoc_VAR(sys_doc) =
1317PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001318"This module provides access to some objects used or maintained by the\n\
1319interpreter and to functions that interact strongly with the interpreter.\n\
1320\n\
1321Dynamic objects:\n\
1322\n\
1323argv -- command line arguments; argv[0] is the script pathname if known\n\
1324path -- module search path; path[0] is the script directory, else ''\n\
1325modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001326\n\
1327displayhook -- called to show results in an interactive session\n\
1328excepthook -- called to handle any uncaught exception other than SystemExit\n\
1329 To customize printing in an interactive session or to install a custom\n\
1330 top-level exception handler, assign other functions to replace these.\n\
1331\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001332stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001333stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001334stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001335 By assigning other file objects (or objects that behave like files)\n\
1336 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001337\n\
1338last_type -- type of last uncaught exception\n\
1339last_value -- value of last uncaught exception\n\
1340last_traceback -- traceback of last uncaught exception\n\
1341 These three are only available in an interactive session after a\n\
1342 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001343"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001344)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001345/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001346PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001347"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001348Static objects:\n\
1349\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001350builtin_module_names -- tuple of module names built into this interpreter\n\
1351copyright -- copyright notice pertaining to this interpreter\n\
1352exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001353executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001354float_info -- a struct sequence with information about the float implementation.\n\
1355float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001356hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001357hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001358implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001359int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001360maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001361maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001362platform -- platform identifier\n\
1363prefix -- prefix used to find the Python library\n\
1364thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001365version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001366version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001367"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001368)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001369#ifdef MS_WINDOWS
1370/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001371PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001372"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001373winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001374"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001375)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001376#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001377PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001378"__stdin__ -- the original stdin; don't touch!\n\
1379__stdout__ -- the original stdout; don't touch!\n\
1380__stderr__ -- the original stderr; don't touch!\n\
1381__displayhook__ -- the original displayhook; don't touch!\n\
1382__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001383\n\
1384Functions:\n\
1385\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001386displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001387excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001388exc_info() -- return thread-safe information about the current exception\n\
1389exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001390getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001391getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001392getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001393getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001394getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001395gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001396setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001397setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001398setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001399setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001400settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001401"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001402)
Fred Drakeccede592000-08-14 20:59:57 +00001403/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001404
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001405
1406PyDoc_STRVAR(flags__doc__,
1407"sys.flags\n\
1408\n\
1409Flags provided through command line arguments or environment vars.");
1410
1411static PyTypeObject FlagsType;
1412
1413static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 {"inspect", "-i"},
1416 {"interactive", "-i"},
1417 {"optimize", "-O or -OO"},
1418 {"dont_write_bytecode", "-B"},
1419 {"no_user_site", "-s"},
1420 {"no_site", "-S"},
1421 {"ignore_environment", "-E"},
1422 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 /* {"unbuffered", "-u"}, */
1424 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001425 {"bytes_warning", "-b"},
1426 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001427 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001428 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001430};
1431
1432static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001433 "sys.flags", /* name */
1434 flags__doc__, /* doc */
1435 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001436 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001437};
1438
1439static PyObject*
1440make_flags(void)
1441{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001442 int pos = 0;
1443 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001444
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001445 seq = PyStructSequence_New(&FlagsType);
1446 if (seq == NULL)
1447 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001448
1449#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001451
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 SetFlag(Py_InspectFlag);
1454 SetFlag(Py_InteractiveFlag);
1455 SetFlag(Py_OptimizeFlag);
1456 SetFlag(Py_DontWriteBytecodeFlag);
1457 SetFlag(Py_NoUserSiteDirectory);
1458 SetFlag(Py_NoSiteFlag);
1459 SetFlag(Py_IgnoreEnvironmentFlag);
1460 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* SetFlag(saw_unbuffered_flag); */
1462 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001463 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001464 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001465 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001466 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001467#undef SetFlag
1468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (PyErr_Occurred()) {
1470 return NULL;
1471 }
1472 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001473}
1474
Eric Smith0e5b5622009-02-06 01:32:42 +00001475PyDoc_STRVAR(version_info__doc__,
1476"sys.version_info\n\
1477\n\
1478Version information as a named tuple.");
1479
1480static PyTypeObject VersionInfoType;
1481
1482static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 {"major", "Major release number"},
1484 {"minor", "Minor release number"},
1485 {"micro", "Patch release number"},
1486 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1487 {"serial", "Serial release number"},
1488 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001489};
1490
1491static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 "sys.version_info", /* name */
1493 version_info__doc__, /* doc */
1494 version_info_fields, /* fields */
1495 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001496};
1497
1498static PyObject *
1499make_version_info(void)
1500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 PyObject *version_info;
1502 char *s;
1503 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 version_info = PyStructSequence_New(&VersionInfoType);
1506 if (version_info == NULL) {
1507 return NULL;
1508 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 /*
1511 * These release level checks are mutually exclusive and cover
1512 * the field, so don't get too fancy with the pre-processor!
1513 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001514#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001516#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001518#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001520#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001522#endif
1523
1524#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001526#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 SetIntItem(PY_MAJOR_VERSION);
1530 SetIntItem(PY_MINOR_VERSION);
1531 SetIntItem(PY_MICRO_VERSION);
1532 SetStrItem(s);
1533 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001534#undef SetIntItem
1535#undef SetStrItem
1536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (PyErr_Occurred()) {
1538 Py_CLEAR(version_info);
1539 return NULL;
1540 }
1541 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001542}
1543
Brett Cannon3adc7b72012-07-09 14:22:12 -04001544/* sys.implementation values */
1545#define NAME "cpython"
1546const char *_PySys_ImplName = NAME;
1547#define QUOTE(arg) #arg
1548#define STRIFY(name) QUOTE(name)
1549#define MAJOR STRIFY(PY_MAJOR_VERSION)
1550#define MINOR STRIFY(PY_MINOR_VERSION)
1551#define TAG NAME "-" MAJOR MINOR;
1552const char *_PySys_ImplCacheTag = TAG;
1553#undef NAME
1554#undef QUOTE
1555#undef STRIFY
1556#undef MAJOR
1557#undef MINOR
1558#undef TAG
1559
Barry Warsaw409da152012-06-03 16:18:47 -04001560static PyObject *
1561make_impl_info(PyObject *version_info)
1562{
1563 int res;
1564 PyObject *impl_info, *value, *ns;
1565
1566 impl_info = PyDict_New();
1567 if (impl_info == NULL)
1568 return NULL;
1569
1570 /* populate the dict */
1571
Brett Cannon3adc7b72012-07-09 14:22:12 -04001572 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001573 if (value == NULL)
1574 goto error;
1575 res = PyDict_SetItemString(impl_info, "name", value);
1576 Py_DECREF(value);
1577 if (res < 0)
1578 goto error;
1579
Brett Cannon3adc7b72012-07-09 14:22:12 -04001580 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001581 if (value == NULL)
1582 goto error;
1583 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1584 Py_DECREF(value);
1585 if (res < 0)
1586 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001587
1588 res = PyDict_SetItemString(impl_info, "version", version_info);
1589 if (res < 0)
1590 goto error;
1591
1592 value = PyLong_FromLong(PY_VERSION_HEX);
1593 if (value == NULL)
1594 goto error;
1595 res = PyDict_SetItemString(impl_info, "hexversion", value);
1596 Py_DECREF(value);
1597 if (res < 0)
1598 goto error;
1599
1600 /* dict ready */
1601
1602 ns = _PyNamespace_New(impl_info);
1603 Py_DECREF(impl_info);
1604 return ns;
1605
1606error:
1607 Py_CLEAR(impl_info);
1608 return NULL;
1609}
1610
Martin v. Löwis1a214512008-06-11 05:26:20 +00001611static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 PyModuleDef_HEAD_INIT,
1613 "sys",
1614 sys_doc,
1615 -1, /* multiple "initialization" just copies the module dict. */
1616 sys_methods,
1617 NULL,
1618 NULL,
1619 NULL,
1620 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001621};
1622
Guido van Rossum25ce5661997-08-02 03:10:38 +00001623PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001624_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001625{
Victor Stinner58049602013-07-22 22:40:00 +02001626 PyObject *m, *sysdict, *version_info;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001627
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001628 m = PyModule_Create(&sysmodule);
1629 if (m == NULL)
1630 return NULL;
1631 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001632#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001633 do { \
1634 int res; \
1635 PyObject *v = (value); \
1636 if (v == NULL) \
1637 return NULL; \
1638 res = PyDict_SetItemString(sysdict, key, v); \
1639 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001640 return NULL; \
1641 } \
1642 } while (0)
1643#define SET_SYS_FROM_STRING(key, value) \
1644 do { \
1645 int res; \
1646 PyObject *v = (value); \
1647 if (v == NULL) \
1648 return NULL; \
1649 res = PyDict_SetItemString(sysdict, key, v); \
1650 Py_DECREF(v); \
1651 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001652 return NULL; \
1653 } \
1654 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001655
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 /* Check that stdin is not a directory
1657 Using shell redirection, you can redirect stdin to a directory,
1658 crashing the Python interpreter. Catch this common mistake here
1659 and output a useful error message. Note that under MS Windows,
1660 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001661#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 {
1663 struct stat sb;
1664 if (fstat(fileno(stdin), &sb) == 0 &&
1665 S_ISDIR(sb.st_mode)) {
1666 /* There's nothing more we can do. */
1667 /* Py_FatalError() will core dump, so just exit. */
1668 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1669 exit(EXIT_FAILURE);
1670 }
1671 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001672#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001675
Victor Stinner8fea2522013-10-27 17:15:42 +01001676 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1677 PyDict_GetItemString(sysdict, "displayhook"));
1678 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1679 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001680 SET_SYS_FROM_STRING("version",
1681 PyUnicode_FromString(Py_GetVersion()));
1682 SET_SYS_FROM_STRING("hexversion",
1683 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001684 SET_SYS_FROM_STRING("_mercurial",
1685 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1686 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001687 SET_SYS_FROM_STRING("dont_write_bytecode",
1688 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1689 SET_SYS_FROM_STRING("api_version",
1690 PyLong_FromLong(PYTHON_API_VERSION));
1691 SET_SYS_FROM_STRING("copyright",
1692 PyUnicode_FromString(Py_GetCopyright()));
1693 SET_SYS_FROM_STRING("platform",
1694 PyUnicode_FromString(Py_GetPlatform()));
1695 SET_SYS_FROM_STRING("executable",
1696 PyUnicode_FromWideChar(
1697 Py_GetProgramFullPath(), -1));
1698 SET_SYS_FROM_STRING("prefix",
1699 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1700 SET_SYS_FROM_STRING("exec_prefix",
1701 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001702 SET_SYS_FROM_STRING("base_prefix",
1703 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1704 SET_SYS_FROM_STRING("base_exec_prefix",
1705 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001706 SET_SYS_FROM_STRING("maxsize",
1707 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1708 SET_SYS_FROM_STRING("float_info",
1709 PyFloat_GetInfo());
1710 SET_SYS_FROM_STRING("int_info",
1711 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001712 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001713 if (Hash_InfoType.tp_name == NULL) {
1714 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1715 return NULL;
1716 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001717 SET_SYS_FROM_STRING("hash_info",
1718 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001720 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 SET_SYS_FROM_STRING("builtin_module_names",
1722 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001723#if PY_BIG_ENDIAN
1724 SET_SYS_FROM_STRING("byteorder",
1725 PyUnicode_FromString("big"));
1726#else
1727 SET_SYS_FROM_STRING("byteorder",
1728 PyUnicode_FromString("little"));
1729#endif
Fred Drake099325e2000-08-14 15:47:03 +00001730
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001731#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 SET_SYS_FROM_STRING("dllhandle",
1733 PyLong_FromVoidPtr(PyWin_DLLhModule));
1734 SET_SYS_FROM_STRING("winver",
1735 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001736#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001737#ifdef ABIFLAGS
1738 SET_SYS_FROM_STRING("abiflags",
1739 PyUnicode_FromString(ABIFLAGS));
1740#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (warnoptions == NULL) {
1742 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02001743 if (warnoptions == NULL)
1744 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 }
1746 else {
1747 Py_INCREF(warnoptions);
1748 }
Victor Stinner8fea2522013-10-27 17:15:42 +01001749 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00001750
Victor Stinner8fea2522013-10-27 17:15:42 +01001751 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001752
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001754 if (VersionInfoType.tp_name == NULL) {
1755 if (PyStructSequence_InitType2(&VersionInfoType,
1756 &version_info_desc) < 0)
1757 return NULL;
1758 }
Barry Warsaw409da152012-06-03 16:18:47 -04001759 version_info = make_version_info();
1760 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001761 /* prevent user from creating new instances */
1762 VersionInfoType.tp_init = NULL;
1763 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001764
Barry Warsaw409da152012-06-03 16:18:47 -04001765 /* implementation */
1766 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1767
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001768 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001769 if (FlagsType.tp_name == 0) {
1770 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
1771 return NULL;
1772 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 SET_SYS_FROM_STRING("flags", make_flags());
1774 /* prevent user from creating new instances */
1775 FlagsType.tp_init = NULL;
1776 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001777
Eric Smithf7bb5782010-01-27 00:44:57 +00001778
1779#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 /* getwindowsversion */
1781 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02001782 if (PyStructSequence_InitType2(&WindowsVersionType,
1783 &windows_version_desc) < 0)
1784 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001785 /* prevent user from creating new instances */
1786 WindowsVersionType.tp_init = NULL;
1787 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001788#endif
1789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001791#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001792 SET_SYS_FROM_STRING("float_repr_style",
1793 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001794#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001795 SET_SYS_FROM_STRING("float_repr_style",
1796 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001797#endif
1798
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001799#ifdef WITH_THREAD
1800 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1801#endif
1802
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001803#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 if (PyErr_Occurred())
1805 return NULL;
1806 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001807}
1808
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001809static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001810makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 int i, n;
1813 const wchar_t *p;
1814 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001815
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 n = 1;
1817 p = path;
1818 while ((p = wcschr(p, delim)) != NULL) {
1819 n++;
1820 p++;
1821 }
1822 v = PyList_New(n);
1823 if (v == NULL)
1824 return NULL;
1825 for (i = 0; ; i++) {
1826 p = wcschr(path, delim);
1827 if (p == NULL)
1828 p = path + wcslen(path); /* End of string */
1829 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1830 if (w == NULL) {
1831 Py_DECREF(v);
1832 return NULL;
1833 }
1834 PyList_SetItem(v, i, w);
1835 if (*p == '\0')
1836 break;
1837 path = p+1;
1838 }
1839 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001840}
1841
1842void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001843PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PyObject *v;
1846 if ((v = makepathobject(path, DELIM)) == NULL)
1847 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01001848 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 Py_FatalError("can't assign sys.path");
1850 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001851}
1852
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001853static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001854makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001855{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001856 PyObject *av;
1857 if (argc <= 0 || argv == NULL) {
1858 /* Ensure at least one (empty) argument is seen */
1859 static wchar_t *empty_argv[1] = {L""};
1860 argv = empty_argv;
1861 argc = 1;
1862 }
1863 av = PyList_New(argc);
1864 if (av != NULL) {
1865 int i;
1866 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001867#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001869
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 /* argv[0] is the script pathname if known */
1871 if (i == 0) {
1872 char* fn = decc$translate_vms(argv[0]);
1873 if ((fn == (char *)0) || fn == (char *)-1)
1874 v = PyUnicode_FromString(argv[0]);
1875 else
1876 v = PyUnicode_FromString(
1877 decc$translate_vms(argv[0]));
1878 } else
1879 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001880#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001882#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 if (v == NULL) {
1884 Py_DECREF(av);
1885 av = NULL;
1886 break;
1887 }
1888 PyList_SetItem(av, i, v);
1889 }
1890 }
1891 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001892}
1893
Nick Coghland26c18a2010-08-17 13:06:11 +00001894#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1895 (argc > 0 && argv0 != NULL && \
1896 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001897
1898static void
1899sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001900{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001901 wchar_t *argv0;
1902 wchar_t *p = NULL;
1903 Py_ssize_t n = 0;
1904 PyObject *a;
1905 PyObject *path;
1906#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001907 wchar_t link[MAXPATHLEN+1];
1908 wchar_t argv0copy[2*MAXPATHLEN+1];
1909 int nr = 0;
1910#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001911#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001913#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001914 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001915#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001916
Victor Stinnerbd303c12013-11-07 23:07:29 +01001917 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001918 if (path == NULL)
1919 return;
1920
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001921 argv0 = argv[0];
1922
1923#ifdef HAVE_READLINK
1924 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1925 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1926 if (nr > 0) {
1927 /* It's a symlink */
1928 link[nr] = '\0';
1929 if (link[0] == SEP)
1930 argv0 = link; /* Link to absolute path */
1931 else if (wcschr(link, SEP) == NULL)
1932 ; /* Link without path */
1933 else {
1934 /* Must join(dirname(argv0), link) */
1935 wchar_t *q = wcsrchr(argv0, SEP);
1936 if (q == NULL)
1937 argv0 = link; /* argv0 without path */
1938 else {
Christian Heimes60a60672013-07-22 12:53:32 +02001939 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
1940 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001941 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02001942 wcsncpy(q+1, link, MAXPATHLEN);
1943 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001944 argv0 = argv0copy;
1945 }
1946 }
1947 }
1948#endif /* HAVE_READLINK */
1949#if SEP == '\\' /* Special case for MS filename syntax */
1950 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1951 wchar_t *q;
1952#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1953 /* This code here replaces the first element in argv with the full
1954 path that it represents. Under CE, there are no relative paths so
1955 the argument must be the full path anyway. */
1956 wchar_t *ptemp;
1957 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001958 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001959 fullpath,
1960 &ptemp)) {
1961 argv0 = fullpath;
1962 }
1963#endif
1964 p = wcsrchr(argv0, SEP);
1965 /* Test for alternate separator */
1966 q = wcsrchr(p ? p : argv0, '/');
1967 if (q != NULL)
1968 p = q;
1969 if (p != NULL) {
1970 n = p + 1 - argv0;
1971 if (n > 1 && p[-1] != ':')
1972 n--; /* Drop trailing separator */
1973 }
1974 }
1975#else /* All other filename syntaxes */
1976 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1977#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01001978 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001979 argv0 = fullpath;
1980 }
1981#endif
1982 p = wcsrchr(argv0, SEP);
1983 }
1984 if (p != NULL) {
1985 n = p + 1 - argv0;
1986#if SEP == '/' /* Special case for Unix filename syntax */
1987 if (n > 1)
1988 n--; /* Drop trailing separator */
1989#endif /* Unix */
1990 }
1991#endif /* All others */
1992 a = PyUnicode_FromWideChar(argv0, n);
1993 if (a == NULL)
1994 Py_FatalError("no mem for sys.path insertion");
1995 if (PyList_Insert(path, 0, a) < 0)
1996 Py_FatalError("sys.path.insert(0) failed");
1997 Py_DECREF(a);
1998}
1999
2000void
2001PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2002{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002004 if (av == NULL)
2005 Py_FatalError("no mem for sys.argv");
2006 if (PySys_SetObject("argv", av) != 0)
2007 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002008 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002009 if (updatepath)
2010 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002011}
Guido van Rossuma890e681998-05-12 14:59:24 +00002012
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002013void
2014PySys_SetArgv(int argc, wchar_t **argv)
2015{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002016 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002017}
2018
Victor Stinner14284c22010-04-23 12:02:30 +00002019/* Reimplementation of PyFile_WriteString() no calling indirectly
2020 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2021
2022static int
Victor Stinner79766632010-08-16 17:36:42 +00002023sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002024{
Victor Stinner79766632010-08-16 17:36:42 +00002025 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002027
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002028 if (file == NULL)
2029 return -1;
2030
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002031 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002032 if (writer == NULL)
2033 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 args = PyTuple_Pack(1, unicode);
2036 if (args == NULL)
2037 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002038
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 result = PyEval_CallObject(writer, args);
2040 if (result == NULL) {
2041 goto error;
2042 } else {
2043 err = 0;
2044 goto finally;
2045 }
Victor Stinner14284c22010-04-23 12:02:30 +00002046
2047error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002049finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002050 Py_XDECREF(writer);
2051 Py_XDECREF(args);
2052 Py_XDECREF(result);
2053 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002054}
2055
Victor Stinner79766632010-08-16 17:36:42 +00002056static int
2057sys_pyfile_write(const char *text, PyObject *file)
2058{
2059 PyObject *unicode = NULL;
2060 int err;
2061
2062 if (file == NULL)
2063 return -1;
2064
2065 unicode = PyUnicode_FromString(text);
2066 if (unicode == NULL)
2067 return -1;
2068
2069 err = sys_pyfile_write_unicode(unicode, file);
2070 Py_DECREF(unicode);
2071 return err;
2072}
Guido van Rossuma890e681998-05-12 14:59:24 +00002073
2074/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2075 Adapted from code submitted by Just van Rossum.
2076
2077 PySys_WriteStdout(format, ...)
2078 PySys_WriteStderr(format, ...)
2079
2080 The first function writes to sys.stdout; the second to sys.stderr. When
2081 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002082 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002083
Victor Stinner14284c22010-04-23 12:02:30 +00002084 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002085 signal handlers: they may raise a new exception whereas sys_write()
2086 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002087
Guido van Rossuma890e681998-05-12 14:59:24 +00002088 Both take a printf-style format string as their first argument followed
2089 by a variable length argument list determined by the format string.
2090
2091 *** WARNING ***
2092
2093 The format should limit the total size of the formatted output string to
2094 1000 bytes. In particular, this means that no unrestricted "%s" formats
2095 should occur; these should be limited using "%.<N>s where <N> is a
2096 decimal number calculated so that <N> plus the maximum size of other
2097 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2098 which can print hundreds of digits for very large numbers.
2099
2100 */
2101
2102static void
Victor Stinner09054372013-11-06 22:41:44 +01002103sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002104{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002105 PyObject *file;
2106 PyObject *error_type, *error_value, *error_traceback;
2107 char buffer[1001];
2108 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002109
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002111 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002112 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2113 if (sys_pyfile_write(buffer, file) != 0) {
2114 PyErr_Clear();
2115 fputs(buffer, fp);
2116 }
2117 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2118 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002119 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002120 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
2122 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002123}
2124
2125void
Guido van Rossuma890e681998-05-12 14:59:24 +00002126PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002129
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002131 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002133}
2134
2135void
Guido van Rossuma890e681998-05-12 14:59:24 +00002136PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002137{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002139
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002140 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002141 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002142 va_end(va);
2143}
2144
2145static void
Victor Stinner09054372013-11-06 22:41:44 +01002146sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002147{
2148 PyObject *file, *message;
2149 PyObject *error_type, *error_value, *error_traceback;
2150 char *utf8;
2151
2152 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002153 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002154 message = PyUnicode_FromFormatV(format, va);
2155 if (message != NULL) {
2156 if (sys_pyfile_write_unicode(message, file) != 0) {
2157 PyErr_Clear();
2158 utf8 = _PyUnicode_AsString(message);
2159 if (utf8 != NULL)
2160 fputs(utf8, fp);
2161 }
2162 Py_DECREF(message);
2163 }
2164 PyErr_Restore(error_type, error_value, error_traceback);
2165}
2166
2167void
2168PySys_FormatStdout(const char *format, ...)
2169{
2170 va_list va;
2171
2172 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002173 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002174 va_end(va);
2175}
2176
2177void
2178PySys_FormatStderr(const char *format, ...)
2179{
2180 va_list va;
2181
2182 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002183 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002184 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002185}