sysmodule.c 59.2 KB
Newer Older
1

Guido van Rossum's avatar
Guido van Rossum committed
2 3 4 5 6
/* System module */

/*
Various bits of information used by the interpreter are collected in
module 'sys'.
Guido van Rossum's avatar
Guido van Rossum committed
7
Function member:
8
- exit(sts): raise SystemExit
Guido van Rossum's avatar
Guido van Rossum committed
9 10 11
Data members:
- stdin, stdout, stderr: standard file objects
- modules: the table of modules (dictionary)
Guido van Rossum's avatar
Guido van Rossum committed
12 13 14
- path: module search path (list of strings)
- argv: script arguments (list of strings)
- ps1, ps2: optional primary and secondary prompts (strings)
Guido van Rossum's avatar
Guido van Rossum committed
15 16
*/

Guido van Rossum's avatar
Guido van Rossum committed
17
#include "Python.h"
Jeremy Hylton's avatar
Jeremy Hylton committed
18
#include "code.h"
19
#include "frameobject.h"
20
#include "pythread.h"
Guido van Rossum's avatar
Guido van Rossum committed
21

22
#include "osdefs.h"
Guido van Rossum's avatar
Guido van Rossum committed
23

24 25
#ifdef MS_WINDOWS
#define WIN32_LEAN_AND_MEAN
26
#include <windows.h>
27 28
#endif /* MS_WINDOWS */

29
#ifdef MS_COREDLL
30
extern void *PyWin_DLLhModule;
31 32
/* A string loaded from the DLL at startup: */
extern const char *PyWin_DLLVersionString;
33 34
#endif

35 36 37 38
#ifdef __VMS
#include <unixlib.h>
#endif

39 40 41 42 43
#ifdef HAVE_LANGINFO_H
#include <locale.h>
#include <langinfo.h>
#endif

Guido van Rossum's avatar
Guido van Rossum committed
44
PyObject *
45
PySys_GetObject(const char *name)
Guido van Rossum's avatar
Guido van Rossum committed
46
{
47 48 49 50 51
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *sd = tstate->interp->sysdict;
    if (sd == NULL)
        return NULL;
    return PyDict_GetItemString(sd, name);
Guido van Rossum's avatar
Guido van Rossum committed
52 53 54
}

int
55
PySys_SetObject(const char *name, PyObject *v)
Guido van Rossum's avatar
Guido van Rossum committed
56
{
57 58 59 60 61 62 63 64 65 66
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *sd = tstate->interp->sysdict;
    if (v == NULL) {
        if (PyDict_GetItemString(sd, name) == NULL)
            return 0;
        else
            return PyDict_DelItemString(sd, name);
    }
    else
        return PyDict_SetItemString(sd, name, v);
Guido van Rossum's avatar
Guido van Rossum committed
67 68
}

69 70 71 72 73 74 75 76 77 78 79 80 81
/* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace'
   error handler. If sys.stdout has a buffer attribute, use
   sys.stdout.buffer.write(encoded), otherwise redecode the string and use
   sys.stdout.write(redecoded).

   Helper function for sys_displayhook(). */
static int
sys_displayhook_unencodable(PyObject *outf, PyObject *o)
{
    PyObject *stdout_encoding = NULL;
    PyObject *encoded, *escaped_str, *repr_str, *buffer, *result;
    char *stdout_encoding_str;
    int ret;
82 83
    _Py_IDENTIFIER(encoding);
    _Py_IDENTIFIER(buffer);
84

85
    stdout_encoding = _PyObject_GetAttrId(outf, &PyId_encoding);
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
    if (stdout_encoding == NULL)
        goto error;
    stdout_encoding_str = _PyUnicode_AsString(stdout_encoding);
    if (stdout_encoding_str == NULL)
        goto error;

    repr_str = PyObject_Repr(o);
    if (repr_str == NULL)
        goto error;
    encoded = PyUnicode_AsEncodedString(repr_str,
                                        stdout_encoding_str,
                                        "backslashreplace");
    Py_DECREF(repr_str);
    if (encoded == NULL)
        goto error;

102
    buffer = _PyObject_GetAttrId(outf, &PyId_buffer);
103
    if (buffer) {
104
        _Py_IDENTIFIER(write);
105
        result = _PyObject_CallMethodId(buffer, &PyId_write, "(O)", encoded);
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
        Py_DECREF(buffer);
        Py_DECREF(encoded);
        if (result == NULL)
            goto error;
        Py_DECREF(result);
    }
    else {
        PyErr_Clear();
        escaped_str = PyUnicode_FromEncodedObject(encoded,
                                                  stdout_encoding_str,
                                                  "strict");
        Py_DECREF(encoded);
        if (PyFile_WriteObject(escaped_str, outf, Py_PRINT_RAW) != 0) {
            Py_DECREF(escaped_str);
            goto error;
        }
        Py_DECREF(escaped_str);
    }
    ret = 0;
    goto finally;

error:
    ret = -1;
finally:
    Py_XDECREF(stdout_encoding);
    return ret;
}

134
static PyObject *
135
sys_displayhook(PyObject *self, PyObject *o)
136
{
137 138 139 140
    PyObject *outf;
    PyInterpreterState *interp = PyThreadState_GET()->interp;
    PyObject *modules = interp->modules;
    PyObject *builtins = PyDict_GetItemString(modules, "builtins");
141
    int err;
142
    _Py_IDENTIFIER(_);
143 144 145 146 147 148 149 150 151 152 153 154 155

    if (builtins == NULL) {
        PyErr_SetString(PyExc_RuntimeError, "lost builtins module");
        return NULL;
    }

    /* Print value except if None */
    /* After printing, also assign to '_' */
    /* Before, set '_' to None to avoid recursion */
    if (o == Py_None) {
        Py_INCREF(Py_None);
        return Py_None;
    }
156
    if (_PyObject_SetAttrId(builtins, &PyId__, Py_None) != 0)
157 158 159 160 161 162
        return NULL;
    outf = PySys_GetObject("stdout");
    if (outf == NULL || outf == Py_None) {
        PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
        return NULL;
    }
163 164 165 166 167 168 169 170 171 172 173 174 175
    if (PyFile_WriteObject(o, outf, 0) != 0) {
        if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
            /* repr(o) is not encodable to sys.stdout.encoding with
             * sys.stdout.errors error handler (which is probably 'strict') */
            PyErr_Clear();
            err = sys_displayhook_unencodable(outf, o);
            if (err)
                return NULL;
        }
        else {
            return NULL;
        }
    }
176 177
    if (PyFile_WriteString("\n", outf) != 0)
        return NULL;
178
    if (_PyObject_SetAttrId(builtins, &PyId__, o) != 0)
179 180 181
        return NULL;
    Py_INCREF(Py_None);
    return Py_None;
182 183
}

184
PyDoc_STRVAR(displayhook_doc,
Ka-Ping Yee's avatar
Ka-Ping Yee committed
185
"displayhook(object) -> None\n"
186
"\n"
187
"Print an object to sys.stdout and also save it in builtins._\n"
188
);
Ka-Ping Yee's avatar
Ka-Ping Yee committed
189 190 191 192

static PyObject *
sys_excepthook(PyObject* self, PyObject* args)
{
193 194 195 196 197 198
    PyObject *exc, *value, *tb;
    if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
        return NULL;
    PyErr_Display(exc, value, tb);
    Py_INCREF(Py_None);
    return Py_None;
Ka-Ping Yee's avatar
Ka-Ping Yee committed
199 200
}

201
PyDoc_STRVAR(excepthook_doc,
Ka-Ping Yee's avatar
Ka-Ping Yee committed
202 203
"excepthook(exctype, value, traceback) -> None\n"
"\n"
204 205
"Handle an exception by displaying it with a traceback on sys.stderr.\n"
);
206

207
static PyObject *
208
sys_exc_info(PyObject *self, PyObject *noargs)
209
{
210 211 212 213 214 215 216 217
    PyThreadState *tstate;
    tstate = PyThreadState_GET();
    return Py_BuildValue(
        "(OOO)",
        tstate->exc_type != NULL ? tstate->exc_type : Py_None,
        tstate->exc_value != NULL ? tstate->exc_value : Py_None,
        tstate->exc_traceback != NULL ?
            tstate->exc_traceback : Py_None);
218 219
}

220
PyDoc_STRVAR(exc_info_doc,
221 222
"exc_info() -> (type, value, traceback)\n\
\n\
223 224 225 226
Return information about the most recent exception caught by an except\n\
clause in the current stack frame or in an older stack frame."
);

Guido van Rossum's avatar
Guido van Rossum committed
227
static PyObject *
228
sys_exit(PyObject *self, PyObject *args)
Guido van Rossum's avatar
Guido van Rossum committed
229
{
230 231 232 233 234 235
    PyObject *exit_code = 0;
    if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
        return NULL;
    /* Raise SystemExit so callers may catch it or clean up. */
    PyErr_SetObject(PyExc_SystemExit, exit_code);
    return NULL;
Guido van Rossum's avatar
Guido van Rossum committed
236 237
}

