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