blob: 90c165a495773c51f136b585e54431bfbbe448d6 [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 *
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000186sys_getfilesystemencoding(PyObject *self)
187{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000188 if (Py_FileSystemDefaultEncoding)
189 return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
190 Py_INCREF(Py_None);
191 return Py_None;
Martin v. Löwis73d538b2003-03-05 15:13:47 +0000192}
193
194PyDoc_STRVAR(getfilesystemencoding_doc,
195"getfilesystemencoding() -> string\n\
196\n\
197Return the encoding used to convert Unicode filenames in\n\
198operating system filenames."
199);
200
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000201static PyObject *
202sys_setfilesystemencoding(PyObject *self, PyObject *args)
203{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 PyObject *new_encoding;
205 if (!PyArg_ParseTuple(args, "U:setfilesystemencoding", &new_encoding))
206 return NULL;
207 if (_Py_SetFileSystemEncoding(new_encoding))
208 return NULL;
209 Py_INCREF(Py_None);
210 return Py_None;
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000211}
Martin v. Löwis339d0f72001-08-17 18:39:25 +0000212
Martin v. Löwis04dc25c2008-10-03 16:09:28 +0000213PyDoc_STRVAR(setfilesystemencoding_doc,
214"setfilesystemencoding(string) -> None\n\
215\n\
216Set the encoding used to convert Unicode filenames in\n\
217operating system filenames."
218);
Georg Brandl66a796e2006-12-19 20:50:34 +0000219
220static PyObject *
221sys_intern(PyObject *self, PyObject *args)
222{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000223 PyObject *s;
224 if (!PyArg_ParseTuple(args, "U:intern", &s))
225 return NULL;
226 if (PyUnicode_CheckExact(s)) {
227 Py_INCREF(s);
228 PyUnicode_InternInPlace(&s);
229 return s;
230 }
231 else {
232 PyErr_Format(PyExc_TypeError,
233 "can't intern %.400s", s->ob_type->tp_name);
234 return NULL;
235 }
Georg Brandl66a796e2006-12-19 20:50:34 +0000236}
237
238PyDoc_STRVAR(intern_doc,
239"intern(string) -> string\n\
240\n\
241``Intern'' the given string. This enters the string in the (global)\n\
242table of interned strings whose purpose is to speed up dictionary lookups.\n\
243Return the string itself or the previously interned string object with the\n\
244same value.");
245
246
Fred Drake5755ce62001-06-27 19:19:46 +0000247/*
248 * Cached interned string objects used for calling the profile and
249 * trace functions. Initialized by trace_init().
250 */
Nicholas Bastinc69ebe82004-03-24 21:57:10 +0000251static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
Fred Drake5755ce62001-06-27 19:19:46 +0000252
253static int
254trace_init(void)
255{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000256 static char *whatnames[7] = {"call", "exception", "line", "return",
257 "c_call", "c_exception", "c_return"};
258 PyObject *name;
259 int i;
260 for (i = 0; i < 7; ++i) {
261 if (whatstrings[i] == NULL) {
262 name = PyUnicode_InternFromString(whatnames[i]);
263 if (name == NULL)
264 return -1;
265 whatstrings[i] = name;
266 }
267 }
268 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000269}
270
271
272static PyObject *
273call_trampoline(PyThreadState *tstate, PyObject* callback,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000274 PyFrameObject *frame, int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000275{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000276 PyObject *args = PyTuple_New(3);
277 PyObject *whatstr;
278 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000279
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000280 if (args == NULL)
281 return NULL;
282 Py_INCREF(frame);
283 whatstr = whatstrings[what];
284 Py_INCREF(whatstr);
285 if (arg == NULL)
286 arg = Py_None;
287 Py_INCREF(arg);
288 PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
289 PyTuple_SET_ITEM(args, 1, whatstr);
290 PyTuple_SET_ITEM(args, 2, arg);
Fred Drake5755ce62001-06-27 19:19:46 +0000291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000292 /* call the Python-level function */
293 PyFrame_FastToLocals(frame);
294 result = PyEval_CallObject(callback, args);
295 PyFrame_LocalsToFast(frame, 1);
296 if (result == NULL)
297 PyTraceBack_Here(frame);
Fred Drake5755ce62001-06-27 19:19:46 +0000298
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000299 /* cleanup */
300 Py_DECREF(args);
301 return result;
Fred Drake5755ce62001-06-27 19:19:46 +0000302}
303
304static int
305profile_trampoline(PyObject *self, PyFrameObject *frame,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000306 int what, PyObject *arg)
Fred Drake5755ce62001-06-27 19:19:46 +0000307{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000308 PyThreadState *tstate = frame->f_tstate;
309 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000310
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000311 if (arg == NULL)
312 arg = Py_None;
313 result = call_trampoline(tstate, self, frame, what, arg);
314 if (result == NULL) {
315 PyEval_SetProfile(NULL, NULL);
316 return -1;
317 }
318 Py_DECREF(result);
319 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000320}
321
322static int
323trace_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 *callback;
328 PyObject *result;
Fred Drake5755ce62001-06-27 19:19:46 +0000329
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000330 if (what == PyTrace_CALL)
331 callback = self;
332 else
333 callback = frame->f_trace;
334 if (callback == NULL)
335 return 0;
336 result = call_trampoline(tstate, callback, frame, what, arg);
337 if (result == NULL) {
338 PyEval_SetTrace(NULL, NULL);
339 Py_XDECREF(frame->f_trace);
340 frame->f_trace = NULL;
341 return -1;
342 }
343 if (result != Py_None) {
344 PyObject *temp = frame->f_trace;
345 frame->f_trace = NULL;
346 Py_XDECREF(temp);
347 frame->f_trace = result;
348 }
349 else {
350 Py_DECREF(result);
351 }
352 return 0;
Fred Drake5755ce62001-06-27 19:19:46 +0000353}
Fred Draked0838392001-06-16 21:02:31 +0000354
Fred Drake8b4d01d2000-05-09 19:57:01 +0000355static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000356sys_settrace(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000357{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000358 if (trace_init() == -1)
359 return NULL;
360 if (args == Py_None)
361 PyEval_SetTrace(NULL, NULL);
362 else
363 PyEval_SetTrace(trace_trampoline, args);
364 Py_INCREF(Py_None);
365 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000366}
367
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000368PyDoc_STRVAR(settrace_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000369"settrace(function)\n\
370\n\
371Set the global debug tracing function. It will be called on each\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000372function call. See the debugger chapter in the library manual."
373);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000374
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000375static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000376sys_gettrace(PyObject *self, PyObject *args)
377{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyThreadState *tstate = PyThreadState_GET();
379 PyObject *temp = tstate->c_traceobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000380
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000381 if (temp == NULL)
382 temp = Py_None;
383 Py_INCREF(temp);
384 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000385}
386
387PyDoc_STRVAR(gettrace_doc,
388"gettrace()\n\
389\n\
390Return the global debug tracing function set with sys.settrace.\n\
391See the debugger chapter in the library manual."
392);
393
394static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000395sys_setprofile(PyObject *self, PyObject *args)
Guido van Rossume2437a11992-03-23 18:20:18 +0000396{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000397 if (trace_init() == -1)
398 return NULL;
399 if (args == Py_None)
400 PyEval_SetProfile(NULL, NULL);
401 else
402 PyEval_SetProfile(profile_trampoline, args);
403 Py_INCREF(Py_None);
404 return Py_None;
Guido van Rossume2437a11992-03-23 18:20:18 +0000405}
406
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000407PyDoc_STRVAR(setprofile_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000408"setprofile(function)\n\
409\n\
410Set the profiling function. It will be called on each function call\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000411and return. See the profiler chapter in the library manual."
412);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000413
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000414static PyObject *
Christian Heimes9bd667a2008-01-20 15:14:11 +0000415sys_getprofile(PyObject *self, PyObject *args)
416{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000417 PyThreadState *tstate = PyThreadState_GET();
418 PyObject *temp = tstate->c_profileobj;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000420 if (temp == NULL)
421 temp = Py_None;
422 Py_INCREF(temp);
423 return temp;
Christian Heimes9bd667a2008-01-20 15:14:11 +0000424}
425
426PyDoc_STRVAR(getprofile_doc,
427"getprofile()\n\
428\n\
429Return the profiling function set with sys.setprofile.\n\
430See the profiler chapter in the library manual."
431);
432
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000433static int _check_interval = 100;
434
Christian Heimes9bd667a2008-01-20 15:14:11 +0000435static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000436sys_setcheckinterval(PyObject *self, PyObject *args)
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000437{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000438 if (PyErr_WarnEx(PyExc_DeprecationWarning,
439 "sys.getcheckinterval() and sys.setcheckinterval() "
440 "are deprecated. Use sys.setswitchinterval() "
441 "instead.", 1) < 0)
442 return NULL;
443 if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
444 return NULL;
445 Py_INCREF(Py_None);
446 return Py_None;
Guido van Rossuma0d7a231995-01-09 17:46:13 +0000447}
448
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000449PyDoc_STRVAR(setcheckinterval_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000450"setcheckinterval(n)\n\
451\n\
452Tell the Python interpreter to check for asynchronous events every\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000453n instructions. This also affects how often thread switches occur."
454);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000455
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000456static PyObject *
Tim Peterse5e065b2003-07-06 18:36:54 +0000457sys_getcheckinterval(PyObject *self, PyObject *args)
458{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000459 if (PyErr_WarnEx(PyExc_DeprecationWarning,
460 "sys.getcheckinterval() and sys.setcheckinterval() "
461 "are deprecated. Use sys.getswitchinterval() "
462 "instead.", 1) < 0)
463 return NULL;
464 return PyLong_FromLong(_check_interval);
Tim Peterse5e065b2003-07-06 18:36:54 +0000465}
466
467PyDoc_STRVAR(getcheckinterval_doc,
468"getcheckinterval() -> current check interval; see setcheckinterval()."
469);
470
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000471#ifdef WITH_THREAD
472static PyObject *
473sys_setswitchinterval(PyObject *self, PyObject *args)
474{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000475 double d;
476 if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
477 return NULL;
478 if (d <= 0.0) {
479 PyErr_SetString(PyExc_ValueError,
480 "switch interval must be strictly positive");
481 return NULL;
482 }
483 _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
484 Py_INCREF(Py_None);
485 return Py_None;
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000486}
487
488PyDoc_STRVAR(setswitchinterval_doc,
489"setswitchinterval(n)\n\
490\n\
491Set the ideal thread switching delay inside the Python interpreter\n\
492The actual frequency of switching threads can be lower if the\n\
493interpreter executes long sequences of uninterruptible code\n\
494(this is implementation-specific and workload-dependent).\n\
495\n\
496The parameter must represent the desired switching delay in seconds\n\
497A typical value is 0.005 (5 milliseconds)."
498);
499
500static PyObject *
501sys_getswitchinterval(PyObject *self, PyObject *args)
502{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000503 return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou074e5ed2009-11-10 19:50:40 +0000504}
505
506PyDoc_STRVAR(getswitchinterval_doc,
507"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
508);
509
510#endif /* WITH_THREAD */
511
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000512#ifdef WITH_TSC
513static PyObject *
514sys_settscdump(PyObject *self, PyObject *args)
515{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000516 int bool;
517 PyThreadState *tstate = PyThreadState_Get();
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000519 if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
520 return NULL;
521 if (bool)
522 tstate->interp->tscdump = 1;
523 else
524 tstate->interp->tscdump = 0;
525 Py_INCREF(Py_None);
526 return Py_None;
Tim Peters216b78b2006-01-06 02:40:53 +0000527
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000528}
529
Tim Peters216b78b2006-01-06 02:40:53 +0000530PyDoc_STRVAR(settscdump_doc,
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000531"settscdump(bool)\n\
532\n\
533If true, tell the Python interpreter to dump VM measurements to\n\
534stderr. If false, turn off dump. The measurements are based on the\n\
Michael W. Hudson800ba232004-08-12 18:19:17 +0000535processor's time-stamp counter."
Tim Peters216b78b2006-01-06 02:40:53 +0000536);
Neal Norwitz0f5aed42004-06-13 20:32:17 +0000537#endif /* TSC */
Martin v. Löwisf30d60e2004-06-08 08:17:44 +0000538
Tim Peterse5e065b2003-07-06 18:36:54 +0000539static PyObject *
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000540sys_setrecursionlimit(PyObject *self, PyObject *args)
541{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000542 int new_limit;
543 if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
544 return NULL;
545 if (new_limit <= 0) {
546 PyErr_SetString(PyExc_ValueError,
547 "recursion limit must be positive");
548 return NULL;
549 }
550 Py_SetRecursionLimit(new_limit);
551 Py_INCREF(Py_None);
552 return Py_None;
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000553}
554
Mark Dickinsondc787d22010-05-23 13:33:13 +0000555static PyTypeObject Hash_InfoType;
556
557PyDoc_STRVAR(hash_info_doc,
558"hash_info\n\
559\n\
560A struct sequence providing parameters used for computing\n\
561numeric hashes. The attributes are read only.");
562
563static PyStructSequence_Field hash_info_fields[] = {
564 {"width", "width of the type used for hashing, in bits"},
565 {"modulus", "prime number giving the modulus on which the hash "
566 "function is based"},
567 {"inf", "value to be used for hash of a positive infinity"},
568 {"nan", "value to be used for hash of a nan"},
569 {"imag", "multiplier used for the imaginary part of a complex number"},
570 {NULL, NULL}
571};
572
573static PyStructSequence_Desc hash_info_desc = {
574 "sys.hash_info",
575 hash_info_doc,
576 hash_info_fields,
577 5,
578};
579
Matthias Klosed885e952010-07-06 10:53:30 +0000580static PyObject *
Mark Dickinsondc787d22010-05-23 13:33:13 +0000581get_hash_info(void)
582{
583 PyObject *hash_info;
584 int field = 0;
585 hash_info = PyStructSequence_New(&Hash_InfoType);
586 if (hash_info == NULL)
587 return NULL;
588 PyStructSequence_SET_ITEM(hash_info, field++,
589 PyLong_FromLong(8*sizeof(long)));
590 PyStructSequence_SET_ITEM(hash_info, field++,
591 PyLong_FromLong(_PyHASH_MODULUS));
592 PyStructSequence_SET_ITEM(hash_info, field++,
593 PyLong_FromLong(_PyHASH_INF));
594 PyStructSequence_SET_ITEM(hash_info, field++,
595 PyLong_FromLong(_PyHASH_NAN));
596 PyStructSequence_SET_ITEM(hash_info, field++,
597 PyLong_FromLong(_PyHASH_IMAG));
598 if (PyErr_Occurred()) {
599 Py_CLEAR(hash_info);
600 return NULL;
601 }
602 return hash_info;
603}
604
605
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000606PyDoc_STRVAR(setrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000607"setrecursionlimit(n)\n\
608\n\
609Set the maximum depth of the Python interpreter stack to n. This\n\
610limit prevents infinite recursion from causing an overflow of the C\n\
611stack and crashing Python. The highest possible limit is platform-\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000612dependent."
613);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000614
615static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000616sys_getrecursionlimit(PyObject *self)
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000617{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 return PyLong_FromLong(Py_GetRecursionLimit());
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000619}
620
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000621PyDoc_STRVAR(getrecursionlimit_doc,
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000622"getrecursionlimit()\n\
623\n\
624Return the current value of the recursion limit, the maximum depth\n\
625of the Python interpreter stack. This limit prevents infinite\n\
Jack Jansene739a0d2002-06-26 20:39:20 +0000626recursion from causing an overflow of the C stack and crashing Python."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000627);
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +0000628
Mark Hammond8696ebc2002-10-08 02:44:31 +0000629#ifdef MS_WINDOWS
630PyDoc_STRVAR(getwindowsversion_doc,
631"getwindowsversion()\n\
632\n\
Eric Smithf7bb5782010-01-27 00:44:57 +0000633Return information about the running version of Windows as a named tuple.\n\
634The members are named: major, minor, build, platform, service_pack,\n\
635service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
636backward compatibiliy, only the first 5 items are available by indexing.\n\
637All elements are numbers, except service_pack which is a string. Platform\n\
638may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
6393 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
640controller, 3 for a server."
Mark Hammond8696ebc2002-10-08 02:44:31 +0000641);
642
Eric Smithf7bb5782010-01-27 00:44:57 +0000643static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
644
645static PyStructSequence_Field windows_version_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000646 {"major", "Major version number"},
647 {"minor", "Minor version number"},
648 {"build", "Build number"},
649 {"platform", "Operating system platform"},
650 {"service_pack", "Latest Service Pack installed on the system"},
651 {"service_pack_major", "Service Pack major version number"},
652 {"service_pack_minor", "Service Pack minor version number"},
653 {"suite_mask", "Bit mask identifying available product suites"},
654 {"product_type", "System product type"},
655 {0}
Eric Smithf7bb5782010-01-27 00:44:57 +0000656};
657
658static PyStructSequence_Desc windows_version_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000659 "sys.getwindowsversion", /* name */
660 getwindowsversion_doc, /* doc */
661 windows_version_fields, /* fields */
662 5 /* For backward compatibility,
663 only the first 5 items are accessible
664 via indexing, the rest are name only */
Eric Smithf7bb5782010-01-27 00:44:57 +0000665};
666
Mark Hammond8696ebc2002-10-08 02:44:31 +0000667static PyObject *
668sys_getwindowsversion(PyObject *self)
669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000670 PyObject *version;
671 int pos = 0;
672 OSVERSIONINFOEX ver;
673 ver.dwOSVersionInfoSize = sizeof(ver);
674 if (!GetVersionEx((OSVERSIONINFO*) &ver))
675 return PyErr_SetFromWindowsErr(0);
Eric Smithf7bb5782010-01-27 00:44:57 +0000676
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000677 version = PyStructSequence_New(&WindowsVersionType);
678 if (version == NULL)
679 return NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +0000680
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000681 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
682 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
683 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
684 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
685 PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
686 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
687 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
688 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
689 PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));
Eric Smithf7bb5782010-01-27 00:44:57 +0000690
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000691 return version;
Mark Hammond8696ebc2002-10-08 02:44:31 +0000692}
693
694#endif /* MS_WINDOWS */
695
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000696#ifdef HAVE_DLOPEN
697static PyObject *
698sys_setdlopenflags(PyObject *self, PyObject *args)
699{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000700 int new_val;
701 PyThreadState *tstate = PyThreadState_GET();
702 if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
703 return NULL;
704 if (!tstate)
705 return NULL;
706 tstate->interp->dlopenflags = new_val;
707 Py_INCREF(Py_None);
708 return Py_None;
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000709}
710
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000711PyDoc_STRVAR(setdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000712"setdlopenflags(n) -> None\n\
713\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000714Set the flags used by the interpreter for dlopen calls, such as when the\n\
715interpreter loads extension modules. Among other things, this will enable\n\
716a lazy resolving of symbols when importing a module, if called as\n\
717sys.setdlopenflags(0). To share symbols across extension modules, call as\n\
718sys.setdlopenflags(ctypes.RTLD_GLOBAL). Symbolic names for the flag modules\n\
719can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
720is not available, it can be generated from /usr/include/dlfcn.h using the\n\
721h2py script.");
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000722
723static PyObject *
724sys_getdlopenflags(PyObject *self, PyObject *args)
725{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000726 PyThreadState *tstate = PyThreadState_GET();
727 if (!tstate)
728 return NULL;
729 return PyLong_FromLong(tstate->interp->dlopenflags);
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000730}
731
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000732PyDoc_STRVAR(getdlopenflags_doc,
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000733"getdlopenflags() -> int\n\
734\n\
Alexandre Vassalotti260484d2009-07-17 11:43:26 +0000735Return the current value of the flags that are used for dlopen calls.\n\
736The flag constants are defined in the ctypes and DLFCN modules.");
737
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000738#endif /* HAVE_DLOPEN */
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000739
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000740#ifdef USE_MALLOPT
741/* Link with -lmalloc (or -lmpc) on an SGI */
742#include <malloc.h>
743
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000744static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +0000745sys_mdebug(PyObject *self, PyObject *args)
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 int flag;
748 if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
749 return NULL;
750 mallopt(M_DEBUG, flag);
751 Py_INCREF(Py_None);
752 return Py_None;
Guido van Rossum14b4adb1992-09-03 20:25:30 +0000753}
754#endif /* USE_MALLOPT */
755
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000756static PyObject *
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000757sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000759 PyObject *res = NULL;
760 static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
761 static char *kwlist[] = {"object", "default", 0};
762 PyObject *o, *dflt = NULL;
763 PyObject *method;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000764
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000765 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
766 kwlist, &o, &dflt))
767 return NULL;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000768
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000769 /* Initialize static variable for GC head size */
770 if (gc_head_size == NULL) {
771 gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
772 if (gc_head_size == NULL)
773 return NULL;
774 }
Benjamin Petersona5758c02009-05-09 18:15:04 +0000775
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000776 /* Make sure the type is initialized. float gets initialized late */
777 if (PyType_Ready(Py_TYPE(o)) < 0)
778 return NULL;
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000779
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000780 method = _PyObject_LookupSpecial(o, "__sizeof__",
781 &str__sizeof__);
782 if (method == NULL) {
783 if (!PyErr_Occurred())
784 PyErr_Format(PyExc_TypeError,
785 "Type %.100s doesn't define __sizeof__",
786 Py_TYPE(o)->tp_name);
787 }
788 else {
789 res = PyObject_CallFunctionObjArgs(method, NULL);
790 Py_DECREF(method);
791 }
792
793 /* Has a default value been given */
794 if ((res == NULL) && (dflt != NULL) &&
795 PyErr_ExceptionMatches(PyExc_TypeError))
796 {
797 PyErr_Clear();
798 Py_INCREF(dflt);
799 return dflt;
800 }
801 else if (res == NULL)
802 return res;
803
804 /* add gc_head size */
805 if (PyObject_IS_GC(o)) {
806 PyObject *tmp = res;
807 res = PyNumber_Add(tmp, gc_head_size);
808 Py_DECREF(tmp);
809 }
810 return res;
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000811}
812
813PyDoc_STRVAR(getsizeof_doc,
Robert Schuppeniesfbe94c52008-07-14 10:13:31 +0000814"getsizeof(object, default) -> int\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +0000815\n\
816Return the size of object in bytes.");
817
818static PyObject *
Fred Drakea7688822001-10-24 20:47:48 +0000819sys_getrefcount(PyObject *self, PyObject *arg)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000820{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000821 return PyLong_FromSsize_t(arg->ob_refcnt);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000822}
823
Tim Peters4be93d02002-07-07 19:59:50 +0000824#ifdef Py_REF_DEBUG
Mark Hammond440d8982000-06-20 08:12:48 +0000825static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000826sys_gettotalrefcount(PyObject *self)
Mark Hammond440d8982000-06-20 08:12:48 +0000827{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000828 return PyLong_FromSsize_t(_Py_GetRefTotal());
Mark Hammond440d8982000-06-20 08:12:48 +0000829}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000830#endif /* Py_REF_DEBUG */
Mark Hammond440d8982000-06-20 08:12:48 +0000831
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000832PyDoc_STRVAR(getrefcount_doc,
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000833"getrefcount(object) -> integer\n\
834\n\
Fred Drakeba3ff1b2002-06-20 21:36:19 +0000835Return the reference count of object. The count returned is generally\n\
836one higher than you might expect, because it includes the (temporary)\n\
837reference as an argument to getrefcount()."
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000838);
Guido van Rossumc3bc31e1998-06-27 19:43:25 +0000839
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000840#ifdef COUNT_ALLOCS
841static PyObject *
Martin v. Löwise3eb1f22001-08-16 13:15:00 +0000842sys_getcounts(PyObject *self)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000843{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000844 extern PyObject *get_counts(void);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000845
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000846 return get_counts();
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000847}
848#endif
849
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000850PyDoc_STRVAR(getframe_doc,
Barry Warsawb6a54d22000-12-06 21:47:46 +0000851"_getframe([depth]) -> frameobject\n\
852\n\
853Return a frame object from the call stack. If optional integer depth is\n\
854given, return the frame object that many calls below the top of the stack.\n\
855If that is deeper than the call stack, ValueError is raised. The default\n\
856for depth is zero, returning the frame at the top of the call stack.\n\
857\n\
858This function should be used for internal and specialized\n\
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +0000859purposes only."
860);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000861
862static PyObject *
863sys_getframe(PyObject *self, PyObject *args)
864{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000865 PyFrameObject *f = PyThreadState_GET()->frame;
866 int depth = -1;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000867
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000868 if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
869 return NULL;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000870
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000871 while (depth > 0 && f != NULL) {
872 f = f->f_back;
873 --depth;
874 }
875 if (f == NULL) {
876 PyErr_SetString(PyExc_ValueError,
877 "call stack is not deep enough");
878 return NULL;
879 }
880 Py_INCREF(f);
881 return (PyObject*)f;
Barry Warsawb6a54d22000-12-06 21:47:46 +0000882}
883
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000884PyDoc_STRVAR(current_frames_doc,
885"_current_frames() -> dictionary\n\
886\n\
887Return a dictionary mapping each current thread T's thread id to T's\n\
888current stack frame.\n\
889\n\
890This function should be used for specialized purposes only."
891);
892
893static PyObject *
894sys_current_frames(PyObject *self, PyObject *noargs)
895{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000896 return _PyThread_CurrentFrames();
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000897}
898
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000899PyDoc_STRVAR(call_tracing_doc,
900"call_tracing(func, args) -> object\n\
901\n\
902Call func(*args), while tracing is enabled. The tracing state is\n\
903saved, and restored afterwards. This is intended to be called from\n\
904a debugger from a checkpoint, to recursively debug some other code."
905);
906
907static PyObject *
908sys_call_tracing(PyObject *self, PyObject *args)
909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 PyObject *func, *funcargs;
911 if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
912 return NULL;
913 return _PyEval_CallTracing(func, funcargs);
Guido van Rossuma12fe4e2003-04-09 19:06:21 +0000914}
915
Jeremy Hylton985eba52003-02-05 23:13:00 +0000916PyDoc_STRVAR(callstats_doc,
917"callstats() -> tuple of integers\n\
918\n\
919Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
920when Python was built. Otherwise, return None.\n\
921\n\
922When enabled, this function returns detailed, implementation-specific\n\
923details about the number of function calls executed. The return value is\n\
924a 11-tuple where the entries in the tuple are counts of:\n\
9250. all function calls\n\
9261. calls to PyFunction_Type objects\n\
9272. PyFunction calls that do not create an argument tuple\n\
9283. PyFunction calls that do not create an argument tuple\n\
929 and bypass PyEval_EvalCodeEx()\n\
9304. PyMethod calls\n\
9315. PyMethod calls on bound methods\n\
9326. PyType calls\n\
9337. PyCFunction calls\n\
9348. generator calls\n\
9359. All other calls\n\
93610. Number of stack pops performed by call_function()"
937);
Barry Warsawb6a54d22000-12-06 21:47:46 +0000938
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000939#ifdef __cplusplus
940extern "C" {
941#endif
942
Guido van Rossum7f3f2c11996-05-23 22:45:41 +0000943#ifdef Py_TRACE_REFS
Guido van Rossumded690f1996-05-24 20:48:31 +0000944/* Defined in objects.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000945extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000946#endif
Guido van Rossumded690f1996-05-24 20:48:31 +0000947
Guido van Rossum43f1b8d1997-01-24 04:07:45 +0000948#ifdef DYNAMIC_EXECUTION_PROFILE
949/* Defined in ceval.c because it uses static globals if that file */
Tim Petersdbd9ba62000-07-09 03:09:57 +0000950extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
Guido van Rossum43f1b8d1997-01-24 04:07:45 +0000951#endif
952
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000953#ifdef __cplusplus
954}
955#endif
956
Christian Heimes15ebc882008-02-04 18:48:49 +0000957static PyObject *
958sys_clear_type_cache(PyObject* self, PyObject* args)
959{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000960 PyType_ClearCache();
961 Py_RETURN_NONE;
Christian Heimes15ebc882008-02-04 18:48:49 +0000962}
963
964PyDoc_STRVAR(sys_clear_type_cache__doc__,
965"_clear_type_cache() -> None\n\
966Clear the internal type lookup cache.");
967
968
Guido van Rossum65bf9f21997-04-29 18:33:38 +0000969static PyMethodDef sys_methods[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000970 /* Might as well keep this in alphabetic order */
971 {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
972 callstats_doc},
973 {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
974 sys_clear_type_cache__doc__},
975 {"_current_frames", sys_current_frames, METH_NOARGS,
976 current_frames_doc},
977 {"displayhook", sys_displayhook, METH_O, displayhook_doc},
978 {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
979 {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
980 {"exit", sys_exit, METH_VARARGS, exit_doc},
981 {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
982 METH_NOARGS, getdefaultencoding_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000983#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000984 {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
985 getdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +0000986#endif
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000987#ifdef COUNT_ALLOCS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000988 {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000989#endif
Guido van Rossum43f1b8d1997-01-24 04:07:45 +0000990#ifdef DYNAMIC_EXECUTION_PROFILE
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000991 {"getdxp", _Py_GetDXProfile, METH_VARARGS},
Guido van Rossum43f1b8d1997-01-24 04:07:45 +0000992#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000993 {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
994 METH_NOARGS, getfilesystemencoding_doc},
Guido van Rossum7f3f2c11996-05-23 22:45:41 +0000995#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000996 {"getobjects", _Py_GetObjects, METH_VARARGS},
Tim Peters4be93d02002-07-07 19:59:50 +0000997#endif
998#ifdef Py_REF_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000999 {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001000#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001001 {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
1002 {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
1003 getrecursionlimit_doc},
1004 {"getsizeof", (PyCFunction)sys_getsizeof,
1005 METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
1006 {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001007#ifdef MS_WINDOWS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
1009 getwindowsversion_doc},
Mark Hammond8696ebc2002-10-08 02:44:31 +00001010#endif /* MS_WINDOWS */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 {"intern", sys_intern, METH_VARARGS, intern_doc},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001012#ifdef USE_MALLOPT
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001013 {"mdebug", sys_mdebug, METH_VARARGS},
Guido van Rossum14b4adb1992-09-03 20:25:30 +00001014#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001015 {"setfilesystemencoding", sys_setfilesystemencoding, METH_VARARGS,
1016 setfilesystemencoding_doc},
1017 {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
1018 setcheckinterval_doc},
1019 {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
1020 getcheckinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001021#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001022 {"setswitchinterval", sys_setswitchinterval, METH_VARARGS,
1023 setswitchinterval_doc},
1024 {"getswitchinterval", sys_getswitchinterval, METH_NOARGS,
1025 getswitchinterval_doc},
Antoine Pitrou074e5ed2009-11-10 19:50:40 +00001026#endif
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001027#ifdef HAVE_DLOPEN
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001028 {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
1029 setdlopenflags_doc},
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001030#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 {"setprofile", sys_setprofile, METH_O, setprofile_doc},
1032 {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
1033 {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
1034 setrecursionlimit_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001035#ifdef WITH_TSC
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001036 {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
Martin v. Löwisf30d60e2004-06-08 08:17:44 +00001037#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001038 {"settrace", sys_settrace, METH_O, settrace_doc},
1039 {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
1040 {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1041 {NULL, NULL} /* sentinel */
Guido van Rossum3f5da241990-12-20 15:06:42 +00001042};
1043
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001044static PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001045list_builtin_module_names(void)
Guido van Rossum34679b71993-01-26 13:33:44 +00001046{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001047 PyObject *list = PyList_New(0);
1048 int i;
1049 if (list == NULL)
1050 return NULL;
1051 for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
1052 PyObject *name = PyUnicode_FromString(
1053 PyImport_Inittab[i].name);
1054 if (name == NULL)
1055 break;
1056 PyList_Append(list, name);
1057 Py_DECREF(name);
1058 }
1059 if (PyList_Sort(list) != 0) {
1060 Py_DECREF(list);
1061 list = NULL;
1062 }
1063 if (list) {
1064 PyObject *v = PyList_AsTuple(list);
1065 Py_DECREF(list);
1066 list = v;
1067 }
1068 return list;
Guido van Rossum34679b71993-01-26 13:33:44 +00001069}
1070
Guido van Rossum23fff912000-12-15 22:02:05 +00001071static PyObject *warnoptions = NULL;
1072
1073void
1074PySys_ResetWarnOptions(void)
1075{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001076 if (warnoptions == NULL || !PyList_Check(warnoptions))
1077 return;
1078 PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
Guido van Rossum23fff912000-12-15 22:02:05 +00001079}
1080
1081void
Victor Stinner9ca9c252010-05-19 16:53:30 +00001082PySys_AddWarnOptionUnicode(PyObject *unicode)
Guido van Rossum23fff912000-12-15 22:02:05 +00001083{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001084 if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1085 Py_XDECREF(warnoptions);
1086 warnoptions = PyList_New(0);
1087 if (warnoptions == NULL)
1088 return;
1089 }
Victor Stinner9ca9c252010-05-19 16:53:30 +00001090 PyList_Append(warnoptions, unicode);
1091}
1092
1093void
1094PySys_AddWarnOption(const wchar_t *s)
1095{
1096 PyObject *unicode;
1097 unicode = PyUnicode_FromWideChar(s, -1);
1098 if (unicode == NULL)
1099 return;
1100 PySys_AddWarnOptionUnicode(unicode);
1101 Py_DECREF(unicode);
Guido van Rossum23fff912000-12-15 22:02:05 +00001102}
1103
Christian Heimes33fe8092008-04-13 13:53:33 +00001104int
1105PySys_HasWarnOptions(void)
1106{
1107 return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1108}
1109
Guido van Rossum40552d01998-08-06 03:34:39 +00001110/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1111 Two literals concatenated works just fine. If you have a K&R compiler
1112 or other abomination that however *does* understand longer strings,
1113 get rid of the !!! comment in the middle and the quotes that surround it. */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001114PyDoc_VAR(sys_doc) =
1115PyDoc_STR(
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001116"This module provides access to some objects used or maintained by the\n\
1117interpreter and to functions that interact strongly with the interpreter.\n\
1118\n\
1119Dynamic objects:\n\
1120\n\
1121argv -- command line arguments; argv[0] is the script pathname if known\n\
1122path -- module search path; path[0] is the script directory, else ''\n\
1123modules -- dictionary of loaded modules\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001124\n\
1125displayhook -- called to show results in an interactive session\n\
1126excepthook -- called to handle any uncaught exception other than SystemExit\n\
1127 To customize printing in an interactive session or to install a custom\n\
1128 top-level exception handler, assign other functions to replace these.\n\
1129\n\
Benjamin Peterson06157a42008-07-15 00:28:36 +00001130stdin -- standard input file object; used by input()\n\
Georg Brandl88fc6642007-02-09 21:28:07 +00001131stdout -- standard output file object; used by print()\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001132stderr -- standard error object; used for error messages\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001133 By assigning other file objects (or objects that behave like files)\n\
1134 to these, it is possible to redirect all of the interpreter's I/O.\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001135\n\
1136last_type -- type of last uncaught exception\n\
1137last_value -- value of last uncaught exception\n\
1138last_traceback -- traceback of last uncaught exception\n\
1139 These three are only available in an interactive session after a\n\
1140 traceback has been printed.\n\
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001141"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001142)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001143/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001144PyDoc_STR(
Guido van Rossuma71b5f41999-01-14 19:07:00 +00001145"\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001146Static objects:\n\
1147\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001148float_info -- a dict with information about the float implementation.\n\
Mark Dickinsonbd792642009-03-18 20:06:12 +00001149int_info -- a struct sequence with information about the int implementation.\n\
Thomas Woutersd2cf20e2007-08-30 22:57:53 +00001150maxsize -- the largest supported length of containers.\n\
Martin v. Löwisce9b5a52001-06-27 06:28:56 +00001151maxunicode -- the largest supported character\n\
Neal Norwitz2a47c0f2002-01-29 00:53:41 +00001152builtin_module_names -- tuple of module names built into this interpreter\n\
Christian Heimes2d378ab2007-12-15 01:28:04 +00001153subversion -- subversion information of the build as tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001154version -- the version of this interpreter as a string\n\
Eric Smith0e5b5622009-02-06 01:32:42 +00001155version_info -- version information as a named tuple\n\
Fred Drake801c08d2000-04-13 15:29:10 +00001156hexversion -- version information encoded as a single integer\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001157copyright -- copyright notice pertaining to this interpreter\n\
1158platform -- platform identifier\n\
1159executable -- pathname of this Python interpreter\n\
1160prefix -- prefix used to find the Python library\n\
1161exec_prefix -- prefix used to find the machine-specific Python library\n\
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001162float_repr_style -- string indicating the style of repr() output for floats\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001163"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001164)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001165#ifdef MS_WINDOWS
1166/* concatenating string here */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001167PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001168"dllhandle -- [Windows only] integer handle of the Python DLL\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001169winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001170"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001171)
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001172#endif /* MS_WINDOWS */
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001173PyDoc_STR(
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001174"__stdin__ -- the original stdin; don't touch!\n\
1175__stdout__ -- the original stdout; don't touch!\n\
1176__stderr__ -- the original stderr; don't touch!\n\
1177__displayhook__ -- the original displayhook; don't touch!\n\
1178__excepthook__ -- the original excepthook; don't touch!\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001179\n\
1180Functions:\n\
1181\n\
Georg Brandl1a3284e2007-12-02 09:40:06 +00001182displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yeeb5c51322001-03-23 02:46:52 +00001183excepthook() -- print an exception and its traceback to sys.stderr\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001184exc_info() -- return thread-safe information about the current exception\n\
1185exit() -- exit the interpreter by raising SystemExit\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001186getdlopenflags() -- returns flags to be used for dlopen() calls\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001187getprofile() -- get the global profiling function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001188getrefcount() -- return the reference count for an object (plus one :-)\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001189getrecursionlimit() -- return the max recursion depth for the interpreter\n\
Martin v. Löwis00709aa2008-06-04 14:18:43 +00001190getsizeof() -- return the size of an object in bytes\n\
Christian Heimes9bd667a2008-01-20 15:14:11 +00001191gettrace() -- get the global debug tracing function\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001192setcheckinterval() -- control how often the interpreter checks for events\n\
Martin v. Löwisf0473d52001-07-18 16:17:16 +00001193setdlopenflags() -- set the flags to be used for dlopen() calls\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001194setprofile() -- set the global profiling function\n\
Jeremy Hyltonee5adfb2000-08-31 19:23:01 +00001195setrecursionlimit() -- set the max recursion depth for the interpreter\n\
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001196settrace() -- set the global debug tracing function\n\
Fred Drakeccede592000-08-14 20:59:57 +00001197"
Martin v. Löwisa3fb4f72002-06-09 13:33:54 +00001198)
Fred Drakeccede592000-08-14 20:59:57 +00001199/* end of sys_doc */ ;
Guido van Rossumc3bc31e1998-06-27 19:43:25 +00001200
Martin v. Löwis43b57802006-01-05 23:38:54 +00001201/* Subversion branch and revision management */
1202static const char _patchlevel_revision[] = PY_PATCHLEVEL_REVISION;
1203static const char headurl[] = "$HeadURL$";
1204static int svn_initialized;
1205static char patchlevel_revision[50]; /* Just the number */
1206static char branch[50];
1207static char shortbranch[50];
1208static const char *svn_revision;
1209
Tim Peterse86e7a52006-01-06 02:42:46 +00001210static void
1211svnversion_init(void)
Martin v. Löwis43b57802006-01-05 23:38:54 +00001212{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001213 const char *python, *br_start, *br_end, *br_end2, *svnversion;
1214 Py_ssize_t len;
1215 int istag = 0;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 if (svn_initialized)
1218 return;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001219
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001220 python = strstr(headurl, "/python/");
1221 if (!python) {
1222 strcpy(branch, "unknown branch");
1223 strcpy(shortbranch, "unknown");
1224 }
1225 else {
1226 br_start = python + 8;
1227 br_end = strchr(br_start, '/');
1228 assert(br_end);
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001229
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001230 /* Works even for trunk,
1231 as we are in trunk/Python/sysmodule.c */
1232 br_end2 = strchr(br_end+1, '/');
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001233
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001234 istag = strncmp(br_start, "tags", 4) == 0;
1235 if (strncmp(br_start, "trunk", 5) == 0) {
1236 strcpy(branch, "trunk");
1237 strcpy(shortbranch, "trunk");
1238 }
1239 else if (istag || strncmp(br_start, "branches", 8) == 0) {
1240 len = br_end2 - br_start;
1241 strncpy(branch, br_start, len);
1242 branch[len] = '\0';
Collin Winterd5a5f5d2007-08-22 19:45:07 +00001243
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001244 len = br_end2 - (br_end + 1);
1245 strncpy(shortbranch, br_end + 1, len);
1246 shortbranch[len] = '\0';
1247 }
1248 else {
1249 Py_FatalError("bad HeadURL");
1250 return;
1251 }
1252 }
Martin v. Löwis43b57802006-01-05 23:38:54 +00001253
1254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 svnversion = _Py_svnversion();
1256 if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0)
1257 svn_revision = svnversion;
1258 else if (istag) {
1259 len = strlen(_patchlevel_revision);
1260 assert(len >= 13);
1261 assert(len < (sizeof(patchlevel_revision) + 13));
1262 strncpy(patchlevel_revision, _patchlevel_revision + 11,
1263 len - 13);
1264 patchlevel_revision[len - 13] = '\0';
1265 svn_revision = patchlevel_revision;
1266 }
1267 else
1268 svn_revision = "";
Tim Peters216b78b2006-01-06 02:40:53 +00001269
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001270 svn_initialized = 1;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001271}
1272
1273/* Return svnversion output if available.
1274 Else return Revision of patchlevel.h if on branch.
1275 Else return empty string */
1276const char*
1277Py_SubversionRevision()
1278{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001279 svnversion_init();
1280 return svn_revision;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001281}
1282
1283const char*
1284Py_SubversionShortBranch()
1285{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001286 svnversion_init();
1287 return shortbranch;
Martin v. Löwis43b57802006-01-05 23:38:54 +00001288}
1289
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001290
1291PyDoc_STRVAR(flags__doc__,
1292"sys.flags\n\
1293\n\
1294Flags provided through command line arguments or environment vars.");
1295
1296static PyTypeObject FlagsType;
1297
1298static PyStructSequence_Field flags_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001299 {"debug", "-d"},
1300 {"division_warning", "-Q"},
1301 {"inspect", "-i"},
1302 {"interactive", "-i"},
1303 {"optimize", "-O or -OO"},
1304 {"dont_write_bytecode", "-B"},
1305 {"no_user_site", "-s"},
1306 {"no_site", "-S"},
1307 {"ignore_environment", "-E"},
1308 {"verbose", "-v"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001309#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 {"riscos_wimp", "???"},
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001311#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001312 /* {"unbuffered", "-u"}, */
1313 /* {"skip_first", "-x"}, */
1314 {"bytes_warning", "-b"},
1315 {0}
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001316};
1317
1318static PyStructSequence_Desc flags_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001319 "sys.flags", /* name */
1320 flags__doc__, /* doc */
1321 flags_fields, /* fields */
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001322#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001323 12
Georg Brandle1b5ac62008-06-04 13:06:58 +00001324#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001325 11
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001326#endif
1327};
1328
1329static PyObject*
1330make_flags(void)
1331{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 int pos = 0;
1333 PyObject *seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001334
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001335 seq = PyStructSequence_New(&FlagsType);
1336 if (seq == NULL)
1337 return NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001338
1339#define SetFlag(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001340 PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001341
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001342 SetFlag(Py_DebugFlag);
1343 SetFlag(Py_DivisionWarningFlag);
1344 SetFlag(Py_InspectFlag);
1345 SetFlag(Py_InteractiveFlag);
1346 SetFlag(Py_OptimizeFlag);
1347 SetFlag(Py_DontWriteBytecodeFlag);
1348 SetFlag(Py_NoUserSiteDirectory);
1349 SetFlag(Py_NoSiteFlag);
1350 SetFlag(Py_IgnoreEnvironmentFlag);
1351 SetFlag(Py_VerboseFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001352#ifdef RISCOS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001353 SetFlag(Py_RISCOSWimpFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001354#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 /* SetFlag(saw_unbuffered_flag); */
1356 /* SetFlag(skipfirstline); */
Christian Heimes33fe8092008-04-13 13:53:33 +00001357 SetFlag(Py_BytesWarningFlag);
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001358#undef SetFlag
1359
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 if (PyErr_Occurred()) {
1361 return NULL;
1362 }
1363 return seq;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001364}
1365
Eric Smith0e5b5622009-02-06 01:32:42 +00001366PyDoc_STRVAR(version_info__doc__,
1367"sys.version_info\n\
1368\n\
1369Version information as a named tuple.");
1370
1371static PyTypeObject VersionInfoType;
1372
1373static PyStructSequence_Field version_info_fields[] = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 {"major", "Major release number"},
1375 {"minor", "Minor release number"},
1376 {"micro", "Patch release number"},
1377 {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1378 {"serial", "Serial release number"},
1379 {0}
Eric Smith0e5b5622009-02-06 01:32:42 +00001380};
1381
1382static PyStructSequence_Desc version_info_desc = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 "sys.version_info", /* name */
1384 version_info__doc__, /* doc */
1385 version_info_fields, /* fields */
1386 5
Eric Smith0e5b5622009-02-06 01:32:42 +00001387};
1388
1389static PyObject *
1390make_version_info(void)
1391{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 PyObject *version_info;
1393 char *s;
1394 int pos = 0;
Eric Smith0e5b5622009-02-06 01:32:42 +00001395
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001396 version_info = PyStructSequence_New(&VersionInfoType);
1397 if (version_info == NULL) {
1398 return NULL;
1399 }
Eric Smith0e5b5622009-02-06 01:32:42 +00001400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001401 /*
1402 * These release level checks are mutually exclusive and cover
1403 * the field, so don't get too fancy with the pre-processor!
1404 */
Eric Smith0e5b5622009-02-06 01:32:42 +00001405#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001406 s = "alpha";
Eric Smith0e5b5622009-02-06 01:32:42 +00001407#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001408 s = "beta";
Eric Smith0e5b5622009-02-06 01:32:42 +00001409#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001410 s = "candidate";
Eric Smith0e5b5622009-02-06 01:32:42 +00001411#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 s = "final";
Eric Smith0e5b5622009-02-06 01:32:42 +00001413#endif
1414
1415#define SetIntItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001416 PyStructSequence_SET_ITEM(version_info, pos++, PyLong_FromLong(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001417#define SetStrItem(flag) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001418 PyStructSequence_SET_ITEM(version_info, pos++, PyUnicode_FromString(flag))
Eric Smith0e5b5622009-02-06 01:32:42 +00001419
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 SetIntItem(PY_MAJOR_VERSION);
1421 SetIntItem(PY_MINOR_VERSION);
1422 SetIntItem(PY_MICRO_VERSION);
1423 SetStrItem(s);
1424 SetIntItem(PY_RELEASE_SERIAL);
Eric Smith0e5b5622009-02-06 01:32:42 +00001425#undef SetIntItem
1426#undef SetStrItem
1427
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (PyErr_Occurred()) {
1429 Py_CLEAR(version_info);
1430 return NULL;
1431 }
1432 return version_info;
Eric Smith0e5b5622009-02-06 01:32:42 +00001433}
1434
Martin v. Löwis1a214512008-06-11 05:26:20 +00001435static struct PyModuleDef sysmodule = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001436 PyModuleDef_HEAD_INIT,
1437 "sys",
1438 sys_doc,
1439 -1, /* multiple "initialization" just copies the module dict. */
1440 sys_methods,
1441 NULL,
1442 NULL,
1443 NULL,
1444 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00001445};
1446
Guido van Rossum25ce5661997-08-02 03:10:38 +00001447PyObject *
Thomas Woutersf70ef4f2000-07-22 18:47:25 +00001448_PySys_Init(void)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 PyObject *m, *v, *sysdict;
1451 char *s;
Guido van Rossum25ce5661997-08-02 03:10:38 +00001452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001453 m = PyModule_Create(&sysmodule);
1454 if (m == NULL)
1455 return NULL;
1456 sysdict = PyModule_GetDict(m);
1457#define SET_SYS_FROM_STRING(key, value) \
1458 v = value; \
1459 if (v != NULL) \
1460 PyDict_SetItemString(sysdict, key, v); \
1461 Py_XDECREF(v)
Guido van Rossum25ce5661997-08-02 03:10:38 +00001462
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 /* Check that stdin is not a directory
1464 Using shell redirection, you can redirect stdin to a directory,
1465 crashing the Python interpreter. Catch this common mistake here
1466 and output a useful error message. Note that under MS Windows,
1467 the shell already prevents that. */
Martin v. Löwisec59d042009-01-12 07:59:10 +00001468#if !defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001469 {
1470 struct stat sb;
1471 if (fstat(fileno(stdin), &sb) == 0 &&
1472 S_ISDIR(sb.st_mode)) {
1473 /* There's nothing more we can do. */
1474 /* Py_FatalError() will core dump, so just exit. */
1475 PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1476 exit(EXIT_FAILURE);
1477 }
1478 }
Martin v. Löwisec59d042009-01-12 07:59:10 +00001479#endif
Neal Norwitz11bd1192005-10-03 00:54:56 +00001480
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001481 /* stdin/stdout/stderr are now set by pythonrun.c */
Martin v. Löwis5467d4c2003-05-10 07:10:12 +00001482
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001483 PyDict_SetItemString(sysdict, "__displayhook__",
1484 PyDict_GetItemString(sysdict, "displayhook"));
1485 PyDict_SetItemString(sysdict, "__excepthook__",
1486 PyDict_GetItemString(sysdict, "excepthook"));
1487 SET_SYS_FROM_STRING("version",
1488 PyUnicode_FromString(Py_GetVersion()));
1489 SET_SYS_FROM_STRING("hexversion",
1490 PyLong_FromLong(PY_VERSION_HEX));
1491 svnversion_init();
1492 SET_SYS_FROM_STRING("subversion",
Victor Stinner7eeb5b52010-06-07 19:57:46 +00001493 Py_BuildValue("(sss)", "CPython", branch,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 svn_revision));
1495 SET_SYS_FROM_STRING("dont_write_bytecode",
1496 PyBool_FromLong(Py_DontWriteBytecodeFlag));
1497 SET_SYS_FROM_STRING("api_version",
1498 PyLong_FromLong(PYTHON_API_VERSION));
1499 SET_SYS_FROM_STRING("copyright",
1500 PyUnicode_FromString(Py_GetCopyright()));
1501 SET_SYS_FROM_STRING("platform",
1502 PyUnicode_FromString(Py_GetPlatform()));
1503 SET_SYS_FROM_STRING("executable",
1504 PyUnicode_FromWideChar(
1505 Py_GetProgramFullPath(), -1));
1506 SET_SYS_FROM_STRING("prefix",
1507 PyUnicode_FromWideChar(Py_GetPrefix(), -1));
1508 SET_SYS_FROM_STRING("exec_prefix",
1509 PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1510 SET_SYS_FROM_STRING("maxsize",
1511 PyLong_FromSsize_t(PY_SSIZE_T_MAX));
1512 SET_SYS_FROM_STRING("float_info",
1513 PyFloat_GetInfo());
1514 SET_SYS_FROM_STRING("int_info",
1515 PyLong_GetInfo());
Mark Dickinsondc787d22010-05-23 13:33:13 +00001516 /* initialize hash_info */
1517 if (Hash_InfoType.tp_name == 0)
1518 PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
1519 SET_SYS_FROM_STRING("hash_info",
1520 get_hash_info());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001521 SET_SYS_FROM_STRING("maxunicode",
1522 PyLong_FromLong(PyUnicode_GetMax()));
1523 SET_SYS_FROM_STRING("builtin_module_names",
1524 list_builtin_module_names());
1525 {
1526 /* Assumes that longs are at least 2 bytes long.
1527 Should be safe! */
1528 unsigned long number = 1;
1529 char *value;
Fred Drake099325e2000-08-14 15:47:03 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 s = (char *) &number;
1532 if (s[0] == 0)
1533 value = "big";
1534 else
1535 value = "little";
1536 SET_SYS_FROM_STRING("byteorder",
1537 PyUnicode_FromString(value));
1538 }
Guido van Rossum8b9ea871996-08-23 18:14:47 +00001539#ifdef MS_COREDLL
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 SET_SYS_FROM_STRING("dllhandle",
1541 PyLong_FromVoidPtr(PyWin_DLLhModule));
1542 SET_SYS_FROM_STRING("winver",
1543 PyUnicode_FromString(PyWin_DLLVersionString));
Guido van Rossumc606fe11996-04-09 02:37:57 +00001544#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001545 if (warnoptions == NULL) {
1546 warnoptions = PyList_New(0);
1547 }
1548 else {
1549 Py_INCREF(warnoptions);
1550 }
1551 if (warnoptions != NULL) {
1552 PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1553 }
Tim Peters216b78b2006-01-06 02:40:53 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 /* version_info */
1556 if (VersionInfoType.tp_name == 0)
1557 PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1558 SET_SYS_FROM_STRING("version_info", make_version_info());
1559 /* prevent user from creating new instances */
1560 VersionInfoType.tp_init = NULL;
1561 VersionInfoType.tp_new = NULL;
Eric Smith0e5b5622009-02-06 01:32:42 +00001562
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001563 /* flags */
1564 if (FlagsType.tp_name == 0)
1565 PyStructSequence_InitType(&FlagsType, &flags_desc);
1566 SET_SYS_FROM_STRING("flags", make_flags());
1567 /* prevent user from creating new instances */
1568 FlagsType.tp_init = NULL;
1569 FlagsType.tp_new = NULL;
Christian Heimesd32ed6f2008-01-14 18:49:24 +00001570
Eric Smithf7bb5782010-01-27 00:44:57 +00001571
1572#if defined(MS_WINDOWS)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 /* getwindowsversion */
1574 if (WindowsVersionType.tp_name == 0)
1575 PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1576 /* prevent user from creating new instances */
1577 WindowsVersionType.tp_init = NULL;
1578 WindowsVersionType.tp_new = NULL;
Eric Smithf7bb5782010-01-27 00:44:57 +00001579#endif
1580
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001581 /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001582#ifndef PY_NO_SHORT_FLOAT_REPR
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 SET_SYS_FROM_STRING("float_repr_style",
1584 PyUnicode_FromString("short"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001585#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 SET_SYS_FROM_STRING("float_repr_style",
1587 PyUnicode_FromString("legacy"));
Mark Dickinsonb08a53a2009-04-16 19:52:09 +00001588#endif
1589
Christian Heimes7b3ce6a2008-01-31 14:31:45 +00001590#undef SET_SYS_FROM_STRING
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (PyErr_Occurred())
1592 return NULL;
1593 return m;
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001594}
1595
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001596static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001597makepathobject(const wchar_t *path, wchar_t delim)
Guido van Rossum5b3138b1990-11-18 17:41:40 +00001598{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001599 int i, n;
1600 const wchar_t *p;
1601 PyObject *v, *w;
Tim Peters216b78b2006-01-06 02:40:53 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 n = 1;
1604 p = path;
1605 while ((p = wcschr(p, delim)) != NULL) {
1606 n++;
1607 p++;
1608 }
1609 v = PyList_New(n);
1610 if (v == NULL)
1611 return NULL;
1612 for (i = 0; ; i++) {
1613 p = wcschr(path, delim);
1614 if (p == NULL)
1615 p = path + wcslen(path); /* End of string */
1616 w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
1617 if (w == NULL) {
1618 Py_DECREF(v);
1619 return NULL;
1620 }
1621 PyList_SetItem(v, i, w);
1622 if (*p == '\0')
1623 break;
1624 path = p+1;
1625 }
1626 return v;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001627}
1628
1629void
Martin v. Löwis790465f2008-04-05 20:41:37 +00001630PySys_SetPath(const wchar_t *path)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001631{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001632 PyObject *v;
1633 if ((v = makepathobject(path, DELIM)) == NULL)
1634 Py_FatalError("can't create sys.path");
1635 if (PySys_SetObject("path", v) != 0)
1636 Py_FatalError("can't assign sys.path");
1637 Py_DECREF(v);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001638}
1639
Guido van Rossum65bf9f21997-04-29 18:33:38 +00001640static PyObject *
Martin v. Löwis790465f2008-04-05 20:41:37 +00001641makeargvobject(int argc, wchar_t **argv)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001642{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 PyObject *av;
1644 if (argc <= 0 || argv == NULL) {
1645 /* Ensure at least one (empty) argument is seen */
1646 static wchar_t *empty_argv[1] = {L""};
1647 argv = empty_argv;
1648 argc = 1;
1649 }
1650 av = PyList_New(argc);
1651 if (av != NULL) {
1652 int i;
1653 for (i = 0; i < argc; i++) {
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001654#ifdef __VMS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001655 PyObject *v;
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001656
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 /* argv[0] is the script pathname if known */
1658 if (i == 0) {
1659 char* fn = decc$translate_vms(argv[0]);
1660 if ((fn == (char *)0) || fn == (char *)-1)
1661 v = PyUnicode_FromString(argv[0]);
1662 else
1663 v = PyUnicode_FromString(
1664 decc$translate_vms(argv[0]));
1665 } else
1666 v = PyUnicode_FromString(argv[i]);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001667#else
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001668 PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
Martin v. Löwisc16f3bd2003-05-03 09:14:54 +00001669#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001670 if (v == NULL) {
1671 Py_DECREF(av);
1672 av = NULL;
1673 break;
1674 }
1675 PyList_SetItem(av, i, v);
1676 }
1677 }
1678 return av;
Guido van Rossum3f5da241990-12-20 15:06:42 +00001679}
1680
Martin v. Löwis790465f2008-04-05 20:41:37 +00001681#ifdef HAVE_REALPATH
1682static wchar_t*
1683_wrealpath(const wchar_t *path, wchar_t *resolved_path)
1684{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 char cpath[PATH_MAX];
1686 char cresolved_path[PATH_MAX];
1687 char *res;
1688 size_t r;
1689 r = wcstombs(cpath, path, PATH_MAX);
1690 if (r == (size_t)-1 || r >= PATH_MAX) {
1691 errno = EINVAL;
1692 return NULL;
1693 }
1694 res = realpath(cpath, cresolved_path);
1695 if (res == NULL)
1696 return NULL;
1697 r = mbstowcs(resolved_path, cresolved_path, PATH_MAX);
1698 if (r == (size_t)-1 || r >= PATH_MAX) {
1699 errno = EINVAL;
1700 return NULL;
1701 }
1702 return resolved_path;
Martin v. Löwis790465f2008-04-05 20:41:37 +00001703}
1704#endif
1705
Nick Coghland26c18a2010-08-17 13:06:11 +00001706#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
1707 (argc > 0 && argv0 != NULL && \
1708 wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
1709
Guido van Rossum3f5da241990-12-20 15:06:42 +00001710void
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001711PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001712{
Guido van Rossum162e38c2003-02-19 15:25:10 +00001713#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001714 wchar_t fullpath[MAXPATHLEN];
Martin v. Löwisec59d042009-01-12 07:59:10 +00001715#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 wchar_t fullpath[MAX_PATH];
Thomas Heller27bb71e2003-01-08 14:33:48 +00001717#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001718 PyObject *av = makeargvobject(argc, argv);
1719 PyObject *path = PySys_GetObject("path");
1720 if (av == NULL)
1721 Py_FatalError("no mem for sys.argv");
1722 if (PySys_SetObject("argv", av) != 0)
1723 Py_FatalError("can't assign sys.argv");
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001724 if (updatepath && path != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001725 wchar_t *argv0 = argv[0];
1726 wchar_t *p = NULL;
1727 Py_ssize_t n = 0;
1728 PyObject *a;
1729 extern int _Py_wreadlink(const wchar_t *, wchar_t *, size_t);
Guido van Rossumc474dea1997-04-25 15:38:31 +00001730#ifdef HAVE_READLINK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 wchar_t link[MAXPATHLEN+1];
1732 wchar_t argv0copy[2*MAXPATHLEN+1];
1733 int nr = 0;
Nick Coghland26c18a2010-08-17 13:06:11 +00001734 if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
1736 if (nr > 0) {
1737 /* It's a symlink */
1738 link[nr] = '\0';
1739 if (link[0] == SEP)
1740 argv0 = link; /* Link to absolute path */
1741 else if (wcschr(link, SEP) == NULL)
1742 ; /* Link without path */
1743 else {
1744 /* Must join(dirname(argv0), link) */
1745 wchar_t *q = wcsrchr(argv0, SEP);
1746 if (q == NULL)
1747 argv0 = link; /* argv0 without path */
1748 else {
1749 /* Must make a copy */
1750 wcscpy(argv0copy, argv0);
1751 q = wcsrchr(argv0copy, SEP);
1752 wcscpy(q+1, link);
1753 argv0 = argv0copy;
1754 }
1755 }
1756 }
Guido van Rossumc474dea1997-04-25 15:38:31 +00001757#endif /* HAVE_READLINK */
Guido van Rossumcc883411996-09-10 14:44:21 +00001758#if SEP == '\\' /* Special case for MS filename syntax */
Nick Coghland26c18a2010-08-17 13:06:11 +00001759 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001760 wchar_t *q;
Martin v. Löwisec59d042009-01-12 07:59:10 +00001761#if defined(MS_WINDOWS) && !defined(MS_WINCE)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 /* This code here replaces the first element in argv with the full
1763 path that it represents. Under CE, there are no relative paths so
1764 the argument must be the full path anyway. */
1765 wchar_t *ptemp;
1766 if (GetFullPathNameW(argv0,
1767 sizeof(fullpath)/sizeof(fullpath[0]),
1768 fullpath,
1769 &ptemp)) {
1770 argv0 = fullpath;
1771 }
Thomas Heller27bb71e2003-01-08 14:33:48 +00001772#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001773 p = wcsrchr(argv0, SEP);
1774 /* Test for alternate separator */
1775 q = wcsrchr(p ? p : argv0, '/');
1776 if (q != NULL)
1777 p = q;
1778 if (p != NULL) {
1779 n = p + 1 - argv0;
1780 if (n > 1 && p[-1] != ':')
1781 n--; /* Drop trailing separator */
1782 }
1783 }
Guido van Rossumcc883411996-09-10 14:44:21 +00001784#else /* All other filename syntaxes */
Nick Coghland26c18a2010-08-17 13:06:11 +00001785 if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
Guido van Rossum162e38c2003-02-19 15:25:10 +00001786#if defined(HAVE_REALPATH)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001787 if (_wrealpath(argv0, fullpath)) {
1788 argv0 = fullpath;
1789 }
Guido van Rossum162e38c2003-02-19 15:25:10 +00001790#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 p = wcsrchr(argv0, SEP);
1792 }
1793 if (p != NULL) {
1794 n = p + 1 - argv0;
Guido van Rossumcc883411996-09-10 14:44:21 +00001795#if SEP == '/' /* Special case for Unix filename syntax */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001796 if (n > 1)
1797 n--; /* Drop trailing separator */
Guido van Rossumcc883411996-09-10 14:44:21 +00001798#endif /* Unix */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001799 }
Guido van Rossumcc883411996-09-10 14:44:21 +00001800#endif /* All others */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001801 a = PyUnicode_FromWideChar(argv0, n);
1802 if (a == NULL)
1803 Py_FatalError("no mem for sys.path insertion");
1804 if (PyList_Insert(path, 0, a) < 0)
1805 Py_FatalError("sys.path.insert(0) failed");
1806 Py_DECREF(a);
1807 }
1808 Py_DECREF(av);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001809}
Guido van Rossuma890e681998-05-12 14:59:24 +00001810
Antoine Pitrouf978fac2010-05-21 17:25:34 +00001811void
1812PySys_SetArgv(int argc, wchar_t **argv)
1813{
1814 PySys_SetArgvEx(argc, argv, 1);
1815}
1816
Victor Stinner14284c22010-04-23 12:02:30 +00001817/* Reimplementation of PyFile_WriteString() no calling indirectly
1818 PyErr_CheckSignals(): avoid the call to PyObject_Str(). */
1819
1820static int
Victor Stinner79766632010-08-16 17:36:42 +00001821sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
Victor Stinner14284c22010-04-23 12:02:30 +00001822{
Victor Stinner79766632010-08-16 17:36:42 +00001823 PyObject *writer = NULL, *args = NULL, *result = NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001824 int err;
Victor Stinner14284c22010-04-23 12:02:30 +00001825
Victor Stinnerecccc4f2010-06-08 20:46:00 +00001826 if (file == NULL)
1827 return -1;
1828
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001829 writer = PyObject_GetAttrString(file, "write");
1830 if (writer == NULL)
1831 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001832
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 args = PyTuple_Pack(1, unicode);
1834 if (args == NULL)
1835 goto error;
Victor Stinner14284c22010-04-23 12:02:30 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 result = PyEval_CallObject(writer, args);
1838 if (result == NULL) {
1839 goto error;
1840 } else {
1841 err = 0;
1842 goto finally;
1843 }
Victor Stinner14284c22010-04-23 12:02:30 +00001844
1845error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 err = -1;
Victor Stinner14284c22010-04-23 12:02:30 +00001847finally:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001848 Py_XDECREF(writer);
1849 Py_XDECREF(args);
1850 Py_XDECREF(result);
1851 return err;
Victor Stinner14284c22010-04-23 12:02:30 +00001852}
1853
Victor Stinner79766632010-08-16 17:36:42 +00001854static int
1855sys_pyfile_write(const char *text, PyObject *file)
1856{
1857 PyObject *unicode = NULL;
1858 int err;
1859
1860 if (file == NULL)
1861 return -1;
1862
1863 unicode = PyUnicode_FromString(text);
1864 if (unicode == NULL)
1865 return -1;
1866
1867 err = sys_pyfile_write_unicode(unicode, file);
1868 Py_DECREF(unicode);
1869 return err;
1870}
Guido van Rossuma890e681998-05-12 14:59:24 +00001871
1872/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1873 Adapted from code submitted by Just van Rossum.
1874
1875 PySys_WriteStdout(format, ...)
1876 PySys_WriteStderr(format, ...)
1877
1878 The first function writes to sys.stdout; the second to sys.stderr. When
1879 there is a problem, they write to the real (C level) stdout or stderr;
Guido van Rossum8442af31998-10-12 18:22:10 +00001880 no exceptions are raised.
Guido van Rossuma890e681998-05-12 14:59:24 +00001881
Victor Stinner14284c22010-04-23 12:02:30 +00001882 PyErr_CheckSignals() is not called to avoid the execution of the Python
Victor Stinner79766632010-08-16 17:36:42 +00001883 signal handlers: they may raise a new exception whereas sys_write()
1884 ignores all exceptions.
Victor Stinner14284c22010-04-23 12:02:30 +00001885
Guido van Rossuma890e681998-05-12 14:59:24 +00001886 Both take a printf-style format string as their first argument followed
1887 by a variable length argument list determined by the format string.
1888
1889 *** WARNING ***
1890
1891 The format should limit the total size of the formatted output string to
1892 1000 bytes. In particular, this means that no unrestricted "%s" formats
1893 should occur; these should be limited using "%.<N>s where <N> is a
1894 decimal number calculated so that <N> plus the maximum size of other
1895 formatted text does not exceed 1000 bytes. Also watch out for "%f",
1896 which can print hundreds of digits for very large numbers.
1897
1898 */
1899
1900static void
Victor Stinner79766632010-08-16 17:36:42 +00001901sys_write(char *name, FILE *fp, const char *format, va_list va)
Guido van Rossuma890e681998-05-12 14:59:24 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyObject *file;
1904 PyObject *error_type, *error_value, *error_traceback;
1905 char buffer[1001];
1906 int written;
Guido van Rossuma890e681998-05-12 14:59:24 +00001907
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001908 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1909 file = PySys_GetObject(name);
1910 written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
1911 if (sys_pyfile_write(buffer, file) != 0) {
1912 PyErr_Clear();
1913 fputs(buffer, fp);
1914 }
1915 if (written < 0 || (size_t)written >= sizeof(buffer)) {
1916 const char *truncated = "... truncated";
Victor Stinner79766632010-08-16 17:36:42 +00001917 if (sys_pyfile_write(truncated, file) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001918 fputs(truncated, fp);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001919 }
1920 PyErr_Restore(error_type, error_value, error_traceback);
Guido van Rossuma890e681998-05-12 14:59:24 +00001921}
1922
1923void
Guido van Rossuma890e681998-05-12 14:59:24 +00001924PySys_WriteStdout(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001925{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001926 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001927
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001928 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001929 sys_write("stdout", stdout, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001930 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00001931}
1932
1933void
Guido van Rossuma890e681998-05-12 14:59:24 +00001934PySys_WriteStderr(const char *format, ...)
Guido van Rossuma890e681998-05-12 14:59:24 +00001935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 va_list va;
Guido van Rossuma890e681998-05-12 14:59:24 +00001937
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001938 va_start(va, format);
Victor Stinner79766632010-08-16 17:36:42 +00001939 sys_write("stderr", stderr, format, va);
1940 va_end(va);
1941}
1942
1943static void
1944sys_format(char *name, FILE *fp, const char *format, va_list va)
1945{
1946 PyObject *file, *message;
1947 PyObject *error_type, *error_value, *error_traceback;
1948 char *utf8;
1949
1950 PyErr_Fetch(&error_type, &error_value, &error_traceback);
1951 file = PySys_GetObject(name);
1952 message = PyUnicode_FromFormatV(format, va);
1953 if (message != NULL) {
1954 if (sys_pyfile_write_unicode(message, file) != 0) {
1955 PyErr_Clear();
1956 utf8 = _PyUnicode_AsString(message);
1957 if (utf8 != NULL)
1958 fputs(utf8, fp);
1959 }
1960 Py_DECREF(message);
1961 }
1962 PyErr_Restore(error_type, error_value, error_traceback);
1963}
1964
1965void
1966PySys_FormatStdout(const char *format, ...)
1967{
1968 va_list va;
1969
1970 va_start(va, format);
1971 sys_format("stdout", stdout, format, va);
1972 va_end(va);
1973}
1974
1975void
1976PySys_FormatStderr(const char *format, ...)
1977{
1978 va_list va;
1979
1980 va_start(va, format);
1981 sys_format("stderr", stderr, format, va);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001982 va_end(va);
Guido van Rossuma890e681998-05-12 14:59:24 +00001983}