238
PyDoc_STRVAR(exit_doc,
239 240 241 242
"exit([status])\n\
\n\
Exit the interpreter by raising SystemExit(status).\n\
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 246
exit status will be one (i.e., failure)."
);
247

248

249
static PyObject *
250
sys_getdefaultencoding(PyObject *self)
251
{
252
    return PyUnicode_FromString(PyUnicode_GetDefaultEncoding());
253 254
}

255
PyDoc_STRVAR(getdefaultencoding_doc,
256
"getdefaultencoding() -> string\n\
257 258
\n\
Return the current default string encoding used by the Unicode \n\
259 260
implementation."
);
261

262 263 264
static PyObject *
sys_getfilesystemencoding(PyObject *self)
{
265 266
    if (Py_FileSystemDefaultEncoding)
        return PyUnicode_FromString(Py_FileSystemDefaultEncoding);
267 268 269
    PyErr_SetString(PyExc_RuntimeError,
                    "filesystem encoding is not initialized");
    return NULL;
270 271 272 273 274 275 276 277 278
}

PyDoc_STRVAR(getfilesystemencoding_doc,
"getfilesystemencoding() -> string\n\
\n\
Return the encoding used to convert Unicode filenames in\n\
operating system filenames."
);

279 280 281
static PyObject *
sys_intern(PyObject *self, PyObject *args)
{
282 283 284 285 286 287 288 289 290 291 292 293 294
    PyObject *s;
    if (!PyArg_ParseTuple(args, "U:intern", &s))
        return NULL;
    if (PyUnicode_CheckExact(s)) {
        Py_INCREF(s);
        PyUnicode_InternInPlace(&s);
        return s;
    }
    else {
        PyErr_Format(PyExc_TypeError,
                        "can't intern %.400s", s->ob_type->tp_name);
        return NULL;
    }
295 296 297 298 299 300 301 302 303 304 305
}

PyDoc_STRVAR(intern_doc,
"intern(string) -> string\n\
\n\
``Intern'' the given string.  This enters the string in the (global)\n\
table of interned strings whose purpose is to speed up dictionary lookups.\n\
Return the string itself or the previously interned string object with the\n\
same value.");


306 307 308 309
/*
 * Cached interned string objects used for calling the profile and
 * trace functions.  Initialized by trace_init().
 */
310
static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
311 312 313 314

static int
trace_init(void)
{
315 316 317 318 319 320 321 322 323 324 325 326 327
    static char *whatnames[7] = {"call", "exception", "line", "return",
                                    "c_call", "c_exception", "c_return"};
    PyObject *name;
    int i;
    for (i = 0; i < 7; ++i) {
        if (whatstrings[i] == NULL) {
            name = PyUnicode_InternFromString(whatnames[i]);
            if (name == NULL)
                return -1;
            whatstrings[i] = name;
        }
    }
    return 0;
328 329 330 331 332
}


static PyObject *
call_trampoline(PyThreadState *tstate, PyObject* callback,
333
                PyFrameObject *frame, int what, PyObject *arg)
334
{
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
    PyObject *args = PyTuple_New(3);
    PyObject *whatstr;
    PyObject *result;

    if (args == NULL)
        return NULL;
    Py_INCREF(frame);
    whatstr = whatstrings[what];
    Py_INCREF(whatstr);
    if (arg == NULL)
        arg = Py_None;
    Py_INCREF(arg);
    PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
    PyTuple_SET_ITEM(args, 1, whatstr);
    PyTuple_SET_ITEM(args, 2, arg);

    /* call the Python-level function */
    PyFrame_FastToLocals(frame);
    result = PyEval_CallObject(callback, args);
    PyFrame_LocalsToFast(frame, 1);
    if (result == NULL)
        PyTraceBack_Here(frame);

    /* cleanup */
    Py_DECREF(args);
    return result;
361 362 363 364
}

static int
profile_trampoline(PyObject *self, PyFrameObject *frame,
365
                   int what, PyObject *arg)
366
{
367 368 369 370 371 372 373 374 375 376 377 378
    PyThreadState *tstate = frame->f_tstate;
    PyObject *result;

    if (arg == NULL)
        arg = Py_None;
    result = call_trampoline(tstate, self, frame, what, arg);
    if (result == NULL) {
        PyEval_SetProfile(NULL, NULL);
        return -1;
    }
    Py_DECREF(result);
    return 0;
379 380 381 382
}

static int
trace_trampoline(PyObject *self, PyFrameObject *frame,
383
                 int what, PyObject *arg)
384
{
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
    PyThreadState *tstate = frame->f_tstate;
    PyObject *callback;
    PyObject *result;

    if (what == PyTrace_CALL)
        callback = self;
    else
        callback = frame->f_trace;
    if (callback == NULL)
        return 0;
    result = call_trampoline(tstate, callback, frame, what, arg);
    if (result == NULL) {
        PyEval_SetTrace(NULL, NULL);
        Py_XDECREF(frame->f_trace);
        frame->f_trace = NULL;
        return -1;
    }
    if (result != Py_None) {
        PyObject *temp = frame->f_trace;
        frame->f_trace = NULL;
        Py_XDECREF(temp);
        frame->f_trace = result;
    }
    else {
        Py_DECREF(result);
    }
    return 0;
412
}
413

Guido van Rossum's avatar
Guido van Rossum committed
414
static PyObject *
415
sys_settrace(PyObject *self, PyObject *args)
416
{
417 418 419 420 421 422 423 424
    if (trace_init() == -1)
        return NULL;
    if (args == Py_None)
        PyEval_SetTrace(NULL, NULL);
    else
        PyEval_SetTrace(trace_trampoline, args);
    Py_INCREF(Py_None);
    return Py_None;
425 426
}

427
PyDoc_STRVAR(settrace_doc,
428 429 430
"settrace(function)\n\
\n\
Set the global debug tracing function.  It will be called on each\n\
431 432
function call.  See the debugger chapter in the library manual."
);
433

434 435 436
static PyObject *
sys_gettrace(PyObject *self, PyObject *args)
{
437 438
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *temp = tstate->c_traceobj;
439

440 441 442 443
    if (temp == NULL)
        temp = Py_None;
    Py_INCREF(temp);
    return temp;
444 445 446 447 448 449 450 451 452
}

PyDoc_STRVAR(gettrace_doc,
"gettrace()\n\
\n\
Return the global debug tracing function set with sys.settrace.\n\
See the debugger chapter in the library manual."
);

Guido van Rossum's avatar
Guido van Rossum committed
453
static PyObject *
454
sys_setprofile(PyObject *self, PyObject *args)
455
{
456 457 458 459 460 461 462 463
    if (trace_init() == -1)
        return NULL;
    if (args == Py_None)
        PyEval_SetProfile(NULL, NULL);
    else
        PyEval_SetProfile(profile_trampoline, args);
    Py_INCREF(Py_None);
    return Py_None;
464 465
}

466
PyDoc_STRVAR(setprofile_doc,
467 468 469
"setprofile(function)\n\
\n\
Set the profiling function.  It will be called on each function call\n\
470 471
and return.  See the profiler chapter in the library manual."
);
472

473 474 475
static PyObject *
sys_getprofile(PyObject *self, PyObject *args)
{
476 477
    PyThreadState *tstate = PyThreadState_GET();
    PyObject *temp = tstate->c_profileobj;
478

479 480 481 482
    if (temp == NULL)
        temp = Py_None;
    Py_INCREF(temp);
    return temp;
483 484 485 486 487 488 489 490 491
}

PyDoc_STRVAR(getprofile_doc,
"getprofile()\n\
\n\
Return the profiling function set with sys.setprofile.\n\
See the profiler chapter in the library manual."
);

Antoine Pitrou's avatar
Antoine Pitrou committed
492 493
static int _check_interval = 100;

Guido van Rossum's avatar
Guido van Rossum committed
494
static PyObject *
495
sys_setcheckinterval(PyObject *self, PyObject *args)
496
{
497 498 499 500 501 502 503 504 505
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
                     "sys.getcheckinterval() and sys.setcheckinterval() "
                     "are deprecated.  Use sys.setswitchinterval() "
                     "instead.", 1) < 0)
        return NULL;
    if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_check_interval))
        return NULL;
    Py_INCREF(Py_None);
    return Py_None;
506 507
}

508
PyDoc_STRVAR(setcheckinterval_doc,
509 510 511
"setcheckinterval(n)\n\
\n\
Tell the Python interpreter to check for asynchronous events every\n\
512 513
n instructions.  This also affects how often thread switches occur."
);
514

515 516 517
static PyObject *
sys_getcheckinterval(PyObject *self, PyObject *args)
{
518 519 520 521 522 523
    if (PyErr_WarnEx(PyExc_DeprecationWarning,
                     "sys.getcheckinterval() and sys.setcheckinterval() "
                     "are deprecated.  Use sys.getswitchinterval() "
                     "instead.", 1) < 0)
        return NULL;
    return PyLong_FromLong(_check_interval);
524 525 526 527 528 529
}

