sysmodule.c 29.2 KB
Newer Older
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:
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 24 25 26 27
#ifdef MS_WINDOWS
#define WIN32_LEAN_AND_MEAN
#include "windows.h"
#endif /* MS_WINDOWS */

28
#ifdef MS_COREDLL
29
extern void *PyWin_DLLhModule;
30 31
/* A string loaded from the DLL at startup: */
extern const char *PyWin_DLLVersionString;
32 33
#endif

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

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

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

71
static PyObject *
72
sys_displayhook(PyObject *self, PyObject *o)
73
{
74
	PyObject *outf;
75 76 77 78
	PyInterpreterState *interp = PyThreadState_Get()->interp;
	PyObject *modules = interp->modules;
	PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");

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

84 85 86 87 88 89 90 91 92 93 94
	/* 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;
95 96
	outf = PySys_GetObject("stdout");
	if (outf == NULL) {
97 98 99
		PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
		return NULL;
	}
100
	if (PyFile_WriteObject(o, outf, 0) != 0)
101
		return NULL;
102
	PyFile_SoftSpace(outf, 1);
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;
}

111
PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yee's avatar
Ka-Ping Yee committed
112
"displayhook(object) -> None\n"
113
"\n"
114 115
"Print an object to sys.stdout and also save it in __builtin__._\n"
);
Ka-Ping Yee's avatar
Ka-Ping Yee committed
116 117 118 119 120

static PyObject *
sys_excepthook(PyObject* self, PyObject* args)
{
	PyObject *exc, *value, *tb;
121
	if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
Ka-Ping Yee's avatar
Ka-Ping Yee committed
122 123 124 125 126 127
		return NULL;
	PyErr_Display(exc, value, tb);
	Py_INCREF(Py_None);
	return Py_None;
}

128
PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yee's avatar
Ka-Ping Yee committed
129 130
"excepthook(exctype, value, traceback) -> None\n"
"\n"
131 132
"Handle an exception by displaying it with a traceback on sys.stderr.\n"
);
133

134
static PyObject *
135
sys_exc_info(PyObject *self)
136 137 138 139 140 141 142 143 144 145 146
{
	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);
}

147
PyDoc_STRVAR(exc_info_doc,
148 149 150
"exc_info() -> (type, value, traceback)\n\
\n\
Return information about the exception that is currently being handled.\n\
151 152
This should be called from inside an except clause only."
);
153

Guido van Rossum's avatar
Guido van Rossum committed
154
static PyObject *
155
sys_exit(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
156
{
157 158 159
	PyObject *exit_code = 0;
	if (!PyArg_ParseTuple(args, "|O:exit", &exit_code))
		return NULL;
160
	/* Raise SystemExit so callers may catch it or clean up. */
161
	PyErr_SetObject(PyExc_SystemExit, exit_code);
162
	return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
163 164
}

165
PyDoc_STRVAR(exit_doc,
166 167 168 169
"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\
170
If the status is numeric, it will be used as the system exit status.\n\
171
If it is another kind of object, it will be printed and the system\n\
172 173
exit status will be one (i.e., failure)."
);
174

175 176
#ifdef Py_USING_UNICODE

177
static PyObject *
178
sys_getdefaultencoding(PyObject *self)
179 180 181 182
{
	return PyString_FromString(PyUnicode_GetDefaultEncoding());
}

183
PyDoc_STRVAR(getdefaultencoding_doc,
184
"getdefaultencoding() -> string\n\
185 186
\n\
Return the current default string encoding used by the Unicode \n\
187 188
implementation."
);
189 190

static PyObject *
191
sys_setdefaultencoding(PyObject *self, PyObject *args)
192 193
{
	char *encoding;
194
	if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
195 196 197 198 199 200 201
		return NULL;
	if (PyUnicode_SetDefaultEncoding(encoding))
	    	return NULL;
	Py_INCREF(Py_None);
	return Py_None;
}

