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