PyDoc_STRVAR(getcheckinterval_doc,
"getcheckinterval() -> current check interval; see setcheckinterval()."
);

Antoine Pitrou's avatar
Antoine Pitrou committed
530 531 532 533
#ifdef WITH_THREAD
static PyObject *
sys_setswitchinterval(PyObject *self, PyObject *args)
{
534 535 536 537 538 539 540 541 542 543 544
    double d;
    if (!PyArg_ParseTuple(args, "d:setswitchinterval", &d))
        return NULL;
    if (d <= 0.0) {
        PyErr_SetString(PyExc_ValueError,
                        "switch interval must be strictly positive");
        return NULL;
    }
    _PyEval_SetSwitchInterval((unsigned long) (1e6 * d));
    Py_INCREF(Py_None);
    return Py_None;
Antoine Pitrou's avatar
Antoine Pitrou committed
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
}

PyDoc_STRVAR(setswitchinterval_doc,
"setswitchinterval(n)\n\
\n\
Set the ideal thread switching delay inside the Python interpreter\n\
The actual frequency of switching threads can be lower if the\n\
interpreter executes long sequences of uninterruptible code\n\
(this is implementation-specific and workload-dependent).\n\
\n\
The parameter must represent the desired switching delay in seconds\n\
A typical value is 0.005 (5 milliseconds)."
);

static PyObject *
sys_getswitchinterval(PyObject *self, PyObject *args)
{
562
    return PyFloat_FromDouble(1e-6 * _PyEval_GetSwitchInterval());
Antoine Pitrou's avatar
Antoine Pitrou committed
563 564 565 566 567 568 569 570
}

PyDoc_STRVAR(getswitchinterval_doc,
"getswitchinterval() -> current thread switch interval; see setswitchinterval()."
);

#endif /* WITH_THREAD */

571 572 573 574
#ifdef WITH_TSC
static PyObject *
sys_settscdump(PyObject *self, PyObject *args)
{
575 576 577 578 579 580 581 582 583 584 585
    int bool;
    PyThreadState *tstate = PyThreadState_Get();

    if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
        return NULL;
    if (bool)
        tstate->interp->tscdump = 1;
    else
        tstate->interp->tscdump = 0;
    Py_INCREF(Py_None);
    return Py_None;
586

587 588
}

589
PyDoc_STRVAR(settscdump_doc,
590 591 592 593
"settscdump(bool)\n\
\n\
If true, tell the Python interpreter to dump VM measurements to\n\
stderr.  If false, turn off dump.  The measurements are based on the\n\
Michael W. Hudson's avatar
Michael W. Hudson committed
594
processor's time-stamp counter."
595
);
Neal Norwitz's avatar
Neal Norwitz committed
596
#endif /* TSC */
597

598 599 600
static PyObject *
sys_setrecursionlimit(PyObject *self, PyObject *args)
{
601 602 603 604 605 606 607 608 609 610 611
    int new_limit;
    if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
        return NULL;
    if (new_limit <= 0) {
        PyErr_SetString(PyExc_ValueError,
                        "recursion limit must be positive");
        return NULL;
    }
    Py_SetRecursionLimit(new_limit);
    Py_INCREF(Py_None);
    return Py_None;
612 613
}

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
static PyTypeObject Hash_InfoType;

PyDoc_STRVAR(hash_info_doc,
"hash_info\n\
\n\
A struct sequence providing parameters used for computing\n\
numeric hashes.  The attributes are read only.");

static PyStructSequence_Field hash_info_fields[] = {
    {"width", "width of the type used for hashing, in bits"},
    {"modulus", "prime number giving the modulus on which the hash "
                "function is based"},
    {"inf", "value to be used for hash of a positive infinity"},
    {"nan", "value to be used for hash of a nan"},
    {"imag", "multiplier used for the imaginary part of a complex number"},
    {NULL, NULL}
};

static PyStructSequence_Desc hash_info_desc = {
    "sys.hash_info",
    hash_info_doc,
    hash_info_fields,
    5,
};

639
static PyObject *
640 641 642 643 644 645 646 647
get_hash_info(void)
{
    PyObject *hash_info;
    int field = 0;
    hash_info = PyStructSequence_New(&Hash_InfoType);
    if (hash_info == NULL)
        return NULL;
    PyStructSequence_SET_ITEM(hash_info, field++,
648
                              PyLong_FromLong(8*sizeof(Py_hash_t)));
649
    PyStructSequence_SET_ITEM(hash_info, field++,
650
                              PyLong_FromSsize_t(_PyHASH_MODULUS));
651 652 653 654 655 656 657 658 659 660 661 662 663 664
    PyStructSequence_SET_ITEM(hash_info, field++,
                              PyLong_FromLong(_PyHASH_INF));
    PyStructSequence_SET_ITEM(hash_info, field++,
                              PyLong_FromLong(_PyHASH_NAN));
    PyStructSequence_SET_ITEM(hash_info, field++,
                              PyLong_FromLong(_PyHASH_IMAG));
    if (PyErr_Occurred()) {
        Py_CLEAR(hash_info);
        return NULL;
    }
    return hash_info;
}


665
PyDoc_STRVAR(setrecursionlimit_doc,
666 667 668 669 670
"setrecursionlimit(n)\n\
\n\
Set the maximum depth of the Python interpreter stack to n.  This\n\
limit prevents infinite recursion from causing an overflow of the C\n\
stack and crashing Python.  The highest possible limit is platform-\n\
671 672
dependent."
);
673 674

static PyObject *
675
sys_getrecursionlimit(PyObject *self)
676
{
677
    return PyLong_FromLong(Py_GetRecursionLimit());
678 679
}

680
PyDoc_STRVAR(getrecursionlimit_doc,
681 682 683 684
"getrecursionlimit()\n\
\n\
Return the current value of the recursion limit, the maximum depth\n\
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 689 690 691
#ifdef MS_WINDOWS
PyDoc_STRVAR(getwindowsversion_doc,
"getwindowsversion()\n\
\n\
692 693 694
Return information about the running version of Windows as a named tuple.\n\
The members are named: major, minor, build, platform, service_pack,\n\
service_pack_major, service_pack_minor, suite_mask, and product_type. For\n\
Ezio Melotti's avatar
Ezio Melotti committed
695
backward compatibility, only the first 5 items are available by indexing.\n\
696 697 698 699
All elements are numbers, except service_pack which is a string. Platform\n\
may be 0 for win32s, 1 for Windows 9x/ME, 2 for Windows NT/2000/XP/Vista/7,\n\
3 for Windows CE. Product_type may be 1 for a workstation, 2 for a domain\n\
controller, 3 for a server."
700 701
);

702 703 704
static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};

static PyStructSequence_Field windows_version_fields[] = {
705 706 707 708 709 710 711 712 713 714
    {"major", "Major version number"},
    {"minor", "Minor version number"},
    {"build", "Build number"},
    {"platform", "Operating system platform"},
    {"service_pack", "Latest Service Pack installed on the system"},
    {"service_pack_major", "Service Pack major version number"},
    {"service_pack_minor", "Service Pack minor version number"},
    {"suite_mask", "Bit mask identifying available product suites"},
    {"product_type", "System product type"},
    {0}
715 716 717
};

static PyStructSequence_Desc windows_version_desc = {
718 719 720 721 722 723
    "sys.getwindowsversion",  /* name */
    getwindowsversion_doc,    /* doc */
    windows_version_fields,   /* fields */
    5                         /* For backward compatibility,
                                 only the first 5 items are accessible
                                 via indexing, the rest are name only */
724 725
};

726 727 728
static PyObject *
sys_getwindowsversion(PyObject *self)
{
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
    PyObject *version;
    int pos = 0;
    OSVERSIONINFOEX ver;
    ver.dwOSVersionInfoSize = sizeof(ver);
    if (!GetVersionEx((OSVERSIONINFO*) &ver))
        return PyErr_SetFromWindowsErr(0);

    version = PyStructSequence_New(&WindowsVersionType);
    if (version == NULL)
        return NULL;

    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMajorVersion));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwMinorVersion));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwBuildNumber));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.dwPlatformId));
    PyStructSequence_SET_ITEM(version, pos++, PyUnicode_FromString(ver.szCSDVersion));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMajor));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wServicePackMinor));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wSuiteMask));
    PyStructSequence_SET_ITEM(version, pos++, PyLong_FromLong(ver.wProductType));

    return version;
751 752 753 754
}

#endif /* MS_WINDOWS */

755 756 757 758
#ifdef HAVE_DLOPEN
static PyObject *
sys_setdlopenflags(PyObject *self, PyObject *args)
{
759 760 761 762 763 764 765 766 767
    int new_val;
    PyThreadState *tstate = PyThreadState_GET();
    if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
        return NULL;
    if (!tstate)
        return NULL;
    tstate->interp->dlopenflags = new_val;
    Py_INCREF(Py_None);
    return Py_None;
768 769
}

