object.c revision a701388de1135241b5a8e4c970e06c0e83a66dc0
1 2/* Generic object operations; and implementation of None */ 3 4#include "Python.h" 5#include "frameobject.h" 6 7#ifdef __cplusplus 8extern "C" { 9#endif 10 11#ifdef Py_REF_DEBUG 12Py_ssize_t _Py_RefTotal; 13 14Py_ssize_t 15_Py_GetRefTotal(void) 16{ 17 PyObject *o; 18 Py_ssize_t total = _Py_RefTotal; 19 /* ignore the references to the dummy object of the dicts and sets 20 because they are not reliable and not useful (now that the 21 hash table code is well-tested) */ 22 o = _PyDict_Dummy(); 23 if (o != NULL) 24 total -= o->ob_refcnt; 25 o = _PySet_Dummy(); 26 if (o != NULL) 27 total -= o->ob_refcnt; 28 return total; 29} 30#endif /* Py_REF_DEBUG */ 31 32/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros. 33 These are used by the individual routines for object creation. 34 Do not call them otherwise, they do not initialize the object! */ 35 36#ifdef Py_TRACE_REFS 37/* Head of circular doubly-linked list of all objects. These are linked 38 * together via the _ob_prev and _ob_next members of a PyObject, which 39 * exist only in a Py_TRACE_REFS build. 40 */ 41static PyObject refchain = {&refchain, &refchain}; 42 43/* Insert op at the front of the list of all objects. If force is true, 44 * op is added even if _ob_prev and _ob_next are non-NULL already. If 45 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing. 46 * force should be true if and only if op points to freshly allocated, 47 * uninitialized memory, or you've unlinked op from the list and are 48 * relinking it into the front. 49 * Note that objects are normally added to the list via _Py_NewReference, 50 * which is called by PyObject_Init. Not all objects are initialized that 51 * way, though; exceptions include statically allocated type objects, and 52 * statically allocated singletons (like Py_True and Py_None). 53 */ 54void 55_Py_AddToAllObjects(PyObject *op, int force) 56{ 57#ifdef Py_DEBUG 58 if (!force) { 59 /* If it's initialized memory, op must be in or out of 60 * the list unambiguously. 61 */ 62 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL)); 63 } 64#endif 65 if (force || op->_ob_prev == NULL) { 66 op->_ob_next = refchain._ob_next; 67 op->_ob_prev = &refchain; 68 refchain._ob_next->_ob_prev = op; 69 refchain._ob_next = op; 70 } 71} 72#endif /* Py_TRACE_REFS */ 73 74#ifdef COUNT_ALLOCS 75static PyTypeObject *type_list; 76/* All types are added to type_list, at least when 77 they get one object created. That makes them 78 immortal, which unfortunately contributes to 79 garbage itself. If unlist_types_without_objects 80 is set, they will be removed from the type_list 81 once the last object is deallocated. */ 82static int unlist_types_without_objects; 83extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs; 84extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs; 85extern Py_ssize_t null_strings, one_strings; 86void 87dump_counts(FILE* f) 88{ 89 PyTypeObject *tp; 90 91 for (tp = type_list; tp; tp = tp->tp_next) 92 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, " 93 "freed: %" PY_FORMAT_SIZE_T "d, " 94 "max in use: %" PY_FORMAT_SIZE_T "d\n", 95 tp->tp_name, tp->tp_allocs, tp->tp_frees, 96 tp->tp_maxalloc); 97 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, " 98 "empty: %" PY_FORMAT_SIZE_T "d\n", 99 fast_tuple_allocs, tuple_zero_allocs); 100 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, " 101 "neg: %" PY_FORMAT_SIZE_T "d\n", 102 quick_int_allocs, quick_neg_int_allocs); 103 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, " 104 "1-strings: %" PY_FORMAT_SIZE_T "d\n", 105 null_strings, one_strings); 106} 107 108PyObject * 109get_counts(void) 110{ 111 PyTypeObject *tp; 112 PyObject *result; 113 PyObject *v; 114 115 result = PyList_New(0); 116 if (result == NULL) 117 return NULL; 118 for (tp = type_list; tp; tp = tp->tp_next) { 119 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs, 120 tp->tp_frees, tp->tp_maxalloc); 121 if (v == NULL) { 122 Py_DECREF(result); 123 return NULL; 124 } 125 if (PyList_Append(result, v) < 0) { 126 Py_DECREF(v); 127 Py_DECREF(result); 128 return NULL; 129 } 130 Py_DECREF(v); 131 } 132 return result; 133} 134 135void 136inc_count(PyTypeObject *tp) 137{ 138 if (tp->tp_next == NULL && tp->tp_prev == NULL) { 139 /* first time; insert in linked list */ 140 if (tp->tp_next != NULL) /* sanity check */ 141 Py_FatalError("XXX inc_count sanity check"); 142 if (type_list) 143 type_list->tp_prev = tp; 144 tp->tp_next = type_list; 145 /* Note that as of Python 2.2, heap-allocated type objects 146 * can go away, but this code requires that they stay alive 147 * until program exit. That's why we're careful with 148 * refcounts here. type_list gets a new reference to tp, 149 * while ownership of the reference type_list used to hold 150 * (if any) was transferred to tp->tp_next in the line above. 151 * tp is thus effectively immortal after this. 152 */ 153 Py_INCREF(tp); 154 type_list = tp; 155#ifdef Py_TRACE_REFS 156 /* Also insert in the doubly-linked list of all objects, 157 * if not already there. 158 */ 159 _Py_AddToAllObjects((PyObject *)tp, 0); 160#endif 161 } 162 tp->tp_allocs++; 163 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc) 164 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees; 165} 166 167void dec_count(PyTypeObject *tp) 168{ 169 tp->tp_frees++; 170 if (unlist_types_without_objects && 171 tp->tp_allocs == tp->tp_frees) { 172 /* unlink the type from type_list */ 173 if (tp->tp_prev) 174 tp->tp_prev->tp_next = tp->tp_next; 175 else 176 type_list = tp->tp_next; 177 if (tp->tp_next) 178 tp->tp_next->tp_prev = tp->tp_prev; 179 tp->tp_next = tp->tp_prev = NULL; 180 Py_DECREF(tp); 181 } 182} 183 184#endif 185 186#ifdef Py_REF_DEBUG 187/* Log a fatal error; doesn't return. */ 188void 189_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op) 190{ 191 char buf[300]; 192 193 PyOS_snprintf(buf, sizeof(buf), 194 "%s:%i object at %p has negative ref count " 195 "%" PY_FORMAT_SIZE_T "d", 196 fname, lineno, op, op->ob_refcnt); 197 Py_FatalError(buf); 198} 199 200#endif /* Py_REF_DEBUG */ 201 202void 203Py_IncRef(PyObject *o) 204{ 205 Py_XINCREF(o); 206} 207 208void 209Py_DecRef(PyObject *o) 210{ 211 Py_XDECREF(o); 212} 213 214PyObject * 215PyObject_Init(PyObject *op, PyTypeObject *tp) 216{ 217 if (op == NULL) 218 return PyErr_NoMemory(); 219 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */ 220 Py_TYPE(op) = tp; 221 _Py_NewReference(op); 222 return op; 223} 224 225PyVarObject * 226PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size) 227{ 228 if (op == NULL) 229 return (PyVarObject *) PyErr_NoMemory(); 230 /* Any changes should be reflected in PyObject_INIT_VAR */ 231 op->ob_size = size; 232 Py_TYPE(op) = tp; 233 _Py_NewReference((PyObject *)op); 234 return op; 235} 236 237PyObject * 238_PyObject_New(PyTypeObject *tp) 239{ 240 PyObject *op; 241 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp)); 242 if (op == NULL) 243 return PyErr_NoMemory(); 244 return PyObject_INIT(op, tp); 245} 246 247PyVarObject * 248_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems) 249{ 250 PyVarObject *op; 251 const size_t size = _PyObject_VAR_SIZE(tp, nitems); 252 op = (PyVarObject *) PyObject_MALLOC(size); 253 if (op == NULL) 254 return (PyVarObject *)PyErr_NoMemory(); 255 return PyObject_INIT_VAR(op, tp, nitems); 256} 257 258int 259PyObject_Print(PyObject *op, FILE *fp, int flags) 260{ 261 int ret = 0; 262 if (PyErr_CheckSignals()) 263 return -1; 264#ifdef USE_STACKCHECK 265 if (PyOS_CheckStack()) { 266 PyErr_SetString(PyExc_MemoryError, "stack overflow"); 267 return -1; 268 } 269#endif 270 clearerr(fp); /* Clear any previous error condition */ 271 if (op == NULL) { 272 Py_BEGIN_ALLOW_THREADS 273 fprintf(fp, "<nil>"); 274 Py_END_ALLOW_THREADS 275 } 276 else { 277 if (op->ob_refcnt <= 0) 278 /* XXX(twouters) cast refcount to long until %zd is 279 universally available */ 280 Py_BEGIN_ALLOW_THREADS 281 fprintf(fp, "<refcnt %ld at %p>", 282 (long)op->ob_refcnt, op); 283 Py_END_ALLOW_THREADS 284 else { 285 PyObject *s; 286 if (flags & Py_PRINT_RAW) 287 s = PyObject_Str(op); 288 else 289 s = PyObject_Repr(op); 290 if (s == NULL) 291 ret = -1; 292 else if (PyBytes_Check(s)) { 293 fwrite(PyBytes_AS_STRING(s), 1, 294 PyBytes_GET_SIZE(s), fp); 295 } 296 else if (PyUnicode_Check(s)) { 297 PyObject *t; 298 t = PyUnicode_AsEncodedString(s, "utf-8", "backslashreplace"); 299 if (t == NULL) 300 ret = 0; 301 else { 302 fwrite(PyBytes_AS_STRING(t), 1, 303 PyBytes_GET_SIZE(t), fp); 304 Py_DECREF(t); 305 } 306 } 307 else { 308 PyErr_Format(PyExc_TypeError, 309 "str() or repr() returned '%.100s'", 310 s->ob_type->tp_name); 311 ret = -1; 312 } 313 Py_XDECREF(s); 314 } 315 } 316 if (ret == 0) { 317 if (ferror(fp)) { 318 PyErr_SetFromErrno(PyExc_IOError); 319 clearerr(fp); 320 ret = -1; 321 } 322 } 323 return ret; 324} 325 326/* For debugging convenience. Set a breakpoint here and call it from your DLL */ 327void 328_Py_BreakPoint(void) 329{ 330} 331 332 333/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */ 334void 335_PyObject_Dump(PyObject* op) 336{ 337 if (op == NULL) 338 fprintf(stderr, "NULL\n"); 339 else { 340#ifdef WITH_THREAD 341 PyGILState_STATE gil; 342#endif 343 fprintf(stderr, "object : "); 344#ifdef WITH_THREAD 345 gil = PyGILState_Ensure(); 346#endif 347 (void)PyObject_Print(op, stderr, 0); 348#ifdef WITH_THREAD 349 PyGILState_Release(gil); 350#endif 351 /* XXX(twouters) cast refcount to long until %zd is 352 universally available */ 353 fprintf(stderr, "\n" 354 "type : %s\n" 355 "refcount: %ld\n" 356 "address : %p\n", 357 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name, 358 (long)op->ob_refcnt, 359 op); 360 } 361} 362 363PyObject * 364PyObject_Repr(PyObject *v) 365{ 366 PyObject *res; 367 if (PyErr_CheckSignals()) 368 return NULL; 369#ifdef USE_STACKCHECK 370 if (PyOS_CheckStack()) { 371 PyErr_SetString(PyExc_MemoryError, "stack overflow"); 372 return NULL; 373 } 374#endif 375 if (v == NULL) 376 return PyUnicode_FromString("<NULL>"); 377 if (Py_TYPE(v)->tp_repr == NULL) 378 return PyUnicode_FromFormat("<%s object at %p>", 379 v->ob_type->tp_name, v); 380 res = (*v->ob_type->tp_repr)(v); 381 if (res == NULL) 382 return NULL; 383 if (!PyUnicode_Check(res)) { 384 PyErr_Format(PyExc_TypeError, 385 "__repr__ returned non-string (type %.200s)", 386 res->ob_type->tp_name); 387 Py_DECREF(res); 388 return NULL; 389 } 390#ifndef Py_DEBUG 391 if (PyUnicode_READY(res) < 0) 392 return NULL; 393#endif 394 return res; 395} 396 397PyObject * 398PyObject_Str(PyObject *v) 399{ 400 PyObject *res; 401 if (PyErr_CheckSignals()) 402 return NULL; 403#ifdef USE_STACKCHECK 404 if (PyOS_CheckStack()) { 405 PyErr_SetString(PyExc_MemoryError, "stack overflow"); 406 return NULL; 407 } 408#endif 409 if (v == NULL) 410 return PyUnicode_FromString("<NULL>"); 411 if (PyUnicode_CheckExact(v)) { 412#ifndef Py_DEBUG 413 if (PyUnicode_READY(v) < 0) 414 return NULL; 415#endif 416 Py_INCREF(v); 417 return v; 418 } 419 if (Py_TYPE(v)->tp_str == NULL) 420 return PyObject_Repr(v); 421 422 /* It is possible for a type to have a tp_str representation that loops 423 infinitely. */ 424 if (Py_EnterRecursiveCall(" while getting the str of an object")) 425 return NULL; 426 res = (*Py_TYPE(v)->tp_str)(v); 427 Py_LeaveRecursiveCall(); 428 if (res == NULL) 429 return NULL; 430 if (!PyUnicode_Check(res)) { 431 PyErr_Format(PyExc_TypeError, 432 "__str__ returned non-string (type %.200s)", 433 Py_TYPE(res)->tp_name); 434 Py_DECREF(res); 435 return NULL; 436 } 437#ifndef Py_DEBUG 438 if (PyUnicode_READY(res) < 0) 439 return NULL; 440#endif 441 assert(_PyUnicode_CheckConsistency(res, 1)); 442 return res; 443} 444 445PyObject * 446PyObject_ASCII(PyObject *v) 447{ 448 PyObject *repr, *ascii, *res; 449 450 repr = PyObject_Repr(v); 451 if (repr == NULL) 452 return NULL; 453 454 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */ 455 ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace"); 456 Py_DECREF(repr); 457 if (ascii == NULL) 458 return NULL; 459 460 res = PyUnicode_DecodeASCII( 461 PyBytes_AS_STRING(ascii), 462 PyBytes_GET_SIZE(ascii), 463 NULL); 464 465 Py_DECREF(ascii); 466 return res; 467} 468 469PyObject * 470PyObject_Bytes(PyObject *v) 471{ 472 PyObject *result, *func; 473 _Py_IDENTIFIER(__bytes__); 474 475 if (v == NULL) 476 return PyBytes_FromString("<NULL>"); 477 478 if (PyBytes_CheckExact(v)) { 479 Py_INCREF(v); 480 return v; 481 } 482 483 func = _PyObject_LookupSpecial(v, &PyId___bytes__); 484 if (func != NULL) { 485 result = PyObject_CallFunctionObjArgs(func, NULL); 486 Py_DECREF(func); 487 if (result == NULL) 488 return NULL; 489 if (!PyBytes_Check(result)) { 490 PyErr_Format(PyExc_TypeError, 491 "__bytes__ returned non-bytes (type %.200s)", 492 Py_TYPE(result)->tp_name); 493 Py_DECREF(result); 494 return NULL; 495 } 496 return result; 497 } 498 else if (PyErr_Occurred()) 499 return NULL; 500 return PyBytes_FromObject(v); 501} 502 503/* For Python 3.0.1 and later, the old three-way comparison has been 504 completely removed in favour of rich comparisons. PyObject_Compare() and 505 PyObject_Cmp() are gone, and the builtin cmp function no longer exists. 506 The old tp_compare slot has been renamed to tp_reserved, and should no 507 longer be used. Use tp_richcompare instead. 508 509 See (*) below for practical amendments. 510 511 tp_richcompare gets called with a first argument of the appropriate type 512 and a second object of an arbitrary type. We never do any kind of 513 coercion. 514 515 The tp_richcompare slot should return an object, as follows: 516 517 NULL if an exception occurred 518 NotImplemented if the requested comparison is not implemented 519 any other false value if the requested comparison is false 520 any other true value if the requested comparison is true 521 522 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get 523 NotImplemented. 524 525 (*) Practical amendments: 526 527 - If rich comparison returns NotImplemented, == and != are decided by 528 comparing the object pointer (i.e. falling back to the base object 529 implementation). 530 531*/ 532 533/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */ 534int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE}; 535 536static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="}; 537 538/* Perform a rich comparison, raising TypeError when the requested comparison 539 operator is not supported. */ 540static PyObject * 541do_richcompare(PyObject *v, PyObject *w, int op) 542{ 543 richcmpfunc f; 544 PyObject *res; 545 int checked_reverse_op = 0; 546 547 if (v->ob_type != w->ob_type && 548 PyType_IsSubtype(w->ob_type, v->ob_type) && 549 (f = w->ob_type->tp_richcompare) != NULL) { 550 checked_reverse_op = 1; 551 res = (*f)(w, v, _Py_SwappedOp[op]); 552 if (res != Py_NotImplemented) 553 return res; 554 Py_DECREF(res); 555 } 556 if ((f = v->ob_type->tp_richcompare) != NULL) { 557 res = (*f)(v, w, op); 558 if (res != Py_NotImplemented) 559 return res; 560 Py_DECREF(res); 561 } 562 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) { 563 res = (*f)(w, v, _Py_SwappedOp[op]); 564 if (res != Py_NotImplemented) 565 return res; 566 Py_DECREF(res); 567 } 568 /* If neither object implements it, provide a sensible default 569 for == and !=, but raise an exception for ordering. */ 570 switch (op) { 571 case Py_EQ: 572 res = (v == w) ? Py_True : Py_False; 573 break; 574 case Py_NE: 575 res = (v != w) ? Py_True : Py_False; 576 break; 577 default: 578 /* XXX Special-case None so it doesn't show as NoneType() */ 579 PyErr_Format(PyExc_TypeError, 580 "unorderable types: %.100s() %s %.100s()", 581 v->ob_type->tp_name, 582 opstrings[op], 583 w->ob_type->tp_name); 584 return NULL; 585 } 586 Py_INCREF(res); 587 return res; 588} 589 590/* Perform a rich comparison with object result. This wraps do_richcompare() 591 with a check for NULL arguments and a recursion check. */ 592 593PyObject * 594PyObject_RichCompare(PyObject *v, PyObject *w, int op) 595{ 596 PyObject *res; 597 598 assert(Py_LT <= op && op <= Py_GE); 599 if (v == NULL || w == NULL) { 600 if (!PyErr_Occurred()) 601 PyErr_BadInternalCall(); 602 return NULL; 603 } 604 if (Py_EnterRecursiveCall(" in comparison")) 605 return NULL; 606 res = do_richcompare(v, w, op); 607 Py_LeaveRecursiveCall(); 608 return res; 609} 610 611/* Perform a rich comparison with integer result. This wraps 612 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */ 613int 614PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) 615{ 616 PyObject *res; 617 int ok; 618 619 /* Quick result when objects are the same. 620 Guarantees that identity implies equality. */ 621 if (v == w) { 622 if (op == Py_EQ) 623 return 1; 624 else if (op == Py_NE) 625 return 0; 626 } 627 628 res = PyObject_RichCompare(v, w, op); 629 if (res == NULL) 630 return -1; 631 if (PyBool_Check(res)) 632 ok = (res == Py_True); 633 else 634 ok = PyObject_IsTrue(res); 635 Py_DECREF(res); 636 return ok; 637} 638 639/* Set of hash utility functions to help maintaining the invariant that 640 if a==b then hash(a)==hash(b) 641 642 All the utility functions (_Py_Hash*()) return "-1" to signify an error. 643*/ 644 645/* For numeric types, the hash of a number x is based on the reduction 646 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that 647 hash(x) == hash(y) whenever x and y are numerically equal, even if 648 x and y have different types. 649 650 A quick summary of the hashing strategy: 651 652 (1) First define the 'reduction of x modulo P' for any rational 653 number x; this is a standard extension of the usual notion of 654 reduction modulo P for integers. If x == p/q (written in lowest 655 terms), the reduction is interpreted as the reduction of p times 656 the inverse of the reduction of q, all modulo P; if q is exactly 657 divisible by P then define the reduction to be infinity. So we've 658 got a well-defined map 659 660 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }. 661 662 (2) Now for a rational number x, define hash(x) by: 663 664 reduce(x) if x >= 0 665 -reduce(-x) if x < 0 666 667 If the result of the reduction is infinity (this is impossible for 668 integers, floats and Decimals) then use the predefined hash value 669 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead. 670 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the 671 hashes of float and Decimal infinities and nans. 672 673 A selling point for the above strategy is that it makes it possible 674 to compute hashes of decimal and binary floating-point numbers 675 efficiently, even if the exponent of the binary or decimal number 676 is large. The key point is that 677 678 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS) 679 680 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a 681 binary or decimal float is never infinity, since the denominator is a power 682 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have, 683 for nonnegative x, 684 685 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS 686 687 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS 688 689 and reduce(10**e) can be computed efficiently by the usual modular 690 exponentiation algorithm. For reduce(2**e) it's even better: since 691 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication 692 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits. 693 694 */ 695 696Py_hash_t 697_Py_HashDouble(double v) 698{ 699 int e, sign; 700 double m; 701 Py_uhash_t x, y; 702 703 if (!Py_IS_FINITE(v)) { 704 if (Py_IS_INFINITY(v)) 705 return v > 0 ? _PyHASH_INF : -_PyHASH_INF; 706 else 707 return _PyHASH_NAN; 708 } 709 710 m = frexp(v, &e); 711 712 sign = 1; 713 if (m < 0) { 714 sign = -1; 715 m = -m; 716 } 717 718 /* process 28 bits at a time; this should work well both for binary 719 and hexadecimal floating point. */ 720 x = 0; 721 while (m) { 722 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28); 723 m *= 268435456.0; /* 2**28 */ 724 e -= 28; 725 y = (Py_uhash_t)m; /* pull out integer part */ 726 m -= y; 727 x += y; 728 if (x >= _PyHASH_MODULUS) 729 x -= _PyHASH_MODULUS; 730 } 731 732 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */ 733 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS); 734 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e); 735 736 x = x * sign; 737 if (x == (Py_uhash_t)-1) 738 x = (Py_uhash_t)-2; 739 return (Py_hash_t)x; 740} 741 742Py_hash_t 743_Py_HashPointer(void *p) 744{ 745 Py_hash_t x; 746 size_t y = (size_t)p; 747 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid 748 excessive hash collisions for dicts and sets */ 749 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4)); 750 x = (Py_hash_t)y; 751 if (x == -1) 752 x = -2; 753 return x; 754} 755 756Py_hash_t 757_Py_HashBytes(unsigned char *p, Py_ssize_t len) 758{ 759 Py_uhash_t x; 760 Py_ssize_t i; 761 762 /* 763 We make the hash of the empty string be 0, rather than using 764 (prefix ^ suffix), since this slightly obfuscates the hash secret 765 */ 766 assert(_Py_HashSecret_Initialized); 767 if (len == 0) { 768 return 0; 769 } 770 x = (Py_uhash_t) _Py_HashSecret.prefix; 771 x ^= (Py_uhash_t) *p << 7; 772 for (i = 0; i < len; i++) 773 x = (_PyHASH_MULTIPLIER * x) ^ (Py_uhash_t) *p++; 774 x ^= (Py_uhash_t) len; 775 x ^= (Py_uhash_t) _Py_HashSecret.suffix; 776 if (x == -1) 777 x = -2; 778 return x; 779} 780 781Py_hash_t 782PyObject_HashNotImplemented(PyObject *v) 783{ 784 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'", 785 Py_TYPE(v)->tp_name); 786 return -1; 787} 788 789_Py_HashSecret_t _Py_HashSecret; 790 791Py_hash_t 792PyObject_Hash(PyObject *v) 793{ 794 PyTypeObject *tp = Py_TYPE(v); 795 if (tp->tp_hash != NULL) 796 return (*tp->tp_hash)(v); 797 /* To keep to the general practice that inheriting 798 * solely from object in C code should work without 799 * an explicit call to PyType_Ready, we implicitly call 800 * PyType_Ready here and then check the tp_hash slot again 801 */ 802 if (tp->tp_dict == NULL) { 803 if (PyType_Ready(tp) < 0) 804 return -1; 805 if (tp->tp_hash != NULL) 806 return (*tp->tp_hash)(v); 807 } 808 /* Otherwise, the object can't be hashed */ 809 return PyObject_HashNotImplemented(v); 810} 811 812PyObject * 813PyObject_GetAttrString(PyObject *v, const char *name) 814{ 815 PyObject *w, *res; 816 817 if (Py_TYPE(v)->tp_getattr != NULL) 818 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name); 819 w = PyUnicode_InternFromString(name); 820 if (w == NULL) 821 return NULL; 822 res = PyObject_GetAttr(v, w); 823 Py_DECREF(w); 824 return res; 825} 826 827int 828PyObject_HasAttrString(PyObject *v, const char *name) 829{ 830 PyObject *res = PyObject_GetAttrString(v, name); 831 if (res != NULL) { 832 Py_DECREF(res); 833 return 1; 834 } 835 PyErr_Clear(); 836 return 0; 837} 838 839int 840PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w) 841{ 842 PyObject *s; 843 int res; 844 845 if (Py_TYPE(v)->tp_setattr != NULL) 846 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w); 847 s = PyUnicode_InternFromString(name); 848 if (s == NULL) 849 return -1; 850 res = PyObject_SetAttr(v, s, w); 851 Py_XDECREF(s); 852 return res; 853} 854 855int 856_PyObject_IsAbstract(PyObject *obj) 857{ 858 int res; 859 PyObject* isabstract; 860 _Py_IDENTIFIER(__isabstractmethod__); 861 862 if (obj == NULL) 863 return 0; 864 865 isabstract = _PyObject_GetAttrId(obj, &PyId___isabstractmethod__); 866 if (isabstract == NULL) { 867 if (PyErr_ExceptionMatches(PyExc_AttributeError)) { 868 PyErr_Clear(); 869 return 0; 870 } 871 return -1; 872 } 873 res = PyObject_IsTrue(isabstract); 874 Py_DECREF(isabstract); 875 return res; 876} 877 878PyObject * 879_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name) 880{ 881 PyObject *result; 882 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */ 883 if (!oname) 884 return NULL; 885 result = PyObject_GetAttr(v, oname); 886 return result; 887} 888 889int 890_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name) 891{ 892 int result; 893 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */ 894 if (!oname) 895 return -1; 896 result = PyObject_HasAttr(v, oname); 897 return result; 898} 899 900int 901_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w) 902{ 903 int result; 904 PyObject *oname = _PyUnicode_FromId(name); /* borrowed */ 905 if (!oname) 906 return -1; 907 result = PyObject_SetAttr(v, oname, w); 908 return result; 909} 910 911PyObject * 912PyObject_GetAttr(PyObject *v, PyObject *name) 913{ 914 PyTypeObject *tp = Py_TYPE(v); 915 916 if (!PyUnicode_Check(name)) { 917 PyErr_Format(PyExc_TypeError, 918 "attribute name must be string, not '%.200s'", 919 name->ob_type->tp_name); 920 return NULL; 921 } 922 if (tp->tp_getattro != NULL) 923 return (*tp->tp_getattro)(v, name); 924 if (tp->tp_getattr != NULL) { 925 char *name_str = _PyUnicode_AsString(name); 926 if (name_str == NULL) 927 return NULL; 928 return (*tp->tp_getattr)(v, name_str); 929 } 930 PyErr_Format(PyExc_AttributeError, 931 "'%.50s' object has no attribute '%U'", 932 tp->tp_name, name); 933 return NULL; 934} 935 936int 937PyObject_HasAttr(PyObject *v, PyObject *name) 938{ 939 PyObject *res = PyObject_GetAttr(v, name); 940 if (res != NULL) { 941 Py_DECREF(res); 942 return 1; 943 } 944 PyErr_Clear(); 945 return 0; 946} 947 948int 949PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value) 950{ 951 PyTypeObject *tp = Py_TYPE(v); 952 int err; 953 954 if (!PyUnicode_Check(name)) { 955 PyErr_Format(PyExc_TypeError, 956 "attribute name must be string, not '%.200s'", 957 name->ob_type->tp_name); 958 return -1; 959 } 960 Py_INCREF(name); 961 962 PyUnicode_InternInPlace(&name); 963 if (tp->tp_setattro != NULL) { 964 err = (*tp->tp_setattro)(v, name, value); 965 Py_DECREF(name); 966 return err; 967 } 968 if (tp->tp_setattr != NULL) { 969 char *name_str = _PyUnicode_AsString(name); 970 if (name_str == NULL) 971 return -1; 972 err = (*tp->tp_setattr)(v, name_str, value); 973 Py_DECREF(name); 974 return err; 975 } 976 Py_DECREF(name); 977 assert(name->ob_refcnt >= 1); 978 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL) 979 PyErr_Format(PyExc_TypeError, 980 "'%.100s' object has no attributes " 981 "(%s .%U)", 982 tp->tp_name, 983 value==NULL ? "del" : "assign to", 984 name); 985 else 986 PyErr_Format(PyExc_TypeError, 987 "'%.100s' object has only read-only attributes " 988 "(%s .%U)", 989 tp->tp_name, 990 value==NULL ? "del" : "assign to", 991 name); 992 return -1; 993} 994 995/* Helper to get a pointer to an object's __dict__ slot, if any */ 996 997PyObject ** 998_PyObject_GetDictPtr(PyObject *obj) 999{ 1000 Py_ssize_t dictoffset; 1001 PyTypeObject *tp = Py_TYPE(obj); 1002 1003 dictoffset = tp->tp_dictoffset; 1004 if (dictoffset == 0) 1005 return NULL; 1006 if (dictoffset < 0) { 1007 Py_ssize_t tsize; 1008 size_t size; 1009 1010 tsize = ((PyVarObject *)obj)->ob_size; 1011 if (tsize < 0) 1012 tsize = -tsize; 1013 size = _PyObject_VAR_SIZE(tp, tsize); 1014 1015 dictoffset += (long)size; 1016 assert(dictoffset > 0); 1017 assert(dictoffset % SIZEOF_VOID_P == 0); 1018 } 1019 return (PyObject **) ((char *)obj + dictoffset); 1020} 1021 1022PyObject * 1023PyObject_SelfIter(PyObject *obj) 1024{ 1025 Py_INCREF(obj); 1026 return obj; 1027} 1028 1029/* Convenience function to get a builtin from its name */ 1030PyObject * 1031_PyObject_GetBuiltin(const char *name) 1032{ 1033 PyObject *mod, *attr; 1034 mod = PyImport_ImportModule("builtins"); 1035 if (mod == NULL) 1036 return NULL; 1037 attr = PyObject_GetAttrString(mod, name); 1038 Py_DECREF(mod); 1039 return attr; 1040} 1041 1042/* Helper used when the __next__ method is removed from a type: 1043 tp_iternext is never NULL and can be safely called without checking 1044 on every iteration. 1045 */ 1046 1047PyObject * 1048_PyObject_NextNotImplemented(PyObject *self) 1049{ 1050 PyErr_Format(PyExc_TypeError, 1051 "'%.200s' object is not iterable", 1052 Py_TYPE(self)->tp_name); 1053 return NULL; 1054} 1055 1056/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */ 1057 1058PyObject * 1059_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict) 1060{ 1061 PyTypeObject *tp = Py_TYPE(obj); 1062 PyObject *descr = NULL; 1063 PyObject *res = NULL; 1064 descrgetfunc f; 1065 Py_ssize_t dictoffset; 1066 PyObject **dictptr; 1067 1068 if (!PyUnicode_Check(name)){ 1069 PyErr_Format(PyExc_TypeError, 1070 "attribute name must be string, not '%.200s'", 1071 name->ob_type->tp_name); 1072 return NULL; 1073 } 1074 else 1075 Py_INCREF(name); 1076 1077 if (tp->tp_dict == NULL) { 1078 if (PyType_Ready(tp) < 0) 1079 goto done; 1080 } 1081 1082 descr = _PyType_Lookup(tp, name); 1083 Py_XINCREF(descr); 1084 1085 f = NULL; 1086 if (descr != NULL) { 1087 f = descr->ob_type->tp_descr_get; 1088 if (f != NULL && PyDescr_IsData(descr)) { 1089 res = f(descr, obj, (PyObject *)obj->ob_type); 1090 goto done; 1091 } 1092 } 1093 1094 if (dict == NULL) { 1095 /* Inline _PyObject_GetDictPtr */ 1096 dictoffset = tp->tp_dictoffset; 1097 if (dictoffset != 0) { 1098 if (dictoffset < 0) { 1099 Py_ssize_t tsize; 1100 size_t size; 1101 1102 tsize = ((PyVarObject *)obj)->ob_size; 1103 if (tsize < 0) 1104 tsize = -tsize; 1105 size = _PyObject_VAR_SIZE(tp, tsize); 1106 1107 dictoffset += (long)size; 1108 assert(dictoffset > 0); 1109 assert(dictoffset % SIZEOF_VOID_P == 0); 1110 } 1111 dictptr = (PyObject **) ((char *)obj + dictoffset); 1112 dict = *dictptr; 1113 } 1114 } 1115 if (dict != NULL) { 1116 Py_INCREF(dict); 1117 res = PyDict_GetItem(dict, name); 1118 if (res != NULL) { 1119 Py_INCREF(res); 1120 Py_DECREF(dict); 1121 goto done; 1122 } 1123 Py_DECREF(dict); 1124 } 1125 1126 if (f != NULL) { 1127 res = f(descr, obj, (PyObject *)Py_TYPE(obj)); 1128 goto done; 1129 } 1130 1131 if (descr != NULL) { 1132 res = descr; 1133 descr = NULL; 1134 goto done; 1135 } 1136 1137 PyErr_Format(PyExc_AttributeError, 1138 "'%.50s' object has no attribute '%U'", 1139 tp->tp_name, name); 1140 done: 1141 Py_XDECREF(descr); 1142 Py_DECREF(name); 1143 return res; 1144} 1145 1146PyObject * 1147PyObject_GenericGetAttr(PyObject *obj, PyObject *name) 1148{ 1149 return _PyObject_GenericGetAttrWithDict(obj, name, NULL); 1150} 1151 1152int 1153_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name, 1154 PyObject *value, PyObject *dict) 1155{ 1156 PyTypeObject *tp = Py_TYPE(obj); 1157 PyObject *descr; 1158 descrsetfunc f; 1159 PyObject **dictptr; 1160 int res = -1; 1161 1162 if (!PyUnicode_Check(name)){ 1163 PyErr_Format(PyExc_TypeError, 1164 "attribute name must be string, not '%.200s'", 1165 name->ob_type->tp_name); 1166 return -1; 1167 } 1168 1169 if (tp->tp_dict == NULL && PyType_Ready(tp) < 0) 1170 return -1; 1171 1172 Py_INCREF(name); 1173 1174 descr = _PyType_Lookup(tp, name); 1175 Py_XINCREF(descr); 1176 1177 f = NULL; 1178 if (descr != NULL) { 1179 f = descr->ob_type->tp_descr_set; 1180 if (f != NULL && PyDescr_IsData(descr)) { 1181 res = f(descr, obj, value); 1182 goto done; 1183 } 1184 } 1185 1186 if (dict == NULL) { 1187 dictptr = _PyObject_GetDictPtr(obj); 1188 if (dictptr != NULL) { 1189 dict = *dictptr; 1190 if (dict == NULL && value != NULL) { 1191 dict = PyDict_New(); 1192 if (dict == NULL) 1193 goto done; 1194 *dictptr = dict; 1195 } 1196 } 1197 } 1198 if (dict != NULL) { 1199 Py_INCREF(dict); 1200 if (value == NULL) 1201 res = PyDict_DelItem(dict, name); 1202 else 1203 res = PyDict_SetItem(dict, name, value); 1204 Py_DECREF(dict); 1205 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError)) 1206 PyErr_SetObject(PyExc_AttributeError, name); 1207 goto done; 1208 } 1209 1210 if (f != NULL) { 1211 res = f(descr, obj, value); 1212 goto done; 1213 } 1214 1215 if (descr == NULL) { 1216 PyErr_Format(PyExc_AttributeError, 1217 "'%.100s' object has no attribute '%U'", 1218 tp->tp_name, name); 1219 goto done; 1220 } 1221 1222 PyErr_Format(PyExc_AttributeError, 1223 "'%.50s' object attribute '%U' is read-only", 1224 tp->tp_name, name); 1225 done: 1226 Py_XDECREF(descr); 1227 Py_DECREF(name); 1228 return res; 1229} 1230 1231int 1232PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value) 1233{ 1234 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL); 1235} 1236 1237PyObject * 1238PyObject_GenericGetDict(PyObject *obj, void *context) 1239{ 1240 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj); 1241 if (dictptr == NULL) { 1242 PyErr_SetString(PyExc_AttributeError, 1243 "This object has no __dict__"); 1244 return NULL; 1245 } 1246 dict = *dictptr; 1247 if (dict == NULL) 1248 *dictptr = dict = PyDict_New(); 1249 Py_XINCREF(dict); 1250 return dict; 1251} 1252 1253int 1254PyObject_GenericSetDict(PyObject *obj, PyObject *value, void *context) 1255{ 1256 PyObject *dict, **dictptr = _PyObject_GetDictPtr(obj); 1257 if (dictptr == NULL) { 1258 PyErr_SetString(PyExc_AttributeError, 1259 "This object has no __dict__"); 1260 return -1; 1261 } 1262 if (value == NULL) { 1263 PyErr_SetString(PyExc_TypeError, "cannot delete __dict__"); 1264 return -1; 1265 } 1266 if (!PyDict_Check(value)) { 1267 PyErr_Format(PyExc_TypeError, 1268 "__dict__ must be set to a dictionary, " 1269 "not a '%.200s'", Py_TYPE(value)->tp_name); 1270 return -1; 1271 } 1272 dict = *dictptr; 1273 Py_XINCREF(value); 1274 *dictptr = value; 1275 Py_XDECREF(dict); 1276 return 0; 1277} 1278 1279 1280/* Test a value used as condition, e.g., in a for or if statement. 1281 Return -1 if an error occurred */ 1282 1283int 1284PyObject_IsTrue(PyObject *v) 1285{ 1286 Py_ssize_t res; 1287 if (v == Py_True) 1288 return 1; 1289 if (v == Py_False) 1290 return 0; 1291 if (v == Py_None) 1292 return 0; 1293 else if (v->ob_type->tp_as_number != NULL && 1294 v->ob_type->tp_as_number->nb_bool != NULL) 1295 res = (*v->ob_type->tp_as_number->nb_bool)(v); 1296 else if (v->ob_type->tp_as_mapping != NULL && 1297 v->ob_type->tp_as_mapping->mp_length != NULL) 1298 res = (*v->ob_type->tp_as_mapping->mp_length)(v); 1299 else if (v->ob_type->tp_as_sequence != NULL && 1300 v->ob_type->tp_as_sequence->sq_length != NULL) 1301 res = (*v->ob_type->tp_as_sequence->sq_length)(v); 1302 else 1303 return 1; 1304 /* if it is negative, it should be either -1 or -2 */ 1305 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int); 1306} 1307 1308/* equivalent of 'not v' 1309 Return -1 if an error occurred */ 1310 1311int 1312PyObject_Not(PyObject *v) 1313{ 1314 int res; 1315 res = PyObject_IsTrue(v); 1316 if (res < 0) 1317 return res; 1318 return res == 0; 1319} 1320 1321/* Test whether an object can be called */ 1322 1323int 1324PyCallable_Check(PyObject *x) 1325{ 1326 if (x == NULL) 1327 return 0; 1328 return x->ob_type->tp_call != NULL; 1329} 1330 1331 1332/* Helper for PyObject_Dir without arguments: returns the local scope. */ 1333static PyObject * 1334_dir_locals(void) 1335{ 1336 PyObject *names; 1337 PyObject *locals = PyEval_GetLocals(); 1338 1339 if (locals == NULL) { 1340 PyErr_SetString(PyExc_SystemError, "frame does not exist"); 1341 return NULL; 1342 } 1343 1344 names = PyMapping_Keys(locals); 1345 if (!names) 1346 return NULL; 1347 if (!PyList_Check(names)) { 1348 PyErr_Format(PyExc_TypeError, 1349 "dir(): expected keys() of locals to be a list, " 1350 "not '%.200s'", Py_TYPE(names)->tp_name); 1351 Py_DECREF(names); 1352 return NULL; 1353 } 1354 if (PyList_Sort(names)) { 1355 Py_DECREF(names); 1356 return NULL; 1357 } 1358 /* the locals don't need to be DECREF'd */ 1359 return names; 1360} 1361 1362/* Helper for PyObject_Dir: object introspection. */ 1363static PyObject * 1364_dir_object(PyObject *obj) 1365{ 1366 PyObject *result, *sorted; 1367 _Py_IDENTIFIER(__dir__); 1368 PyObject *dirfunc = _PyObject_LookupSpecial(obj, &PyId___dir__); 1369 1370 assert(obj); 1371 if (dirfunc == NULL) { 1372 if (!PyErr_Occurred()) 1373 PyErr_SetString(PyExc_TypeError, "object does not provide __dir__"); 1374 return NULL; 1375 } 1376 /* use __dir__ */ 1377 result = PyObject_CallFunctionObjArgs(dirfunc, NULL); 1378 Py_DECREF(dirfunc); 1379 if (result == NULL) 1380 return NULL; 1381 /* return sorted(result) */ 1382 sorted = PySequence_List(result); 1383 Py_DECREF(result); 1384 if (sorted == NULL) 1385 return NULL; 1386 if (PyList_Sort(sorted)) { 1387 Py_DECREF(sorted); 1388 return NULL; 1389 } 1390 return sorted; 1391} 1392 1393/* Implementation of dir() -- if obj is NULL, returns the names in the current 1394 (local) scope. Otherwise, performs introspection of the object: returns a 1395 sorted list of attribute names (supposedly) accessible from the object 1396*/ 1397PyObject * 1398PyObject_Dir(PyObject *obj) 1399{ 1400 return (obj == NULL) ? _dir_locals() : _dir_object(obj); 1401} 1402 1403/* 1404None is a non-NULL undefined value. 1405There is (and should be!) no way to create other objects of this type, 1406so there is exactly one (which is indestructible, by the way). 1407*/ 1408 1409/* ARGSUSED */ 1410static PyObject * 1411none_repr(PyObject *op) 1412{ 1413 return PyUnicode_FromString("None"); 1414} 1415 1416/* ARGUSED */ 1417static void 1418none_dealloc(PyObject* ignore) 1419{ 1420 /* This should never get called, but we also don't want to SEGV if 1421 * we accidentally decref None out of existence. 1422 */ 1423 Py_FatalError("deallocating None"); 1424} 1425 1426static PyObject * 1427none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) 1428{ 1429 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { 1430 PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments"); 1431 return NULL; 1432 } 1433 Py_RETURN_NONE; 1434} 1435 1436static int 1437none_bool(PyObject *v) 1438{ 1439 return 0; 1440} 1441 1442static PyNumberMethods none_as_number = { 1443 0, /* nb_add */ 1444 0, /* nb_subtract */ 1445 0, /* nb_multiply */ 1446 0, /* nb_remainder */ 1447 0, /* nb_divmod */ 1448 0, /* nb_power */ 1449 0, /* nb_negative */ 1450 0, /* nb_positive */ 1451 0, /* nb_absolute */ 1452 (inquiry)none_bool, /* nb_bool */ 1453 0, /* nb_invert */ 1454 0, /* nb_lshift */ 1455 0, /* nb_rshift */ 1456 0, /* nb_and */ 1457 0, /* nb_xor */ 1458 0, /* nb_or */ 1459 0, /* nb_int */ 1460 0, /* nb_reserved */ 1461 0, /* nb_float */ 1462 0, /* nb_inplace_add */ 1463 0, /* nb_inplace_subtract */ 1464 0, /* nb_inplace_multiply */ 1465 0, /* nb_inplace_remainder */ 1466 0, /* nb_inplace_power */ 1467 0, /* nb_inplace_lshift */ 1468 0, /* nb_inplace_rshift */ 1469 0, /* nb_inplace_and */ 1470 0, /* nb_inplace_xor */ 1471 0, /* nb_inplace_or */ 1472 0, /* nb_floor_divide */ 1473 0, /* nb_true_divide */ 1474 0, /* nb_inplace_floor_divide */ 1475 0, /* nb_inplace_true_divide */ 1476 0, /* nb_index */ 1477}; 1478 1479static PyTypeObject PyNone_Type = { 1480 PyVarObject_HEAD_INIT(&PyType_Type, 0) 1481 "NoneType", 1482 0, 1483 0, 1484 none_dealloc, /*tp_dealloc*/ /*never called*/ 1485 0, /*tp_print*/ 1486 0, /*tp_getattr*/ 1487 0, /*tp_setattr*/ 1488 0, /*tp_reserved*/ 1489 none_repr, /*tp_repr*/ 1490 &none_as_number, /*tp_as_number*/ 1491 0, /*tp_as_sequence*/ 1492 0, /*tp_as_mapping*/ 1493 0, /*tp_hash */ 1494 0, /*tp_call */ 1495 0, /*tp_str */ 1496 0, /*tp_getattro */ 1497 0, /*tp_setattro */ 1498 0, /*tp_as_buffer */ 1499 Py_TPFLAGS_DEFAULT, /*tp_flags */ 1500 0, /*tp_doc */ 1501 0, /*tp_traverse */ 1502 0, /*tp_clear */ 1503 0, /*tp_richcompare */ 1504 0, /*tp_weaklistoffset */ 1505 0, /*tp_iter */ 1506 0, /*tp_iternext */ 1507 0, /*tp_methods */ 1508 0, /*tp_members */ 1509 0, /*tp_getset */ 1510 0, /*tp_base */ 1511 0, /*tp_dict */ 1512 0, /*tp_descr_get */ 1513 0, /*tp_descr_set */ 1514 0, /*tp_dictoffset */ 1515 0, /*tp_init */ 1516 0, /*tp_alloc */ 1517 none_new, /*tp_new */ 1518}; 1519 1520PyObject _Py_NoneStruct = { 1521 _PyObject_EXTRA_INIT 1522 1, &PyNone_Type 1523}; 1524 1525/* NotImplemented is an object that can be used to signal that an 1526 operation is not implemented for the given type combination. */ 1527 1528static PyObject * 1529NotImplemented_repr(PyObject *op) 1530{ 1531 return PyUnicode_FromString("NotImplemented"); 1532} 1533 1534static PyObject * 1535notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) 1536{ 1537 if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) { 1538 PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments"); 1539 return NULL; 1540 } 1541 Py_RETURN_NOTIMPLEMENTED; 1542} 1543 1544static PyTypeObject PyNotImplemented_Type = { 1545 PyVarObject_HEAD_INIT(&PyType_Type, 0) 1546 "NotImplementedType", 1547 0, 1548 0, 1549 none_dealloc, /*tp_dealloc*/ /*never called*/ 1550 0, /*tp_print*/ 1551 0, /*tp_getattr*/ 1552 0, /*tp_setattr*/ 1553 0, /*tp_reserved*/ 1554 NotImplemented_repr, /*tp_repr*/ 1555 0, /*tp_as_number*/ 1556 0, /*tp_as_sequence*/ 1557 0, /*tp_as_mapping*/ 1558 0, /*tp_hash */ 1559 0, /*tp_call */ 1560 0, /*tp_str */ 1561 0, /*tp_getattro */ 1562 0, /*tp_setattro */ 1563 0, /*tp_as_buffer */ 1564 Py_TPFLAGS_DEFAULT, /*tp_flags */ 1565 0, /*tp_doc */ 1566 0, /*tp_traverse */ 1567 0, /*tp_clear */ 1568 0, /*tp_richcompare */ 1569 0, /*tp_weaklistoffset */ 1570 0, /*tp_iter */ 1571 0, /*tp_iternext */ 1572 0, /*tp_methods */ 1573 0, /*tp_members */ 1574 0, /*tp_getset */ 1575 0, /*tp_base */ 1576 0, /*tp_dict */ 1577 0, /*tp_descr_get */ 1578 0, /*tp_descr_set */ 1579 0, /*tp_dictoffset */ 1580 0, /*tp_init */ 1581 0, /*tp_alloc */ 1582 notimplemented_new, /*tp_new */ 1583}; 1584 1585PyObject _Py_NotImplementedStruct = { 1586 _PyObject_EXTRA_INIT 1587 1, &PyNotImplemented_Type 1588}; 1589 1590void 1591_Py_ReadyTypes(void) 1592{ 1593 if (PyType_Ready(&PyType_Type) < 0) 1594 Py_FatalError("Can't initialize type type"); 1595 1596 if (PyType_Ready(&_PyWeakref_RefType) < 0) 1597 Py_FatalError("Can't initialize weakref type"); 1598 1599 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0) 1600 Py_FatalError("Can't initialize callable weakref proxy type"); 1601 1602 if (PyType_Ready(&_PyWeakref_ProxyType) < 0) 1603 Py_FatalError("Can't initialize weakref proxy type"); 1604 1605 if (PyType_Ready(&PyBool_Type) < 0) 1606 Py_FatalError("Can't initialize bool type"); 1607 1608 if (PyType_Ready(&PyByteArray_Type) < 0) 1609 Py_FatalError("Can't initialize bytearray type"); 1610 1611 if (PyType_Ready(&PyBytes_Type) < 0) 1612 Py_FatalError("Can't initialize 'str'"); 1613 1614 if (PyType_Ready(&PyList_Type) < 0) 1615 Py_FatalError("Can't initialize list type"); 1616 1617 if (PyType_Ready(&PyNone_Type) < 0) 1618 Py_FatalError("Can't initialize None type"); 1619 1620 if (PyType_Ready(&PyNotImplemented_Type) < 0) 1621 Py_FatalError("Can't initialize NotImplemented type"); 1622 1623 if (PyType_Ready(&PyTraceBack_Type) < 0) 1624 Py_FatalError("Can't initialize traceback type"); 1625 1626 if (PyType_Ready(&PySuper_Type) < 0) 1627 Py_FatalError("Can't initialize super type"); 1628 1629 if (PyType_Ready(&PyBaseObject_Type) < 0) 1630 Py_FatalError("Can't initialize object type"); 1631 1632 if (PyType_Ready(&PyRange_Type) < 0) 1633 Py_FatalError("Can't initialize range type"); 1634 1635 if (PyType_Ready(&PyDict_Type) < 0) 1636 Py_FatalError("Can't initialize dict type"); 1637 1638 if (PyType_Ready(&PySet_Type) < 0) 1639 Py_FatalError("Can't initialize set type"); 1640 1641 if (PyType_Ready(&PyUnicode_Type) < 0) 1642 Py_FatalError("Can't initialize str type"); 1643 1644 if (PyType_Ready(&PySlice_Type) < 0) 1645 Py_FatalError("Can't initialize slice type"); 1646 1647 if (PyType_Ready(&PyStaticMethod_Type) < 0) 1648 Py_FatalError("Can't initialize static method type"); 1649 1650 if (PyType_Ready(&PyComplex_Type) < 0) 1651 Py_FatalError("Can't initialize complex type"); 1652 1653 if (PyType_Ready(&PyFloat_Type) < 0) 1654 Py_FatalError("Can't initialize float type"); 1655 1656 if (PyType_Ready(&PyLong_Type) < 0) 1657 Py_FatalError("Can't initialize int type"); 1658 1659 if (PyType_Ready(&PyFrozenSet_Type) < 0) 1660 Py_FatalError("Can't initialize frozenset type"); 1661 1662 if (PyType_Ready(&PyProperty_Type) < 0) 1663 Py_FatalError("Can't initialize property type"); 1664 1665 if (PyType_Ready(&_PyManagedBuffer_Type) < 0) 1666 Py_FatalError("Can't initialize managed buffer type"); 1667 1668 if (PyType_Ready(&PyMemoryView_Type) < 0) 1669 Py_FatalError("Can't initialize memoryview type"); 1670 1671 if (PyType_Ready(&PyTuple_Type) < 0) 1672 Py_FatalError("Can't initialize tuple type"); 1673 1674 if (PyType_Ready(&PyEnum_Type) < 0) 1675 Py_FatalError("Can't initialize enumerate type"); 1676 1677 if (PyType_Ready(&PyReversed_Type) < 0) 1678 Py_FatalError("Can't initialize reversed type"); 1679 1680 if (PyType_Ready(&PyStdPrinter_Type) < 0) 1681 Py_FatalError("Can't initialize StdPrinter"); 1682 1683 if (PyType_Ready(&PyCode_Type) < 0) 1684 Py_FatalError("Can't initialize code type"); 1685 1686 if (PyType_Ready(&PyFrame_Type) < 0) 1687 Py_FatalError("Can't initialize frame type"); 1688 1689 if (PyType_Ready(&PyCFunction_Type) < 0) 1690 Py_FatalError("Can't initialize builtin function type"); 1691 1692 if (PyType_Ready(&PyMethod_Type) < 0) 1693 Py_FatalError("Can't initialize method type"); 1694 1695 if (PyType_Ready(&PyFunction_Type) < 0) 1696 Py_FatalError("Can't initialize function type"); 1697 1698 if (PyType_Ready(&PyDictProxy_Type) < 0) 1699 Py_FatalError("Can't initialize dict proxy type"); 1700 1701 if (PyType_Ready(&PyGen_Type) < 0) 1702 Py_FatalError("Can't initialize generator type"); 1703 1704 if (PyType_Ready(&PyGetSetDescr_Type) < 0) 1705 Py_FatalError("Can't initialize get-set descriptor type"); 1706 1707 if (PyType_Ready(&PyWrapperDescr_Type) < 0) 1708 Py_FatalError("Can't initialize wrapper type"); 1709 1710 if (PyType_Ready(&_PyMethodWrapper_Type) < 0) 1711 Py_FatalError("Can't initialize method wrapper type"); 1712 1713 if (PyType_Ready(&PyEllipsis_Type) < 0) 1714 Py_FatalError("Can't initialize ellipsis type"); 1715 1716 if (PyType_Ready(&PyMemberDescr_Type) < 0) 1717 Py_FatalError("Can't initialize member descriptor type"); 1718 1719 if (PyType_Ready(&PyFilter_Type) < 0) 1720 Py_FatalError("Can't initialize filter type"); 1721 1722 if (PyType_Ready(&PyMap_Type) < 0) 1723 Py_FatalError("Can't initialize map type"); 1724 1725 if (PyType_Ready(&PyZip_Type) < 0) 1726 Py_FatalError("Can't initialize zip type"); 1727} 1728 1729 1730#ifdef Py_TRACE_REFS 1731 1732void 1733_Py_NewReference(PyObject *op) 1734{ 1735 _Py_INC_REFTOTAL; 1736 op->ob_refcnt = 1; 1737 _Py_AddToAllObjects(op, 1); 1738 _Py_INC_TPALLOCS(op); 1739} 1740 1741void 1742_Py_ForgetReference(register PyObject *op) 1743{ 1744#ifdef SLOW_UNREF_CHECK 1745 register PyObject *p; 1746#endif 1747 if (op->ob_refcnt < 0) 1748 Py_FatalError("UNREF negative refcnt"); 1749 if (op == &refchain || 1750 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) { 1751 fprintf(stderr, "* ob\n"); 1752 _PyObject_Dump(op); 1753 fprintf(stderr, "* op->_ob_prev->_ob_next\n"); 1754 _PyObject_Dump(op->_ob_prev->_ob_next); 1755 fprintf(stderr, "* op->_ob_next->_ob_prev\n"); 1756 _PyObject_Dump(op->_ob_next->_ob_prev); 1757 Py_FatalError("UNREF invalid object"); 1758 } 1759#ifdef SLOW_UNREF_CHECK 1760 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) { 1761 if (p == op) 1762 break; 1763 } 1764 if (p == &refchain) /* Not found */ 1765 Py_FatalError("UNREF unknown object"); 1766#endif 1767 op->_ob_next->_ob_prev = op->_ob_prev; 1768 op->_ob_prev->_ob_next = op->_ob_next; 1769 op->_ob_next = op->_ob_prev = NULL; 1770 _Py_INC_TPFREES(op); 1771} 1772 1773void 1774_Py_Dealloc(PyObject *op) 1775{ 1776 destructor dealloc = Py_TYPE(op)->tp_dealloc; 1777 _Py_ForgetReference(op); 1778 (*dealloc)(op); 1779} 1780 1781/* Print all live objects. Because PyObject_Print is called, the 1782 * interpreter must be in a healthy state. 1783 */ 1784void 1785_Py_PrintReferences(FILE *fp) 1786{ 1787 PyObject *op; 1788 fprintf(fp, "Remaining objects:\n"); 1789 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) { 1790 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt); 1791 if (PyObject_Print(op, fp, 0) != 0) 1792 PyErr_Clear(); 1793 putc('\n', fp); 1794 } 1795} 1796 1797/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this 1798 * doesn't make any calls to the Python C API, so is always safe to call. 1799 */ 1800void 1801_Py_PrintReferenceAddresses(FILE *fp) 1802{ 1803 PyObject *op; 1804 fprintf(fp, "Remaining object addresses:\n"); 1805 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) 1806 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op, 1807 op->ob_refcnt, Py_TYPE(op)->tp_name); 1808} 1809 1810PyObject * 1811_Py_GetObjects(PyObject *self, PyObject *args) 1812{ 1813 int i, n; 1814 PyObject *t = NULL; 1815 PyObject *res, *op; 1816 1817 if (!PyArg_ParseTuple(args, "i|O", &n, &t)) 1818 return NULL; 1819 op = refchain._ob_next; 1820 res = PyList_New(0); 1821 if (res == NULL) 1822 return NULL; 1823 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) { 1824 while (op == self || op == args || op == res || op == t || 1825 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) { 1826 op = op->_ob_next; 1827 if (op == &refchain) 1828 return res; 1829 } 1830 if (PyList_Append(res, op) < 0) { 1831 Py_DECREF(res); 1832 return NULL; 1833 } 1834 op = op->_ob_next; 1835 } 1836 return res; 1837} 1838 1839#endif 1840 1841/* Hack to force loading of pycapsule.o */ 1842PyTypeObject *_PyCapsule_hack = &PyCapsule_Type; 1843 1844 1845/* Hack to force loading of abstract.o */ 1846Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size; 1847 1848 1849/* Python's malloc wrappers (see pymem.h) */ 1850 1851void * 1852PyMem_Malloc(size_t nbytes) 1853{ 1854 return PyMem_MALLOC(nbytes); 1855} 1856 1857void * 1858PyMem_Realloc(void *p, size_t nbytes) 1859{ 1860 return PyMem_REALLOC(p, nbytes); 1861} 1862 1863void 1864PyMem_Free(void *p) 1865{ 1866 PyMem_FREE(p); 1867} 1868 1869 1870/* These methods are used to control infinite recursion in repr, str, print, 1871 etc. Container objects that may recursively contain themselves, 1872 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and 1873 Py_ReprLeave() to avoid infinite recursion. 1874 1875 Py_ReprEnter() returns 0 the first time it is called for a particular 1876 object and 1 every time thereafter. It returns -1 if an exception 1877 occurred. Py_ReprLeave() has no return value. 1878 1879 See dictobject.c and listobject.c for examples of use. 1880*/ 1881 1882#define KEY "Py_Repr" 1883 1884int 1885Py_ReprEnter(PyObject *obj) 1886{ 1887 PyObject *dict; 1888 PyObject *list; 1889 Py_ssize_t i; 1890 1891 dict = PyThreadState_GetDict(); 1892 if (dict == NULL) 1893 return 0; 1894 list = PyDict_GetItemString(dict, KEY); 1895 if (list == NULL) { 1896 list = PyList_New(0); 1897 if (list == NULL) 1898 return -1; 1899 if (PyDict_SetItemString(dict, KEY, list) < 0) 1900 return -1; 1901 Py_DECREF(list); 1902 } 1903 i = PyList_GET_SIZE(list); 1904 while (--i >= 0) { 1905 if (PyList_GET_ITEM(list, i) == obj) 1906 return 1; 1907 } 1908 PyList_Append(list, obj); 1909 return 0; 1910} 1911 1912void 1913Py_ReprLeave(PyObject *obj) 1914{ 1915 PyObject *dict; 1916 PyObject *list; 1917 Py_ssize_t i; 1918 1919 dict = PyThreadState_GetDict(); 1920 if (dict == NULL) 1921 return; 1922 list = PyDict_GetItemString(dict, KEY); 1923 if (list == NULL || !PyList_Check(list)) 1924 return; 1925 i = PyList_GET_SIZE(list); 1926 /* Count backwards because we always expect obj to be list[-1] */ 1927 while (--i >= 0) { 1928 if (PyList_GET_ITEM(list, i) == obj) { 1929 PyList_SetSlice(list, i, i + 1, NULL); 1930 break; 1931 } 1932 } 1933} 1934 1935/* Trashcan support. */ 1936 1937/* Current call-stack depth of tp_dealloc calls. */ 1938int _PyTrash_delete_nesting = 0; 1939 1940/* List of objects that still need to be cleaned up, singly linked via their 1941 * gc headers' gc_prev pointers. 1942 */ 1943PyObject *_PyTrash_delete_later = NULL; 1944 1945/* Add op to the _PyTrash_delete_later list. Called when the current 1946 * call-stack depth gets large. op must be a currently untracked gc'ed 1947 * object, with refcount 0. Py_DECREF must already have been called on it. 1948 */ 1949void 1950_PyTrash_deposit_object(PyObject *op) 1951{ 1952 assert(PyObject_IS_GC(op)); 1953 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED); 1954 assert(op->ob_refcnt == 0); 1955 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later; 1956 _PyTrash_delete_later = op; 1957} 1958 1959/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when 1960 * the call-stack unwinds again. 1961 */ 1962void 1963_PyTrash_destroy_chain(void) 1964{ 1965 while (_PyTrash_delete_later) { 1966 PyObject *op = _PyTrash_delete_later; 1967 destructor dealloc = Py_TYPE(op)->tp_dealloc; 1968 1969 _PyTrash_delete_later = 1970 (PyObject*) _Py_AS_GC(op)->gc.gc_prev; 1971 1972 /* Call the deallocator directly. This used to try to 1973 * fool Py_DECREF into calling it indirectly, but 1974 * Py_DECREF was already called on this object, and in 1975 * assorted non-release builds calling Py_DECREF again ends 1976 * up distorting allocation statistics. 1977 */ 1978 assert(op->ob_refcnt == 0); 1979 ++_PyTrash_delete_nesting; 1980 (*dealloc)(op); 1981 --_PyTrash_delete_nesting; 1982 } 1983} 1984 1985#ifndef Py_TRACE_REFS 1986/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc. 1987 Define this here, so we can undefine the macro. */ 1988#undef _Py_Dealloc 1989PyAPI_FUNC(void) _Py_Dealloc(PyObject *); 1990void 1991_Py_Dealloc(PyObject *op) 1992{ 1993 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA 1994 (*Py_TYPE(op)->tp_dealloc)(op); 1995} 1996#endif 1997 1998#ifdef __cplusplus 1999} 2000#endif 2001