2 /* Generic object operations; and implementation of None (NoObject) */
14 int Py_DivisionWarningFlag
;
16 /* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
17 These are used by the individual routines for object creation.
18 Do not call them otherwise, they do not initialize the object! */
21 /* Head of circular doubly-linked list of all objects. These are linked
22 * together via the _ob_prev and _ob_next members of a PyObject, which
23 * exist only in a Py_TRACE_REFS build.
25 static PyObject refchain
= {&refchain
, &refchain
};
27 /* Insert op at the front of the list of all objects. If force is true,
28 * op is added even if _ob_prev and _ob_next are non-NULL already. If
29 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
30 * force should be true if and only if op points to freshly allocated,
31 * uninitialized memory, or you've unlinked op from the list and are
32 * relinking it into the front.
33 * Note that objects are normally added to the list via _Py_NewReference,
34 * which is called by PyObject_Init. Not all objects are initialized that
35 * way, though; exceptions include statically allocated type objects, and
36 * statically allocated singletons (like Py_True and Py_None).
39 _Py_AddToAllObjects(PyObject
*op
, int force
)
43 /* If it's initialized memory, op must be in or out of
44 * the list unambiguously.
46 assert((op
->_ob_prev
== NULL
) == (op
->_ob_next
== NULL
));
49 if (force
|| op
->_ob_prev
== NULL
) {
50 op
->_ob_next
= refchain
._ob_next
;
51 op
->_ob_prev
= &refchain
;
52 refchain
._ob_next
->_ob_prev
= op
;
53 refchain
._ob_next
= op
;
56 #endif /* Py_TRACE_REFS */
59 static PyTypeObject
*type_list
;
60 extern int tuple_zero_allocs
, fast_tuple_allocs
;
61 extern int quick_int_allocs
, quick_neg_int_allocs
;
62 extern int null_strings
, one_strings
;
68 for (tp
= type_list
; tp
; tp
= tp
->tp_next
)
69 fprintf(stderr
, "%s alloc'd: %d, freed: %d, max in use: %d\n",
70 tp
->tp_name
, tp
->tp_allocs
, tp
->tp_frees
,
72 fprintf(stderr
, "fast tuple allocs: %d, empty: %d\n",
73 fast_tuple_allocs
, tuple_zero_allocs
);
74 fprintf(stderr
, "fast int allocs: pos: %d, neg: %d\n",
75 quick_int_allocs
, quick_neg_int_allocs
);
76 fprintf(stderr
, "null strings: %d, 1-strings: %d\n",
77 null_strings
, one_strings
);
87 result
= PyList_New(0);
90 for (tp
= type_list
; tp
; tp
= tp
->tp_next
) {
91 v
= Py_BuildValue("(siii)", tp
->tp_name
, tp
->tp_allocs
,
92 tp
->tp_frees
, tp
->tp_maxalloc
);
97 if (PyList_Append(result
, v
) < 0) {
108 inc_count(PyTypeObject
*tp
)
110 if (tp
->tp_allocs
== 0) {
111 /* first time; insert in linked list */
112 if (tp
->tp_next
!= NULL
) /* sanity check */
113 Py_FatalError("XXX inc_count sanity check");
114 tp
->tp_next
= type_list
;
115 /* Note that as of Python 2.2, heap-allocated type objects
116 * can go away, but this code requires that they stay alive
117 * until program exit. That's why we're careful with
118 * refcounts here. type_list gets a new reference to tp,
119 * while ownership of the reference type_list used to hold
120 * (if any) was transferred to tp->tp_next in the line above.
121 * tp is thus effectively immortal after this.
126 /* Also insert in the doubly-linked list of all objects,
127 * if not already there.
129 _Py_AddToAllObjects((PyObject
*)tp
, 0);
133 if (tp
->tp_allocs
- tp
->tp_frees
> tp
->tp_maxalloc
)
134 tp
->tp_maxalloc
= tp
->tp_allocs
- tp
->tp_frees
;
139 /* Log a fatal error; doesn't return. */
141 _Py_NegativeRefcount(const char *fname
, int lineno
, PyObject
*op
)
145 PyOS_snprintf(buf
, sizeof(buf
),
146 "%s:%i object at %p has negative ref count %i",
147 fname
, lineno
, op
, op
->ob_refcnt
);
151 #endif /* Py_REF_DEBUG */
154 PyObject_Init(PyObject
*op
, PyTypeObject
*tp
)
157 return PyErr_NoMemory();
158 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
160 _Py_NewReference(op
);
165 PyObject_InitVar(PyVarObject
*op
, PyTypeObject
*tp
, int size
)
168 return (PyVarObject
*) PyErr_NoMemory();
169 /* Any changes should be reflected in PyObject_INIT_VAR */
172 _Py_NewReference((PyObject
*)op
);
177 _PyObject_New(PyTypeObject
*tp
)
180 op
= (PyObject
*) PyObject_MALLOC(_PyObject_SIZE(tp
));
182 return PyErr_NoMemory();
183 return PyObject_INIT(op
, tp
);
187 _PyObject_NewVar(PyTypeObject
*tp
, int nitems
)
190 const size_t size
= _PyObject_VAR_SIZE(tp
, nitems
);
191 op
= (PyVarObject
*) PyObject_MALLOC(size
);
193 return (PyVarObject
*)PyErr_NoMemory();
194 return PyObject_INIT_VAR(op
, tp
, nitems
);
197 /* for binary compatibility with 2.2 */
200 _PyObject_Del(PyObject
*op
)
205 /* Implementation of PyObject_Print with recursion checking */
207 internal_print(PyObject
*op
, FILE *fp
, int flags
, int nesting
)
211 PyErr_SetString(PyExc_RuntimeError
, "print recursion");
214 if (PyErr_CheckSignals())
216 #ifdef USE_STACKCHECK
217 if (PyOS_CheckStack()) {
218 PyErr_SetString(PyExc_MemoryError
, "stack overflow");
222 clearerr(fp
); /* Clear any previous error condition */
224 fprintf(fp
, "<nil>");
227 if (op
->ob_refcnt
<= 0)
228 fprintf(fp
, "<refcnt %u at %p>",
230 else if (op
->ob_type
->tp_print
== NULL
) {
232 if (flags
& Py_PRINT_RAW
)
233 s
= PyObject_Str(op
);
235 s
= PyObject_Repr(op
);
239 ret
= internal_print(s
, fp
, Py_PRINT_RAW
,
245 ret
= (*op
->ob_type
->tp_print
)(op
, fp
, flags
);
249 PyErr_SetFromErrno(PyExc_IOError
);
258 PyObject_Print(PyObject
*op
, FILE *fp
, int flags
)
260 return internal_print(op
, fp
, flags
, 0);
264 /* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
265 void _PyObject_Dump(PyObject
* op
)
268 fprintf(stderr
, "NULL\n");
270 fprintf(stderr
, "object : ");
271 (void)PyObject_Print(op
, stderr
, 0);
276 op
->ob_type
==NULL
? "NULL" : op
->ob_type
->tp_name
,
283 PyObject_Repr(PyObject
*v
)
285 if (PyErr_CheckSignals())
287 #ifdef USE_STACKCHECK
288 if (PyOS_CheckStack()) {
289 PyErr_SetString(PyExc_MemoryError
, "stack overflow");
294 return PyString_FromString("<NULL>");
295 else if (v
->ob_type
->tp_repr
== NULL
)
296 return PyString_FromFormat("<%s object at %p>",
297 v
->ob_type
->tp_name
, v
);
300 res
= (*v
->ob_type
->tp_repr
)(v
);
303 #ifdef Py_USING_UNICODE
304 if (PyUnicode_Check(res
)) {
306 str
= PyUnicode_AsUnicodeEscapeString(res
);
314 if (!PyString_Check(res
)) {
315 PyErr_Format(PyExc_TypeError
,
316 "__repr__ returned non-string (type %.200s)",
317 res
->ob_type
->tp_name
);
326 PyObject_Str(PyObject
*v
)
331 return PyString_FromString("<NULL>");
332 if (PyString_CheckExact(v
)) {
336 if (v
->ob_type
->tp_str
== NULL
)
337 return PyObject_Repr(v
);
339 res
= (*v
->ob_type
->tp_str
)(v
);
342 #ifdef Py_USING_UNICODE
343 if (PyUnicode_Check(res
)) {
345 str
= PyUnicode_AsEncodedString(res
, NULL
, NULL
);
353 if (!PyString_Check(res
)) {
354 PyErr_Format(PyExc_TypeError
,
355 "__str__ returned non-string (type %.200s)",
356 res
->ob_type
->tp_name
);
363 #ifdef Py_USING_UNICODE
365 PyObject_Unicode(PyObject
*v
)
370 res
= PyString_FromString("<NULL>");
371 if (PyUnicode_CheckExact(v
)) {
375 if (PyUnicode_Check(v
)) {
376 /* For a Unicode subtype that's not a Unicode object,
377 return a true Unicode object with the same data. */
378 return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v
),
379 PyUnicode_GET_SIZE(v
));
381 if (PyString_Check(v
)) {
387 static PyObject
*unicodestr
;
388 /* XXX As soon as we have a tp_unicode slot, we should
389 check this before trying the __unicode__
391 if (unicodestr
== NULL
) {
392 unicodestr
= PyString_InternFromString(
394 if (unicodestr
== NULL
)
397 func
= PyObject_GetAttr(v
, unicodestr
);
399 res
= PyEval_CallObject(func
, (PyObject
*)NULL
);
404 if (v
->ob_type
->tp_str
!= NULL
)
405 res
= (*v
->ob_type
->tp_str
)(v
);
407 res
= PyObject_Repr(v
);
412 if (!PyUnicode_Check(res
)) {
414 str
= PyUnicode_FromEncodedObject(res
, NULL
, "strict");
426 /* Helper to warn about deprecated tp_compare return values. Return:
431 (This function cannot return 2.)
434 adjust_tp_compare(int c
)
436 if (PyErr_Occurred()) {
437 if (c
!= -1 && c
!= -2) {
438 PyObject
*t
, *v
, *tb
;
439 PyErr_Fetch(&t
, &v
, &tb
);
440 if (PyErr_Warn(PyExc_RuntimeWarning
,
441 "tp_compare didn't return -1 or -2 "
442 "for exception") < 0) {
448 PyErr_Restore(t
, v
, tb
);
452 else if (c
< -1 || c
> 1) {
453 if (PyErr_Warn(PyExc_RuntimeWarning
,
454 "tp_compare didn't return -1, 0 or 1") < 0)
457 return c
< -1 ? -1 : 1;
460 assert(c
>= -1 && c
<= 1);
466 /* Macro to get the tp_richcompare field of a type if defined */
467 #define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
468 ? (t)->tp_richcompare : NULL)
470 /* Map rich comparison operators to their swapped version, e.g. LT --> GT */
471 static int swapped_op
[] = {Py_GT
, Py_GE
, Py_EQ
, Py_NE
, Py_LT
, Py_LE
};
473 /* Try a genuine rich comparison, returning an object. Return:
475 NotImplemented if this particular rich comparison is not implemented or
477 some object not equal to NotImplemented if it is implemented
478 (this latter object may not be a Boolean).
481 try_rich_compare(PyObject
*v
, PyObject
*w
, int op
)
486 if (v
->ob_type
!= w
->ob_type
&&
487 PyType_IsSubtype(w
->ob_type
, v
->ob_type
) &&
488 (f
= RICHCOMPARE(w
->ob_type
)) != NULL
) {
489 res
= (*f
)(w
, v
, swapped_op
[op
]);
490 if (res
!= Py_NotImplemented
)
494 if ((f
= RICHCOMPARE(v
->ob_type
)) != NULL
) {
495 res
= (*f
)(v
, w
, op
);
496 if (res
!= Py_NotImplemented
)
500 if ((f
= RICHCOMPARE(w
->ob_type
)) != NULL
) {
501 return (*f
)(w
, v
, swapped_op
[op
]);
503 res
= Py_NotImplemented
;
508 /* Try a genuine rich comparison, returning an int. Return:
509 -1 for exception (including the case where try_rich_compare() returns an
510 object that's not a Boolean);
511 0 if the outcome is false;
512 1 if the outcome is true;
513 2 if this particular rich comparison is not implemented or undefined.
516 try_rich_compare_bool(PyObject
*v
, PyObject
*w
, int op
)
521 if (RICHCOMPARE(v
->ob_type
) == NULL
&& RICHCOMPARE(w
->ob_type
) == NULL
)
522 return 2; /* Shortcut, avoid INCREF+DECREF */
523 res
= try_rich_compare(v
, w
, op
);
526 if (res
== Py_NotImplemented
) {
530 ok
= PyObject_IsTrue(res
);
535 /* Try rich comparisons to determine a 3-way comparison. Return:
540 2 if this particular rich comparison is not implemented or undefined.
543 try_rich_to_3way_compare(PyObject
*v
, PyObject
*w
)
545 static struct { int op
; int outcome
; } tries
[3] = {
546 /* Try this operator, and if it is true, use this outcome: */
553 if (RICHCOMPARE(v
->ob_type
) == NULL
&& RICHCOMPARE(w
->ob_type
) == NULL
)
554 return 2; /* Shortcut */
556 for (i
= 0; i
< 3; i
++) {
557 switch (try_rich_compare_bool(v
, w
, tries
[i
].op
)) {
561 return tries
[i
].outcome
;
568 /* Try a 3-way comparison, returning an int. Return:
573 2 if this particular 3-way comparison is not implemented or undefined.
576 try_3way_compare(PyObject
*v
, PyObject
*w
)
581 /* Comparisons involving instances are given to instance_compare,
582 which has the same return conventions as this function. */
584 f
= v
->ob_type
->tp_compare
;
585 if (PyInstance_Check(v
))
587 if (PyInstance_Check(w
))
588 return (*w
->ob_type
->tp_compare
)(v
, w
);
590 /* If both have the same (non-NULL) tp_compare, use it. */
591 if (f
!= NULL
&& f
== w
->ob_type
->tp_compare
) {
593 return adjust_tp_compare(c
);
596 /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
597 if (f
== _PyObject_SlotCompare
||
598 w
->ob_type
->tp_compare
== _PyObject_SlotCompare
)
599 return _PyObject_SlotCompare(v
, w
);
601 /* Try coercion; if it fails, give up */
602 c
= PyNumber_CoerceEx(&v
, &w
);
608 /* Try v's comparison, if defined */
609 if ((f
= v
->ob_type
->tp_compare
) != NULL
) {
613 return adjust_tp_compare(c
);
616 /* Try w's comparison, if defined */
617 if ((f
= w
->ob_type
->tp_compare
) != NULL
) {
618 c
= (*f
)(w
, v
); /* swapped! */
621 c
= adjust_tp_compare(c
);
623 return -c
; /* Swapped! */
628 /* No comparison defined */
634 /* Final fallback 3-way comparison, returning an int. Return:
635 -2 if an error occurred;
641 default_3way_compare(PyObject
*v
, PyObject
*w
)
646 if (v
->ob_type
== w
->ob_type
) {
647 /* When comparing these pointers, they must be cast to
648 * integer types (i.e. Py_uintptr_t, our spelling of C9X's
649 * uintptr_t). ANSI specifies that pointer compares other
650 * than == and != to non-related structures are undefined.
652 Py_uintptr_t vv
= (Py_uintptr_t
)v
;
653 Py_uintptr_t ww
= (Py_uintptr_t
)w
;
654 return (vv
< ww
) ? -1 : (vv
> ww
) ? 1 : 0;
657 #ifdef Py_USING_UNICODE
658 /* Special case for Unicode */
659 if (PyUnicode_Check(v
) || PyUnicode_Check(w
)) {
660 c
= PyUnicode_Compare(v
, w
);
661 if (!PyErr_Occurred())
663 /* TypeErrors are ignored: if Unicode coercion fails due
664 to one of the arguments not having the right type, we
665 continue as defined by the coercion protocol (see
666 above). Luckily, decoding errors are reported as
667 ValueErrors and are not masked by this technique. */
668 if (!PyErr_ExceptionMatches(PyExc_TypeError
))
674 /* None is smaller than anything */
680 /* different type: compare type names; numbers are smaller */
681 if (PyNumber_Check(v
))
684 vname
= v
->ob_type
->tp_name
;
685 if (PyNumber_Check(w
))
688 wname
= w
->ob_type
->tp_name
;
689 c
= strcmp(vname
, wname
);
694 /* Same type name, or (more likely) incomparable numeric types */
695 return ((Py_uintptr_t
)(v
->ob_type
) < (
696 Py_uintptr_t
)(w
->ob_type
)) ? -1 : 1;
699 #define CHECK_TYPES(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_CHECKTYPES)
701 /* Do a 3-way comparison, by hook or by crook. Return:
702 -2 for an exception (but see below);
706 BUT: if the object implements a tp_compare function, it returns
707 whatever this function returns (whether with an exception or not).
710 do_cmp(PyObject
*v
, PyObject
*w
)
715 if (v
->ob_type
== w
->ob_type
716 && (f
= v
->ob_type
->tp_compare
) != NULL
) {
718 if (PyInstance_Check(v
)) {
719 /* Instance tp_compare has a different signature.
720 But if it returns undefined we fall through. */
723 /* Else fall through to try_rich_to_3way_compare() */
726 return adjust_tp_compare(c
);
728 /* We only get here if one of the following is true:
729 a) v and w have different types
730 b) v and w have the same type, which doesn't have tp_compare
731 c) v and w are instances, and either __cmp__ is not defined or
732 __cmp__ returns NotImplemented
734 c
= try_rich_to_3way_compare(v
, w
);
737 c
= try_3way_compare(v
, w
);
740 return default_3way_compare(v
, w
);
743 /* compare_nesting is incremented before calling compare (for
744 some types) and decremented on exit. If the count exceeds the
745 nesting limit, enable code to detect circular data structures.
747 This is a tunable parameter that should only affect the performance
748 of comparisons, nothing else. Setting it high makes comparing deeply
749 nested non-cyclical data structures faster, but makes comparing cyclical
750 data structures slower.
752 #define NESTING_LIMIT 20
754 static int compare_nesting
= 0;
757 get_inprogress_dict(void)
759 static PyObject
*key
;
760 PyObject
*tstate_dict
, *inprogress
;
763 key
= PyString_InternFromString("cmp_state");
768 tstate_dict
= PyThreadState_GetDict();
769 if (tstate_dict
== NULL
) {
770 PyErr_BadInternalCall();
774 inprogress
= PyDict_GetItem(tstate_dict
, key
);
775 if (inprogress
== NULL
) {
776 inprogress
= PyDict_New();
777 if (inprogress
== NULL
)
779 if (PyDict_SetItem(tstate_dict
, key
, inprogress
) == -1) {
780 Py_DECREF(inprogress
);
783 Py_DECREF(inprogress
);
789 /* If the comparison "v op w" is already in progress in this thread, returns
790 * a borrowed reference to Py_None (the caller must not decref).
791 * If it's not already in progress, returns "a token" which must eventually
792 * be passed to delete_token(). The caller must not decref this either
793 * (delete_token decrefs it). The token must not survive beyond any point
794 * where v or w may die.
795 * If an error occurs (out-of-memory), returns NULL.
798 check_recursion(PyObject
*v
, PyObject
*w
, int op
)
800 PyObject
*inprogress
;
802 Py_uintptr_t iv
= (Py_uintptr_t
)v
;
803 Py_uintptr_t iw
= (Py_uintptr_t
)w
;
806 inprogress
= get_inprogress_dict();
807 if (inprogress
== NULL
)
810 token
= PyTuple_New(3);
815 PyTuple_SET_ITEM(token
, 0, x
= PyLong_FromVoidPtr((void *)v
));
816 PyTuple_SET_ITEM(token
, 1, y
= PyLong_FromVoidPtr((void *)w
));
820 PyTuple_SET_ITEM(token
, 0, x
= PyLong_FromVoidPtr((void *)w
));
821 PyTuple_SET_ITEM(token
, 1, y
= PyLong_FromVoidPtr((void *)v
));
823 PyTuple_SET_ITEM(token
, 2, z
= PyInt_FromLong((long)op
));
824 if (x
== NULL
|| y
== NULL
|| z
== NULL
) {
829 if (PyDict_GetItem(inprogress
, token
) != NULL
) {
831 return Py_None
; /* Without INCREF! */
834 if (PyDict_SetItem(inprogress
, token
, token
) < 0) {
843 delete_token(PyObject
*token
)
845 PyObject
*inprogress
;
847 if (token
== NULL
|| token
== Py_None
)
849 inprogress
= get_inprogress_dict();
850 if (inprogress
== NULL
)
853 PyDict_DelItem(inprogress
, token
);
857 /* Compare v to w. Return
858 -1 if v < w or exception (PyErr_Occurred() true in latter case).
861 XXX The docs (C API manual) say the return value is undefined in case
865 PyObject_Compare(PyObject
*v
, PyObject
*w
)
870 #if defined(USE_STACKCHECK)
871 if (PyOS_CheckStack()) {
872 PyErr_SetString(PyExc_MemoryError
, "Stack overflow");
876 if (v
== NULL
|| w
== NULL
) {
877 PyErr_BadInternalCall();
884 if (compare_nesting
> NESTING_LIMIT
&&
885 (vtp
->tp_as_mapping
|| vtp
->tp_as_sequence
) &&
886 !PyString_CheckExact(v
) &&
887 !PyTuple_CheckExact(v
)) {
888 /* try to detect circular data structures */
889 PyObject
*token
= check_recursion(v
, w
, -1);
894 else if (token
== Py_None
) {
895 /* already comparing these objects. assume
896 they're equal until shown otherwise */
900 result
= do_cmp(v
, w
);
905 result
= do_cmp(v
, w
);
908 return result
< 0 ? -1 : result
;
911 /* Return (new reference to) Py_True or Py_False. */
913 convert_3way_to_object(int op
, int c
)
917 case Py_LT
: c
= c
< 0; break;
918 case Py_LE
: c
= c
<= 0; break;
919 case Py_EQ
: c
= c
== 0; break;
920 case Py_NE
: c
= c
!= 0; break;
921 case Py_GT
: c
= c
> 0; break;
922 case Py_GE
: c
= c
>= 0; break;
924 result
= c
? Py_True
: Py_False
;
929 /* We want a rich comparison but don't have one. Try a 3-way cmp instead.
933 Py_False if not (v op w)
936 try_3way_to_rich_compare(PyObject
*v
, PyObject
*w
, int op
)
940 c
= try_3way_compare(v
, w
);
942 c
= default_3way_compare(v
, w
);
945 return convert_3way_to_object(op
, c
);
948 /* Do rich comparison on v and w. Return
950 Else a new reference to an object other than Py_NotImplemented, usually(?):
952 Py_False if not (v op w)
955 do_richcmp(PyObject
*v
, PyObject
*w
, int op
)
959 res
= try_rich_compare(v
, w
, op
);
960 if (res
!= Py_NotImplemented
)
964 return try_3way_to_rich_compare(v
, w
, op
);
969 some object not equal to NotImplemented if it is implemented
970 (this latter object may not be a Boolean).
973 PyObject_RichCompare(PyObject
*v
, PyObject
*w
, int op
)
977 assert(Py_LT
<= op
&& op
<= Py_GE
);
980 if (compare_nesting
> NESTING_LIMIT
&&
981 (v
->ob_type
->tp_as_mapping
|| v
->ob_type
->tp_as_sequence
) &&
982 !PyString_CheckExact(v
) &&
983 !PyTuple_CheckExact(v
)) {
984 /* try to detect circular data structures */
985 PyObject
*token
= check_recursion(v
, w
, op
);
990 else if (token
== Py_None
) {
991 /* already comparing these objects with this operator.
992 assume they're equal until shown otherwise */
995 else if (op
== Py_NE
)
998 PyErr_SetString(PyExc_ValueError
,
999 "can't order recursive values");
1005 res
= do_richcmp(v
, w
, op
);
1006 delete_token(token
);
1011 /* No nesting extremism.
1012 If the types are equal, and not old-style instances, try to
1013 get out cheap (don't bother with coercions etc.). */
1014 if (v
->ob_type
== w
->ob_type
&& !PyInstance_Check(v
)) {
1016 richcmpfunc frich
= RICHCOMPARE(v
->ob_type
);
1017 /* If the type has richcmp, try it first. try_rich_compare
1018 tries it two-sided, which is not needed since we've a
1019 single type only. */
1020 if (frich
!= NULL
) {
1021 res
= (*frich
)(v
, w
, op
);
1022 if (res
!= Py_NotImplemented
)
1026 /* No richcmp, or this particular richmp not implemented.
1028 fcmp
= v
->ob_type
->tp_compare
;
1030 int c
= (*fcmp
)(v
, w
);
1031 c
= adjust_tp_compare(c
);
1036 res
= convert_3way_to_object(op
, c
);
1041 /* Fast path not taken, or couldn't deliver a useful result. */
1042 res
= do_richcmp(v
, w
, op
);
1048 /* Return -1 if error; 1 if v op w; 0 if not (v op w). */
1050 PyObject_RichCompareBool(PyObject
*v
, PyObject
*w
, int op
)
1052 PyObject
*res
= PyObject_RichCompare(v
, w
, op
);
1057 if (PyBool_Check(res
))
1058 ok
= (res
== Py_True
);
1060 ok
= PyObject_IsTrue(res
);
1065 /* Set of hash utility functions to help maintaining the invariant that
1066 iff a==b then hash(a)==hash(b)
1068 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1072 _Py_HashDouble(double v
)
1074 double intpart
, fractpart
;
1077 long x
; /* the final hash value */
1078 /* This is designed so that Python numbers of different types
1079 * that compare equal hash to the same value; otherwise comparisons
1080 * of mapping keys will turn out weird.
1083 #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
1086 fractpart
= modf(v
, &e
);
1090 fractpart
= modf(v
, &intpart
);
1092 if (fractpart
== 0.0) {
1093 /* This must return the same hash as an equal int or long. */
1094 if (intpart
> LONG_MAX
|| -intpart
> LONG_MAX
) {
1095 /* Convert to long and use its hash. */
1096 PyObject
*plong
; /* converted to Python long */
1097 if (Py_IS_INFINITY(intpart
))
1098 /* can't convert to long int -- arbitrary */
1099 v
= v
< 0 ? -271828.0 : 314159.0;
1100 plong
= PyLong_FromDouble(v
);
1103 x
= PyObject_Hash(plong
);
1107 /* Fits in a C long == a Python int, so is its own hash. */
1113 /* The fractional part is non-zero, so we don't have to worry about
1114 * making this match the hash of some other type.
1115 * Use frexp to get at the bits in the double.
1116 * Since the VAX D double format has 56 mantissa bits, which is the
1117 * most of any double format in use, each of these parts may have as
1118 * many as (but no more than) 56 significant bits.
1119 * So, assuming sizeof(long) >= 4, each part can be broken into two
1120 * longs; frexp and multiplication are used to do that.
1121 * Also, since the Cray double format has 15 exponent bits, which is
1122 * the most of any double format in use, shifting the exponent field
1123 * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1125 v
= frexp(v
, &expo
);
1126 v
*= 2147483648.0; /* 2**31 */
1127 hipart
= (long)v
; /* take the top 32 bits */
1128 v
= (v
- (double)hipart
) * 2147483648.0; /* get the next 32 bits */
1129 x
= hipart
+ (long)v
+ (expo
<< 15);
1136 _Py_HashPointer(void *p
)
1138 #if SIZEOF_LONG >= SIZEOF_VOID_P
1141 /* convert to a Python long and hash that */
1145 if ((longobj
= PyLong_FromVoidPtr(p
)) == NULL
) {
1149 x
= PyObject_Hash(longobj
);
1152 Py_XDECREF(longobj
);
1159 PyObject_Hash(PyObject
*v
)
1161 PyTypeObject
*tp
= v
->ob_type
;
1162 if (tp
->tp_hash
!= NULL
)
1163 return (*tp
->tp_hash
)(v
);
1164 if (tp
->tp_compare
== NULL
&& RICHCOMPARE(tp
) == NULL
) {
1165 return _Py_HashPointer(v
); /* Use address as hash value */
1167 /* If there's a cmp but no hash defined, the object can't be hashed */
1168 PyErr_SetString(PyExc_TypeError
, "unhashable type");
1173 PyObject_GetAttrString(PyObject
*v
, char *name
)
1177 if (v
->ob_type
->tp_getattr
!= NULL
)
1178 return (*v
->ob_type
->tp_getattr
)(v
, name
);
1179 w
= PyString_InternFromString(name
);
1182 res
= PyObject_GetAttr(v
, w
);
1188 PyObject_HasAttrString(PyObject
*v
, char *name
)
1190 PyObject
*res
= PyObject_GetAttrString(v
, name
);
1200 PyObject_SetAttrString(PyObject
*v
, char *name
, PyObject
*w
)
1205 if (v
->ob_type
->tp_setattr
!= NULL
)
1206 return (*v
->ob_type
->tp_setattr
)(v
, name
, w
);
1207 s
= PyString_InternFromString(name
);
1210 res
= PyObject_SetAttr(v
, s
, w
);
1216 PyObject_GetAttr(PyObject
*v
, PyObject
*name
)
1218 PyTypeObject
*tp
= v
->ob_type
;
1220 if (!PyString_Check(name
)) {
1221 #ifdef Py_USING_UNICODE
1222 /* The Unicode to string conversion is done here because the
1223 existing tp_getattro slots expect a string object as name
1224 and we wouldn't want to break those. */
1225 if (PyUnicode_Check(name
)) {
1226 name
= _PyUnicode_AsDefaultEncodedString(name
, NULL
);
1233 PyErr_SetString(PyExc_TypeError
,
1234 "attribute name must be string");
1238 if (tp
->tp_getattro
!= NULL
)
1239 return (*tp
->tp_getattro
)(v
, name
);
1240 if (tp
->tp_getattr
!= NULL
)
1241 return (*tp
->tp_getattr
)(v
, PyString_AS_STRING(name
));
1242 PyErr_Format(PyExc_AttributeError
,
1243 "'%.50s' object has no attribute '%.400s'",
1244 tp
->tp_name
, PyString_AS_STRING(name
));
1249 PyObject_HasAttr(PyObject
*v
, PyObject
*name
)
1251 PyObject
*res
= PyObject_GetAttr(v
, name
);
1261 PyObject_SetAttr(PyObject
*v
, PyObject
*name
, PyObject
*value
)
1263 PyTypeObject
*tp
= v
->ob_type
;
1266 if (!PyString_Check(name
)){
1267 #ifdef Py_USING_UNICODE
1268 /* The Unicode to string conversion is done here because the
1269 existing tp_setattro slots expect a string object as name
1270 and we wouldn't want to break those. */
1271 if (PyUnicode_Check(name
)) {
1272 name
= PyUnicode_AsEncodedString(name
, NULL
, NULL
);
1279 PyErr_SetString(PyExc_TypeError
,
1280 "attribute name must be string");
1287 PyString_InternInPlace(&name
);
1288 if (tp
->tp_setattro
!= NULL
) {
1289 err
= (*tp
->tp_setattro
)(v
, name
, value
);
1293 if (tp
->tp_setattr
!= NULL
) {
1294 err
= (*tp
->tp_setattr
)(v
, PyString_AS_STRING(name
), value
);
1299 if (tp
->tp_getattr
== NULL
&& tp
->tp_getattro
== NULL
)
1300 PyErr_Format(PyExc_TypeError
,
1301 "'%.100s' object has no attributes "
1304 value
==NULL
? "del" : "assign to",
1305 PyString_AS_STRING(name
));
1307 PyErr_Format(PyExc_TypeError
,
1308 "'%.100s' object has only read-only attributes "
1311 value
==NULL
? "del" : "assign to",
1312 PyString_AS_STRING(name
));
1316 /* Helper to get a pointer to an object's __dict__ slot, if any */
1319 _PyObject_GetDictPtr(PyObject
*obj
)
1322 PyTypeObject
*tp
= obj
->ob_type
;
1324 if (!(tp
->tp_flags
& Py_TPFLAGS_HAVE_CLASS
))
1326 dictoffset
= tp
->tp_dictoffset
;
1327 if (dictoffset
== 0)
1329 if (dictoffset
< 0) {
1333 tsize
= ((PyVarObject
*)obj
)->ob_size
;
1336 size
= _PyObject_VAR_SIZE(tp
, tsize
);
1338 dictoffset
+= (long)size
;
1339 assert(dictoffset
> 0);
1340 assert(dictoffset
% SIZEOF_VOID_P
== 0);
1342 return (PyObject
**) ((char *)obj
+ dictoffset
);
1345 /* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1348 PyObject_SelfIter(PyObject
*obj
)
1355 PyObject_GenericGetAttr(PyObject
*obj
, PyObject
*name
)
1357 PyTypeObject
*tp
= obj
->ob_type
;
1358 PyObject
*descr
= NULL
;
1359 PyObject
*res
= NULL
;
1364 if (!PyString_Check(name
)){
1365 #ifdef Py_USING_UNICODE
1366 /* The Unicode to string conversion is done here because the
1367 existing tp_setattro slots expect a string object as name
1368 and we wouldn't want to break those. */
1369 if (PyUnicode_Check(name
)) {
1370 name
= PyUnicode_AsEncodedString(name
, NULL
, NULL
);
1377 PyErr_SetString(PyExc_TypeError
,
1378 "attribute name must be string");
1385 if (tp
->tp_dict
== NULL
) {
1386 if (PyType_Ready(tp
) < 0)
1390 /* Inline _PyType_Lookup */
1393 PyObject
*mro
, *base
, *dict
;
1395 /* Look in tp_dict of types in MRO */
1397 assert(mro
!= NULL
);
1398 assert(PyTuple_Check(mro
));
1399 n
= PyTuple_GET_SIZE(mro
);
1400 for (i
= 0; i
< n
; i
++) {
1401 base
= PyTuple_GET_ITEM(mro
, i
);
1402 if (PyClass_Check(base
))
1403 dict
= ((PyClassObject
*)base
)->cl_dict
;
1405 assert(PyType_Check(base
));
1406 dict
= ((PyTypeObject
*)base
)->tp_dict
;
1408 assert(dict
&& PyDict_Check(dict
));
1409 descr
= PyDict_GetItem(dict
, name
);
1416 if (descr
!= NULL
&&
1417 PyType_HasFeature(descr
->ob_type
, Py_TPFLAGS_HAVE_CLASS
)) {
1418 f
= descr
->ob_type
->tp_descr_get
;
1419 if (f
!= NULL
&& PyDescr_IsData(descr
)) {
1420 res
= f(descr
, obj
, (PyObject
*)obj
->ob_type
);
1425 /* Inline _PyObject_GetDictPtr */
1426 dictoffset
= tp
->tp_dictoffset
;
1427 if (dictoffset
!= 0) {
1429 if (dictoffset
< 0) {
1433 tsize
= ((PyVarObject
*)obj
)->ob_size
;
1436 size
= _PyObject_VAR_SIZE(tp
, tsize
);
1438 dictoffset
+= (long)size
;
1439 assert(dictoffset
> 0);
1440 assert(dictoffset
% SIZEOF_VOID_P
== 0);
1442 dictptr
= (PyObject
**) ((char *)obj
+ dictoffset
);
1445 res
= PyDict_GetItem(dict
, name
);
1454 res
= f(descr
, obj
, (PyObject
*)obj
->ob_type
);
1458 if (descr
!= NULL
) {
1464 PyErr_Format(PyExc_AttributeError
,
1465 "'%.50s' object has no attribute '%.400s'",
1466 tp
->tp_name
, PyString_AS_STRING(name
));
1473 PyObject_GenericSetAttr(PyObject
*obj
, PyObject
*name
, PyObject
*value
)
1475 PyTypeObject
*tp
= obj
->ob_type
;
1481 if (!PyString_Check(name
)){
1482 #ifdef Py_USING_UNICODE
1483 /* The Unicode to string conversion is done here because the
1484 existing tp_setattro slots expect a string object as name
1485 and we wouldn't want to break those. */
1486 if (PyUnicode_Check(name
)) {
1487 name
= PyUnicode_AsEncodedString(name
, NULL
, NULL
);
1494 PyErr_SetString(PyExc_TypeError
,
1495 "attribute name must be string");
1502 if (tp
->tp_dict
== NULL
) {
1503 if (PyType_Ready(tp
) < 0)
1507 descr
= _PyType_Lookup(tp
, name
);
1509 if (descr
!= NULL
&&
1510 PyType_HasFeature(descr
->ob_type
, Py_TPFLAGS_HAVE_CLASS
)) {
1511 f
= descr
->ob_type
->tp_descr_set
;
1512 if (f
!= NULL
&& PyDescr_IsData(descr
)) {
1513 res
= f(descr
, obj
, value
);
1518 dictptr
= _PyObject_GetDictPtr(obj
);
1519 if (dictptr
!= NULL
) {
1520 PyObject
*dict
= *dictptr
;
1521 if (dict
== NULL
&& value
!= NULL
) {
1522 dict
= PyDict_New();
1529 res
= PyDict_DelItem(dict
, name
);
1531 res
= PyDict_SetItem(dict
, name
, value
);
1532 if (res
< 0 && PyErr_ExceptionMatches(PyExc_KeyError
))
1533 PyErr_SetObject(PyExc_AttributeError
, name
);
1539 res
= f(descr
, obj
, value
);
1543 if (descr
== NULL
) {
1544 PyErr_Format(PyExc_AttributeError
,
1545 "'%.50s' object has no attribute '%.400s'",
1546 tp
->tp_name
, PyString_AS_STRING(name
));
1550 PyErr_Format(PyExc_AttributeError
,
1551 "'%.50s' object attribute '%.400s' is read-only",
1552 tp
->tp_name
, PyString_AS_STRING(name
));
1558 /* Test a value used as condition, e.g., in a for or if statement.
1559 Return -1 if an error occurred */
1562 PyObject_IsTrue(PyObject
*v
)
1571 else if (v
->ob_type
->tp_as_number
!= NULL
&&
1572 v
->ob_type
->tp_as_number
->nb_nonzero
!= NULL
)
1573 res
= (*v
->ob_type
->tp_as_number
->nb_nonzero
)(v
);
1574 else if (v
->ob_type
->tp_as_mapping
!= NULL
&&
1575 v
->ob_type
->tp_as_mapping
->mp_length
!= NULL
)
1576 res
= (*v
->ob_type
->tp_as_mapping
->mp_length
)(v
);
1577 else if (v
->ob_type
->tp_as_sequence
!= NULL
&&
1578 v
->ob_type
->tp_as_sequence
->sq_length
!= NULL
)
1579 res
= (*v
->ob_type
->tp_as_sequence
->sq_length
)(v
);
1582 return (res
> 0) ? 1 : res
;
1585 /* equivalent of 'not v'
1586 Return -1 if an error occurred */
1589 PyObject_Not(PyObject
*v
)
1592 res
= PyObject_IsTrue(v
);
1598 /* Coerce two numeric types to the "larger" one.
1599 Increment the reference count on each argument.
1601 -1 if an error occurred;
1602 0 if the coercion succeeded (and then the reference counts are increased);
1603 1 if no coercion is possible (and no error is raised).
1606 PyNumber_CoerceEx(PyObject
**pv
, PyObject
**pw
)
1608 register PyObject
*v
= *pv
;
1609 register PyObject
*w
= *pw
;
1612 /* Shortcut only for old-style types */
1613 if (v
->ob_type
== w
->ob_type
&&
1614 !PyType_HasFeature(v
->ob_type
, Py_TPFLAGS_CHECKTYPES
))
1620 if (v
->ob_type
->tp_as_number
&& v
->ob_type
->tp_as_number
->nb_coerce
) {
1621 res
= (*v
->ob_type
->tp_as_number
->nb_coerce
)(pv
, pw
);
1625 if (w
->ob_type
->tp_as_number
&& w
->ob_type
->tp_as_number
->nb_coerce
) {
1626 res
= (*w
->ob_type
->tp_as_number
->nb_coerce
)(pw
, pv
);
1633 /* Coerce two numeric types to the "larger" one.
1634 Increment the reference count on each argument.
1635 Return -1 and raise an exception if no coercion is possible
1636 (and then no reference count is incremented).
1639 PyNumber_Coerce(PyObject
**pv
, PyObject
**pw
)
1641 int err
= PyNumber_CoerceEx(pv
, pw
);
1644 PyErr_SetString(PyExc_TypeError
, "number coercion failed");
1649 /* Test whether an object can be called */
1652 PyCallable_Check(PyObject
*x
)
1656 if (PyInstance_Check(x
)) {
1657 PyObject
*call
= PyObject_GetAttrString(x
, "__call__");
1662 /* Could test recursively but don't, for fear of endless
1663 recursion if some joker sets self.__call__ = self */
1668 return x
->ob_type
->tp_call
!= NULL
;
1672 /* Helper for PyObject_Dir.
1673 Merge the __dict__ of aclass into dict, and recursively also all
1674 the __dict__s of aclass's base classes. The order of merging isn't
1675 defined, as it's expected that only the final set of dict keys is
1677 Return 0 on success, -1 on error.
1681 merge_class_dict(PyObject
* dict
, PyObject
* aclass
)
1683 PyObject
*classdict
;
1686 assert(PyDict_Check(dict
));
1689 /* Merge in the type's dict (if any). */
1690 classdict
= PyObject_GetAttrString(aclass
, "__dict__");
1691 if (classdict
== NULL
)
1694 int status
= PyDict_Update(dict
, classdict
);
1695 Py_DECREF(classdict
);
1700 /* Recursively merge in the base types' (if any) dicts. */
1701 bases
= PyObject_GetAttrString(aclass
, "__bases__");
1705 /* We have no guarantee that bases is a real tuple */
1707 n
= PySequence_Size(bases
); /* This better be right */
1711 for (i
= 0; i
< n
; i
++) {
1713 PyObject
*base
= PySequence_GetItem(bases
, i
);
1718 status
= merge_class_dict(dict
, base
);
1731 /* Helper for PyObject_Dir.
1732 If obj has an attr named attrname that's a list, merge its string
1733 elements into keys of dict.
1734 Return 0 on success, -1 on error. Errors due to not finding the attr,
1735 or the attr not being a list, are suppressed.
1739 merge_list_attr(PyObject
* dict
, PyObject
* obj
, char *attrname
)
1744 assert(PyDict_Check(dict
));
1748 list
= PyObject_GetAttrString(obj
, attrname
);
1752 else if (PyList_Check(list
)) {
1754 for (i
= 0; i
< PyList_GET_SIZE(list
); ++i
) {
1755 PyObject
*item
= PyList_GET_ITEM(list
, i
);
1756 if (PyString_Check(item
)) {
1757 result
= PyDict_SetItem(dict
, item
, Py_None
);
1768 /* Like __builtin__.dir(arg). See bltinmodule.c's builtin_dir for the
1769 docstring, which should be kept in synch with this implementation. */
1772 PyObject_Dir(PyObject
*arg
)
1774 /* Set exactly one of these non-NULL before the end. */
1775 PyObject
*result
= NULL
; /* result list */
1776 PyObject
*masterdict
= NULL
; /* result is masterdict.keys() */
1778 /* If NULL arg, return the locals. */
1780 PyObject
*locals
= PyEval_GetLocals();
1783 result
= PyDict_Keys(locals
);
1788 /* Elif this is some form of module, we only want its dict. */
1789 else if (PyModule_Check(arg
)) {
1790 masterdict
= PyObject_GetAttrString(arg
, "__dict__");
1791 if (masterdict
== NULL
)
1793 if (!PyDict_Check(masterdict
)) {
1794 PyErr_SetString(PyExc_TypeError
,
1795 "module.__dict__ is not a dictionary");
1800 /* Elif some form of type or class, grab its dict and its bases.
1801 We deliberately don't suck up its __class__, as methods belonging
1802 to the metaclass would probably be more confusing than helpful. */
1803 else if (PyType_Check(arg
) || PyClass_Check(arg
)) {
1804 masterdict
= PyDict_New();
1805 if (masterdict
== NULL
)
1807 if (merge_class_dict(masterdict
, arg
) < 0)
1811 /* Else look at its dict, and the attrs reachable from its class. */
1814 /* Create a dict to start with. CAUTION: Not everything
1815 responding to __dict__ returns a dict! */
1816 masterdict
= PyObject_GetAttrString(arg
, "__dict__");
1817 if (masterdict
== NULL
) {
1819 masterdict
= PyDict_New();
1821 else if (!PyDict_Check(masterdict
)) {
1822 Py_DECREF(masterdict
);
1823 masterdict
= PyDict_New();
1826 /* The object may have returned a reference to its
1827 dict, so copy it to avoid mutating it. */
1828 PyObject
*temp
= PyDict_Copy(masterdict
);
1829 Py_DECREF(masterdict
);
1832 if (masterdict
== NULL
)
1835 /* Merge in __members__ and __methods__ (if any).
1836 XXX Would like this to go away someday; for now, it's
1837 XXX needed to get at im_self etc of method objects. */
1838 if (merge_list_attr(masterdict
, arg
, "__members__") < 0)
1840 if (merge_list_attr(masterdict
, arg
, "__methods__") < 0)
1843 /* Merge in attrs reachable from its class.
1844 CAUTION: Not all objects have a __class__ attr. */
1845 itsclass
= PyObject_GetAttrString(arg
, "__class__");
1846 if (itsclass
== NULL
)
1849 int status
= merge_class_dict(masterdict
, itsclass
);
1850 Py_DECREF(itsclass
);
1856 assert((result
== NULL
) ^ (masterdict
== NULL
));
1857 if (masterdict
!= NULL
) {
1858 /* The result comes from its keys. */
1859 assert(result
== NULL
);
1860 result
= PyDict_Keys(masterdict
);
1866 if (PyList_Sort(result
) != 0)
1876 Py_XDECREF(masterdict
);
1881 NoObject is usable as a non-NULL undefined value, used by the macro None.
1882 There is (and should be!) no way to create other objects of this type,
1883 so there is exactly one (which is indestructible, by the way).
1884 (XXX This type and the type of NotImplemented below should be unified.)
1889 none_repr(PyObject
*op
)
1891 return PyString_FromString("None");
1896 none_dealloc(PyObject
* ignore
)
1898 /* This should never get called, but we also don't want to SEGV if
1899 * we accidently decref None out of existance.
1901 Py_FatalError("deallocating None");
1905 static PyTypeObject PyNone_Type
= {
1906 PyObject_HEAD_INIT(&PyType_Type
)
1911 (destructor
)none_dealloc
, /*tp_dealloc*/ /*never called*/
1916 (reprfunc
)none_repr
, /*tp_repr*/
1918 0, /*tp_as_sequence*/
1919 0, /*tp_as_mapping*/
1923 PyObject _Py_NoneStruct
= {
1924 PyObject_HEAD_INIT(&PyNone_Type
)
1927 /* NotImplemented is an object that can be used to signal that an
1928 operation is not implemented for the given type combination. */
1931 NotImplemented_repr(PyObject
*op
)
1933 return PyString_FromString("NotImplemented");
1936 static PyTypeObject PyNotImplemented_Type
= {
1937 PyObject_HEAD_INIT(&PyType_Type
)
1939 "NotImplementedType",
1942 (destructor
)none_dealloc
, /*tp_dealloc*/ /*never called*/
1947 (reprfunc
)NotImplemented_repr
, /*tp_repr*/
1949 0, /*tp_as_sequence*/
1950 0, /*tp_as_mapping*/
1954 PyObject _Py_NotImplementedStruct
= {
1955 PyObject_HEAD_INIT(&PyNotImplemented_Type
)
1959 _Py_ReadyTypes(void)
1961 if (PyType_Ready(&PyType_Type
) < 0)
1962 Py_FatalError("Can't initialize 'type'");
1964 if (PyType_Ready(&PyBool_Type
) < 0)
1965 Py_FatalError("Can't initialize 'bool'");
1967 if (PyType_Ready(&PyString_Type
) < 0)
1968 Py_FatalError("Can't initialize 'str'");
1970 if (PyType_Ready(&PyList_Type
) < 0)
1971 Py_FatalError("Can't initialize 'list'");
1973 if (PyType_Ready(&PyNone_Type
) < 0)
1974 Py_FatalError("Can't initialize type(None)");
1976 if (PyType_Ready(&PyNotImplemented_Type
) < 0)
1977 Py_FatalError("Can't initialize type(NotImplemented)");
1981 #ifdef Py_TRACE_REFS
1984 _Py_NewReference(PyObject
*op
)
1988 _Py_AddToAllObjects(op
, 1);
1989 _Py_INC_TPALLOCS(op
);
1993 _Py_ForgetReference(register PyObject
*op
)
1995 #ifdef SLOW_UNREF_CHECK
1996 register PyObject
*p
;
1998 if (op
->ob_refcnt
< 0)
1999 Py_FatalError("UNREF negative refcnt");
2000 if (op
== &refchain
||
2001 op
->_ob_prev
->_ob_next
!= op
|| op
->_ob_next
->_ob_prev
!= op
)
2002 Py_FatalError("UNREF invalid object");
2003 #ifdef SLOW_UNREF_CHECK
2004 for (p
= refchain
._ob_next
; p
!= &refchain
; p
= p
->_ob_next
) {
2008 if (p
== &refchain
) /* Not found */
2009 Py_FatalError("UNREF unknown object");
2011 op
->_ob_next
->_ob_prev
= op
->_ob_prev
;
2012 op
->_ob_prev
->_ob_next
= op
->_ob_next
;
2013 op
->_ob_next
= op
->_ob_prev
= NULL
;
2014 _Py_INC_TPFREES(op
);
2018 _Py_Dealloc(PyObject
*op
)
2020 destructor dealloc
= op
->ob_type
->tp_dealloc
;
2021 _Py_ForgetReference(op
);
2025 /* Print all live objects. Because PyObject_Print is called, the
2026 * interpreter must be in a healthy state.
2029 _Py_PrintReferences(FILE *fp
)
2032 fprintf(fp
, "Remaining objects:\n");
2033 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
) {
2034 fprintf(fp
, "%p [%d] ", op
, op
->ob_refcnt
);
2035 if (PyObject_Print(op
, fp
, 0) != 0)
2041 /* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
2042 * doesn't make any calls to the Python C API, so is always safe to call.
2045 _Py_PrintReferenceAddresses(FILE *fp
)
2048 fprintf(fp
, "Remaining object addresses:\n");
2049 for (op
= refchain
._ob_next
; op
!= &refchain
; op
= op
->_ob_next
)
2050 fprintf(fp
, "%p [%d] %s\n", op
, op
->ob_refcnt
,
2051 op
->ob_type
->tp_name
);
2055 _Py_GetObjects(PyObject
*self
, PyObject
*args
)
2061 if (!PyArg_ParseTuple(args
, "i|O", &n
, &t
))
2063 op
= refchain
._ob_next
;
2064 res
= PyList_New(0);
2067 for (i
= 0; (n
== 0 || i
< n
) && op
!= &refchain
; i
++) {
2068 while (op
== self
|| op
== args
|| op
== res
|| op
== t
||
2069 (t
!= NULL
&& op
->ob_type
!= (PyTypeObject
*) t
)) {
2071 if (op
== &refchain
)
2074 if (PyList_Append(res
, op
) < 0) {
2086 /* Hack to force loading of cobject.o */
2087 PyTypeObject
*_Py_cobject_hack
= &PyCObject_Type
;
2090 /* Hack to force loading of abstract.o */
2091 int (*_Py_abstract_hack
)(PyObject
*) = PyObject_Size
;
2094 /* Python's malloc wrappers (see pymem.h) */
2097 PyMem_Malloc(size_t nbytes
)
2099 return PyMem_MALLOC(nbytes
);
2103 PyMem_Realloc(void *p
, size_t nbytes
)
2105 return PyMem_REALLOC(p
, nbytes
);
2115 /* These methods are used to control infinite recursion in repr, str, print,
2116 etc. Container objects that may recursively contain themselves,
2117 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
2118 Py_ReprLeave() to avoid infinite recursion.
2120 Py_ReprEnter() returns 0 the first time it is called for a particular
2121 object and 1 every time thereafter. It returns -1 if an exception
2122 occurred. Py_ReprLeave() has no return value.
2124 See dictobject.c and listobject.c for examples of use.
2127 #define KEY "Py_Repr"
2130 Py_ReprEnter(PyObject
*obj
)
2136 dict
= PyThreadState_GetDict();
2139 list
= PyDict_GetItemString(dict
, KEY
);
2141 list
= PyList_New(0);
2144 if (PyDict_SetItemString(dict
, KEY
, list
) < 0)
2148 i
= PyList_GET_SIZE(list
);
2150 if (PyList_GET_ITEM(list
, i
) == obj
)
2153 PyList_Append(list
, obj
);
2158 Py_ReprLeave(PyObject
*obj
)
2164 dict
= PyThreadState_GetDict();
2167 list
= PyDict_GetItemString(dict
, KEY
);
2168 if (list
== NULL
|| !PyList_Check(list
))
2170 i
= PyList_GET_SIZE(list
);
2171 /* Count backwards because we always expect obj to be list[-1] */
2173 if (PyList_GET_ITEM(list
, i
) == obj
) {
2174 PyList_SetSlice(list
, i
, i
+ 1, NULL
);
2180 /* Trashcan support. */
2182 /* Current call-stack depth of tp_dealloc calls. */
2183 int _PyTrash_delete_nesting
= 0;
2185 /* List of objects that still need to be cleaned up, singly linked via their
2186 * gc headers' gc_prev pointers.
2188 PyObject
*_PyTrash_delete_later
= NULL
;
2190 /* Add op to the _PyTrash_delete_later list. Called when the current
2191 * call-stack depth gets large. op must be a currently untracked gc'ed
2192 * object, with refcount 0. Py_DECREF must already have been called on it.
2195 _PyTrash_deposit_object(PyObject
*op
)
2197 assert(PyObject_IS_GC(op
));
2198 assert(_Py_AS_GC(op
)->gc
.gc_refs
== _PyGC_REFS_UNTRACKED
);
2199 assert(op
->ob_refcnt
== 0);
2200 _Py_AS_GC(op
)->gc
.gc_prev
= (PyGC_Head
*)_PyTrash_delete_later
;
2201 _PyTrash_delete_later
= op
;
2204 /* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
2205 * the call-stack unwinds again.
2208 _PyTrash_destroy_chain(void)
2210 while (_PyTrash_delete_later
) {
2211 PyObject
*op
= _PyTrash_delete_later
;
2212 destructor dealloc
= op
->ob_type
->tp_dealloc
;
2214 _PyTrash_delete_later
=
2215 (PyObject
*) _Py_AS_GC(op
)->gc
.gc_prev
;
2217 /* Call the deallocator directly. This used to try to
2218 * fool Py_DECREF into calling it indirectly, but
2219 * Py_DECREF was already called on this object, and in
2220 * assorted non-release builds calling Py_DECREF again ends
2221 * up distorting allocation statistics.
2223 assert(op
->ob_refcnt
== 0);
2224 ++_PyTrash_delete_nesting
;
2226 --_PyTrash_delete_nesting
;