202
PyDoc_STRVAR(setdefaultencoding_doc,
203
"setdefaultencoding(encoding)\n\
204
\n\
205 206
Set the current default string encoding used by the Unicode implementation."
);
207

208 209
#endif

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 263 264 265 266 267 268 269 270 271 272
/*
 * 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;

273 274
	if (arg == NULL)
		arg = Py_None;
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 306 307 308 309 310 311 312 313 314 315
	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;
}
316

Guido van Rossum's avatar
Guido van Rossum committed
317
static PyObject *
318
sys_settrace(PyObject *self, PyObject *args)
319
{
320
	if (trace_init() == -1)
321
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
322
	if (args == Py_None)
323
		PyEval_SetTrace(NULL, NULL);
324
	else
325
		PyEval_SetTrace(trace_trampoline, args);
Guido van Rossum's avatar
Guido van Rossum committed
326 327
	Py_INCREF(Py_None);
	return Py_None;
328 329
}

330
PyDoc_STRVAR(settrace_doc,
331 332 333
"settrace(function)\n\
\n\
Set the global debug tracing function.  It will be called on each\n\
334 335
function call.  See the debugger chapter in the library manual."
);
336

Guido van Rossum's avatar
Guido van Rossum committed
337
static PyObject *
338
sys_setprofile(PyObject *self, PyObject *args)
339
{
340
	if (trace_init() == -1)
341
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
342
	if (args == Py_None)
343
		PyEval_SetProfile(NULL, NULL);
344
	else
345
		PyEval_SetProfile(profile_trampoline, args);
Guido van Rossum's avatar
Guido van Rossum committed
346 347
	Py_INCREF(Py_None);
	return Py_None;
348 349
}

350
PyDoc_STRVAR(setprofile_doc,
351 352 353
"setprofile(function)\n\
\n\
Set the profiling function.  It will be called on each function call\n\
354 355
and return.  See the profiler chapter in the library manual."
);
356

Guido van Rossum's avatar
Guido van Rossum committed
357
static PyObject *
358
sys_setcheckinterval(PyObject *self, PyObject *args)
359
{
360
	if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
361
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
362 363
	Py_INCREF(Py_None);
	return Py_None;
364 365
}

366
PyDoc_STRVAR(setcheckinterval_doc,
367 368 369
"setcheckinterval(n)\n\
\n\
Tell the Python interpreter to check for asynchronous events every\n\
370 371
n instructions.  This also affects how often thread switches occur."
);
372

373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
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;
}

389
PyDoc_STRVAR(setrecursionlimit_doc,
390 391 392 393 394
"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\
395 396
dependent."
);
397 398

static PyObject *
399
sys_getrecursionlimit(PyObject *self)
400 401 402 403
{
	return PyInt_FromLong(Py_GetRecursionLimit());
}

404
PyDoc_STRVAR(getrecursionlimit_doc,
405 406 407 408
"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\
409
recursion from causing an overflow of the C stack and crashing Python."
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 438 439
#ifdef MS_WINDOWS
PyDoc_STRVAR(getwindowsversion_doc,
"getwindowsversion()\n\
\n\
Return information about the running version of Windows.\n\
The result is a tuple of (major, minor, build, platform, text)\n\
All elements are numbers, except text which is a string.\n\
Platform may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP\n\
"
);

static PyObject *
sys_getwindowsversion(PyObject *self)
{
	OSVERSIONINFO ver;
	ver.dwOSVersionInfoSize = sizeof(ver);
	if (!GetVersionEx(&ver))
		return PyErr_SetFromWindowsErr(0);
	return Py_BuildValue("HHHHs",
	                     ver.dwMajorVersion,
	                     ver.dwMinorVersion,
	                     ver.dwBuildNumber,
	                     ver.dwPlatformId,
	                     ver.szCSDVersion);
}

#endif /* MS_WINDOWS */

440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
#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;
}

