sysmodule.c revision 1e0c2f4bee43728930bd5f4dc77283f09c4ba004
1/***********************************************************
2Copyright (c) 2000, BeOpen.com.
3Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
5All rights reserved.
6
7See the file "Misc/COPYRIGHT" for information on usage and
8redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9******************************************************************/
10
11/* System module */
12
13/*
14Various bits of information used by the interpreter are collected in
15module 'sys'.
16Function member:
17- exit(sts): raise SystemExit
18Data members:
19- stdin, stdout, stderr: standard file objects
20- modules: the table of modules (dictionary)
21- path: module search path (list of strings)
22- argv: script arguments (list of strings)
23- ps1, ps2: optional primary and secondary prompts (strings)
24*/
25
26#include "Python.h"
27
28#include "osdefs.h"
29
30#ifdef HAVE_UNISTD_H
31#include <unistd.h>
32#endif
33
34#ifdef MS_COREDLL
35extern void *PyWin_DLLhModule;
36/* A string loaded from the DLL at startup: */
37extern const char *PyWin_DLLVersionString;
38#endif
39
40PyObject *
41PySys_GetObject(char *name)
42{
43	PyThreadState *tstate = PyThreadState_Get();
44	PyObject *sd = tstate->interp->sysdict;
45	if (sd == NULL)
46		return NULL;
47	return PyDict_GetItemString(sd, name);
48}
49
50FILE *
51PySys_GetFile(char *name, FILE *def)
52{
53	FILE *fp = NULL;
54	PyObject *v = PySys_GetObject(name);
55	if (v != NULL && PyFile_Check(v))
56		fp = PyFile_AsFile(v);
57	if (fp == NULL)
58		fp = def;
59	return fp;
60}
61
62int
63PySys_SetObject(char *name, PyObject *v)
64{
65	PyThreadState *tstate = PyThreadState_Get();
66	PyObject *sd = tstate->interp->sysdict;
67	if (v == NULL) {
68		if (PyDict_GetItemString(sd, name) == NULL)
69			return 0;
70		else
71			return PyDict_DelItemString(sd, name);
72	}
73	else
74		return PyDict_SetItemString(sd, name, v);
75}
76
77static PyObject *
78sys_exc_info(PyObject *self, PyObject *args)
79{
80	PyThreadState *tstate;
81	if (!PyArg_ParseTuple(args, ":exc_info"))
82		return NULL;
83	tstate = PyThreadState_Get();
84	return Py_BuildValue(
85		"(OOO)",
86		tstate->exc_type != NULL ? tstate->exc_type : Py_None,
87		tstate->exc_value != NULL ? tstate->exc_value : Py_None,
88		tstate->exc_traceback != NULL ?
89			tstate->exc_traceback : Py_None);
90}
91
92static char exc_info_doc[] =
93"exc_info() -> (type, value, traceback)\n\
94\n\
95Return information about the exception that is currently being handled.\n\
96This should be called from inside an except clause only.";
97
98static PyObject *
99sys_exit(PyObject *self, PyObject *args)
100{
101	/* Raise SystemExit so callers may catch it or clean up. */
102	PyErr_SetObject(PyExc_SystemExit, args);
103	return NULL;
104}
105
106static char exit_doc[] =
107"exit([status])\n\
108\n\
109Exit the interpreter by raising SystemExit(status).\n\
110If the status is omitted or None, it defaults to zero (i.e., success).\n\
111If the status numeric, it will be used as the system exit status.\n\
112If it is another kind of object, it will be printed and the system\n\
113exit status will be one (i.e., failure).";
114
115static PyObject *
116sys_getdefaultencoding(PyObject *self, PyObject *args)
117{
118	if (!PyArg_ParseTuple(args, ":getdefaultencoding"))
119		return NULL;
120	return PyString_FromString(PyUnicode_GetDefaultEncoding());
121}
122
123static char getdefaultencoding_doc[] =
124"getdefaultencoding() -> string\n\
125\n\
126Return the current default string encoding used by the Unicode \n\
127implementation.";
128
129static PyObject *
130sys_setdefaultencoding(PyObject *self, PyObject *args)
131{
132	char *encoding;
133	if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
134		return NULL;
135	if (PyUnicode_SetDefaultEncoding(encoding))
136	    	return NULL;
137	Py_INCREF(Py_None);
138	return Py_None;
139}
140
141static char setdefaultencoding_doc[] =
142"setdefaultencoding(encoding)\n\
143\n\
144Set the current default string encoding used by the Unicode implementation.";
145
146static PyObject *
147sys_settrace(PyObject *self, PyObject *args)
148{
149	PyThreadState *tstate = PyThreadState_Get();
150	if (args == Py_None)
151		args = NULL;
152	else
153		Py_XINCREF(args);
154	Py_XDECREF(tstate->sys_tracefunc);
155	tstate->sys_tracefunc = args;
156	Py_INCREF(Py_None);
157	return Py_None;
158}
159
160static char settrace_doc[] =
161"settrace(function)\n\
162\n\
163Set the global debug tracing function.  It will be called on each\n\
164function call.  See the debugger chapter in the library manual.";
165
166static PyObject *
167sys_setprofile(PyObject *self, PyObject *args)
168{
169	PyThreadState *tstate = PyThreadState_Get();
170	if (args == Py_None)
171		args = NULL;
172	else
173		Py_XINCREF(args);
174	Py_XDECREF(tstate->sys_profilefunc);
175	tstate->sys_profilefunc = args;
176	Py_INCREF(Py_None);
177	return Py_None;
178}
179
180static char setprofile_doc[] =
181"setprofile(function)\n\
182\n\
183Set the profiling function.  It will be called on each function call\n\
184and return.  See the profiler chapter in the library manual.";
185
186static PyObject *
187sys_setcheckinterval(PyObject *self, PyObject *args)
188{
189	PyThreadState *tstate = PyThreadState_Get();
190	if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval))
191		return NULL;
192	Py_INCREF(Py_None);
193	return Py_None;
194}
195
196static char setcheckinterval_doc[] =
197"setcheckinterval(n)\n\
198\n\
199Tell the Python interpreter to check for asynchronous events every\n\
200n instructions.  This also affects how often thread switches occur.";
201
202#ifdef USE_MALLOPT
203/* Link with -lmalloc (or -lmpc) on an SGI */
204#include <malloc.h>
205
206static PyObject *
207sys_mdebug(PyObject *self, PyObject *args)
208{
209	int flag;
210	if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
211		return NULL;
212	mallopt(M_DEBUG, flag);
213	Py_INCREF(Py_None);
214	return Py_None;
215}
216#endif /* USE_MALLOPT */
217
218static PyObject *
219sys_getrefcount(PyObject *self, PyObject *args)
220{
221	PyObject *arg;
222	if (!PyArg_ParseTuple(args, "O:getrefcount", &arg))
223		return NULL;
224	return PyInt_FromLong(arg->ob_refcnt);
225}
226
227#ifdef Py_TRACE_REFS
228static PyObject *
229sys_gettotalrefcount(PyObject *self, PyObject *args)
230{
231	extern long _Py_RefTotal;
232	if (!PyArg_ParseTuple(args, ":gettotalrefcount"))
233		return NULL;
234	return PyInt_FromLong(_Py_RefTotal);
235}
236
237#endif /* Py_TRACE_REFS */
238
239static char getrefcount_doc[] =
240"getrefcount(object) -> integer\n\
241\n\
242Return the current reference count for the object.  This includes the\n\
243temporary reference in the argument list, so it is at least 2.";
244
245#ifdef COUNT_ALLOCS
246static PyObject *
247sys_getcounts(PyObject *self, PyObject *args)
248{
249	extern PyObject *get_counts(void);
250
251	if (!PyArg_ParseTuple(args, ":getcounts"))
252		return NULL;
253	return get_counts();
254}
255#endif
256
257#ifdef Py_TRACE_REFS
258/* Defined in objects.c because it uses static globals if that file */
259extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
260#endif
261
262#ifdef DYNAMIC_EXECUTION_PROFILE
263/* Defined in ceval.c because it uses static globals if that file */
264extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
265#endif
266
267static PyMethodDef sys_methods[] = {
268	/* Might as well keep this in alphabetic order */
269	{"exc_info",	sys_exc_info, 1, exc_info_doc},
270	{"exit",	sys_exit, 0, exit_doc},
271	{"getdefaultencoding", sys_getdefaultencoding, 1, getdefaultencoding_doc},
272#ifdef COUNT_ALLOCS
273	{"getcounts",	sys_getcounts, 1},
274#endif
275#ifdef DYNAMIC_EXECUTION_PROFILE
276	{"getdxp",	_Py_GetDXProfile, 1},
277#endif
278#ifdef Py_TRACE_REFS
279	{"getobjects",	_Py_GetObjects, 1},
280	{"gettotalrefcount", sys_gettotalrefcount, 1},
281#endif
282	{"getrefcount",	sys_getrefcount, 1, getrefcount_doc},
283#ifdef USE_MALLOPT
284	{"mdebug",	sys_mdebug, 1},
285#endif
286	{"setdefaultencoding", sys_setdefaultencoding, 1, setdefaultencoding_doc},
287	{"setcheckinterval",	sys_setcheckinterval, 1, setcheckinterval_doc},
288	{"setprofile",	sys_setprofile, 0, setprofile_doc},
289	{"settrace",	sys_settrace, 0, settrace_doc},
290	{NULL,		NULL}		/* sentinel */
291};
292
293static PyObject *
294list_builtin_module_names(void)
295{
296	PyObject *list = PyList_New(0);
297	int i;
298	if (list == NULL)
299		return NULL;
300	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
301		PyObject *name = PyString_FromString(
302			PyImport_Inittab[i].name);
303		if (name == NULL)
304			break;
305		PyList_Append(list, name);
306		Py_DECREF(name);
307	}
308	if (PyList_Sort(list) != 0) {
309		Py_DECREF(list);
310		list = NULL;
311	}
312	if (list) {
313		PyObject *v = PyList_AsTuple(list);
314		Py_DECREF(list);
315		list = v;
316	}
317	return list;
318}
319
320/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
321   Two literals concatenated works just fine.  If you have a K&R compiler
322   or other abomination that however *does* understand longer strings,
323   get rid of the !!! comment in the middle and the quotes that surround it. */
324static char sys_doc[] =
325"This module provides access to some objects used or maintained by the\n\
326interpreter and to functions that interact strongly with the interpreter.\n\
327\n\
328Dynamic objects:\n\
329\n\
330argv -- command line arguments; argv[0] is the script pathname if known\n\
331path -- module search path; path[0] is the script directory, else ''\n\
332modules -- dictionary of loaded modules\n\
333exitfunc -- you may set this to a function to be called when Python exits\n\
334\n\
335stdin -- standard input file object; used by raw_input() and input()\n\
336stdout -- standard output file object; used by the print statement\n\
337stderr -- standard error object; used for error messages\n\
338  By assigning another file object (or an object that behaves like a file)\n\
339  to one of these, it is possible to redirect all of the interpreter's I/O.\n\
340\n\
341last_type -- type of last uncaught exception\n\
342last_value -- value of last uncaught exception\n\
343last_traceback -- traceback of last uncaught exception\n\
344  These three are only available in an interactive session after a\n\
345  traceback has been printed.\n\
346\n\
347exc_type -- type of exception currently being handled\n\
348exc_value -- value of exception currently being handled\n\
349exc_traceback -- traceback of exception currently being handled\n\
350  The function exc_info() should be used instead of these three,\n\
351  because it is thread-safe.\n\
352"
353#ifndef MS_WIN16
354/* Concatenating string here */
355"\n\
356Static objects:\n\
357\n\
358maxint -- the largest supported integer (the smallest is -maxint-1)\n\
359builtin_module_names -- tuple of module names built into this intepreter\n\
360version -- the version of this interpreter as a string\n\
361version_info -- version information as a tuple\n\
362hexversion -- version information encoded as a single integer\n\
363copyright -- copyright notice pertaining to this interpreter\n\
364platform -- platform identifier\n\
365executable -- pathname of this Python interpreter\n\
366prefix -- prefix used to find the Python library\n\
367exec_prefix -- prefix used to find the machine-specific Python library\n\
368dllhandle -- [Windows only] integer handle of the Python DLL\n\
369winver -- [Windows only] version number of the Python DLL\n\
370__stdin__ -- the original stdin; don't use!\n\
371__stdout__ -- the original stdout; don't use!\n\
372__stderr__ -- the original stderr; don't use!\n\
373\n\
374Functions:\n\
375\n\
376exc_info() -- return thread-safe information about the current exception\n\
377exit() -- exit the interpreter by raising SystemExit\n\
378getrefcount() -- return the reference count for an object (plus one :-)\n\
379setcheckinterval() -- control how often the interpreter checks for events\n\
380setprofile() -- set the global profiling function\n\
381settrace() -- set the global debug tracing function\n\
382";
383#endif
384
385PyObject *
386_PySys_Init(void)
387{
388	PyObject *m, *v, *sysdict;
389	PyObject *sysin, *sysout, *syserr;
390	char *s;
391
392	m = Py_InitModule3("sys", sys_methods, sys_doc);
393	sysdict = PyModule_GetDict(m);
394
395	sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
396	sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
397	syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
398	if (PyErr_Occurred())
399		return NULL;
400	PyDict_SetItemString(sysdict, "stdin", sysin);
401	PyDict_SetItemString(sysdict, "stdout", sysout);
402	PyDict_SetItemString(sysdict, "stderr", syserr);
403	/* Make backup copies for cleanup */
404	PyDict_SetItemString(sysdict, "__stdin__", sysin);
405	PyDict_SetItemString(sysdict, "__stdout__", sysout);
406	PyDict_SetItemString(sysdict, "__stderr__", syserr);
407	Py_XDECREF(sysin);
408	Py_XDECREF(sysout);
409	Py_XDECREF(syserr);
410	PyDict_SetItemString(sysdict, "version",
411			     v = PyString_FromString(Py_GetVersion()));
412	Py_XDECREF(v);
413	PyDict_SetItemString(sysdict, "hexversion",
414			     v = PyInt_FromLong(PY_VERSION_HEX));
415	Py_XDECREF(v);
416	/*
417	 * These release level checks are mutually exclusive and cover
418	 * the field, so don't get too fancy with the pre-processor!
419	 */
420#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
421	s = "alpha";
422#endif
423#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
424	s = "beta";
425#endif
426#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
427	s = "candidate";
428#endif
429#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
430	s = "final";
431#endif
432	PyDict_SetItemString(sysdict, "version_info",
433			     v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
434					       PY_MINOR_VERSION,
435					       PY_MICRO_VERSION, s,
436					       PY_RELEASE_SERIAL));
437	Py_XDECREF(v);
438	PyDict_SetItemString(sysdict, "copyright",
439			     v = PyString_FromString(Py_GetCopyright()));
440	Py_XDECREF(v);
441	PyDict_SetItemString(sysdict, "platform",
442			     v = PyString_FromString(Py_GetPlatform()));
443	Py_XDECREF(v);
444	PyDict_SetItemString(sysdict, "executable",
445			     v = PyString_FromString(Py_GetProgramFullPath()));
446	Py_XDECREF(v);
447	PyDict_SetItemString(sysdict, "prefix",
448			     v = PyString_FromString(Py_GetPrefix()));
449	Py_XDECREF(v);
450	PyDict_SetItemString(sysdict, "exec_prefix",
451		   v = PyString_FromString(Py_GetExecPrefix()));
452	Py_XDECREF(v);
453	PyDict_SetItemString(sysdict, "maxint",
454			     v = PyInt_FromLong(PyInt_GetMax()));
455	Py_XDECREF(v);
456	PyDict_SetItemString(sysdict, "builtin_module_names",
457		   v = list_builtin_module_names());
458	Py_XDECREF(v);
459#ifdef MS_COREDLL
460	PyDict_SetItemString(sysdict, "dllhandle",
461			     v = PyLong_FromVoidPtr(PyWin_DLLhModule));
462	Py_XDECREF(v);
463	PyDict_SetItemString(sysdict, "winver",
464			     v = PyString_FromString(PyWin_DLLVersionString));
465	Py_XDECREF(v);
466#endif
467	if (PyErr_Occurred())
468		return NULL;
469	return m;
470}
471
472static PyObject *
473makepathobject(char *path, int delim)
474{
475	int i, n;
476	char *p;
477	PyObject *v, *w;
478
479	n = 1;
480	p = path;
481	while ((p = strchr(p, delim)) != NULL) {
482		n++;
483		p++;
484	}
485	v = PyList_New(n);
486	if (v == NULL)
487		return NULL;
488	for (i = 0; ; i++) {
489		p = strchr(path, delim);
490		if (p == NULL)
491			p = strchr(path, '\0'); /* End of string */
492		w = PyString_FromStringAndSize(path, (int) (p - path));
493		if (w == NULL) {
494			Py_DECREF(v);
495			return NULL;
496		}
497		PyList_SetItem(v, i, w);
498		if (*p == '\0')
499			break;
500		path = p+1;
501	}
502	return v;
503}
504
505void
506PySys_SetPath(char *path)
507{
508	PyObject *v;
509	if ((v = makepathobject(path, DELIM)) == NULL)
510		Py_FatalError("can't create sys.path");
511	if (PySys_SetObject("path", v) != 0)
512		Py_FatalError("can't assign sys.path");
513	Py_DECREF(v);
514}
515
516static PyObject *
517makeargvobject(int argc, char **argv)
518{
519	PyObject *av;
520	if (argc <= 0 || argv == NULL) {
521		/* Ensure at least one (empty) argument is seen */
522		static char *empty_argv[1] = {""};
523		argv = empty_argv;
524		argc = 1;
525	}
526	av = PyList_New(argc);
527	if (av != NULL) {
528		int i;
529		for (i = 0; i < argc; i++) {
530			PyObject *v = PyString_FromString(argv[i]);
531			if (v == NULL) {
532				Py_DECREF(av);
533				av = NULL;
534				break;
535			}
536			PyList_SetItem(av, i, v);
537		}
538	}
539	return av;
540}
541
542void
543PySys_SetArgv(int argc, char **argv)
544{
545	PyObject *av = makeargvobject(argc, argv);
546	PyObject *path = PySys_GetObject("path");
547	if (av == NULL)
548		Py_FatalError("no mem for sys.argv");
549	if (PySys_SetObject("argv", av) != 0)
550		Py_FatalError("can't assign sys.argv");
551	if (path != NULL) {
552		char *argv0 = argv[0];
553		char *p = NULL;
554		int n = 0;
555		PyObject *a;
556#ifdef HAVE_READLINK
557		char link[MAXPATHLEN+1];
558		char argv0copy[2*MAXPATHLEN+1];
559		int nr = 0;
560		if (argc > 0 && argv0 != NULL)
561			nr = readlink(argv0, link, MAXPATHLEN);
562		if (nr > 0) {
563			/* It's a symlink */
564			link[nr] = '\0';
565			if (link[0] == SEP)
566				argv0 = link; /* Link to absolute path */
567			else if (strchr(link, SEP) == NULL)
568				; /* Link without path */
569			else {
570				/* Must join(dirname(argv0), link) */
571				char *q = strrchr(argv0, SEP);
572				if (q == NULL)
573					argv0 = link; /* argv0 without path */
574				else {
575					/* Must make a copy */
576					strcpy(argv0copy, argv0);
577					q = strrchr(argv0copy, SEP);
578					strcpy(q+1, link);
579					argv0 = argv0copy;
580				}
581			}
582		}
583#endif /* HAVE_READLINK */
584#if SEP == '\\' /* Special case for MS filename syntax */
585		if (argc > 0 && argv0 != NULL) {
586			char *q;
587			p = strrchr(argv0, SEP);
588			/* Test for alternate separator */
589			q = strrchr(p ? p : argv0, '/');
590			if (q != NULL)
591				p = q;
592			if (p != NULL) {
593				n = p + 1 - argv0;
594				if (n > 1 && p[-1] != ':')
595					n--; /* Drop trailing separator */
596			}
597		}
598#else /* All other filename syntaxes */
599		if (argc > 0 && argv0 != NULL)
600			p = strrchr(argv0, SEP);
601		if (p != NULL) {
602			n = p + 1 - argv0;
603#if SEP == '/' /* Special case for Unix filename syntax */
604			if (n > 1)
605				n--; /* Drop trailing separator */
606#endif /* Unix */
607		}
608#endif /* All others */
609		a = PyString_FromStringAndSize(argv0, n);
610		if (a == NULL)
611			Py_FatalError("no mem for sys.path insertion");
612		if (PyList_Insert(path, 0, a) < 0)
613			Py_FatalError("sys.path.insert(0) failed");
614		Py_DECREF(a);
615	}
616	Py_DECREF(av);
617}
618
619
620/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
621   Adapted from code submitted by Just van Rossum.
622
623   PySys_WriteStdout(format, ...)
624   PySys_WriteStderr(format, ...)
625
626      The first function writes to sys.stdout; the second to sys.stderr.  When
627      there is a problem, they write to the real (C level) stdout or stderr;
628      no exceptions are raised.
629
630      Both take a printf-style format string as their first argument followed
631      by a variable length argument list determined by the format string.
632
633      *** WARNING ***
634
635      The format should limit the total size of the formatted output string to
636      1000 bytes.  In particular, this means that no unrestricted "%s" formats
637      should occur; these should be limited using "%.<N>s where <N> is a
638      decimal number calculated so that <N> plus the maximum size of other
639      formatted text does not exceed 1000 bytes.  Also watch out for "%f",
640      which can print hundreds of digits for very large numbers.
641
642 */
643
644static void
645mywrite(char *name, FILE *fp, const char *format, va_list va)
646{
647	PyObject *file;
648	PyObject *error_type, *error_value, *error_traceback;
649
650	PyErr_Fetch(&error_type, &error_value, &error_traceback);
651	file = PySys_GetObject(name);
652	if (file == NULL || PyFile_AsFile(file) == fp)
653		vfprintf(fp, format, va);
654	else {
655		char buffer[1001];
656		if (vsprintf(buffer, format, va) >= sizeof(buffer))
657		    Py_FatalError("PySys_WriteStdout/err: buffer overrun");
658		if (PyFile_WriteString(buffer, file) != 0) {
659			PyErr_Clear();
660			fputs(buffer, fp);
661		}
662	}
663	PyErr_Restore(error_type, error_value, error_traceback);
664}
665
666void
667PySys_WriteStdout(const char *format, ...)
668{
669	va_list va;
670
671	va_start(va, format);
672	mywrite("stdout", stdout, format, va);
673	va_end(va);
674}
675
676void
677PySys_WriteStderr(const char *format, ...)
678{
679	va_list va;
680
681	va_start(va, format);
682	mywrite("stderr", stderr, format, va);
683	va_end(va);
684}
685