sysmodule.c 28 KB
Newer Older
Guido van Rossum's avatar
Guido van Rossum committed
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3 4 5 6
/* System module */

/*
Various bits of information used by the interpreter are collected in
module 'sys'.
Guido van Rossum's avatar
Guido van Rossum committed
7
Function member:
Guido van Rossum's avatar
Guido van Rossum committed
8
- exit(sts): raise SystemExit
Guido van Rossum's avatar
Guido van Rossum committed
9 10 11
Data members:
- stdin, stdout, stderr: standard file objects
- modules: the table of modules (dictionary)
Guido van Rossum's avatar
Guido van Rossum committed
12 13 14
- path: module search path (list of strings)
- argv: script arguments (list of strings)
- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum's avatar
Guido van Rossum committed
15 16
*/

Guido van Rossum's avatar
Guido van Rossum committed
17
#include "Python.h"
18 19
#include "compile.h"
#include "frameobject.h"
Guido van Rossum's avatar
Guido van Rossum committed
20

21
#include "osdefs.h"
Guido van Rossum's avatar
Guido van Rossum committed
22

23
#ifdef HAVE_UNISTD_H
24 25 26
#include <unistd.h>
#endif

Guido van Rossum's avatar
Guido van Rossum committed
27
#ifdef MS_COREDLL
28
extern void *PyWin_DLLhModule;
29 30
/* A string loaded from the DLL at startup: */
extern const char *PyWin_DLLVersionString;
31 32
#endif

Guido van Rossum's avatar
Guido van Rossum committed
33
PyObject *
34
PySys_GetObject(char *name)
Guido van Rossum's avatar
Guido van Rossum committed
35
{
36 37
	PyThreadState *tstate = PyThreadState_Get();
	PyObject *sd = tstate->interp->sysdict;
38 39
	if (sd == NULL)
		return NULL;
40
	return PyDict_GetItemString(sd, name);
Guido van Rossum's avatar
Guido van Rossum committed
41 42 43
}

FILE *
44
PySys_GetFile(char *name, FILE *def)
Guido van Rossum's avatar
Guido van Rossum committed
45 46
{
	FILE *fp = NULL;
Guido van Rossum's avatar
Guido van Rossum committed
47 48 49
	PyObject *v = PySys_GetObject(name);
	if (v != NULL && PyFile_Check(v))
		fp = PyFile_AsFile(v);
Guido van Rossum's avatar
Guido van Rossum committed
50 51 52 53 54 55
	if (fp == NULL)
		fp = def;
	return fp;
}