455
PyDoc_STRVAR(setdlopenflags_doc,
456 457 458
"setdlopenflags(n) -> None\n\
\n\
Set the flags that will be used for dlopen() calls. Among other\n\
459
things, this will enable a lazy resolving of symbols when importing\n\
460
a module, if called as sys.setdlopenflags(0)\n\
461
To share symbols across extension modules, call as\n\
462 463
sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)"
);
464 465 466 467 468 469 470 471 472 473

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

474
PyDoc_STRVAR(getdlopenflags_doc,
475 476 477
"getdlopenflags() -> int\n\
\n\
Return the current value of the flags that are used for dlopen()\n\
478 479
calls. The flag constants are defined in the dl module."
);
480 481
#endif

482 483 484 485
#ifdef USE_MALLOPT
/* Link with -lmalloc (or -lmpc) on an SGI */
#include <malloc.h>

Guido van Rossum's avatar
Guido van Rossum committed
486
static PyObject *
487
sys_mdebug(PyObject *self, PyObject *args)
488 489
{
	int flag;
490
	if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
491 492
		return NULL;
	mallopt(M_DEBUG, flag);
Guido van Rossum's avatar
Guido van Rossum committed
493 494
	Py_INCREF(Py_None);
	return Py_None;
495 496 497
}
#endif /* USE_MALLOPT */

Guido van Rossum's avatar
Guido van Rossum committed
498
static PyObject *
499
sys_getrefcount(PyObject *self, PyObject *arg)
500
{
501
	return PyInt_FromLong(arg->ob_refcnt);
502 503
}

504
#ifdef Py_REF_DEBUG
505
static PyObject *
506
sys_gettotalrefcount(PyObject *self)
507 508 509 510 511 512
{
	return PyInt_FromLong(_Py_RefTotal);
}

#endif /* Py_TRACE_REFS */

513
PyDoc_STRVAR(getrefcount_doc,
514 515
"getrefcount(object) -> integer\n\
\n\
516 517 518
Return the reference count of object.  The count returned is generally\n\
one higher than you might expect, because it includes the (temporary)\n\
reference as an argument to getrefcount()."
519
);
520

521 522
#ifdef COUNT_ALLOCS
static PyObject *
523
sys_getcounts(PyObject *self)
524
{
525
	extern PyObject *get_counts(void);
526 527 528 529 530

	return get_counts();
}
#endif

531
PyDoc_STRVAR(getframe_doc,
532 533 534 535 536 537 538 539
"_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\
540 541
purposes only."
);
542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565

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;
}


566
#ifdef Py_TRACE_REFS
567
/* Defined in objects.c because it uses static globals if that file */
568
extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
569
#endif
570

571 572
#ifdef DYNAMIC_EXECUTION_PROFILE
/* Defined in ceval.c because it uses static globals if that file */
573
extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
574 575
#endif

