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