int
56
PySys_SetObject(char *name, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
57
{
58 59
	PyThreadState *tstate = PyThreadState_Get();
	PyObject *sd = tstate->interp->sysdict;
60
	if (v == NULL) {
61
		if (PyDict_GetItemString(sd, name) == NULL)
62 63
			return 0;
		else
64
			return PyDict_DelItemString(sd, name);
65
	}
Guido van Rossum's avatar
Guido van Rossum committed
66
	else
67
		return PyDict_SetItemString(sd, name, v);
Guido van Rossum's avatar
Guido van Rossum committed
68 69
}

Moshe Zadka's avatar
Moshe Zadka committed
70
static PyObject *
71
sys_displayhook(PyObject *self, PyObject *o)
Moshe Zadka's avatar
Moshe Zadka committed
72
{
73
	PyObject *outf;
Moshe Zadka's avatar
Moshe Zadka committed
74 75 76 77
	PyInterpreterState *interp = PyThreadState_Get()->interp;
	PyObject *modules = interp->modules;
	PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");

78 79 80 81 82
	if (builtins == NULL) {
		PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
		return NULL;
	}

Moshe Zadka's avatar
Moshe Zadka committed
83 84 85 86 87 88 89 90 91 92 93
	/* Print value except if None */
	/* After printing, also assign to '_' */
	/* Before, set '_' to None to avoid recursion */
	if (o == Py_None) {
		Py_INCREF(Py_None);
		return Py_None;
	}
	if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
		return NULL;
	if (Py_FlushLine() != 0)
		return NULL;
94 95
	outf = PySys_GetObject("stdout");
	if (outf == NULL) {
Moshe Zadka's avatar
Moshe Zadka committed
96 97 98
		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
		return NULL;
	}
99
	if (PyFile_WriteObject(o, outf, 0) != 0)
Moshe Zadka's avatar
Moshe Zadka committed
100
		return NULL;
101
	PyFile_SoftSpace(outf, 1);
Moshe Zadka's avatar
Moshe Zadka committed
102 103 104 105 106 107 108 109 110
	if (Py_FlushLine() != 0)
		return NULL;
	if (PyObject_SetAttrString(builtins, "_", o) != 0)
		return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

static char displayhook_doc[] =
Ka-Ping Yee's avatar
Ka-Ping Yee committed
111
"displayhook(object) -> None\n"
Moshe Zadka's avatar
Moshe Zadka committed
112
"\n"
Ka-Ping Yee's avatar
Ka-Ping Yee committed
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
"Print an object to sys.stdout and also save it in __builtin__._\n";

static PyObject *
sys_excepthook(PyObject* self, PyObject* args)
{
	PyObject *exc, *value, *tb;
	if (!PyArg_ParseTuple(args, "OOO:excepthook", &exc, &value, &tb))
		return NULL;
	PyErr_Display(exc, value, tb);
	Py_INCREF(Py_None);
	return Py_None;
}

static char excepthook_doc[] =
"excepthook(exctype, value, traceback) -> None\n"
"\n"
"Handle an exception by displaying it with a traceback on sys.stderr.\n";
Moshe Zadka's avatar
Moshe Zadka committed
130

131
static PyObject *
132
sys_exc_info(PyObject *self)
133 134 135 136 137 138 139 140 141 142 143
{
	PyThreadState *tstate;
	tstate = PyThreadState_Get();
	return Py_BuildValue(
		"(OOO)",
		tstate->exc_type != NULL ? tstate->exc_type : Py_None,
		tstate->exc_value != NULL ? tstate->exc_value : Py_None,
		tstate->exc_traceback != NULL ?
			tstate->exc_traceback : Py_None);
}

144 145 146 147 148 149
static char exc_info_doc[] =
"exc_info() -> (type, value, traceback)\n\
\n\
Return information about the exception that is currently being handled.\n\
This should be called from inside an except clause only.";

Guido van Rossum's avatar
Guido van Rossum committed
150
static PyObject *
151
sys_exit(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
152
{
153
	/* Raise SystemExit so callers may catch it or clean up. */
Guido van Rossum's avatar
Guido van Rossum committed
154
	PyErr_SetObject(PyExc_SystemExit, args);
155
	return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
156 157
}

158 159 160 161 162 163 164 165 166
static char exit_doc[] =
"exit([status])\n\
\n\
Exit the interpreter by raising SystemExit(status).\n\
If the status is omitted or None, it defaults to zero (i.e., success).\n\
If the status numeric, it will be used as the system exit status.\n\
If it is another kind of object, it will be printed and the system\n\
exit status will be one (i.e., failure).";

167
static PyObject *
168
sys_getdefaultencoding(PyObject *self)
169 170 171 172
{
	return PyString_FromString(PyUnicode_GetDefaultEncoding());
}

173 174
static char getdefaultencoding_doc[] =
"getdefaultencoding() -> string\n\
175 176 177 178
\n\
Return the current default string encoding used by the Unicode \n\
implementation.";

179 180
#ifdef Py_USING_UNICODE

181
static PyObject *
182
sys_setdefaultencoding(PyObject *self, PyObject *args)
183 184
{
	char *encoding;
185
	if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
186 187 188 189 190 191 192
		return NULL;
	if (PyUnicode_SetDefaultEncoding(encoding))
	    	return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

193 194
static char setdefaultencoding_doc[] =
"setdefaultencoding(encoding)\n\
195 196 197
\n\
Set the current default string encoding used by the Unicode implementation.";

198 199
#endif

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
/*
 * Cached interned string objects used for calling the profile and
 * trace functions.  Initialized by trace_init().
 */
static PyObject *whatstrings[4] = {NULL, NULL, NULL, NULL};

static int
trace_init(void)
{
	static char *whatnames[4] = {"call", "exception", "line", "return"};
	PyObject *name;
	int i;
	for (i = 0; i < 4; ++i) {
		if (whatstrings[i] == NULL) {
			name = PyString_InternFromString(whatnames[i]);
			if (name == NULL)
				return -1;
			whatstrings[i] = name;
                }
	}
	return 0;
}


static PyObject *
call_trampoline(PyThreadState *tstate, PyObject* callback,
		PyFrameObject *frame, int what, PyObject *arg)
{
	PyObject *args = PyTuple_New(3);
	PyObject *whatstr;
	PyObject *result;

	if (args == NULL)
		return NULL;
	Py_INCREF(frame);
	whatstr = whatstrings[what];
	Py_INCREF(whatstr);
	if (arg == NULL)
		arg = Py_None;
	Py_INCREF(arg);
	PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
	PyTuple_SET_ITEM(args, 1, whatstr);
	PyTuple_SET_ITEM(args, 2, arg);

	/* call the Python-level function */
	PyFrame_FastToLocals(frame);
	result = PyEval_CallObject(callback, args);
	PyFrame_LocalsToFast(frame, 1);
	if (result == NULL)
		PyTraceBack_Here(frame);

	/* cleanup */
	Py_DECREF(args);
	return result;
}

static int
profile_trampoline(PyObject *self, PyFrameObject *frame,
		   int what, PyObject *arg)
{
	PyThreadState *tstate = frame->f_tstate;
	PyObject *result;

263 264
	if (arg == NULL)
		arg = Py_None;
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
	result = call_trampoline(tstate, self, frame, what, arg);
	if (result == NULL) {
		PyEval_SetProfile(NULL, NULL);
		return -1;
	}
	Py_DECREF(result);
	return 0;
}

static int
trace_trampoline(PyObject *self, PyFrameObject *frame,
		 int what, PyObject *arg)
{
	PyThreadState *tstate = frame->f_tstate;
	PyObject *callback;
	PyObject *result;

	if (what == PyTrace_CALL)
		callback = self;
	else
		callback = frame->f_trace;
	if (callback == NULL)
		return 0;
	result = call_trampoline(tstate, callback, frame, what, arg);
	if (result == NULL) {
		PyEval_SetTrace(NULL, NULL);
		Py_XDECREF(frame->f_trace);
		frame->f_trace = NULL;
		return -1;
	}
	if (result != Py_None) {
		PyObject *temp = frame->f_trace;
		frame->f_trace = NULL;
		Py_XDECREF(temp);
		frame->f_trace = result;
	}
	else {
		Py_DECREF(result);
	}
	return 0;
}
306

Guido van Rossum's avatar
Guido van Rossum committed
307
static PyObject *
308
sys_settrace(PyObject *self, PyObject *args)
309
{
310
	if (trace_init() == -1)
311
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
312
	if (args == Py_None)
313
		PyEval_SetTrace(NULL, NULL);
314
	else
315
		PyEval_SetTrace(trace_trampoline, args);
Guido van Rossum's avatar
Guido van Rossum committed
316 317
	Py_INCREF(Py_None);
	return Py_None;
318 319
}

320 321 322 323 324 325
static char settrace_doc[] =
"settrace(function)\n\
\n\
Set the global debug tracing function.  It will be called on each\n\
function call.  See the debugger chapter in the library manual.";

Guido van Rossum's avatar
Guido van Rossum committed
326
static PyObject *
327
sys_setprofile(PyObject *self, PyObject *args)
328
{
329
	if (trace_init() == -1)
330
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
331
	if (args == Py_None)
332
		PyEval_SetProfile(NULL, NULL);
333
	else
334
		PyEval_SetProfile(profile_trampoline, args);
Guido van Rossum's avatar
Guido van Rossum committed
335 336
	Py_INCREF(Py_None);
	return Py_None;
337 338
}

339 340 341 342 343 344
static char setprofile_doc[] =
"setprofile(function)\n\
\n\
Set the profiling function.  It will be called on each function call\n\
and return.  See the profiler chapter in the library manual.";

Guido van Rossum's avatar
Guido van Rossum committed
345
static PyObject *
346
sys_setcheckinterval(PyObject *self, PyObject *args)
347
{
348
	PyThreadState *tstate = PyThreadState_Get();
349
	if (!PyArg_ParseTuple(args, "i:setcheckinterval", &tstate->interp->checkinterval))
350
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
351 352
	Py_INCREF(Py_None);
	return Py_None;
353 354
}

355 356 357 358 359 360
static char setcheckinterval_doc[] =
"setcheckinterval(n)\n\
\n\
Tell the Python interpreter to check for asynchronous events every\n\
n instructions.  This also affects how often thread switches occur.";

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385
static PyObject *
sys_setrecursionlimit(PyObject *self, PyObject *args)
{
	int new_limit;
	if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
		return NULL;
	if (new_limit <= 0) {
		PyErr_SetString(PyExc_ValueError, 
				"recursion limit must be positive");  
		return NULL;
	}
	Py_SetRecursionLimit(new_limit);
	Py_INCREF(Py_None);
	return Py_None;
}

static char setrecursionlimit_doc[] =
"setrecursionlimit(n)\n\
\n\
Set the maximum depth of the Python interpreter stack to n.  This\n\
limit prevents infinite recursion from causing an overflow of the C\n\
stack and crashing Python.  The highest possible limit is platform-\n\
dependent.";

static PyObject *
386
sys_getrecursionlimit(PyObject *self)
387 388 389 390 391 392 393 394 395 396 397
{
	return PyInt_FromLong(Py_GetRecursionLimit());
}

static char getrecursionlimit_doc[] =
"getrecursionlimit()\n\
\n\
Return the current value of the recursion limit, the maximum depth\n\
of the Python interpreter stack.  This limit prevents infinite\n\
recursion from causing an overflow of the C stack and crashing Python.";

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
#ifdef HAVE_DLOPEN
static PyObject *
sys_setdlopenflags(PyObject *self, PyObject *args)
{
	int new_val;
        PyThreadState *tstate = PyThreadState_Get();
	if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
		return NULL;
        if (!tstate)
		return NULL;
        tstate->interp->dlopenflags = new_val;
	Py_INCREF(Py_None);
	return Py_None;
}

static char setdlopenflags_doc[] =
"setdlopenflags(n) -> None\n\
\n\
Set the flags that will be used for dlopen() calls. Among other\n\
things, this will enable a lazy resolving of symbols when imporing\n\
a module, if called as sys.setdlopenflags(0)\n\
To share symols across extension modules, call as\n\
sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)";

static PyObject *
sys_getdlopenflags(PyObject *self, PyObject *args)
{
        PyThreadState *tstate = PyThreadState_Get();
        if (!tstate)
		return NULL;
        return PyInt_FromLong(tstate->interp->dlopenflags);
}

static char getdlopenflags_doc[] =
"getdlopenflags() -> int\n\
\n\
Return the current value of the flags that are used for dlopen()\n\
calls. The flag constants are defined in the dl module.";
#endif

438 439 440 441
#ifdef USE_MALLOPT
/* Link with -lmalloc (or -lmpc) on an SGI */
#include <malloc.h>

Guido van Rossum's avatar
Guido van Rossum committed
442
static PyObject *
443
sys_mdebug(PyObject *self, PyObject *args)
444 445
{
	int flag;
446
	if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
447 448
		return NULL;
	mallopt(M_DEBUG, flag);
Guido van Rossum's avatar
Guido van Rossum committed
449 450
	Py_INCREF(Py_None);
	return Py_None;
451 452 453
}
#endif /* USE_MALLOPT */

Guido van Rossum's avatar
Guido van Rossum committed
454
static PyObject *
455
sys_getrefcount(PyObject *self, PyObject *args)
456
{
Guido van Rossum's avatar
Guido van Rossum committed
457
	PyObject *arg;
458
	if (!PyArg_ParseTuple(args, "O:getrefcount", &arg))
459
		return NULL;
460
	return PyInt_FromLong(arg->ob_refcnt);
461 462
}

463 464
#ifdef Py_TRACE_REFS
static PyObject *
465
sys_gettotalrefcount(PyObject *self)
466 467 468 469 470 471 472
{
	extern long _Py_RefTotal;
	return PyInt_FromLong(_Py_RefTotal);
}

#endif /* Py_TRACE_REFS */

473 474 475 476 477 478
static char getrefcount_doc[] =
"getrefcount(object) -> integer\n\
\n\
Return the current reference count for the object.  This includes the\n\
temporary reference in the argument list, so it is at least 2.";

479 480
#ifdef COUNT_ALLOCS
static PyObject *
481
sys_getcounts(PyObject *self)
482
{
483
	extern PyObject *get_counts(void);
484 485 486 487 488

	return get_counts();
}
#endif

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
static char getframe_doc[] =
"_getframe([depth]) -> frameobject\n\
\n\
Return a frame object from the call stack.  If optional integer depth is\n\
given, return the frame object that many calls below the top of the stack.\n\
If that is deeper than the call stack, ValueError is raised.  The default\n\
for depth is zero, returning the frame at the top of the call stack.\n\
\n\
This function should be used for internal and specialized\n\
purposes only.";

static PyObject *
sys_getframe(PyObject *self, PyObject *args)
{
	PyFrameObject *f = PyThreadState_Get()->frame;
	int depth = -1;

	if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
		return NULL;

	while (depth > 0 && f != NULL) {
		f = f->f_back;
		--depth;
	}
	if (f == NULL) {
		PyErr_SetString(PyExc_ValueError,
				"call stack is not deep enough");
		return NULL;
	}
	Py_INCREF(f);
	return (PyObject*)f;
}


523
#ifdef Py_TRACE_REFS
524
/* Defined in objects.c because it uses static globals if that file */
525
extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
526
#endif
527

528 529
#ifdef DYNAMIC_EXECUTION_PROFILE
/* Defined in ceval.c because it uses static globals if that file */
530
extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
531 532
#endif

Guido van Rossum's avatar
Guido van Rossum committed
533
static PyMethodDef sys_methods[] = {
534
	/* Might as well keep this in alphabetic order */
535 536 537 538
	{"displayhook",	sys_displayhook, METH_O, displayhook_doc},
	{"exc_info",	(PyCFunction)sys_exc_info, METH_NOARGS, exc_info_doc},
	{"excepthook",	sys_excepthook, METH_VARARGS, excepthook_doc},
	{"exit",	sys_exit, METH_OLDARGS, exit_doc},
539
#ifdef Py_USING_UNICODE
540
	{"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, METH_NOARGS,
541
	 getdefaultencoding_doc}, 
542
#endif
543
#ifdef HAVE_DLOPEN
544 545
	{"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, 
	 getdlopenflags_doc},
546
#endif
547
#ifdef COUNT_ALLOCS
548
	{"getcounts",	(PyCFunction)sys_getcounts, METH_NOARGS},
549
#endif
550
#ifdef DYNAMIC_EXECUTION_PROFILE
551
	{"getdxp",	_Py_GetDXProfile, METH_VARARGS},
552
#endif
553
#ifdef Py_TRACE_REFS
554 555
	{"getobjects",	_Py_GetObjects, METH_VARARGS},
	{"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
556
#endif
557 558
	{"getrefcount",	sys_getrefcount, METH_VARARGS, getrefcount_doc},
	{"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
559
	 getrecursionlimit_doc},
560
	{"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
561
#ifdef USE_MALLOPT
562
	{"mdebug",	sys_mdebug, METH_VARARGS},
563
#endif
564
#ifdef Py_USING_UNICODE
565
	{"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
566
	 setdefaultencoding_doc}, 
567
#endif
568
	{"setcheckinterval",	sys_setcheckinterval, METH_VARARGS,
569
	 setcheckinterval_doc}, 
570
#ifdef HAVE_DLOPEN
571 572
	{"setdlopenflags", sys_setdlopenflags, METH_VARARGS, 
	 setdlopenflags_doc},
573
#endif
574 575
	{"setprofile",	sys_setprofile, METH_OLDARGS, setprofile_doc},
	{"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
576
	 setrecursionlimit_doc},
577
	{"settrace",	sys_settrace, METH_OLDARGS, settrace_doc},
Guido van Rossum's avatar
Guido van Rossum committed
578 579 580
	{NULL,		NULL}		/* sentinel */
};

Guido van Rossum's avatar
Guido van Rossum committed
581
static PyObject *
582
list_builtin_module_names(void)
583
{
Guido van Rossum's avatar
Guido van Rossum committed
584
	PyObject *list = PyList_New(0);
585 586 587
	int i;
	if (list == NULL)
		return NULL;
588
	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
589
		PyObject *name = PyString_FromString(
590
			PyImport_Inittab[i].name);
591 592
		if (name == NULL)
			break;
Guido van Rossum's avatar
Guido van Rossum committed
593 594
		PyList_Append(list, name);
		Py_DECREF(name);
595
	}
Guido van Rossum's avatar
Guido van Rossum committed
596 597
	if (PyList_Sort(list) != 0) {
		Py_DECREF(list);
Guido van Rossum's avatar
Guido van Rossum committed
598 599
		list = NULL;
	}
600
	if (list) {
Guido van Rossum's avatar
Guido van Rossum committed
601 602
		PyObject *v = PyList_AsTuple(list);
		Py_DECREF(list);
603 604
		list = v;
	}
605 606 607
	return list;
}

608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635
static PyObject *warnoptions = NULL;

void
PySys_ResetWarnOptions(void)
{
	if (warnoptions == NULL || !PyList_Check(warnoptions))
		return;
	PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
}

void
PySys_AddWarnOption(char *s)
{
	PyObject *str;

	if (warnoptions == NULL || !PyList_Check(warnoptions)) {
		Py_XDECREF(warnoptions);
		warnoptions = PyList_New(0);
		if (warnoptions == NULL)
			return;
	}
	str = PyString_FromString(s);
	if (str != NULL) {
		PyList_Append(warnoptions, str);
		Py_DECREF(str);
	}
}

636 637 638 639
/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
   Two literals concatenated works just fine.  If you have a K&R compiler
   or other abomination that however *does* understand longer strings,
   get rid of the !!! comment in the middle and the quotes that surround it. */
640 641 642 643 644 645 646 647 648
static char sys_doc[] =
"This module provides access to some objects used or maintained by the\n\
interpreter and to functions that interact strongly with the interpreter.\n\
\n\
Dynamic objects:\n\
\n\
argv -- command line arguments; argv[0] is the script pathname if known\n\
path -- module search path; path[0] is the script directory, else ''\n\
modules -- dictionary of loaded modules\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
649 650 651 652 653 654 655 656
\n\
displayhook -- called to show results in an interactive session\n\
excepthook -- called to handle any uncaught exception other than SystemExit\n\
  To customize printing in an interactive session or to install a custom\n\
  top-level exception handler, assign other functions to replace these.\n\
\n\
exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
  Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
657 658 659 660
\n\
stdin -- standard input file object; used by raw_input() and input()\n\
stdout -- standard output file object; used by the print statement\n\
stderr -- standard error object; used for error messages\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
661 662
  By assigning other file objects (or objects that behave like files)\n\
  to these, it is possible to redirect all of the interpreter's I/O.\n\
663 664 665 666 667 668 669 670 671 672 673 674
\n\
last_type -- type of last uncaught exception\n\
last_value -- value of last uncaught exception\n\
last_traceback -- traceback of last uncaught exception\n\
  These three are only available in an interactive session after a\n\
  traceback has been printed.\n\
\n\
exc_type -- type of exception currently being handled\n\
exc_value -- value of exception currently being handled\n\
exc_traceback -- traceback of exception currently being handled\n\
  The function exc_info() should be used instead of these three,\n\
  because it is thread-safe.\n\
675 676
"
#ifndef MS_WIN16
Ka-Ping Yee's avatar
Ka-Ping Yee committed
677
/* concatenating string here */
678
"\n\
679 680 681
Static objects:\n\
\n\
maxint -- the largest supported integer (the smallest is -maxint-1)\n\
682
maxunicode -- the largest supported character\n\
683
builtin_module_names -- tuple of module names built into this intepreter\n\
684 685 686
version -- the version of this interpreter as a string\n\
version_info -- version information as a tuple\n\
hexversion -- version information encoded as a single integer\n\
687 688 689 690 691
copyright -- copyright notice pertaining to this interpreter\n\
platform -- platform identifier\n\
executable -- pathname of this Python interpreter\n\
prefix -- prefix used to find the Python library\n\
exec_prefix -- prefix used to find the machine-specific Python library\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
692 693 694 695
"
#ifdef MS_WINDOWS
/* concatenating string here */
"dllhandle -- [Windows only] integer handle of the Python DLL\n\
696
winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
697 698 699 700 701 702 703
"
#endif /* MS_WINDOWS */
"__stdin__ -- the original stdin; don't touch!\n\
__stdout__ -- the original stdout; don't touch!\n\
__stderr__ -- the original stderr; don't touch!\n\
__displayhook__ -- the original displayhook; don't touch!\n\
__excepthook__ -- the original excepthook; don't touch!\n\
704 705 706
\n\
Functions:\n\
\n\
Moshe Zadka's avatar
Moshe Zadka committed
707
displayhook() -- print an object to the screen, and save it in __builtin__._\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
708
excepthook() -- print an exception and its traceback to sys.stderr\n\
709 710
exc_info() -- return thread-safe information about the current exception\n\
exit() -- exit the interpreter by raising SystemExit\n\
711
getdlopenflags() -- returns flags to be used for dlopen() calls\n\
712
getrefcount() -- return the reference count for an object (plus one :-)\n\
713
getrecursionlimit() -- return the max recursion depth for the interpreter\n\
714
setcheckinterval() -- control how often the interpreter checks for events\n\
715
setdlopenflags() -- set the flags to be used for dlopen() calls\n\
716
setprofile() -- set the global profiling function\n\
717
setrecursionlimit() -- set the max recursion depth for the interpreter\n\
718
settrace() -- set the global debug tracing function\n\
719
"
Ka-Ping Yee's avatar
Ka-Ping Yee committed
720
#endif /* MS_WIN16 */
721
/* end of sys_doc */ ;
722

723
PyObject *
724
_PySys_Init(void)
Guido van Rossum's avatar
Guido van Rossum committed
725
{
726 727
	PyObject *m, *v, *sysdict;
	PyObject *sysin, *sysout, *syserr;
728
	char *s;
729

730
	m = Py_InitModule3("sys", sys_methods, sys_doc);
Guido van Rossum's avatar
Guido van Rossum committed
731
	sysdict = PyModule_GetDict(m);
732 733 734 735

	sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
	sysout = PyFile_FromFile(stdout, "<stdout>", "w", NULL);
	syserr = PyFile_FromFile(stderr, "<stderr>", "w", NULL);
Guido van Rossum's avatar
Guido van Rossum committed
736
	if (PyErr_Occurred())
737
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
738 739 740
	PyDict_SetItemString(sysdict, "stdin", sysin);
	PyDict_SetItemString(sysdict, "stdout", sysout);
	PyDict_SetItemString(sysdict, "stderr", syserr);
741 742 743 744
	/* Make backup copies for cleanup */
	PyDict_SetItemString(sysdict, "__stdin__", sysin);
	PyDict_SetItemString(sysdict, "__stdout__", sysout);
	PyDict_SetItemString(sysdict, "__stderr__", syserr);
Ka-Ping Yee's avatar
Ka-Ping Yee committed
745 746 747 748
	PyDict_SetItemString(sysdict, "__displayhook__",
                             PyDict_GetItemString(sysdict, "displayhook"));
	PyDict_SetItemString(sysdict, "__excepthook__",
                             PyDict_GetItemString(sysdict, "excepthook"));
749 750 751
	Py_XDECREF(sysin);
	Py_XDECREF(sysout);
	Py_XDECREF(syserr);
Guido van Rossum's avatar
Guido van Rossum committed
752 753
	PyDict_SetItemString(sysdict, "version",
			     v = PyString_FromString(Py_GetVersion()));
754
	Py_XDECREF(v);
755 756
	PyDict_SetItemString(sysdict, "hexversion",
			     v = PyInt_FromLong(PY_VERSION_HEX));
Guido van Rossum's avatar
Guido van Rossum committed
757
	Py_XDECREF(v);
758 759 760 761 762
	/*
	 * These release level checks are mutually exclusive and cover
	 * the field, so don't get too fancy with the pre-processor!
	 */
#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
763
	s = "alpha";
764
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
765
	s = "beta";
766
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
767
	s = "candidate";
768
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
769
	s = "final";
770
#endif
771
	PyDict_SetItemString(sysdict, "version_info",
772
			     v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
773
					       PY_MINOR_VERSION,
774
					       PY_MICRO_VERSION, s,
775
					       PY_RELEASE_SERIAL));
776
	Py_XDECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
777 778 779 780 781 782
	PyDict_SetItemString(sysdict, "copyright",
			     v = PyString_FromString(Py_GetCopyright()));
	Py_XDECREF(v);
	PyDict_SetItemString(sysdict, "platform",
			     v = PyString_FromString(Py_GetPlatform()));
	Py_XDECREF(v);
783 784 785
	PyDict_SetItemString(sysdict, "executable",
			     v = PyString_FromString(Py_GetProgramFullPath()));
	Py_XDECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
786 787 788 789 790 791 792 793 794
	PyDict_SetItemString(sysdict, "prefix",
			     v = PyString_FromString(Py_GetPrefix()));
	Py_XDECREF(v);
	PyDict_SetItemString(sysdict, "exec_prefix",
		   v = PyString_FromString(Py_GetExecPrefix()));
	Py_XDECREF(v);
	PyDict_SetItemString(sysdict, "maxint",
			     v = PyInt_FromLong(PyInt_GetMax()));
	Py_XDECREF(v);
795
#ifdef Py_USING_UNICODE
796 797 798
	PyDict_SetItemString(sysdict, "maxunicode",
			     v = PyInt_FromLong(PyUnicode_GetMax()));
	Py_XDECREF(v);
799
#endif
Guido van Rossum's avatar
Guido van Rossum committed
800
	PyDict_SetItemString(sysdict, "builtin_module_names",
801
		   v = list_builtin_module_names());
Guido van Rossum's avatar
Guido van Rossum committed
802
	Py_XDECREF(v);
803 804 805 806
	{
		/* Assumes that longs are at least 2 bytes long.
		   Should be safe! */
		unsigned long number = 1;
807
		char *value;
808 809 810

		s = (char *) &number;
		if (s[0] == 0)
811
			value = "big";
812
		else
813 814
			value = "little";
		PyDict_SetItemString(sysdict, "byteorder",
815 816
				     v = PyString_FromString(value));
		Py_XDECREF(v);
817
	}
818
#ifdef MS_COREDLL
Guido van Rossum's avatar
Guido van Rossum committed
819
	PyDict_SetItemString(sysdict, "dllhandle",
820
			     v = PyLong_FromVoidPtr(PyWin_DLLhModule));
Guido van Rossum's avatar
Guido van Rossum committed
821 822
	Py_XDECREF(v);
	PyDict_SetItemString(sysdict, "winver",
823
			     v = PyString_FromString(PyWin_DLLVersionString));
Guido van Rossum's avatar
Guido van Rossum committed
824
	Py_XDECREF(v);
825
#endif
826 827 828 829 830 831 832
	if (warnoptions == NULL) {
		warnoptions = PyList_New(0);
	}
	else {
		Py_INCREF(warnoptions);
	}
	if (warnoptions != NULL) {
833
		PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
834 835
	}
	
Guido van Rossum's avatar
Guido van Rossum committed
836
	if (PyErr_Occurred())
837 838
		return NULL;
	return m;
839 840
}

Guido van Rossum's avatar
Guido van Rossum committed
841
static PyObject *
842
makepathobject(char *path, int delim)
843
{
Guido van Rossum's avatar
Guido van Rossum committed
844 845
	int i, n;
	char *p;
Guido van Rossum's avatar
Guido van Rossum committed
846
	PyObject *v, *w;
Guido van Rossum's avatar
Guido van Rossum committed
847 848 849 850 851 852 853
	
	n = 1;
	p = path;
	while ((p = strchr(p, delim)) != NULL) {
		n++;
		p++;
	}
Guido van Rossum's avatar
Guido van Rossum committed
854
	v = PyList_New(n);
Guido van Rossum's avatar
Guido van Rossum committed
855 856 857 858 859 860
	if (v == NULL)
		return NULL;
	for (i = 0; ; i++) {
		p = strchr(path, delim);
		if (p == NULL)
			p = strchr(path, '\0'); /* End of string */
Guido van Rossum's avatar
Guido van Rossum committed
861
		w = PyString_FromStringAndSize(path, (int) (p - path));
Guido van Rossum's avatar
Guido van Rossum committed
862
		if (w == NULL) {
Guido van Rossum's avatar
Guido van Rossum committed
863
			Py_DECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
864
			return NULL;
865
		}
Guido van Rossum's avatar
Guido van Rossum committed
866
		PyList_SetItem(v, i, w);
Guido van Rossum's avatar
Guido van Rossum committed
867 868 869
		if (*p == '\0')
			break;
		path = p+1;
870
	}
Guido van Rossum's avatar
Guido van Rossum committed
871
	return v;
Guido van Rossum's avatar
Guido van Rossum committed
872 873 874
}

void
875
PySys_SetPath(char *path)
Guido van Rossum's avatar
Guido van Rossum committed
876
{
Guido van Rossum's avatar
Guido van Rossum committed
877
	PyObject *v;
Guido van Rossum's avatar
Guido van Rossum committed
878
	if ((v = makepathobject(path, DELIM)) == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
879 880 881 882
		Py_FatalError("can't create sys.path");
	if (PySys_SetObject("path", v) != 0)
		Py_FatalError("can't assign sys.path");
	Py_DECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
883 884
}

Guido van Rossum's avatar
Guido van Rossum committed
885
static PyObject *
886
makeargvobject(int argc, char **argv)
Guido van Rossum's avatar
Guido van Rossum committed
887
{
Guido van Rossum's avatar
Guido van Rossum committed
888
	PyObject *av;
889 890 891 892 893 894
	if (argc <= 0 || argv == NULL) {
		/* Ensure at least one (empty) argument is seen */
		static char *empty_argv[1] = {""};
		argv = empty_argv;
		argc = 1;
	}
Guido van Rossum's avatar
Guido van Rossum committed
895
	av = PyList_New(argc);
Guido van Rossum's avatar
Guido van Rossum committed
896
	if (av != NULL) {
897
		int i;
Guido van Rossum's avatar
Guido van Rossum committed
898
		for (i = 0; i < argc; i++) {
Guido van Rossum's avatar
Guido van Rossum committed
899
			PyObject *v = PyString_FromString(argv[i]);
Guido van Rossum's avatar
Guido van Rossum committed
900
			if (v == NULL) {
Guido van Rossum's avatar
Guido van Rossum committed
901
				Py_DECREF(av);
Guido van Rossum's avatar
Guido van Rossum committed
902 903
				av = NULL;
				break;
904
			}
Guido van Rossum's avatar
Guido van Rossum committed
905
			PyList_SetItem(av, i, v);
906 907
		}
	}
Guido van Rossum's avatar
Guido van Rossum committed
908 909 910 911
	return av;
}

void
912
PySys_SetArgv(int argc, char **argv)
Guido van Rossum's avatar
Guido van Rossum committed
913
{
Guido van Rossum's avatar
Guido van Rossum committed
914 915
	PyObject *av = makeargvobject(argc, argv);
	PyObject *path = PySys_GetObject("path");
Guido van Rossum's avatar
Guido van Rossum committed
916
	if (av == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
917 918 919
		Py_FatalError("no mem for sys.argv");
	if (PySys_SetObject("argv", av) != 0)
		Py_FatalError("can't assign sys.argv");
920
	if (path != NULL) {
921
		char *argv0 = argv[0];
922
		char *p = NULL;
923
		int n = 0;
Guido van Rossum's avatar
Guido van Rossum committed
924
		PyObject *a;
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952
#ifdef HAVE_READLINK
		char link[MAXPATHLEN+1];
		char argv0copy[2*MAXPATHLEN+1];
		int nr = 0;
		if (argc > 0 && argv0 != NULL)
			nr = readlink(argv0, link, MAXPATHLEN);
		if (nr > 0) {
			/* It's a symlink */
			link[nr] = '\0';
			if (link[0] == SEP)
				argv0 = link; /* Link to absolute path */
			else if (strchr(link, SEP) == NULL)
				; /* Link without path */
			else {
				/* Must join(dirname(argv0), link) */
				char *q = strrchr(argv0, SEP);
				if (q == NULL)
					argv0 = link; /* argv0 without path */
				else {
					/* Must make a copy */
					strcpy(argv0copy, argv0);
					q = strrchr(argv0copy, SEP);
					strcpy(q+1, link);
					argv0 = argv0copy;
				}
			}
		}
#endif /* HAVE_READLINK */
953
#if SEP == '\\' /* Special case for MS filename syntax */
954
		if (argc > 0 && argv0 != NULL) {
955
			char *q;
956
			p = strrchr(argv0, SEP);
957
			/* Test for alternate separator */
958
			q = strrchr(p ? p : argv0, '/');
959 960 961
			if (q != NULL)
				p = q;
			if (p != NULL) {
962
				n = p + 1 - argv0;
963 964 965 966 967
				if (n > 1 && p[-1] != ':')
					n--; /* Drop trailing separator */
			}
		}
#else /* All other filename syntaxes */
968 969
		if (argc > 0 && argv0 != NULL)
			p = strrchr(argv0, SEP);
970
		if (p != NULL) {
971
#ifndef RISCOS
972
			n = p + 1 - argv0;
973 974 975
#else /* don't include trailing separator */
			n = p - argv0;
#endif /* RISCOS */
976 977 978 979 980 981
#if SEP == '/' /* Special case for Unix filename syntax */
			if (n > 1)
				n--; /* Drop trailing separator */
#endif /* Unix */
		}
#endif /* All others */
Guido van Rossum's avatar
Guido van Rossum committed
982
		a = PyString_FromStringAndSize(argv0, n);
983
		if (a == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
984 985 986 987
			Py_FatalError("no mem for sys.path insertion");
		if (PyList_Insert(path, 0, a) < 0)
			Py_FatalError("sys.path.insert(0) failed");
		Py_DECREF(a);
988
	}
Guido van Rossum's avatar
Guido van Rossum committed
989
	Py_DECREF(av);
Guido van Rossum's avatar
Guido van Rossum committed
990
}
991 992 993 994 995 996 997 998 999 1000


/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
   Adapted from code submitted by Just van Rossum.

   PySys_WriteStdout(format, ...)
   PySys_WriteStderr(format, ...)

      The first function writes to sys.stdout; the second to sys.stderr.  When
      there is a problem, they write to the real (C level) stdout or stderr;
1001
      no exceptions are raised.
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017

      Both take a printf-style format string as their first argument followed
      by a variable length argument list determined by the format string.

      *** WARNING ***

      The format should limit the total size of the formatted output string to
      1000 bytes.  In particular, this means that no unrestricted "%s" formats
      should occur; these should be limited using "%.<N>s where <N> is a
      decimal number calculated so that <N> plus the maximum size of other
      formatted text does not exceed 1000 bytes.  Also watch out for "%f",
      which can print hundreds of digits for very large numbers.

 */

static void
1018
mywrite(char *name, FILE *fp, const char *format, va_list va)
1019 1020
{
	PyObject *file;
1021
	PyObject *error_type, *error_value, *error_traceback;
1022

1023
	PyErr_Fetch(&error_type, &error_value, &error_traceback);
1024 1025 1026 1027 1028
	file = PySys_GetObject(name);
	if (file == NULL || PyFile_AsFile(file) == fp)
		vfprintf(fp, format, va);
	else {
		char buffer[1001];
1029 1030
		if (vsprintf(buffer, format, va) >= sizeof(buffer))
		    Py_FatalError("PySys_WriteStdout/err: buffer overrun");
1031 1032 1033 1034 1035
		if (PyFile_WriteString(buffer, file) != 0) {
			PyErr_Clear();
			fputs(buffer, fp);
		}
	}
1036
	PyErr_Restore(error_type, error_value, error_traceback);
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
}

void
PySys_WriteStdout(const char *format, ...)
{
	va_list va;

	va_start(va, format);
	mywrite("stdout", stdout, format, va);
	va_end(va);
}

void
PySys_WriteStderr(const char *format, ...)
{
	va_list va;

	va_start(va, format);
	mywrite("stderr", stderr, format, va);
	va_end(va);
}