Guido van Rossum's avatar
Guido van Rossum committed
576
static PyMethodDef sys_methods[] = {
577
	/* Might as well keep this in alphabetic order */
578 579 580
	{"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},
581
	{"exit",	sys_exit, METH_VARARGS, exit_doc},
582
#ifdef Py_USING_UNICODE
583
	{"getdefaultencoding", (PyCFunction)sys_getdefaultencoding, METH_NOARGS,
584
	 getdefaultencoding_doc}, 
585
#endif
586
#ifdef HAVE_DLOPEN
587 588
	{"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS, 
	 getdlopenflags_doc},
589
#endif
590
#ifdef COUNT_ALLOCS
591
	{"getcounts",	(PyCFunction)sys_getcounts, METH_NOARGS},
592
#endif
593
#ifdef DYNAMIC_EXECUTION_PROFILE
594
	{"getdxp",	_Py_GetDXProfile, METH_VARARGS},
595
#endif
596
#ifdef Py_TRACE_REFS
597
	{"getobjects",	_Py_GetObjects, METH_VARARGS},
598 599
#endif
#ifdef Py_REF_DEBUG
600
	{"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
601
#endif
602
	{"getrefcount",	(PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
603
	{"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
604
	 getrecursionlimit_doc},
605
	{"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
606 607 608 609
#ifdef MS_WINDOWS
	{"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
	 getwindowsversion_doc},
#endif /* MS_WINDOWS */
610
#ifdef USE_MALLOPT
611
	{"mdebug",	sys_mdebug, METH_VARARGS},
612
#endif
613
#ifdef Py_USING_UNICODE
614
	{"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
615
	 setdefaultencoding_doc}, 
616
#endif
617
	{"setcheckinterval",	sys_setcheckinterval, METH_VARARGS,
618
	 setcheckinterval_doc}, 
619
#ifdef HAVE_DLOPEN
620 621
	{"setdlopenflags", sys_setdlopenflags, METH_VARARGS, 
	 setdlopenflags_doc},
622
#endif
623
	{"setprofile",	sys_setprofile, METH_O, setprofile_doc},
624
	{"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
625
	 setrecursionlimit_doc},
626
	{"settrace",	sys_settrace, METH_O, settrace_doc},
Guido van Rossum's avatar
Guido van Rossum committed
627 628 629
	{NULL,		NULL}		/* sentinel */
};

Guido van Rossum's avatar
Guido van Rossum committed
630
static PyObject *
631
list_builtin_module_names(void)
632
{
Guido van Rossum's avatar
Guido van Rossum committed
633
	PyObject *list = PyList_New(0);
634 635 636
	int i;
	if (list == NULL)
		return NULL;
637
	for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
638
		PyObject *name = PyString_FromString(
639
			PyImport_Inittab[i].name);
640 641
		if (name == NULL)
			break;
Guido van Rossum's avatar
Guido van Rossum committed
642 643
		PyList_Append(list, name);
		Py_DECREF(name);
644
	}
Guido van Rossum's avatar
Guido van Rossum committed
645 646
	if (PyList_Sort(list) != 0) {
		Py_DECREF(list);
647 648
		list = NULL;
	}
649
	if (list) {
Guido van Rossum's avatar
Guido van Rossum committed
650 651
		PyObject *v = PyList_AsTuple(list);
		Py_DECREF(list);
652 653
		list = v;
	}
654 655 656
	return list;
}

657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
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);
	}
}

685 686 687 688
/* 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. */
689 690
PyDoc_VAR(sys_doc) =
PyDoc_STR(
691 692 693 694 695 696 697 698
"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
699 700 701 702 703 704 705 706
\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\
707 708 709 710
\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
711 712
  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\
713 714 715 716 717 718 719 720 721 722 723 724
\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\
725
"
726
)
Ka-Ping Yee's avatar
Ka-Ping Yee committed
727
/* concatenating string here */
728
PyDoc_STR(
729
"\n\
730 731 732
Static objects:\n\
\n\
maxint -- the largest supported integer (the smallest is -maxint-1)\n\
733
maxunicode -- the largest supported character\n\
734
builtin_module_names -- tuple of module names built into this interpreter\n\
735 736 737
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\
738 739 740 741 742
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
743
"
744
)
Ka-Ping Yee's avatar
Ka-Ping Yee committed
745 746
#ifdef MS_WINDOWS
/* concatenating string here */
747
PyDoc_STR(
Ka-Ping Yee's avatar
Ka-Ping Yee committed
748
"dllhandle -- [Windows only] integer handle of the Python DLL\n\
749
winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
750
"
751
)
Ka-Ping Yee's avatar
Ka-Ping Yee committed
752
#endif /* MS_WINDOWS */
753
PyDoc_STR(
Ka-Ping Yee's avatar
Ka-Ping Yee committed
754 755 756 757 758
"__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\
759 760 761
\n\
Functions:\n\
\n\
762
displayhook() -- print an object to the screen, and save it in __builtin__._\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
763
excepthook() -- print an exception and its traceback to sys.stderr\n\
764 765
exc_info() -- return thread-safe information about the current exception\n\
exit() -- exit the interpreter by raising SystemExit\n\
766
getdlopenflags() -- returns flags to be used for dlopen() calls\n\
767
getrefcount() -- return the reference count for an object (plus one :-)\n\
768
getrecursionlimit() -- return the max recursion depth for the interpreter\n\
769
setcheckinterval() -- control how often the interpreter checks for events\n\
770
setdlopenflags() -- set the flags to be used for dlopen() calls\n\
771
setprofile() -- set the global profiling function\n\
772
setrecursionlimit() -- set the max recursion depth for the interpreter\n\
773
settrace() -- set the global debug tracing function\n\
774
"
775
)
776
/* end of sys_doc */ ;
777

778
PyObject *
779
_PySys_Init(void)
Guido van Rossum's avatar
Guido van Rossum committed
780
{
781 782
	PyObject *m, *v, *sysdict;
	PyObject *sysin, *sysout, *syserr;
783
	char *s;
784

785
	m = Py_InitModule3("sys", sys_methods, sys_doc);
Guido van Rossum's avatar
Guido van Rossum committed
786
	sysdict = PyModule_GetDict(m);
787 788 789 790

	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
791
	if (PyErr_Occurred())
792
		return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
793 794 795
	PyDict_SetItemString(sysdict, "stdin", sysin);
	PyDict_SetItemString(sysdict, "stdout", sysout);
	PyDict_SetItemString(sysdict, "stderr", syserr);
796 797 798 799
	/* 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
800 801 802 803
	PyDict_SetItemString(sysdict, "__displayhook__",
                             PyDict_GetItemString(sysdict, "displayhook"));
	PyDict_SetItemString(sysdict, "__excepthook__",
                             PyDict_GetItemString(sysdict, "excepthook"));
804 805 806
	Py_XDECREF(sysin);
	Py_XDECREF(sysout);
	Py_XDECREF(syserr);
Guido van Rossum's avatar
Guido van Rossum committed
807 808
	PyDict_SetItemString(sysdict, "version",
			     v = PyString_FromString(Py_GetVersion()));
809
	Py_XDECREF(v);
810 811
	PyDict_SetItemString(sysdict, "hexversion",
			     v = PyInt_FromLong(PY_VERSION_HEX));
Guido van Rossum's avatar
Guido van Rossum committed
812
	Py_XDECREF(v);
813 814 815 816 817
	/*
	 * 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
818
	s = "alpha";
819
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
820
	s = "beta";
821
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
822
	s = "candidate";
823
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
824
	s = "final";
825
#endif
826
	PyDict_SetItemString(sysdict, "version_info",
827
			     v = Py_BuildValue("iiisi", PY_MAJOR_VERSION,
828
					       PY_MINOR_VERSION,
829
					       PY_MICRO_VERSION, s,
830
					       PY_RELEASE_SERIAL));
831
	Py_XDECREF(v);
832 833 834
	PyDict_SetItemString(sysdict, "api_version",
			     v = PyInt_FromLong(PYTHON_API_VERSION));
	Py_XDECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
835 836 837 838 839 840
	PyDict_SetItemString(sysdict, "copyright",
			     v = PyString_FromString(Py_GetCopyright()));
	Py_XDECREF(v);
	PyDict_SetItemString(sysdict, "platform",
			     v = PyString_FromString(Py_GetPlatform()));
	Py_XDECREF(v);
841 842 843
	PyDict_SetItemString(sysdict, "executable",
			     v = PyString_FromString(Py_GetProgramFullPath()));
	Py_XDECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
844 845 846 847 848 849 850 851 852
	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);
853
#ifdef Py_USING_UNICODE
854 855 856
	PyDict_SetItemString(sysdict, "maxunicode",
			     v = PyInt_FromLong(PyUnicode_GetMax()));
	Py_XDECREF(v);
857
#endif
Guido van Rossum's avatar
Guido van Rossum committed
858
	PyDict_SetItemString(sysdict, "builtin_module_names",
859
		   v = list_builtin_module_names());
Guido van Rossum's avatar
Guido van Rossum committed
860
	Py_XDECREF(v);
861 862 863 864
	{
		/* Assumes that longs are at least 2 bytes long.
		   Should be safe! */
		unsigned long number = 1;
865
		char *value;
866 867 868

		s = (char *) &number;
		if (s[0] == 0)
869
			value = "big";
870
		else
871 872
			value = "little";
		PyDict_SetItemString(sysdict, "byteorder",
873 874
				     v = PyString_FromString(value));
		Py_XDECREF(v);
875
	}
876
#ifdef MS_COREDLL
Guido van Rossum's avatar
Guido van Rossum committed
877
	PyDict_SetItemString(sysdict, "dllhandle",
878
			     v = PyLong_FromVoidPtr(PyWin_DLLhModule));
Guido van Rossum's avatar
Guido van Rossum committed
879 880
	Py_XDECREF(v);
	PyDict_SetItemString(sysdict, "winver",
881
			     v = PyString_FromString(PyWin_DLLVersionString));
Guido van Rossum's avatar
Guido van Rossum committed
882
	Py_XDECREF(v);
883
#endif
884 885 886 887 888 889 890
	if (warnoptions == NULL) {
		warnoptions = PyList_New(0);
	}
	else {
		Py_INCREF(warnoptions);
	}
	if (warnoptions != NULL) {
891
		PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
892 893
	}
	
Guido van Rossum's avatar
Guido van Rossum committed
894
	if (PyErr_Occurred())
895 896
		return NULL;
	return m;
897 898
}