770
PyDoc_STRVAR(setdlopenflags_doc,
771 772
"setdlopenflags(n) -> None\n\
\n\
773 774 775 776 777
Set the flags used by the interpreter for dlopen calls, such as when the\n\
interpreter loads extension modules.  Among other things, this will enable\n\
a lazy resolving of symbols when importing a module, if called as\n\
sys.setdlopenflags(0).  To share symbols across extension modules, call as\n\
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 781 782

static PyObject *
sys_getdlopenflags(PyObject *self, PyObject *args)
{
783 784 785 786
    PyThreadState *tstate = PyThreadState_GET();
    if (!tstate)
        return NULL;
    return PyLong_FromLong(tstate->interp->dlopenflags);
787 788
}

789
PyDoc_STRVAR(getdlopenflags_doc,
790 791
"getdlopenflags() -> int\n\
\n\
792 793 794
Return the current value of the flags that are used for dlopen calls.\n\
The flag constants are defined in the ctypes and DLFCN modules.");

795
#endif  /* HAVE_DLOPEN */
796

797 798 799 800
#ifdef USE_MALLOPT
/* Link with -lmalloc (or -lmpc) on an SGI */
#include <malloc.h>

Guido van Rossum's avatar
Guido van Rossum committed
801
static PyObject *
802
sys_mdebug(PyObject *self, PyObject *args)
803
{
804 805 806 807 808 809
    int flag;
    if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
        return NULL;
    mallopt(M_DEBUG, flag);
    Py_INCREF(Py_None);
    return Py_None;
810 811 812
}
#endif /* USE_MALLOPT */

813
static PyObject *
814
sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
815
{
816
    PyObject *res = NULL;
817
    static PyObject *gc_head_size = NULL;
818 819 820
    static char *kwlist[] = {"object", "default", 0};
    PyObject *o, *dflt = NULL;
    PyObject *method;
821
    _Py_IDENTIFIER(__sizeof__);
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
                                     kwlist, &o, &dflt))
        return NULL;

    /* Initialize static variable for GC head size */
    if (gc_head_size == NULL) {
        gc_head_size = PyLong_FromSsize_t(sizeof(PyGC_Head));
        if (gc_head_size == NULL)
            return NULL;
    }

    /* Make sure the type is initialized. float gets initialized late */
    if (PyType_Ready(Py_TYPE(o)) < 0)
        return NULL;

838
    method = _PyObject_LookupSpecial(o, &PyId___sizeof__);
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867
    if (method == NULL) {
        if (!PyErr_Occurred())
            PyErr_Format(PyExc_TypeError,
                         "Type %.100s doesn't define __sizeof__",
                         Py_TYPE(o)->tp_name);
    }
    else {
        res = PyObject_CallFunctionObjArgs(method, NULL);
        Py_DECREF(method);
    }

    /* Has a default value been given */
    if ((res == NULL) && (dflt != NULL) &&
        PyErr_ExceptionMatches(PyExc_TypeError))
    {
        PyErr_Clear();
        Py_INCREF(dflt);
        return dflt;
    }
    else if (res == NULL)
        return res;

    /* add gc_head size */
    if (PyObject_IS_GC(o)) {
        PyObject *tmp = res;
        res = PyNumber_Add(tmp, gc_head_size);
        Py_DECREF(tmp);
    }
    return res;
868 869 870
}

