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