Guido van Rossum's avatar
Guido van Rossum committed
899
static PyObject *
900
makepathobject(char *path, int delim)
901
{
Guido van Rossum's avatar
Guido van Rossum committed
902 903
	int i, n;
	char *p;
Guido van Rossum's avatar
Guido van Rossum committed
904
	PyObject *v, *w;
Guido van Rossum's avatar
Guido van Rossum committed
905 906 907 908 909 910 911
	
	n = 1;
	p = path;
	while ((p = strchr(p, delim)) != NULL) {
		n++;
		p++;
	}
Guido van Rossum's avatar
Guido van Rossum committed
912
	v = PyList_New(n);
Guido van Rossum's avatar
Guido van Rossum committed
913 914 915 916 917 918
	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
919
		w = PyString_FromStringAndSize(path, (int) (p - path));
Guido van Rossum's avatar
Guido van Rossum committed
920
		if (w == NULL) {
Guido van Rossum's avatar
Guido van Rossum committed
921
			Py_DECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
922
			return NULL;
923
		}
Guido van Rossum's avatar
Guido van Rossum committed
924
		PyList_SetItem(v, i, w);
Guido van Rossum's avatar
Guido van Rossum committed
925 926 927
		if (*p == '\0')
			break;
		path = p+1;
928
	}
