LCOV - code coverage report
Current view: top level - libreoffice/workdir/unxlngi6.pro/UnpackedTarball/python3/Python - sysmodule.c (source / functions) Hit Total Coverage
Test: libreoffice_filtered.info Lines: 193 687 28.1 %
Date: 2012-12-17 Functions: 15 60 25.0 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.10