blob: 9c94ececd52107ee76b6058f7c3fb31baa8a2e1c [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"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020
Guido van Rossume2437a11992-03-23 18:20:18 +000021#include "osdefs.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000022
Mark Hammond8696ebc2002-10-08 02:44:31 +000023#ifdef MS_WINDOWS
24#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000025#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000026#endif /* MS_WINDOWS */
27
Guido van Rossum9b38a141996-09-11 23:12:24 +000028#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000029extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000030/* A string loaded from the DLL at startup: */
31extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000032#endif
33
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +000034#ifdef __VMS
35#include <unixlib.h>
36#endif
37
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000038#ifdef HAVE_LANGINFO_H
39#include <locale.h>
40#include <langinfo.h>
41#endif
42
Guido van Rossum65bf9f21997-04-29 18:33:38 +000043PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000044PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000045{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000046 PyThreadState *tstate = PyThreadState_GET();
47 PyObject *sd = tstate->interp->sysdict;
48 if (sd == NULL)
49 return NULL;
50 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000051}
52
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053int
Neal Norwitzf3081322007-08-25 00:32:45 +000054PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000056 PyThreadState *tstate = PyThreadState_GET();
57 PyObject *sd = tstate->interp->sysdict;
58 if (v == NULL) {
59 if (PyDict_GetItemString(sd, name) == NULL)
60 return 0;
61 else
62 return PyDict_DelItemString(sd, name);
63 }
64 else
65 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066}
67
Victor Stinner13d49ee2010-12-04 17:24:33 +000068/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
69 error handler. If sys.stdout has a buffer attribute, use
70 sys.stdout.buffer.write(encoded), otherwise redecode the string and use
71 sys.stdout.write(redecoded).
72
73 Helper function for sys_displayhook(). */
74static int
75sys_displayhook_unencodable(PyObject *outf, PyObject *o)
76{
77 PyObject *stdout_encoding = NULL;
78 PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
79 char *stdout_encoding_str;
80 int ret;
81
82 stdout_encoding = PyObject_GetAttrString(outf, "encoding");
83 if (stdout_encoding == NULL)
84 goto error;
85 stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
86 if (stdout_encoding_str == NULL)
87 goto error;
88
89 repr_str = PyObject_Repr(o);
90 if (repr_str == NULL)
91 goto error;
92 encoded = PyUnicode_AsEncodedString(repr_str,
93 stdout_encoding_str,
94 "backslashreplace");
95 Py_DECREF(repr_str);
96 if (encoded == NULL)
97 goto error;
98
99 buffer = PyObject_GetAttrString(outf, "buffer");
100 if (buffer) {
101 result = PyObject_CallMethod(buffer, "write", "(O)", encoded);
102 Py_DECREF(buffer);
103 Py_DECREF(encoded);
104 if (result == NULL)
105 goto error;
106 Py_DECREF(result);
107 }
108 else {
109 PyErr_Clear();
110 escaped_str = PyUnicode_FromEncodedObject(encoded,
111 stdout_encoding_str,
112 "strict");
113 Py_DECREF(encoded);
114 if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
115 Py_DECREF(escaped_str);
116 goto error;
117 }
118 Py_DECREF(escaped_str);
119 }
120 ret = 0;
121 goto finally;
122
123error:
124 ret = -1;
125finally:
126 Py_XDECREF(stdout_encoding);
127 return ret;
128}
129
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000130static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000131sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyObject *outf;
134 PyInterpreterState *interp = PyThreadState_GET()->interp;
135 PyObject *modules = interp->modules;
136 PyObject *builtins = PyDict_GetItemString(modules, "builtins");
Victor Stinner13d49ee2010-12-04 17:24:33 +0000137 int err;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000139 if (builtins == NULL) {
140 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
141 return NULL;
142 }
Moshe Zadka03897ea2001-07-23 13:32:43 +0000143
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000144 /* Print value except if None */
145 /* After printing, also assign to '_' */
146 /* Before, set '_' to None to avoid recursion */
147 if (o == Py_None) {
148 Py_INCREF(Py_None);
149 return Py_None;
150 }
151 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
152 return NULL;
153 outf = PySys_GetObject("stdout");
154 if (outf == NULL || outf == Py_None) {
155 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
156 return NULL;
157 }
Victor Stinner13d49ee2010-12-04 17:24:33 +0000158 if (PyFile_WriteObject(o, outf, 0) != 0) {
159 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
160 /* repr(o) is not encodable to sys.stdout.encoding with
161 * sys.stdout.errors error handler (which is probably 'strict') */
162 PyErr_Clear();
163 err = sys_displayhook_unencodable(outf, o);
164 if (err)
165 return NULL;
166 }
167 else {
168 return NULL;
169 }
170 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 if (PyFile_WriteString("\n", outf) != 0)
172 return NULL;
173 if (PyObject_SetAttrString(builtins, "_", o) != 0)
174 return NULL;
175 Py_INCREF(Py_None);
176 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000177}
178
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000179PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000180"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000181"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000182"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000183);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000184
185static PyObject *
186sys_excepthook(PyObject* self, PyObject* args)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 PyObject *exc, *value, *tb;
189 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
190 return NULL;
191 PyErr_Display(exc, value, tb);
192 Py_INCREF(Py_None);
193 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000194}
195
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000196PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000197"excepthook(exctype, value, traceback) -> None\n"
198"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000199"Handle an exception by displaying it with a traceback on sys.stderr.\n"
200);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000201
202static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000203sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000204{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000205 PyThreadState *tstate;
206 tstate = PyThreadState_GET();
207 return Py_BuildValue(
208 "(OOO)",
209 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
210 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
211 tstate->exc_traceback != NULL ?
212 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000213}
214
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000215PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000216"exc_info() -> (type, value, traceback)\n\
217\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000218Return information about the most recent exception caught by an except\n\
219clause in the current stack frame or in an older stack frame."
220);
221
222static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000223sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000224{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000225 PyObject *exit_code = 0;
226 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
227 return NULL;
228 /* Raise SystemExit so callers may catch it or clean up. */
229 PyErr_SetObject(PyExc_SystemExit, exit_code);
230 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000231}
232
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000233PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000234"exit([status])\n\
235\n\
236Exit the interpreter by raising SystemExit(status).\n\
237If the status is omitted or None, it defaults to zero (i.e., success).\n\
Neil Schemenauer0f2103f2002-03-23 20:46:35 +0000238If the status is numeric, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000239If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000240exit status will be one (i.e., failure)."
241);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000242
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000243
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000244static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000245sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000246{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000247 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000248}
249
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000250PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000251"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000252\n\
253Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000254implementation."
255);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000256
257static PyObject *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000258sys_getfilesystemencoding(PyObject *self)
259{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000260 if (Py_FileSystemDefaultEncoding)
261 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
262 Py_INCREF(Py_None);
263 return Py_None;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000264}
265
266PyDoc_STRVAR(getfilesystemencoding_doc,
267"getfilesystemencoding() -> string\n\
268\n\
269Return the encoding used to convert Unicode filenames in\n\
270operating system filenames."
271);
272
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000273static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000274sys_intern(PyObject *self, PyObject *args)
275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 PyObject *s;
277 if (!PyArg_ParseTuple(args, "U:intern", &s))
278 return NULL;
279 if (PyUnicode_CheckExact(s)) {
280 Py_INCREF(s);
281 PyUnicode_InternInPlace(&s);
282 return s;
283 }
284 else {
285 PyErr_Format(PyExc_TypeError,
286 "can't intern %.400s", s->ob_type->tp_name);
287 return NULL;
288 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000289}
290
291PyDoc_STRVAR(intern_doc,
292"intern(string) -> string\n\
293\n\
294``Intern'' the given string. This enters the string in the (global)\n\
295table of interned strings whose purpose is to speed up dictionary lookups.\n\
296Return the string itself or the previously interned string object with the\n\
297same value.");
298
299
Fred Drake5755ce62001-06-27 19:19:46 +0000300/*
301 * Cached interned string objects used for calling the profile and
302 * trace functions. Initialized by trace_init().
303 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000304static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000305
306static int
307trace_init(void)
308{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 static char *whatnames[7] = {"call", "exception", "line", "return",
310 "c_call", "c_exception", "c_return"};
311 PyObject *name;
312 int i;
313 for (i = 0; i < 7; ++i) {
314 if (whatstrings[i] == NULL) {
315 name = PyUnicode_InternFromString(whatnames[i]);
316 if (name == NULL)
317 return -1;
318 whatstrings[i] = name;
319 }
320 }
321 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000322}
323
324
325static PyObject *
326call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000327 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000328{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 PyObject *args = PyTuple_New(3);
330 PyObject *whatstr;
331 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000332
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000333 if (args == NULL)
334 return NULL;
335 Py_INCREF(frame);
336 whatstr = whatstrings[what];
337 Py_INCREF(whatstr);
338 if (arg == NULL)
339 arg = Py_None;
340 Py_INCREF(arg);
341 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
342 PyTuple_SET_ITEM(args, 1, whatstr);
343 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000344
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 /* call the Python-level function */
346 PyFrame_FastToLocals(frame);
347 result = PyEval_CallObject(callback, args);
348 PyFrame_LocalsToFast(frame, 1);
349 if (result == NULL)
350 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000351
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000352 /* cleanup */
353 Py_DECREF(args);
354 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000355}
356
357static int
358profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000359 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000360{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 PyThreadState *tstate = frame->f_tstate;
362 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 if (arg == NULL)
365 arg = Py_None;
366 result = call_trampoline(tstate, self, frame, what, arg);
367 if (result == NULL) {
368 PyEval_SetProfile(NULL, NULL);
369 return -1;
370 }
371 Py_DECREF(result);
372 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000373}
374
375static int
376trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000377 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000378{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 PyThreadState *tstate = frame->f_tstate;
380 PyObject *callback;
381 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000383 if (what == PyTrace_CALL)
384 callback = self;
385 else
386 callback = frame->f_trace;
387 if (callback == NULL)
388 return 0;
389 result = call_trampoline(tstate, callback, frame, what, arg);
390 if (result == NULL) {
391 PyEval_SetTrace(NULL, NULL);
392 Py_XDECREF(frame->f_trace);
393 frame->f_trace = NULL;
394 return -1;
395 }
396 if (result != Py_None) {
397 PyObject *temp = frame->f_trace;
398 frame->f_trace = NULL;
399 Py_XDECREF(temp);
400 frame->f_trace = result;
401 }
402 else {
403 Py_DECREF(result);
404 }
405 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000406}
Fred Draked0838392001-06-16 21:02:31 +0000407
Fred Drake8b4d01d2000-05-09 19:57:01 +0000408static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000409sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000410{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000411 if (trace_init() == -1)
412 return NULL;
413 if (args == Py_None)
414 PyEval_SetTrace(NULL, NULL);
415 else
416 PyEval_SetTrace(trace_trampoline, args);
417 Py_INCREF(Py_None);
418 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000419}
420
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000421PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000422"settrace(function)\n\
423\n\
424Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000425function call. See the debugger chapter in the library manual."
426);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000427
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000428static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000429sys_gettrace(PyObject *self, PyObject *args)
430{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000431 PyThreadState *tstate = PyThreadState_GET();
432 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000433
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000434 if (temp == NULL)
435 temp = Py_None;
436 Py_INCREF(temp);
437 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000438}
439
440PyDoc_STRVAR(gettrace_doc,
441"gettrace()\n\
442\n\
443Return the global debug tracing function set with sys.settrace.\n\
444See the debugger chapter in the library manual."
445);
446
447static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000448sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000450 if (trace_init() == -1)
451 return NULL;
452 if (args == Py_None)
453 PyEval_SetProfile(NULL, NULL);
454 else
455 PyEval_SetProfile(profile_trampoline, args);
456 Py_INCREF(Py_None);
457 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000458}
459
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000460PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000461"setprofile(function)\n\
462\n\
463Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000464and return. See the profiler chapter in the library manual."
465);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000466
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000467static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000468sys_getprofile(PyObject *self, PyObject *args)
469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000470 PyThreadState *tstate = PyThreadState_GET();
471 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000473 if (temp == NULL)
474 temp = Py_None;
475 Py_INCREF(temp);
476 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000477}
478
479PyDoc_STRVAR(getprofile_doc,
480"getprofile()\n\
481\n\
482Return the profiling function set with sys.setprofile.\n\
483See the profiler chapter in the library manual."
484);
485
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000486static int _check_interval = 100;
487
Christian Heimes9bd667a2008-01-20 15:14:11 +0000488static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000489sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000490{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000491 if (PyErr_WarnEx(PyExc_DeprecationWarning,
492 "sys.getcheckinterval() and sys.setcheckinterval() "
493 "are deprecated. Use sys.setswitchinterval() "
494 "instead.", 1) < 0)
495 return NULL;
496 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
497 return NULL;
498 Py_INCREF(Py_None);
499 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000500}
501
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000502PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000503"setcheckinterval(n)\n\
504\n\
505Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000506n instructions. This also affects how often thread switches occur."
507);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000508
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000509static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000510sys_getcheckinterval(PyObject *self, PyObject *args)
511{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000512 if (PyErr_WarnEx(PyExc_DeprecationWarning,
513 "sys.getcheckinterval() and sys.setcheckinterval() "
514 "are deprecated. Use sys.getswitchinterval() "
515 "instead.", 1) < 0)
516 return NULL;
517 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000518}
519
520PyDoc_STRVAR(getcheckinterval_doc,
521"getcheckinterval() -> current check interval; see setcheckinterval()."
522);
523
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000524#ifdef WITH_THREAD
525static PyObject *
526sys_setswitchinterval(PyObject *self, PyObject *args)
527{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000528 double d;
529 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
530 return NULL;
531 if (d <= 0.0) {
532 PyErr_SetString(PyExc_ValueError,
533 "switch interval must be strictly positive");
534 return NULL;
535 }
536 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
537 Py_INCREF(Py_None);
538 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000539}
540
541PyDoc_STRVAR(setswitchinterval_doc,
542"setswitchinterval(n)\n\
543\n\
544Set the ideal thread switching delay inside the Python interpreter\n\
545The actual frequency of switching threads can be lower if the\n\
546interpreter executes long sequences of uninterruptible code\n\
547(this is implementation-specific and workload-dependent).\n\
548\n\
549The parameter must represent the desired switching delay in seconds\n\
550A typical value is 0.005 (5 milliseconds)."
551);
552
553static PyObject *
554sys_getswitchinterval(PyObject *self, PyObject *args)
555{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000556 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000557}
558
559PyDoc_STRVAR(getswitchinterval_doc,
560"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
561);
562
563#endif /* WITH_THREAD */
564
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000565#ifdef WITH_TSC
566static PyObject *
567sys_settscdump(PyObject *self, PyObject *args)
568{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000569 int bool;
570 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000572 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
573 return NULL;
574 if (bool)
575 tstate->interp->tscdump = 1;
576 else
577 tstate->interp->tscdump = 0;
578 Py_INCREF(Py_None);
579 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000580
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000581}
582
Tim Peters216b78b2006-01-06 02:40:53 +0000583PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000584"settscdump(bool)\n\
585\n\
586If true, tell the Python interpreter to dump VM measurements to\n\
587stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000588processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000589);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000590#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000591
Tim Peterse5e065b2003-07-06 18:36:54 +0000592static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000593sys_setrecursionlimit(PyObject *self, PyObject *args)
594{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000595 int new_limit;
596 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
597 return NULL;
598 if (new_limit <= 0) {
599 PyErr_SetString(PyExc_ValueError,
600 "recursion limit must be positive");
601 return NULL;
602 }
603 Py_SetRecursionLimit(new_limit);
604 Py_INCREF(Py_None);
605 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000606}
607
Mark Dickinsondc787d22010-05-23 13:33:13 +0000608static PyTypeObject Hash_InfoType;
609
610PyDoc_STRVAR(hash_info_doc,
611"hash_info\n\
612\n\
613A struct sequence providing parameters used for computing\n\
614numeric hashes. The attributes are read only.");
615
616static PyStructSequence_Field hash_info_fields[] = {
617 {"width", "width of the type used for hashing, in bits"},
618 {"modulus", "prime number giving the modulus on which the hash "
619 "function is based"},
620 {"inf", "value to be used for hash of a positive infinity"},
621 {"nan", "value to be used for hash of a nan"},
622 {"imag", "multiplier used for the imaginary part of a complex number"},
623 {NULL, NULL}
624};
625
626static PyStructSequence_Desc hash_info_desc = {
627 "sys.hash_info",
628 hash_info_doc,
629 hash_info_fields,
630 5,
631};
632
Matthias Klosed885e952010-07-06 10:53:30 +0000633static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000634get_hash_info(void)
635{
636 PyObject *hash_info;
637 int field = 0;
638 hash_info = PyStructSequence_New(&Hash_InfoType);
639 if (hash_info == NULL)
640 return NULL;
641 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000642 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000643 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000644 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000645 PyStructSequence_SET_ITEM(hash_info, field++,
646 PyLong_FromLong(_PyHASH_INF));
647 PyStructSequence_SET_ITEM(hash_info, field++,
648 PyLong_FromLong(_PyHASH_NAN));
649 PyStructSequence_SET_ITEM(hash_info, field++,
650 PyLong_FromLong(_PyHASH_IMAG));
651 if (PyErr_Occurred()) {
652 Py_CLEAR(hash_info);
653 return NULL;
654 }
655 return hash_info;
656}
657
658
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000659PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000660"setrecursionlimit(n)\n\
661\n\
662Set the maximum depth of the Python interpreter stack to n. This\n\
663limit prevents infinite recursion from causing an overflow of the C\n\
664stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000665dependent."
666);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000667
668static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000669sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000670{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000672}
673
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000674PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000675"getrecursionlimit()\n\
676\n\
677Return the current value of the recursion limit, the maximum depth\n\
678of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000679recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000680);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000681
Mark Hammond8696ebc2002-10-08 02:44:31 +0000682#ifdef MS_WINDOWS
683PyDoc_STRVAR(getwindowsversion_doc,
684"getwindowsversion()\n\
685\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000686Return information about the running version of Windows as a named tuple.\n\
687The members are named: major, minor, build, platform, service_pack,\n\
688service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
689backward compatibiliy, only the first 5 items are available by indexing.\n\
690All elements are numbers, except service_pack which is a string. Platform\n\
691may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6923 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
693controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000694);
695
Eric Smithf7bb5782010-01-27 00:44:57 +0000696static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
697
698static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 {"major", "Major version number"},
700 {"minor", "Minor version number"},
701 {"build", "Build number"},
702 {"platform", "Operating system platform"},
703 {"service_pack", "Latest Service Pack installed on the system"},
704 {"service_pack_major", "Service Pack major version number"},
705 {"service_pack_minor", "Service Pack minor version number"},
706 {"suite_mask", "Bit mask identifying available product suites"},
707 {"product_type", "System product type"},
708 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000709};
710
711static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000712 "sys.getwindowsversion", /* name */
713 getwindowsversion_doc, /* doc */
714 windows_version_fields, /* fields */
715 5 /* For backward compatibility,
716 only the first 5 items are accessible
717 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000718};
719
Mark Hammond8696ebc2002-10-08 02:44:31 +0000720static PyObject *
721sys_getwindowsversion(PyObject *self)
722{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000723 PyObject *version;
724 int pos = 0;
725 OSVERSIONINFOEX ver;
726 ver.dwOSVersionInfoSize = sizeof(ver);
727 if (!GetVersionEx((OSVERSIONINFO*) &ver))
728 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000729
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000730 version = PyStructSequence_New(&WindowsVersionType);
731 if (version == NULL)
732 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000734 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
735 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
736 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
737 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
738 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
739 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
740 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
741 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
742 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000745}
746
747#endif /* MS_WINDOWS */
748
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000749#ifdef HAVE_DLOPEN
750static PyObject *
751sys_setdlopenflags(PyObject *self, PyObject *args)
752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000753 int new_val;
754 PyThreadState *tstate = PyThreadState_GET();
755 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
756 return NULL;
757 if (!tstate)
758 return NULL;
759 tstate->interp->dlopenflags = new_val;
760 Py_INCREF(Py_None);
761 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000762}
763
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000764PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000765"setdlopenflags(n) -> None\n\
766\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000767Set the flags used by the interpreter for dlopen calls, such as when the\n\
768interpreter loads extension modules. Among other things, this will enable\n\
769a lazy resolving of symbols when importing a module, if called as\n\
770sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
771sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
772can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
773is not available, it can be generated from /usr/include/dlfcn.h using the\n\
774h2py script.");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000775
776static PyObject *
777sys_getdlopenflags(PyObject *self, PyObject *args)
778{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000779 PyThreadState *tstate = PyThreadState_GET();
780 if (!tstate)
781 return NULL;
782 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000783}
784
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000785PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000786"getdlopenflags() -> int\n\
787\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000788Return the current value of the flags that are used for dlopen calls.\n\
789The flag constants are defined in the ctypes and DLFCN modules.");
790
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000791#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000792
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000793#ifdef USE_MALLOPT
794/* Link with -lmalloc (or -lmpc) on an SGI */
795#include <malloc.h>
796
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000797static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000798sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000799{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000800 int flag;
801 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
802 return NULL;
803 mallopt(M_DEBUG, flag);
804 Py_INCREF(Py_None);
805 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000806}
807#endif /* USE_MALLOPT */
808
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000809static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000810sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000812 PyObject *res = NULL;
813 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
814 static char *kwlist[] = {"object", "default", 0};
815 PyObject *o, *dflt = NULL;
816 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000817
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000818 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
819 kwlist, &o, &dflt))
820 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000822 /* Initialize static variable for GC head size */
823 if (gc_head_size == NULL) {
824 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
825 if (gc_head_size == NULL)
826 return NULL;
827 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000829 /* Make sure the type is initialized. float gets initialized late */
830 if (PyType_Ready(Py_TYPE(o)) < 0)
831 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000833 method = _PyObject_LookupSpecial(o, "__sizeof__",
834 &str__sizeof__);
835 if (method == NULL) {
836 if (!PyErr_Occurred())
837 PyErr_Format(PyExc_TypeError,
838 "Type %.100s doesn't define __sizeof__",
839 Py_TYPE(o)->tp_name);
840 }
841 else {
842 res = PyObject_CallFunctionObjArgs(method, NULL);
843 Py_DECREF(method);
844 }
845
846 /* Has a default value been given */
847 if ((res == NULL) && (dflt != NULL) &&
848 PyErr_ExceptionMatches(PyExc_TypeError))
849 {
850 PyErr_Clear();
851 Py_INCREF(dflt);
852 return dflt;
853 }
854 else if (res == NULL)
855 return res;
856
857 /* add gc_head size */
858 if (PyObject_IS_GC(o)) {
859 PyObject *tmp = res;
860 res = PyNumber_Add(tmp, gc_head_size);
861 Py_DECREF(tmp);
862 }
863 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000864}
865
866PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000867"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000868\n\
869Return the size of object in bytes.");
870
871static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000872sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000873{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000874 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000875}
876
Tim Peters4be93d02002-07-07 19:59:50 +0000877#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000878static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000879sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000880{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000881 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000882}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000883#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000884
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000885PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000886"getrefcount(object) -> integer\n\
887\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000888Return the reference count of object. The count returned is generally\n\
889one higher than you might expect, because it includes the (temporary)\n\
890reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000891);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000892
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000893#ifdef COUNT_ALLOCS
894static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000895sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000896{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000897 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000898
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000899 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000900}
901#endif
902
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000903PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000904"_getframe([depth]) -> frameobject\n\
905\n\
906Return a frame object from the call stack. If optional integer depth is\n\
907given, return the frame object that many calls below the top of the stack.\n\
908If that is deeper than the call stack, ValueError is raised. The default\n\
909for depth is zero, returning the frame at the top of the call stack.\n\
910\n\
911This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000912purposes only."
913);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000914
915static PyObject *
916sys_getframe(PyObject *self, PyObject *args)
917{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000918 PyFrameObject *f = PyThreadState_GET()->frame;
919 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000920
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000921 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
922 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000923
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000924 while (depth > 0 && f != NULL) {
925 f = f->f_back;
926 --depth;
927 }
928 if (f == NULL) {
929 PyErr_SetString(PyExc_ValueError,
930 "call stack is not deep enough");
931 return NULL;
932 }
933 Py_INCREF(f);
934 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000935}
936
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000937PyDoc_STRVAR(current_frames_doc,
938"_current_frames() -> dictionary\n\
939\n\
940Return a dictionary mapping each current thread T's thread id to T's\n\
941current stack frame.\n\
942\n\
943This function should be used for specialized purposes only."
944);
945
946static PyObject *
947sys_current_frames(PyObject *self, PyObject *noargs)
948{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000949 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000950}
951
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000952PyDoc_STRVAR(call_tracing_doc,
953"call_tracing(func, args) -> object\n\
954\n\
955Call func(*args), while tracing is enabled. The tracing state is\n\
956saved, and restored afterwards. This is intended to be called from\n\
957a debugger from a checkpoint, to recursively debug some other code."
958);
959
960static PyObject *
961sys_call_tracing(PyObject *self, PyObject *args)
962{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000963 PyObject *func, *funcargs;
964 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
965 return NULL;
966 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000967}
968
Jeremy Hylton985eba52003-02-05 23:13:00 +0000969PyDoc_STRVAR(callstats_doc,
970"callstats() -> tuple of integers\n\
971\n\
972Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
973when Python was built. Otherwise, return None.\n\
974\n\
975When enabled, this function returns detailed, implementation-specific\n\
976details about the number of function calls executed. The return value is\n\
977a 11-tuple where the entries in the tuple are counts of:\n\
9780. all function calls\n\
9791. calls to PyFunction_Type objects\n\
9802. PyFunction calls that do not create an argument tuple\n\
9813. PyFunction calls that do not create an argument tuple\n\
982 and bypass PyEval_EvalCodeEx()\n\
9834. PyMethod calls\n\
9845. PyMethod calls on bound methods\n\
9856. PyType calls\n\
9867. PyCFunction calls\n\
9878. generator calls\n\
9889. All other calls\n\
98910. Number of stack pops performed by call_function()"
990);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000991
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000992#ifdef __cplusplus
993extern "C" {
994#endif
995
Guido van Rossum7f3f2c11996-05-23 22:45:41 +0000996#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +0000997/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000998extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000999#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001000
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001001#ifdef DYNAMIC_EXECUTION_PROFILE
1002/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001003extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001004#endif
1005
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001006#ifdef __cplusplus
1007}
1008#endif
1009
Christian Heimes15ebc882008-02-04 18:48:49 +00001010static PyObject *
1011sys_clear_type_cache(PyObject* self, PyObject* args)
1012{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 PyType_ClearCache();
1014 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001015}
1016
1017PyDoc_STRVAR(sys_clear_type_cache__doc__,
1018"_clear_type_cache() -> None\n\
1019Clear the internal type lookup cache.");
1020
1021
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001022static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001023 /* Might as well keep this in alphabetic order */
1024 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1025 callstats_doc},
1026 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1027 sys_clear_type_cache__doc__},
1028 {"_current_frames", sys_current_frames, METH_NOARGS,
1029 current_frames_doc},
1030 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1031 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1032 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1033 {"exit", sys_exit, METH_VARARGS, exit_doc},
1034 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1035 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001036#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1038 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001039#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001040#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001042#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001043#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001044 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001045#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001046 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1047 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001048#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001050#endif
1051#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001052 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001053#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001054 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1055 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1056 getrecursionlimit_doc},
1057 {"getsizeof", (PyCFunction)sys_getsizeof,
1058 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1059 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001060#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1062 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001063#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001064 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001065#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001066 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001067#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001068 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1069 setcheckinterval_doc},
1070 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1071 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001072#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001073 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1074 setswitchinterval_doc},
1075 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1076 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001077#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001078#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001079 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1080 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001081#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001082 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1083 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1084 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1085 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001086#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001087 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001088#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001089 {"settrace", sys_settrace, METH_O, settrace_doc},
1090 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1091 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1092 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001093};
1094
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001095static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001096list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001097{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001098 PyObject *list = PyList_New(0);
1099 int i;
1100 if (list == NULL)
1101 return NULL;
1102 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1103 PyObject *name = PyUnicode_FromString(
1104 PyImport_Inittab[i].name);
1105 if (name == NULL)
1106 break;
1107 PyList_Append(list, name);
1108 Py_DECREF(name);
1109 }
1110 if (PyList_Sort(list) != 0) {
1111 Py_DECREF(list);
1112 list = NULL;
1113 }
1114 if (list) {
1115 PyObject *v = PyList_AsTuple(list);
1116 Py_DECREF(list);
1117 list = v;
1118 }
1119 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001120}
1121
Guido van Rossum23fff912000-12-15 22:02:05 +00001122static PyObject *warnoptions = NULL;
1123
1124void
1125PySys_ResetWarnOptions(void)
1126{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001127 if (warnoptions == NULL || !PyList_Check(warnoptions))
1128 return;
1129 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001130}
1131
1132void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001133PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001134{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001135 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1136 Py_XDECREF(warnoptions);
1137 warnoptions = PyList_New(0);
1138 if (warnoptions == NULL)
1139 return;
1140 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001141 PyList_Append(warnoptions, unicode);
1142}
1143
1144void
1145PySys_AddWarnOption(const wchar_t *s)
1146{
1147 PyObject *unicode;
1148 unicode = PyUnicode_FromWideChar(s, -1);
1149 if (unicode == NULL)
1150 return;
1151 PySys_AddWarnOptionUnicode(unicode);
1152 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001153}
1154
Christian Heimes33fe8092008-04-13 13:53:33 +00001155int
1156PySys_HasWarnOptions(void)
1157{
1158 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1159}
1160
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001161static PyObject *xoptions = NULL;
1162
1163static PyObject *
1164get_xoptions(void)
1165{
1166 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1167 Py_XDECREF(xoptions);
1168 xoptions = PyDict_New();
1169 }
1170 return xoptions;
1171}
1172
1173void
1174PySys_AddXOption(const wchar_t *s)
1175{
1176 PyObject *opts;
1177 PyObject *name = NULL, *value = NULL;
1178 const wchar_t *name_end;
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001179
1180 opts = get_xoptions();
1181 if (opts == NULL)
1182 goto error;
1183
1184 name_end = wcschr(s, L'=');
1185 if (!name_end) {
1186 name = PyUnicode_FromWideChar(s, -1);
1187 value = Py_True;
1188 Py_INCREF(value);
1189 }
1190 else {
1191 name = PyUnicode_FromWideChar(s, name_end - s);
1192 value = PyUnicode_FromWideChar(name_end + 1, -1);
1193 }
1194 if (name == NULL || value == NULL)
1195 goto error;
Brett Cannonb94767f2011-02-22 20:15:44 +00001196 PyDict_SetItem(opts, name, value);
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001197 Py_DECREF(name);
1198 Py_DECREF(value);
1199 return;
1200
1201error:
1202 Py_XDECREF(name);
1203 Py_XDECREF(value);
1204 /* No return value, therefore clear error state if possible */
1205 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1206 PyErr_Clear();
1207}
1208
1209PyObject *
1210PySys_GetXOptions(void)
1211{
1212 return get_xoptions();
1213}
1214
Guido van Rossum40552d01998-08-06 03:34:39 +00001215/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1216 Two literals concatenated works just fine. If you have a K&R compiler
1217 or other abomination that however *does* understand longer strings,
1218 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001219PyDoc_VAR(sys_doc) =
1220PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001221"This module provides access to some objects used or maintained by the\n\
1222interpreter and to functions that interact strongly with the interpreter.\n\
1223\n\
1224Dynamic objects:\n\
1225\n\
1226argv -- command line arguments; argv[0] is the script pathname if known\n\
1227path -- module search path; path[0] is the script directory, else ''\n\
1228modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001229\n\
1230displayhook -- called to show results in an interactive session\n\
1231excepthook -- called to handle any uncaught exception other than SystemExit\n\
1232 To customize printing in an interactive session or to install a custom\n\
1233 top-level exception handler, assign other functions to replace these.\n\
1234\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001235stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001236stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001237stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001238 By assigning other file objects (or objects that behave like files)\n\
1239 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001240\n\
1241last_type -- type of last uncaught exception\n\
1242last_value -- value of last uncaught exception\n\
1243last_traceback -- traceback of last uncaught exception\n\
1244 These three are only available in an interactive session after a\n\
1245 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001246"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001247)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001248/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001249PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001250"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001251Static objects:\n\
1252\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001253float_info -- a dict with information about the float implementation.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001254int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001255maxsize -- the largest supported length of containers.\n\
Martin v. Löwisce9b5a52001-06-27 06:28:56 +00001256maxunicode -- the largest supported character\n\
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001257builtin_module_names -- tuple of module names built into this interpreter\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001258subversion -- subversion information of the build as tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001259version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001260version_info -- version information as a named tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001261hexversion -- version information encoded as a single integer\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001262copyright -- copyright notice pertaining to this interpreter\n\
1263platform -- platform identifier\n\
1264executable -- pathname of this Python interpreter\n\
1265prefix -- prefix used to find the Python library\n\
1266exec_prefix -- prefix used to find the machine-specific Python library\n\
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001267float_repr_style -- string indicating the style of repr() output for floats\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001268"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001269)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001270#ifdef MS_WINDOWS
1271/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001272PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001273"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001274winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001275"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001276)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001277#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001278PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001279"__stdin__ -- the original stdin; don't touch!\n\
1280__stdout__ -- the original stdout; don't touch!\n\
1281__stderr__ -- the original stderr; don't touch!\n\
1282__displayhook__ -- the original displayhook; don't touch!\n\
1283__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001284\n\
1285Functions:\n\
1286\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001287displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001288excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001289exc_info() -- return thread-safe information about the current exception\n\
1290exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001291getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001292getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001293getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001294getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001295getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001296gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001297setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001298setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001299setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001300setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001301settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001302"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001303)
Fred Drakeccede592000-08-14 20:59:57 +00001304/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001305
Martin v. Löwis43b57802006-01-05 23:38:54 +00001306/* Subversion branch and revision management */
1307static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION;
1308static const char headurl[] = "$HeadURL$";
1309static int svn_initialized;
1310static char patchlevel_revision[50]; /* Just the number */
1311static char branch[50];
1312static char shortbranch[50];
1313static const char *svn_revision;
1314
Tim Peterse86e7a52006-01-06 02:42:46 +00001315static void
1316svnversion_init(void)
Martin v. Löwis43b57802006-01-05 23:38:54 +00001317{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001318 const char *python, *br_start, *br_end, *br_end2, *svnversion;
1319 Py_ssize_t len;
1320 int istag = 0;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001321
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001322 if (svn_initialized)
1323 return;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001324
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 python = strstr(headurl, "/python/");
1326 if (!python) {
1327 strcpy(branch, "unknown branch");
1328 strcpy(shortbranch, "unknown");
1329 }
1330 else {
1331 br_start = python + 8;
1332 br_end = strchr(br_start, '/');
1333 assert(br_end);
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 /* Works even for trunk,
1336 as we are in trunk/Python/sysmodule.c */
1337 br_end2 = strchr(br_end+1, '/');
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001338
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 istag = strncmp(br_start, "tags", 4) == 0;
1340 if (strncmp(br_start, "trunk", 5) == 0) {
1341 strcpy(branch, "trunk");
1342 strcpy(shortbranch, "trunk");
1343 }
1344 else if (istag || strncmp(br_start, "branches", 8) == 0) {
1345 len = br_end2 - br_start;
1346 strncpy(branch, br_start, len);
1347 branch[len] = '\0';
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001348
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001349 len = br_end2 - (br_end + 1);
1350 strncpy(shortbranch, br_end + 1, len);
1351 shortbranch[len] = '\0';
1352 }
1353 else {
1354 Py_FatalError("bad HeadURL");
1355 return;
1356 }
1357 }
Martin v. Löwis43b57802006-01-05 23:38:54 +00001358
1359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 svnversion = _Py_svnversion();
1361 if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0)
1362 svn_revision = svnversion;
1363 else if (istag) {
1364 len = strlen(_patchlevel_revision);
1365 assert(len >= 13);
1366 assert(len < (sizeof(patchlevel_revision) + 13));
1367 strncpy(patchlevel_revision, _patchlevel_revision + 11,
1368 len - 13);
1369 patchlevel_revision[len - 13] = '\0';
1370 svn_revision = patchlevel_revision;
1371 }
1372 else
1373 svn_revision = "";
Tim Peters216b78b2006-01-06 02:40:53 +00001374
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 svn_initialized = 1;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001376}
1377
1378/* Return svnversion output if available.
1379 Else return Revision of patchlevel.h if on branch.
1380 Else return empty string */
1381const char*
1382Py_SubversionRevision()
1383{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001384 svnversion_init();
1385 return svn_revision;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001386}
1387
1388const char*
1389Py_SubversionShortBranch()
1390{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 svnversion_init();
1392 return shortbranch;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001393}
1394
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001395
1396PyDoc_STRVAR(flags__doc__,
1397"sys.flags\n\
1398\n\
1399Flags provided through command line arguments or environment vars.");
1400
1401static PyTypeObject FlagsType;
1402
1403static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001404 {"debug", "-d"},
1405 {"division_warning", "-Q"},
1406 {"inspect", "-i"},
1407 {"interactive", "-i"},
1408 {"optimize", "-O or -OO"},
1409 {"dont_write_bytecode", "-B"},
1410 {"no_user_site", "-s"},
1411 {"no_site", "-S"},
1412 {"ignore_environment", "-E"},
1413 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001414#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001416#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 /* {"unbuffered", "-u"}, */
1418 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001419 {"bytes_warning", "-b"},
1420 {"quiet", "-q"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001422};
1423
1424static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001425 "sys.flags", /* name */
1426 flags__doc__, /* doc */
1427 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001428#ifdef RISCOS
Raymond Hettinger90e8f8c2011-01-05 20:08:25 +00001429 13
Georg Brandle1b5ac62008-06-04 13:06:58 +00001430#else
Raymond Hettinger90e8f8c2011-01-05 20:08:25 +00001431 12
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001432#endif
1433};
1434
1435static PyObject*
1436make_flags(void)
1437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 int pos = 0;
1439 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001440
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001441 seq = PyStructSequence_New(&FlagsType);
1442 if (seq == NULL)
1443 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001444
1445#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001446 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 SetFlag(Py_DebugFlag);
1449 SetFlag(Py_DivisionWarningFlag);
1450 SetFlag(Py_InspectFlag);
1451 SetFlag(Py_InteractiveFlag);
1452 SetFlag(Py_OptimizeFlag);
1453 SetFlag(Py_DontWriteBytecodeFlag);
1454 SetFlag(Py_NoUserSiteDirectory);
1455 SetFlag(Py_NoSiteFlag);
1456 SetFlag(Py_IgnoreEnvironmentFlag);
1457 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001458#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001460#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 /* SetFlag(saw_unbuffered_flag); */
1462 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001463 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001464 SetFlag(Py_QuietFlag);
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
Martin v. Löwis1a214512008-06-11 05:26:20 +00001542static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 PyModuleDef_HEAD_INIT,
1544 "sys",
1545 sys_doc,
1546 -1, /* multiple "initialization" just copies the module dict. */
1547 sys_methods,
1548 NULL,
1549 NULL,
1550 NULL,
1551 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001552};
1553
Guido van Rossum25ce5661997-08-02 03:10:38 +00001554PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001555_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001557 PyObject *m, *v, *sysdict;
1558 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001559
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 m = PyModule_Create(&sysmodule);
1561 if (m == NULL)
1562 return NULL;
1563 sysdict = PyModule_GetDict(m);
1564#define SET_SYS_FROM_STRING(key, value) \
1565 v = value; \
1566 if (v != NULL) \
1567 PyDict_SetItemString(sysdict, key, v); \
1568 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 /* Check that stdin is not a directory
1571 Using shell redirection, you can redirect stdin to a directory,
1572 crashing the Python interpreter. Catch this common mistake here
1573 and output a useful error message. Note that under MS Windows,
1574 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001575#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 {
1577 struct stat sb;
1578 if (fstat(fileno(stdin), &sb) == 0 &&
1579 S_ISDIR(sb.st_mode)) {
1580 /* There's nothing more we can do. */
1581 /* Py_FatalError() will core dump, so just exit. */
1582 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1583 exit(EXIT_FAILURE);
1584 }
1585 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001586#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 PyDict_SetItemString(sysdict, "__displayhook__",
1591 PyDict_GetItemString(sysdict, "displayhook"));
1592 PyDict_SetItemString(sysdict, "__excepthook__",
1593 PyDict_GetItemString(sysdict, "excepthook"));
1594 SET_SYS_FROM_STRING("version",
1595 PyUnicode_FromString(Py_GetVersion()));
1596 SET_SYS_FROM_STRING("hexversion",
1597 PyLong_FromLong(PY_VERSION_HEX));
1598 svnversion_init();
1599 SET_SYS_FROM_STRING("subversion",
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001600 Py_BuildValue("(sss)", "CPython", branch,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 svn_revision));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001602 SET_SYS_FROM_STRING("_mercurial",
1603 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1604 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 SET_SYS_FROM_STRING("dont_write_bytecode",
1606 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1607 SET_SYS_FROM_STRING("api_version",
1608 PyLong_FromLong(PYTHON_API_VERSION));
1609 SET_SYS_FROM_STRING("copyright",
1610 PyUnicode_FromString(Py_GetCopyright()));
1611 SET_SYS_FROM_STRING("platform",
1612 PyUnicode_FromString(Py_GetPlatform()));
1613 SET_SYS_FROM_STRING("executable",
1614 PyUnicode_FromWideChar(
1615 Py_GetProgramFullPath(), -1));
1616 SET_SYS_FROM_STRING("prefix",
1617 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1618 SET_SYS_FROM_STRING("exec_prefix",
1619 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1620 SET_SYS_FROM_STRING("maxsize",
1621 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1622 SET_SYS_FROM_STRING("float_info",
1623 PyFloat_GetInfo());
1624 SET_SYS_FROM_STRING("int_info",
1625 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001626 /* initialize hash_info */
1627 if (Hash_InfoType.tp_name == 0)
1628 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1629 SET_SYS_FROM_STRING("hash_info",
1630 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 SET_SYS_FROM_STRING("maxunicode",
1632 PyLong_FromLong(PyUnicode_GetMax()));
1633 SET_SYS_FROM_STRING("builtin_module_names",
1634 list_builtin_module_names());
1635 {
1636 /* Assumes that longs are at least 2 bytes long.
1637 Should be safe! */
1638 unsigned long number = 1;
1639 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001640
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001641 s = (char *) &number;
1642 if (s[0] == 0)
1643 value = "big";
1644 else
1645 value = "little";
1646 SET_SYS_FROM_STRING("byteorder",
1647 PyUnicode_FromString(value));
1648 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001649#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 SET_SYS_FROM_STRING("dllhandle",
1651 PyLong_FromVoidPtr(PyWin_DLLhModule));
1652 SET_SYS_FROM_STRING("winver",
1653 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001654#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001655#ifdef ABIFLAGS
1656 SET_SYS_FROM_STRING("abiflags",
1657 PyUnicode_FromString(ABIFLAGS));
1658#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 if (warnoptions == NULL) {
1660 warnoptions = PyList_New(0);
1661 }
1662 else {
1663 Py_INCREF(warnoptions);
1664 }
1665 if (warnoptions != NULL) {
1666 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1667 }
Tim Peters216b78b2006-01-06 02:40:53 +00001668
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001669 v = get_xoptions();
1670 if (v != NULL) {
1671 PyDict_SetItemString(sysdict, "_xoptions", v);
1672 }
1673
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 /* version_info */
1675 if (VersionInfoType.tp_name == 0)
1676 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1677 SET_SYS_FROM_STRING("version_info", make_version_info());
1678 /* prevent user from creating new instances */
1679 VersionInfoType.tp_init = NULL;
1680 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001681
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 /* flags */
1683 if (FlagsType.tp_name == 0)
1684 PyStructSequence_InitType(&FlagsType, &flags_desc);
1685 SET_SYS_FROM_STRING("flags", make_flags());
1686 /* prevent user from creating new instances */
1687 FlagsType.tp_init = NULL;
1688 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001689
Eric Smithf7bb5782010-01-27 00:44:57 +00001690
1691#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* getwindowsversion */
1693 if (WindowsVersionType.tp_name == 0)
1694 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1695 /* prevent user from creating new instances */
1696 WindowsVersionType.tp_init = NULL;
1697 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001698#endif
1699
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001700 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001701#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 SET_SYS_FROM_STRING("float_repr_style",
1703 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001704#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 SET_SYS_FROM_STRING("float_repr_style",
1706 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001707#endif
1708
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001709#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001710 if (PyErr_Occurred())
1711 return NULL;
1712 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001713}
1714
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001715static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001716makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 int i, n;
1719 const wchar_t *p;
1720 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001722 n = 1;
1723 p = path;
1724 while ((p = wcschr(p, delim)) != NULL) {
1725 n++;
1726 p++;
1727 }
1728 v = PyList_New(n);
1729 if (v == NULL)
1730 return NULL;
1731 for (i = 0; ; i++) {
1732 p = wcschr(path, delim);
1733 if (p == NULL)
1734 p = path + wcslen(path); /* End of string */
1735 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1736 if (w == NULL) {
1737 Py_DECREF(v);
1738 return NULL;
1739 }
1740 PyList_SetItem(v, i, w);
1741 if (*p == '\0')
1742 break;
1743 path = p+1;
1744 }
1745 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001746}
1747
1748void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001749PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001750{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 PyObject *v;
1752 if ((v = makepathobject(path, DELIM)) == NULL)
1753 Py_FatalError("can't create sys.path");
1754 if (PySys_SetObject("path", v) != 0)
1755 Py_FatalError("can't assign sys.path");
1756 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001757}
1758
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001759static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001760makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001761{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 PyObject *av;
1763 if (argc <= 0 || argv == NULL) {
1764 /* Ensure at least one (empty) argument is seen */
1765 static wchar_t *empty_argv[1] = {L""};
1766 argv = empty_argv;
1767 argc = 1;
1768 }
1769 av = PyList_New(argc);
1770 if (av != NULL) {
1771 int i;
1772 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001773#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 /* argv[0] is the script pathname if known */
1777 if (i == 0) {
1778 char* fn = decc$translate_vms(argv[0]);
1779 if ((fn == (char *)0) || fn == (char *)-1)
1780 v = PyUnicode_FromString(argv[0]);
1781 else
1782 v = PyUnicode_FromString(
1783 decc$translate_vms(argv[0]));
1784 } else
1785 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001786#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001788#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 if (v == NULL) {
1790 Py_DECREF(av);
1791 av = NULL;
1792 break;
1793 }
1794 PyList_SetItem(av, i, v);
1795 }
1796 }
1797 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001798}
1799
Nick Coghland26c18a2010-08-17 13:06:11 +00001800#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1801 (argc > 0 && argv0 != NULL && \
1802 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001803
1804static void
1805sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001806{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001807 wchar_t *argv0;
1808 wchar_t *p = NULL;
1809 Py_ssize_t n = 0;
1810 PyObject *a;
1811 PyObject *path;
1812#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001813 wchar_t link[MAXPATHLEN+1];
1814 wchar_t argv0copy[2*MAXPATHLEN+1];
1815 int nr = 0;
1816#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001817#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001818 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001819#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001821#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001822
1823 path = PySys_GetObject("path");
1824 if (path == NULL)
1825 return;
1826
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001827 argv0 = argv[0];
1828
1829#ifdef HAVE_READLINK
1830 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1831 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1832 if (nr > 0) {
1833 /* It's a symlink */
1834 link[nr] = '\0';
1835 if (link[0] == SEP)
1836 argv0 = link; /* Link to absolute path */
1837 else if (wcschr(link, SEP) == NULL)
1838 ; /* Link without path */
1839 else {
1840 /* Must join(dirname(argv0), link) */
1841 wchar_t *q = wcsrchr(argv0, SEP);
1842 if (q == NULL)
1843 argv0 = link; /* argv0 without path */
1844 else {
1845 /* Must make a copy */
1846 wcscpy(argv0copy, argv0);
1847 q = wcsrchr(argv0copy, SEP);
1848 wcscpy(q+1, link);
1849 argv0 = argv0copy;
1850 }
1851 }
1852 }
1853#endif /* HAVE_READLINK */
1854#if SEP == '\\' /* Special case for MS filename syntax */
1855 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1856 wchar_t *q;
1857#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1858 /* This code here replaces the first element in argv with the full
1859 path that it represents. Under CE, there are no relative paths so
1860 the argument must be the full path anyway. */
1861 wchar_t *ptemp;
1862 if (GetFullPathNameW(argv0,
1863 sizeof(fullpath)/sizeof(fullpath[0]),
1864 fullpath,
1865 &ptemp)) {
1866 argv0 = fullpath;
1867 }
1868#endif
1869 p = wcsrchr(argv0, SEP);
1870 /* Test for alternate separator */
1871 q = wcsrchr(p ? p : argv0, '/');
1872 if (q != NULL)
1873 p = q;
1874 if (p != NULL) {
1875 n = p + 1 - argv0;
1876 if (n > 1 && p[-1] != ':')
1877 n--; /* Drop trailing separator */
1878 }
1879 }
1880#else /* All other filename syntaxes */
1881 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1882#if defined(HAVE_REALPATH)
Victor Stinner015f4d82010-10-07 22:29:53 +00001883 if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001884 argv0 = fullpath;
1885 }
1886#endif
1887 p = wcsrchr(argv0, SEP);
1888 }
1889 if (p != NULL) {
1890 n = p + 1 - argv0;
1891#if SEP == '/' /* Special case for Unix filename syntax */
1892 if (n > 1)
1893 n--; /* Drop trailing separator */
1894#endif /* Unix */
1895 }
1896#endif /* All others */
1897 a = PyUnicode_FromWideChar(argv0, n);
1898 if (a == NULL)
1899 Py_FatalError("no mem for sys.path insertion");
1900 if (PyList_Insert(path, 0, a) < 0)
1901 Py_FatalError("sys.path.insert(0) failed");
1902 Py_DECREF(a);
1903}
1904
1905void
1906PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
1907{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001909 if (av == NULL)
1910 Py_FatalError("no mem for sys.argv");
1911 if (PySys_SetObject("argv", av) != 0)
1912 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001914 if (updatepath)
1915 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001916}
Guido van Rossuma890e681998-05-12 14:59:24 +00001917
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001918void
1919PySys_SetArgv(int argc, wchar_t **argv)
1920{
1921 PySys_SetArgvEx(argc, argv, 1);
1922}
1923
Victor Stinner14284c22010-04-23 12:02:30 +00001924/* Reimplementation of PyFile_WriteString() no calling indirectly
1925 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1926
1927static int
Victor Stinner79766632010-08-16 17:36:42 +00001928sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001929{
Victor Stinner79766632010-08-16 17:36:42 +00001930 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001931 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00001932
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001933 if (file == NULL)
1934 return -1;
1935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 writer = PyObject_GetAttrString(file, "write");
1937 if (writer == NULL)
1938 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001939
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001940 args = PyTuple_Pack(1, unicode);
1941 if (args == NULL)
1942 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 result = PyEval_CallObject(writer, args);
1945 if (result == NULL) {
1946 goto error;
1947 } else {
1948 err = 0;
1949 goto finally;
1950 }
Victor Stinner14284c22010-04-23 12:02:30 +00001951
1952error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001954finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 Py_XDECREF(writer);
1956 Py_XDECREF(args);
1957 Py_XDECREF(result);
1958 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001959}
1960
Victor Stinner79766632010-08-16 17:36:42 +00001961static int
1962sys_pyfile_write(const char *text, PyObject *file)
1963{
1964 PyObject *unicode = NULL;
1965 int err;
1966
1967 if (file == NULL)
1968 return -1;
1969
1970 unicode = PyUnicode_FromString(text);
1971 if (unicode == NULL)
1972 return -1;
1973
1974 err = sys_pyfile_write_unicode(unicode, file);
1975 Py_DECREF(unicode);
1976 return err;
1977}
Guido van Rossuma890e681998-05-12 14:59:24 +00001978
1979/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1980 Adapted from code submitted by Just van Rossum.
1981
1982 PySys_WriteStdout(format, ...)
1983 PySys_WriteStderr(format, ...)
1984
1985 The first function writes to sys.stdout; the second to sys.stderr. When
1986 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00001987 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00001988
Victor Stinner14284c22010-04-23 12:02:30 +00001989 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00001990 signal handlers: they may raise a new exception whereas sys_write()
1991 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00001992
Guido van Rossuma890e681998-05-12 14:59:24 +00001993 Both take a printf-style format string as their first argument followed
1994 by a variable length argument list determined by the format string.
1995
1996 *** WARNING ***
1997
1998 The format should limit the total size of the formatted output string to
1999 1000 bytes. In particular, this means that no unrestricted "%s" formats
2000 should occur; these should be limited using "%.<N>s where <N> is a
2001 decimal number calculated so that <N> plus the maximum size of other
2002 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2003 which can print hundreds of digits for very large numbers.
2004
2005 */
2006
2007static void
Victor Stinner79766632010-08-16 17:36:42 +00002008sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002010 PyObject *file;
2011 PyObject *error_type, *error_value, *error_traceback;
2012 char buffer[1001];
2013 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002014
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2016 file = PySys_GetObject(name);
2017 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2018 if (sys_pyfile_write(buffer, file) != 0) {
2019 PyErr_Clear();
2020 fputs(buffer, fp);
2021 }
2022 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2023 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002024 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002025 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 }
2027 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002028}
2029
2030void
Guido van Rossuma890e681998-05-12 14:59:24 +00002031PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002033 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002034
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002036 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002038}
2039
2040void
Guido van Rossuma890e681998-05-12 14:59:24 +00002041PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002042{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002043 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002046 sys_write("stderr", stderr, format, va);
2047 va_end(va);
2048}
2049
2050static void
2051sys_format(char *name, FILE *fp, const char *format, va_list va)
2052{
2053 PyObject *file, *message;
2054 PyObject *error_type, *error_value, *error_traceback;
2055 char *utf8;
2056
2057 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2058 file = PySys_GetObject(name);
2059 message = PyUnicode_FromFormatV(format, va);
2060 if (message != NULL) {
2061 if (sys_pyfile_write_unicode(message, file) != 0) {
2062 PyErr_Clear();
2063 utf8 = _PyUnicode_AsString(message);
2064 if (utf8 != NULL)
2065 fputs(utf8, fp);
2066 }
2067 Py_DECREF(message);
2068 }
2069 PyErr_Restore(error_type, error_value, error_traceback);
2070}
2071
2072void
2073PySys_FormatStdout(const char *format, ...)
2074{
2075 va_list va;
2076
2077 va_start(va, format);
2078 sys_format("stdout", stdout, format, va);
2079 va_end(va);
2080}
2081
2082void
2083PySys_FormatStderr(const char *format, ...)
2084{
2085 va_list va;
2086
2087 va_start(va, format);
2088 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002089 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002090}