blob: 013f5f1a9b4786cd061bb2a34ba80062712815ac [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"
Christian Heimesd32ed6f2008-01-14 18:49:24 +000018#include "structseq.h"
Jeremy Hylton3e0055f2005-10-20 19:59:25 +000019#include "code.h"
Barry Warsawb6a54d22000-12-06 21:47:46 +000020#include "frameobject.h"
Guido van Rossuma12fe4e2003-04-09 19:06:21 +000021#include "eval.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000022
Guido van Rossume2437a11992-03-23 18:20:18 +000023#include "osdefs.h"
Guido van Rossum3f5da241990-12-20 15:06:42 +000024
Mark Hammond8696ebc2002-10-08 02:44:31 +000025#ifdef MS_WINDOWS
26#define WIN32_LEAN_AND_MEAN
Amaury Forgeot d'Arc06cfe952007-11-10 13:55:44 +000027#include <windows.h>
Mark Hammond8696ebc2002-10-08 02:44:31 +000028#endif /* MS_WINDOWS */
29
Guido van Rossum9b38a141996-09-11 23:12:24 +000030#ifdef MS_COREDLL
Guido van Rossumc606fe11996-04-09 02:37:57 +000031extern void *PyWin_DLLhModule;
Guido van Rossum6c1e5f21997-09-29 23:34:23 +000032/* A string loaded from the DLL at startup: */
33extern const char *PyWin_DLLVersionString;
Guido van Rossumc606fe11996-04-09 02:37:57 +000034#endif
35
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +000036#ifdef __VMS
37#include <unixlib.h>
38#endif
39
Martin v. Löwis5467d4c2003-05-10 07:10:12 +000040#ifdef HAVE_LANGINFO_H
41#include <locale.h>
42#include <langinfo.h>
43#endif
44
Guido van Rossum65bf9f21997-04-29 18:33:38 +000045PyObject *
Neal Norwitzf3081322007-08-25 00:32:45 +000046PySys_GetObject(const char *name)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000047{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000048 PyThreadState *tstate = PyThreadState_GET();
49 PyObject *sd = tstate->interp->sysdict;
50 if (sd == NULL)
51 return NULL;
52 return PyDict_GetItemString(sd, name);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000053}
54
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000055int
Neal Norwitzf3081322007-08-25 00:32:45 +000056PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000058 PyThreadState *tstate = PyThreadState_GET();
59 PyObject *sd = tstate->interp->sysdict;
60 if (v == NULL) {
61 if (PyDict_GetItemString(sd, name) == NULL)
62 return 0;
63 else
64 return PyDict_DelItemString(sd, name);
65 }
66 else
67 return PyDict_SetItemString(sd, name, v);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000068}
69
Guido van Rossum65bf9f21997-04-29 18:33:38 +000070static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +000071sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +000072{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000073 PyObject *outf;
74 PyInterpreterState *interp = PyThreadState_GET()->interp;
75 PyObject *modules = interp->modules;
76 PyObject *builtins = PyDict_GetItemString(modules, "builtins");
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +000077
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000078 if (builtins == NULL) {
79 PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
80 return NULL;
81 }
Moshe Zadka03897ea2001-07-23 13:32:43 +000082
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000083 /* Print value except if None */
84 /* After printing, also assign to '_' */
85 /* Before, set '_' to None to avoid recursion */
86 if (o == Py_None) {
87 Py_INCREF(Py_None);
88 return Py_None;
89 }
90 if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
91 return NULL;
92 outf = PySys_GetObject("stdout");
93 if (outf == NULL || outf == Py_None) {
94 PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
95 return NULL;
96 }
97 if (PyFile_WriteObject(o, outf, 0) != 0)
98 return NULL;
99 if (PyFile_WriteString("\n", outf) != 0)
100 return NULL;
101 if (PyObject_SetAttrString(builtins, "_", o) != 0)
102 return NULL;
103 Py_INCREF(Py_None);
104 return Py_None;
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000105}
106
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000107PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000108"displayhook(object) -> None\n"
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000109"\n"
Florent Xicluna5749e852010-03-03 11:54:54 +0000110"Print an object to sys.stdout and also save it in builtins._\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000111);
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000112
113static PyObject *
114sys_excepthook(PyObject* self, PyObject* args)
115{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000116 PyObject *exc, *value, *tb;
117 if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
118 return NULL;
119 PyErr_Display(exc, value, tb);
120 Py_INCREF(Py_None);
121 return Py_None;
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000122}
123
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000124PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +0000125"excepthook(exctype, value, traceback) -> None\n"
126"\n"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000127"Handle an exception by displaying it with a traceback on sys.stderr.\n"
128);
Moshe Zadkaf68f2fe2001-01-11 05:41:27 +0000129
130static PyObject *
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000131sys_exc_info(PyObject *self, PyObject *noargs)
Guido van Rossuma027efa1997-05-05 20:56:21 +0000132{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000133 PyThreadState *tstate;
134 tstate = PyThreadState_GET();
135 return Py_BuildValue(
136 "(OOO)",
137 tstate->exc_type != NULL ? tstate->exc_type : Py_None,
138 tstate->exc_value != NULL ? tstate->exc_value : Py_None,
139 tstate->exc_traceback != NULL ?
140 tstate->exc_traceback : Py_None);
Guido van Rossuma027efa1997-05-05 20:56:21 +0000141}
142
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000143PyDoc_STRVAR(exc_info_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000144"exc_info() -> (type, value, traceback)\n\
145\n\
Guido van Rossum46d3dc32003-03-01 03:20:41 +0000146Return information about the most recent exception caught by an except\n\
147clause in the current stack frame or in an older stack frame."
148);
149
150static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000151sys_exit(PyObject *self, PyObject *args)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000152{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000153 PyObject *exit_code = 0;
154 if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
155 return NULL;
156 /* Raise SystemExit so callers may catch it or clean up. */
157 PyErr_SetObject(PyExc_SystemExit, exit_code);
158 return NULL;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000159}
160
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000161PyDoc_STRVAR(exit_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000162"exit([status])\n\
163\n\
164Exit the interpreter by raising SystemExit(status).\n\
165If the status is omitted or None, it defaults to zero (i.e., success).\n\
Neil Schemenauer0f2103f2002-03-23 20:46:35 +0000166If the status is numeric, it will be used as the system exit status.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000167If it is another kind of object, it will be printed and the system\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000168exit status will be one (i.e., failure)."
169);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000170
Martin v. Löwis107b7da2001-11-09 20:59:39 +0000171
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000172static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000173sys_getdefaultencoding(PyObject *self)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000174{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
Fred Drake8b4d01d2000-05-09 19:57:01 +0000176}
177
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000178PyDoc_STRVAR(getdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000179"getdefaultencoding() -> string\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000180\n\
181Return the current default string encoding used by the Unicode \n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000182implementation."
183);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000184
185static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000186sys_setdefaultencoding(PyObject *self, PyObject *args)
Fred Drake8b4d01d2000-05-09 19:57:01 +0000187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 char *encoding;
189 if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
190 return NULL;
191 if (PyUnicode_SetDefaultEncoding(encoding))
192 return NULL;
193 Py_INCREF(Py_None);
194 return Py_None;
Fred Drake8b4d01d2000-05-09 19:57:01 +0000195}
196
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000197PyDoc_STRVAR(setdefaultencoding_doc,
Marc-André Lemburg99964b82000-06-07 09:13:41 +0000198"setdefaultencoding(encoding)\n\
Fred Drake8b4d01d2000-05-09 19:57:01 +0000199\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000200Set the current default string encoding used by the Unicode implementation."
201);
Fred Drake8b4d01d2000-05-09 19:57:01 +0000202
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000203static PyObject *
204sys_getfilesystemencoding(PyObject *self)
205{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000206 if (Py_FileSystemDefaultEncoding)
207 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
208 Py_INCREF(Py_None);
209 return Py_None;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000210}
211
212PyDoc_STRVAR(getfilesystemencoding_doc,
213"getfilesystemencoding() -> string\n\
214\n\
215Return the encoding used to convert Unicode filenames in\n\
216operating system filenames."
217);
218
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000219static PyObject *
220sys_setfilesystemencoding(PyObject *self, PyObject *args)
221{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000222 PyObject *new_encoding;
223 if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding))
224 return NULL;
225 if (_Py_SetFileSystemEncoding(new_encoding))
226 return NULL;
227 Py_INCREF(Py_None);
228 return Py_None;
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000229}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000230
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000231PyDoc_STRVAR(setfilesystemencoding_doc,
232"setfilesystemencoding(string) -> None\n\
233\n\
234Set the encoding used to convert Unicode filenames in\n\
235operating system filenames."
236);
Georg Brandl66a796e2006-12-19 20:50:34 +0000237
238static PyObject *
239sys_intern(PyObject *self, PyObject *args)
240{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 PyObject *s;
242 if (!PyArg_ParseTuple(args, "U:intern", &s))
243 return NULL;
244 if (PyUnicode_CheckExact(s)) {
245 Py_INCREF(s);
246 PyUnicode_InternInPlace(&s);
247 return s;
248 }
249 else {
250 PyErr_Format(PyExc_TypeError,
251 "can't intern %.400s", s->ob_type->tp_name);
252 return NULL;
253 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000254}
255
256PyDoc_STRVAR(intern_doc,
257"intern(string) -> string\n\
258\n\
259``Intern'' the given string. This enters the string in the (global)\n\
260table of interned strings whose purpose is to speed up dictionary lookups.\n\
261Return the string itself or the previously interned string object with the\n\
262same value.");
263
264
Fred Drake5755ce62001-06-27 19:19:46 +0000265/*
266 * Cached interned string objects used for calling the profile and
267 * trace functions. Initialized by trace_init().
268 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000269static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000270
271static int
272trace_init(void)
273{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 static char *whatnames[7] = {"call", "exception", "line", "return",
275 "c_call", "c_exception", "c_return"};
276 PyObject *name;
277 int i;
278 for (i = 0; i < 7; ++i) {
279 if (whatstrings[i] == NULL) {
280 name = PyUnicode_InternFromString(whatnames[i]);
281 if (name == NULL)
282 return -1;
283 whatstrings[i] = name;
284 }
285 }
286 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000287}
288
289
290static PyObject *
291call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000293{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000294 PyObject *args = PyTuple_New(3);
295 PyObject *whatstr;
296 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 if (args == NULL)
299 return NULL;
300 Py_INCREF(frame);
301 whatstr = whatstrings[what];
302 Py_INCREF(whatstr);
303 if (arg == NULL)
304 arg = Py_None;
305 Py_INCREF(arg);
306 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
307 PyTuple_SET_ITEM(args, 1, whatstr);
308 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000310 /* call the Python-level function */
311 PyFrame_FastToLocals(frame);
312 result = PyEval_CallObject(callback, args);
313 PyFrame_LocalsToFast(frame, 1);
314 if (result == NULL)
315 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000316
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000317 /* cleanup */
318 Py_DECREF(args);
319 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000320}
321
322static int
323profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000324 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 PyThreadState *tstate = frame->f_tstate;
327 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000328
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000329 if (arg == NULL)
330 arg = Py_None;
331 result = call_trampoline(tstate, self, frame, what, arg);
332 if (result == NULL) {
333 PyEval_SetProfile(NULL, NULL);
334 return -1;
335 }
336 Py_DECREF(result);
337 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000338}
339
340static int
341trace_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000342 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000343{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000344 PyThreadState *tstate = frame->f_tstate;
345 PyObject *callback;
346 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000347
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 if (what == PyTrace_CALL)
349 callback = self;
350 else
351 callback = frame->f_trace;
352 if (callback == NULL)
353 return 0;
354 result = call_trampoline(tstate, callback, frame, what, arg);
355 if (result == NULL) {
356 PyEval_SetTrace(NULL, NULL);
357 Py_XDECREF(frame->f_trace);
358 frame->f_trace = NULL;
359 return -1;
360 }
361 if (result != Py_None) {
362 PyObject *temp = frame->f_trace;
363 frame->f_trace = NULL;
364 Py_XDECREF(temp);
365 frame->f_trace = result;
366 }
367 else {
368 Py_DECREF(result);
369 }
370 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000371}
Fred Draked0838392001-06-16 21:02:31 +0000372
Fred Drake8b4d01d2000-05-09 19:57:01 +0000373static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000374sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000375{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000376 if (trace_init() == -1)
377 return NULL;
378 if (args == Py_None)
379 PyEval_SetTrace(NULL, NULL);
380 else
381 PyEval_SetTrace(trace_trampoline, args);
382 Py_INCREF(Py_None);
383 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000384}
385
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000386PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000387"settrace(function)\n\
388\n\
389Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000390function call. See the debugger chapter in the library manual."
391);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000392
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000393static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000394sys_gettrace(PyObject *self, PyObject *args)
395{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000396 PyThreadState *tstate = PyThreadState_GET();
397 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000398
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000399 if (temp == NULL)
400 temp = Py_None;
401 Py_INCREF(temp);
402 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000403}
404
405PyDoc_STRVAR(gettrace_doc,
406"gettrace()\n\
407\n\
408Return the global debug tracing function set with sys.settrace.\n\
409See the debugger chapter in the library manual."
410);
411
412static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000413sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 if (trace_init() == -1)
416 return NULL;
417 if (args == Py_None)
418 PyEval_SetProfile(NULL, NULL);
419 else
420 PyEval_SetProfile(profile_trampoline, args);
421 Py_INCREF(Py_None);
422 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000423}
424
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000425PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000426"setprofile(function)\n\
427\n\
428Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000429and return. See the profiler chapter in the library manual."
430);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000431
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000432static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000433sys_getprofile(PyObject *self, PyObject *args)
434{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000435 PyThreadState *tstate = PyThreadState_GET();
436 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (temp == NULL)
439 temp = Py_None;
440 Py_INCREF(temp);
441 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000442}
443
444PyDoc_STRVAR(getprofile_doc,
445"getprofile()\n\
446\n\
447Return the profiling function set with sys.setprofile.\n\
448See the profiler chapter in the library manual."
449);
450
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000451static int _check_interval = 100;
452
Christian Heimes9bd667a2008-01-20 15:14:11 +0000453static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000454sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000455{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000456 if (PyErr_WarnEx(PyExc_DeprecationWarning,
457 "sys.getcheckinterval() and sys.setcheckinterval() "
458 "are deprecated. Use sys.setswitchinterval() "
459 "instead.", 1) < 0)
460 return NULL;
461 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
462 return NULL;
463 Py_INCREF(Py_None);
464 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000465}
466
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000467PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000468"setcheckinterval(n)\n\
469\n\
470Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000471n instructions. This also affects how often thread switches occur."
472);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000473
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000474static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000475sys_getcheckinterval(PyObject *self, PyObject *args)
476{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000477 if (PyErr_WarnEx(PyExc_DeprecationWarning,
478 "sys.getcheckinterval() and sys.setcheckinterval() "
479 "are deprecated. Use sys.getswitchinterval() "
480 "instead.", 1) < 0)
481 return NULL;
482 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000483}
484
485PyDoc_STRVAR(getcheckinterval_doc,
486"getcheckinterval() -> current check interval; see setcheckinterval()."
487);
488
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000489#ifdef WITH_THREAD
490static PyObject *
491sys_setswitchinterval(PyObject *self, PyObject *args)
492{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000493 double d;
494 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
495 return NULL;
496 if (d <= 0.0) {
497 PyErr_SetString(PyExc_ValueError,
498 "switch interval must be strictly positive");
499 return NULL;
500 }
501 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
502 Py_INCREF(Py_None);
503 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000504}
505
506PyDoc_STRVAR(setswitchinterval_doc,
507"setswitchinterval(n)\n\
508\n\
509Set the ideal thread switching delay inside the Python interpreter\n\
510The actual frequency of switching threads can be lower if the\n\
511interpreter executes long sequences of uninterruptible code\n\
512(this is implementation-specific and workload-dependent).\n\
513\n\
514The parameter must represent the desired switching delay in seconds\n\
515A typical value is 0.005 (5 milliseconds)."
516);
517
518static PyObject *
519sys_getswitchinterval(PyObject *self, PyObject *args)
520{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000521 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000522}
523
524PyDoc_STRVAR(getswitchinterval_doc,
525"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
526);
527
528#endif /* WITH_THREAD */
529
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000530#ifdef WITH_TSC
531static PyObject *
532sys_settscdump(PyObject *self, PyObject *args)
533{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000534 int bool;
535 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000537 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
538 return NULL;
539 if (bool)
540 tstate->interp->tscdump = 1;
541 else
542 tstate->interp->tscdump = 0;
543 Py_INCREF(Py_None);
544 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000545
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000546}
547
Tim Peters216b78b2006-01-06 02:40:53 +0000548PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000549"settscdump(bool)\n\
550\n\
551If true, tell the Python interpreter to dump VM measurements to\n\
552stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000553processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000554);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000555#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000556
Tim Peterse5e065b2003-07-06 18:36:54 +0000557static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000558sys_setrecursionlimit(PyObject *self, PyObject *args)
559{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000560 int new_limit;
561 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
562 return NULL;
563 if (new_limit <= 0) {
564 PyErr_SetString(PyExc_ValueError,
565 "recursion limit must be positive");
566 return NULL;
567 }
568 Py_SetRecursionLimit(new_limit);
569 Py_INCREF(Py_None);
570 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000571}
572
Mark Dickinsondc787d22010-05-23 13:33:13 +0000573static PyTypeObject Hash_InfoType;
574
575PyDoc_STRVAR(hash_info_doc,
576"hash_info\n\
577\n\
578A struct sequence providing parameters used for computing\n\
579numeric hashes. The attributes are read only.");
580
581static PyStructSequence_Field hash_info_fields[] = {
582 {"width", "width of the type used for hashing, in bits"},
583 {"modulus", "prime number giving the modulus on which the hash "
584 "function is based"},
585 {"inf", "value to be used for hash of a positive infinity"},
586 {"nan", "value to be used for hash of a nan"},
587 {"imag", "multiplier used for the imaginary part of a complex number"},
588 {NULL, NULL}
589};
590
591static PyStructSequence_Desc hash_info_desc = {
592 "sys.hash_info",
593 hash_info_doc,
594 hash_info_fields,
595 5,
596};
597
Matthias Klosed885e952010-07-06 10:53:30 +0000598static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000599get_hash_info(void)
600{
601 PyObject *hash_info;
602 int field = 0;
603 hash_info = PyStructSequence_New(&Hash_InfoType);
604 if (hash_info == NULL)
605 return NULL;
606 PyStructSequence_SET_ITEM(hash_info, field++,
607 PyLong_FromLong(8*sizeof(long)));
608 PyStructSequence_SET_ITEM(hash_info, field++,
609 PyLong_FromLong(_PyHASH_MODULUS));
610 PyStructSequence_SET_ITEM(hash_info, field++,
611 PyLong_FromLong(_PyHASH_INF));
612 PyStructSequence_SET_ITEM(hash_info, field++,
613 PyLong_FromLong(_PyHASH_NAN));
614 PyStructSequence_SET_ITEM(hash_info, field++,
615 PyLong_FromLong(_PyHASH_IMAG));
616 if (PyErr_Occurred()) {
617 Py_CLEAR(hash_info);
618 return NULL;
619 }
620 return hash_info;
621}
622
623
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000624PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000625"setrecursionlimit(n)\n\
626\n\
627Set the maximum depth of the Python interpreter stack to n. This\n\
628limit prevents infinite recursion from causing an overflow of the C\n\
629stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000630dependent."
631);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000632
633static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000634sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000635{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000636 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000637}
638
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000639PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000640"getrecursionlimit()\n\
641\n\
642Return the current value of the recursion limit, the maximum depth\n\
643of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000644recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000645);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000646
Mark Hammond8696ebc2002-10-08 02:44:31 +0000647#ifdef MS_WINDOWS
648PyDoc_STRVAR(getwindowsversion_doc,
649"getwindowsversion()\n\
650\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000651Return information about the running version of Windows as a named tuple.\n\
652The members are named: major, minor, build, platform, service_pack,\n\
653service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
654backward compatibiliy, only the first 5 items are available by indexing.\n\
655All elements are numbers, except service_pack which is a string. Platform\n\
656may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6573 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
658controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000659);
660
Eric Smithf7bb5782010-01-27 00:44:57 +0000661static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
662
663static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000664 {"major", "Major version number"},
665 {"minor", "Minor version number"},
666 {"build", "Build number"},
667 {"platform", "Operating system platform"},
668 {"service_pack", "Latest Service Pack installed on the system"},
669 {"service_pack_major", "Service Pack major version number"},
670 {"service_pack_minor", "Service Pack minor version number"},
671 {"suite_mask", "Bit mask identifying available product suites"},
672 {"product_type", "System product type"},
673 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000674};
675
676static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 "sys.getwindowsversion", /* name */
678 getwindowsversion_doc, /* doc */
679 windows_version_fields, /* fields */
680 5 /* For backward compatibility,
681 only the first 5 items are accessible
682 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000683};
684
Mark Hammond8696ebc2002-10-08 02:44:31 +0000685static PyObject *
686sys_getwindowsversion(PyObject *self)
687{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000688 PyObject *version;
689 int pos = 0;
690 OSVERSIONINFOEX ver;
691 ver.dwOSVersionInfoSize = sizeof(ver);
692 if (!GetVersionEx((OSVERSIONINFO*) &ver))
693 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000694
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000695 version = PyStructSequence_New(&WindowsVersionType);
696 if (version == NULL)
697 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000698
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
700 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
701 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
702 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
703 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
704 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
705 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
706 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
707 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000708
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000710}
711
712#endif /* MS_WINDOWS */
713
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000714#ifdef HAVE_DLOPEN
715static PyObject *
716sys_setdlopenflags(PyObject *self, PyObject *args)
717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000718 int new_val;
719 PyThreadState *tstate = PyThreadState_GET();
720 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
721 return NULL;
722 if (!tstate)
723 return NULL;
724 tstate->interp->dlopenflags = new_val;
725 Py_INCREF(Py_None);
726 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000727}
728
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000729PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000730"setdlopenflags(n) -> None\n\
731\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000732Set the flags used by the interpreter for dlopen calls, such as when the\n\
733interpreter loads extension modules. Among other things, this will enable\n\
734a lazy resolving of symbols when importing a module, if called as\n\
735sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
736sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
737can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
738is not available, it can be generated from /usr/include/dlfcn.h using the\n\
739h2py script.");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000740
741static PyObject *
742sys_getdlopenflags(PyObject *self, PyObject *args)
743{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 PyThreadState *tstate = PyThreadState_GET();
745 if (!tstate)
746 return NULL;
747 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000748}
749
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000750PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000751"getdlopenflags() -> int\n\
752\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000753Return the current value of the flags that are used for dlopen calls.\n\
754The flag constants are defined in the ctypes and DLFCN modules.");
755
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000756#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000757
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000758#ifdef USE_MALLOPT
759/* Link with -lmalloc (or -lmpc) on an SGI */
760#include <malloc.h>
761
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000762static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000763sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000764{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 int flag;
766 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
767 return NULL;
768 mallopt(M_DEBUG, flag);
769 Py_INCREF(Py_None);
770 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000771}
772#endif /* USE_MALLOPT */
773
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000774static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000775sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000777 PyObject *res = NULL;
778 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
779 static char *kwlist[] = {"object", "default", 0};
780 PyObject *o, *dflt = NULL;
781 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
784 kwlist, &o, &dflt))
785 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000786
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000787 /* Initialize static variable for GC head size */
788 if (gc_head_size == NULL) {
789 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
790 if (gc_head_size == NULL)
791 return NULL;
792 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000793
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000794 /* Make sure the type is initialized. float gets initialized late */
795 if (PyType_Ready(Py_TYPE(o)) < 0)
796 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000797
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000798 method = _PyObject_LookupSpecial(o, "__sizeof__",
799 &str__sizeof__);
800 if (method == NULL) {
801 if (!PyErr_Occurred())
802 PyErr_Format(PyExc_TypeError,
803 "Type %.100s doesn't define __sizeof__",
804 Py_TYPE(o)->tp_name);
805 }
806 else {
807 res = PyObject_CallFunctionObjArgs(method, NULL);
808 Py_DECREF(method);
809 }
810
811 /* Has a default value been given */
812 if ((res == NULL) && (dflt != NULL) &&
813 PyErr_ExceptionMatches(PyExc_TypeError))
814 {
815 PyErr_Clear();
816 Py_INCREF(dflt);
817 return dflt;
818 }
819 else if (res == NULL)
820 return res;
821
822 /* add gc_head size */
823 if (PyObject_IS_GC(o)) {
824 PyObject *tmp = res;
825 res = PyNumber_Add(tmp, gc_head_size);
826 Py_DECREF(tmp);
827 }
828 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000829}
830
831PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000832"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000833\n\
834Return the size of object in bytes.");
835
836static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000837sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000838{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000839 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000840}
841
Tim Peters4be93d02002-07-07 19:59:50 +0000842#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000843static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000844sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000845{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000847}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000848#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000849
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000850PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000851"getrefcount(object) -> integer\n\
852\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000853Return the reference count of object. The count returned is generally\n\
854one higher than you might expect, because it includes the (temporary)\n\
855reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000856);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000857
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000858#ifdef COUNT_ALLOCS
859static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000860sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000861{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000862 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000865}
866#endif
867
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000868PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000869"_getframe([depth]) -> frameobject\n\
870\n\
871Return a frame object from the call stack. If optional integer depth is\n\
872given, return the frame object that many calls below the top of the stack.\n\
873If that is deeper than the call stack, ValueError is raised. The default\n\
874for depth is zero, returning the frame at the top of the call stack.\n\
875\n\
876This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000877purposes only."
878);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000879
880static PyObject *
881sys_getframe(PyObject *self, PyObject *args)
882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000883 PyFrameObject *f = PyThreadState_GET()->frame;
884 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
887 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000889 while (depth > 0 && f != NULL) {
890 f = f->f_back;
891 --depth;
892 }
893 if (f == NULL) {
894 PyErr_SetString(PyExc_ValueError,
895 "call stack is not deep enough");
896 return NULL;
897 }
898 Py_INCREF(f);
899 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000900}
901
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000902PyDoc_STRVAR(current_frames_doc,
903"_current_frames() -> dictionary\n\
904\n\
905Return a dictionary mapping each current thread T's thread id to T's\n\
906current stack frame.\n\
907\n\
908This function should be used for specialized purposes only."
909);
910
911static PyObject *
912sys_current_frames(PyObject *self, PyObject *noargs)
913{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000914 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000915}
916
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000917PyDoc_STRVAR(call_tracing_doc,
918"call_tracing(func, args) -> object\n\
919\n\
920Call func(*args), while tracing is enabled. The tracing state is\n\
921saved, and restored afterwards. This is intended to be called from\n\
922a debugger from a checkpoint, to recursively debug some other code."
923);
924
925static PyObject *
926sys_call_tracing(PyObject *self, PyObject *args)
927{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000928 PyObject *func, *funcargs;
929 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
930 return NULL;
931 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000932}
933
Jeremy Hylton985eba52003-02-05 23:13:00 +0000934PyDoc_STRVAR(callstats_doc,
935"callstats() -> tuple of integers\n\
936\n\
937Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
938when Python was built. Otherwise, return None.\n\
939\n\
940When enabled, this function returns detailed, implementation-specific\n\
941details about the number of function calls executed. The return value is\n\
942a 11-tuple where the entries in the tuple are counts of:\n\
9430. all function calls\n\
9441. calls to PyFunction_Type objects\n\
9452. PyFunction calls that do not create an argument tuple\n\
9463. PyFunction calls that do not create an argument tuple\n\
947 and bypass PyEval_EvalCodeEx()\n\
9484. PyMethod calls\n\
9495. PyMethod calls on bound methods\n\
9506. PyType calls\n\
9517. PyCFunction calls\n\
9528. generator calls\n\
9539. All other calls\n\
95410. Number of stack pops performed by call_function()"
955);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000956
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000957#ifdef __cplusplus
958extern "C" {
959#endif
960
Guido van Rossum7f3f2c11996-05-23 22:45:41 +0000961#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +0000962/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000963extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000964#endif
Guido van Rossumded690f1996-05-24 20:48:31 +0000965
Guido van Rossum43f1b8d1997-01-24 04:07:45 +0000966#ifdef DYNAMIC_EXECUTION_PROFILE
967/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000968extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +0000969#endif
970
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000971#ifdef __cplusplus
972}
973#endif
974
Christian Heimes15ebc882008-02-04 18:48:49 +0000975static PyObject *
976sys_clear_type_cache(PyObject* self, PyObject* args)
977{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000978 PyType_ClearCache();
979 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +0000980}
981
982PyDoc_STRVAR(sys_clear_type_cache__doc__,
983"_clear_type_cache() -> None\n\
984Clear the internal type lookup cache.");
985
986
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000987static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 /* Might as well keep this in alphabetic order */
989 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
990 callstats_doc},
991 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
992 sys_clear_type_cache__doc__},
993 {"_current_frames", sys_current_frames, METH_NOARGS,
994 current_frames_doc},
995 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
996 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
997 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
998 {"exit", sys_exit, METH_VARARGS, exit_doc},
999 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
1000 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001001#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001002 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
1003 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001004#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001005#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001006 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001007#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001008#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001009 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +00001010#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
1012 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +00001013#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001014 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +00001015#endif
1016#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001017 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001018#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001019 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1020 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1021 getrecursionlimit_doc},
1022 {"getsizeof", (PyCFunction)sys_getsizeof,
1023 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1024 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001025#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001026 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1027 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001028#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001029 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001030#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001032#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
1034 setdefaultencoding_doc},
1035 {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS,
1036 setfilesystemencoding_doc},
1037 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1038 setcheckinterval_doc},
1039 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1040 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001041#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001042 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1043 setswitchinterval_doc},
1044 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1045 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001046#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001047#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001048 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1049 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001050#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001051 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1052 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1053 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1054 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001055#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001056 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001057#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001058 {"settrace", sys_settrace, METH_O, settrace_doc},
1059 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1060 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1061 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001062};
1063
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001064static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001065list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001067 PyObject *list = PyList_New(0);
1068 int i;
1069 if (list == NULL)
1070 return NULL;
1071 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1072 PyObject *name = PyUnicode_FromString(
1073 PyImport_Inittab[i].name);
1074 if (name == NULL)
1075 break;
1076 PyList_Append(list, name);
1077 Py_DECREF(name);
1078 }
1079 if (PyList_Sort(list) != 0) {
1080 Py_DECREF(list);
1081 list = NULL;
1082 }
1083 if (list) {
1084 PyObject *v = PyList_AsTuple(list);
1085 Py_DECREF(list);
1086 list = v;
1087 }
1088 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001089}
1090
Guido van Rossum23fff912000-12-15 22:02:05 +00001091static PyObject *warnoptions = NULL;
1092
1093void
1094PySys_ResetWarnOptions(void)
1095{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001096 if (warnoptions == NULL || !PyList_Check(warnoptions))
1097 return;
1098 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001099}
1100
1101void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001102PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001103{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001104 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1105 Py_XDECREF(warnoptions);
1106 warnoptions = PyList_New(0);
1107 if (warnoptions == NULL)
1108 return;
1109 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001110 PyList_Append(warnoptions, unicode);
1111}
1112
1113void
1114PySys_AddWarnOption(const wchar_t *s)
1115{
1116 PyObject *unicode;
1117 unicode = PyUnicode_FromWideChar(s, -1);
1118 if (unicode == NULL)
1119 return;
1120 PySys_AddWarnOptionUnicode(unicode);
1121 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001122}
1123
Christian Heimes33fe8092008-04-13 13:53:33 +00001124int
1125PySys_HasWarnOptions(void)
1126{
1127 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1128}
1129
Guido van Rossum40552d01998-08-06 03:34:39 +00001130/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1131 Two literals concatenated works just fine. If you have a K&R compiler
1132 or other abomination that however *does* understand longer strings,
1133 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001134PyDoc_VAR(sys_doc) =
1135PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001136"This module provides access to some objects used or maintained by the\n\
1137interpreter and to functions that interact strongly with the interpreter.\n\
1138\n\
1139Dynamic objects:\n\
1140\n\
1141argv -- command line arguments; argv[0] is the script pathname if known\n\
1142path -- module search path; path[0] is the script directory, else ''\n\
1143modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001144\n\
1145displayhook -- called to show results in an interactive session\n\
1146excepthook -- called to handle any uncaught exception other than SystemExit\n\
1147 To customize printing in an interactive session or to install a custom\n\
1148 top-level exception handler, assign other functions to replace these.\n\
1149\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001150stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001151stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001152stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001153 By assigning other file objects (or objects that behave like files)\n\
1154 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001155\n\
1156last_type -- type of last uncaught exception\n\
1157last_value -- value of last uncaught exception\n\
1158last_traceback -- traceback of last uncaught exception\n\
1159 These three are only available in an interactive session after a\n\
1160 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001161"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001162)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001163/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001164PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001165"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001166Static objects:\n\
1167\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001168float_info -- a dict with information about the float implementation.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001169int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001170maxsize -- the largest supported length of containers.\n\
Martin v. Löwisce9b5a52001-06-27 06:28:56 +00001171maxunicode -- the largest supported character\n\
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001172builtin_module_names -- tuple of module names built into this interpreter\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001173subversion -- subversion information of the build as tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001174version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001175version_info -- version information as a named tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001176hexversion -- version information encoded as a single integer\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001177copyright -- copyright notice pertaining to this interpreter\n\
1178platform -- platform identifier\n\
1179executable -- pathname of this Python interpreter\n\
1180prefix -- prefix used to find the Python library\n\
1181exec_prefix -- prefix used to find the machine-specific Python library\n\
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001182float_repr_style -- string indicating the style of repr() output for floats\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001183"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001184)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001185#ifdef MS_WINDOWS
1186/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001187PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001188"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001189winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001190"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001191)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001192#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001193PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001194"__stdin__ -- the original stdin; don't touch!\n\
1195__stdout__ -- the original stdout; don't touch!\n\
1196__stderr__ -- the original stderr; don't touch!\n\
1197__displayhook__ -- the original displayhook; don't touch!\n\
1198__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001199\n\
1200Functions:\n\
1201\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001202displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001203excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001204exc_info() -- return thread-safe information about the current exception\n\
1205exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001206getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001207getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001208getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001209getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001210getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001211gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001212setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001213setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001214setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001215setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001216settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001217"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001218)
Fred Drakeccede592000-08-14 20:59:57 +00001219/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001220
Martin v. Löwis43b57802006-01-05 23:38:54 +00001221/* Subversion branch and revision management */
1222static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION;
1223static const char headurl[] = "$HeadURL$";
1224static int svn_initialized;
1225static char patchlevel_revision[50]; /* Just the number */
1226static char branch[50];
1227static char shortbranch[50];
1228static const char *svn_revision;
1229
Tim Peterse86e7a52006-01-06 02:42:46 +00001230static void
1231svnversion_init(void)
Martin v. Löwis43b57802006-01-05 23:38:54 +00001232{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001233 const char *python, *br_start, *br_end, *br_end2, *svnversion;
1234 Py_ssize_t len;
1235 int istag = 0;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001236
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 if (svn_initialized)
1238 return;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001239
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001240 python = strstr(headurl, "/python/");
1241 if (!python) {
1242 strcpy(branch, "unknown branch");
1243 strcpy(shortbranch, "unknown");
1244 }
1245 else {
1246 br_start = python + 8;
1247 br_end = strchr(br_start, '/');
1248 assert(br_end);
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001249
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 /* Works even for trunk,
1251 as we are in trunk/Python/sysmodule.c */
1252 br_end2 = strchr(br_end+1, '/');
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001253
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001254 istag = strncmp(br_start, "tags", 4) == 0;
1255 if (strncmp(br_start, "trunk", 5) == 0) {
1256 strcpy(branch, "trunk");
1257 strcpy(shortbranch, "trunk");
1258 }
1259 else if (istag || strncmp(br_start, "branches", 8) == 0) {
1260 len = br_end2 - br_start;
1261 strncpy(branch, br_start, len);
1262 branch[len] = '\0';
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001263
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001264 len = br_end2 - (br_end + 1);
1265 strncpy(shortbranch, br_end + 1, len);
1266 shortbranch[len] = '\0';
1267 }
1268 else {
1269 Py_FatalError("bad HeadURL");
1270 return;
1271 }
1272 }
Martin v. Löwis43b57802006-01-05 23:38:54 +00001273
1274
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001275 svnversion = _Py_svnversion();
1276 if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0)
1277 svn_revision = svnversion;
1278 else if (istag) {
1279 len = strlen(_patchlevel_revision);
1280 assert(len >= 13);
1281 assert(len < (sizeof(patchlevel_revision) + 13));
1282 strncpy(patchlevel_revision, _patchlevel_revision + 11,
1283 len - 13);
1284 patchlevel_revision[len - 13] = '\0';
1285 svn_revision = patchlevel_revision;
1286 }
1287 else
1288 svn_revision = "";
Tim Peters216b78b2006-01-06 02:40:53 +00001289
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001290 svn_initialized = 1;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001291}
1292
1293/* Return svnversion output if available.
1294 Else return Revision of patchlevel.h if on branch.
1295 Else return empty string */
1296const char*
1297Py_SubversionRevision()
1298{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 svnversion_init();
1300 return svn_revision;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001301}
1302
1303const char*
1304Py_SubversionShortBranch()
1305{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001306 svnversion_init();
1307 return shortbranch;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001308}
1309
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001310
1311PyDoc_STRVAR(flags__doc__,
1312"sys.flags\n\
1313\n\
1314Flags provided through command line arguments or environment vars.");
1315
1316static PyTypeObject FlagsType;
1317
1318static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 {"debug", "-d"},
1320 {"division_warning", "-Q"},
1321 {"inspect", "-i"},
1322 {"interactive", "-i"},
1323 {"optimize", "-O or -OO"},
1324 {"dont_write_bytecode", "-B"},
1325 {"no_user_site", "-s"},
1326 {"no_site", "-S"},
1327 {"ignore_environment", "-E"},
1328 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001329#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001330 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001331#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 /* {"unbuffered", "-u"}, */
1333 /* {"skip_first", "-x"}, */
1334 {"bytes_warning", "-b"},
1335 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001336};
1337
1338static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001339 "sys.flags", /* name */
1340 flags__doc__, /* doc */
1341 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001342#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001343 12
Georg Brandle1b5ac62008-06-04 13:06:58 +00001344#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001345 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001346#endif
1347};
1348
1349static PyObject*
1350make_flags(void)
1351{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001352 int pos = 0;
1353 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 seq = PyStructSequence_New(&FlagsType);
1356 if (seq == NULL)
1357 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001358
1359#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001361
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001362 SetFlag(Py_DebugFlag);
1363 SetFlag(Py_DivisionWarningFlag);
1364 SetFlag(Py_InspectFlag);
1365 SetFlag(Py_InteractiveFlag);
1366 SetFlag(Py_OptimizeFlag);
1367 SetFlag(Py_DontWriteBytecodeFlag);
1368 SetFlag(Py_NoUserSiteDirectory);
1369 SetFlag(Py_NoSiteFlag);
1370 SetFlag(Py_IgnoreEnvironmentFlag);
1371 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001372#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001374#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001375 /* SetFlag(saw_unbuffered_flag); */
1376 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001377 SetFlag(Py_BytesWarningFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001378#undef SetFlag
1379
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001380 if (PyErr_Occurred()) {
1381 return NULL;
1382 }
1383 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001384}
1385
Eric Smith0e5b5622009-02-06 01:32:42 +00001386PyDoc_STRVAR(version_info__doc__,
1387"sys.version_info\n\
1388\n\
1389Version information as a named tuple.");
1390
1391static PyTypeObject VersionInfoType;
1392
1393static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 {"major", "Major release number"},
1395 {"minor", "Minor release number"},
1396 {"micro", "Patch release number"},
1397 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1398 {"serial", "Serial release number"},
1399 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001400};
1401
1402static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 "sys.version_info", /* name */
1404 version_info__doc__, /* doc */
1405 version_info_fields, /* fields */
1406 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001407};
1408
1409static PyObject *
1410make_version_info(void)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyObject *version_info;
1413 char *s;
1414 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 version_info = PyStructSequence_New(&VersionInfoType);
1417 if (version_info == NULL) {
1418 return NULL;
1419 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 /*
1422 * These release level checks are mutually exclusive and cover
1423 * the field, so don't get too fancy with the pre-processor!
1424 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001425#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001426 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001427#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001429#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001431#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001432 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001433#endif
1434
1435#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001437#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001439
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001440 SetIntItem(PY_MAJOR_VERSION);
1441 SetIntItem(PY_MINOR_VERSION);
1442 SetIntItem(PY_MICRO_VERSION);
1443 SetStrItem(s);
1444 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001445#undef SetIntItem
1446#undef SetStrItem
1447
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001448 if (PyErr_Occurred()) {
1449 Py_CLEAR(version_info);
1450 return NULL;
1451 }
1452 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001453}
1454
Martin v. Löwis1a214512008-06-11 05:26:20 +00001455static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001456 PyModuleDef_HEAD_INIT,
1457 "sys",
1458 sys_doc,
1459 -1, /* multiple "initialization" just copies the module dict. */
1460 sys_methods,
1461 NULL,
1462 NULL,
1463 NULL,
1464 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001465};
1466
Guido van Rossum25ce5661997-08-02 03:10:38 +00001467PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001468_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001469{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001470 PyObject *m, *v, *sysdict;
1471 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001472
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001473 m = PyModule_Create(&sysmodule);
1474 if (m == NULL)
1475 return NULL;
1476 sysdict = PyModule_GetDict(m);
1477#define SET_SYS_FROM_STRING(key, value) \
1478 v = value; \
1479 if (v != NULL) \
1480 PyDict_SetItemString(sysdict, key, v); \
1481 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 /* Check that stdin is not a directory
1484 Using shell redirection, you can redirect stdin to a directory,
1485 crashing the Python interpreter. Catch this common mistake here
1486 and output a useful error message. Note that under MS Windows,
1487 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001488#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 {
1490 struct stat sb;
1491 if (fstat(fileno(stdin), &sb) == 0 &&
1492 S_ISDIR(sb.st_mode)) {
1493 /* There's nothing more we can do. */
1494 /* Py_FatalError() will core dump, so just exit. */
1495 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1496 exit(EXIT_FAILURE);
1497 }
1498 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001499#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001500
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001501 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001502
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 PyDict_SetItemString(sysdict, "__displayhook__",
1504 PyDict_GetItemString(sysdict, "displayhook"));
1505 PyDict_SetItemString(sysdict, "__excepthook__",
1506 PyDict_GetItemString(sysdict, "excepthook"));
1507 SET_SYS_FROM_STRING("version",
1508 PyUnicode_FromString(Py_GetVersion()));
1509 SET_SYS_FROM_STRING("hexversion",
1510 PyLong_FromLong(PY_VERSION_HEX));
1511 svnversion_init();
1512 SET_SYS_FROM_STRING("subversion",
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001513 Py_BuildValue("(sss)", "CPython", branch,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 svn_revision));
1515 SET_SYS_FROM_STRING("dont_write_bytecode",
1516 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1517 SET_SYS_FROM_STRING("api_version",
1518 PyLong_FromLong(PYTHON_API_VERSION));
1519 SET_SYS_FROM_STRING("copyright",
1520 PyUnicode_FromString(Py_GetCopyright()));
1521 SET_SYS_FROM_STRING("platform",
1522 PyUnicode_FromString(Py_GetPlatform()));
1523 SET_SYS_FROM_STRING("executable",
1524 PyUnicode_FromWideChar(
1525 Py_GetProgramFullPath(), -1));
1526 SET_SYS_FROM_STRING("prefix",
1527 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1528 SET_SYS_FROM_STRING("exec_prefix",
1529 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1530 SET_SYS_FROM_STRING("maxsize",
1531 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1532 SET_SYS_FROM_STRING("float_info",
1533 PyFloat_GetInfo());
1534 SET_SYS_FROM_STRING("int_info",
1535 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001536 /* initialize hash_info */
1537 if (Hash_InfoType.tp_name == 0)
1538 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1539 SET_SYS_FROM_STRING("hash_info",
1540 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 SET_SYS_FROM_STRING("maxunicode",
1542 PyLong_FromLong(PyUnicode_GetMax()));
1543 SET_SYS_FROM_STRING("builtin_module_names",
1544 list_builtin_module_names());
1545 {
1546 /* Assumes that longs are at least 2 bytes long.
1547 Should be safe! */
1548 unsigned long number = 1;
1549 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001551 s = (char *) &number;
1552 if (s[0] == 0)
1553 value = "big";
1554 else
1555 value = "little";
1556 SET_SYS_FROM_STRING("byteorder",
1557 PyUnicode_FromString(value));
1558 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001559#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001560 SET_SYS_FROM_STRING("dllhandle",
1561 PyLong_FromVoidPtr(PyWin_DLLhModule));
1562 SET_SYS_FROM_STRING("winver",
1563 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001564#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (warnoptions == NULL) {
1566 warnoptions = PyList_New(0);
1567 }
1568 else {
1569 Py_INCREF(warnoptions);
1570 }
1571 if (warnoptions != NULL) {
1572 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1573 }
Tim Peters216b78b2006-01-06 02:40:53 +00001574
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001575 /* version_info */
1576 if (VersionInfoType.tp_name == 0)
1577 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1578 SET_SYS_FROM_STRING("version_info", make_version_info());
1579 /* prevent user from creating new instances */
1580 VersionInfoType.tp_init = NULL;
1581 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 /* flags */
1584 if (FlagsType.tp_name == 0)
1585 PyStructSequence_InitType(&FlagsType, &flags_desc);
1586 SET_SYS_FROM_STRING("flags", make_flags());
1587 /* prevent user from creating new instances */
1588 FlagsType.tp_init = NULL;
1589 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001590
Eric Smithf7bb5782010-01-27 00:44:57 +00001591
1592#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 /* getwindowsversion */
1594 if (WindowsVersionType.tp_name == 0)
1595 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1596 /* prevent user from creating new instances */
1597 WindowsVersionType.tp_init = NULL;
1598 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001599#endif
1600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001602#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 SET_SYS_FROM_STRING("float_repr_style",
1604 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001605#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 SET_SYS_FROM_STRING("float_repr_style",
1607 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001608#endif
1609
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001610#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001611 if (PyErr_Occurred())
1612 return NULL;
1613 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001614}
1615
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001616static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001617makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001618{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 int i, n;
1620 const wchar_t *p;
1621 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001622
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001623 n = 1;
1624 p = path;
1625 while ((p = wcschr(p, delim)) != NULL) {
1626 n++;
1627 p++;
1628 }
1629 v = PyList_New(n);
1630 if (v == NULL)
1631 return NULL;
1632 for (i = 0; ; i++) {
1633 p = wcschr(path, delim);
1634 if (p == NULL)
1635 p = path + wcslen(path); /* End of string */
1636 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1637 if (w == NULL) {
1638 Py_DECREF(v);
1639 return NULL;
1640 }
1641 PyList_SetItem(v, i, w);
1642 if (*p == '\0')
1643 break;
1644 path = p+1;
1645 }
1646 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001647}
1648
1649void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001650PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 PyObject *v;
1653 if ((v = makepathobject(path, DELIM)) == NULL)
1654 Py_FatalError("can't create sys.path");
1655 if (PySys_SetObject("path", v) != 0)
1656 Py_FatalError("can't assign sys.path");
1657 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001658}
1659
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001660static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001661makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001662{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 PyObject *av;
1664 if (argc <= 0 || argv == NULL) {
1665 /* Ensure at least one (empty) argument is seen */
1666 static wchar_t *empty_argv[1] = {L""};
1667 argv = empty_argv;
1668 argc = 1;
1669 }
1670 av = PyList_New(argc);
1671 if (av != NULL) {
1672 int i;
1673 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001674#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001675 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 /* argv[0] is the script pathname if known */
1678 if (i == 0) {
1679 char* fn = decc$translate_vms(argv[0]);
1680 if ((fn == (char *)0) || fn == (char *)-1)
1681 v = PyUnicode_FromString(argv[0]);
1682 else
1683 v = PyUnicode_FromString(
1684 decc$translate_vms(argv[0]));
1685 } else
1686 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001687#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001688 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001689#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001690 if (v == NULL) {
1691 Py_DECREF(av);
1692 av = NULL;
1693 break;
1694 }
1695 PyList_SetItem(av, i, v);
1696 }
1697 }
1698 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001699}
1700
Martin v. Löwis790465f2008-04-05 20:41:37 +00001701#ifdef HAVE_REALPATH
1702static wchar_t*
1703_wrealpath(const wchar_t *path, wchar_t *resolved_path)
1704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 char cpath[PATH_MAX];
1706 char cresolved_path[PATH_MAX];
1707 char *res;
1708 size_t r;
1709 r = wcstombs(cpath, path, PATH_MAX);
1710 if (r == (size_t)-1 || r >= PATH_MAX) {
1711 errno = EINVAL;
1712 return NULL;
1713 }
1714 res = realpath(cpath, cresolved_path);
1715 if (res == NULL)
1716 return NULL;
1717 r = mbstowcs(resolved_path, cresolved_path, PATH_MAX);
1718 if (r == (size_t)-1 || r >= PATH_MAX) {
1719 errno = EINVAL;
1720 return NULL;
1721 }
1722 return resolved_path;
Martin v. Löwis790465f2008-04-05 20:41:37 +00001723}
1724#endif
1725
Nick Coghland26c18a2010-08-17 13:06:11 +00001726#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1727 (argc > 0 && argv0 != NULL && \
1728 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
1729
Guido van Rossum3f5da241990-12-20 15:06:42 +00001730void
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001731PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001732{
Guido van Rossum162e38c2003-02-19 15:25:10 +00001733#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001735#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001737#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001738 PyObject *av = makeargvobject(argc, argv);
1739 PyObject *path = PySys_GetObject("path");
1740 if (av == NULL)
1741 Py_FatalError("no mem for sys.argv");
1742 if (PySys_SetObject("argv", av) != 0)
1743 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001744 if (updatepath && path != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001745 wchar_t *argv0 = argv[0];
1746 wchar_t *p = NULL;
1747 Py_ssize_t n = 0;
1748 PyObject *a;
1749 extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t);
Guido van Rossumc474dea1997-04-25 15:38:31 +00001750#ifdef HAVE_READLINK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001751 wchar_t link[MAXPATHLEN+1];
1752 wchar_t argv0copy[2*MAXPATHLEN+1];
1753 int nr = 0;
Nick Coghland26c18a2010-08-17 13:06:11 +00001754 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001755 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1756 if (nr > 0) {
1757 /* It's a symlink */
1758 link[nr] = '\0';
1759 if (link[0] == SEP)
1760 argv0 = link; /* Link to absolute path */
1761 else if (wcschr(link, SEP) == NULL)
1762 ; /* Link without path */
1763 else {
1764 /* Must join(dirname(argv0), link) */
1765 wchar_t *q = wcsrchr(argv0, SEP);
1766 if (q == NULL)
1767 argv0 = link; /* argv0 without path */
1768 else {
1769 /* Must make a copy */
1770 wcscpy(argv0copy, argv0);
1771 q = wcsrchr(argv0copy, SEP);
1772 wcscpy(q+1, link);
1773 argv0 = argv0copy;
1774 }
1775 }
1776 }
Guido van Rossumc474dea1997-04-25 15:38:31 +00001777#endif /* HAVE_READLINK */
Guido van Rossumcc883411996-09-10 14:44:21 +00001778#if SEP == '\\' /* Special case for MS filename syntax */
Nick Coghland26c18a2010-08-17 13:06:11 +00001779 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 wchar_t *q;
Martin v. Löwisec59d042009-01-12 07:59:10 +00001781#if defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 /* This code here replaces the first element in argv with the full
1783 path that it represents. Under CE, there are no relative paths so
1784 the argument must be the full path anyway. */
1785 wchar_t *ptemp;
1786 if (GetFullPathNameW(argv0,
1787 sizeof(fullpath)/sizeof(fullpath[0]),
1788 fullpath,
1789 &ptemp)) {
1790 argv0 = fullpath;
1791 }
Thomas Heller27bb71e2003-01-08 14:33:48 +00001792#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001793 p = wcsrchr(argv0, SEP);
1794 /* Test for alternate separator */
1795 q = wcsrchr(p ? p : argv0, '/');
1796 if (q != NULL)
1797 p = q;
1798 if (p != NULL) {
1799 n = p + 1 - argv0;
1800 if (n > 1 && p[-1] != ':')
1801 n--; /* Drop trailing separator */
1802 }
1803 }
Guido van Rossumcc883411996-09-10 14:44:21 +00001804#else /* All other filename syntaxes */
Nick Coghland26c18a2010-08-17 13:06:11 +00001805 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
Guido van Rossum162e38c2003-02-19 15:25:10 +00001806#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001807 if (_wrealpath(argv0, fullpath)) {
1808 argv0 = fullpath;
1809 }
Guido van Rossum162e38c2003-02-19 15:25:10 +00001810#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001811 p = wcsrchr(argv0, SEP);
1812 }
1813 if (p != NULL) {
1814 n = p + 1 - argv0;
Guido van Rossumcc883411996-09-10 14:44:21 +00001815#if SEP == '/' /* Special case for Unix filename syntax */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001816 if (n > 1)
1817 n--; /* Drop trailing separator */
Guido van Rossumcc883411996-09-10 14:44:21 +00001818#endif /* Unix */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001819 }
Guido van Rossumcc883411996-09-10 14:44:21 +00001820#endif /* All others */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001821 a = PyUnicode_FromWideChar(argv0, n);
1822 if (a == NULL)
1823 Py_FatalError("no mem for sys.path insertion");
1824 if (PyList_Insert(path, 0, a) < 0)
1825 Py_FatalError("sys.path.insert(0) failed");
1826 Py_DECREF(a);
1827 }
1828 Py_DECREF(av);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001829}
Guido van Rossuma890e681998-05-12 14:59:24 +00001830
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001831void
1832PySys_SetArgv(int argc, wchar_t **argv)
1833{
1834 PySys_SetArgvEx(argc, argv, 1);
1835}
1836
Victor Stinner14284c22010-04-23 12:02:30 +00001837/* Reimplementation of PyFile_WriteString() no calling indirectly
1838 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1839
1840static int
Victor Stinner79766632010-08-16 17:36:42 +00001841sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001842{
Victor Stinner79766632010-08-16 17:36:42 +00001843 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001844 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00001845
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001846 if (file == NULL)
1847 return -1;
1848
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001849 writer = PyObject_GetAttrString(file, "write");
1850 if (writer == NULL)
1851 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001852
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 args = PyTuple_Pack(1, unicode);
1854 if (args == NULL)
1855 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001856
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001857 result = PyEval_CallObject(writer, args);
1858 if (result == NULL) {
1859 goto error;
1860 } else {
1861 err = 0;
1862 goto finally;
1863 }
Victor Stinner14284c22010-04-23 12:02:30 +00001864
1865error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001866 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001867finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001868 Py_XDECREF(writer);
1869 Py_XDECREF(args);
1870 Py_XDECREF(result);
1871 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001872}
1873
Victor Stinner79766632010-08-16 17:36:42 +00001874static int
1875sys_pyfile_write(const char *text, PyObject *file)
1876{
1877 PyObject *unicode = NULL;
1878 int err;
1879
1880 if (file == NULL)
1881 return -1;
1882
1883 unicode = PyUnicode_FromString(text);
1884 if (unicode == NULL)
1885 return -1;
1886
1887 err = sys_pyfile_write_unicode(unicode, file);
1888 Py_DECREF(unicode);
1889 return err;
1890}
Guido van Rossuma890e681998-05-12 14:59:24 +00001891
1892/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1893 Adapted from code submitted by Just van Rossum.
1894
1895 PySys_WriteStdout(format, ...)
1896 PySys_WriteStderr(format, ...)
1897
1898 The first function writes to sys.stdout; the second to sys.stderr. When
1899 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00001900 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00001901
Victor Stinner14284c22010-04-23 12:02:30 +00001902 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00001903 signal handlers: they may raise a new exception whereas sys_write()
1904 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00001905
Guido van Rossuma890e681998-05-12 14:59:24 +00001906 Both take a printf-style format string as their first argument followed
1907 by a variable length argument list determined by the format string.
1908
1909 *** WARNING ***
1910
1911 The format should limit the total size of the formatted output string to
1912 1000 bytes. In particular, this means that no unrestricted "%s" formats
1913 should occur; these should be limited using "%.<N>s where <N> is a
1914 decimal number calculated so that <N> plus the maximum size of other
1915 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1916 which can print hundreds of digits for very large numbers.
1917
1918 */
1919
1920static void
Victor Stinner79766632010-08-16 17:36:42 +00001921sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00001922{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001923 PyObject *file;
1924 PyObject *error_type, *error_value, *error_traceback;
1925 char buffer[1001];
1926 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1929 file = PySys_GetObject(name);
1930 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
1931 if (sys_pyfile_write(buffer, file) != 0) {
1932 PyErr_Clear();
1933 fputs(buffer, fp);
1934 }
1935 if (written < 0 || (size_t)written >= sizeof(buffer)) {
1936 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00001937 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001939 }
1940 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00001941}
1942
1943void
Guido van Rossuma890e681998-05-12 14:59:24 +00001944PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001945{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001949 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001950 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00001951}
1952
1953void
Guido van Rossuma890e681998-05-12 14:59:24 +00001954PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001955{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001957
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001958 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001959 sys_write("stderr", stderr, format, va);
1960 va_end(va);
1961}
1962
1963static void
1964sys_format(char *name, FILE *fp, const char *format, va_list va)
1965{
1966 PyObject *file, *message;
1967 PyObject *error_type, *error_value, *error_traceback;
1968 char *utf8;
1969
1970 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1971 file = PySys_GetObject(name);
1972 message = PyUnicode_FromFormatV(format, va);
1973 if (message != NULL) {
1974 if (sys_pyfile_write_unicode(message, file) != 0) {
1975 PyErr_Clear();
1976 utf8 = _PyUnicode_AsString(message);
1977 if (utf8 != NULL)
1978 fputs(utf8, fp);
1979 }
1980 Py_DECREF(message);
1981 }
1982 PyErr_Restore(error_type, error_value, error_traceback);
1983}
1984
1985void
1986PySys_FormatStdout(const char *format, ...)
1987{
1988 va_list va;
1989
1990 va_start(va, format);
1991 sys_format("stdout", stdout, format, va);
1992 va_end(va);
1993}
1994
1995void
1996PySys_FormatStderr(const char *format, ...)
1997{
1998 va_list va;
1999
2000 va_start(va, format);
2001 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00002003}