sysmodule.c revision 6238d2b024f061159b2613387ff700695c10deef
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
21#include "osdefs.h"
22
23#ifdef MS_COREDLL
24extern void *PyWin_DLLhModule;
25/* A string loaded from the DLL at startup: */
26extern const char *PyWin_DLLVersionString;
27#endif
28
29PyObject *
30PySys_GetObject(char *name)
31{
32	PyThreadState *tstate = PyThreadState_Get();
33	PyObject *sd = tstate->interp->sysdict;
34	if (sd == NULL)
35		return NULL;
36	return PyDict_GetItemString(sd, name);
37}
38
39FILE *
40PySys_GetFile(char *name, FILE *def)
41{
42	FILE *fp = NULL;
43	PyObject *v = PySys_GetObject(name);
44	if (v != NULL && PyFile_Check(v))
45		fp = PyFile_AsFile(v);
46	if (fp == NULL)
47		fp = def;
48	return fp;
49}
50
51int
52PySys_SetObject(char *name, PyObject *v)
53{
54	PyThreadState *tstate = PyThreadState_Get();
55	PyObject *sd = tstate->interp->sysdict;
56	if (v == NULL) {
57		if (PyDict_GetItemString(sd, name) == NULL)
58			return 0;
59		else
60			return PyDict_DelItemString(sd, name);
61	}
62	else
63		return PyDict_SetItemString(sd, name, v);
64}
65
66static PyObject *
67sys_displayhook(PyObject *self, PyObject *o)
68{
69	PyObject *outf;
70	PyInterpreterState *interp = PyThreadState_Get()->interp;
71	PyObject *modules = interp->modules;
72	PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
73
74	if (builtins == NULL) {
75		PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
76		return NULL;
77	}
78
79	/* Print value except if None */
80	/* After printing, also assign to '_' */
81	/* Before, set '_' to None to avoid recursion */
82	if (o == Py_None) {
83		Py_INCREF(Py_None);
84		return Py_None;
85	}
86	if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
87		return NULL;
88	if (Py_FlushLine() != 0)
89		return NULL;
90	outf = PySys_GetObject("stdout");
91	if (outf == NULL) {
92		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
93		return NULL;
94	}
95	if (PyFile_WriteObject(o, outf, 0) != 0)
96		return NULL;
97	PyFile_SoftSpace(outf, 1);
98	if (Py_FlushLine() != 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 __builtin__._\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)
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 exception that is currently being handled.\n\
146This should be called from inside an except clause only."
147);
148
149static PyObject *
150sys_exit(PyObject *self, PyObject *args)
151{
152	PyObject *exit_code = 0;
153	if (!PyArg_ParseTuple(args, "|O:exit", &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#ifdef Py_USING_UNICODE
171
172static PyObject *
173sys_getdefaultencoding(PyObject *self)
174{
175	return PyString_FromString(PyUnicode_GetDefaultEncoding());
176}
177
178PyDoc_STRVAR(getdefaultencoding_doc,
179"getdefaultencoding() -> string\n\
180\n\
181Return the current default string encoding used by the Unicode \n\
182implementation."
183);
184
185static PyObject *
186sys_setdefaultencoding(PyObject *self, PyObject *args)
187{
188	char *encoding;
189	if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
190		return NULL;
191	if (PyUnicode_SetDefaultEncoding(encoding))
192	    	return NULL;
193	Py_INCREF(Py_None);
194	return Py_None;
195}
196
197PyDoc_STRVAR(setdefaultencoding_doc,
198"setdefaultencoding(encoding)\n\
199\n\
200Set the current default string encoding used by the Unicode implementation."
201);
202
203#endif
204
205/*
206 * Cached interned string objects used for calling the profile and
207 * trace functions.  Initialized by trace_init().
208 */
209static PyObject *whatstrings[4] = {NULL, NULL, NULL, NULL};
210
211static int
212trace_init(void)
213{
214	static char *whatnames[4] = {"call", "exception", "line", "return"};
215	PyObject *name;
216	int i;
217	for (i = 0; i < 4; ++i) {
218		if (whatstrings[i] == NULL) {
219			name = PyString_InternFromString(whatnames[i]);
220			if (name == NULL)
221				return -1;
222			whatstrings[i] = name;
223                }
224	}
225	return 0;
226}
227
228
229static PyObject *
230call_trampoline(PyThreadState *tstate, PyObject* callback,
231		PyFrameObject *frame, int what, PyObject *arg)
232{
233	PyObject *args = PyTuple_New(3);
234	PyObject *whatstr;
235	PyObject *result;
236
237	if (args == NULL)
238		return NULL;
239	Py_INCREF(frame);
240	whatstr = whatstrings[what];
241	Py_INCREF(whatstr);
242	if (arg == NULL)
243		arg = Py_None;
244	Py_INCREF(arg);
245	PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
246	PyTuple_SET_ITEM(args, 1, whatstr);
247	PyTuple_SET_ITEM(args, 2, arg);
248
249	/* call the Python-level function */
250	PyFrame_FastToLocals(frame);
251	result = PyEval_CallObject(callback, args);
252	PyFrame_LocalsToFast(frame, 1);
253	if (result == NULL)
254		PyTraceBack_Here(frame);
255
256	/* cleanup */
257	Py_DECREF(args);
258	return result;
259}
260
261static int
262profile_trampoline(PyObject *self, PyFrameObject *frame,
263		   int what, PyObject *arg)
264{
265	PyThreadState *tstate = frame->f_tstate;
266	PyObject *result;
267
268	if (arg == NULL)
269		arg = Py_None;
270	result = call_trampoline(tstate, self, frame, what, arg);
271	if (result == NULL) {
272		PyEval_SetProfile(NULL, NULL);
273		return -1;
274	}
275	Py_DECREF(result);
276	return 0;
277}
278
279static int
280trace_trampoline(PyObject *self, PyFrameObject *frame,
281		 int what, PyObject *arg)
282{
283	PyThreadState *tstate = frame->f_tstate;
284	PyObject *callback;
285	PyObject *result;
286
287	if (what == PyTrace_CALL)
288		callback = self;
289	else
290		callback = frame->f_trace;
291	if (callback == NULL)
292		return 0;
293	result = call_trampoline(tstate, callback, frame, what, arg);
294	if (result == NULL) {
295		PyEval_SetTrace(NULL, NULL);
296		Py_XDECREF(frame->f_trace);
297		frame->f_trace = NULL;
298		return -1;
299	}
300	if (result != Py_None) {
301		PyObject *temp = frame->f_trace;
302		frame->f_trace = NULL;
303		Py_XDECREF(temp);
304		frame->f_trace = result;
305	}
306	else {
307		Py_DECREF(result);
308	}
309	return 0;
310}
311
312static PyObject *
313sys_settrace(PyObject *self, PyObject *args)
314{
315	if (trace_init() == -1)
316		return NULL;
317	if (args == Py_None)
318		PyEval_SetTrace(NULL, NULL);
319	else
320		PyEval_SetTrace(trace_trampoline, args);
321	Py_INCREF(Py_None);
322	return Py_None;
323}
324
325PyDoc_STRVAR(settrace_doc,
326"settrace(function)\n\
327\n\
328Set the global debug tracing function.  It will be called on each\n\
329function call.  See the debugger chapter in the library manual."
330);
331
332static PyObject *
333sys_setprofile(PyObject *self, PyObject *args)
334{
335	if (trace_init() == -1)
336		return NULL;
337	if (args == Py_None)
338		PyEval_SetProfile(NULL, NULL);
339	else
340		PyEval_SetProfile(profile_trampoline, args);
341	Py_INCREF(Py_None);
342	return Py_None;
343}
344
345PyDoc_STRVAR(setprofile_doc,
346"setprofile(function)\n\
347\n\
348Set the profiling function.  It will be called on each function call\n\
349and return.  See the profiler chapter in the library manual."
350);
351
352static PyObject *
353sys_setcheckinterval(PyObject *self, PyObject *args)
354{
355	PyThreadState *tstate = PyThreadState_Get();
356	if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval))
357		return NULL;
358	Py_INCREF(Py_None);
359	return Py_None;
360}
361
362PyDoc_STRVAR(setcheckinterval_doc,
363"setcheckinterval(n)\n\
364\n\
365Tell the Python interpreter to check for asynchronous events every\n\
366n instructions.  This also affects how often thread switches occur."
367);
368
369static PyObject *
370sys_setrecursionlimit(PyObject *self, PyObject *args)
371{
372	int new_limit;
373	if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
374		return NULL;
375	if (new_limit <= 0) {
376		PyErr_SetString(PyExc_ValueError,
377				"recursion limit must be positive");
378		return NULL;
379	}
380	Py_SetRecursionLimit(new_limit);
381	Py_INCREF(Py_None);
382	return Py_None;
383}
384
385PyDoc_STRVAR(setrecursionlimit_doc,
386"setrecursionlimit(n)\n\
387\n\
388Set the maximum depth of the Python interpreter stack to n.  This\n\
389limit prevents infinite recursion from causing an overflow of the C\n\
390stack and crashing Python.  The highest possible limit is platform-\n\
391dependent."
392);
393
394static PyObject *
395sys_getrecursionlimit(PyObject *self)
396{
397	return PyInt_FromLong(Py_GetRecursionLimit());
398}
399
400PyDoc_STRVAR(getrecursionlimit_doc,
401"getrecursionlimit()\n\
402\n\
403Return the current value of the recursion limit, the maximum depth\n\
404of the Python interpreter stack.  This limit prevents infinite\n\
405recursion from causing an overflow of the C stack and crashing Python."
406);
407
408#ifdef HAVE_DLOPEN
409static PyObject *
410sys_setdlopenflags(PyObject *self, PyObject *args)
411{
412	int new_val;
413        PyThreadState *tstate = PyThreadState_Get();
414	if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
415		return NULL;
416        if (!tstate)
417		return NULL;
418        tstate->interp->dlopenflags = new_val;
419	Py_INCREF(Py_None);
420	return Py_None;
421}
422
423PyDoc_STRVAR(setdlopenflags_doc,
424"setdlopenflags(n) -> None\n\
425\n\
426Set the flags that will be used for dlopen() calls. Among other\n\
427things, this will enable a lazy resolving of symbols when importing\n\
428a module, if called as sys.setdlopenflags(0)\n\
429To share symbols across extension modules, call as\n\
430sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
431);
432
433static PyObject *
434sys_getdlopenflags(PyObject *self, PyObject *args)
435{
436        PyThreadState *tstate = PyThreadState_Get();
437        if (!tstate)
438		return NULL;
439        return PyInt_FromLong(tstate->interp->dlopenflags);
440}
441
442PyDoc_STRVAR(getdlopenflags_doc,
443"getdlopenflags() -> int\n\
444\n\
445Return the current value of the flags that are used for dlopen()\n\
446calls. The flag constants are defined in the dl module."
447);
448#endif
449
450#ifdef USE_MALLOPT
451/* Link with -lmalloc (or -lmpc) on an SGI */
452#include <malloc.h>
453
454static PyObject *
455sys_mdebug(PyObject *self, PyObject *args)
456{
457	int flag;
458	if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
459		return NULL;
460	mallopt(M_DEBUG, flag);
461	Py_INCREF(Py_None);
462	return Py_None;
463}
464#endif /* USE_MALLOPT */
465
466static PyObject *
467sys_getrefcount(PyObject *self, PyObject *arg)
468{
469	return PyInt_FromLong(arg->ob_refcnt);
470}
471
472#ifdef Py_TRACE_REFS
473static PyObject *
474sys_gettotalrefcount(PyObject *self)
475{
476	extern long _Py_RefTotal;
477	return PyInt_FromLong(_Py_RefTotal);
478}
479
480#endif /* Py_TRACE_REFS */
481
482PyDoc_STRVAR(getrefcount_doc,
483"getrefcount(object) -> integer\n\
484\n\
485Return the reference count of object.  The count returned is generally\n\
486one higher than you might expect, because it includes the (temporary)\n\
487reference as an argument to getrefcount()."
488);
489
490#ifdef COUNT_ALLOCS
491static PyObject *
492sys_getcounts(PyObject *self)
493{
494	extern PyObject *get_counts(void);
495
496	return get_counts();
497}
498#endif
499
500PyDoc_STRVAR(getframe_doc,
501"_getframe([depth]) -> frameobject\n\
502\n\
503Return a frame object from the call stack.  If optional integer depth is\n\
504given, return the frame object that many calls below the top of the stack.\n\
505If that is deeper than the call stack, ValueError is raised.  The default\n\
506for depth is zero, returning the frame at the top of the call stack.\n\
507\n\
508This function should be used for internal and specialized\n\
509purposes only."
510);
511
512static PyObject *
513sys_getframe(PyObject *self, PyObject *args)
514{
515	PyFrameObject *f = PyThreadState_Get()->frame;
516	int depth = -1;
517
518	if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
519		return NULL;
520
521	while (depth > 0 && f != NULL) {
522		f = f->f_back;
523		--depth;
524	}
525	if (f == NULL) {
526		PyErr_SetString(PyExc_ValueError,
527				"call stack is not deep enough");
528		return NULL;
529	}
530	Py_INCREF(f);
531	return (PyObject*)f;
532}
533
534
535#ifdef Py_TRACE_REFS
536/* Defined in objects.c because it uses static globals if that file */
537extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
538#endif
539
540#ifdef DYNAMIC_EXECUTION_PROFILE
541/* Defined in ceval.c because it uses static globals if that file */
542extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
543#endif
544
545static PyMethodDef sys_methods[] = {
546	/* Might as well keep this in alphabetic order */
547	{"displayhook",	sys_displayhook, METH_O, displayhook_doc},
548	{"exc_info",	(PyCFunction)sys_exc_info, METH_NOARGS, exc_info_doc},
549	{"excepthook",	sys_excepthook, METH_VARARGS, excepthook_doc},
550	{"exit",	sys_exit, METH_VARARGS, exit_doc},
551#ifdef Py_USING_UNICODE
552	{"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, METH_NOARGS,
553	 getdefaultencoding_doc},
554#endif
555#ifdef HAVE_DLOPEN
556	{"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
557	 getdlopenflags_doc},
558#endif
559#ifdef COUNT_ALLOCS
560	{"getcounts",	(PyCFunction)sys_getcounts, METH_NOARGS},
561#endif
562#ifdef DYNAMIC_EXECUTION_PROFILE
563	{"getdxp",	_Py_GetDXProfile, METH_VARARGS},
564#endif
565#ifdef Py_TRACE_REFS
566	{"getobjects",	_Py_GetObjects, METH_VARARGS},
567	{"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
568#endif
569	{"getrefcount",	(PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
570	{"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
571	 getrecursionlimit_doc},
572	{"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
573#ifdef USE_MALLOPT
574	{"mdebug",	sys_mdebug, METH_VARARGS},
575#endif
576#ifdef Py_USING_UNICODE
577	{"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
578	 setdefaultencoding_doc},
579#endif
580	{"setcheckinterval",	sys_setcheckinterval, METH_VARARGS,
581	 setcheckinterval_doc},
582#ifdef HAVE_DLOPEN
583	{"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
584	 setdlopenflags_doc},
585#endif
586	{"setprofile",	sys_setprofile, METH_O, setprofile_doc},
587	{"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
588	 setrecursionlimit_doc},
589	{"settrace",	sys_settrace, METH_O, settrace_doc},
590	{NULL,		NULL}		/* sentinel */
591};
592
593static PyObject *
594list_builtin_module_names(void)
595{
596	PyObject *list = PyList_New(0);
597	int i;
598	if (list == NULL)
599		return NULL;
600	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
601		PyObject *name = PyString_FromString(
602			PyImport_Inittab[i].name);
603		if (name == NULL)
604			break;
605		PyList_Append(list, name);
606		Py_DECREF(name);
607	}
608	if (PyList_Sort(list) != 0) {
609		Py_DECREF(list);
610		list = NULL;
611	}
612	if (list) {
613		PyObject *v = PyList_AsTuple(list);
614		Py_DECREF(list);
615		list = v;
616	}
617	return list;
618}
619
620static PyObject *warnoptions = NULL;
621
622void
623PySys_ResetWarnOptions(void)
624{
625	if (warnoptions == NULL || !PyList_Check(warnoptions))
626		return;
627	PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
628}
629
630void
631PySys_AddWarnOption(char *s)
632{
633	PyObject *str;
634
635	if (warnoptions == NULL || !PyList_Check(warnoptions)) {
636		Py_XDECREF(warnoptions);
637		warnoptions = PyList_New(0);
638		if (warnoptions == NULL)
639			return;
640	}
641	str = PyString_FromString(s);
642	if (str != NULL) {
643		PyList_Append(warnoptions, str);
644		Py_DECREF(str);
645	}
646}
647
648/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
649   Two literals concatenated works just fine.  If you have a K&R compiler
650   or other abomination that however *does* understand longer strings,
651   get rid of the !!! comment in the middle and the quotes that surround it. */
652PyDoc_VAR(sys_doc) =
653PyDoc_STR(
654"This module provides access to some objects used or maintained by the\n\
655interpreter and to functions that interact strongly with the interpreter.\n\
656\n\
657Dynamic objects:\n\
658\n\
659argv -- command line arguments; argv[0] is the script pathname if known\n\
660path -- module search path; path[0] is the script directory, else ''\n\
661modules -- dictionary of loaded modules\n\
662\n\
663displayhook -- called to show results in an interactive session\n\
664excepthook -- called to handle any uncaught exception other than SystemExit\n\
665  To customize printing in an interactive session or to install a custom\n\
666  top-level exception handler, assign other functions to replace these.\n\
667\n\
668exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
669  Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
670\n\
671stdin -- standard input file object; used by raw_input() and input()\n\
672stdout -- standard output file object; used by the print statement\n\
673stderr -- standard error object; used for error messages\n\
674  By assigning other file objects (or objects that behave like files)\n\
675  to these, it is possible to redirect all of the interpreter's I/O.\n\
676\n\
677last_type -- type of last uncaught exception\n\
678last_value -- value of last uncaught exception\n\
679last_traceback -- traceback of last uncaught exception\n\
680  These three are only available in an interactive session after a\n\
681  traceback has been printed.\n\
682\n\
683exc_type -- type of exception currently being handled\n\
684exc_value -- value of exception currently being handled\n\
685exc_traceback -- traceback of exception currently being handled\n\
686  The function exc_info() should be used instead of these three,\n\
687  because it is thread-safe.\n\
688"
689)
690/* concatenating string here */
691PyDoc_STR(
692"\n\
693Static objects:\n\
694\n\
695maxint -- the largest supported integer (the smallest is -maxint-1)\n\
696maxunicode -- the largest supported character\n\
697builtin_module_names -- tuple of module names built into this interpreter\n\
698version -- the version of this interpreter as a string\n\
699version_info -- version information as a tuple\n\
700hexversion -- version information encoded as a single integer\n\
701copyright -- copyright notice pertaining to this interpreter\n\
702platform -- platform identifier\n\
703executable -- pathname of this Python interpreter\n\
704prefix -- prefix used to find the Python library\n\
705exec_prefix -- prefix used to find the machine-specific Python library\n\
706"
707)
708#ifdef MS_WINDOWS
709/* concatenating string here */
710PyDoc_STR(
711"dllhandle -- [Windows only] integer handle of the Python DLL\n\
712winver -- [Windows only] version number of the Python DLL\n\
713"
714)
715#endif /* MS_WINDOWS */
716PyDoc_STR(
717"__stdin__ -- the original stdin; don't touch!\n\
718__stdout__ -- the original stdout; don't touch!\n\
719__stderr__ -- the original stderr; don't touch!\n\
720__displayhook__ -- the original displayhook; don't touch!\n\
721__excepthook__ -- the original excepthook; don't touch!\n\
722\n\
723Functions:\n\
724\n\
725displayhook() -- print an object to the screen, and save it in __builtin__._\n\
726excepthook() -- print an exception and its traceback to sys.stderr\n\
727exc_info() -- return thread-safe information about the current exception\n\
728exit() -- exit the interpreter by raising SystemExit\n\
729getdlopenflags() -- returns flags to be used for dlopen() calls\n\
730getrefcount() -- return the reference count for an object (plus one :-)\n\
731getrecursionlimit() -- return the max recursion depth for the interpreter\n\
732setcheckinterval() -- control how often the interpreter checks for events\n\
733setdlopenflags() -- set the flags to be used for dlopen() calls\n\
734setprofile() -- set the global profiling function\n\
735setrecursionlimit() -- set the max recursion depth for the interpreter\n\
736settrace() -- set the global debug tracing function\n\
737"
738)
739/* end of sys_doc */ ;
740
741PyObject *
742_PySys_Init(void)
743{
744	PyObject *m, *v, *sysdict;
745	PyObject *sysin, *sysout, *syserr;
746	char *s;
747
748	m = Py_InitModule3("sys", sys_methods, sys_doc);
749	sysdict = PyModule_GetDict(m);
750
751	sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
752	sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
753	syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
754	if (PyErr_Occurred())
755		return NULL;
756	PyDict_SetItemString(sysdict, "stdin", sysin);
757	PyDict_SetItemString(sysdict, "stdout", sysout);
758	PyDict_SetItemString(sysdict, "stderr", syserr);
759	/* Make backup copies for cleanup */
760	PyDict_SetItemString(sysdict, "__stdin__", sysin);
761	PyDict_SetItemString(sysdict, "__stdout__", sysout);
762	PyDict_SetItemString(sysdict, "__stderr__", syserr);
763	PyDict_SetItemString(sysdict, "__displayhook__",
764                             PyDict_GetItemString(sysdict, "displayhook"));
765	PyDict_SetItemString(sysdict, "__excepthook__",
766                             PyDict_GetItemString(sysdict, "excepthook"));
767	Py_XDECREF(sysin);
768	Py_XDECREF(sysout);
769	Py_XDECREF(syserr);
770	PyDict_SetItemString(sysdict, "version",
771			     v = PyString_FromString(Py_GetVersion()));
772	Py_XDECREF(v);
773	PyDict_SetItemString(sysdict, "hexversion",
774			     v = PyInt_FromLong(PY_VERSION_HEX));
775	Py_XDECREF(v);
776	/*
777	 * These release level checks are mutually exclusive and cover
778	 * the field, so don't get too fancy with the pre-processor!
779	 */
780#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
781	s = "alpha";
782#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
783	s = "beta";
784#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
785	s = "candidate";
786#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
787	s = "final";
788#endif
789	PyDict_SetItemString(sysdict, "version_info",
790			     v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
791					       PY_MINOR_VERSION,
792					       PY_MICRO_VERSION, s,
793					       PY_RELEASE_SERIAL));
794	Py_XDECREF(v);
795	PyDict_SetItemString(sysdict, "copyright",
796			     v = PyString_FromString(Py_GetCopyright()));
797	Py_XDECREF(v);
798	PyDict_SetItemString(sysdict, "platform",
799			     v = PyString_FromString(Py_GetPlatform()));
800	Py_XDECREF(v);
801	PyDict_SetItemString(sysdict, "executable",
802			     v = PyString_FromString(Py_GetProgramFullPath()));
803	Py_XDECREF(v);
804	PyDict_SetItemString(sysdict, "prefix",
805			     v = PyString_FromString(Py_GetPrefix()));
806	Py_XDECREF(v);
807	PyDict_SetItemString(sysdict, "exec_prefix",
808		   v = PyString_FromString(Py_GetExecPrefix()));
809	Py_XDECREF(v);
810	PyDict_SetItemString(sysdict, "maxint",
811			     v = PyInt_FromLong(PyInt_GetMax()));
812	Py_XDECREF(v);
813#ifdef Py_USING_UNICODE
814	PyDict_SetItemString(sysdict, "maxunicode",
815			     v = PyInt_FromLong(PyUnicode_GetMax()));
816	Py_XDECREF(v);
817#endif
818	PyDict_SetItemString(sysdict, "builtin_module_names",
819		   v = list_builtin_module_names());
820	Py_XDECREF(v);
821	{
822		/* Assumes that longs are at least 2 bytes long.
823		   Should be safe! */
824		unsigned long number = 1;
825		char *value;
826
827		s = (char *) &number;
828		if (s[0] == 0)
829			value = "big";
830		else
831			value = "little";
832		PyDict_SetItemString(sysdict, "byteorder",
833				     v = PyString_FromString(value));
834		Py_XDECREF(v);
835	}
836#ifdef MS_COREDLL
837	PyDict_SetItemString(sysdict, "dllhandle",
838			     v = PyLong_FromVoidPtr(PyWin_DLLhModule));
839	Py_XDECREF(v);
840	PyDict_SetItemString(sysdict, "winver",
841			     v = PyString_FromString(PyWin_DLLVersionString));
842	Py_XDECREF(v);
843#endif
844	if (warnoptions == NULL) {
845		warnoptions = PyList_New(0);
846	}
847	else {
848		Py_INCREF(warnoptions);
849	}
850	if (warnoptions != NULL) {
851		PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
852	}
853
854	if (PyErr_Occurred())
855		return NULL;
856	return m;
857}
858
859static PyObject *
860makepathobject(char *path, int delim)
861{
862	int i, n;
863	char *p;
864	PyObject *v, *w;
865
866	n = 1;
867	p = path;
868	while ((p = strchr(p, delim)) != NULL) {
869		n++;
870		p++;
871	}
872	v = PyList_New(n);
873	if (v == NULL)
874		return NULL;
875	for (i = 0; ; i++) {
876		p = strchr(path, delim);
877		if (p == NULL)
878			p = strchr(path, '\0'); /* End of string */
879		w = PyString_FromStringAndSize(path, (int) (p - path));
880		if (w == NULL) {
881			Py_DECREF(v);
882			return NULL;
883		}
884		PyList_SetItem(v, i, w);
885		if (*p == '\0')
886			break;
887		path = p+1;
888	}
889	return v;
890}
891
892void
893PySys_SetPath(char *path)
894{
895	PyObject *v;
896	if ((v = makepathobject(path, DELIM)) == NULL)
897		Py_FatalError("can't create sys.path");
898	if (PySys_SetObject("path", v) != 0)
899		Py_FatalError("can't assign sys.path");
900	Py_DECREF(v);
901}
902
903static PyObject *
904makeargvobject(int argc, char **argv)
905{
906	PyObject *av;
907	if (argc <= 0 || argv == NULL) {
908		/* Ensure at least one (empty) argument is seen */
909		static char *empty_argv[1] = {""};
910		argv = empty_argv;
911		argc = 1;
912	}
913	av = PyList_New(argc);
914	if (av != NULL) {
915		int i;
916		for (i = 0; i < argc; i++) {
917			PyObject *v = PyString_FromString(argv[i]);
918			if (v == NULL) {
919				Py_DECREF(av);
920				av = NULL;
921				break;
922			}
923			PyList_SetItem(av, i, v);
924		}
925	}
926	return av;
927}
928
929void
930PySys_SetArgv(int argc, char **argv)
931{
932	PyObject *av = makeargvobject(argc, argv);
933	PyObject *path = PySys_GetObject("path");
934	if (av == NULL)
935		Py_FatalError("no mem for sys.argv");
936	if (PySys_SetObject("argv", av) != 0)
937		Py_FatalError("can't assign sys.argv");
938	if (path != NULL) {
939		char *argv0 = argv[0];
940		char *p = NULL;
941		int n = 0;
942		PyObject *a;
943#ifdef HAVE_READLINK
944		char link[MAXPATHLEN+1];
945		char argv0copy[2*MAXPATHLEN+1];
946		int nr = 0;
947		if (argc > 0 && argv0 != NULL)
948			nr = readlink(argv0, link, MAXPATHLEN);
949		if (nr > 0) {
950			/* It's a symlink */
951			link[nr] = '\0';
952			if (link[0] == SEP)
953				argv0 = link; /* Link to absolute path */
954			else if (strchr(link, SEP) == NULL)
955				; /* Link without path */
956			else {
957				/* Must join(dirname(argv0), link) */
958				char *q = strrchr(argv0, SEP);
959				if (q == NULL)
960					argv0 = link; /* argv0 without path */
961				else {
962					/* Must make a copy */
963					strcpy(argv0copy, argv0);
964					q = strrchr(argv0copy, SEP);
965					strcpy(q+1, link);
966					argv0 = argv0copy;
967				}
968			}
969		}
970#endif /* HAVE_READLINK */
971#if SEP == '\\' /* Special case for MS filename syntax */
972		if (argc > 0 && argv0 != NULL) {
973			char *q;
974			p = strrchr(argv0, SEP);
975			/* Test for alternate separator */
976			q = strrchr(p ? p : argv0, '/');
977			if (q != NULL)
978				p = q;
979			if (p != NULL) {
980				n = p + 1 - argv0;
981				if (n > 1 && p[-1] != ':')
982					n--; /* Drop trailing separator */
983			}
984		}
985#else /* All other filename syntaxes */
986		if (argc > 0 && argv0 != NULL)
987			p = strrchr(argv0, SEP);
988		if (p != NULL) {
989#ifndef RISCOS
990			n = p + 1 - argv0;
991#else /* don't include trailing separator */
992			n = p - argv0;
993#endif /* RISCOS */
994#if SEP == '/' /* Special case for Unix filename syntax */
995			if (n > 1)
996				n--; /* Drop trailing separator */
997#endif /* Unix */
998		}
999#endif /* All others */
1000		a = PyString_FromStringAndSize(argv0, n);
1001		if (a == NULL)
1002			Py_FatalError("no mem for sys.path insertion");
1003		if (PyList_Insert(path, 0, a) < 0)
1004			Py_FatalError("sys.path.insert(0) failed");
1005		Py_DECREF(a);
1006	}
1007	Py_DECREF(av);
1008}
1009
1010
1011/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1012   Adapted from code submitted by Just van Rossum.
1013
1014   PySys_WriteStdout(format, ...)
1015   PySys_WriteStderr(format, ...)
1016
1017      The first function writes to sys.stdout; the second to sys.stderr.  When
1018      there is a problem, they write to the real (C level) stdout or stderr;
1019      no exceptions are raised.
1020
1021      Both take a printf-style format string as their first argument followed
1022      by a variable length argument list determined by the format string.
1023
1024      *** WARNING ***
1025
1026      The format should limit the total size of the formatted output string to
1027      1000 bytes.  In particular, this means that no unrestricted "%s" formats
1028      should occur; these should be limited using "%.<N>s where <N> is a
1029      decimal number calculated so that <N> plus the maximum size of other
1030      formatted text does not exceed 1000 bytes.  Also watch out for "%f",
1031      which can print hundreds of digits for very large numbers.
1032
1033 */
1034
1035static void
1036mywrite(char *name, FILE *fp, const char *format, va_list va)
1037{
1038	PyObject *file;
1039	PyObject *error_type, *error_value, *error_traceback;
1040
1041	PyErr_Fetch(&error_type, &error_value, &error_traceback);
1042	file = PySys_GetObject(name);
1043	if (file == NULL || PyFile_AsFile(file) == fp)
1044		vfprintf(fp, format, va);
1045	else {
1046		char buffer[1001];
1047		const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
1048						   format, va);
1049		if (PyFile_WriteString(buffer, file) != 0) {
1050			PyErr_Clear();
1051			fputs(buffer, fp);
1052		}
1053		if (written < 0 || written >= sizeof(buffer)) {
1054			const char *truncated = "... truncated";
1055			if (PyFile_WriteString(truncated, file) != 0) {
1056				PyErr_Clear();
1057				fputs(truncated, fp);
1058			}
1059		}
1060	}
1061	PyErr_Restore(error_type, error_value, error_traceback);
1062}
1063
1064void
1065PySys_WriteStdout(const char *format, ...)
1066{
1067	va_list va;
1068
1069	va_start(va, format);
1070	mywrite("stdout", stdout, format, va);
1071	va_end(va);
1072}
1073
1074void
1075PySys_WriteStderr(const char *format, ...)
1076{
1077	va_list va;
1078
1079	va_start(va, format);
1080	mywrite("stderr", stderr, format, va);
1081	va_end(va);
1082}
1083