Python-2.7.3/Python/sysmodule.c

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

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'v')
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

1616 1617 static PyObject * 1618 makeargvobject(int argc, char **argv) 1619 { 1620 PyObject *av; 1621 if (argc <= 0 || argv == NULL) { 1622 /* Ensure at least one (empty) argument is seen */ 1623 static char *empty_argv[1] = {""}; 1624 argv = empty_argv; 1625 argc = 1; 1626 } 1627 av = PyList_New(argc); 1628 if (av != NULL) { 1629 int i; 1630 for (i = 0; i < argc; i++) { 1631 #ifdef __VMS 1632 PyObject *v; 1633 1634 /* argv[0] is the script pathname if known */ 1635 if (i == 0) { 1636 char* fn = decc$translate_vms(argv[0]); 1637 if ((fn == (char *)0) || fn == (char *)-1) 1638 v = PyString_FromString(argv[0]); 1639 else 1640 v = PyString_FromString( 1641 decc$translate_vms(argv[0])); 1642 } else 1643 v = PyString_FromString(argv[i]); 1644 #else 1645 PyObject *v = PyString_FromString(argv[i]); 1646 #endif 1647 if (v == NULL) { 1648 Py_DECREF(av); 1649 av = NULL; 1650 break; 1651 } 1652 PyList_SetItem(av, i, v); 1653 } 1654 } 1655 return av; 1656 } 1657 1658 void 1659 PySys_SetArgvEx(int argc, char **argv, int updatepath) 1660 { 1661 #if defined(HAVE_REALPATH) 1662 char fullpath[MAXPATHLEN]; 1663 #elif defined(MS_WINDOWS) && !defined(MS_WINCE) 1664 char fullpath[MAX_PATH]; 1665 #endif 1666 PyObject *av = makeargvobject(argc, argv); 1667 PyObject *path = PySys_GetObject("path"); 1668 if (av == NULL) 1669 Py_FatalError("no mem for sys.argv"); 1670 if (PySys_SetObject("argv", av) != 0) 1671 Py_FatalError("can't assign sys.argv"); 1672 if (updatepath && path != NULL) { 1673 char *argv0 = argv[0]; 1674 char *p = NULL; 1675 Py_ssize_t n = 0; 1676 PyObject *a; 1677 #ifdef HAVE_READLINK 1678 char link[MAXPATHLEN+1]; 1679 char argv0copy[2*MAXPATHLEN+1]; 1680 int nr = 0; 1681 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) 1682 nr = readlink(argv0, link, MAXPATHLEN); 1683 if (nr > 0) { 1684 /* It's a symlink */ 1685 link[nr] = '\0'; 1686 if (link[0] == SEP) 1687 argv0 = link; /* Link to absolute path */ 1688 else if (strchr(link, SEP) == NULL) 1689 ; /* Link without path */ 1690 else { 1691 /* Must join(dirname(argv0), link) */ 1692 char *q = strrchr(argv0, SEP); 1693 if (q == NULL) 1694 argv0 = link; /* argv0 without path */ 1695 else { 1696 /* Must make a copy */ 1697 strcpy(argv0copy, argv0); 1698 q = strrchr(argv0copy, SEP); 1699 strcpy(q+1, link); 1700 argv0 = argv0copy; 1701 } 1702 } 1703 } 1704 #endif /* HAVE_READLINK */ 1705 #if SEP == '\\' /* Special case for MS filename syntax */ 1706 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { 1707 char *q; 1708 #if defined(MS_WINDOWS) && !defined(MS_WINCE) 1709 /* This code here replaces the first element in argv with the full 1710 path that it represents. Under CE, there are no relative paths so 1711 the argument must be the full path anyway. */ 1712 char *ptemp; 1713 if (GetFullPathName(argv0, 1714 sizeof(fullpath), 1715 fullpath, 1716 &ptemp)) { 1717 argv0 = fullpath; 1718 } 1719 #endif 1720 p = strrchr(argv0, SEP); 1721 /* Test for alternate separator */ 1722 q = strrchr(p ? p : argv0, '/'); 1723 if (q != NULL) 1724 p = q; 1725 if (p != NULL) { 1726 n = p + 1 - argv0; 1727 if (n > 1 && p[-1] != ':') 1728 n--; /* Drop trailing separator */ 1729 } 1730 } 1731 #else /* All other filename syntaxes */ 1732 if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) { 1733 #if defined(HAVE_REALPATH) 1734 if (realpath(argv0, fullpath)) { 1735 argv0 = fullpath; 1736 } 1737 #endif 1738 p = strrchr(argv0, SEP); 1739 } 1740 if (p != NULL) { 1741 #ifndef RISCOS 1742 n = p + 1 - argv0; 1743 #else /* don't include trailing separator */ 1744 n = p - argv0; 1745 #endif /* RISCOS */ 1746 #if SEP == '/' /* Special case for Unix filename syntax */ 1747 if (n > 1) 1748 n--; /* Drop trailing separator */ 1749 #endif /* Unix */ 1750 } 1751 #endif /* All others */ 1752 a = PyString_FromStringAndSize(argv0, n); 1753 if (a == NULL) 1754 Py_FatalError("no mem for sys.path insertion"); 1755 if (PyList_Insert(path, 0, a) < 0) 1756 Py_FatalError("sys.path.insert(0) failed"); 1757 Py_DECREF(a); 1758 }
Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'a')
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'a')
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

1759 Py_DECREF(av); 1760 }
Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'av')
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

