Update to 2.7.3
[profile/ivi/python.git] / Python / sysmodule.c
1
2 /* System module */
3
4 /*
5 Various bits of information used by the interpreter are collected in
6 module 'sys'.
7 Function member:
8 - exit(sts): raise SystemExit
9 Data members:
10 - stdin, stdout, stderr: standard file objects
11 - modules: the table of modules (dictionary)
12 - path: module search path (list of strings)
13 - argv: script arguments (list of strings)
14 - ps1, ps2: optional primary and secondary prompts (strings)
15 */
16
17 #include "Python.h"
18 #include "structseq.h"
19 #include "code.h"
20 #include "frameobject.h"
21 #include "eval.h"
22
23 #include "osdefs.h"
24
25 #ifdef MS_WINDOWS
26 #define WIN32_LEAN_AND_MEAN
27 #include "windows.h"
28 #endif /* MS_WINDOWS */
29
30 #ifdef MS_COREDLL
31 extern void *PyWin_DLLhModule;
32 /* A string loaded from the DLL at startup: */
33 extern const char *PyWin_DLLVersionString;
34 #endif
35
36 #ifdef __VMS
37 #include <unixlib.h>
38 #endif
39
40 #ifdef MS_WINDOWS
41 #include <windows.h>
42 #endif
43
44 #ifdef HAVE_LANGINFO_H
45 #include <locale.h>
46 #include <langinfo.h>
47 #endif
48
49 PyObject *
50 PySys_GetObject(char *name)
51 {
52     PyThreadState *tstate = PyThreadState_GET();
53     PyObject *sd = tstate->interp->sysdict;
54     if (sd == NULL)
55         return NULL;
56     return PyDict_GetItemString(sd, name);
57 }
58
59 FILE *
60 PySys_GetFile(char *name, FILE *def)
61 {
62     FILE *fp = NULL;
63     PyObject *v = PySys_GetObject(name);
64     if (v != NULL && PyFile_Check(v))
65         fp = PyFile_AsFile(v);
66     if (fp == NULL)
67         fp = def;
68     return fp;
69 }
70
71 int
72 PySys_SetObject(char *name, PyObject *v)
73 {
74     PyThreadState *tstate = PyThreadState_GET();
75     PyObject *sd = tstate->interp->sysdict;
76     if (v == NULL) {
77         if (PyDict_GetItemString(sd, name) == NULL)
78             return 0;
79         else
80             return PyDict_DelItemString(sd, name);
81     }
82     else
83         return PyDict_SetItemString(sd, name, v);
84 }
85
86 static PyObject *
87 sys_displayhook(PyObject *self, PyObject *o)
88 {
89     PyObject *outf;
90     PyInterpreterState *interp = PyThreadState_GET()->interp;
91     PyObject *modules = interp->modules;
92     PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
93
94     if (builtins == NULL) {
95         PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
96         return NULL;
97     }
98
99     /* Print value except if None */
100     /* After printing, also assign to '_' */
101     /* Before, set '_' to None to avoid recursion */
102     if (o == Py_None) {
103         Py_INCREF(Py_None);
104         return Py_None;
105     }
106     if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
107         return NULL;
108     if (Py_FlushLine() != 0)
109         return NULL;
110     outf = PySys_GetObject("stdout");
111     if (outf == NULL) {
112         PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
113         return NULL;
114     }
115     if (PyFile_WriteObject(o, outf, 0) != 0)
116         return NULL;
117     PyFile_SoftSpace(outf, 1);
118     if (Py_FlushLine() != 0)
119         return NULL;
120     if (PyObject_SetAttrString(builtins, "_", o) != 0)
121         return NULL;
122     Py_INCREF(Py_None);
123     return Py_None;
124 }
125
126 PyDoc_STRVAR(displayhook_doc,
127 "displayhook(object) -> None\n"
128 "\n"
129 "Print an object to sys.stdout and also save it in __builtin__._\n"
130 );
131
132 static PyObject *
133 sys_excepthook(PyObject* self, PyObject* args)
134 {
135     PyObject *exc, *value, *tb;
136     if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
137         return NULL;
138     PyErr_Display(exc, value, tb);
139     Py_INCREF(Py_None);
140     return Py_None;
141 }
142
143 PyDoc_STRVAR(excepthook_doc,
144 "excepthook(exctype, value, traceback) -> None\n"
145 "\n"
146 "Handle an exception by displaying it with a traceback on sys.stderr.\n"
147 );
148
149 static PyObject *
150 sys_exc_info(PyObject *self, PyObject *noargs)
151 {
152     PyThreadState *tstate;
153     tstate = PyThreadState_GET();
154     return Py_BuildValue(
155         "(OOO)",
156         tstate->exc_type != NULL ? tstate->exc_type : Py_None,
157         tstate->exc_value != NULL ? tstate->exc_value : Py_None,
158         tstate->exc_traceback != NULL ?
159             tstate->exc_traceback : Py_None);
160 }
161
162 PyDoc_STRVAR(exc_info_doc,
163 "exc_info() -> (type, value, traceback)\n\
164 \n\
165 Return information about the most recent exception caught by an except\n\
166 clause in the current stack frame or in an older stack frame."
167 );
168
169 static PyObject *
170 sys_exc_clear(PyObject *self, PyObject *noargs)
171 {
172     PyThreadState *tstate;
173     PyObject *tmp_type, *tmp_value, *tmp_tb;
174
175     if (PyErr_WarnPy3k("sys.exc_clear() not supported in 3.x; "
176                        "use except clauses", 1) < 0)
177         return NULL;
178
179     tstate = PyThreadState_GET();
180     tmp_type = tstate->exc_type;
181     tmp_value = tstate->exc_value;
182     tmp_tb = tstate->exc_traceback;
183     tstate->exc_type = NULL;
184     tstate->exc_value = NULL;
185     tstate->exc_traceback = NULL;
186     Py_XDECREF(tmp_type);
187     Py_XDECREF(tmp_value);
188     Py_XDECREF(tmp_tb);
189     /* For b/w compatibility */
190     PySys_SetObject("exc_type", Py_None);
191     PySys_SetObject("exc_value", Py_None);
192     PySys_SetObject("exc_traceback", Py_None);
193     Py_INCREF(Py_None);
194     return Py_None;
195 }
196
197 PyDoc_STRVAR(exc_clear_doc,
198 "exc_clear() -> None\n\
199 \n\
200 Clear global information on the current exception.  Subsequent calls to\n\
201 exc_info() will return (None,None,None) until another exception is raised\n\
202 in the current thread or the execution stack returns to a frame where\n\
203 another exception is being handled."
204 );
205
206 static PyObject *
207 sys_exit(PyObject *self, PyObject *args)
208 {
209     PyObject *exit_code = 0;
210     if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
211         return NULL;
212     /* Raise SystemExit so callers may catch it or clean up. */
213     PyErr_SetObject(PyExc_SystemExit, exit_code);
214     return NULL;
215 }
216
217 PyDoc_STRVAR(exit_doc,
218 "exit([status])\n\
219 \n\
220 Exit the interpreter by raising SystemExit(status).\n\
221 If the status is omitted or None, it defaults to zero (i.e., success).\n\
222 If the status is numeric, it will be used as the system exit status.\n\
223 If it is another kind of object, it will be printed and the system\n\
224 exit status will be one (i.e., failure)."
225 );
226
227 #ifdef Py_USING_UNICODE
228
229 static PyObject *
230 sys_getdefaultencoding(PyObject *self)
231 {
232     return PyString_FromString(PyUnicode_GetDefaultEncoding());
233 }
234
235 PyDoc_STRVAR(getdefaultencoding_doc,
236 "getdefaultencoding() -> string\n\
237 \n\
238 Return the current default string encoding used by the Unicode \n\
239 implementation."
240 );
241
242 static PyObject *
243 sys_setdefaultencoding(PyObject *self, PyObject *args)
244 {
245     char *encoding;
246     if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
247         return NULL;
248     if (PyUnicode_SetDefaultEncoding(encoding))
249         return NULL;
250     Py_INCREF(Py_None);
251     return Py_None;
252 }
253
254 PyDoc_STRVAR(setdefaultencoding_doc,
255 "setdefaultencoding(encoding)\n\
256 \n\
257 Set the current default string encoding used by the Unicode implementation."
258 );
259
260 static PyObject *
261 sys_getfilesystemencoding(PyObject *self)
262 {
263     if (Py_FileSystemDefaultEncoding)
264         return PyString_FromString(Py_FileSystemDefaultEncoding);
265     Py_INCREF(Py_None);
266     return Py_None;
267 }
268
269 PyDoc_STRVAR(getfilesystemencoding_doc,
270 "getfilesystemencoding() -> string\n\
271 \n\
272 Return the encoding used to convert Unicode filenames in\n\
273 operating system filenames."
274 );
275
276 #endif
277
278 /*
279  * Cached interned string objects used for calling the profile and
280  * trace functions.  Initialized by trace_init().
281  */
282 static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
283
284 static int
285 trace_init(void)
286 {
287     static char *whatnames[7] = {"call", "exception", "line", "return",
288                                     "c_call", "c_exception", "c_return"};
289     PyObject *name;
290     int i;
291     for (i = 0; i < 7; ++i) {
292         if (whatstrings[i] == NULL) {
293             name = PyString_InternFromString(whatnames[i]);
294             if (name == NULL)
295                 return -1;
296             whatstrings[i] = name;
297         }
298     }
299     return 0;
300 }
301
302
303 static PyObject *
304 call_trampoline(PyThreadState *tstate, PyObject* callback,
305                 PyFrameObject *frame, int what, PyObject *arg)
306 {
307     PyObject *args = PyTuple_New(3);
308     PyObject *whatstr;
309     PyObject *result;
310
311     if (args == NULL)
312         return NULL;
313     Py_INCREF(frame);
314     whatstr = whatstrings[what];
315     Py_INCREF(whatstr);
316     if (arg == NULL)
317         arg = Py_None;
318     Py_INCREF(arg);
319     PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
320     PyTuple_SET_ITEM(args, 1, whatstr);
321     PyTuple_SET_ITEM(args, 2, arg);
322
323     /* call the Python-level function */
324     PyFrame_FastToLocals(frame);
325     result = PyEval_CallObject(callback, args);
326     PyFrame_LocalsToFast(frame, 1);
327     if (result == NULL)
328         PyTraceBack_Here(frame);
329
330     /* cleanup */
331     Py_DECREF(args);
332     return result;
333 }
334
335 static int
336 profile_trampoline(PyObject *self, PyFrameObject *frame,
337                    int what, PyObject *arg)
338 {
339     PyThreadState *tstate = frame->f_tstate;
340     PyObject *result;
341
342     if (arg == NULL)
343         arg = Py_None;
344     result = call_trampoline(tstate, self, frame, what, arg);
345     if (result == NULL) {
346         PyEval_SetProfile(NULL, NULL);
347         return -1;
348     }
349     Py_DECREF(result);
350     return 0;
351 }
352
353 static int
354 trace_trampoline(PyObject *self, PyFrameObject *frame,
355                  int what, PyObject *arg)
356 {
357     PyThreadState *tstate = frame->f_tstate;
358     PyObject *callback;
359     PyObject *result;
360
361     if (what == PyTrace_CALL)
362         callback = self;
363     else
364         callback = frame->f_trace;
365     if (callback == NULL)
366         return 0;
367     result = call_trampoline(tstate, callback, frame, what, arg);
368     if (result == NULL) {
369         PyEval_SetTrace(NULL, NULL);
370         Py_XDECREF(frame->f_trace);
371         frame->f_trace = NULL;
372         return -1;
373     }
374     if (result != Py_None) {
375         PyObject *temp = frame->f_trace;
376         frame->f_trace = NULL;
377         Py_XDECREF(temp);
378         frame->f_trace = result;
379     }
380     else {
381         Py_DECREF(result);
382     }
383     return 0;
384 }
385
386 static PyObject *
387 sys_settrace(PyObject *self, PyObject *args)
388 {
389     if (trace_init() == -1)
390         return NULL;
391     if (args == Py_None)
392         PyEval_SetTrace(NULL, NULL);
393     else
394         PyEval_SetTrace(trace_trampoline, args);
395     Py_INCREF(Py_None);
396     return Py_None;
397 }
398
399 PyDoc_STRVAR(settrace_doc,
400 "settrace(function)\n\
401 \n\
402 Set the global debug tracing function.  It will be called on each\n\
403 function call.  See the debugger chapter in the library manual."
404 );
405
406 static PyObject *
407 sys_gettrace(PyObject *self, PyObject *args)
408 {
409     PyThreadState *tstate = PyThreadState_GET();
410     PyObject *temp = tstate->c_traceobj;
411
412     if (temp == NULL)
413         temp = Py_None;
414     Py_INCREF(temp);
415     return temp;
416 }
417
418 PyDoc_STRVAR(gettrace_doc,
419 "gettrace()\n\
420 \n\
421 Return the global debug tracing function set with sys.settrace.\n\
422 See the debugger chapter in the library manual."
423 );
424
425 static PyObject *
426 sys_setprofile(PyObject *self, PyObject *args)
427 {
428     if (trace_init() == -1)
429         return NULL;
430     if (args == Py_None)
431         PyEval_SetProfile(NULL, NULL);
432     else
433         PyEval_SetProfile(profile_trampoline, args);
434     Py_INCREF(Py_None);
435     return Py_None;
436 }
437
438 PyDoc_STRVAR(setprofile_doc,
439 "setprofile(function)\n\
440 \n\
441 Set the profiling function.  It will be called on each function call\n\
442 and return.  See the profiler chapter in the library manual."
443 );
444
445 static PyObject *
446 sys_getprofile(PyObject *self, PyObject *args)
447 {
448     PyThreadState *tstate = PyThreadState_GET();
449     PyObject *temp = tstate->c_profileobj;
450
451     if (temp == NULL)
452         temp = Py_None;
453     Py_INCREF(temp);
454     return temp;
455 }
456
457 PyDoc_STRVAR(getprofile_doc,
458 "getprofile()\n\
459 \n\
460 Return the profiling function set with sys.setprofile.\n\
461 See the profiler chapter in the library manual."
462 );
463
464 static PyObject *
465 sys_setcheckinterval(PyObject *self, PyObject *args)
466 {
467     if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
468         return NULL;
469     _Py_Ticker = _Py_CheckInterval;
470     Py_INCREF(Py_None);
471     return Py_None;
472 }
473
474 PyDoc_STRVAR(setcheckinterval_doc,
475 "setcheckinterval(n)\n\
476 \n\
477 Tell the Python interpreter to check for asynchronous events every\n\
478 n instructions.  This also affects how often thread switches occur."
479 );
480
481 static PyObject *
482 sys_getcheckinterval(PyObject *self, PyObject *args)
483 {
484     return PyInt_FromLong(_Py_CheckInterval);
485 }
486
487 PyDoc_STRVAR(getcheckinterval_doc,
488 "getcheckinterval() -> current check interval; see setcheckinterval()."
489 );
490
491 #ifdef WITH_TSC
492 static PyObject *
493 sys_settscdump(PyObject *self, PyObject *args)
494 {
495     int bool;
496     PyThreadState *tstate = PyThreadState_Get();
497
498     if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
499         return NULL;
500     if (bool)
501         tstate->interp->tscdump = 1;
502     else
503         tstate->interp->tscdump = 0;
504     Py_INCREF(Py_None);
505     return Py_None;
506
507 }
508
509 PyDoc_STRVAR(settscdump_doc,
510 "settscdump(bool)\n\
511 \n\
512 If true, tell the Python interpreter to dump VM measurements to\n\
513 stderr.  If false, turn off dump.  The measurements are based on the\n\
514 processor's time-stamp counter."
515 );
516 #endif /* TSC */
517
518 static PyObject *
519 sys_setrecursionlimit(PyObject *self, PyObject *args)
520 {
521     int new_limit;
522     if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
523         return NULL;
524     if (new_limit <= 0) {
525         PyErr_SetString(PyExc_ValueError,
526                         "recursion limit must be positive");
527         return NULL;
528     }
529     Py_SetRecursionLimit(new_limit);
530     Py_INCREF(Py_None);
531     return Py_None;
532 }
533
534 PyDoc_STRVAR(setrecursionlimit_doc,
535 "setrecursionlimit(n)\n\
536 \n\
537 Set the maximum depth of the Python interpreter stack to n.  This\n\
538 limit prevents infinite recursion from causing an overflow of the C\n\
539 stack and crashing Python.  The highest possible limit is platform-\n\
540 dependent."
541 );
542
543 static PyObject *
544 sys_getrecursionlimit(PyObject *self)
545 {
546     return PyInt_FromLong(Py_GetRecursionLimit());
547 }
548
549 PyDoc_STRVAR(getrecursionlimit_doc,
550 "getrecursionlimit()\n\
551 \n\
552 Return the current value of the recursion limit, the maximum depth\n\
553 of the Python interpreter stack.  This limit prevents infinite\n\
554 recursion from causing an overflow of the C stack and crashing Python."
555 );
556
557 #ifdef MS_WINDOWS
558 PyDoc_STRVAR(getwindowsversion_doc,
559 "getwindowsversion()\n\
560 \n\
561 Return information about the running version of Windows as a named tuple.\n\
562 The members are named: major, minor, build, platform, service_pack,\n\
563 service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
564 backward compatibility, only the first 5 items are available by indexing.\n\
565 All elements are numbers, except service_pack which is a string. Platform\n\
566 may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
567 3 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
568 controller, 3 for a server."
569 );
570
571 static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
572
573 static PyStructSequence_Field windows_version_fields[] = {
574     {"major", "Major version number"},
575     {"minor", "Minor version number"},
576     {"build", "Build number"},
577     {"platform", "Operating system platform"},
578     {"service_pack", "Latest Service Pack installed on the system"},
579     {"service_pack_major", "Service Pack major version number"},
580     {"service_pack_minor", "Service Pack minor version number"},
581     {"suite_mask", "Bit mask identifying available product suites"},
582     {"product_type", "System product type"},
583     {0}
584 };
585
586 static PyStructSequence_Desc windows_version_desc = {
587     "sys.getwindowsversion",  /* name */
588     getwindowsversion_doc,    /* doc */
589     windows_version_fields,   /* fields */
590     5                         /* For backward compatibility,
591                                  only the first 5 items are accessible
592                                  via indexing, the rest are name only */
593 };
594
595 static PyObject *
596 sys_getwindowsversion(PyObject *self)
597 {
598     PyObject *version;
599     int pos = 0;
600     OSVERSIONINFOEX ver;
601     ver.dwOSVersionInfoSize = sizeof(ver);
602     if (!GetVersionEx((OSVERSIONINFO*) &ver))
603         return PyErr_SetFromWindowsErr(0);
604
605     version = PyStructSequence_New(&WindowsVersionType);
606     if (version == NULL)
607         return NULL;
608
609     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMajorVersion));
610     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMinorVersion));
611     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwBuildNumber));
612     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwPlatformId));
613     PyStructSequence_SET_ITEM(version, pos++, PyString_FromString(ver.szCSDVersion));
614     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMajor));
615     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMinor));
616     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wSuiteMask));
617     PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wProductType));
618
619     return version;
620 }
621
622 #endif /* MS_WINDOWS */
623
624 #ifdef HAVE_DLOPEN
625 static PyObject *
626 sys_setdlopenflags(PyObject *self, PyObject *args)
627 {
628     int new_val;
629     PyThreadState *tstate = PyThreadState_GET();
630     if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
631         return NULL;
632     if (!tstate)
633         return NULL;
634     tstate->interp->dlopenflags = new_val;
635     Py_INCREF(Py_None);
636     return Py_None;
637 }
638
639 PyDoc_STRVAR(setdlopenflags_doc,
640 "setdlopenflags(n) -> None\n\
641 \n\
642 Set the flags used by the interpreter for dlopen calls, such as when the\n\
643 interpreter loads extension modules.  Among other things, this will enable\n\
644 a lazy resolving of symbols when importing a module, if called as\n\
645 sys.setdlopenflags(0).  To share symbols across extension modules, call as\n\
646 sys.setdlopenflags(ctypes.RTLD_GLOBAL).  Symbolic names for the flag modules\n\
647 can be either found in the ctypes module, or in the DLFCN module. If DLFCN\n\
648 is not available, it can be generated from /usr/include/dlfcn.h using the\n\
649 h2py script.");
650
651 static PyObject *
652 sys_getdlopenflags(PyObject *self, PyObject *args)
653 {
654     PyThreadState *tstate = PyThreadState_GET();
655     if (!tstate)
656         return NULL;
657     return PyInt_FromLong(tstate->interp->dlopenflags);
658 }
659
660 PyDoc_STRVAR(getdlopenflags_doc,
661 "getdlopenflags() -> int\n\
662 \n\
663 Return the current value of the flags that are used for dlopen calls.\n\
664 The flag constants are defined in the ctypes and DLFCN modules.");
665
666 #endif  /* HAVE_DLOPEN */
667
668 #ifdef USE_MALLOPT
669 /* Link with -lmalloc (or -lmpc) on an SGI */
670 #include <malloc.h>
671
672 static PyObject *
673 sys_mdebug(PyObject *self, PyObject *args)
674 {
675     int flag;
676     if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
677         return NULL;
678     mallopt(M_DEBUG, flag);
679     Py_INCREF(Py_None);
680     return Py_None;
681 }
682 #endif /* USE_MALLOPT */
683
684 static PyObject *
685 sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
686 {
687     PyObject *res = NULL;
688     static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
689     static char *kwlist[] = {"object", "default", 0};
690     PyObject *o, *dflt = NULL;
691
692     if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
693                                      kwlist, &o, &dflt))
694         return NULL;
695
696     /* Initialize static variable for GC head size */
697     if (gc_head_size == NULL) {
698         gc_head_size = PyInt_FromSsize_t(sizeof(PyGC_Head));
699         if (gc_head_size == NULL)
700             return NULL;
701     }
702
703     /* Make sure the type is initialized. float gets initialized late */
704     if (PyType_Ready(Py_TYPE(o)) < 0)
705         return NULL;
706
707     /* Instance of old-style class */
708     if (PyInstance_Check(o))
709         res = PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);
710     /* all other objects */
711     else {
712         PyObject *method = _PyObject_LookupSpecial(o, "__sizeof__",
713                                                    &str__sizeof__);
714         if (method == NULL) {
715             if (!PyErr_Occurred())
716                 PyErr_Format(PyExc_TypeError,
717                              "Type %.100s doesn't define __sizeof__",
718                              Py_TYPE(o)->tp_name);
719         }
720         else {
721             res = PyObject_CallFunctionObjArgs(method, NULL);
722             Py_DECREF(method);
723         }
724     }
725
726     /* Has a default value been given? */
727     if ((res == NULL) && (dflt != NULL) &&
728         PyErr_ExceptionMatches(PyExc_TypeError))
729     {
730         PyErr_Clear();
731         Py_INCREF(dflt);
732         return dflt;
733     }
734     else if (res == NULL)
735         return res;
736
737     /* add gc_head size */
738     if (PyObject_IS_GC(o)) {
739         PyObject *tmp = res;
740         res = PyNumber_Add(tmp, gc_head_size);
741         Py_DECREF(tmp);
742     }
743     return res;
744 }
745
746 PyDoc_STRVAR(getsizeof_doc,
747 "getsizeof(object, default) -> int\n\
748 \n\
749 Return the size of object in bytes.");
750
751 static PyObject *
752 sys_getrefcount(PyObject *self, PyObject *arg)
753 {
754     return PyInt_FromSsize_t(arg->ob_refcnt);
755 }
756
757 #ifdef Py_REF_DEBUG
758 static PyObject *
759 sys_gettotalrefcount(PyObject *self)
760 {
761     return PyInt_FromSsize_t(_Py_GetRefTotal());
762 }
763 #endif /* Py_REF_DEBUG */
764
765 PyDoc_STRVAR(getrefcount_doc,
766 "getrefcount(object) -> integer\n\
767 \n\
768 Return the reference count of object.  The count returned is generally\n\
769 one higher than you might expect, because it includes the (temporary)\n\
770 reference as an argument to getrefcount()."
771 );
772
773 #ifdef COUNT_ALLOCS
774 static PyObject *
775 sys_getcounts(PyObject *self)
776 {
777     extern PyObject *get_counts(void);
778
779     return get_counts();
780 }
781 #endif
782
783 PyDoc_STRVAR(getframe_doc,
784 "_getframe([depth]) -> frameobject\n\
785 \n\
786 Return a frame object from the call stack.  If optional integer depth is\n\
787 given, return the frame object that many calls below the top of the stack.\n\
788 If that is deeper than the call stack, ValueError is raised.  The default\n\
789 for depth is zero, returning the frame at the top of the call stack.\n\
790 \n\
791 This function should be used for internal and specialized\n\
792 purposes only."
793 );
794
795 static PyObject *
796 sys_getframe(PyObject *self, PyObject *args)
797 {
798     PyFrameObject *f = PyThreadState_GET()->frame;
799     int depth = -1;
800
801     if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
802         return NULL;
803
804     while (depth > 0 && f != NULL) {
805         f = f->f_back;
806         --depth;
807     }
808     if (f == NULL) {
809         PyErr_SetString(PyExc_ValueError,
810                         "call stack is not deep enough");
811         return NULL;
812     }
813     Py_INCREF(f);
814     return (PyObject*)f;
815 }
816
817 PyDoc_STRVAR(current_frames_doc,
818 "_current_frames() -> dictionary\n\
819 \n\
820 Return a dictionary mapping each current thread T's thread id to T's\n\
821 current stack frame.\n\
822 \n\
823 This function should be used for specialized purposes only."
824 );
825
826 static PyObject *
827 sys_current_frames(PyObject *self, PyObject *noargs)
828 {
829     return _PyThread_CurrentFrames();
830 }
831
832 PyDoc_STRVAR(call_tracing_doc,
833 "call_tracing(func, args) -> object\n\
834 \n\
835 Call func(*args), while tracing is enabled.  The tracing state is\n\
836 saved, and restored afterwards.  This is intended to be called from\n\
837 a debugger from a checkpoint, to recursively debug some other code."
838 );
839
840 static PyObject *
841 sys_call_tracing(PyObject *self, PyObject *args)
842 {
843     PyObject *func, *funcargs;
844     if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
845         return NULL;
846     return _PyEval_CallTracing(func, funcargs);
847 }
848
849 PyDoc_STRVAR(callstats_doc,
850 "callstats() -> tuple of integers\n\
851 \n\
852 Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
853 when Python was built.  Otherwise, return None.\n\
854 \n\
855 When enabled, this function returns detailed, implementation-specific\n\
856 details about the number of function calls executed. The return value is\n\
857 a 11-tuple where the entries in the tuple are counts of:\n\
858 0. all function calls\n\
859 1. calls to PyFunction_Type objects\n\
860 2. PyFunction calls that do not create an argument tuple\n\
861 3. PyFunction calls that do not create an argument tuple\n\
862    and bypass PyEval_EvalCodeEx()\n\
863 4. PyMethod calls\n\
864 5. PyMethod calls on bound methods\n\
865 6. PyType calls\n\
866 7. PyCFunction calls\n\
867 8. generator calls\n\
868 9. All other calls\n\
869 10. Number of stack pops performed by call_function()"
870 );
871
872 #ifdef __cplusplus
873 extern "C" {
874 #endif
875
876 #ifdef Py_TRACE_REFS
877 /* Defined in objects.c because it uses static globals if that file */
878 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
879 #endif
880
881 #ifdef DYNAMIC_EXECUTION_PROFILE
882 /* Defined in ceval.c because it uses static globals if that file */
883 extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
884 #endif
885
886 #ifdef __cplusplus
887 }
888 #endif
889
890 static PyObject *
891 sys_clear_type_cache(PyObject* self, PyObject* args)
892 {
893     PyType_ClearCache();
894     Py_RETURN_NONE;
895 }
896
897 PyDoc_STRVAR(sys_clear_type_cache__doc__,
898 "_clear_type_cache() -> None\n\
899 Clear the internal type lookup cache.");
900
901
902 static PyMethodDef sys_methods[] = {
903     /* Might as well keep this in alphabetic order */
904     {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
905      callstats_doc},
906     {"_clear_type_cache",       sys_clear_type_cache,     METH_NOARGS,
907      sys_clear_type_cache__doc__},
908     {"_current_frames", sys_current_frames, METH_NOARGS,
909      current_frames_doc},
910     {"displayhook",     sys_displayhook, METH_O, displayhook_doc},
911     {"exc_info",        sys_exc_info, METH_NOARGS, exc_info_doc},
912     {"exc_clear",       sys_exc_clear, METH_NOARGS, exc_clear_doc},
913     {"excepthook",      sys_excepthook, METH_VARARGS, excepthook_doc},
914     {"exit",            sys_exit, METH_VARARGS, exit_doc},
915 #ifdef Py_USING_UNICODE
916     {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
917      METH_NOARGS, getdefaultencoding_doc},
918 #endif
919 #ifdef HAVE_DLOPEN
920     {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
921      getdlopenflags_doc},
922 #endif
923 #ifdef COUNT_ALLOCS
924     {"getcounts",       (PyCFunction)sys_getcounts, METH_NOARGS},
925 #endif
926 #ifdef DYNAMIC_EXECUTION_PROFILE
927     {"getdxp",          _Py_GetDXProfile, METH_VARARGS},
928 #endif
929 #ifdef Py_USING_UNICODE
930     {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
931      METH_NOARGS, getfilesystemencoding_doc},
932 #endif
933 #ifdef Py_TRACE_REFS
934     {"getobjects",      _Py_GetObjects, METH_VARARGS},
935 #endif
936 #ifdef Py_REF_DEBUG
937     {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
938 #endif
939     {"getrefcount",     (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
940     {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
941      getrecursionlimit_doc},
942     {"getsizeof",   (PyCFunction)sys_getsizeof,
943      METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
944     {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
945 #ifdef MS_WINDOWS
946     {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
947      getwindowsversion_doc},
948 #endif /* MS_WINDOWS */
949 #ifdef USE_MALLOPT
950     {"mdebug",          sys_mdebug, METH_VARARGS},
951 #endif
952 #ifdef Py_USING_UNICODE
953     {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
954      setdefaultencoding_doc},
955 #endif
956     {"setcheckinterval",        sys_setcheckinterval, METH_VARARGS,
957      setcheckinterval_doc},
958     {"getcheckinterval",        sys_getcheckinterval, METH_NOARGS,
959      getcheckinterval_doc},
960 #ifdef HAVE_DLOPEN
961     {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
962      setdlopenflags_doc},
963 #endif
964     {"setprofile",      sys_setprofile, METH_O, setprofile_doc},
965     {"getprofile",      sys_getprofile, METH_NOARGS, getprofile_doc},
966     {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
967      setrecursionlimit_doc},
968 #ifdef WITH_TSC
969     {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
970 #endif
971     {"settrace",        sys_settrace, METH_O, settrace_doc},
972     {"gettrace",        sys_gettrace, METH_NOARGS, gettrace_doc},
973     {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
974     {NULL,              NULL}           /* sentinel */
975 };
976
977 static PyObject *
978 list_builtin_module_names(void)
979 {
980     PyObject *list = PyList_New(0);
981     int i;
982     if (list == NULL)
983         return NULL;
984     for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
985         PyObject *name = PyString_FromString(
986             PyImport_Inittab[i].name);
987         if (name == NULL)
988             break;
989         PyList_Append(list, name);
990         Py_DECREF(name);
991     }
992     if (PyList_Sort(list) != 0) {
993         Py_DECREF(list);
994         list = NULL;
995     }
996     if (list) {
997         PyObject *v = PyList_AsTuple(list);
998         Py_DECREF(list);
999         list = v;
1000     }
1001     return list;
1002 }
1003
1004 static PyObject *warnoptions = NULL;
1005
1006 void
1007 PySys_ResetWarnOptions(void)
1008 {
1009     if (warnoptions == NULL || !PyList_Check(warnoptions))
1010         return;
1011     PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
1012 }
1013
1014 void
1015 PySys_AddWarnOption(char *s)
1016 {
1017     PyObject *str;
1018
1019     if (warnoptions == NULL || !PyList_Check(warnoptions)) {
1020         Py_XDECREF(warnoptions);
1021         warnoptions = PyList_New(0);
1022         if (warnoptions == NULL)
1023             return;
1024     }
1025     str = PyString_FromString(s);
1026     if (str != NULL) {
1027         PyList_Append(warnoptions, str);
1028         Py_DECREF(str);
1029     }
1030 }
1031
1032 int
1033 PySys_HasWarnOptions(void)
1034 {
1035     return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
1036 }
1037
1038 /* XXX This doc string is too long to be a single string literal in VC++ 5.0.
1039    Two literals concatenated works just fine.  If you have a K&R compiler
1040    or other abomination that however *does* understand longer strings,
1041    get rid of the !!! comment in the middle and the quotes that surround it. */
1042 PyDoc_VAR(sys_doc) =
1043 PyDoc_STR(
1044 "This module provides access to some objects used or maintained by the\n\
1045 interpreter and to functions that interact strongly with the interpreter.\n\
1046 \n\
1047 Dynamic objects:\n\
1048 \n\
1049 argv -- command line arguments; argv[0] is the script pathname if known\n\
1050 path -- module search path; path[0] is the script directory, else ''\n\
1051 modules -- dictionary of loaded modules\n\
1052 \n\
1053 displayhook -- called to show results in an interactive session\n\
1054 excepthook -- called to handle any uncaught exception other than SystemExit\n\
1055   To customize printing in an interactive session or to install a custom\n\
1056   top-level exception handler, assign other functions to replace these.\n\
1057 \n\
1058 exitfunc -- if sys.exitfunc exists, this routine is called when Python exits\n\
1059   Assigning to sys.exitfunc is deprecated; use the atexit module instead.\n\
1060 \n\
1061 stdin -- standard input file object; used by raw_input() and input()\n\
1062 stdout -- standard output file object; used by the print statement\n\
1063 stderr -- standard error object; used for error messages\n\
1064   By assigning other file objects (or objects that behave like files)\n\
1065   to these, it is possible to redirect all of the interpreter's I/O.\n\
1066 \n\
1067 last_type -- type of last uncaught exception\n\
1068 last_value -- value of last uncaught exception\n\
1069 last_traceback -- traceback of last uncaught exception\n\
1070   These three are only available in an interactive session after a\n\
1071   traceback has been printed.\n\
1072 \n\
1073 exc_type -- type of exception currently being handled\n\
1074 exc_value -- value of exception currently being handled\n\
1075 exc_traceback -- traceback of exception currently being handled\n\
1076   The function exc_info() should be used instead of these three,\n\
1077   because it is thread-safe.\n\
1078 "
1079 )
1080 /* concatenating string here */
1081 PyDoc_STR(
1082 "\n\
1083 Static objects:\n\
1084 \n\
1085 float_info -- a dict with information about the float inplementation.\n\
1086 long_info -- a struct sequence with information about the long implementation.\n\
1087 maxint -- the largest supported integer (the smallest is -maxint-1)\n\
1088 maxsize -- the largest supported length of containers.\n\
1089 maxunicode -- the largest supported character\n\
1090 builtin_module_names -- tuple of module names built into this interpreter\n\
1091 version -- the version of this interpreter as a string\n\
1092 version_info -- version information as a named tuple\n\
1093 hexversion -- version information encoded as a single integer\n\
1094 copyright -- copyright notice pertaining to this interpreter\n\
1095 platform -- platform identifier\n\
1096 executable -- absolute path of the executable binary of the Python interpreter\n\
1097 prefix -- prefix used to find the Python library\n\
1098 exec_prefix -- prefix used to find the machine-specific Python library\n\
1099 float_repr_style -- string indicating the style of repr() output for floats\n\
1100 "
1101 )
1102 #ifdef MS_WINDOWS
1103 /* concatenating string here */
1104 PyDoc_STR(
1105 "dllhandle -- [Windows only] integer handle of the Python DLL\n\
1106 winver -- [Windows only] version number of the Python DLL\n\
1107 "
1108 )
1109 #endif /* MS_WINDOWS */
1110 PyDoc_STR(
1111 "__stdin__ -- the original stdin; don't touch!\n\
1112 __stdout__ -- the original stdout; don't touch!\n\
1113 __stderr__ -- the original stderr; don't touch!\n\
1114 __displayhook__ -- the original displayhook; don't touch!\n\
1115 __excepthook__ -- the original excepthook; don't touch!\n\
1116 \n\
1117 Functions:\n\
1118 \n\
1119 displayhook() -- print an object to the screen, and save it in __builtin__._\n\
1120 excepthook() -- print an exception and its traceback to sys.stderr\n\
1121 exc_info() -- return thread-safe information about the current exception\n\
1122 exc_clear() -- clear the exception state for the current thread\n\
1123 exit() -- exit the interpreter by raising SystemExit\n\
1124 getdlopenflags() -- returns flags to be used for dlopen() calls\n\
1125 getprofile() -- get the global profiling function\n\
1126 getrefcount() -- return the reference count for an object (plus one :-)\n\
1127 getrecursionlimit() -- return the max recursion depth for the interpreter\n\
1128 getsizeof() -- return the size of an object in bytes\n\
1129 gettrace() -- get the global debug tracing function\n\
1130 setcheckinterval() -- control how often the interpreter checks for events\n\
1131 setdlopenflags() -- set the flags to be used for dlopen() calls\n\
1132 setprofile() -- set the global profiling function\n\
1133 setrecursionlimit() -- set the max recursion depth for the interpreter\n\
1134 settrace() -- set the global debug tracing function\n\
1135 "
1136 )
1137 /* end of sys_doc */ ;
1138
1139 static int
1140 _check_and_flush (FILE *stream)
1141 {
1142   int prev_fail = ferror (stream);
1143   return fflush (stream) || prev_fail ? EOF : 0;
1144 }
1145
1146 /* Subversion branch and revision management */
1147 static int svn_initialized;
1148 static char patchlevel_revision[50]; /* Just the number */
1149 static char branch[50];
1150 static char shortbranch[50];
1151 static const char *svn_revision;
1152
1153 static void
1154 svnversion_init(void)
1155 {
1156     if (svn_initialized)
1157         return;
1158     svn_initialized = 1;
1159     *patchlevel_revision = '\0';
1160     strcpy(branch, "");
1161     strcpy(shortbranch, "unknown");
1162     svn_revision = "";
1163     return;
1164 }
1165
1166 /* Return svnversion output if available.
1167    Else return Revision of patchlevel.h if on branch.
1168    Else return empty string */
1169 const char*
1170 Py_SubversionRevision()
1171 {
1172     svnversion_init();
1173     return svn_revision;
1174 }
1175
1176 const char*
1177 Py_SubversionShortBranch()
1178 {
1179     svnversion_init();
1180     return shortbranch;
1181 }
1182
1183
1184 PyDoc_STRVAR(flags__doc__,
1185 "sys.flags\n\
1186 \n\
1187 Flags provided through command line arguments or environment vars.");
1188
1189 static PyTypeObject FlagsType = {0, 0, 0, 0, 0, 0};
1190
1191 static PyStructSequence_Field flags_fields[] = {
1192     {"debug",                   "-d"},
1193     {"py3k_warning",            "-3"},
1194     {"division_warning",        "-Q"},
1195     {"division_new",            "-Qnew"},
1196     {"inspect",                 "-i"},
1197     {"interactive",             "-i"},
1198     {"optimize",                "-O or -OO"},
1199     {"dont_write_bytecode",     "-B"},
1200     {"no_user_site",            "-s"},
1201     {"no_site",                 "-S"},
1202     {"ignore_environment",      "-E"},
1203     {"tabcheck",                "-t or -tt"},
1204     {"verbose",                 "-v"},
1205 #ifdef RISCOS
1206     {"riscos_wimp",             "???"},
1207 #endif
1208     /* {"unbuffered",                   "-u"}, */
1209     {"unicode",                 "-U"},
1210     /* {"skip_first",                   "-x"}, */
1211     {"bytes_warning", "-b"},
1212     {"hash_randomization", "-R"},
1213     {0}
1214 };
1215
1216 static PyStructSequence_Desc flags_desc = {
1217     "sys.flags",        /* name */
1218     flags__doc__,       /* doc */
1219     flags_fields,       /* fields */
1220 #ifdef RISCOS
1221     17
1222 #else
1223     16
1224 #endif
1225 };
1226
1227 static PyObject*
1228 make_flags(void)
1229 {
1230     int pos = 0;
1231     PyObject *seq;
1232
1233     seq = PyStructSequence_New(&FlagsType);
1234     if (seq == NULL)
1235         return NULL;
1236
1237 #define SetFlag(flag) \
1238     PyStructSequence_SET_ITEM(seq, pos++, PyInt_FromLong(flag))
1239
1240     SetFlag(Py_DebugFlag);
1241     SetFlag(Py_Py3kWarningFlag);
1242     SetFlag(Py_DivisionWarningFlag);
1243     SetFlag(_Py_QnewFlag);
1244     SetFlag(Py_InspectFlag);
1245     SetFlag(Py_InteractiveFlag);
1246     SetFlag(Py_OptimizeFlag);
1247     SetFlag(Py_DontWriteBytecodeFlag);
1248     SetFlag(Py_NoUserSiteDirectory);
1249     SetFlag(Py_NoSiteFlag);
1250     SetFlag(Py_IgnoreEnvironmentFlag);
1251     SetFlag(Py_TabcheckFlag);
1252     SetFlag(Py_VerboseFlag);
1253 #ifdef RISCOS
1254     SetFlag(Py_RISCOSWimpFlag);
1255 #endif
1256     /* SetFlag(saw_unbuffered_flag); */
1257     SetFlag(Py_UnicodeFlag);
1258     /* SetFlag(skipfirstline); */
1259     SetFlag(Py_BytesWarningFlag);
1260     SetFlag(Py_HashRandomizationFlag);
1261 #undef SetFlag
1262
1263     if (PyErr_Occurred()) {
1264         return NULL;
1265     }
1266     return seq;
1267 }
1268
1269 PyDoc_STRVAR(version_info__doc__,
1270 "sys.version_info\n\
1271 \n\
1272 Version information as a named tuple.");
1273
1274 static PyTypeObject VersionInfoType = {0, 0, 0, 0, 0, 0};
1275
1276 static PyStructSequence_Field version_info_fields[] = {
1277     {"major", "Major release number"},
1278     {"minor", "Minor release number"},
1279     {"micro", "Patch release number"},
1280     {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
1281     {"serial", "Serial release number"},
1282     {0}
1283 };
1284
1285 static PyStructSequence_Desc version_info_desc = {
1286     "sys.version_info",     /* name */
1287     version_info__doc__,    /* doc */
1288     version_info_fields,    /* fields */
1289     5
1290 };
1291
1292 static PyObject *
1293 make_version_info(void)
1294 {
1295     PyObject *version_info;
1296     char *s;
1297     int pos = 0;
1298
1299     version_info = PyStructSequence_New(&VersionInfoType);
1300     if (version_info == NULL) {
1301         return NULL;
1302     }
1303
1304     /*
1305      * These release level checks are mutually exclusive and cover
1306      * the field, so don't get too fancy with the pre-processor!
1307      */
1308 #if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
1309     s = "alpha";
1310 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
1311     s = "beta";
1312 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
1313     s = "candidate";
1314 #elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
1315     s = "final";
1316 #endif
1317
1318 #define SetIntItem(flag) \
1319     PyStructSequence_SET_ITEM(version_info, pos++, PyInt_FromLong(flag))
1320 #define SetStrItem(flag) \
1321     PyStructSequence_SET_ITEM(version_info, pos++, PyString_FromString(flag))
1322
1323     SetIntItem(PY_MAJOR_VERSION);
1324     SetIntItem(PY_MINOR_VERSION);
1325     SetIntItem(PY_MICRO_VERSION);
1326     SetStrItem(s);
1327     SetIntItem(PY_RELEASE_SERIAL);
1328 #undef SetIntItem
1329 #undef SetStrItem
1330
1331     if (PyErr_Occurred()) {
1332         Py_CLEAR(version_info);
1333         return NULL;
1334     }
1335     return version_info;
1336 }
1337
1338 PyObject *
1339 _PySys_Init(void)
1340 {
1341     PyObject *m, *v, *sysdict;
1342     PyObject *sysin, *sysout, *syserr;
1343     char *s;
1344
1345     m = Py_InitModule3("sys", sys_methods, sys_doc);
1346     if (m == NULL)
1347         return NULL;
1348     sysdict = PyModule_GetDict(m);
1349 #define SET_SYS_FROM_STRING(key, value)                 \
1350     v = value;                                          \
1351     if (v != NULL)                                      \
1352         PyDict_SetItemString(sysdict, key, v);          \
1353     Py_XDECREF(v)
1354
1355     /* Check that stdin is not a directory
1356     Using shell redirection, you can redirect stdin to a directory,
1357     crashing the Python interpreter. Catch this common mistake here
1358     and output a useful error message. Note that under MS Windows,
1359     the shell already prevents that. */
1360 #if !defined(MS_WINDOWS)
1361     {
1362         struct stat sb;
1363         if (fstat(fileno(stdin), &sb) == 0 &&
1364             S_ISDIR(sb.st_mode)) {
1365             /* There's nothing more we can do. */
1366             /* Py_FatalError() will core dump, so just exit. */
1367             PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
1368             exit(EXIT_FAILURE);
1369         }
1370     }
1371 #endif
1372
1373     /* Closing the standard FILE* if sys.std* goes aways causes problems
1374      * for embedded Python usages. Closing them when somebody explicitly
1375      * invokes .close() might be possible, but the FAQ promises they get
1376      * never closed. However, we still need to get write errors when
1377      * writing fails (e.g. because stdout is redirected), so we flush the
1378      * streams and check for errors before the file objects are deleted.
1379      * On OS X, fflush()ing stdin causes an error, so we exempt stdin
1380      * from that procedure.
1381      */
1382     sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
1383     sysout = PyFile_FromFile(stdout, "<stdout>", "w", _check_and_flush);
1384     syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);
1385     if (PyErr_Occurred())
1386         return NULL;
1387
1388     PyDict_SetItemString(sysdict, "stdin", sysin);
1389     PyDict_SetItemString(sysdict, "stdout", sysout);
1390     PyDict_SetItemString(sysdict, "stderr", syserr);
1391     /* Make backup copies for cleanup */
1392     PyDict_SetItemString(sysdict, "__stdin__", sysin);
1393     PyDict_SetItemString(sysdict, "__stdout__", sysout);
1394     PyDict_SetItemString(sysdict, "__stderr__", syserr);
1395     PyDict_SetItemString(sysdict, "__displayhook__",
1396                          PyDict_GetItemString(sysdict, "displayhook"));
1397     PyDict_SetItemString(sysdict, "__excepthook__",
1398                          PyDict_GetItemString(sysdict, "excepthook"));
1399     Py_XDECREF(sysin);
1400     Py_XDECREF(sysout);
1401     Py_XDECREF(syserr);
1402
1403     SET_SYS_FROM_STRING("version",
1404                          PyString_FromString(Py_GetVersion()));
1405     SET_SYS_FROM_STRING("hexversion",
1406                          PyInt_FromLong(PY_VERSION_HEX));
1407     svnversion_init();
1408     SET_SYS_FROM_STRING("subversion",
1409                          Py_BuildValue("(ssz)", "CPython", branch,
1410                                       svn_revision));
1411     SET_SYS_FROM_STRING("_mercurial",
1412                         Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
1413                                       _Py_hgversion()));
1414     SET_SYS_FROM_STRING("dont_write_bytecode",
1415                          PyBool_FromLong(Py_DontWriteBytecodeFlag));
1416     SET_SYS_FROM_STRING("api_version",
1417                         PyInt_FromLong(PYTHON_API_VERSION));
1418     SET_SYS_FROM_STRING("copyright",
1419                         PyString_FromString(Py_GetCopyright()));
1420     SET_SYS_FROM_STRING("platform",
1421                         PyString_FromString(Py_GetPlatform()));
1422     SET_SYS_FROM_STRING("executable",
1423                         PyString_FromString(Py_GetProgramFullPath()));
1424     SET_SYS_FROM_STRING("prefix",
1425                         PyString_FromString(Py_GetPrefix()));
1426     SET_SYS_FROM_STRING("exec_prefix",
1427                         PyString_FromString(Py_GetExecPrefix()));
1428     SET_SYS_FROM_STRING("maxsize",
1429                         PyInt_FromSsize_t(PY_SSIZE_T_MAX));
1430     SET_SYS_FROM_STRING("maxint",
1431                         PyInt_FromLong(PyInt_GetMax()));
1432     SET_SYS_FROM_STRING("py3kwarning",
1433                         PyBool_FromLong(Py_Py3kWarningFlag));
1434     SET_SYS_FROM_STRING("float_info",
1435                         PyFloat_GetInfo());
1436     SET_SYS_FROM_STRING("long_info",
1437                         PyLong_GetInfo());
1438 #ifdef Py_USING_UNICODE
1439     SET_SYS_FROM_STRING("maxunicode",
1440                         PyInt_FromLong(PyUnicode_GetMax()));
1441 #endif
1442     SET_SYS_FROM_STRING("builtin_module_names",
1443                         list_builtin_module_names());
1444     {
1445         /* Assumes that longs are at least 2 bytes long.
1446            Should be safe! */
1447         unsigned long number = 1;
1448         char *value;
1449
1450         s = (char *) &number;
1451         if (s[0] == 0)
1452             value = "big";
1453         else
1454             value = "little";
1455         SET_SYS_FROM_STRING("byteorder",
1456                             PyString_FromString(value));
1457     }
1458 #ifdef MS_COREDLL
1459     SET_SYS_FROM_STRING("dllhandle",
1460                         PyLong_FromVoidPtr(PyWin_DLLhModule));
1461     SET_SYS_FROM_STRING("winver",
1462                         PyString_FromString(PyWin_DLLVersionString));
1463 #endif
1464     if (warnoptions == NULL) {
1465         warnoptions = PyList_New(0);
1466     }
1467     else {
1468         Py_INCREF(warnoptions);
1469     }
1470     if (warnoptions != NULL) {
1471         PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
1472     }
1473
1474     /* version_info */
1475     if (VersionInfoType.tp_name == 0)
1476         PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1477     SET_SYS_FROM_STRING("version_info", make_version_info());
1478     /* prevent user from creating new instances */
1479     VersionInfoType.tp_init = NULL;
1480     VersionInfoType.tp_new = NULL;
1481
1482     /* flags */
1483     if (FlagsType.tp_name == 0)
1484         PyStructSequence_InitType(&FlagsType, &flags_desc);
1485     SET_SYS_FROM_STRING("flags", make_flags());
1486     /* prevent user from creating new instances */
1487     FlagsType.tp_init = NULL;
1488     FlagsType.tp_new = NULL;
1489
1490
1491 #if defined(MS_WINDOWS)
1492     /* getwindowsversion */
1493     if (WindowsVersionType.tp_name == 0)
1494         PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
1495     /* prevent user from creating new instances */
1496     WindowsVersionType.tp_init = NULL;
1497     WindowsVersionType.tp_new = NULL;
1498 #endif
1499
1500     /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
1501 #ifndef PY_NO_SHORT_FLOAT_REPR
1502     SET_SYS_FROM_STRING("float_repr_style",
1503                         PyString_FromString("short"));
1504 #else
1505     SET_SYS_FROM_STRING("float_repr_style",
1506                         PyString_FromString("legacy"));
1507 #endif
1508
1509 #undef SET_SYS_FROM_STRING
1510     if (PyErr_Occurred())
1511         return NULL;
1512     return m;
1513 }
1514
1515 static PyObject *
1516 makepathobject(char *path, int delim)
1517 {
1518     int i, n;
1519     char *p;
1520     PyObject *v, *w;
1521
1522     n = 1;
1523     p = path;
1524     while ((p = strchr(p, delim)) != NULL) {
1525         n++;
1526         p++;
1527     }
1528     v = PyList_New(n);
1529     if (v == NULL)
1530         return NULL;
1531     for (i = 0; ; i++) {
1532         p = strchr(path, delim);
1533         if (p == NULL)
1534             p = strchr(path, '\0'); /* End of string */
1535         w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));
1536         if (w == NULL) {
1537             Py_DECREF(v);
1538             return NULL;
1539         }
1540         PyList_SetItem(v, i, w);
1541         if (*p == '\0')
1542             break;
1543         path = p+1;
1544     }
1545     return v;
1546 }
1547
1548 void
1549 PySys_SetPath(char *path)
1550 {
1551     PyObject *v;
1552     if ((v = makepathobject(path, DELIM)) == NULL)
1553         Py_FatalError("can't create sys.path");
1554     if (PySys_SetObject("path", v) != 0)
1555         Py_FatalError("can't assign sys.path");
1556     Py_DECREF(v);
1557 }
1558
1559 static PyObject *
1560 makeargvobject(int argc, char **argv)
1561 {
1562     PyObject *av;
1563     if (argc <= 0 || argv == NULL) {
1564         /* Ensure at least one (empty) argument is seen */
1565         static char *empty_argv[1] = {""};
1566         argv = empty_argv;
1567         argc = 1;
1568     }
1569     av = PyList_New(argc);
1570     if (av != NULL) {
1571         int i;
1572         for (i = 0; i < argc; i++) {
1573 #ifdef __VMS
1574             PyObject *v;
1575
1576             /* argv[0] is the script pathname if known */
1577             if (i == 0) {
1578                 char* fn = decc$translate_vms(argv[0]);
1579                 if ((fn == (char *)0) || fn == (char *)-1)
1580                     v = PyString_FromString(argv[0]);
1581                 else
1582                     v = PyString_FromString(
1583                         decc$translate_vms(argv[0]));
1584             } else
1585                 v = PyString_FromString(argv[i]);
1586 #else
1587             PyObject *v = PyString_FromString(argv[i]);
1588 #endif
1589             if (v == NULL) {
1590                 Py_DECREF(av);
1591                 av = NULL;
1592                 break;
1593             }
1594             PyList_SetItem(av, i, v);
1595         }
1596     }
1597     return av;
1598 }
1599
1600 void
1601 PySys_SetArgvEx(int argc, char **argv, int updatepath)
1602 {
1603 #if defined(HAVE_REALPATH)
1604     char fullpath[MAXPATHLEN];
1605 #elif defined(MS_WINDOWS) && !defined(MS_WINCE)
1606     char fullpath[MAX_PATH];
1607 #endif
1608     PyObject *av = makeargvobject(argc, argv);
1609     PyObject *path = PySys_GetObject("path");
1610     if (av == NULL)
1611         Py_FatalError("no mem for sys.argv");
1612     if (PySys_SetObject("argv", av) != 0)
1613         Py_FatalError("can't assign sys.argv");
1614     if (updatepath && path != NULL) {
1615         char *argv0 = argv[0];
1616         char *p = NULL;
1617         Py_ssize_t n = 0;
1618         PyObject *a;
1619 #ifdef HAVE_READLINK
1620         char link[MAXPATHLEN+1];
1621         char argv0copy[2*MAXPATHLEN+1];
1622         int nr = 0;
1623         if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)
1624             nr = readlink(argv0, link, MAXPATHLEN);
1625         if (nr > 0) {
1626             /* It's a symlink */
1627             link[nr] = '\0';
1628             if (link[0] == SEP)
1629                 argv0 = link; /* Link to absolute path */
1630             else if (strchr(link, SEP) == NULL)
1631                 ; /* Link without path */
1632             else {
1633                 /* Must join(dirname(argv0), link) */
1634                 char *q = strrchr(argv0, SEP);
1635                 if (q == NULL)
1636                     argv0 = link; /* argv0 without path */
1637                 else {
1638                     /* Must make a copy */
1639                     strcpy(argv0copy, argv0);
1640                     q = strrchr(argv0copy, SEP);
1641                     strcpy(q+1, link);
1642                     argv0 = argv0copy;
1643                 }
1644             }
1645         }
1646 #endif /* HAVE_READLINK */
1647 #if SEP == '\\' /* Special case for MS filename syntax */
1648         if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
1649             char *q;
1650 #if defined(MS_WINDOWS) && !defined(MS_WINCE)
1651             /* This code here replaces the first element in argv with the full
1652             path that it represents. Under CE, there are no relative paths so
1653             the argument must be the full path anyway. */
1654             char *ptemp;
1655             if (GetFullPathName(argv0,
1656                                sizeof(fullpath),
1657                                fullpath,
1658                                &ptemp)) {
1659                 argv0 = fullpath;
1660             }
1661 #endif
1662             p = strrchr(argv0, SEP);
1663             /* Test for alternate separator */
1664             q = strrchr(p ? p : argv0, '/');
1665             if (q != NULL)
1666                 p = q;
1667             if (p != NULL) {
1668                 n = p + 1 - argv0;
1669                 if (n > 1 && p[-1] != ':')
1670                     n--; /* Drop trailing separator */
1671             }
1672         }
1673 #else /* All other filename syntaxes */
1674         if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
1675 #if defined(HAVE_REALPATH)
1676             if (realpath(argv0, fullpath)) {
1677                 argv0 = fullpath;
1678             }
1679 #endif
1680             p = strrchr(argv0, SEP);
1681         }
1682         if (p != NULL) {
1683 #ifndef RISCOS
1684             n = p + 1 - argv0;
1685 #else /* don't include trailing separator */
1686             n = p - argv0;
1687 #endif /* RISCOS */
1688 #if SEP == '/' /* Special case for Unix filename syntax */
1689             if (n > 1)
1690                 n--; /* Drop trailing separator */
1691 #endif /* Unix */
1692         }
1693 #endif /* All others */
1694         a = PyString_FromStringAndSize(argv0, n);
1695         if (a == NULL)
1696             Py_FatalError("no mem for sys.path insertion");
1697         if (PyList_Insert(path, 0, a) < 0)
1698             Py_FatalError("sys.path.insert(0) failed");
1699         Py_DECREF(a);
1700     }
1701     Py_DECREF(av);
1702 }
1703
1704 void
1705 PySys_SetArgv(int argc, char **argv)
1706 {
1707     PySys_SetArgvEx(argc, argv, 1);
1708 }
1709
1710
1711 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
1712    Adapted from code submitted by Just van Rossum.
1713
1714    PySys_WriteStdout(format, ...)
1715    PySys_WriteStderr(format, ...)
1716
1717       The first function writes to sys.stdout; the second to sys.stderr.  When
1718       there is a problem, they write to the real (C level) stdout or stderr;
1719       no exceptions are raised.
1720
1721       Both take a printf-style format string as their first argument followed
1722       by a variable length argument list determined by the format string.
1723
1724       *** WARNING ***
1725
1726       The format should limit the total size of the formatted output string to
1727       1000 bytes.  In particular, this means that no unrestricted "%s" formats
1728       should occur; these should be limited using "%.<N>s where <N> is a
1729       decimal number calculated so that <N> plus the maximum size of other
1730       formatted text does not exceed 1000 bytes.  Also watch out for "%f",
1731       which can print hundreds of digits for very large numbers.
1732
1733  */
1734
1735 static void
1736 mywrite(char *name, FILE *fp, const char *format, va_list va)
1737 {
1738     PyObject *file;
1739     PyObject *error_type, *error_value, *error_traceback;
1740
1741     PyErr_Fetch(&error_type, &error_value, &error_traceback);
1742     file = PySys_GetObject(name);
1743     if (file == NULL || PyFile_AsFile(file) == fp)
1744         vfprintf(fp, format, va);
1745     else {
1746         char buffer[1001];
1747         const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
1748                                            format, va);
1749         if (PyFile_WriteString(buffer, file) != 0) {
1750             PyErr_Clear();
1751             fputs(buffer, fp);
1752         }
1753         if (written < 0 || (size_t)written >= sizeof(buffer)) {
1754             const char *truncated = "... truncated";
1755             if (PyFile_WriteString(truncated, file) != 0) {
1756                 PyErr_Clear();
1757                 fputs(truncated, fp);
1758             }
1759         }
1760     }
1761     PyErr_Restore(error_type, error_value, error_traceback);
1762 }
1763
1764 void
1765 PySys_WriteStdout(const char *format, ...)
1766 {
1767     va_list va;
1768
1769     va_start(va, format);
1770     mywrite("stdout", stdout, format, va);
1771     va_end(va);
1772 }
1773
1774 void
1775 PySys_WriteStderr(const char *format, ...)
1776 {
1777     va_list va;
1778
1779     va_start(va, format);
1780     mywrite("stderr", stderr, format, va);
1781     va_end(va);
1782 }