sysmodule.c revision 0f5aed4e41d1df04ffd004747fc0da4ace16350f
1
2/* System module */
3
4/*
5Various bits of information used by the interpreter are collected in
6module 'sys'.
7Function member:
8- exit(sts): raise SystemExit
9Data members:
10- stdin, stdout, stderr: standard file objects
11- modules: the table of modules (dictionary)
12- path: module search path (list of strings)
13- argv: script arguments (list of strings)
14- ps1, ps2: optional primary and secondary prompts (strings)
15*/
16
17#include "Python.h"
18#include "compile.h"
19#include "frameobject.h"
20#include "eval.h"
21
22#include "osdefs.h"
23
24#ifdef MS_WINDOWS
25#define WIN32_LEAN_AND_MEAN
26#include "windows.h"
27#endif /* MS_WINDOWS */
28
29#ifdef MS_COREDLL
30extern void *PyWin_DLLhModule;
31/* A string loaded from the DLL at startup: */
32extern const char *PyWin_DLLVersionString;
33#endif
34
35#ifdef __VMS
36#include <unixlib.h>
37#endif
38
39#ifdef MS_WINDOWS
40#include <windows.h>
41#endif
42
43#ifdef HAVE_LANGINFO_H
44#include <locale.h>
45#include <langinfo.h>
46#endif
47
48PyObject *
49PySys_GetObject(char *name)
50{
51	PyThreadState *tstate = PyThreadState_GET();
52	PyObject *sd = tstate->interp->sysdict;
53	if (sd == NULL)
54		return NULL;
55	return PyDict_GetItemString(sd, name);
56}
57
58FILE *
59PySys_GetFile(char *name, FILE *def)
60{
61	FILE *fp = NULL;
62	PyObject *v = PySys_GetObject(name);
63	if (v != NULL && PyFile_Check(v))
64		fp = PyFile_AsFile(v);
65	if (fp == NULL)
66		fp = def;
67	return fp;
68}
69
70int
71PySys_SetObject(char *name, PyObject *v)
72{
73	PyThreadState *tstate = PyThreadState_GET();
74	PyObject *sd = tstate->interp->sysdict;
75	if (v == NULL) {
76		if (PyDict_GetItemString(sd, name) == NULL)
77			return 0;
78		else
79			return PyDict_DelItemString(sd, name);
80	}
81	else
82		return PyDict_SetItemString(sd, name, v);
83}
84
85static PyObject *
86sys_displayhook(PyObject *self, PyObject *o)
87{
88	PyObject *outf;
89	PyInterpreterState *interp = PyThreadState_GET()->interp;
90	PyObject *modules = interp->modules;
91	PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
92
93	if (builtins == NULL) {
94		PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
95		return NULL;
96	}
97
98	/* Print value except if None */
99	/* After printing, also assign to '_' */
100	/* Before, set '_' to None to avoid recursion */
101	if (o == Py_None) {
102		Py_INCREF(Py_None);
103		return Py_None;
104	}
105	if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
106		return NULL;
107	if (Py_FlushLine() != 0)
108		return NULL;
109	outf = PySys_GetObject("stdout");
110	if (outf == NULL) {
111		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
112		return NULL;
113	}
114	if (PyFile_WriteObject(o, outf, 0) != 0)
115		return NULL;
116	PyFile_SoftSpace(outf, 1);
117	if (Py_FlushLine() != 0)
118		return NULL;
119	if (PyObject_SetAttrString(builtins, "_", o) != 0)
120		return NULL;
121	Py_INCREF(Py_None);
122	return Py_None;
123}
124
125PyDoc_STRVAR(displayhook_doc,
126"displayhook(object) -> None\n"
127"\n"
128"Print an object to sys.stdout and also save it in __builtin__._\n"
129);
130
131static PyObject *
132sys_excepthook(PyObject* self, PyObject* args)
133{
134	PyObject *exc, *value, *tb;
135	if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
136		return NULL;
137	PyErr_Display(exc, value, tb);
138	Py_INCREF(Py_None);
139	return Py_None;
140}
141
142PyDoc_STRVAR(excepthook_doc,
143"excepthook(exctype, value, traceback) -> None\n"
144"\n"
145"Handle an exception by displaying it with a traceback on sys.stderr.\n"
146);
147
148static PyObject *
149sys_exc_info(PyObject *self, PyObject *noargs)
150{
151	PyThreadState *tstate;
152	tstate = PyThreadState_GET();
153	return Py_BuildValue(
154		"(OOO)",
155		tstate->exc_type != NULL ? tstate->exc_type : Py_None,
156		tstate->exc_value != NULL ? tstate->exc_value : Py_None,
157		tstate->exc_traceback != NULL ?
158			tstate->exc_traceback : Py_None);
159}
160
161PyDoc_STRVAR(exc_info_doc,
162"exc_info() -> (type, value, traceback)\n\
163\n\
164Return information about the most recent exception caught by an except\n\
165clause in the current stack frame or in an older stack frame."
166);
167
168static PyObject *
169sys_exc_clear(PyObject *self, PyObject *noargs)
170{
171	PyThreadState *tstate = PyThreadState_GET();
172	PyObject *tmp_type, *tmp_value, *tmp_tb;
173	tmp_type = tstate->exc_type;
174	tmp_value = tstate->exc_value;
175	tmp_tb = tstate->exc_traceback;
176	tstate->exc_type = NULL;
177	tstate->exc_value = NULL;
178	tstate->exc_traceback = NULL;
179	Py_XDECREF(tmp_type);
180	Py_XDECREF(tmp_value);
181	Py_XDECREF(tmp_tb);
182	/* For b/w compatibility */
183	PySys_SetObject("exc_type", Py_None);
184	PySys_SetObject("exc_value", Py_None);
185	PySys_SetObject("exc_traceback", Py_None);
186	Py_INCREF(Py_None);
187	return Py_None;
188}
189
190PyDoc_STRVAR(exc_clear_doc,
191"exc_clear() -> None\n\
192\n\
193Clear global information on the current exception.  Subsequent calls to\n\
194exc_info() will return (None,None,None) until another exception is raised\n\
195in the current thread or the execution stack returns to a frame where\n\
196another exception is being handled."
197);
198
199static PyObject *
200sys_exit(PyObject *self, PyObject *args)
201{
202	PyObject *exit_code = 0;
203	if (!PyArg_ParseTuple(args, "|O:exit", &exit_code))
204		return NULL;
205	/* Raise SystemExit so callers may catch it or clean up. */
206	PyErr_SetObject(PyExc_SystemExit, exit_code);
207	return NULL;
208}
209
210PyDoc_STRVAR(exit_doc,
211"exit([status])\n\
212\n\
213Exit the interpreter by raising SystemExit(status).\n\
214If the status is omitted or None, it defaults to zero (i.e., success).\n\
215If the status is numeric, it will be used as the system exit status.\n\
216If it is another kind of object, it will be printed and the system\n\
217exit status will be one (i.e., failure)."
218);
219
220#ifdef Py_USING_UNICODE
221
222static PyObject *
223sys_getdefaultencoding(PyObject *self)
224{
225	return PyString_FromString(PyUnicode_GetDefaultEncoding());
226}
227
228PyDoc_STRVAR(getdefaultencoding_doc,
229"getdefaultencoding() -> string\n\
230\n\
231Return the current default string encoding used by the Unicode \n\
232implementation."
233);
234
235static PyObject *
236sys_setdefaultencoding(PyObject *self, PyObject *args)
237{
238	char *encoding;
239	if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
240		return NULL;
241	if (PyUnicode_SetDefaultEncoding(encoding))
242	    	return NULL;
243	Py_INCREF(Py_None);
244	return Py_None;
245}
246
247PyDoc_STRVAR(setdefaultencoding_doc,
248"setdefaultencoding(encoding)\n\
249\n\
250Set the current default string encoding used by the Unicode implementation."
251);
252
253static PyObject *
254sys_getfilesystemencoding(PyObject *self)
255{
256	if (Py_FileSystemDefaultEncoding)
257		return PyString_FromString(Py_FileSystemDefaultEncoding);
258	Py_INCREF(Py_None);
259	return Py_None;
260}
261
262PyDoc_STRVAR(getfilesystemencoding_doc,
263"getfilesystemencoding() -> string\n\
264\n\
265Return the encoding used to convert Unicode filenames in\n\
266operating system filenames."
267);
268
269#endif
270
271/*
272 * Cached interned string objects used for calling the profile and
273 * trace functions.  Initialized by trace_init().
274 */
275static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
276
277static int
278trace_init(void)
279{
280	static char *whatnames[7] = {"call", "exception", "line", "return",
281					"c_call", "c_exception", "c_return"};
282	PyObject *name;
283	int i;
284	for (i = 0; i < 7; ++i) {
285		if (whatstrings[i] == NULL) {
286			name = PyString_InternFromString(whatnames[i]);
287			if (name == NULL)
288				return -1;
289			whatstrings[i] = name;
290                }
291	}
292	return 0;
293}
294
295
296static PyObject *
297call_trampoline(PyThreadState *tstate, PyObject* callback,
298		PyFrameObject *frame, int what, PyObject *arg)
299{
300	PyObject *args = PyTuple_New(3);
301	PyObject *whatstr;
302	PyObject *result;
303
304	if (args == NULL)
305		return NULL;
306	Py_INCREF(frame);
307	whatstr = whatstrings[what];
308	Py_INCREF(whatstr);
309	if (arg == NULL)
310		arg = Py_None;
311	Py_INCREF(arg);
312	PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
313	PyTuple_SET_ITEM(args, 1, whatstr);
314	PyTuple_SET_ITEM(args, 2, arg);
315
316	/* call the Python-level function */
317	PyFrame_FastToLocals(frame);
318	result = PyEval_CallObject(callback, args);
319	PyFrame_LocalsToFast(frame, 1);
320	if (result == NULL)
321		PyTraceBack_Here(frame);
322
323	/* cleanup */
324	Py_DECREF(args);
325	return result;
326}
327
328static int
329profile_trampoline(PyObject *self, PyFrameObject *frame,
330		   int what, PyObject *arg)
331{
332	PyThreadState *tstate = frame->f_tstate;
333	PyObject *result;
334
335	if (arg == NULL)
336		arg = Py_None;
337	result = call_trampoline(tstate, self, frame, what, arg);
338	if (result == NULL) {
339		PyEval_SetProfile(NULL, NULL);
340		return -1;
341	}
342	Py_DECREF(result);
343	return 0;
344}
345
346static int
347trace_trampoline(PyObject *self, PyFrameObject *frame,
348		 int what, PyObject *arg)
349{
350	PyThreadState *tstate = frame->f_tstate;
351	PyObject *callback;
352	PyObject *result;
353
354	if (what == PyTrace_CALL)
355		callback = self;
356	else
357		callback = frame->f_trace;
358	if (callback == NULL)
359		return 0;
360	result = call_trampoline(tstate, callback, frame, what, arg);
361	if (result == NULL) {
362		PyEval_SetTrace(NULL, NULL);
363		Py_XDECREF(frame->f_trace);
364		frame->f_trace = NULL;
365		return -1;
366	}
367	if (result != Py_None) {
368		PyObject *temp = frame->f_trace;
369		frame->f_trace = NULL;
370		Py_XDECREF(temp);
371		frame->f_trace = result;
372	}
373	else {
374		Py_DECREF(result);
375	}
376	return 0;
377}
378
379static PyObject *
380sys_settrace(PyObject *self, PyObject *args)
381{
382	if (trace_init() == -1)
383		return NULL;
384	if (args == Py_None)
385		PyEval_SetTrace(NULL, NULL);
386	else
387		PyEval_SetTrace(trace_trampoline, args);
388	Py_INCREF(Py_None);
389	return Py_None;
390}
391
392PyDoc_STRVAR(settrace_doc,
393"settrace(function)\n\
394\n\
395Set the global debug tracing function.  It will be called on each\n\
396function call.  See the debugger chapter in the library manual."
397);
398
399static PyObject *
400sys_setprofile(PyObject *self, PyObject *args)
401{
402	if (trace_init() == -1)
403		return NULL;
404	if (args == Py_None)
405		PyEval_SetProfile(NULL, NULL);
406	else
407		PyEval_SetProfile(profile_trampoline, args);
408	Py_INCREF(Py_None);
409	return Py_None;
410}
411
412PyDoc_STRVAR(setprofile_doc,
413"setprofile(function)\n\
414\n\
415Set the profiling function.  It will be called on each function call\n\
416and return.  See the profiler chapter in the library manual."
417);
418
419static PyObject *
420sys_setcheckinterval(PyObject *self, PyObject *args)
421{
422	if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
423		return NULL;
424	Py_INCREF(Py_None);
425	return Py_None;
426}
427
428PyDoc_STRVAR(setcheckinterval_doc,
429"setcheckinterval(n)\n\
430\n\
431Tell the Python interpreter to check for asynchronous events every\n\
432n instructions.  This also affects how often thread switches occur."
433);
434
435static PyObject *
436sys_getcheckinterval(PyObject *self, PyObject *args)
437{
438	return PyInt_FromLong(_Py_CheckInterval);
439}
440
441PyDoc_STRVAR(getcheckinterval_doc,
442"getcheckinterval() -> current check interval; see setcheckinterval()."
443);
444
445#ifdef WITH_TSC
446static PyObject *
447sys_settscdump(PyObject *self, PyObject *args)
448{
449	int bool;
450	PyThreadState *tstate = PyThreadState_Get();
451
452	if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
453		return NULL;
454	if (bool)
455		tstate->interp->tscdump = 1;
456	else
457		tstate->interp->tscdump = 0;
458	Py_INCREF(Py_None);
459	return Py_None;
460
461}
462
463PyDoc_STRVAR(settscdump_doc,
464"settscdump(bool)\n\
465\n\
466If true, tell the Python interpreter to dump VM measurements to\n\
467stderr.  If false, turn off dump.  The measurements are based on the\n\
468Pentium time-stamp counter."
469);
470#endif /* TSC */
471
472static PyObject *
473sys_setrecursionlimit(PyObject *self, PyObject *args)
474{
475	int new_limit;
476	if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
477		return NULL;
478	if (new_limit <= 0) {
479		PyErr_SetString(PyExc_ValueError,
480				"recursion limit must be positive");
481		return NULL;
482	}
483	Py_SetRecursionLimit(new_limit);
484	Py_INCREF(Py_None);
485	return Py_None;
486}
487
488PyDoc_STRVAR(setrecursionlimit_doc,
489"setrecursionlimit(n)\n\
490\n\
491Set the maximum depth of the Python interpreter stack to n.  This\n\
492limit prevents infinite recursion from causing an overflow of the C\n\
493stack and crashing Python.  The highest possible limit is platform-\n\
494dependent."
495);
496
497static PyObject *
498sys_getrecursionlimit(PyObject *self)
499{
500	return PyInt_FromLong(Py_GetRecursionLimit());
501}
502
503PyDoc_STRVAR(getrecursionlimit_doc,
504"getrecursionlimit()\n\
505\n\
506Return the current value of the recursion limit, the maximum depth\n\
507of the Python interpreter stack.  This limit prevents infinite\n\
508recursion from causing an overflow of the C stack and crashing Python."
509);
510
511#ifdef MS_WINDOWS
512PyDoc_STRVAR(getwindowsversion_doc,
513"getwindowsversion()\n\
514\n\
515Return information about the running version of Windows.\n\
516The result is a tuple of (major, minor, build, platform, text)\n\
517All elements are numbers, except text which is a string.\n\
518Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
519"
520);
521
522static PyObject *
523sys_getwindowsversion(PyObject *self)
524{
525	OSVERSIONINFO ver;
526	ver.dwOSVersionInfoSize = sizeof(ver);
527	if (!GetVersionEx(&ver))
528		return PyErr_SetFromWindowsErr(0);
529	return Py_BuildValue("HHHHs",
530	                     ver.dwMajorVersion,
531	                     ver.dwMinorVersion,
532	                     ver.dwBuildNumber,
533	                     ver.dwPlatformId,
534	                     ver.szCSDVersion);
535}
536
537#endif /* MS_WINDOWS */
538
539#ifdef HAVE_DLOPEN
540static PyObject *
541sys_setdlopenflags(PyObject *self, PyObject *args)
542{
543	int new_val;
544        PyThreadState *tstate = PyThreadState_GET();
545	if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
546		return NULL;
547        if (!tstate)
548		return NULL;
549        tstate->interp->dlopenflags = new_val;
550	Py_INCREF(Py_None);
551	return Py_None;
552}
553
554PyDoc_STRVAR(setdlopenflags_doc,
555"setdlopenflags(n) -> None\n\
556\n\
557Set the flags that will be used for dlopen() calls. Among other\n\
558things, this will enable a lazy resolving of symbols when importing\n\
559a module, if called as sys.setdlopenflags(0)\n\
560To share symbols across extension modules, call as\n\
561sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
562);
563
564static PyObject *
565sys_getdlopenflags(PyObject *self, PyObject *args)
566{
567        PyThreadState *tstate = PyThreadState_GET();
568        if (!tstate)
569		return NULL;
570        return PyInt_FromLong(tstate->interp->dlopenflags);
571}
572
573PyDoc_STRVAR(getdlopenflags_doc,
574"getdlopenflags() -> int\n\
575\n\
576Return the current value of the flags that are used for dlopen()\n\
577calls. The flag constants are defined in the dl module."
578);
579#endif
580
581#ifdef USE_MALLOPT
582/* Link with -lmalloc (or -lmpc) on an SGI */
583#include <malloc.h>
584
585static PyObject *
586sys_mdebug(PyObject *self, PyObject *args)
587{
588	int flag;
589	if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
590		return NULL;
591	mallopt(M_DEBUG, flag);
592	Py_INCREF(Py_None);
593	return Py_None;
594}
595#endif /* USE_MALLOPT */
596
597static PyObject *
598sys_getrefcount(PyObject *self, PyObject *arg)
599{
600	return PyInt_FromLong(arg->ob_refcnt);
601}
602
603#ifdef Py_REF_DEBUG
604static PyObject *
605sys_gettotalrefcount(PyObject *self)
606{
607	return PyInt_FromLong(_Py_RefTotal);
608}
609
610#endif /* Py_TRACE_REFS */
611
612PyDoc_STRVAR(getrefcount_doc,
613"getrefcount(object) -> integer\n\
614\n\
615Return the reference count of object.  The count returned is generally\n\
616one higher than you might expect, because it includes the (temporary)\n\
617reference as an argument to getrefcount()."
618);
619
620#ifdef COUNT_ALLOCS
621static PyObject *
622sys_getcounts(PyObject *self)
623{
624	extern PyObject *get_counts(void);
625
626	return get_counts();
627}
628#endif
629
630PyDoc_STRVAR(getframe_doc,
631"_getframe([depth]) -> frameobject\n\
632\n\
633Return a frame object from the call stack.  If optional integer depth is\n\
634given, return the frame object that many calls below the top of the stack.\n\
635If that is deeper than the call stack, ValueError is raised.  The default\n\
636for depth is zero, returning the frame at the top of the call stack.\n\
637\n\
638This function should be used for internal and specialized\n\
639purposes only."
640);
641
642static PyObject *
643sys_getframe(PyObject *self, PyObject *args)
644{
645	PyFrameObject *f = PyThreadState_GET()->frame;
646	int depth = -1;
647
648	if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
649		return NULL;
650
651	while (depth > 0 && f != NULL) {
652		f = f->f_back;
653		--depth;
654	}
655	if (f == NULL) {
656		PyErr_SetString(PyExc_ValueError,
657				"call stack is not deep enough");
658		return NULL;
659	}
660	Py_INCREF(f);
661	return (PyObject*)f;
662}
663
664PyDoc_STRVAR(call_tracing_doc,
665"call_tracing(func, args) -> object\n\
666\n\
667Call func(*args), while tracing is enabled.  The tracing state is\n\
668saved, and restored afterwards.  This is intended to be called from\n\
669a debugger from a checkpoint, to recursively debug some other code."
670);
671
672static PyObject *
673sys_call_tracing(PyObject *self, PyObject *args)
674{
675	PyObject *func, *funcargs;
676	if (!PyArg_ParseTuple(args, "OO:call_tracing", &func, &funcargs))
677		return NULL;
678	return _PyEval_CallTracing(func, funcargs);
679}
680
681PyDoc_STRVAR(callstats_doc,
682"callstats() -> tuple of integers\n\
683\n\
684Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
685when Python was built.  Otherwise, return None.\n\
686\n\
687When enabled, this function returns detailed, implementation-specific\n\
688details about the number of function calls executed. The return value is\n\
689a 11-tuple where the entries in the tuple are counts of:\n\
6900. all function calls\n\
6911. calls to PyFunction_Type objects\n\
6922. PyFunction calls that do not create an argument tuple\n\
6933. PyFunction calls that do not create an argument tuple\n\
694   and bypass PyEval_EvalCodeEx()\n\
6954. PyMethod calls\n\
6965. PyMethod calls on bound methods\n\
6976. PyType calls\n\
6987. PyCFunction calls\n\
6998. generator calls\n\
7009. All other calls\n\
70110. Number of stack pops performed by call_function()"
702);
703
704#ifdef Py_TRACE_REFS
705/* Defined in objects.c because it uses static globals if that file */
706extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
707#endif
708
709#ifdef DYNAMIC_EXECUTION_PROFILE
710/* Defined in ceval.c because it uses static globals if that file */
711extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
712#endif
713
714static PyMethodDef sys_methods[] = {
715	/* Might as well keep this in alphabetic order */
716	{"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
717	 callstats_doc},
718	{"displayhook",	sys_displayhook, METH_O, displayhook_doc},
719	{"exc_info",	sys_exc_info, METH_NOARGS, exc_info_doc},
720	{"exc_clear",	sys_exc_clear, METH_NOARGS, exc_clear_doc},
721	{"excepthook",	sys_excepthook, METH_VARARGS, excepthook_doc},
722	{"exit",	sys_exit, METH_VARARGS, exit_doc},
723#ifdef Py_USING_UNICODE
724	{"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
725	 METH_NOARGS, getdefaultencoding_doc},
726#endif
727#ifdef HAVE_DLOPEN
728	{"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
729	 getdlopenflags_doc},
730#endif
731#ifdef COUNT_ALLOCS
732	{"getcounts",	(PyCFunction)sys_getcounts, METH_NOARGS},
733#endif
734#ifdef DYNAMIC_EXECUTION_PROFILE
735	{"getdxp",	_Py_GetDXProfile, METH_VARARGS},
736#endif
737#ifdef Py_USING_UNICODE
738	{"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
739	 METH_NOARGS, getfilesystemencoding_doc},
740#endif
741#ifdef Py_TRACE_REFS
742	{"getobjects",	_Py_GetObjects, METH_VARARGS},
743#endif
744#ifdef Py_REF_DEBUG
745	{"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
746#endif
747	{"getrefcount",	(PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
748	{"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
749	 getrecursionlimit_doc},
750	{"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
751#ifdef MS_WINDOWS
752	{"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
753	 getwindowsversion_doc},
754#endif /* MS_WINDOWS */
755#ifdef USE_MALLOPT
756	{"mdebug",	sys_mdebug, METH_VARARGS},
757#endif
758#ifdef Py_USING_UNICODE
759	{"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
760	 setdefaultencoding_doc},
761#endif
762	{"setcheckinterval",	sys_setcheckinterval, METH_VARARGS,
763	 setcheckinterval_doc},
764	{"getcheckinterval",	sys_getcheckinterval, METH_NOARGS,
765	 getcheckinterval_doc},
766#ifdef HAVE_DLOPEN
767	{"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
768	 setdlopenflags_doc},
769#endif
770	{"setprofile",	sys_setprofile, METH_O, setprofile_doc},
771	{"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
772	 setrecursionlimit_doc},
773#ifdef WITH_TSC
774	{"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
775#endif
776	{"settrace",	sys_settrace, METH_O, settrace_doc},
777	{"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
778	{NULL,		NULL}		/* sentinel */
779};
780
781static PyObject *
782list_builtin_module_names(void)
783{
784	PyObject *list = PyList_New(0);
785	int i;
786	if (list == NULL)
787		return NULL;
788	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
789		PyObject *name = PyString_FromString(
790			PyImport_Inittab[i].name);
791		if (name == NULL)
792			break;
793		PyList_Append(list, name);
794		Py_DECREF(name);
795	}
796	if (PyList_Sort(list) != 0) {
797		Py_DECREF(list);
798		list = NULL;
799	}
800	if (list) {
801		PyObject *v = PyList_AsTuple(list);
802		Py_DECREF(list);
803		list = v;
804	}
805	return list;
806}
807
808static PyObject *warnoptions = NULL;
809
810void
811PySys_ResetWarnOptions(void)
812{
813	if (warnoptions == NULL || !PyList_Check(warnoptions))
814		return;
815	PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
816}
817
818void
819PySys_AddWarnOption(char *s)
820{
821	PyObject *str;
822
823	if (warnoptions == NULL || !PyList_Check(warnoptions)) {
824		Py_XDECREF(warnoptions);
825		warnoptions = PyList_New(0);
826		if (warnoptions == NULL)
827			return;
828	}
829	str = PyString_FromString(s);
830	if (str != NULL) {
831		PyList_Append(warnoptions, str);
832		Py_DECREF(str);
833	}
834}
835
836/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
837   Two literals concatenated works just fine.  If you have a K&R compiler
838   or other abomination that however *does* understand longer strings,
839   get rid of the !!! comment in the middle and the quotes that surround it. */
840PyDoc_VAR(sys_doc) =
841PyDoc_STR(
842"This module provides access to some objects used or maintained by the\n\
843interpreter and to functions that interact strongly with the interpreter.\n\
844\n\
845Dynamic objects:\n\
846\n\
847argv -- command line arguments; argv[0] is the script pathname if known\n\
848path -- module search path; path[0] is the script directory, else ''\n\
849modules -- dictionary of loaded modules\n\
850\n\
851displayhook -- called to show results in an interactive session\n\
852excepthook -- called to handle any uncaught exception other than SystemExit\n\
853  To customize printing in an interactive session or to install a custom\n\
854  top-level exception handler, assign other functions to replace these.\n\
855\n\
856exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
857  Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
858\n\
859stdin -- standard input file object; used by raw_input() and input()\n\
860stdout -- standard output file object; used by the print statement\n\
861stderr -- standard error object; used for error messages\n\
862  By assigning other file objects (or objects that behave like files)\n\
863  to these, it is possible to redirect all of the interpreter's I/O.\n\
864\n\
865last_type -- type of last uncaught exception\n\
866last_value -- value of last uncaught exception\n\
867last_traceback -- traceback of last uncaught exception\n\
868  These three are only available in an interactive session after a\n\
869  traceback has been printed.\n\
870\n\
871exc_type -- type of exception currently being handled\n\
872exc_value -- value of exception currently being handled\n\
873exc_traceback -- traceback of exception currently being handled\n\
874  The function exc_info() should be used instead of these three,\n\
875  because it is thread-safe.\n\
876"
877)
878/* concatenating string here */
879PyDoc_STR(
880"\n\
881Static objects:\n\
882\n\
883maxint -- the largest supported integer (the smallest is -maxint-1)\n\
884maxunicode -- the largest supported character\n\
885builtin_module_names -- tuple of module names built into this interpreter\n\
886version -- the version of this interpreter as a string\n\
887version_info -- version information as a tuple\n\
888hexversion -- version information encoded as a single integer\n\
889copyright -- copyright notice pertaining to this interpreter\n\
890platform -- platform identifier\n\
891executable -- pathname of this Python interpreter\n\
892prefix -- prefix used to find the Python library\n\
893exec_prefix -- prefix used to find the machine-specific Python library\n\
894"
895)
896#ifdef MS_WINDOWS
897/* concatenating string here */
898PyDoc_STR(
899"dllhandle -- [Windows only] integer handle of the Python DLL\n\
900winver -- [Windows only] version number of the Python DLL\n\
901"
902)
903#endif /* MS_WINDOWS */
904PyDoc_STR(
905"__stdin__ -- the original stdin; don't touch!\n\
906__stdout__ -- the original stdout; don't touch!\n\
907__stderr__ -- the original stderr; don't touch!\n\
908__displayhook__ -- the original displayhook; don't touch!\n\
909__excepthook__ -- the original excepthook; don't touch!\n\
910\n\
911Functions:\n\
912\n\
913displayhook() -- print an object to the screen, and save it in __builtin__._\n\
914excepthook() -- print an exception and its traceback to sys.stderr\n\
915exc_info() -- return thread-safe information about the current exception\n\
916exc_clear() -- clear the exception state for the current thread\n\
917exit() -- exit the interpreter by raising SystemExit\n\
918getdlopenflags() -- returns flags to be used for dlopen() calls\n\
919getrefcount() -- return the reference count for an object (plus one :-)\n\
920getrecursionlimit() -- return the max recursion depth for the interpreter\n\
921setcheckinterval() -- control how often the interpreter checks for events\n\
922setdlopenflags() -- set the flags to be used for dlopen() calls\n\
923setprofile() -- set the global profiling function\n\
924setrecursionlimit() -- set the max recursion depth for the interpreter\n\
925settrace() -- set the global debug tracing function\n\
926"
927)
928/* end of sys_doc */ ;
929
930PyObject *
931_PySys_Init(void)
932{
933	PyObject *m, *v, *sysdict;
934	PyObject *sysin, *sysout, *syserr;
935	char *s;
936#ifdef MS_WINDOWS
937	char buf[10];
938#endif
939
940	m = Py_InitModule3("sys", sys_methods, sys_doc);
941	sysdict = PyModule_GetDict(m);
942
943	sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
944	sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
945	syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
946	if (PyErr_Occurred())
947		return NULL;
948#ifdef MS_WINDOWS
949	if(isatty(_fileno(stdin))){
950		sprintf(buf, "cp%d", GetConsoleCP());
951		if (!PyFile_SetEncoding(sysin, buf))
952			return NULL;
953	}
954	if(isatty(_fileno(stdout))) {
955		sprintf(buf, "cp%d", GetConsoleOutputCP());
956		if (!PyFile_SetEncoding(sysout, buf))
957			return NULL;
958	}
959#endif
960
961	PyDict_SetItemString(sysdict, "stdin", sysin);
962	PyDict_SetItemString(sysdict, "stdout", sysout);
963	PyDict_SetItemString(sysdict, "stderr", syserr);
964	/* Make backup copies for cleanup */
965	PyDict_SetItemString(sysdict, "__stdin__", sysin);
966	PyDict_SetItemString(sysdict, "__stdout__", sysout);
967	PyDict_SetItemString(sysdict, "__stderr__", syserr);
968	PyDict_SetItemString(sysdict, "__displayhook__",
969                             PyDict_GetItemString(sysdict, "displayhook"));
970	PyDict_SetItemString(sysdict, "__excepthook__",
971                             PyDict_GetItemString(sysdict, "excepthook"));
972	Py_XDECREF(sysin);
973	Py_XDECREF(sysout);
974	Py_XDECREF(syserr);
975	PyDict_SetItemString(sysdict, "version",
976			     v = PyString_FromString(Py_GetVersion()));
977	Py_XDECREF(v);
978	PyDict_SetItemString(sysdict, "hexversion",
979			     v = PyInt_FromLong(PY_VERSION_HEX));
980	Py_XDECREF(v);
981	/*
982	 * These release level checks are mutually exclusive and cover
983	 * the field, so don't get too fancy with the pre-processor!
984	 */
985#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
986	s = "alpha";
987#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
988	s = "beta";
989#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
990	s = "candidate";
991#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
992	s = "final";
993#endif
994	PyDict_SetItemString(sysdict, "version_info",
995			     v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
996					       PY_MINOR_VERSION,
997					       PY_MICRO_VERSION, s,
998					       PY_RELEASE_SERIAL));
999	Py_XDECREF(v);
1000	PyDict_SetItemString(sysdict, "api_version",
1001			     v = PyInt_FromLong(PYTHON_API_VERSION));
1002	Py_XDECREF(v);
1003	PyDict_SetItemString(sysdict, "copyright",
1004			     v = PyString_FromString(Py_GetCopyright()));
1005	Py_XDECREF(v);
1006	PyDict_SetItemString(sysdict, "platform",
1007			     v = PyString_FromString(Py_GetPlatform()));
1008	Py_XDECREF(v);
1009	PyDict_SetItemString(sysdict, "executable",
1010			     v = PyString_FromString(Py_GetProgramFullPath()));
1011	Py_XDECREF(v);
1012	PyDict_SetItemString(sysdict, "prefix",
1013			     v = PyString_FromString(Py_GetPrefix()));
1014	Py_XDECREF(v);
1015	PyDict_SetItemString(sysdict, "exec_prefix",
1016		   v = PyString_FromString(Py_GetExecPrefix()));
1017	Py_XDECREF(v);
1018	PyDict_SetItemString(sysdict, "maxint",
1019			     v = PyInt_FromLong(PyInt_GetMax()));
1020	Py_XDECREF(v);
1021#ifdef Py_USING_UNICODE
1022	PyDict_SetItemString(sysdict, "maxunicode",
1023			     v = PyInt_FromLong(PyUnicode_GetMax()));
1024	Py_XDECREF(v);
1025#endif
1026	PyDict_SetItemString(sysdict, "builtin_module_names",
1027		   v = list_builtin_module_names());
1028	Py_XDECREF(v);
1029	{
1030		/* Assumes that longs are at least 2 bytes long.
1031		   Should be safe! */
1032		unsigned long number = 1;
1033		char *value;
1034
1035		s = (char *) &number;
1036		if (s[0] == 0)
1037			value = "big";
1038		else
1039			value = "little";
1040		PyDict_SetItemString(sysdict, "byteorder",
1041				     v = PyString_FromString(value));
1042		Py_XDECREF(v);
1043	}
1044#ifdef MS_COREDLL
1045	PyDict_SetItemString(sysdict, "dllhandle",
1046			     v = PyLong_FromVoidPtr(PyWin_DLLhModule));
1047	Py_XDECREF(v);
1048	PyDict_SetItemString(sysdict, "winver",
1049			     v = PyString_FromString(PyWin_DLLVersionString));
1050	Py_XDECREF(v);
1051#endif
1052	if (warnoptions == NULL) {
1053		warnoptions = PyList_New(0);
1054	}
1055	else {
1056		Py_INCREF(warnoptions);
1057	}
1058	if (warnoptions != NULL) {
1059		PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1060	}
1061
1062	if (PyErr_Occurred())
1063		return NULL;
1064	return m;
1065}
1066
1067static PyObject *
1068makepathobject(char *path, int delim)
1069{
1070	int i, n;
1071	char *p;
1072	PyObject *v, *w;
1073
1074	n = 1;
1075	p = path;
1076	while ((p = strchr(p, delim)) != NULL) {
1077		n++;
1078		p++;
1079	}
1080	v = PyList_New(n);
1081	if (v == NULL)
1082		return NULL;
1083	for (i = 0; ; i++) {
1084		p = strchr(path, delim);
1085		if (p == NULL)
1086			p = strchr(path, '\0'); /* End of string */
1087		w = PyString_FromStringAndSize(path, (int) (p - path));
1088		if (w == NULL) {
1089			Py_DECREF(v);
1090			return NULL;
1091		}
1092		PyList_SetItem(v, i, w);
1093		if (*p == '\0')
1094			break;
1095		path = p+1;
1096	}
1097	return v;
1098}
1099
1100void
1101PySys_SetPath(char *path)
1102{
1103	PyObject *v;
1104	if ((v = makepathobject(path, DELIM)) == NULL)
1105		Py_FatalError("can't create sys.path");
1106	if (PySys_SetObject("path", v) != 0)
1107		Py_FatalError("can't assign sys.path");
1108	Py_DECREF(v);
1109}
1110
1111static PyObject *
1112makeargvobject(int argc, char **argv)
1113{
1114	PyObject *av;
1115	if (argc <= 0 || argv == NULL) {
1116		/* Ensure at least one (empty) argument is seen */
1117		static char *empty_argv[1] = {""};
1118		argv = empty_argv;
1119		argc = 1;
1120	}
1121	av = PyList_New(argc);
1122	if (av != NULL) {
1123		int i;
1124		for (i = 0; i < argc; i++) {
1125#ifdef __VMS
1126			PyObject *v;
1127
1128			/* argv[0] is the script pathname if known */
1129			if (i == 0) {
1130				char* fn = decc$translate_vms(argv[0]);
1131				if ((fn == (char *)0) || fn == (char *)-1)
1132					v = PyString_FromString(argv[0]);
1133				else
1134					v = PyString_FromString(
1135						decc$translate_vms(argv[0]));
1136			} else
1137				v = PyString_FromString(argv[i]);
1138#else
1139			PyObject *v = PyString_FromString(argv[i]);
1140#endif
1141			if (v == NULL) {
1142				Py_DECREF(av);
1143				av = NULL;
1144				break;
1145			}
1146			PyList_SetItem(av, i, v);
1147		}
1148	}
1149	return av;
1150}
1151
1152void
1153PySys_SetArgv(int argc, char **argv)
1154{
1155#if defined(HAVE_REALPATH)
1156	char fullpath[MAXPATHLEN];
1157#elif defined(MS_WINDOWS)
1158	char fullpath[MAX_PATH];
1159#endif
1160	PyObject *av = makeargvobject(argc, argv);
1161	PyObject *path = PySys_GetObject("path");
1162	if (av == NULL)
1163		Py_FatalError("no mem for sys.argv");
1164	if (PySys_SetObject("argv", av) != 0)
1165		Py_FatalError("can't assign sys.argv");
1166	if (path != NULL) {
1167		char *argv0 = argv[0];
1168		char *p = NULL;
1169		int n = 0;
1170		PyObject *a;
1171#ifdef HAVE_READLINK
1172		char link[MAXPATHLEN+1];
1173		char argv0copy[2*MAXPATHLEN+1];
1174		int nr = 0;
1175		if (argc > 0 && argv0 != NULL)
1176			nr = readlink(argv0, link, MAXPATHLEN);
1177		if (nr > 0) {
1178			/* It's a symlink */
1179			link[nr] = '\0';
1180			if (link[0] == SEP)
1181				argv0 = link; /* Link to absolute path */
1182			else if (strchr(link, SEP) == NULL)
1183				; /* Link without path */
1184			else {
1185				/* Must join(dirname(argv0), link) */
1186				char *q = strrchr(argv0, SEP);
1187				if (q == NULL)
1188					argv0 = link; /* argv0 without path */
1189				else {
1190					/* Must make a copy */
1191					strcpy(argv0copy, argv0);
1192					q = strrchr(argv0copy, SEP);
1193					strcpy(q+1, link);
1194					argv0 = argv0copy;
1195				}
1196			}
1197		}
1198#endif /* HAVE_READLINK */
1199#if SEP == '\\' /* Special case for MS filename syntax */
1200		if (argc > 0 && argv0 != NULL) {
1201			char *q;
1202#ifdef MS_WINDOWS
1203			char *ptemp;
1204			if (GetFullPathName(argv0,
1205					   sizeof(fullpath),
1206					   fullpath,
1207					   &ptemp)) {
1208				argv0 = fullpath;
1209			}
1210#endif
1211			p = strrchr(argv0, SEP);
1212			/* Test for alternate separator */
1213			q = strrchr(p ? p : argv0, '/');
1214			if (q != NULL)
1215				p = q;
1216			if (p != NULL) {
1217				n = p + 1 - argv0;
1218				if (n > 1 && p[-1] != ':')
1219					n--; /* Drop trailing separator */
1220			}
1221		}
1222#else /* All other filename syntaxes */
1223		if (argc > 0 && argv0 != NULL) {
1224#if defined(HAVE_REALPATH)
1225			if (realpath(argv0, fullpath)) {
1226				argv0 = fullpath;
1227			}
1228#endif
1229			p = strrchr(argv0, SEP);
1230		}
1231		if (p != NULL) {
1232#ifndef RISCOS
1233			n = p + 1 - argv0;
1234#else /* don't include trailing separator */
1235			n = p - argv0;
1236#endif /* RISCOS */
1237#if SEP == '/' /* Special case for Unix filename syntax */
1238			if (n > 1)
1239				n--; /* Drop trailing separator */
1240#endif /* Unix */
1241		}
1242#endif /* All others */
1243		a = PyString_FromStringAndSize(argv0, n);
1244		if (a == NULL)
1245			Py_FatalError("no mem for sys.path insertion");
1246		if (PyList_Insert(path, 0, a) < 0)
1247			Py_FatalError("sys.path.insert(0) failed");
1248		Py_DECREF(a);
1249	}
1250	Py_DECREF(av);
1251}
1252
1253
1254/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1255   Adapted from code submitted by Just van Rossum.
1256
1257   PySys_WriteStdout(format, ...)
1258   PySys_WriteStderr(format, ...)
1259
1260      The first function writes to sys.stdout; the second to sys.stderr.  When
1261      there is a problem, they write to the real (C level) stdout or stderr;
1262      no exceptions are raised.
1263
1264      Both take a printf-style format string as their first argument followed
1265      by a variable length argument list determined by the format string.
1266
1267      *** WARNING ***
1268
1269      The format should limit the total size of the formatted output string to
1270      1000 bytes.  In particular, this means that no unrestricted "%s" formats
1271      should occur; these should be limited using "%.<N>s where <N> is a
1272      decimal number calculated so that <N> plus the maximum size of other
1273      formatted text does not exceed 1000 bytes.  Also watch out for "%f",
1274      which can print hundreds of digits for very large numbers.
1275
1276 */
1277
1278static void
1279mywrite(char *name, FILE *fp, const char *format, va_list va)
1280{
1281	PyObject *file;
1282	PyObject *error_type, *error_value, *error_traceback;
1283
1284	PyErr_Fetch(&error_type, &error_value, &error_traceback);
1285	file = PySys_GetObject(name);
1286	if (file == NULL || PyFile_AsFile(file) == fp)
1287		vfprintf(fp, format, va);
1288	else {
1289		char buffer[1001];
1290		const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
1291						   format, va);
1292		if (PyFile_WriteString(buffer, file) != 0) {
1293			PyErr_Clear();
1294			fputs(buffer, fp);
1295		}
1296		if (written < 0 || written >= sizeof(buffer)) {
1297			const char *truncated = "... truncated";
1298			if (PyFile_WriteString(truncated, file) != 0) {
1299				PyErr_Clear();
1300				fputs(truncated, fp);
1301			}
1302		}
1303	}
1304	PyErr_Restore(error_type, error_value, error_traceback);
1305}
1306
1307void
1308PySys_WriteStdout(const char *format, ...)
1309{
1310	va_list va;
1311
1312	va_start(va, format);
1313	mywrite("stdout", stdout, format, va);
1314	va_end(va);
1315}
1316
1317void
1318PySys_WriteStderr(const char *format, ...)
1319{
1320	va_list va;
1321
1322	va_start(va, format);
1323	mywrite("stderr", stderr, format, va);
1324	va_end(va);
1325}
1326