Access to field 'ob_refcnt' results in a dereference of a null pointer (loaded from variable 'av')
(emitted by clang-analyzer)

TODO: a detailed trace is available in the data model (not yet rendered in this report)

1761 1762 void 1763 PySys_SetArgv(int argc, char **argv) 1764 { 1765 PySys_SetArgvEx(argc, argv, 1); 1766 } 1767 1768 1769 /* APIs to write to sys.stdout or sys.stderr using a printf-like interface. 1770 Adapted from code submitted by Just van Rossum. 1771 1772 PySys_WriteStdout(format, ...) 1773 PySys_WriteStderr(format, ...) 1774 1775 The first function writes to sys.stdout; the second to sys.stderr. When 1776 there is a problem, they write to the real (C level) stdout or stderr; 1777 no exceptions are raised. 1778 1779 Both take a printf-style format string as their first argument followed 1780 by a variable length argument list determined by the format string. 1781 1782 *** WARNING *** 1783 1784 The format should limit the total size of the formatted output string to 1785 1000 bytes. In particular, this means that no unrestricted "%s" formats 1786 should occur; these should be limited using "%.<N>s where <N> is a 1787 decimal number calculated so that <N> plus the maximum size of other 1788 formatted text does not exceed 1000 bytes. Also watch out for "%f", 1789 which can print hundreds of digits for very large numbers. 1790 1791 */ 1792 1793 static void 1794 mywrite(char *name, FILE *fp, const char *format, va_list va) 1795 { 1796 PyObject *file; 1797 PyObject *error_type, *error_value, *error_traceback; 1798 1799 PyErr_Fetch(&error_type, &error_value, &error_traceback); 1800 file = PySys_GetObject(name); 1801 if (file == NULL || PyFile_AsFile(file) == fp) 1802 vfprintf(fp, format, va); 1803 else { 1804 char buffer[1001]; 1805 const int written = PyOS_vsnprintf(buffer, sizeof(buffer), 1806 format, va); 1807 if (PyFile_WriteString(buffer, file) != 0) { 1808 PyErr_Clear(); 1809 fputs(buffer, fp); 1810 } 1811 if (written < 0 || (size_t)written >= sizeof(buffer)) { 1812 const char *truncated = "... truncated"; 1813 if (PyFile_WriteString(truncated, file) != 0) { 1814 PyErr_Clear(); 1815 fputs(truncated, fp); 1816 } 1817 } 1818 } 1819 PyErr_Restore(error_type, error_value, error_traceback); 1820 } 1821 1822 void 1823 PySys_WriteStdout(const char *format, ...) 1824 { 1825 va_list va; 1826 1827 va_start(va, format); 1828 mywrite("stdout", stdout, format, va); 1829 va_end(va); 1830 } 1831 1832 void 1833 PySys_WriteStderr(const char *format, ...) 1834 { 1835 va_list va; 1836 1837 va_start(va, format); 1838 mywrite("stderr", stderr, format, va); 1839 va_end(va); 1840 }