blob: 961657ec6197cec8d526652a835ae1b443d7d039 [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 *
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100370call_trampoline(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 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000409
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000410 if (arg == NULL)
411 arg = Py_None;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100412 result = call_trampoline(self, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000413 if (result == NULL) {
414 PyEval_SetProfile(NULL, NULL);
415 return -1;
416 }
417 Py_DECREF(result);
418 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000419}
420
421static int
422trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000423 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000424{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000425 PyObject *callback;
426 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000428 if (what == PyTrace_CALL)
429 callback = self;
430 else
431 callback = frame->f_trace;
432 if (callback == NULL)
433 return 0;
Victor Stinnerfdeb6ec2013-12-13 02:01:38 +0100434 result = call_trampoline(callback, frame, what, arg);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (result == NULL) {
436 PyEval_SetTrace(NULL, NULL);
437 Py_XDECREF(frame->f_trace);
438 frame->f_trace = NULL;
439 return -1;
440 }
441 if (result != Py_None) {
442 PyObject *temp = frame->f_trace;
443 frame->f_trace = NULL;
444 Py_XDECREF(temp);
445 frame->f_trace = result;
446 }
447 else {
448 Py_DECREF(result);
449 }
450 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000451}
Fred Draked0838392001-06-16 21:02:31 +0000452
Fred Drake8b4d01d2000-05-09 19:57:01 +0000453static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000454sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (trace_init() == -1)
457 return NULL;
458 if (args == Py_None)
459 PyEval_SetTrace(NULL, NULL);
460 else
461 PyEval_SetTrace(trace_trampoline, args);
462 Py_INCREF(Py_None);
463 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000464}
465
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000466PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000467"settrace(function)\n\
468\n\
469Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000470function call. See the debugger chapter in the library manual."
471);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000472
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000473static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000474sys_gettrace(PyObject *self, PyObject *args)
475{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 PyThreadState *tstate = PyThreadState_GET();
477 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000478
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000479 if (temp == NULL)
480 temp = Py_None;
481 Py_INCREF(temp);
482 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000483}
484
485PyDoc_STRVAR(gettrace_doc,
486"gettrace()\n\
487\n\
488Return the global debug tracing function set with sys.settrace.\n\
489See the debugger chapter in the library manual."
490);
491
492static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000493sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000494{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000495 if (trace_init() == -1)
496 return NULL;
497 if (args == Py_None)
498 PyEval_SetProfile(NULL, NULL);
499 else
500 PyEval_SetProfile(profile_trampoline, args);
501 Py_INCREF(Py_None);
502 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000503}
504
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000505PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000506"setprofile(function)\n\
507\n\
508Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000509and return. See the profiler chapter in the library manual."
510);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000511
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000512static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000513sys_getprofile(PyObject *self, PyObject *args)
514{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000515 PyThreadState *tstate = PyThreadState_GET();
516 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000517
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000518 if (temp == NULL)
519 temp = Py_None;
520 Py_INCREF(temp);
521 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000522}
523
524PyDoc_STRVAR(getprofile_doc,
525"getprofile()\n\
526\n\
527Return the profiling function set with sys.setprofile.\n\
528See the profiler chapter in the library manual."
529);
530
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000531static int _check_interval = 100;
532
Christian Heimes9bd667a2008-01-20 15:14:11 +0000533static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000534sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 if (PyErr_WarnEx(PyExc_DeprecationWarning,
537 "sys.getcheckinterval() and sys.setcheckinterval() "
538 "are deprecated. Use sys.setswitchinterval() "
539 "instead.", 1) < 0)
540 return NULL;
541 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
542 return NULL;
543 Py_INCREF(Py_None);
544 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000545}
546
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000547PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000548"setcheckinterval(n)\n\
549\n\
550Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000551n instructions. This also affects how often thread switches occur."
552);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000553
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000554static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000555sys_getcheckinterval(PyObject *self, PyObject *args)
556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 if (PyErr_WarnEx(PyExc_DeprecationWarning,
558 "sys.getcheckinterval() and sys.setcheckinterval() "
559 "are deprecated. Use sys.getswitchinterval() "
560 "instead.", 1) < 0)
561 return NULL;
562 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000563}
564
565PyDoc_STRVAR(getcheckinterval_doc,
566"getcheckinterval() -> current check interval; see setcheckinterval()."
567);
568
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000569#ifdef WITH_THREAD
570static PyObject *
571sys_setswitchinterval(PyObject *self, PyObject *args)
572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 double d;
574 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
575 return NULL;
576 if (d <= 0.0) {
577 PyErr_SetString(PyExc_ValueError,
578 "switch interval must be strictly positive");
579 return NULL;
580 }
581 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
582 Py_INCREF(Py_None);
583 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000584}
585
586PyDoc_STRVAR(setswitchinterval_doc,
587"setswitchinterval(n)\n\
588\n\
589Set the ideal thread switching delay inside the Python interpreter\n\
590The actual frequency of switching threads can be lower if the\n\
591interpreter executes long sequences of uninterruptible code\n\
592(this is implementation-specific and workload-dependent).\n\
593\n\
594The parameter must represent the desired switching delay in seconds\n\
595A typical value is 0.005 (5 milliseconds)."
596);
597
598static PyObject *
599sys_getswitchinterval(PyObject *self, PyObject *args)
600{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000602}
603
604PyDoc_STRVAR(getswitchinterval_doc,
605"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
606);
607
608#endif /* WITH_THREAD */
609
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000610#ifdef WITH_TSC
611static PyObject *
612sys_settscdump(PyObject *self, PyObject *args)
613{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000614 int bool;
615 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000616
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000617 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
618 return NULL;
619 if (bool)
620 tstate->interp->tscdump = 1;
621 else
622 tstate->interp->tscdump = 0;
623 Py_INCREF(Py_None);
624 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000625
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000626}
627
Tim Peters216b78b2006-01-06 02:40:53 +0000628PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000629"settscdump(bool)\n\
630\n\
631If true, tell the Python interpreter to dump VM measurements to\n\
632stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000633processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000634);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000635#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000636
Tim Peterse5e065b2003-07-06 18:36:54 +0000637static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000638sys_setrecursionlimit(PyObject *self, PyObject *args)
639{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 int new_limit;
641 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
642 return NULL;
643 if (new_limit <= 0) {
644 PyErr_SetString(PyExc_ValueError,
645 "recursion limit must be positive");
646 return NULL;
647 }
648 Py_SetRecursionLimit(new_limit);
649 Py_INCREF(Py_None);
650 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000651}
652
Mark Dickinsondc787d22010-05-23 13:33:13 +0000653static PyTypeObject Hash_InfoType;
654
655PyDoc_STRVAR(hash_info_doc,
656"hash_info\n\
657\n\
658A struct sequence providing parameters used for computing\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +0100659hashes. The attributes are read only.");
Mark Dickinsondc787d22010-05-23 13:33:13 +0000660
661static PyStructSequence_Field hash_info_fields[] = {
662 {"width", "width of the type used for hashing, in bits"},
663 {"modulus", "prime number giving the modulus on which the hash "
664 "function is based"},
665 {"inf", "value to be used for hash of a positive infinity"},
666 {"nan", "value to be used for hash of a nan"},
667 {"imag", "multiplier used for the imaginary part of a complex number"},
Christian Heimes985ecdc2013-11-20 11:46:18 +0100668 {"algorithm", "name of the algorithm for hashing of str, bytes and "
669 "memoryviews"},
670 {"hash_bits", "internal output size of hash algorithm"},
671 {"seed_bits", "seed size of hash algorithm"},
672 {"cutoff", "small string optimization cutoff"},
Mark Dickinsondc787d22010-05-23 13:33:13 +0000673 {NULL, NULL}
674};
675
676static PyStructSequence_Desc hash_info_desc = {
677 "sys.hash_info",
678 hash_info_doc,
679 hash_info_fields,
Christian Heimes985ecdc2013-11-20 11:46:18 +0100680 9,
Mark Dickinsondc787d22010-05-23 13:33:13 +0000681};
682
Matthias Klosed885e952010-07-06 10:53:30 +0000683static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000684get_hash_info(void)
685{
686 PyObject *hash_info;
687 int field = 0;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100688 PyHash_FuncDef *hashfunc;
Mark Dickinsondc787d22010-05-23 13:33:13 +0000689 hash_info = PyStructSequence_New(&Hash_InfoType);
690 if (hash_info == NULL)
691 return NULL;
Christian Heimes985ecdc2013-11-20 11:46:18 +0100692 hashfunc = PyHash_GetFuncDef();
Mark Dickinsondc787d22010-05-23 13:33:13 +0000693 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000694 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000695 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000696 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000697 PyStructSequence_SET_ITEM(hash_info, field++,
698 PyLong_FromLong(_PyHASH_INF));
699 PyStructSequence_SET_ITEM(hash_info, field++,
700 PyLong_FromLong(_PyHASH_NAN));
701 PyStructSequence_SET_ITEM(hash_info, field++,
702 PyLong_FromLong(_PyHASH_IMAG));
Christian Heimes985ecdc2013-11-20 11:46:18 +0100703 PyStructSequence_SET_ITEM(hash_info, field++,
704 PyUnicode_FromString(hashfunc->name));
705 PyStructSequence_SET_ITEM(hash_info, field++,
706 PyLong_FromLong(hashfunc->hash_bits));
707 PyStructSequence_SET_ITEM(hash_info, field++,
708 PyLong_FromLong(hashfunc->seed_bits));
709 PyStructSequence_SET_ITEM(hash_info, field++,
710 PyLong_FromLong(Py_HASH_CUTOFF));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000711 if (PyErr_Occurred()) {
712 Py_CLEAR(hash_info);
713 return NULL;
714 }
715 return hash_info;
716}
717
718
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000719PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000720"setrecursionlimit(n)\n\
721\n\
722Set the maximum depth of the Python interpreter stack to n. This\n\
723limit prevents infinite recursion from causing an overflow of the C\n\
724stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000725dependent."
726);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000727
728static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000729sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000732}
733
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000734PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000735"getrecursionlimit()\n\
736\n\
737Return the current value of the recursion limit, the maximum depth\n\
738of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000739recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000740);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000741
Mark Hammond8696ebc2002-10-08 02:44:31 +0000742#ifdef MS_WINDOWS
743PyDoc_STRVAR(getwindowsversion_doc,
744"getwindowsversion()\n\
745\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000746Return information about the running version of Windows as a named tuple.\n\
747The members are named: major, minor, build, platform, service_pack,\n\
748service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200749backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000750All elements are numbers, except service_pack which is a string. Platform\n\
751may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
7523 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
753controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000754);
755
Eric Smithf7bb5782010-01-27 00:44:57 +0000756static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
757
758static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 {"major", "Major version number"},
760 {"minor", "Minor version number"},
761 {"build", "Build number"},
762 {"platform", "Operating system platform"},
763 {"service_pack", "Latest Service Pack installed on the system"},
764 {"service_pack_major", "Service Pack major version number"},
765 {"service_pack_minor", "Service Pack minor version number"},
766 {"suite_mask", "Bit mask identifying available product suites"},
767 {"product_type", "System product type"},
768 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000769};
770
771static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000772 "sys.getwindowsversion", /* name */
773 getwindowsversion_doc, /* doc */
774 windows_version_fields, /* fields */
775 5 /* For backward compatibility,
776 only the first 5 items are accessible
777 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000778};
779
Mark Hammond8696ebc2002-10-08 02:44:31 +0000780static PyObject *
781sys_getwindowsversion(PyObject *self)
782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 PyObject *version;
784 int pos = 0;
785 OSVERSIONINFOEX ver;
786 ver.dwOSVersionInfoSize = sizeof(ver);
787 if (!GetVersionEx((OSVERSIONINFO*) &ver))
788 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000789
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000790 version = PyStructSequence_New(&WindowsVersionType);
791 if (version == NULL)
792 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
795 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
796 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
797 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
798 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
799 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
800 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
801 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
802 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000803
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000804 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000805}
806
807#endif /* MS_WINDOWS */
808
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000809#ifdef HAVE_DLOPEN
810static PyObject *
811sys_setdlopenflags(PyObject *self, PyObject *args)
812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 int new_val;
814 PyThreadState *tstate = PyThreadState_GET();
815 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
816 return NULL;
817 if (!tstate)
818 return NULL;
819 tstate->interp->dlopenflags = new_val;
820 Py_INCREF(Py_None);
821 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000822}
823
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000824PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000825"setdlopenflags(n) -> None\n\
826\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000827Set the flags used by the interpreter for dlopen calls, such as when the\n\
828interpreter loads extension modules. Among other things, this will enable\n\
829a lazy resolving of symbols when importing a module, if called as\n\
830sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400831sys.setdlopenflags(os.RTLD_GLOBAL). Symbolic names for the flag modules\n\
Victor Stinnerf4afa432011-10-31 11:48:09 +0100832can be found in the os module (RTLD_xxx constants, e.g. os.RTLD_LAZY).");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000833
834static PyObject *
835sys_getdlopenflags(PyObject *self, PyObject *args)
836{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000837 PyThreadState *tstate = PyThreadState_GET();
838 if (!tstate)
839 return NULL;
840 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000841}
842
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000843PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000844"getdlopenflags() -> int\n\
845\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000846Return the current value of the flags that are used for dlopen calls.\n\
Andrew Kuchlingc61b9132013-06-21 10:58:41 -0400847The flag constants are defined in the os module.");
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000850
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000851#ifdef USE_MALLOPT
852/* Link with -lmalloc (or -lmpc) on an SGI */
853#include <malloc.h>
854
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000855static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000856sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000857{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 int flag;
859 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
860 return NULL;
861 mallopt(M_DEBUG, flag);
862 Py_INCREF(Py_None);
863 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000864}
865#endif /* USE_MALLOPT */
866
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000867static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000868sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000870 PyObject *res = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500871 static PyObject *gc_head_size = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 static char *kwlist[] = {"object", "default", 0};
873 PyObject *o, *dflt = NULL;
874 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000875
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000876 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
877 kwlist, &o, &dflt))
878 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000880 /* Initialize static variable for GC head size */
881 if (gc_head_size == NULL) {
882 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
883 if (gc_head_size == NULL)
884 return NULL;
885 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000887 /* Make sure the type is initialized. float gets initialized late */
888 if (PyType_Ready(Py_TYPE(o)) < 0)
889 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000890
Benjamin Petersonce798522012-01-22 11:24:29 -0500891 method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 if (method == NULL) {
893 if (!PyErr_Occurred())
894 PyErr_Format(PyExc_TypeError,
895 "Type %.100s doesn't define __sizeof__",
896 Py_TYPE(o)->tp_name);
897 }
898 else {
899 res = PyObject_CallFunctionObjArgs(method, NULL);
900 Py_DECREF(method);
901 }
902
903 /* Has a default value been given */
904 if ((res == NULL) && (dflt != NULL) &&
905 PyErr_ExceptionMatches(PyExc_TypeError))
906 {
907 PyErr_Clear();
908 Py_INCREF(dflt);
909 return dflt;
910 }
911 else if (res == NULL)
912 return res;
913
914 /* add gc_head size */
915 if (PyObject_IS_GC(o)) {
916 PyObject *tmp = res;
917 res = PyNumber_Add(tmp, gc_head_size);
918 Py_DECREF(tmp);
919 }
920 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000921}
922
923PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000924"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000925\n\
926Return the size of object in bytes.");
927
928static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000929sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000930{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000932}
933
Tim Peters4be93d02002-07-07 19:59:50 +0000934#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000935static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000936sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000937{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000938 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000939}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000940#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000941
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000942PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000943"getrefcount(object) -> integer\n\
944\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000945Return the reference count of object. The count returned is generally\n\
946one higher than you might expect, because it includes the (temporary)\n\
947reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000948);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000949
Antoine Pitrouf9d0b122012-12-09 14:28:26 +0100950static PyObject *
951sys_getallocatedblocks(PyObject *self)
952{
953 return PyLong_FromSsize_t(_Py_GetAllocatedBlocks());
954}
955
956PyDoc_STRVAR(getallocatedblocks_doc,
957"getallocatedblocks() -> integer\n\
958\n\
959Return the number of memory blocks currently allocated, regardless of their\n\
960size."
961);
962
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000963#ifdef COUNT_ALLOCS
964static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000965sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000966{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000967 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000969 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000970}
971#endif
972
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000973PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000974"_getframe([depth]) -> frameobject\n\
975\n\
976Return a frame object from the call stack. If optional integer depth is\n\
977given, return the frame object that many calls below the top of the stack.\n\
978If that is deeper than the call stack, ValueError is raised. The default\n\
979for depth is zero, returning the frame at the top of the call stack.\n\
980\n\
981This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000982purposes only."
983);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000984
985static PyObject *
986sys_getframe(PyObject *self, PyObject *args)
987{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 PyFrameObject *f = PyThreadState_GET()->frame;
989 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000990
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
992 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000994 while (depth > 0 && f != NULL) {
995 f = f->f_back;
996 --depth;
997 }
998 if (f == NULL) {
999 PyErr_SetString(PyExc_ValueError,
1000 "call stack is not deep enough");
1001 return NULL;
1002 }
1003 Py_INCREF(f);
1004 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +00001005}
1006
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001007PyDoc_STRVAR(current_frames_doc,
1008"_current_frames() -> dictionary\n\
1009\n\
1010Return a dictionary mapping each current thread T's thread id to T's\n\
1011current stack frame.\n\
1012\n\
1013This function should be used for specialized purposes only."
1014);
1015
1016static PyObject *
1017sys_current_frames(PyObject *self, PyObject *noargs)
1018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001020}
1021
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001022PyDoc_STRVAR(call_tracing_doc,
1023"call_tracing(func, args) -> object\n\
1024\n\
1025Call func(*args), while tracing is enabled. The tracing state is\n\
1026saved, and restored afterwards. This is intended to be called from\n\
1027a debugger from a checkpoint, to recursively debug some other code."
1028);
1029
1030static PyObject *
1031sys_call_tracing(PyObject *self, PyObject *args)
1032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 PyObject *func, *funcargs;
1034 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
1035 return NULL;
1036 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +00001037}
1038
Jeremy Hylton985eba52003-02-05 23:13:00 +00001039PyDoc_STRVAR(callstats_doc,
1040"callstats() -> tuple of integers\n\
1041\n\
1042Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
1043when Python was built. Otherwise, return None.\n\
1044\n\
1045When enabled, this function returns detailed, implementation-specific\n\
1046details about the number of function calls executed. The return value is\n\
1047a 11-tuple where the entries in the tuple are counts of:\n\
10480. all function calls\n\
10491. calls to PyFunction_Type objects\n\
10502. PyFunction calls that do not create an argument tuple\n\
10513. PyFunction calls that do not create an argument tuple\n\
1052 and bypass PyEval_EvalCodeEx()\n\
10534. PyMethod calls\n\
10545. PyMethod calls on bound methods\n\
10556. PyType calls\n\
10567. PyCFunction calls\n\
10578. generator calls\n\
10589. All other calls\n\
105910. Number of stack pops performed by call_function()"
1060);
Barry Warsawb6a54d22000-12-06 21:47:46 +00001061
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001062#ifdef __cplusplus
1063extern "C" {
1064#endif
1065
David Malcolm49526f42012-06-22 14:55:41 -04001066static PyObject *
1067sys_debugmallocstats(PyObject *self, PyObject *args)
1068{
1069#ifdef WITH_PYMALLOC
1070 _PyObject_DebugMallocStats(stderr);
1071 fputc('\n', stderr);
1072#endif
1073 _PyObject_DebugTypeStats(stderr);
1074
1075 Py_RETURN_NONE;
1076}
1077PyDoc_STRVAR(debugmallocstats_doc,
1078"_debugmallocstats()\n\
1079\n\
1080Print summary info to stderr about the state of\n\
1081pymalloc's structures.\n\
1082\n\
1083In Py_DEBUG mode, also perform some expensive internal consistency\n\
1084checks.\n\
1085");
1086
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001087#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +00001088/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001089extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001090#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001091
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001092#ifdef DYNAMIC_EXECUTION_PROFILE
1093/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001094extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001095#endif
1096
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001097#ifdef __cplusplus
1098}
1099#endif
1100
Christian Heimes15ebc882008-02-04 18:48:49 +00001101static PyObject *
1102sys_clear_type_cache(PyObject* self, PyObject* args)
1103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 PyType_ClearCache();
1105 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001106}
1107
1108PyDoc_STRVAR(sys_clear_type_cache__doc__,
1109"_clear_type_cache() -> None\n\
1110Clear the internal type lookup cache.");
1111
1112
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001113static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 /* Might as well keep this in alphabetic order */
1115 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1116 callstats_doc},
1117 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1118 sys_clear_type_cache__doc__},
1119 {"_current_frames", sys_current_frames, METH_NOARGS,
1120 current_frames_doc},
1121 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1122 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1123 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1124 {"exit", sys_exit, METH_VARARGS, exit_doc},
1125 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1126 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001127#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1129 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001130#endif
Antoine Pitrouf9d0b122012-12-09 14:28:26 +01001131 {"getallocatedblocks", (PyCFunction)sys_getallocatedblocks, METH_NOARGS,
1132 getallocatedblocks_doc},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001133#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001134 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001135#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001136#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001137 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001138#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001139 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1140 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001141#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001143#endif
1144#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001145 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001146#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001147 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1148 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1149 getrecursionlimit_doc},
1150 {"getsizeof", (PyCFunction)sys_getsizeof,
1151 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1152 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001153#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001154 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1155 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001156#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001158#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001159 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001160#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001161 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1162 setcheckinterval_doc},
1163 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1164 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001165#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001166 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1167 setswitchinterval_doc},
1168 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1169 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001170#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001171#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001172 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1173 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001174#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1176 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1177 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1178 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001179#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001180 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001181#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 {"settrace", sys_settrace, METH_O, settrace_doc},
1183 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1184 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
David Malcolm49526f42012-06-22 14:55:41 -04001185 {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
1186 debugmallocstats_doc},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001187 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001188};
1189
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001190static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001191list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001193 PyObject *list = PyList_New(0);
1194 int i;
1195 if (list == NULL)
1196 return NULL;
1197 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1198 PyObject *name = PyUnicode_FromString(
1199 PyImport_Inittab[i].name);
1200 if (name == NULL)
1201 break;
1202 PyList_Append(list, name);
1203 Py_DECREF(name);
1204 }
1205 if (PyList_Sort(list) != 0) {
1206 Py_DECREF(list);
1207 list = NULL;
1208 }
1209 if (list) {
1210 PyObject *v = PyList_AsTuple(list);
1211 Py_DECREF(list);
1212 list = v;
1213 }
1214 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001215}
1216
Guido van Rossum23fff912000-12-15 22:02:05 +00001217static PyObject *warnoptions = NULL;
1218
1219void
1220PySys_ResetWarnOptions(void)
1221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001222 if (warnoptions == NULL || !PyList_Check(warnoptions))
1223 return;
1224 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001225}
1226
1227void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001228PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1231 Py_XDECREF(warnoptions);
1232 warnoptions = PyList_New(0);
1233 if (warnoptions == NULL)
1234 return;
1235 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001236 PyList_Append(warnoptions, unicode);
1237}
1238
1239void
1240PySys_AddWarnOption(const wchar_t *s)
1241{
1242 PyObject *unicode;
1243 unicode = PyUnicode_FromWideChar(s, -1);
1244 if (unicode == NULL)
1245 return;
1246 PySys_AddWarnOptionUnicode(unicode);
1247 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001248}
1249
Christian Heimes33fe8092008-04-13 13:53:33 +00001250int
1251PySys_HasWarnOptions(void)
1252{
1253 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1254}
1255
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001256static PyObject *xoptions = NULL;
1257
1258static PyObject *
1259get_xoptions(void)
1260{
1261 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1262 Py_XDECREF(xoptions);
1263 xoptions = PyDict_New();
1264 }
1265 return xoptions;
1266}
1267
1268void
1269PySys_AddXOption(const wchar_t *s)
1270{
1271 PyObject *opts;
1272 PyObject *name = NULL, *value = NULL;
1273 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001274
1275 opts = get_xoptions();
1276 if (opts == NULL)
1277 goto error;
1278
1279 name_end = wcschr(s, L'=');
1280 if (!name_end) {
1281 name = PyUnicode_FromWideChar(s, -1);
1282 value = Py_True;
1283 Py_INCREF(value);
1284 }
1285 else {
1286 name = PyUnicode_FromWideChar(s, name_end - s);
1287 value = PyUnicode_FromWideChar(name_end + 1, -1);
1288 }
1289 if (name == NULL || value == NULL)
1290 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001291 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001292 Py_DECREF(name);
1293 Py_DECREF(value);
1294 return;
1295
1296error:
1297 Py_XDECREF(name);
1298 Py_XDECREF(value);
1299 /* No return value, therefore clear error state if possible */
1300 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1301 PyErr_Clear();
1302}
1303
1304PyObject *
1305PySys_GetXOptions(void)
1306{
1307 return get_xoptions();
1308}
1309
Guido van Rossum40552d01998-08-06 03:34:39 +00001310/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1311 Two literals concatenated works just fine. If you have a K&R compiler
1312 or other abomination that however *does* understand longer strings,
1313 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001314PyDoc_VAR(sys_doc) =
1315PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001316"This module provides access to some objects used or maintained by the\n\
1317interpreter and to functions that interact strongly with the interpreter.\n\
1318\n\
1319Dynamic objects:\n\
1320\n\
1321argv -- command line arguments; argv[0] is the script pathname if known\n\
1322path -- module search path; path[0] is the script directory, else ''\n\
1323modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001324\n\
1325displayhook -- called to show results in an interactive session\n\
1326excepthook -- called to handle any uncaught exception other than SystemExit\n\
1327 To customize printing in an interactive session or to install a custom\n\
1328 top-level exception handler, assign other functions to replace these.\n\
1329\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001330stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001331stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001332stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001333 By assigning other file objects (or objects that behave like files)\n\
1334 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001335\n\
1336last_type -- type of last uncaught exception\n\
1337last_value -- value of last uncaught exception\n\
1338last_traceback -- traceback of last uncaught exception\n\
1339 These three are only available in an interactive session after a\n\
1340 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001341"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001342)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001343/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001344PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001345"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001346Static objects:\n\
1347\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001348builtin_module_names -- tuple of module names built into this interpreter\n\
1349copyright -- copyright notice pertaining to this interpreter\n\
1350exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen4b0eab62012-02-02 21:23:15 +02001351executable -- absolute path of the executable binary of the Python interpreter\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001352float_info -- a struct sequence with information about the float implementation.\n\
1353float_repr_style -- string indicating the style of repr() output for floats\n\
Christian Heimes985ecdc2013-11-20 11:46:18 +01001354hash_info -- a struct sequence with information about the hash algorithm.\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001355hexversion -- version information encoded as a single integer\n\
Barry Warsaw409da152012-06-03 16:18:47 -04001356implementation -- Python implementation information.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001357int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001358maxsize -- the largest supported length of containers.\n\
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001359maxunicode -- the value of the largest Unicode codepoint\n\
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001360platform -- platform identifier\n\
1361prefix -- prefix used to find the Python library\n\
1362thread_info -- a struct sequence with information about the thread implementation.\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001363version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001364version_info -- version information as a named tuple\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001365"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001366)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001367#ifdef MS_WINDOWS
1368/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001369PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001370"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001371winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001372"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001373)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001374#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001375PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001376"__stdin__ -- the original stdin; don't touch!\n\
1377__stdout__ -- the original stdout; don't touch!\n\
1378__stderr__ -- the original stderr; don't touch!\n\
1379__displayhook__ -- the original displayhook; don't touch!\n\
1380__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001381\n\
1382Functions:\n\
1383\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001384displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001385excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001386exc_info() -- return thread-safe information about the current exception\n\
1387exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001388getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001389getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001390getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001391getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001392getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001393gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001394setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001395setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001396setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001397setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001398settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001399"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001400)
Fred Drakeccede592000-08-14 20:59:57 +00001401/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001402
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001403
1404PyDoc_STRVAR(flags__doc__,
1405"sys.flags\n\
1406\n\
1407Flags provided through command line arguments or environment vars.");
1408
1409static PyTypeObject FlagsType;
1410
1411static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 {"debug", "-d"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 {"inspect", "-i"},
1414 {"interactive", "-i"},
1415 {"optimize", "-O or -OO"},
1416 {"dont_write_bytecode", "-B"},
1417 {"no_user_site", "-s"},
1418 {"no_site", "-S"},
1419 {"ignore_environment", "-E"},
1420 {"verbose", "-v"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /* {"unbuffered", "-u"}, */
1422 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001423 {"bytes_warning", "-b"},
1424 {"quiet", "-q"},
Georg Brandl09a7c722012-02-20 21:31:46 +01001425 {"hash_randomization", "-R"},
Christian Heimesad73a9c2013-08-10 16:36:18 +02001426 {"isolated", "-I"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001428};
1429
1430static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001431 "sys.flags", /* name */
1432 flags__doc__, /* doc */
1433 flags_fields, /* fields */
Christian Heimesad73a9c2013-08-10 16:36:18 +02001434 13
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001435};
1436
1437static PyObject*
1438make_flags(void)
1439{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 int pos = 0;
1441 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 seq = PyStructSequence_New(&FlagsType);
1444 if (seq == NULL)
1445 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001446
1447#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001449
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 SetFlag(Py_DebugFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 SetFlag(Py_InspectFlag);
1452 SetFlag(Py_InteractiveFlag);
1453 SetFlag(Py_OptimizeFlag);
1454 SetFlag(Py_DontWriteBytecodeFlag);
1455 SetFlag(Py_NoUserSiteDirectory);
1456 SetFlag(Py_NoSiteFlag);
1457 SetFlag(Py_IgnoreEnvironmentFlag);
1458 SetFlag(Py_VerboseFlag);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 /* SetFlag(saw_unbuffered_flag); */
1460 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001461 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001462 SetFlag(Py_QuietFlag);
Georg Brandl2daf6ae2012-02-20 19:54:16 +01001463 SetFlag(Py_HashRandomizationFlag);
Christian Heimesad73a9c2013-08-10 16:36:18 +02001464 SetFlag(Py_IsolatedFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001465#undef SetFlag
1466
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 if (PyErr_Occurred()) {
1468 return NULL;
1469 }
1470 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001471}
1472
Eric Smith0e5b5622009-02-06 01:32:42 +00001473PyDoc_STRVAR(version_info__doc__,
1474"sys.version_info\n\
1475\n\
1476Version information as a named tuple.");
1477
1478static PyTypeObject VersionInfoType;
1479
1480static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 {"major", "Major release number"},
1482 {"minor", "Minor release number"},
1483 {"micro", "Patch release number"},
1484 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1485 {"serial", "Serial release number"},
1486 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001487};
1488
1489static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 "sys.version_info", /* name */
1491 version_info__doc__, /* doc */
1492 version_info_fields, /* fields */
1493 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001494};
1495
1496static PyObject *
1497make_version_info(void)
1498{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001499 PyObject *version_info;
1500 char *s;
1501 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 version_info = PyStructSequence_New(&VersionInfoType);
1504 if (version_info == NULL) {
1505 return NULL;
1506 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001507
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001508 /*
1509 * These release level checks are mutually exclusive and cover
1510 * the field, so don't get too fancy with the pre-processor!
1511 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001512#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001514#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001516#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001518#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001520#endif
1521
1522#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001524#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001526
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 SetIntItem(PY_MAJOR_VERSION);
1528 SetIntItem(PY_MINOR_VERSION);
1529 SetIntItem(PY_MICRO_VERSION);
1530 SetStrItem(s);
1531 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001532#undef SetIntItem
1533#undef SetStrItem
1534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (PyErr_Occurred()) {
1536 Py_CLEAR(version_info);
1537 return NULL;
1538 }
1539 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001540}
1541
Brett Cannon3adc7b72012-07-09 14:22:12 -04001542/* sys.implementation values */
1543#define NAME "cpython"
1544const char *_PySys_ImplName = NAME;
1545#define QUOTE(arg) #arg
1546#define STRIFY(name) QUOTE(name)
1547#define MAJOR STRIFY(PY_MAJOR_VERSION)
1548#define MINOR STRIFY(PY_MINOR_VERSION)
1549#define TAG NAME "-" MAJOR MINOR;
1550const char *_PySys_ImplCacheTag = TAG;
1551#undef NAME
1552#undef QUOTE
1553#undef STRIFY
1554#undef MAJOR
1555#undef MINOR
1556#undef TAG
1557
Barry Warsaw409da152012-06-03 16:18:47 -04001558static PyObject *
1559make_impl_info(PyObject *version_info)
1560{
1561 int res;
1562 PyObject *impl_info, *value, *ns;
1563
1564 impl_info = PyDict_New();
1565 if (impl_info == NULL)
1566 return NULL;
1567
1568 /* populate the dict */
1569
Brett Cannon3adc7b72012-07-09 14:22:12 -04001570 value = PyUnicode_FromString(_PySys_ImplName);
Barry Warsaw409da152012-06-03 16:18:47 -04001571 if (value == NULL)
1572 goto error;
1573 res = PyDict_SetItemString(impl_info, "name", value);
1574 Py_DECREF(value);
1575 if (res < 0)
1576 goto error;
1577
Brett Cannon3adc7b72012-07-09 14:22:12 -04001578 value = PyUnicode_FromString(_PySys_ImplCacheTag);
Barry Warsaw409da152012-06-03 16:18:47 -04001579 if (value == NULL)
1580 goto error;
1581 res = PyDict_SetItemString(impl_info, "cache_tag", value);
1582 Py_DECREF(value);
1583 if (res < 0)
1584 goto error;
Barry Warsaw409da152012-06-03 16:18:47 -04001585
1586 res = PyDict_SetItemString(impl_info, "version", version_info);
1587 if (res < 0)
1588 goto error;
1589
1590 value = PyLong_FromLong(PY_VERSION_HEX);
1591 if (value == NULL)
1592 goto error;
1593 res = PyDict_SetItemString(impl_info, "hexversion", value);
1594 Py_DECREF(value);
1595 if (res < 0)
1596 goto error;
1597
1598 /* dict ready */
1599
1600 ns = _PyNamespace_New(impl_info);
1601 Py_DECREF(impl_info);
1602 return ns;
1603
1604error:
1605 Py_CLEAR(impl_info);
1606 return NULL;
1607}
1608
Martin v. Löwis1a214512008-06-11 05:26:20 +00001609static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 PyModuleDef_HEAD_INIT,
1611 "sys",
1612 sys_doc,
1613 -1, /* multiple "initialization" just copies the module dict. */
1614 sys_methods,
1615 NULL,
1616 NULL,
1617 NULL,
1618 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001619};
1620
Guido van Rossum25ce5661997-08-02 03:10:38 +00001621PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001622_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001623{
Victor Stinner58049602013-07-22 22:40:00 +02001624 PyObject *m, *sysdict, *version_info;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 m = PyModule_Create(&sysmodule);
1627 if (m == NULL)
1628 return NULL;
1629 sysdict = PyModule_GetDict(m);
Victor Stinner8fea2522013-10-27 17:15:42 +01001630#define SET_SYS_FROM_STRING_BORROW(key, value) \
Victor Stinner58049602013-07-22 22:40:00 +02001631 do { \
1632 int res; \
1633 PyObject *v = (value); \
1634 if (v == NULL) \
1635 return NULL; \
1636 res = PyDict_SetItemString(sysdict, key, v); \
1637 if (res < 0) { \
Victor Stinner8fea2522013-10-27 17:15:42 +01001638 return NULL; \
1639 } \
1640 } while (0)
1641#define SET_SYS_FROM_STRING(key, value) \
1642 do { \
1643 int res; \
1644 PyObject *v = (value); \
1645 if (v == NULL) \
1646 return NULL; \
1647 res = PyDict_SetItemString(sysdict, key, v); \
1648 Py_DECREF(v); \
1649 if (res < 0) { \
Victor Stinner58049602013-07-22 22:40:00 +02001650 return NULL; \
1651 } \
1652 } while (0)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001653
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001654 /* Check that stdin is not a directory
1655 Using shell redirection, you can redirect stdin to a directory,
1656 crashing the Python interpreter. Catch this common mistake here
1657 and output a useful error message. Note that under MS Windows,
1658 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001659#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 {
1661 struct stat sb;
1662 if (fstat(fileno(stdin), &sb) == 0 &&
1663 S_ISDIR(sb.st_mode)) {
1664 /* There's nothing more we can do. */
1665 /* Py_FatalError() will core dump, so just exit. */
1666 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1667 exit(EXIT_FAILURE);
1668 }
1669 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001670#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001672 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001673
Victor Stinner8fea2522013-10-27 17:15:42 +01001674 SET_SYS_FROM_STRING_BORROW("__displayhook__",
1675 PyDict_GetItemString(sysdict, "displayhook"));
1676 SET_SYS_FROM_STRING_BORROW("__excepthook__",
1677 PyDict_GetItemString(sysdict, "excepthook"));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 SET_SYS_FROM_STRING("version",
1679 PyUnicode_FromString(Py_GetVersion()));
1680 SET_SYS_FROM_STRING("hexversion",
1681 PyLong_FromLong(PY_VERSION_HEX));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001682 SET_SYS_FROM_STRING("_mercurial",
1683 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1684 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 SET_SYS_FROM_STRING("dont_write_bytecode",
1686 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1687 SET_SYS_FROM_STRING("api_version",
1688 PyLong_FromLong(PYTHON_API_VERSION));
1689 SET_SYS_FROM_STRING("copyright",
1690 PyUnicode_FromString(Py_GetCopyright()));
1691 SET_SYS_FROM_STRING("platform",
1692 PyUnicode_FromString(Py_GetPlatform()));
1693 SET_SYS_FROM_STRING("executable",
1694 PyUnicode_FromWideChar(
1695 Py_GetProgramFullPath(), -1));
1696 SET_SYS_FROM_STRING("prefix",
1697 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1698 SET_SYS_FROM_STRING("exec_prefix",
1699 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Vinay Sajip7ded1f02012-05-26 03:45:29 +01001700 SET_SYS_FROM_STRING("base_prefix",
1701 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1702 SET_SYS_FROM_STRING("base_exec_prefix",
1703 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 SET_SYS_FROM_STRING("maxsize",
1705 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1706 SET_SYS_FROM_STRING("float_info",
1707 PyFloat_GetInfo());
1708 SET_SYS_FROM_STRING("int_info",
1709 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001710 /* initialize hash_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001711 if (Hash_InfoType.tp_name == NULL) {
1712 if (PyStructSequence_InitType2(&Hash_InfoType, &hash_info_desc) < 0)
1713 return NULL;
1714 }
Mark Dickinsondc787d22010-05-23 13:33:13 +00001715 SET_SYS_FROM_STRING("hash_info",
1716 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001717 SET_SYS_FROM_STRING("maxunicode",
Ezio Melotti48a2f8f2011-09-29 00:18:19 +03001718 PyLong_FromLong(0x10FFFF));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 SET_SYS_FROM_STRING("builtin_module_names",
1720 list_builtin_module_names());
Christian Heimes743e0cd2012-10-17 23:52:17 +02001721#if PY_BIG_ENDIAN
1722 SET_SYS_FROM_STRING("byteorder",
1723 PyUnicode_FromString("big"));
1724#else
1725 SET_SYS_FROM_STRING("byteorder",
1726 PyUnicode_FromString("little"));
1727#endif
Fred Drake099325e2000-08-14 15:47:03 +00001728
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001729#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 SET_SYS_FROM_STRING("dllhandle",
1731 PyLong_FromVoidPtr(PyWin_DLLhModule));
1732 SET_SYS_FROM_STRING("winver",
1733 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001734#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001735#ifdef ABIFLAGS
1736 SET_SYS_FROM_STRING("abiflags",
1737 PyUnicode_FromString(ABIFLAGS));
1738#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001739 if (warnoptions == NULL) {
1740 warnoptions = PyList_New(0);
Victor Stinner58049602013-07-22 22:40:00 +02001741 if (warnoptions == NULL)
1742 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001743 }
1744 else {
1745 Py_INCREF(warnoptions);
1746 }
Victor Stinner8fea2522013-10-27 17:15:42 +01001747 SET_SYS_FROM_STRING_BORROW("warnoptions", warnoptions);
Tim Peters216b78b2006-01-06 02:40:53 +00001748
Victor Stinner8fea2522013-10-27 17:15:42 +01001749 SET_SYS_FROM_STRING_BORROW("_xoptions", get_xoptions());
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001750
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 /* version_info */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001752 if (VersionInfoType.tp_name == NULL) {
1753 if (PyStructSequence_InitType2(&VersionInfoType,
1754 &version_info_desc) < 0)
1755 return NULL;
1756 }
Barry Warsaw409da152012-06-03 16:18:47 -04001757 version_info = make_version_info();
1758 SET_SYS_FROM_STRING("version_info", version_info);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 /* prevent user from creating new instances */
1760 VersionInfoType.tp_init = NULL;
1761 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001762
Barry Warsaw409da152012-06-03 16:18:47 -04001763 /* implementation */
1764 SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));
1765
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 /* flags */
Victor Stinner1c8f0592013-07-22 22:24:54 +02001767 if (FlagsType.tp_name == 0) {
1768 if (PyStructSequence_InitType2(&FlagsType, &flags_desc) < 0)
1769 return NULL;
1770 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 SET_SYS_FROM_STRING("flags", make_flags());
1772 /* prevent user from creating new instances */
1773 FlagsType.tp_init = NULL;
1774 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001775
Eric Smithf7bb5782010-01-27 00:44:57 +00001776
1777#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* getwindowsversion */
1779 if (WindowsVersionType.tp_name == 0)
Victor Stinner1c8f0592013-07-22 22:24:54 +02001780 if (PyStructSequence_InitType2(&WindowsVersionType,
1781 &windows_version_desc) < 0)
1782 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 /* prevent user from creating new instances */
1784 WindowsVersionType.tp_init = NULL;
1785 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001786#endif
1787
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001788 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001789#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001790 SET_SYS_FROM_STRING("float_repr_style",
1791 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001792#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 SET_SYS_FROM_STRING("float_repr_style",
1794 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001795#endif
1796
Victor Stinnerd5c355c2011-04-30 14:53:09 +02001797#ifdef WITH_THREAD
1798 SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
1799#endif
1800
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001801#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001802 if (PyErr_Occurred())
1803 return NULL;
1804 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001805}
1806
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001807static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001808makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001809{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001810 int i, n;
1811 const wchar_t *p;
1812 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 n = 1;
1815 p = path;
1816 while ((p = wcschr(p, delim)) != NULL) {
1817 n++;
1818 p++;
1819 }
1820 v = PyList_New(n);
1821 if (v == NULL)
1822 return NULL;
1823 for (i = 0; ; i++) {
1824 p = wcschr(path, delim);
1825 if (p == NULL)
1826 p = path + wcslen(path); /* End of string */
1827 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1828 if (w == NULL) {
1829 Py_DECREF(v);
1830 return NULL;
1831 }
1832 PyList_SetItem(v, i, w);
1833 if (*p == '\0')
1834 break;
1835 path = p+1;
1836 }
1837 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001838}
1839
1840void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001841PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001842{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001843 PyObject *v;
1844 if ((v = makepathobject(path, DELIM)) == NULL)
1845 Py_FatalError("can't create sys.path");
Victor Stinnerbd303c12013-11-07 23:07:29 +01001846 if (_PySys_SetObjectId(&PyId_path, v) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 Py_FatalError("can't assign sys.path");
1848 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001849}
1850
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001851static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001852makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001853{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001854 PyObject *av;
1855 if (argc <= 0 || argv == NULL) {
1856 /* Ensure at least one (empty) argument is seen */
1857 static wchar_t *empty_argv[1] = {L""};
1858 argv = empty_argv;
1859 argc = 1;
1860 }
1861 av = PyList_New(argc);
1862 if (av != NULL) {
1863 int i;
1864 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001865#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 /* argv[0] is the script pathname if known */
1869 if (i == 0) {
1870 char* fn = decc$translate_vms(argv[0]);
1871 if ((fn == (char *)0) || fn == (char *)-1)
1872 v = PyUnicode_FromString(argv[0]);
1873 else
1874 v = PyUnicode_FromString(
1875 decc$translate_vms(argv[0]));
1876 } else
1877 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001878#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001880#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001881 if (v == NULL) {
1882 Py_DECREF(av);
1883 av = NULL;
1884 break;
1885 }
1886 PyList_SetItem(av, i, v);
1887 }
1888 }
1889 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001890}
1891
Nick Coghland26c18a2010-08-17 13:06:11 +00001892#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1893 (argc > 0 && argv0 != NULL && \
1894 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001895
1896static void
1897sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001898{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001899 wchar_t *argv0;
1900 wchar_t *p = NULL;
1901 Py_ssize_t n = 0;
1902 PyObject *a;
1903 PyObject *path;
1904#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001905 wchar_t link[MAXPATHLEN+1];
1906 wchar_t argv0copy[2*MAXPATHLEN+1];
1907 int nr = 0;
1908#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001909#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001911#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001913#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001914
Victor Stinnerbd303c12013-11-07 23:07:29 +01001915 path = _PySys_GetObjectId(&PyId_path);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001916 if (path == NULL)
1917 return;
1918
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001919 argv0 = argv[0];
1920
1921#ifdef HAVE_READLINK
1922 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1923 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1924 if (nr > 0) {
1925 /* It's a symlink */
1926 link[nr] = '\0';
1927 if (link[0] == SEP)
1928 argv0 = link; /* Link to absolute path */
1929 else if (wcschr(link, SEP) == NULL)
1930 ; /* Link without path */
1931 else {
1932 /* Must join(dirname(argv0), link) */
1933 wchar_t *q = wcsrchr(argv0, SEP);
1934 if (q == NULL)
1935 argv0 = link; /* argv0 without path */
1936 else {
Christian Heimes60a60672013-07-22 12:53:32 +02001937 /* Must make a copy, argv0copy has room for 2 * MAXPATHLEN */
1938 wcsncpy(argv0copy, argv0, MAXPATHLEN);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001939 q = wcsrchr(argv0copy, SEP);
Christian Heimes60a60672013-07-22 12:53:32 +02001940 wcsncpy(q+1, link, MAXPATHLEN);
1941 q[MAXPATHLEN + 1] = L'\0';
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001942 argv0 = argv0copy;
1943 }
1944 }
1945 }
1946#endif /* HAVE_READLINK */
1947#if SEP == '\\' /* Special case for MS filename syntax */
1948 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1949 wchar_t *q;
1950#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1951 /* This code here replaces the first element in argv with the full
1952 path that it represents. Under CE, there are no relative paths so
1953 the argument must be the full path anyway. */
1954 wchar_t *ptemp;
1955 if (GetFullPathNameW(argv0,
Victor Stinner63941882011-09-29 00:42:28 +02001956 Py_ARRAY_LENGTH(fullpath),
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001957 fullpath,
1958 &ptemp)) {
1959 argv0 = fullpath;
1960 }
1961#endif
1962 p = wcsrchr(argv0, SEP);
1963 /* Test for alternate separator */
1964 q = wcsrchr(p ? p : argv0, '/');
1965 if (q != NULL)
1966 p = q;
1967 if (p != NULL) {
1968 n = p + 1 - argv0;
1969 if (n > 1 && p[-1] != ':')
1970 n--; /* Drop trailing separator */
1971 }
1972 }
1973#else /* All other filename syntaxes */
1974 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1975#if defined(HAVE_REALPATH)
Victor Stinner23847142013-11-15 17:33:43 +01001976 if (_Py_wrealpath(argv0, fullpath, Py_ARRAY_LENGTH(fullpath))) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001977 argv0 = fullpath;
1978 }
1979#endif
1980 p = wcsrchr(argv0, SEP);
1981 }
1982 if (p != NULL) {
1983 n = p + 1 - argv0;
1984#if SEP == '/' /* Special case for Unix filename syntax */
1985 if (n > 1)
1986 n--; /* Drop trailing separator */
1987#endif /* Unix */
1988 }
1989#endif /* All others */
1990 a = PyUnicode_FromWideChar(argv0, n);
1991 if (a == NULL)
1992 Py_FatalError("no mem for sys.path insertion");
1993 if (PyList_Insert(path, 0, a) < 0)
1994 Py_FatalError("sys.path.insert(0) failed");
1995 Py_DECREF(a);
1996}
1997
1998void
1999PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
2000{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002001 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 if (av == NULL)
2003 Py_FatalError("no mem for sys.argv");
2004 if (PySys_SetObject("argv", av) != 0)
2005 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002006 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00002007 if (updatepath)
2008 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00002009}
Guido van Rossuma890e681998-05-12 14:59:24 +00002010
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002011void
2012PySys_SetArgv(int argc, wchar_t **argv)
2013{
Christian Heimesad73a9c2013-08-10 16:36:18 +02002014 PySys_SetArgvEx(argc, argv, Py_IsolatedFlag == 0);
Antoine Pitrouf978fac2010-05-21 17:25:34 +00002015}
2016
Victor Stinner14284c22010-04-23 12:02:30 +00002017/* Reimplementation of PyFile_WriteString() no calling indirectly
2018 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
2019
2020static int
Victor Stinner79766632010-08-16 17:36:42 +00002021sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00002022{
Victor Stinner79766632010-08-16 17:36:42 +00002023 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002024 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00002025
Victor Stinnerecccc4f2010-06-08 20:46:00 +00002026 if (file == NULL)
2027 return -1;
2028
Martin v. Löwis1ee1b6f2011-10-10 18:11:30 +02002029 writer = _PyObject_GetAttrId(file, &PyId_write);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 if (writer == NULL)
2031 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002032
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 args = PyTuple_Pack(1, unicode);
2034 if (args == NULL)
2035 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 result = PyEval_CallObject(writer, args);
2038 if (result == NULL) {
2039 goto error;
2040 } else {
2041 err = 0;
2042 goto finally;
2043 }
Victor Stinner14284c22010-04-23 12:02:30 +00002044
2045error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002046 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00002047finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 Py_XDECREF(writer);
2049 Py_XDECREF(args);
2050 Py_XDECREF(result);
2051 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00002052}
2053
Victor Stinner79766632010-08-16 17:36:42 +00002054static int
2055sys_pyfile_write(const char *text, PyObject *file)
2056{
2057 PyObject *unicode = NULL;
2058 int err;
2059
2060 if (file == NULL)
2061 return -1;
2062
2063 unicode = PyUnicode_FromString(text);
2064 if (unicode == NULL)
2065 return -1;
2066
2067 err = sys_pyfile_write_unicode(unicode, file);
2068 Py_DECREF(unicode);
2069 return err;
2070}
Guido van Rossuma890e681998-05-12 14:59:24 +00002071
2072/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
2073 Adapted from code submitted by Just van Rossum.
2074
2075 PySys_WriteStdout(format, ...)
2076 PySys_WriteStderr(format, ...)
2077
2078 The first function writes to sys.stdout; the second to sys.stderr. When
2079 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00002080 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00002081
Victor Stinner14284c22010-04-23 12:02:30 +00002082 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00002083 signal handlers: they may raise a new exception whereas sys_write()
2084 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00002085
Guido van Rossuma890e681998-05-12 14:59:24 +00002086 Both take a printf-style format string as their first argument followed
2087 by a variable length argument list determined by the format string.
2088
2089 *** WARNING ***
2090
2091 The format should limit the total size of the formatted output string to
2092 1000 bytes. In particular, this means that no unrestricted "%s" formats
2093 should occur; these should be limited using "%.<N>s where <N> is a
2094 decimal number calculated so that <N> plus the maximum size of other
2095 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2096 which can print hundreds of digits for very large numbers.
2097
2098 */
2099
2100static void
Victor Stinner09054372013-11-06 22:41:44 +01002101sys_write(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002102{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002103 PyObject *file;
2104 PyObject *error_type, *error_value, *error_traceback;
2105 char buffer[1001];
2106 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002107
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002108 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002109 file = _PySys_GetObjectId(key);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002110 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2111 if (sys_pyfile_write(buffer, file) != 0) {
2112 PyErr_Clear();
2113 fputs(buffer, fp);
2114 }
2115 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2116 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002117 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002118 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 }
2120 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002121}
2122
2123void
Guido van Rossuma890e681998-05-12 14:59:24 +00002124PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002125{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002126 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002127
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002128 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002129 sys_write(&PyId_stdout, stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002130 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002131}
2132
2133void
Guido van Rossuma890e681998-05-12 14:59:24 +00002134PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002136 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002137
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002139 sys_write(&PyId_stderr, stderr, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002140 va_end(va);
2141}
2142
2143static void
Victor Stinner09054372013-11-06 22:41:44 +01002144sys_format(_Py_Identifier *key, FILE *fp, const char *format, va_list va)
Victor Stinner79766632010-08-16 17:36:42 +00002145{
2146 PyObject *file, *message;
2147 PyObject *error_type, *error_value, *error_traceback;
2148 char *utf8;
2149
2150 PyErr_Fetch(&error_type, &error_value, &error_traceback);
Victor Stinner09054372013-11-06 22:41:44 +01002151 file = _PySys_GetObjectId(key);
Victor Stinner79766632010-08-16 17:36:42 +00002152 message = PyUnicode_FromFormatV(format, va);
2153 if (message != NULL) {
2154 if (sys_pyfile_write_unicode(message, file) != 0) {
2155 PyErr_Clear();
2156 utf8 = _PyUnicode_AsString(message);
2157 if (utf8 != NULL)
2158 fputs(utf8, fp);
2159 }
2160 Py_DECREF(message);
2161 }
2162 PyErr_Restore(error_type, error_value, error_traceback);
2163}
2164
2165void
2166PySys_FormatStdout(const char *format, ...)
2167{
2168 va_list va;
2169
2170 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002171 sys_format(&PyId_stdout, stdout, format, va);
Victor Stinner79766632010-08-16 17:36:42 +00002172 va_end(va);
2173}
2174
2175void
2176PySys_FormatStderr(const char *format, ...)
2177{
2178 va_list va;
2179
2180 va_start(va, format);
Victor Stinnerbd303c12013-11-07 23:07:29 +01002181 sys_format(&PyId_stderr, stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002182 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002183}