Guido van Rossum's avatar
Guido van Rossum committed
929
	return v;
Guido van Rossum's avatar
Guido van Rossum committed
930 931 932
}

void
933
PySys_SetPath(char *path)
Guido van Rossum's avatar
Guido van Rossum committed
934
{
Guido van Rossum's avatar
Guido van Rossum committed
935
	PyObject *v;
Guido van Rossum's avatar
Guido van Rossum committed
936
	if ((v = makepathobject(path, DELIM)) == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
937 938 939 940
		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
941 942
}

Guido van Rossum's avatar
Guido van Rossum committed
943
static PyObject *
944
makeargvobject(int argc, char **argv)
Guido van Rossum's avatar
Guido van Rossum committed
945
{
Guido van Rossum's avatar
Guido van Rossum committed
946
	PyObject *av;
947 948 949 950 951 952
	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
953
	av = PyList_New(argc);
Guido van Rossum's avatar
Guido van Rossum committed
954
	if (av != NULL) {
955
		int i;
Guido van Rossum's avatar
Guido van Rossum committed
956
		for (i = 0; i < argc; i++) {
Guido van Rossum's avatar
Guido van Rossum committed
957
			PyObject *v = PyString_FromString(argv[i]);
Guido van Rossum's avatar
Guido van Rossum committed
958
			if (v == NULL) {
Guido van Rossum's avatar
Guido van Rossum committed
959
				Py_DECREF(av);
Guido van Rossum's avatar
Guido van Rossum committed
960 961
				av = NULL;
				break;
962
			}
Guido van Rossum's avatar
Guido van Rossum committed
963
			PyList_SetItem(av, i, v);
964 965
		}
	}
Guido van Rossum's avatar
Guido van Rossum committed
966 967 968 969
	return av;
}

void
970
PySys_SetArgv(int argc, char **argv)
Guido van Rossum's avatar
Guido van Rossum committed
971
{
Guido van Rossum's avatar
Guido van Rossum committed
972 973
	PyObject *av = makeargvobject(argc, argv);
	PyObject *path = PySys_GetObject("path");
Guido van Rossum's avatar
Guido van Rossum committed
974
	if (av == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
975 976 977
		Py_FatalError("no mem for sys.argv");
	if (PySys_SetObject("argv", av) != 0)
		Py_FatalError("can't assign sys.argv");
978
	if (path != NULL) {
979
		char *argv0 = argv[0];
980
		char *p = NULL;
981
		int n = 0;
Guido van Rossum's avatar
Guido van Rossum committed
982
		PyObject *a;
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
#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 */
1011
#if SEP == '\\' /* Special case for MS filename syntax */
1012
		if (argc > 0 && argv0 != NULL) {
1013
			char *q;
1014
			p = strrchr(argv0, SEP);
1015
			/* Test for alternate separator */
1016
			q = strrchr(p ? p : argv0, '/');
1017 1018 1019
			if (q != NULL)
				p = q;
			if (p != NULL) {
1020
				n = p + 1 - argv0;
1021 1022 1023 1024 1025
				if (n > 1 && p[-1] != ':')
					n--; /* Drop trailing separator */
			}
		}
#else /* All other filename syntaxes */
1026 1027
		if (argc > 0 && argv0 != NULL)
			p = strrchr(argv0, SEP);
1028
		if (p != NULL) {
1029
#ifndef RISCOS
1030
			n = p + 1 - argv0;
1031 1032 1033
#else /* don't include trailing separator */
			n = p - argv0;
#endif /* RISCOS */
1034 1035 1036 1037 1038 1039
#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
1040
		a = PyString_FromStringAndSize(argv0, n);
1041
		if (a == NULL)
Guido van Rossum's avatar
Guido van Rossum committed
1042 1043 1044 1045
			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);
1046
	}
Guido van Rossum's avatar
Guido van Rossum committed
1047
	Py_DECREF(av);
Guido van Rossum's avatar
Guido van Rossum committed
1048
}
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058


/* 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;
1059
      no exceptions are raised.
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

      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
1076
mywrite(char *name, FILE *fp, const char *format, va_list va)
1077 1078
{
	PyObject *file;
1079
	PyObject *error_type, *error_value, *error_traceback;
1080

1081
	PyErr_Fetch(&error_type, &error_value, &error_traceback);
1082 1083 1084 1085 1086
	file = PySys_GetObject(name);
	if (file == NULL || PyFile_AsFile(file) == fp)
		vfprintf(fp, format, va);
	else {
		char buffer[1001];
1087 1088
		const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
						   format, va);
1089 1090 1091 1092
		if (PyFile_WriteString(buffer, file) != 0) {
			PyErr_Clear();
			fputs(buffer, fp);
		}
1093
		if (written < 0 || written >= sizeof(buffer)) {
1094 1095 1096 1097 1098 1099
			const char *truncated = "... truncated";
			if (PyFile_WriteString(truncated, file) != 0) {
				PyErr_Clear();
				fputs(truncated, fp);
			}
		}
1100
	}
1101
	PyErr_Restore(error_type, error_value, error_traceback);
1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
}

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);
}