blob: 5664646381979b3bd652fbe76a006cbdddfc0feb [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);
Victor Stinner27181ac2011-03-31 13:39:03 +0200262 PyErr_SetString(PyExc_RuntimeError,
263 "filesystem encoding is not initialized");
264 return NULL;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000265}
266
267PyDoc_STRVAR(getfilesystemencoding_doc,
268"getfilesystemencoding() -> string\n\
269\n\
270Return the encoding used to convert Unicode filenames in\n\
271operating system filenames."
272);
273
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000274static PyObject *
Georg Brandl66a796e2006-12-19 20:50:34 +0000275sys_intern(PyObject *self, PyObject *args)
276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000277 PyObject *s;
278 if (!PyArg_ParseTuple(args, "U:intern", &s))
279 return NULL;
280 if (PyUnicode_CheckExact(s)) {
281 Py_INCREF(s);
282 PyUnicode_InternInPlace(&s);
283 return s;
284 }
285 else {
286 PyErr_Format(PyExc_TypeError,
287 "can't intern %.400s", s->ob_type->tp_name);
288 return NULL;
289 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000290}
291
292PyDoc_STRVAR(intern_doc,
293"intern(string) -> string\n\
294\n\
295``Intern'' the given string. This enters the string in the (global)\n\
296table of interned strings whose purpose is to speed up dictionary lookups.\n\
297Return the string itself or the previously interned string object with the\n\
298same value.");
299
300
Fred Drake5755ce62001-06-27 19:19:46 +0000301/*
302 * Cached interned string objects used for calling the profile and
303 * trace functions. Initialized by trace_init().
304 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000305static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000306
307static int
308trace_init(void)
309{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 static char *whatnames[7] = {"call", "exception", "line", "return",
311 "c_call", "c_exception", "c_return"};
312 PyObject *name;
313 int i;
314 for (i = 0; i < 7; ++i) {
315 if (whatstrings[i] == NULL) {
316 name = PyUnicode_InternFromString(whatnames[i]);
317 if (name == NULL)
318 return -1;
319 whatstrings[i] = name;
320 }
321 }
322 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000323}
324
325
326static PyObject *
327call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000328 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000329{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 PyObject *args = PyTuple_New(3);
331 PyObject *whatstr;
332 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000333
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000334 if (args == NULL)
335 return NULL;
336 Py_INCREF(frame);
337 whatstr = whatstrings[what];
338 Py_INCREF(whatstr);
339 if (arg == NULL)
340 arg = Py_None;
341 Py_INCREF(arg);
342 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
343 PyTuple_SET_ITEM(args, 1, whatstr);
344 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000345
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000346 /* call the Python-level function */
347 PyFrame_FastToLocals(frame);
348 result = PyEval_CallObject(callback, args);
349 PyFrame_LocalsToFast(frame, 1);
350 if (result == NULL)
351 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000352
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 /* cleanup */
354 Py_DECREF(args);
355 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000356}
357
358static int
359profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000360 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000361{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000362 PyThreadState *tstate = frame->f_tstate;
363 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000364
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000365 if (arg == NULL)
366 arg = Py_None;
367 result = call_trampoline(tstate, self, frame, what, arg);
368 if (result == NULL) {
369 PyEval_SetProfile(NULL, NULL);
370 return -1;
371 }
372 Py_DECREF(result);
373 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000374}
375
376static int
377trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000379{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 PyThreadState *tstate = frame->f_tstate;
381 PyObject *callback;
382 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000383
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000384 if (what == PyTrace_CALL)
385 callback = self;
386 else
387 callback = frame->f_trace;
388 if (callback == NULL)
389 return 0;
390 result = call_trampoline(tstate, callback, frame, what, arg);
391 if (result == NULL) {
392 PyEval_SetTrace(NULL, NULL);
393 Py_XDECREF(frame->f_trace);
394 frame->f_trace = NULL;
395 return -1;
396 }
397 if (result != Py_None) {
398 PyObject *temp = frame->f_trace;
399 frame->f_trace = NULL;
400 Py_XDECREF(temp);
401 frame->f_trace = result;
402 }
403 else {
404 Py_DECREF(result);
405 }
406 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000407}
Fred Draked0838392001-06-16 21:02:31 +0000408
Fred Drake8b4d01d2000-05-09 19:57:01 +0000409static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000410sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000412 if (trace_init() == -1)
413 return NULL;
414 if (args == Py_None)
415 PyEval_SetTrace(NULL, NULL);
416 else
417 PyEval_SetTrace(trace_trampoline, args);
418 Py_INCREF(Py_None);
419 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000420}
421
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000422PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000423"settrace(function)\n\
424\n\
425Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000426function call. See the debugger chapter in the library manual."
427);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000428
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000429static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000430sys_gettrace(PyObject *self, PyObject *args)
431{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000432 PyThreadState *tstate = PyThreadState_GET();
433 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000434
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 if (temp == NULL)
436 temp = Py_None;
437 Py_INCREF(temp);
438 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000439}
440
441PyDoc_STRVAR(gettrace_doc,
442"gettrace()\n\
443\n\
444Return the global debug tracing function set with sys.settrace.\n\
445See the debugger chapter in the library manual."
446);
447
448static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000449sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000451 if (trace_init() == -1)
452 return NULL;
453 if (args == Py_None)
454 PyEval_SetProfile(NULL, NULL);
455 else
456 PyEval_SetProfile(profile_trampoline, args);
457 Py_INCREF(Py_None);
458 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000459}
460
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000461PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000462"setprofile(function)\n\
463\n\
464Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000465and return. See the profiler chapter in the library manual."
466);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000467
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000468static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000469sys_getprofile(PyObject *self, PyObject *args)
470{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 PyThreadState *tstate = PyThreadState_GET();
472 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000473
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000474 if (temp == NULL)
475 temp = Py_None;
476 Py_INCREF(temp);
477 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000478}
479
480PyDoc_STRVAR(getprofile_doc,
481"getprofile()\n\
482\n\
483Return the profiling function set with sys.setprofile.\n\
484See the profiler chapter in the library manual."
485);
486
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000487static int _check_interval = 100;
488
Christian Heimes9bd667a2008-01-20 15:14:11 +0000489static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000490sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000491{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000492 if (PyErr_WarnEx(PyExc_DeprecationWarning,
493 "sys.getcheckinterval() and sys.setcheckinterval() "
494 "are deprecated. Use sys.setswitchinterval() "
495 "instead.", 1) < 0)
496 return NULL;
497 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
498 return NULL;
499 Py_INCREF(Py_None);
500 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000501}
502
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000503PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000504"setcheckinterval(n)\n\
505\n\
506Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000507n instructions. This also affects how often thread switches occur."
508);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000509
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000510static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000511sys_getcheckinterval(PyObject *self, PyObject *args)
512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000513 if (PyErr_WarnEx(PyExc_DeprecationWarning,
514 "sys.getcheckinterval() and sys.setcheckinterval() "
515 "are deprecated. Use sys.getswitchinterval() "
516 "instead.", 1) < 0)
517 return NULL;
518 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000519}
520
521PyDoc_STRVAR(getcheckinterval_doc,
522"getcheckinterval() -> current check interval; see setcheckinterval()."
523);
524
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000525#ifdef WITH_THREAD
526static PyObject *
527sys_setswitchinterval(PyObject *self, PyObject *args)
528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000529 double d;
530 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
531 return NULL;
532 if (d <= 0.0) {
533 PyErr_SetString(PyExc_ValueError,
534 "switch interval must be strictly positive");
535 return NULL;
536 }
537 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
538 Py_INCREF(Py_None);
539 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000540}
541
542PyDoc_STRVAR(setswitchinterval_doc,
543"setswitchinterval(n)\n\
544\n\
545Set the ideal thread switching delay inside the Python interpreter\n\
546The actual frequency of switching threads can be lower if the\n\
547interpreter executes long sequences of uninterruptible code\n\
548(this is implementation-specific and workload-dependent).\n\
549\n\
550The parameter must represent the desired switching delay in seconds\n\
551A typical value is 0.005 (5 milliseconds)."
552);
553
554static PyObject *
555sys_getswitchinterval(PyObject *self, PyObject *args)
556{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000557 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000558}
559
560PyDoc_STRVAR(getswitchinterval_doc,
561"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
562);
563
564#endif /* WITH_THREAD */
565
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000566#ifdef WITH_TSC
567static PyObject *
568sys_settscdump(PyObject *self, PyObject *args)
569{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000570 int bool;
571 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000573 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
574 return NULL;
575 if (bool)
576 tstate->interp->tscdump = 1;
577 else
578 tstate->interp->tscdump = 0;
579 Py_INCREF(Py_None);
580 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000581
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000582}
583
Tim Peters216b78b2006-01-06 02:40:53 +0000584PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000585"settscdump(bool)\n\
586\n\
587If true, tell the Python interpreter to dump VM measurements to\n\
588stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000589processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000590);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000591#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000592
Tim Peterse5e065b2003-07-06 18:36:54 +0000593static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000594sys_setrecursionlimit(PyObject *self, PyObject *args)
595{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000596 int new_limit;
597 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
598 return NULL;
599 if (new_limit <= 0) {
600 PyErr_SetString(PyExc_ValueError,
601 "recursion limit must be positive");
602 return NULL;
603 }
604 Py_SetRecursionLimit(new_limit);
605 Py_INCREF(Py_None);
606 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000607}
608
Mark Dickinsondc787d22010-05-23 13:33:13 +0000609static PyTypeObject Hash_InfoType;
610
611PyDoc_STRVAR(hash_info_doc,
612"hash_info\n\
613\n\
614A struct sequence providing parameters used for computing\n\
615numeric hashes. The attributes are read only.");
616
617static PyStructSequence_Field hash_info_fields[] = {
618 {"width", "width of the type used for hashing, in bits"},
619 {"modulus", "prime number giving the modulus on which the hash "
620 "function is based"},
621 {"inf", "value to be used for hash of a positive infinity"},
622 {"nan", "value to be used for hash of a nan"},
623 {"imag", "multiplier used for the imaginary part of a complex number"},
624 {NULL, NULL}
625};
626
627static PyStructSequence_Desc hash_info_desc = {
628 "sys.hash_info",
629 hash_info_doc,
630 hash_info_fields,
631 5,
632};
633
Matthias Klosed885e952010-07-06 10:53:30 +0000634static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000635get_hash_info(void)
636{
637 PyObject *hash_info;
638 int field = 0;
639 hash_info = PyStructSequence_New(&Hash_InfoType);
640 if (hash_info == NULL)
641 return NULL;
642 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000643 PyLong_FromLong(8*sizeof(Py_hash_t)));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000644 PyStructSequence_SET_ITEM(hash_info, field++,
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000645 PyLong_FromSsize_t(_PyHASH_MODULUS));
Mark Dickinsondc787d22010-05-23 13:33:13 +0000646 PyStructSequence_SET_ITEM(hash_info, field++,
647 PyLong_FromLong(_PyHASH_INF));
648 PyStructSequence_SET_ITEM(hash_info, field++,
649 PyLong_FromLong(_PyHASH_NAN));
650 PyStructSequence_SET_ITEM(hash_info, field++,
651 PyLong_FromLong(_PyHASH_IMAG));
652 if (PyErr_Occurred()) {
653 Py_CLEAR(hash_info);
654 return NULL;
655 }
656 return hash_info;
657}
658
659
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000660PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000661"setrecursionlimit(n)\n\
662\n\
663Set the maximum depth of the Python interpreter stack to n. This\n\
664limit prevents infinite recursion from causing an overflow of the C\n\
665stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000666dependent."
667);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000668
669static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000670sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000671{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000672 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000673}
674
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000675PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000676"getrecursionlimit()\n\
677\n\
678Return the current value of the recursion limit, the maximum depth\n\
679of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000680recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000681);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000682
Mark Hammond8696ebc2002-10-08 02:44:31 +0000683#ifdef MS_WINDOWS
684PyDoc_STRVAR(getwindowsversion_doc,
685"getwindowsversion()\n\
686\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000687Return information about the running version of Windows as a named tuple.\n\
688The members are named: major, minor, build, platform, service_pack,\n\
689service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti4969f702011-03-15 05:59:46 +0200690backward compatibility, only the first 5 items are available by indexing.\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000691All elements are numbers, except service_pack which is a string. Platform\n\
692may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6933 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
694controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000695);
696
Eric Smithf7bb5782010-01-27 00:44:57 +0000697static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
698
699static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 {"major", "Major version number"},
701 {"minor", "Minor version number"},
702 {"build", "Build number"},
703 {"platform", "Operating system platform"},
704 {"service_pack", "Latest Service Pack installed on the system"},
705 {"service_pack_major", "Service Pack major version number"},
706 {"service_pack_minor", "Service Pack minor version number"},
707 {"suite_mask", "Bit mask identifying available product suites"},
708 {"product_type", "System product type"},
709 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000710};
711
712static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000713 "sys.getwindowsversion", /* name */
714 getwindowsversion_doc, /* doc */
715 windows_version_fields, /* fields */
716 5 /* For backward compatibility,
717 only the first 5 items are accessible
718 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000719};
720
Mark Hammond8696ebc2002-10-08 02:44:31 +0000721static PyObject *
722sys_getwindowsversion(PyObject *self)
723{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000724 PyObject *version;
725 int pos = 0;
726 OSVERSIONINFOEX ver;
727 ver.dwOSVersionInfoSize = sizeof(ver);
728 if (!GetVersionEx((OSVERSIONINFO*) &ver))
729 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000730
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000731 version = PyStructSequence_New(&WindowsVersionType);
732 if (version == NULL)
733 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000735 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
736 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
737 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
738 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
739 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
740 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
741 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
742 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
743 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000744
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000745 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000746}
747
748#endif /* MS_WINDOWS */
749
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000750#ifdef HAVE_DLOPEN
751static PyObject *
752sys_setdlopenflags(PyObject *self, PyObject *args)
753{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 int new_val;
755 PyThreadState *tstate = PyThreadState_GET();
756 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
757 return NULL;
758 if (!tstate)
759 return NULL;
760 tstate->interp->dlopenflags = new_val;
761 Py_INCREF(Py_None);
762 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000763}
764
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000765PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000766"setdlopenflags(n) -> None\n\
767\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000768Set the flags used by the interpreter for dlopen calls, such as when the\n\
769interpreter loads extension modules. Among other things, this will enable\n\
770a lazy resolving of symbols when importing a module, if called as\n\
771sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
772sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
773can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
774is not available, it can be generated from /usr/include/dlfcn.h using the\n\
775h2py script.");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000776
777static PyObject *
778sys_getdlopenflags(PyObject *self, PyObject *args)
779{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 PyThreadState *tstate = PyThreadState_GET();
781 if (!tstate)
782 return NULL;
783 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000784}
785
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000786PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000787"getdlopenflags() -> int\n\
788\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000789Return the current value of the flags that are used for dlopen calls.\n\
790The flag constants are defined in the ctypes and DLFCN modules.");
791
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000792#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000793
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000794#ifdef USE_MALLOPT
795/* Link with -lmalloc (or -lmpc) on an SGI */
796#include <malloc.h>
797
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000798static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000799sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000800{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000801 int flag;
802 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
803 return NULL;
804 mallopt(M_DEBUG, flag);
805 Py_INCREF(Py_None);
806 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000807}
808#endif /* USE_MALLOPT */
809
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000810static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000811sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000812{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000813 PyObject *res = NULL;
814 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
815 static char *kwlist[] = {"object", "default", 0};
816 PyObject *o, *dflt = NULL;
817 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000818
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000819 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
820 kwlist, &o, &dflt))
821 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000822
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000823 /* Initialize static variable for GC head size */
824 if (gc_head_size == NULL) {
825 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
826 if (gc_head_size == NULL)
827 return NULL;
828 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000829
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000830 /* Make sure the type is initialized. float gets initialized late */
831 if (PyType_Ready(Py_TYPE(o)) < 0)
832 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000833
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 method = _PyObject_LookupSpecial(o, "__sizeof__",
835 &str__sizeof__);
836 if (method == NULL) {
837 if (!PyErr_Occurred())
838 PyErr_Format(PyExc_TypeError,
839 "Type %.100s doesn't define __sizeof__",
840 Py_TYPE(o)->tp_name);
841 }
842 else {
843 res = PyObject_CallFunctionObjArgs(method, NULL);
844 Py_DECREF(method);
845 }
846
847 /* Has a default value been given */
848 if ((res == NULL) && (dflt != NULL) &&
849 PyErr_ExceptionMatches(PyExc_TypeError))
850 {
851 PyErr_Clear();
852 Py_INCREF(dflt);
853 return dflt;
854 }
855 else if (res == NULL)
856 return res;
857
858 /* add gc_head size */
859 if (PyObject_IS_GC(o)) {
860 PyObject *tmp = res;
861 res = PyNumber_Add(tmp, gc_head_size);
862 Py_DECREF(tmp);
863 }
864 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000865}
866
867PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000868"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000869\n\
870Return the size of object in bytes.");
871
872static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000873sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000874{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000875 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000876}
877
Tim Peters4be93d02002-07-07 19:59:50 +0000878#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000879static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000880sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000882 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000883}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000884#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000885
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000886PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000887"getrefcount(object) -> integer\n\
888\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000889Return the reference count of object. The count returned is generally\n\
890one higher than you might expect, because it includes the (temporary)\n\
891reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000892);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000893
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000894#ifdef COUNT_ALLOCS
895static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000896sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000899
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000900 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000901}
902#endif
903
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000904PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000905"_getframe([depth]) -> frameobject\n\
906\n\
907Return a frame object from the call stack. If optional integer depth is\n\
908given, return the frame object that many calls below the top of the stack.\n\
909If that is deeper than the call stack, ValueError is raised. The default\n\
910for depth is zero, returning the frame at the top of the call stack.\n\
911\n\
912This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000913purposes only."
914);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000915
916static PyObject *
917sys_getframe(PyObject *self, PyObject *args)
918{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000919 PyFrameObject *f = PyThreadState_GET()->frame;
920 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000921
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000922 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
923 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 while (depth > 0 && f != NULL) {
926 f = f->f_back;
927 --depth;
928 }
929 if (f == NULL) {
930 PyErr_SetString(PyExc_ValueError,
931 "call stack is not deep enough");
932 return NULL;
933 }
934 Py_INCREF(f);
935 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000936}
937
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000938PyDoc_STRVAR(current_frames_doc,
939"_current_frames() -> dictionary\n\
940\n\
941Return a dictionary mapping each current thread T's thread id to T's\n\
942current stack frame.\n\
943\n\
944This function should be used for specialized purposes only."
945);
946
947static PyObject *
948sys_current_frames(PyObject *self, PyObject *noargs)
949{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000950 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000951}
952
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000953PyDoc_STRVAR(call_tracing_doc,
954"call_tracing(func, args) -> object\n\
955\n\
956Call func(*args), while tracing is enabled. The tracing state is\n\
957saved, and restored afterwards. This is intended to be called from\n\
958a debugger from a checkpoint, to recursively debug some other code."
959);
960
961static PyObject *
962sys_call_tracing(PyObject *self, PyObject *args)
963{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000964 PyObject *func, *funcargs;
965 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
966 return NULL;
967 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000968}
969
Jeremy Hylton985eba52003-02-05 23:13:00 +0000970PyDoc_STRVAR(callstats_doc,
971"callstats() -> tuple of integers\n\
972\n\
973Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
974when Python was built. Otherwise, return None.\n\
975\n\
976When enabled, this function returns detailed, implementation-specific\n\
977details about the number of function calls executed. The return value is\n\
978a 11-tuple where the entries in the tuple are counts of:\n\
9790. all function calls\n\
9801. calls to PyFunction_Type objects\n\
9812. PyFunction calls that do not create an argument tuple\n\
9823. PyFunction calls that do not create an argument tuple\n\
983 and bypass PyEval_EvalCodeEx()\n\
9844. PyMethod calls\n\
9855. PyMethod calls on bound methods\n\
9866. PyType calls\n\
9877. PyCFunction calls\n\
9888. generator calls\n\
9899. All other calls\n\
99010. Number of stack pops performed by call_function()"
991);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000992
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000993#ifdef __cplusplus
994extern "C" {
995#endif
996
Guido van Rossum7f3f2c11996-05-23 22:45:41 +0000997#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +0000998/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000999extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001000#endif
Guido van Rossumded690f1996-05-24 20:48:31 +00001001
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001002#ifdef DYNAMIC_EXECUTION_PROFILE
1003/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +00001004extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001005#endif
1006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001007#ifdef __cplusplus
1008}
1009#endif
1010
Christian Heimes15ebc882008-02-04 18:48:49 +00001011static PyObject *
1012sys_clear_type_cache(PyObject* self, PyObject* args)
1013{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 PyType_ClearCache();
1015 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +00001016}
1017
1018PyDoc_STRVAR(sys_clear_type_cache__doc__,
1019"_clear_type_cache() -> None\n\
1020Clear the internal type lookup cache.");
1021
1022
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001023static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001024 /* Might as well keep this in alphabetic order */
1025 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
1026 callstats_doc},
1027 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
1028 sys_clear_type_cache__doc__},
1029 {"_current_frames", sys_current_frames, METH_NOARGS,
1030 current_frames_doc},
1031 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
1032 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
1033 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
1034 {"exit", sys_exit, METH_VARARGS, exit_doc},
1035 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1036 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001037#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1039 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001040#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001041#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001043#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001044#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001045 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001046#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1048 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001049#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001050 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001051#endif
1052#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001054#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1056 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1057 getrecursionlimit_doc},
1058 {"getsizeof", (PyCFunction)sys_getsizeof,
1059 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1060 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001061#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001062 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1063 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001064#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001065 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001066#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001068#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001069 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1070 setcheckinterval_doc},
1071 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1072 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001073#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1075 setswitchinterval_doc},
1076 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1077 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001078#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001079#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1081 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001082#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001083 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1084 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1085 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1086 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001087#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001088 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001089#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001090 {"settrace", sys_settrace, METH_O, settrace_doc},
1091 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1092 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1093 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001094};
1095
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001096static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001097list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001098{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001099 PyObject *list = PyList_New(0);
1100 int i;
1101 if (list == NULL)
1102 return NULL;
1103 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1104 PyObject *name = PyUnicode_FromString(
1105 PyImport_Inittab[i].name);
1106 if (name == NULL)
1107 break;
1108 PyList_Append(list, name);
1109 Py_DECREF(name);
1110 }
1111 if (PyList_Sort(list) != 0) {
1112 Py_DECREF(list);
1113 list = NULL;
1114 }
1115 if (list) {
1116 PyObject *v = PyList_AsTuple(list);
1117 Py_DECREF(list);
1118 list = v;
1119 }
1120 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001121}
1122
Guido van Rossum23fff912000-12-15 22:02:05 +00001123static PyObject *warnoptions = NULL;
1124
1125void
1126PySys_ResetWarnOptions(void)
1127{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001128 if (warnoptions == NULL || !PyList_Check(warnoptions))
1129 return;
1130 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001131}
1132
1133void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001134PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001135{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001136 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1137 Py_XDECREF(warnoptions);
1138 warnoptions = PyList_New(0);
1139 if (warnoptions == NULL)
1140 return;
1141 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001142 PyList_Append(warnoptions, unicode);
1143}
1144
1145void
1146PySys_AddWarnOption(const wchar_t *s)
1147{
1148 PyObject *unicode;
1149 unicode = PyUnicode_FromWideChar(s, -1);
1150 if (unicode == NULL)
1151 return;
1152 PySys_AddWarnOptionUnicode(unicode);
1153 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001154}
1155
Christian Heimes33fe8092008-04-13 13:53:33 +00001156int
1157PySys_HasWarnOptions(void)
1158{
1159 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1160}
1161
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001162static PyObject *xoptions = NULL;
1163
1164static PyObject *
1165get_xoptions(void)
1166{
1167 if (xoptions == NULL || !PyDict_Check(xoptions)) {
1168 Py_XDECREF(xoptions);
1169 xoptions = PyDict_New();
1170 }
1171 return xoptions;
1172}
1173
1174void
1175PySys_AddXOption(const wchar_t *s)
1176{
1177 PyObject *opts;
1178 PyObject *name = NULL, *value = NULL;
1179 const wchar_t *name_end;
1180 int r;
1181
1182 opts = get_xoptions();
1183 if (opts == NULL)
1184 goto error;
1185
1186 name_end = wcschr(s, L'=');
1187 if (!name_end) {
1188 name = PyUnicode_FromWideChar(s, -1);
1189 value = Py_True;
1190 Py_INCREF(value);
1191 }
1192 else {
1193 name = PyUnicode_FromWideChar(s, name_end - s);
1194 value = PyUnicode_FromWideChar(name_end + 1, -1);
1195 }
1196 if (name == NULL || value == NULL)
1197 goto error;
1198 r = PyDict_SetItem(opts, name, value);
1199 Py_DECREF(name);
1200 Py_DECREF(value);
1201 return;
1202
1203error:
1204 Py_XDECREF(name);
1205 Py_XDECREF(value);
1206 /* No return value, therefore clear error state if possible */
1207 if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
1208 PyErr_Clear();
1209}
1210
1211PyObject *
1212PySys_GetXOptions(void)
1213{
1214 return get_xoptions();
1215}
1216
Guido van Rossum40552d01998-08-06 03:34:39 +00001217/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1218 Two literals concatenated works just fine. If you have a K&R compiler
1219 or other abomination that however *does* understand longer strings,
1220 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001221PyDoc_VAR(sys_doc) =
1222PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001223"This module provides access to some objects used or maintained by the\n\
1224interpreter and to functions that interact strongly with the interpreter.\n\
1225\n\
1226Dynamic objects:\n\
1227\n\
1228argv -- command line arguments; argv[0] is the script pathname if known\n\
1229path -- module search path; path[0] is the script directory, else ''\n\
1230modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001231\n\
1232displayhook -- called to show results in an interactive session\n\
1233excepthook -- called to handle any uncaught exception other than SystemExit\n\
1234 To customize printing in an interactive session or to install a custom\n\
1235 top-level exception handler, assign other functions to replace these.\n\
1236\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001237stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001238stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001239stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001240 By assigning other file objects (or objects that behave like files)\n\
1241 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001242\n\
1243last_type -- type of last uncaught exception\n\
1244last_value -- value of last uncaught exception\n\
1245last_traceback -- traceback of last uncaught exception\n\
1246 These three are only available in an interactive session after a\n\
1247 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001248"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001249)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001250/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001251PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001252"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001253Static objects:\n\
1254\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001255float_info -- a dict with information about the float implementation.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001256int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001257maxsize -- the largest supported length of containers.\n\
Martin v. Löwisce9b5a52001-06-27 06:28:56 +00001258maxunicode -- the largest supported character\n\
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001259builtin_module_names -- tuple of module names built into this interpreter\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001260subversion -- subversion information of the build as tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001261version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001262version_info -- version information as a named tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001263hexversion -- version information encoded as a single integer\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001264copyright -- copyright notice pertaining to this interpreter\n\
1265platform -- platform identifier\n\
1266executable -- pathname of this Python interpreter\n\
1267prefix -- prefix used to find the Python library\n\
1268exec_prefix -- prefix used to find the machine-specific Python library\n\
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001269float_repr_style -- string indicating the style of repr() output for floats\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001270"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001271)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001272#ifdef MS_WINDOWS
1273/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001274PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001275"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001276winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001277"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001278)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001279#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001280PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001281"__stdin__ -- the original stdin; don't touch!\n\
1282__stdout__ -- the original stdout; don't touch!\n\
1283__stderr__ -- the original stderr; don't touch!\n\
1284__displayhook__ -- the original displayhook; don't touch!\n\
1285__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001286\n\
1287Functions:\n\
1288\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001289displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001290excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001291exc_info() -- return thread-safe information about the current exception\n\
1292exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001293getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001294getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001295getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001296getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001297getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001298gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001299setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001300setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001301setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001302setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001303settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001304"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001305)
Fred Drakeccede592000-08-14 20:59:57 +00001306/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001307
Martin v. Löwis43b57802006-01-05 23:38:54 +00001308/* Subversion branch and revision management */
1309static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION;
1310static const char headurl[] = "$HeadURL$";
1311static int svn_initialized;
1312static char patchlevel_revision[50]; /* Just the number */
1313static char branch[50];
1314static char shortbranch[50];
1315static const char *svn_revision;
1316
Tim Peterse86e7a52006-01-06 02:42:46 +00001317static void
1318svnversion_init(void)
Martin v. Löwis43b57802006-01-05 23:38:54 +00001319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 const char *python, *br_start, *br_end, *br_end2, *svnversion;
1321 Py_ssize_t len;
1322 int istag = 0;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 if (svn_initialized)
1325 return;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001326
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 python = strstr(headurl, "/python/");
1328 if (!python) {
1329 strcpy(branch, "unknown branch");
1330 strcpy(shortbranch, "unknown");
1331 }
1332 else {
1333 br_start = python + 8;
1334 br_end = strchr(br_start, '/');
1335 assert(br_end);
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001336
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 /* Works even for trunk,
1338 as we are in trunk/Python/sysmodule.c */
1339 br_end2 = strchr(br_end+1, '/');
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 istag = strncmp(br_start, "tags", 4) == 0;
1342 if (strncmp(br_start, "trunk", 5) == 0) {
1343 strcpy(branch, "trunk");
1344 strcpy(shortbranch, "trunk");
1345 }
1346 else if (istag || strncmp(br_start, "branches", 8) == 0) {
1347 len = br_end2 - br_start;
1348 strncpy(branch, br_start, len);
1349 branch[len] = '\0';
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001351 len = br_end2 - (br_end + 1);
1352 strncpy(shortbranch, br_end + 1, len);
1353 shortbranch[len] = '\0';
1354 }
1355 else {
1356 Py_FatalError("bad HeadURL");
1357 return;
1358 }
1359 }
Martin v. Löwis43b57802006-01-05 23:38:54 +00001360
1361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 svnversion = _Py_svnversion();
1363 if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0)
1364 svn_revision = svnversion;
1365 else if (istag) {
1366 len = strlen(_patchlevel_revision);
1367 assert(len >= 13);
1368 assert(len < (sizeof(patchlevel_revision) + 13));
1369 strncpy(patchlevel_revision, _patchlevel_revision + 11,
1370 len - 13);
1371 patchlevel_revision[len - 13] = '\0';
1372 svn_revision = patchlevel_revision;
1373 }
1374 else
1375 svn_revision = "";
Tim Peters216b78b2006-01-06 02:40:53 +00001376
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 svn_initialized = 1;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001378}
1379
1380/* Return svnversion output if available.
1381 Else return Revision of patchlevel.h if on branch.
1382 Else return empty string */
1383const char*
1384Py_SubversionRevision()
1385{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 svnversion_init();
1387 return svn_revision;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001388}
1389
1390const char*
1391Py_SubversionShortBranch()
1392{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001393 svnversion_init();
1394 return shortbranch;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001395}
1396
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001397
1398PyDoc_STRVAR(flags__doc__,
1399"sys.flags\n\
1400\n\
1401Flags provided through command line arguments or environment vars.");
1402
1403static PyTypeObject FlagsType;
1404
1405static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 {"debug", "-d"},
1407 {"division_warning", "-Q"},
1408 {"inspect", "-i"},
1409 {"interactive", "-i"},
1410 {"optimize", "-O or -OO"},
1411 {"dont_write_bytecode", "-B"},
1412 {"no_user_site", "-s"},
1413 {"no_site", "-S"},
1414 {"ignore_environment", "-E"},
1415 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001416#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001418#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001419 /* {"unbuffered", "-u"}, */
1420 /* {"skip_first", "-x"}, */
Georg Brandl8aa7e992010-12-28 18:30:18 +00001421 {"bytes_warning", "-b"},
1422 {"quiet", "-q"},
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001424};
1425
1426static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001427 "sys.flags", /* name */
1428 flags__doc__, /* doc */
1429 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001430#ifdef RISCOS
Raymond Hettinger90e8f8c2011-01-05 20:08:25 +00001431 13
Georg Brandle1b5ac62008-06-04 13:06:58 +00001432#else
Raymond Hettinger90e8f8c2011-01-05 20:08:25 +00001433 12
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001434#endif
1435};
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);
1451 SetFlag(Py_DivisionWarningFlag);
1452 SetFlag(Py_InspectFlag);
1453 SetFlag(Py_InteractiveFlag);
1454 SetFlag(Py_OptimizeFlag);
1455 SetFlag(Py_DontWriteBytecodeFlag);
1456 SetFlag(Py_NoUserSiteDirectory);
1457 SetFlag(Py_NoSiteFlag);
1458 SetFlag(Py_IgnoreEnvironmentFlag);
1459 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001460#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001462#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 /* SetFlag(saw_unbuffered_flag); */
1464 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001465 SetFlag(Py_BytesWarningFlag);
Georg Brandl8aa7e992010-12-28 18:30:18 +00001466 SetFlag(Py_QuietFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001467#undef SetFlag
1468
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 if (PyErr_Occurred()) {
1470 return NULL;
1471 }
1472 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001473}
1474
Eric Smith0e5b5622009-02-06 01:32:42 +00001475PyDoc_STRVAR(version_info__doc__,
1476"sys.version_info\n\
1477\n\
1478Version information as a named tuple.");
1479
1480static PyTypeObject VersionInfoType;
1481
1482static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 {"major", "Major release number"},
1484 {"minor", "Minor release number"},
1485 {"micro", "Patch release number"},
1486 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1487 {"serial", "Serial release number"},
1488 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001489};
1490
1491static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001492 "sys.version_info", /* name */
1493 version_info__doc__, /* doc */
1494 version_info_fields, /* fields */
1495 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001496};
1497
1498static PyObject *
1499make_version_info(void)
1500{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 PyObject *version_info;
1502 char *s;
1503 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001504
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001505 version_info = PyStructSequence_New(&VersionInfoType);
1506 if (version_info == NULL) {
1507 return NULL;
1508 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001509
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001510 /*
1511 * These release level checks are mutually exclusive and cover
1512 * the field, so don't get too fancy with the pre-processor!
1513 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001514#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001515 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001516#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001518#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001520#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001522#endif
1523
1524#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001526#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001527 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 SetIntItem(PY_MAJOR_VERSION);
1530 SetIntItem(PY_MINOR_VERSION);
1531 SetIntItem(PY_MICRO_VERSION);
1532 SetStrItem(s);
1533 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001534#undef SetIntItem
1535#undef SetStrItem
1536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (PyErr_Occurred()) {
1538 Py_CLEAR(version_info);
1539 return NULL;
1540 }
1541 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001542}
1543
Martin v. Löwis1a214512008-06-11 05:26:20 +00001544static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 PyModuleDef_HEAD_INIT,
1546 "sys",
1547 sys_doc,
1548 -1, /* multiple "initialization" just copies the module dict. */
1549 sys_methods,
1550 NULL,
1551 NULL,
1552 NULL,
1553 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001554};
1555
Guido van Rossum25ce5661997-08-02 03:10:38 +00001556PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001557_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001558{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 PyObject *m, *v, *sysdict;
1560 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 m = PyModule_Create(&sysmodule);
1563 if (m == NULL)
1564 return NULL;
1565 sysdict = PyModule_GetDict(m);
1566#define SET_SYS_FROM_STRING(key, value) \
1567 v = value; \
1568 if (v != NULL) \
1569 PyDict_SetItemString(sysdict, key, v); \
1570 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001571
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001572 /* Check that stdin is not a directory
1573 Using shell redirection, you can redirect stdin to a directory,
1574 crashing the Python interpreter. Catch this common mistake here
1575 and output a useful error message. Note that under MS Windows,
1576 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001577#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 {
1579 struct stat sb;
1580 if (fstat(fileno(stdin), &sb) == 0 &&
1581 S_ISDIR(sb.st_mode)) {
1582 /* There's nothing more we can do. */
1583 /* Py_FatalError() will core dump, so just exit. */
1584 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1585 exit(EXIT_FAILURE);
1586 }
1587 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001588#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001589
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001590 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 PyDict_SetItemString(sysdict, "__displayhook__",
1593 PyDict_GetItemString(sysdict, "displayhook"));
1594 PyDict_SetItemString(sysdict, "__excepthook__",
1595 PyDict_GetItemString(sysdict, "excepthook"));
1596 SET_SYS_FROM_STRING("version",
1597 PyUnicode_FromString(Py_GetVersion()));
1598 SET_SYS_FROM_STRING("hexversion",
1599 PyLong_FromLong(PY_VERSION_HEX));
1600 svnversion_init();
1601 SET_SYS_FROM_STRING("subversion",
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001602 Py_BuildValue("(sss)", "CPython", branch,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 svn_revision));
Georg Brandl1ca2e792011-03-05 20:51:24 +01001604 SET_SYS_FROM_STRING("_mercurial",
1605 Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1606 _Py_hgversion()));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 SET_SYS_FROM_STRING("dont_write_bytecode",
1608 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1609 SET_SYS_FROM_STRING("api_version",
1610 PyLong_FromLong(PYTHON_API_VERSION));
1611 SET_SYS_FROM_STRING("copyright",
1612 PyUnicode_FromString(Py_GetCopyright()));
1613 SET_SYS_FROM_STRING("platform",
1614 PyUnicode_FromString(Py_GetPlatform()));
1615 SET_SYS_FROM_STRING("executable",
1616 PyUnicode_FromWideChar(
1617 Py_GetProgramFullPath(), -1));
1618 SET_SYS_FROM_STRING("prefix",
1619 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1620 SET_SYS_FROM_STRING("exec_prefix",
1621 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1622 SET_SYS_FROM_STRING("maxsize",
1623 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1624 SET_SYS_FROM_STRING("float_info",
1625 PyFloat_GetInfo());
1626 SET_SYS_FROM_STRING("int_info",
1627 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001628 /* initialize hash_info */
1629 if (Hash_InfoType.tp_name == 0)
1630 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1631 SET_SYS_FROM_STRING("hash_info",
1632 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 SET_SYS_FROM_STRING("maxunicode",
1634 PyLong_FromLong(PyUnicode_GetMax()));
1635 SET_SYS_FROM_STRING("builtin_module_names",
1636 list_builtin_module_names());
1637 {
1638 /* Assumes that longs are at least 2 bytes long.
1639 Should be safe! */
1640 unsigned long number = 1;
1641 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 s = (char *) &number;
1644 if (s[0] == 0)
1645 value = "big";
1646 else
1647 value = "little";
1648 SET_SYS_FROM_STRING("byteorder",
1649 PyUnicode_FromString(value));
1650 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001651#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 SET_SYS_FROM_STRING("dllhandle",
1653 PyLong_FromVoidPtr(PyWin_DLLhModule));
1654 SET_SYS_FROM_STRING("winver",
1655 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001656#endif
Barry Warsaw8cf4eae2010-10-16 01:04:07 +00001657#ifdef ABIFLAGS
1658 SET_SYS_FROM_STRING("abiflags",
1659 PyUnicode_FromString(ABIFLAGS));
1660#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001661 if (warnoptions == NULL) {
1662 warnoptions = PyList_New(0);
1663 }
1664 else {
1665 Py_INCREF(warnoptions);
1666 }
1667 if (warnoptions != NULL) {
1668 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1669 }
Tim Peters216b78b2006-01-06 02:40:53 +00001670
Antoine Pitrou9583cac2010-10-21 13:42:28 +00001671 v = get_xoptions();
1672 if (v != NULL) {
1673 PyDict_SetItemString(sysdict, "_xoptions", v);
1674 }
1675
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001676 /* version_info */
1677 if (VersionInfoType.tp_name == 0)
1678 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1679 SET_SYS_FROM_STRING("version_info", make_version_info());
1680 /* prevent user from creating new instances */
1681 VersionInfoType.tp_init = NULL;
1682 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 /* flags */
1685 if (FlagsType.tp_name == 0)
1686 PyStructSequence_InitType(&FlagsType, &flags_desc);
1687 SET_SYS_FROM_STRING("flags", make_flags());
1688 /* prevent user from creating new instances */
1689 FlagsType.tp_init = NULL;
1690 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001691
Eric Smithf7bb5782010-01-27 00:44:57 +00001692
1693#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 /* getwindowsversion */
1695 if (WindowsVersionType.tp_name == 0)
1696 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1697 /* prevent user from creating new instances */
1698 WindowsVersionType.tp_init = NULL;
1699 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001700#endif
1701
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001702 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001703#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 SET_SYS_FROM_STRING("float_repr_style",
1705 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001706#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 SET_SYS_FROM_STRING("float_repr_style",
1708 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001709#endif
1710
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001711#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 if (PyErr_Occurred())
1713 return NULL;
1714 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001715}
1716
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001717static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001718makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 int i, n;
1721 const wchar_t *p;
1722 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 n = 1;
1725 p = path;
1726 while ((p = wcschr(p, delim)) != NULL) {
1727 n++;
1728 p++;
1729 }
1730 v = PyList_New(n);
1731 if (v == NULL)
1732 return NULL;
1733 for (i = 0; ; i++) {
1734 p = wcschr(path, delim);
1735 if (p == NULL)
1736 p = path + wcslen(path); /* End of string */
1737 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1738 if (w == NULL) {
1739 Py_DECREF(v);
1740 return NULL;
1741 }
1742 PyList_SetItem(v, i, w);
1743 if (*p == '\0')
1744 break;
1745 path = p+1;
1746 }
1747 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001748}
1749
1750void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001751PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001752{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001753 PyObject *v;
1754 if ((v = makepathobject(path, DELIM)) == NULL)
1755 Py_FatalError("can't create sys.path");
1756 if (PySys_SetObject("path", v) != 0)
1757 Py_FatalError("can't assign sys.path");
1758 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001759}
1760
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001761static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001762makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001763{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001764 PyObject *av;
1765 if (argc <= 0 || argv == NULL) {
1766 /* Ensure at least one (empty) argument is seen */
1767 static wchar_t *empty_argv[1] = {L""};
1768 argv = empty_argv;
1769 argc = 1;
1770 }
1771 av = PyList_New(argc);
1772 if (av != NULL) {
1773 int i;
1774 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001775#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001776 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001777
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 /* argv[0] is the script pathname if known */
1779 if (i == 0) {
1780 char* fn = decc$translate_vms(argv[0]);
1781 if ((fn == (char *)0) || fn == (char *)-1)
1782 v = PyUnicode_FromString(argv[0]);
1783 else
1784 v = PyUnicode_FromString(
1785 decc$translate_vms(argv[0]));
1786 } else
1787 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001788#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001790#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 if (v == NULL) {
1792 Py_DECREF(av);
1793 av = NULL;
1794 break;
1795 }
1796 PyList_SetItem(av, i, v);
1797 }
1798 }
1799 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001800}
1801
Nick Coghland26c18a2010-08-17 13:06:11 +00001802#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1803 (argc > 0 && argv0 != NULL && \
1804 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001805
1806static void
1807sys_update_path(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001808{
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001809 wchar_t *argv0;
1810 wchar_t *p = NULL;
1811 Py_ssize_t n = 0;
1812 PyObject *a;
1813 PyObject *path;
1814#ifdef HAVE_READLINK
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001815 wchar_t link[MAXPATHLEN+1];
1816 wchar_t argv0copy[2*MAXPATHLEN+1];
1817 int nr = 0;
1818#endif
Guido van Rossum162e38c2003-02-19 15:25:10 +00001819#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001821#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001823#endif
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001824
1825 path = PySys_GetObject("path");
1826 if (path == NULL)
1827 return;
1828
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001829 argv0 = argv[0];
1830
1831#ifdef HAVE_READLINK
1832 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
1833 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1834 if (nr > 0) {
1835 /* It's a symlink */
1836 link[nr] = '\0';
1837 if (link[0] == SEP)
1838 argv0 = link; /* Link to absolute path */
1839 else if (wcschr(link, SEP) == NULL)
1840 ; /* Link without path */
1841 else {
1842 /* Must join(dirname(argv0), link) */
1843 wchar_t *q = wcsrchr(argv0, SEP);
1844 if (q == NULL)
1845 argv0 = link; /* argv0 without path */
1846 else {
1847 /* Must make a copy */
1848 wcscpy(argv0copy, argv0);
1849 q = wcsrchr(argv0copy, SEP);
1850 wcscpy(q+1, link);
1851 argv0 = argv0copy;
1852 }
1853 }
1854 }
1855#endif /* HAVE_READLINK */
1856#if SEP == '\\' /* Special case for MS filename syntax */
1857 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1858 wchar_t *q;
1859#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1860 /* This code here replaces the first element in argv with the full
1861 path that it represents. Under CE, there are no relative paths so
1862 the argument must be the full path anyway. */
1863 wchar_t *ptemp;
1864 if (GetFullPathNameW(argv0,
1865 sizeof(fullpath)/sizeof(fullpath[0]),
1866 fullpath,
1867 &ptemp)) {
1868 argv0 = fullpath;
1869 }
1870#endif
1871 p = wcsrchr(argv0, SEP);
1872 /* Test for alternate separator */
1873 q = wcsrchr(p ? p : argv0, '/');
1874 if (q != NULL)
1875 p = q;
1876 if (p != NULL) {
1877 n = p + 1 - argv0;
1878 if (n > 1 && p[-1] != ':')
1879 n--; /* Drop trailing separator */
1880 }
1881 }
1882#else /* All other filename syntaxes */
1883 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1884#if defined(HAVE_REALPATH)
Victor Stinner015f4d82010-10-07 22:29:53 +00001885 if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) {
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001886 argv0 = fullpath;
1887 }
1888#endif
1889 p = wcsrchr(argv0, SEP);
1890 }
1891 if (p != NULL) {
1892 n = p + 1 - argv0;
1893#if SEP == '/' /* Special case for Unix filename syntax */
1894 if (n > 1)
1895 n--; /* Drop trailing separator */
1896#endif /* Unix */
1897 }
1898#endif /* All others */
1899 a = PyUnicode_FromWideChar(argv0, n);
1900 if (a == NULL)
1901 Py_FatalError("no mem for sys.path insertion");
1902 if (PyList_Insert(path, 0, a) < 0)
1903 Py_FatalError("sys.path.insert(0) failed");
1904 Py_DECREF(a);
1905}
1906
1907void
1908PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
1909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001910 PyObject *av = makeargvobject(argc, argv);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 if (av == NULL)
1912 Py_FatalError("no mem for sys.argv");
1913 if (PySys_SetObject("argv", av) != 0)
1914 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001915 Py_DECREF(av);
Victor Stinnerc08ec9f2010-10-06 22:44:06 +00001916 if (updatepath)
1917 sys_update_path(argc, argv);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001918}
Guido van Rossuma890e681998-05-12 14:59:24 +00001919
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001920void
1921PySys_SetArgv(int argc, wchar_t **argv)
1922{
1923 PySys_SetArgvEx(argc, argv, 1);
1924}
1925
Victor Stinner14284c22010-04-23 12:02:30 +00001926/* Reimplementation of PyFile_WriteString() no calling indirectly
1927 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1928
1929static int
Victor Stinner79766632010-08-16 17:36:42 +00001930sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001931{
Victor Stinner79766632010-08-16 17:36:42 +00001932 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00001934
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001935 if (file == NULL)
1936 return -1;
1937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 writer = PyObject_GetAttrString(file, "write");
1939 if (writer == NULL)
1940 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001941
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001942 args = PyTuple_Pack(1, unicode);
1943 if (args == NULL)
1944 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001945
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 result = PyEval_CallObject(writer, args);
1947 if (result == NULL) {
1948 goto error;
1949 } else {
1950 err = 0;
1951 goto finally;
1952 }
Victor Stinner14284c22010-04-23 12:02:30 +00001953
1954error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001956finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001957 Py_XDECREF(writer);
1958 Py_XDECREF(args);
1959 Py_XDECREF(result);
1960 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001961}
1962
Victor Stinner79766632010-08-16 17:36:42 +00001963static int
1964sys_pyfile_write(const char *text, PyObject *file)
1965{
1966 PyObject *unicode = NULL;
1967 int err;
1968
1969 if (file == NULL)
1970 return -1;
1971
1972 unicode = PyUnicode_FromString(text);
1973 if (unicode == NULL)
1974 return -1;
1975
1976 err = sys_pyfile_write_unicode(unicode, file);
1977 Py_DECREF(unicode);
1978 return err;
1979}
Guido van Rossuma890e681998-05-12 14:59:24 +00001980
1981/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1982 Adapted from code submitted by Just van Rossum.
1983
1984 PySys_WriteStdout(format, ...)
1985 PySys_WriteStderr(format, ...)
1986
1987 The first function writes to sys.stdout; the second to sys.stderr. When
1988 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00001989 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00001990
Victor Stinner14284c22010-04-23 12:02:30 +00001991 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00001992 signal handlers: they may raise a new exception whereas sys_write()
1993 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00001994
Guido van Rossuma890e681998-05-12 14:59:24 +00001995 Both take a printf-style format string as their first argument followed
1996 by a variable length argument list determined by the format string.
1997
1998 *** WARNING ***
1999
2000 The format should limit the total size of the formatted output string to
2001 1000 bytes. In particular, this means that no unrestricted "%s" formats
2002 should occur; these should be limited using "%.<N>s where <N> is a
2003 decimal number calculated so that <N> plus the maximum size of other
2004 formatted text does not exceed 1000 bytes. Also watch out for "%f",
2005 which can print hundreds of digits for very large numbers.
2006
2007 */
2008
2009static void
Victor Stinner79766632010-08-16 17:36:42 +00002010sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00002011{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002012 PyObject *file;
2013 PyObject *error_type, *error_value, *error_traceback;
2014 char buffer[1001];
2015 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00002016
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002017 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2018 file = PySys_GetObject(name);
2019 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
2020 if (sys_pyfile_write(buffer, file) != 0) {
2021 PyErr_Clear();
2022 fputs(buffer, fp);
2023 }
2024 if (written < 0 || (size_t)written >= sizeof(buffer)) {
2025 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00002026 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002027 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002028 }
2029 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00002030}
2031
2032void
Guido van Rossuma890e681998-05-12 14:59:24 +00002033PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002034{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002035 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002038 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002039 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002040}
2041
2042void
Guido van Rossuma890e681998-05-12 14:59:24 +00002043PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00002044{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00002046
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002047 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00002048 sys_write("stderr", stderr, format, va);
2049 va_end(va);
2050}
2051
2052static void
2053sys_format(char *name, FILE *fp, const char *format, va_list va)
2054{
2055 PyObject *file, *message;
2056 PyObject *error_type, *error_value, *error_traceback;
2057 char *utf8;
2058
2059 PyErr_Fetch(&error_type, &error_value, &error_traceback);
2060 file = PySys_GetObject(name);
2061 message = PyUnicode_FromFormatV(format, va);
2062 if (message != NULL) {
2063 if (sys_pyfile_write_unicode(message, file) != 0) {
2064 PyErr_Clear();
2065 utf8 = _PyUnicode_AsString(message);
2066 if (utf8 != NULL)
2067 fputs(utf8, fp);
2068 }
2069 Py_DECREF(message);
2070 }
2071 PyErr_Restore(error_type, error_value, error_traceback);
2072}
2073
2074void
2075PySys_FormatStdout(const char *format, ...)
2076{
2077 va_list va;
2078
2079 va_start(va, format);
2080 sys_format("stdout", stdout, format, va);
2081 va_end(va);
2082}
2083
2084void
2085PySys_FormatStderr(const char *format, ...)
2086{
2087 va_list va;
2088
2089 va_start(va, format);
2090 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002091 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002092}