PyDoc_STRVAR(getsizeof_doc,
871
"getsizeof(object, default) -> int\n\
872 873 874
\n\
Return the size of object in bytes.");

Guido van Rossum's avatar
Guido van Rossum committed
875
static PyObject *
876
sys_getrefcount(PyObject *self, PyObject *arg)
877
{
878
    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 891
"getrefcount(object) -> integer\n\
\n\
892 893 894
Return the reference count of object.  The count returned is generally\n\
one higher than you might expect, because it includes the (temporary)\n\
reference as an argument to getrefcount()."
895
);
896

897 898
#ifdef COUNT_ALLOCS
static PyObject *
899
sys_getcounts(PyObject *self)
900
{
901
    extern PyObject *get_counts(void);
902

903
    return get_counts();
904 905 906
}
#endif

907
PyDoc_STRVAR(getframe_doc,
908 909 910 911 912 913 914 915
"_getframe([depth]) -> frameobject\n\
\n\
Return a frame object from the call stack.  If optional integer depth is\n\
given, return the frame object that many calls below the top of the stack.\n\
If that is deeper than the call stack, ValueError is raised.  The default\n\
for depth is zero, returning the frame at the top of the call stack.\n\
\n\
This function should be used for internal and specialized\n\
916 917
purposes only."
);
918 919 920 921

static PyObject *
sys_getframe(PyObject *self, PyObject *args)
{
922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
    PyFrameObject *f = PyThreadState_GET()->frame;
    int depth = -1;

    if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
        return NULL;

    while (depth > 0 && f != NULL) {
        f = f->f_back;
        --depth;
    }
    if (f == NULL) {
        PyErr_SetString(PyExc_ValueError,
                        "call stack is not deep enough");
        return NULL;
    }
    Py_INCREF(f);
    return (PyObject*)f;
939 940
}

941 942 943 944 945 946 947 948 949 950 951 952
PyDoc_STRVAR(current_frames_doc,
"_current_frames() -> dictionary\n\
\n\
Return a dictionary mapping each current thread T's thread id to T's\n\
current stack frame.\n\
\n\
This function should be used for specialized purposes only."
);

static PyObject *
sys_current_frames(PyObject *self, PyObject *noargs)
{
953
    return _PyThread_CurrentFrames();
954 955
}

956 957 958 959 960 961 962 963 964 965 966
PyDoc_STRVAR(call_tracing_doc,
"call_tracing(func, args) -> object\n\
\n\
Call func(*args), while tracing is enabled.  The tracing state is\n\
saved, and restored afterwards.  This is intended to be called from\n\
a debugger from a checkpoint, to recursively debug some other code."
);

static PyObject *
sys_call_tracing(PyObject *self, PyObject *args)
{
967 968 969 970
    PyObject *func, *funcargs;
    if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
        return NULL;
    return _PyEval_CallTracing(func, funcargs);
971 972
}

973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
PyDoc_STRVAR(callstats_doc,
"callstats() -> tuple of integers\n\
\n\
Return a tuple of function call statistics, if CALL_PROFILE was defined\n\
when Python was built.  Otherwise, return None.\n\
\n\
When enabled, this function returns detailed, implementation-specific\n\
details about the number of function calls executed. The return value is\n\
a 11-tuple where the entries in the tuple are counts of:\n\
0. all function calls\n\
1. calls to PyFunction_Type objects\n\
2. PyFunction calls that do not create an argument tuple\n\
3. PyFunction calls that do not create an argument tuple\n\
   and bypass PyEval_EvalCodeEx()\n\
4. PyMethod calls\n\
5. PyMethod calls on bound methods\n\
6. PyType calls\n\
7. PyCFunction calls\n\
8. generator calls\n\
9. All other calls\n\
10. Number of stack pops performed by call_function()"
);
995

996 997 998 999
#ifdef __cplusplus
extern "C" {
#endif

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
static PyObject *
sys_debugmallocstats(PyObject *self, PyObject *args)
{
#ifdef WITH_PYMALLOC
    _PyObject_DebugMallocStats(stderr);
    fputc('\n', stderr);
#endif
    _PyObject_DebugTypeStats(stderr);

    Py_RETURN_NONE;
}
PyDoc_STRVAR(debugmallocstats_doc,
"_debugmallocstats()\n\
\n\
Print summary info to stderr about the state of\n\
pymalloc's structures.\n\
\n\
In Py_DEBUG mode, also perform some expensive internal consistency\n\
checks.\n\
");

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 1027
#ifdef DYNAMIC_EXECUTION_PROFILE
/* Defined in ceval.c because it uses static globals if that file */
1028
extern PyObject *_Py_GetDXProfile(PyObject *,  PyObject *);
1029 1030
#endif

1031 1032 1033 1034
#ifdef __cplusplus
}
#endif

Christian Heimes's avatar
Christian Heimes committed
1035 1036 1037
static PyObject *
sys_clear_type_cache(PyObject* self, PyObject* args)
{
1038 1039
    PyType_ClearCache();
    Py_RETURN_NONE;
Christian Heimes's avatar
Christian Heimes committed
1040 1041 1042 1043 1044 1045 1046
}

PyDoc_STRVAR(sys_clear_type_cache__doc__,
"_clear_type_cache() -> None\n\
Clear the internal type lookup cache.");


Guido van Rossum's avatar
Guido van Rossum committed
1047
static PyMethodDef sys_methods[] = {
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060
    /* Might as well keep this in alphabetic order */
    {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
     callstats_doc},
    {"_clear_type_cache",       sys_clear_type_cache,     METH_NOARGS,
     sys_clear_type_cache__doc__},
    {"_current_frames", sys_current_frames, METH_NOARGS,
     current_frames_doc},
    {"displayhook",     sys_displayhook, METH_O, displayhook_doc},
    {"exc_info",        sys_exc_info, METH_NOARGS, exc_info_doc},
    {"excepthook",      sys_excepthook, METH_VARARGS, excepthook_doc},
    {"exit",            sys_exit, METH_VARARGS, exit_doc},
    {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
     METH_NOARGS, getdefaultencoding_doc},
1061
#ifdef HAVE_DLOPEN
1062 1063
    {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
     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 1072
    {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
     METH_NOARGS, getfilesystemencoding_doc},
1073
#ifdef Py_TRACE_REFS
1074
    {"getobjects",      _Py_GetObjects, METH_VARARGS},
1075 1076
#endif
#ifdef Py_REF_DEBUG
1077
    {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
1078
#endif
1079 1080 1081 1082 1083 1084
    {"getrefcount",     (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
    {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
     getrecursionlimit_doc},
    {"getsizeof",   (PyCFunction)sys_getsizeof,
     METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
    {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
1085
#ifdef MS_WINDOWS
1086 1087
    {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
     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 1094 1095 1096
    {"setcheckinterval",        sys_setcheckinterval, METH_VARARGS,
     setcheckinterval_doc},
    {"getcheckinterval",        sys_getcheckinterval, METH_NOARGS,
     getcheckinterval_doc},
Antoine Pitrou's avatar
Antoine Pitrou committed
1097
#ifdef WITH_THREAD
1098 1099 1100 1101
    {"setswitchinterval",       sys_setswitchinterval, METH_VARARGS,
     setswitchinterval_doc},
    {"getswitchinterval",       sys_getswitchinterval, METH_NOARGS,
     getswitchinterval_doc},
Antoine Pitrou's avatar
Antoine Pitrou committed
1102
#endif
1103
#ifdef HAVE_DLOPEN
1104 1105
    {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
     setdlopenflags_doc},
1106
#endif
1107 1108 1109 1110
    {"setprofile",      sys_setprofile, METH_O, setprofile_doc},
    {"getprofile",      sys_getprofile, METH_NOARGS, getprofile_doc},
    {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
     setrecursionlimit_doc},
1111
#ifdef WITH_TSC
1112
    {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
1113
#endif
1114 1115 1116
    {"settrace",        sys_settrace, METH_O, settrace_doc},
    {"gettrace",        sys_gettrace, METH_NOARGS, gettrace_doc},
    {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
1117 1118
    {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
     debugmallocstats_doc},
1119
    {NULL,              NULL}           /* sentinel */
Guido van Rossum's avatar
Guido van Rossum committed
1120 1121
};

Guido van Rossum's avatar
Guido van Rossum committed
1122
static PyObject *
1123
list_builtin_module_names(void)
1124
{
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146
    PyObject *list = PyList_New(0);
    int i;
    if (list == NULL)
        return NULL;
    for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
        PyObject *name = PyUnicode_FromString(
            PyImport_Inittab[i].name);
        if (name == NULL)
            break;
        PyList_Append(list, name);
        Py_DECREF(name);
    }
    if (PyList_Sort(list) != 0) {
        Py_DECREF(list);
        list = NULL;
    }
    if (list) {
        PyObject *v = PyList_AsTuple(list);
        Py_DECREF(list);
        list = v;
    }
    return list;
1147 1148
}

1149 1150 1151 1152 1153
static PyObject *warnoptions = NULL;

void
PySys_ResetWarnOptions(void)
{
1154 1155 1156
    if (warnoptions == NULL || !PyList_Check(warnoptions))
        return;
    PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
1157 1158 1159
}

void
1160
PySys_AddWarnOptionUnicode(PyObject *unicode)
1161
{
1162 1163 1164 1165 1166 1167
    if (warnoptions == NULL || !PyList_Check(warnoptions)) {
        Py_XDECREF(warnoptions);
        warnoptions = PyList_New(0);
        if (warnoptions == NULL)
            return;
    }
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179
    PyList_Append(warnoptions, unicode);
}

void
PySys_AddWarnOption(const wchar_t *s)
{
    PyObject *unicode;
    unicode = PyUnicode_FromWideChar(s, -1);
    if (unicode == NULL)
        return;
    PySys_AddWarnOptionUnicode(unicode);
    Py_DECREF(unicode);
1180 1181
}

Christian Heimes's avatar
Christian Heimes committed
1182 1183 1184 1185 1186 1187
int
PySys_HasWarnOptions(void)
{
    return (warnoptions != NULL && (PyList_Size(warnoptions) > 0)) ? 1 : 0;
}

1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
static PyObject *xoptions = NULL;

static PyObject *
get_xoptions(void)
{
    if (xoptions == NULL || !PyDict_Check(xoptions)) {
        Py_XDECREF(xoptions);
        xoptions = PyDict_New();
    }
    return xoptions;
}

void
PySys_AddXOption(const wchar_t *s)
{
    PyObject *opts;
    PyObject *name = NULL, *value = NULL;
    const wchar_t *name_end;

    opts = get_xoptions();
    if (opts == NULL)
        goto error;

    name_end = wcschr(s, L'=');
    if (!name_end) {
        name = PyUnicode_FromWideChar(s, -1);
        value = Py_True;
        Py_INCREF(value);
    }
    else {
        name = PyUnicode_FromWideChar(s, name_end - s);
        value = PyUnicode_FromWideChar(name_end + 1, -1);
    }
    if (name == NULL || value == NULL)
        goto error;
1223
    PyDict_SetItem(opts, name, value);
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
    Py_DECREF(name);
    Py_DECREF(value);
    return;

error:
    Py_XDECREF(name);
    Py_XDECREF(value);
    /* No return value, therefore clear error state if possible */
    if (_Py_atomic_load_relaxed(&_PyThreadState_Current))
        PyErr_Clear();
}

PyObject *
PySys_GetXOptions(void)
{
    return get_xoptions();
}

1242 1243 1244 1245
/* XXX This doc string is too long to be a single string literal in VC++ 5.0.
   Two literals concatenated works just fine.  If you have a K&R compiler
   or other abomination that however *does* understand longer strings,
   get rid of the !!! comment in the middle and the quotes that surround it. */
1246 1247
PyDoc_VAR(sys_doc) =
PyDoc_STR(
1248 1249 1250 1251 1252 1253 1254 1255
"This module provides access to some objects used or maintained by the\n\
interpreter and to functions that interact strongly with the interpreter.\n\
\n\
Dynamic objects:\n\
\n\
argv -- command line arguments; argv[0] is the script pathname if known\n\
path -- module search path; path[0] is the script directory, else ''\n\
modules -- dictionary of loaded modules\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1256 1257 1258 1259 1260 1261
\n\
displayhook -- called to show results in an interactive session\n\
excepthook -- called to handle any uncaught exception other than SystemExit\n\
  To customize printing in an interactive session or to install a custom\n\
  top-level exception handler, assign other functions to replace these.\n\
\n\
Benjamin Peterson's avatar
Benjamin Peterson committed
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\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1265 1266
  By assigning other file objects (or objects that behave like files)\n\
  to these, it is possible to redirect all of the interpreter's I/O.\n\
1267 1268 1269 1270 1271 1272
\n\
last_type -- type of last uncaught exception\n\
last_value -- value of last uncaught exception\n\
last_traceback -- traceback of last uncaught exception\n\
  These three are only available in an interactive session after a\n\
  traceback has been printed.\n\
1273
"
1274
)
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1275
/* concatenating string here */
1276
PyDoc_STR(
1277
"\n\
1278 1279
Static objects:\n\
\n\
1280 1281 1282
builtin_module_names -- tuple of module names built into this interpreter\n\
copyright -- copyright notice pertaining to this interpreter\n\
exec_prefix -- prefix used to find the machine-specific Python library\n\
Petri Lehtinen's avatar
Petri Lehtinen committed
1283
executable -- absolute path of the executable binary of the Python interpreter\n\
1284 1285 1286
float_info -- a struct sequence with information about the float implementation.\n\
float_repr_style -- string indicating the style of repr() output for floats\n\
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 1292
platform -- platform identifier\n\
prefix -- prefix used to find the Python library\n\
1293 1294 1295
thread_info -- a struct sequence with information about the thread implementation.\n\
version -- the version of this interpreter as a string\n\
version_info -- version information as a named tuple\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1296
"
1297
)
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1298 1299
#ifdef MS_WINDOWS
/* concatenating string here */
1300
PyDoc_STR(
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1301
"dllhandle -- [Windows only] integer handle of the Python DLL\n\
1302
winver -- [Windows only] version number of the Python DLL\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1303
"
1304
)
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1305
#endif /* MS_WINDOWS */
1306
PyDoc_STR(
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1307 1308 1309 1310 1311
"__stdin__ -- the original stdin; don't touch!\n\
__stdout__ -- the original stdout; don't touch!\n\
__stderr__ -- the original stderr; don't touch!\n\
__displayhook__ -- the original displayhook; don't touch!\n\
__excepthook__ -- the original excepthook; don't touch!\n\
1312 1313 1314
\n\
Functions:\n\
\n\
1315
displayhook() -- print an object to the screen, and save it in builtins._\n\
Ka-Ping Yee's avatar
Ka-Ping Yee committed
1316
excepthook() -- print an exception and its traceback to sys.stderr\n\
1317 1318
exc_info() -- return thread-safe information about the current exception\n\
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 1336 1337 1338 1339 1340 1341 1342

PyDoc_STRVAR(flags__doc__,
"sys.flags\n\
\n\
Flags provided through command line arguments or environment vars.");

static PyTypeObject FlagsType;

static PyStructSequence_Field flags_fields[] = {
1343 1344 1345 1346 1347 1348 1349 1350 1351
    {"debug",                   "-d"},
    {"inspect",                 "-i"},
    {"interactive",             "-i"},
    {"optimize",                "-O or -OO"},
    {"dont_write_bytecode",     "-B"},
    {"no_user_site",            "-s"},
    {"no_site",                 "-S"},
    {"ignore_environment",      "-E"},
    {"verbose",                 "-v"},
1352
#ifdef RISCOS
1353
    {"riscos_wimp",             "???"},
1354
#endif
1355 1356
    /* {"unbuffered",                   "-u"}, */
    /* {"skip_first",                   "-x"}, */
1357 1358
    {"bytes_warning",           "-b"},
    {"quiet",                   "-q"},
1359
    {"hash_randomization",      "-R"},
1360
    {0}
1361 1362 1363
};

static PyStructSequence_Desc flags_desc = {
1364 1365 1366
    "sys.flags",        /* name */
    flags__doc__,       /* doc */
    flags_fields,       /* fields */
1367
#ifdef RISCOS
1368
    13
1369
#else
1370
    12
1371 1372 1373 1374 1375 1376
#endif
};

static PyObject*
make_flags(void)
{
1377 1378
    int pos = 0;
    PyObject *seq;
1379

1380 1381 1382
    seq = PyStructSequence_New(&FlagsType);
    if (seq == NULL)
        return NULL;
1383 1384

#define SetFlag(flag) \
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395
    PyStructSequence_SET_ITEM(seq, pos++, PyLong_FromLong(flag))

    SetFlag(Py_DebugFlag);
    SetFlag(Py_InspectFlag);
    SetFlag(Py_InteractiveFlag);
    SetFlag(Py_OptimizeFlag);
    SetFlag(Py_DontWriteBytecodeFlag);
    SetFlag(Py_NoUserSiteDirectory);
    SetFlag(Py_NoSiteFlag);
    SetFlag(Py_IgnoreEnvironmentFlag);
    SetFlag(Py_VerboseFlag);
1396
#ifdef RISCOS
1397
    SetFlag(Py_RISCOSWimpFlag);
1398
#endif
1399 1400
    /* SetFlag(saw_unbuffered_flag); */
    /* SetFlag(skipfirstline); */
Christian Heimes's avatar
Christian Heimes committed
1401
    SetFlag(Py_BytesWarningFlag);
1402
    SetFlag(Py_QuietFlag);
1403
    SetFlag(Py_HashRandomizationFlag);
1404 1405
#undef SetFlag

1406 1407 1408 1409
    if (PyErr_Occurred()) {
        return NULL;
    }
    return seq;
1410 1411
}

1412 1413 1414 1415 1416 1417 1418 1419
PyDoc_STRVAR(version_info__doc__,
"sys.version_info\n\
\n\
Version information as a named tuple.");

static PyTypeObject VersionInfoType;

static PyStructSequence_Field version_info_fields[] = {
1420 1421 1422 1423 1424 1425
    {"major", "Major release number"},
    {"minor", "Minor release number"},
    {"micro", "Patch release number"},
    {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
    {"serial", "Serial release number"},
    {0}
1426 1427 1428
};

static PyStructSequence_Desc version_info_desc = {
1429 1430 1431 1432
    "sys.version_info",     /* name */
    version_info__doc__,    /* doc */
    version_info_fields,    /* fields */
    5
1433 1434 1435 1436 1437
};

static PyObject *
make_version_info(void)
{
1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    PyObject *version_info;
    char *s;
    int pos = 0;

    version_info = PyStructSequence_New(&VersionInfoType);
    if (version_info == NULL) {
        return NULL;
    }

    /*
     * These release level checks are mutually exclusive and cover
     * the field, so don't get too fancy with the pre-processor!
     */
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
    s = "final";
1459 1460 1461
#endif

#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 1467 1468 1469 1470
    SetIntItem(PY_MAJOR_VERSION);
    SetIntItem(PY_MINOR_VERSION);
    SetIntItem(PY_MICRO_VERSION);
    SetStrItem(s);
    SetIntItem(PY_RELEASE_SERIAL);
1471 1472 1473
#undef SetIntItem
#undef SetStrItem

1474 1475 1476 1477 1478
    if (PyErr_Occurred()) {
        Py_CLEAR(version_info);
        return NULL;
    }
    return version_info;
1479 1480
}

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496
/* sys.implementation values */
#define NAME "cpython"
const char *_PySys_ImplName = NAME;
#define QUOTE(arg) #arg
#define STRIFY(name) QUOTE(name)
#define MAJOR STRIFY(PY_MAJOR_VERSION)
#define MINOR STRIFY(PY_MINOR_VERSION)
#define TAG NAME "-" MAJOR MINOR;
const char *_PySys_ImplCacheTag = TAG;
#undef NAME
#undef QUOTE
#undef STRIFY
#undef MAJOR
#undef MINOR
#undef TAG

1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
static PyObject *
make_impl_info(PyObject *version_info)
{
    int res;
    PyObject *impl_info, *value, *ns;

    impl_info = PyDict_New();
    if (impl_info == NULL)
        return NULL;

    /* populate the dict */

1509
    value = PyUnicode_FromString(_PySys_ImplName);
1510 1511 1512 1513 1514 1515 1516
    if (value == NULL)
        goto error;
    res = PyDict_SetItemString(impl_info, "name", value);
    Py_DECREF(value);
    if (res < 0)
        goto error;

1517
    value = PyUnicode_FromString(_PySys_ImplCacheTag);
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547
    if (value == NULL)
        goto error;
    res = PyDict_SetItemString(impl_info, "cache_tag", value);
    Py_DECREF(value);
    if (res < 0)
        goto error;

    res = PyDict_SetItemString(impl_info, "version", version_info);
    if (res < 0)
        goto error;

    value = PyLong_FromLong(PY_VERSION_HEX);
    if (value == NULL)
        goto error;
    res = PyDict_SetItemString(impl_info, "hexversion", value);
    Py_DECREF(value);
    if (res < 0)
        goto error;

    /* dict ready */

    ns = _PyNamespace_New(impl_info);
    Py_DECREF(impl_info);
    return ns;

error:
    Py_CLEAR(impl_info);
    return NULL;
}

1548
static struct PyModuleDef sysmodule = {
1549 1550 1551 1552 1553 1554 1555 1556 1557
    PyModuleDef_HEAD_INIT,
    "sys",
    sys_doc,
    -1, /* multiple "initialization" just copies the module dict. */
    sys_methods,
    NULL,
    NULL,
    NULL,
    NULL
1558 1559
};

1560
PyObject *
1561
_PySys_Init(void)
Guido van Rossum's avatar
Guido van Rossum committed
1562
{
1563
    PyObject *m, *v, *sysdict, *version_info;
1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580
    char *s;

    m = PyModule_Create(&sysmodule);
    if (m == NULL)
        return NULL;
    sysdict = PyModule_GetDict(m);
#define SET_SYS_FROM_STRING(key, value)                 \
    v = value;                                          \
    if (v != NULL)                                      \
        PyDict_SetItemString(sysdict, key, v);          \
    Py_XDECREF(v)

    /* Check that stdin is not a directory
    Using shell redirection, you can redirect stdin to a directory,
    crashing the Python interpreter. Catch this common mistake here
    and output a useful error message. Note that under MS Windows,
    the shell already prevents that. */
1581
#if !defined(MS_WINDOWS)
1582 1583 1584 1585 1586 1587 1588 1589 1590 1591
    {
        struct stat sb;
        if (fstat(fileno(stdin), &sb) == 0 &&
            S_ISDIR(sb.st_mode)) {
            /* There's nothing more we can do. */
            /* Py_FatalError() will core dump, so just exit. */
            PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
            exit(EXIT_FAILURE);
        }
    }
1592
#endif
1593

1594 1595 1596 1597 1598 1599 1600 1601 1602 1603
    /* stdin/stdout/stderr are now set by pythonrun.c */

    PyDict_SetItemString(sysdict, "__displayhook__",
                         PyDict_GetItemString(sysdict, "displayhook"));
    PyDict_SetItemString(sysdict, "__excepthook__",
                         PyDict_GetItemString(sysdict, "excepthook"));
    SET_SYS_FROM_STRING("version",
                         PyUnicode_FromString(Py_GetVersion()));
    SET_SYS_FROM_STRING("hexversion",
                         PyLong_FromLong(PY_VERSION_HEX));
1604 1605 1606
    SET_SYS_FROM_STRING("_mercurial",
                        Py_BuildValue("(szz)", "CPython", _Py_hgidentifier(),
                                      _Py_hgversion()));
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621
    SET_SYS_FROM_STRING("dont_write_bytecode",
                         PyBool_FromLong(Py_DontWriteBytecodeFlag));
    SET_SYS_FROM_STRING("api_version",
                        PyLong_FromLong(PYTHON_API_VERSION));
    SET_SYS_FROM_STRING("copyright",
                        PyUnicode_FromString(Py_GetCopyright()));
    SET_SYS_FROM_STRING("platform",
                        PyUnicode_FromString(Py_GetPlatform()));
    SET_SYS_FROM_STRING("executable",
                        PyUnicode_FromWideChar(
                               Py_GetProgramFullPath(), -1));
    SET_SYS_FROM_STRING("prefix",
                        PyUnicode_FromWideChar(Py_GetPrefix(), -1));
    SET_SYS_FROM_STRING("exec_prefix",
                        PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1622 1623 1624 1625
    SET_SYS_FROM_STRING("base_prefix",
                        PyUnicode_FromWideChar(Py_GetPrefix(), -1));
    SET_SYS_FROM_STRING("base_exec_prefix",
                        PyUnicode_FromWideChar(Py_GetExecPrefix(), -1));
1626 1627 1628 1629 1630 1631
    SET_SYS_FROM_STRING("maxsize",
                        PyLong_FromSsize_t(PY_SSIZE_T_MAX));
    SET_SYS_FROM_STRING("float_info",
                        PyFloat_GetInfo());
    SET_SYS_FROM_STRING("int_info",
                        PyLong_GetInfo());
1632 1633 1634 1635 1636
    /* initialize hash_info */
    if (Hash_InfoType.tp_name == 0)
        PyStructSequence_InitType(&Hash_InfoType, &hash_info_desc);
    SET_SYS_FROM_STRING("hash_info",
                        get_hash_info());
1637
    SET_SYS_FROM_STRING("maxunicode",
1638
                        PyLong_FromLong(0x10FFFF));
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
    SET_SYS_FROM_STRING("builtin_module_names",
                        list_builtin_module_names());
    {
        /* Assumes that longs are at least 2 bytes long.
           Should be safe! */
        unsigned long number = 1;
        char *value;

        s = (char *) &number;
        if (s[0] == 0)
            value = "big";
        else
            value = "little";
        SET_SYS_FROM_STRING("byteorder",
                            PyUnicode_FromString(value));
    }
1655
#ifdef MS_COREDLL
1656 1657 1658 1659
    SET_SYS_FROM_STRING("dllhandle",
                        PyLong_FromVoidPtr(PyWin_DLLhModule));
    SET_SYS_FROM_STRING("winver",
                        PyUnicode_FromString(PyWin_DLLVersionString));
1660 1661 1662 1663
#endif
#ifdef ABIFLAGS
    SET_SYS_FROM_STRING("abiflags",
                        PyUnicode_FromString(ABIFLAGS));
1664
#endif
1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
    if (warnoptions == NULL) {
        warnoptions = PyList_New(0);
    }
    else {
        Py_INCREF(warnoptions);
    }
    if (warnoptions != NULL) {
        PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
    }

1675 1676 1677 1678 1679
    v = get_xoptions();
    if (v != NULL) {
        PyDict_SetItemString(sysdict, "_xoptions", v);
    }

1680 1681 1682
    /* version_info */
    if (VersionInfoType.tp_name == 0)
        PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
1683 1684
    version_info = make_version_info();
    SET_SYS_FROM_STRING("version_info", version_info);
1685 1686 1687 1688
    /* prevent user from creating new instances */
    VersionInfoType.tp_init = NULL;
    VersionInfoType.tp_new = NULL;

1689 1690 1691
    /* implementation */
    SET_SYS_FROM_STRING("implementation", make_impl_info(version_info));

1692 1693 1694 1695 1696 1697 1698
    /* flags */
    if (FlagsType.tp_name == 0)
        PyStructSequence_InitType(&FlagsType, &flags_desc);
    SET_SYS_FROM_STRING("flags", make_flags());
    /* prevent user from creating new instances */
    FlagsType.tp_init = NULL;
    FlagsType.tp_new = NULL;
1699

1700 1701

#if defined(MS_WINDOWS)
1702 1703 1704 1705 1706 1707
    /* getwindowsversion */
    if (WindowsVersionType.tp_name == 0)
        PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
    /* prevent user from creating new instances */
    WindowsVersionType.tp_init = NULL;
    WindowsVersionType.tp_new = NULL;
1708 1709
#endif

1710
    /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
1711
#ifndef PY_NO_SHORT_FLOAT_REPR
1712 1713
    SET_SYS_FROM_STRING("float_repr_style",
                        PyUnicode_FromString("short"));
1714
#else
1715 1716
    SET_SYS_FROM_STRING("float_repr_style",
                        PyUnicode_FromString("legacy"));
1717 1718
#endif

1719 1720 1721 1722
#ifdef WITH_THREAD
    SET_SYS_FROM_STRING("thread_info", PyThread_GetInfo());
#endif

1723
#undef SET_SYS_FROM_STRING
1724 1725 1726
    if (PyErr_Occurred())
        return NULL;
    return m;
1727 1728
}

Guido van Rossum's avatar
Guido van Rossum committed
1729
static PyObject *
1730
makepathobject(const wchar_t *path, wchar_t delim)
1731
{
1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
    int i, n;
    const wchar_t *p;
    PyObject *v, *w;

    n = 1;
    p = path;
    while ((p = wcschr(p, delim)) != NULL) {
        n++;
        p++;
    }
    v = PyList_New(n);
    if (v == NULL)
        return NULL;
    for (i = 0; ; i++) {
        p = wcschr(path, delim);
        if (p == NULL)
            p = path + wcslen(path); /* End of string */
        w = PyUnicode_FromWideChar(path, (Py_ssize_t)(p - path));
        if (w == NULL) {
            Py_DECREF(v);
            return NULL;
        }
        PyList_SetItem(v, i, w);
        if (*p == '\0')
            break;
        path = p+1;
    }
    return v;
Guido van Rossum's avatar
Guido van Rossum committed
1760 1761 1762
}

void
1763
PySys_SetPath(const wchar_t *path)
Guido van Rossum's avatar
Guido van Rossum committed
1764
{
1765 1766 1767 1768 1769 1770
    PyObject *v;
    if ((v = makepathobject(path, DELIM)) == NULL)
        Py_FatalError("can't create sys.path");
    if (PySys_SetObject("path", v) != 0)
        Py_FatalError("can't assign sys.path");
    Py_DECREF(v);
Guido van Rossum's avatar
Guido van Rossum committed
1771 1772
}

Guido van Rossum's avatar
Guido van Rossum committed
1773
static PyObject *
1774
makeargvobject(int argc, wchar_t **argv)
Guido van Rossum's avatar
Guido van Rossum committed
1775
{
1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    PyObject *av;
    if (argc <= 0 || argv == NULL) {
        /* Ensure at least one (empty) argument is seen */
        static wchar_t *empty_argv[1] = {L""};
        argv = empty_argv;
        argc = 1;
    }
    av = PyList_New(argc);
    if (av != NULL) {
        int i;
        for (i = 0; i < argc; i++) {
1787
#ifdef __VMS
1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
            PyObject *v;

            /* argv[0] is the script pathname if known */
            if (i == 0) {
                char* fn = decc$translate_vms(argv[0]);
                if ((fn == (char *)0) || fn == (char *)-1)
                    v = PyUnicode_FromString(argv[0]);
                else
                    v = PyUnicode_FromString(
                        decc$translate_vms(argv[0]));
            } else
                v = PyUnicode_FromString(argv[i]);
1800
#else
1801
            PyObject *v = PyUnicode_FromWideChar(argv[i], -1);
1802
#endif
1803 1804 1805 1806 1807 1808 1809 1810 1811
            if (v == NULL) {
                Py_DECREF(av);
                av = NULL;
                break;
            }
            PyList_SetItem(av, i, v);
        }
    }
    return av;
Guido van Rossum's avatar
Guido van Rossum committed
1812 1813
}

1814 1815 1816
#define _HAVE_SCRIPT_ARGUMENT(argc, argv) \
  (argc > 0 && argv0 != NULL && \
   wcscmp(argv0, L"-c") != 0 && wcscmp(argv0, L"-m") != 0)
1817 1818 1819

static void
sys_update_path(int argc, wchar_t **argv)
Guido van Rossum's avatar
Guido van Rossum committed
1820
{
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
    wchar_t *argv0;
    wchar_t *p = NULL;
    Py_ssize_t n = 0;
    PyObject *a;
    PyObject *path;
#ifdef HAVE_READLINK
    wchar_t link[MAXPATHLEN+1];
    wchar_t argv0copy[2*MAXPATHLEN+1];
    int nr = 0;
#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 1838 1839 1840 1841 1842

    path = PySys_GetObject("path");
    if (path == NULL)
        return;

    argv0 = argv[0];

1843
#ifdef HAVE_READLINK
1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857
    if (_HAVE_SCRIPT_ARGUMENT(argc, argv))
        nr = _Py_wreadlink(argv0, link, MAXPATHLEN);
    if (nr > 0) {
        /* It's a symlink */
        link[nr] = '\0';
        if (link[0] == SEP)
            argv0 = link; /* Link to absolute path */
        else if (wcschr(link, SEP) == NULL)
            ; /* Link without path */
        else {
            /* Must join(dirname(argv0), link) */
            wchar_t *q = wcsrchr(argv0, SEP);
            if (q == NULL)
                argv0 = link; /* argv0 without path */
1858
            else {
1859 1860 1861 1862 1863
                /* Must make a copy */
                wcscpy(argv0copy, argv0);
                q = wcsrchr(argv0copy, SEP);
                wcscpy(q+1, link);
                argv0 = argv0copy;
1864 1865
            }
        }
1866
    }
1867
#endif /* HAVE_READLINK */
1868
#if SEP == '\\' /* Special case for MS filename syntax */
1869 1870
    if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
        wchar_t *q;
1871
#if defined(MS_WINDOWS) && !defined(MS_WINCE)
1872 1873 1874 1875 1876
        /* This code here replaces the first element in argv with the full
        path that it represents. Under CE, there are no relative paths so
        the argument must be the full path anyway. */
        wchar_t *ptemp;
        if (GetFullPathNameW(argv0,
1877
                           Py_ARRAY_LENGTH(fullpath),
1878 1879 1880 1881
                           fullpath,
                           &ptemp)) {
            argv0 = fullpath;
        }
1882
#endif
1883 1884 1885 1886 1887 1888 1889 1890 1891
        p = wcsrchr(argv0, SEP);
        /* Test for alternate separator */
        q = wcsrchr(p ? p : argv0, '/');
        if (q != NULL)
            p = q;
        if (p != NULL) {
            n = p + 1 - argv0;
            if (n > 1 && p[-1] != ':')
                n--; /* Drop trailing separator */
1892
        }
1893
    }
1894
#else /* All other filename syntaxes */
1895
    if (_HAVE_SCRIPT_ARGUMENT(argc, argv)) {
1896
#if defined(HAVE_REALPATH)
1897
        if (_Py_wrealpath(argv0, fullpath, PATH_MAX)) {
1898
            argv0 = fullpath;
1899
        }
1900 1901 1902 1903 1904
#endif
        p = wcsrchr(argv0, SEP);
    }
    if (p != NULL) {
        n = p + 1 - argv0;
1905
#if SEP == '/' /* Special case for Unix filename syntax */
1906 1907
        if (n > 1)
            n--; /* Drop trailing separator */
1908
#endif /* Unix */
1909
    }
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
#endif /* All others */
    a = PyUnicode_FromWideChar(argv0, n);
    if (a == NULL)
        Py_FatalError("no mem for sys.path insertion");
    if (PyList_Insert(path, 0, a) < 0)
        Py_FatalError("sys.path.insert(0) failed");
    Py_DECREF(a);
}

void
PySys_SetArgvEx(int argc, wchar_t **argv, int updatepath)
{
    PyObject *av = makeargvobject(argc, argv);
    if (av == NULL)
        Py_FatalError("no mem for sys.argv");
    if (PySys_SetObject("argv", av) != 0)
        Py_FatalError("can't assign sys.argv");
1927
    Py_DECREF(av);
1928 1929
    if (updatepath)
        sys_update_path(argc, argv);
Guido van Rossum's avatar
Guido van Rossum committed
1930
}
1931

1932 1933 1934 1935 1936 1937
void
PySys_SetArgv(int argc, wchar_t **argv)
{
    PySys_SetArgvEx(argc, argv, 1);
}

1938 1939 1940 1941
/* Reimplementation of PyFile_WriteString() no calling indirectly
   PyErr_CheckSignals(): avoid the call to PyObject_Str(). */

static int
1942
sys_pyfile_write_unicode(PyObject *unicode, PyObject *file)
1943
{
1944
    PyObject *writer = NULL, *args = NULL, *result = NULL;
1945
    int err;
1946
    _Py_IDENTIFIER(write);
1947

1948 1949 1950
    if (file == NULL)
        return -1;

1951
    writer = _PyObject_GetAttrId(file, &PyId_write);
1952 1953
    if (writer == NULL)
        goto error;
1954

1955 1956 1957
    args = PyTuple_Pack(1, unicode);
    if (args == NULL)
        goto error;
1958

1959 1960 1961 1962 1963 1964 1965
    result = PyEval_CallObject(writer, args);
    if (result == NULL) {
        goto error;
    } else {
        err = 0;
        goto finally;
    }
1966 1967

error:
1968
    err = -1;
1969
finally:
1970 1971 1972 1973
    Py_XDECREF(writer);
    Py_XDECREF(args);
    Py_XDECREF(result);
    return err;
1974 1975
}

1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992
static int
sys_pyfile_write(const char *text, PyObject *file)
{
    PyObject *unicode = NULL;
    int err;

    if (file == NULL)
        return -1;

    unicode = PyUnicode_FromString(text);
    if (unicode == NULL)
        return -1;

    err = sys_pyfile_write_unicode(unicode, file);
    Py_DECREF(unicode);
    return err;
}
1993 1994 1995 1996 1997 1998 1999 2000 2001

/* APIs to write to sys.stdout or sys.stderr using a printf-like interface.
   Adapted from code submitted by Just van Rossum.

   PySys_WriteStdout(format, ...)
   PySys_WriteStderr(format, ...)

      The first function writes to sys.stdout; the second to sys.stderr.  When
      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 2006
      signal handlers: they may raise a new exception whereas sys_write()
      ignores all exceptions.
2007

2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022
      Both take a printf-style format string as their first argument followed
      by a variable length argument list determined by the format string.

      *** WARNING ***

      The format should limit the total size of the formatted output string to
      1000 bytes.  In particular, this means that no unrestricted "%s" formats
      should occur; these should be limited using "%.<N>s where <N> is a
      decimal number calculated so that <N> plus the maximum size of other
      formatted text does not exceed 1000 bytes.  Also watch out for "%f",
      which can print hundreds of digits for very large numbers.

 */

static void
2023
sys_write(char *name, FILE *fp, const char *format, va_list va)
2024
{
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038
    PyObject *file;
    PyObject *error_type, *error_value, *error_traceback;
    char buffer[1001];
    int written;

    PyErr_Fetch(&error_type, &error_value, &error_traceback);
    file = PySys_GetObject(name);
    written = PyOS_vsnprintf(buffer, sizeof(buffer), format, va);
    if (sys_pyfile_write(buffer, file) != 0) {
        PyErr_Clear();
        fputs(buffer, fp);
    }
    if (written < 0 || (size_t)written >= sizeof(buffer)) {
        const char *truncated = "... truncated";
2039
        if (sys_pyfile_write(truncated, file) != 0)
2040 2041 2042
            fputs(truncated, fp);
    }
    PyErr_Restore(error_type, error_value, error_traceback);
2043 2044 2045 2046 2047
}

void
PySys_WriteStdout(const char *format, ...)
{
2048
    va_list va;
2049

2050
    va_start(va, format);
2051
    sys_write("stdout", stdout, format, va);
2052
    va_end(va);
2053 2054 2055 2056 2057
}

void
PySys_WriteStderr(const char *format, ...)
{
2058
    va_list va;
2059

2060
    va_start(va, format);
2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103
    sys_write("stderr", stderr, format, va);
    va_end(va);
}

static void
sys_format(char *name, FILE *fp, const char *format, va_list va)
{
    PyObject *file, *message;
    PyObject *error_type, *error_value, *error_traceback;
    char *utf8;

    PyErr_Fetch(&error_type, &error_value, &error_traceback);
    file = PySys_GetObject(name);
    message = PyUnicode_FromFormatV(format, va);
    if (message != NULL) {
        if (sys_pyfile_write_unicode(message, file) != 0) {
            PyErr_Clear();
            utf8 = _PyUnicode_AsString(message);
            if (utf8 != NULL)
                fputs(utf8, fp);
        }
        Py_DECREF(message);
    }
    PyErr_Restore(error_type, error_value, error_traceback);
}

void
PySys_FormatStdout(const char *format, ...)
{
    va_list va;

    va_start(va, format);
    sys_format("stdout", stdout, format, va);
    va_end(va);
}

void
PySys_FormatStderr(const char *format, ...)
{
    va_list va;

    va_start(va, format);
    sys_format("stderr", stderr, format, va);
2104
    va_end(va);
2105
}