1
2/* Generic object operations; and implementation of None (NoObject) */
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
32int Py_DivisionWarningFlag;
33int Py_Py3kWarningFlag;
34
35/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
36   These are used by the individual routines for object creation.
37   Do not call them otherwise, they do not initialize the object! */
38
39#ifdef Py_TRACE_REFS
40/* Head of circular doubly-linked list of all objects.  These are linked
41 * together via the _ob_prev and _ob_next members of a PyObject, which
42 * exist only in a Py_TRACE_REFS build.
43 */
44static PyObject refchain = {&refchain, &refchain};
45
46/* Insert op at the front of the list of all objects.  If force is true,
47 * op is added even if _ob_prev and _ob_next are non-NULL already.  If
48 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
49 * force should be true if and only if op points to freshly allocated,
50 * uninitialized memory, or you've unlinked op from the list and are
51 * relinking it into the front.
52 * Note that objects are normally added to the list via _Py_NewReference,
53 * which is called by PyObject_Init.  Not all objects are initialized that
54 * way, though; exceptions include statically allocated type objects, and
55 * statically allocated singletons (like Py_True and Py_None).
56 */
57void
58_Py_AddToAllObjects(PyObject *op, int force)
59{
60#ifdef  Py_DEBUG
61    if (!force) {
62        /* If it's initialized memory, op must be in or out of
63         * the list unambiguously.
64         */
65        assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
66    }
67#endif
68    if (force || op->_ob_prev == NULL) {
69        op->_ob_next = refchain._ob_next;
70        op->_ob_prev = &refchain;
71        refchain._ob_next->_ob_prev = op;
72        refchain._ob_next = op;
73    }
74}
75#endif  /* Py_TRACE_REFS */
76
77#ifdef COUNT_ALLOCS
78static PyTypeObject *type_list;
79/* All types are added to type_list, at least when
80   they get one object created. That makes them
81   immortal, which unfortunately contributes to
82   garbage itself. If unlist_types_without_objects
83   is set, they will be removed from the type_list
84   once the last object is deallocated. */
85static int unlist_types_without_objects;
86extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
87extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
88extern Py_ssize_t null_strings, one_strings;
89void
90dump_counts(FILE* f)
91{
92    PyTypeObject *tp;
93
94    for (tp = type_list; tp; tp = tp->tp_next)
95        fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
96            "freed: %" PY_FORMAT_SIZE_T "d, "
97            "max in use: %" PY_FORMAT_SIZE_T "d\n",
98            tp->tp_name, tp->tp_allocs, tp->tp_frees,
99            tp->tp_maxalloc);
100    fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
101        "empty: %" PY_FORMAT_SIZE_T "d\n",
102        fast_tuple_allocs, tuple_zero_allocs);
103    fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
104        "neg: %" PY_FORMAT_SIZE_T "d\n",
105        quick_int_allocs, quick_neg_int_allocs);
106    fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
107        "1-strings: %" PY_FORMAT_SIZE_T "d\n",
108        null_strings, one_strings);
109}
110
111PyObject *
112get_counts(void)
113{
114    PyTypeObject *tp;
115    PyObject *result;
116    PyObject *v;
117
118    result = PyList_New(0);
119    if (result == NULL)
120        return NULL;
121    for (tp = type_list; tp; tp = tp->tp_next) {
122        v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
123                          tp->tp_frees, tp->tp_maxalloc);
124        if (v == NULL) {
125            Py_DECREF(result);
126            return NULL;
127        }
128        if (PyList_Append(result, v) < 0) {
129            Py_DECREF(v);
130            Py_DECREF(result);
131            return NULL;
132        }
133        Py_DECREF(v);
134    }
135    return result;
136}
137
138void
139inc_count(PyTypeObject *tp)
140{
141    if (tp->tp_next == NULL && tp->tp_prev == NULL) {
142        /* first time; insert in linked list */
143        if (tp->tp_next != NULL) /* sanity check */
144            Py_FatalError("XXX inc_count sanity check");
145        if (type_list)
146            type_list->tp_prev = tp;
147        tp->tp_next = type_list;
148        /* Note that as of Python 2.2, heap-allocated type objects
149         * can go away, but this code requires that they stay alive
150         * until program exit.  That's why we're careful with
151         * refcounts here.  type_list gets a new reference to tp,
152         * while ownership of the reference type_list used to hold
153         * (if any) was transferred to tp->tp_next in the line above.
154         * tp is thus effectively immortal after this.
155         */
156        Py_INCREF(tp);
157        type_list = tp;
158#ifdef Py_TRACE_REFS
159        /* Also insert in the doubly-linked list of all objects,
160         * if not already there.
161         */
162        _Py_AddToAllObjects((PyObject *)tp, 0);
163#endif
164    }
165    tp->tp_allocs++;
166    if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
167        tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
168}
169
170void dec_count(PyTypeObject *tp)
171{
172    tp->tp_frees++;
173    if (unlist_types_without_objects &&
174        tp->tp_allocs == tp->tp_frees) {
175        /* unlink the type from type_list */
176        if (tp->tp_prev)
177            tp->tp_prev->tp_next = tp->tp_next;
178        else
179            type_list = tp->tp_next;
180        if (tp->tp_next)
181            tp->tp_next->tp_prev = tp->tp_prev;
182        tp->tp_next = tp->tp_prev = NULL;
183        Py_DECREF(tp);
184    }
185}
186
187#endif
188
189#ifdef Py_REF_DEBUG
190/* Log a fatal error; doesn't return. */
191void
192_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
193{
194    char buf[300];
195
196    PyOS_snprintf(buf, sizeof(buf),
197                  "%s:%i object at %p has negative ref count "
198                  "%" PY_FORMAT_SIZE_T "d",
199                  fname, lineno, op, op->ob_refcnt);
200    Py_FatalError(buf);
201}
202
203#endif /* Py_REF_DEBUG */
204
205void
206Py_IncRef(PyObject *o)
207{
208    Py_XINCREF(o);
209}
210
211void
212Py_DecRef(PyObject *o)
213{
214    Py_XDECREF(o);
215}
216
217PyObject *
218PyObject_Init(PyObject *op, PyTypeObject *tp)
219{
220    if (op == NULL)
221        return PyErr_NoMemory();
222    /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
223    Py_TYPE(op) = tp;
224    _Py_NewReference(op);
225    return op;
226}
227
228PyVarObject *
229PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
230{
231    if (op == NULL)
232        return (PyVarObject *) PyErr_NoMemory();
233    /* Any changes should be reflected in PyObject_INIT_VAR */
234    op->ob_size = size;
235    Py_TYPE(op) = tp;
236    _Py_NewReference((PyObject *)op);
237    return op;
238}
239
240PyObject *
241_PyObject_New(PyTypeObject *tp)
242{
243    PyObject *op;
244    op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
245    if (op == NULL)
246        return PyErr_NoMemory();
247    return PyObject_INIT(op, tp);
248}
249
250PyVarObject *
251_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
252{
253    PyVarObject *op;
254    const size_t size = _PyObject_VAR_SIZE(tp, nitems);
255    op = (PyVarObject *) PyObject_MALLOC(size);
256    if (op == NULL)
257        return (PyVarObject *)PyErr_NoMemory();
258    return PyObject_INIT_VAR(op, tp, nitems);
259}
260
261/* for binary compatibility with 2.2 */
262#undef _PyObject_Del
263void
264_PyObject_Del(PyObject *op)
265{
266    PyObject_FREE(op);
267}
268
269/* Implementation of PyObject_Print with recursion checking */
270static int
271internal_print(PyObject *op, FILE *fp, int flags, int nesting)
272{
273    int ret = 0;
274    if (nesting > 10) {
275        PyErr_SetString(PyExc_RuntimeError, "print recursion");
276        return -1;
277    }
278    if (PyErr_CheckSignals())
279        return -1;
280#ifdef USE_STACKCHECK
281    if (PyOS_CheckStack()) {
282        PyErr_SetString(PyExc_MemoryError, "stack overflow");
283        return -1;
284    }
285#endif
286    clearerr(fp); /* Clear any previous error condition */
287    if (op == NULL) {
288        Py_BEGIN_ALLOW_THREADS
289        fprintf(fp, "<nil>");
290        Py_END_ALLOW_THREADS
291    }
292    else {
293        if (op->ob_refcnt <= 0)
294            /* XXX(twouters) cast refcount to long until %zd is
295               universally available */
296            Py_BEGIN_ALLOW_THREADS
297            fprintf(fp, "<refcnt %ld at %p>",
298                (long)op->ob_refcnt, op);
299            Py_END_ALLOW_THREADS
300        else if (Py_TYPE(op)->tp_print == NULL) {
301            PyObject *s;
302            if (flags & Py_PRINT_RAW)
303                s = PyObject_Str(op);
304            else
305                s = PyObject_Repr(op);
306            if (s == NULL)
307                ret = -1;
308            else {
309                ret = internal_print(s, fp, Py_PRINT_RAW,
310                                     nesting+1);
311            }
312            Py_XDECREF(s);
313        }
314        else
315            ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
316    }
317    if (ret == 0) {
318        if (ferror(fp)) {
319            PyErr_SetFromErrno(PyExc_IOError);
320            clearerr(fp);
321            ret = -1;
322        }
323    }
324    return ret;
325}
326
327int
328PyObject_Print(PyObject *op, FILE *fp, int flags)
329{
330    return internal_print(op, fp, flags, 0);
331}
332
333
334/* For debugging convenience.  See Misc/gdbinit for some useful gdb hooks */
335void _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    if (PyErr_CheckSignals())
367        return NULL;
368#ifdef USE_STACKCHECK
369    if (PyOS_CheckStack()) {
370        PyErr_SetString(PyExc_MemoryError, "stack overflow");
371        return NULL;
372    }
373#endif
374    if (v == NULL)
375        return PyString_FromString("<NULL>");
376    else if (Py_TYPE(v)->tp_repr == NULL)
377        return PyString_FromFormat("<%s object at %p>",
378                                   Py_TYPE(v)->tp_name, v);
379    else {
380        PyObject *res;
381        res = (*Py_TYPE(v)->tp_repr)(v);
382        if (res == NULL)
383            return NULL;
384#ifdef Py_USING_UNICODE
385        if (PyUnicode_Check(res)) {
386            PyObject* str;
387            str = PyUnicode_AsEncodedString(res, NULL, NULL);
388            Py_DECREF(res);
389            if (str)
390                res = str;
391            else
392                return NULL;
393        }
394#endif
395        if (!PyString_Check(res)) {
396            PyErr_Format(PyExc_TypeError,
397                         "__repr__ returned non-string (type %.200s)",
398                         Py_TYPE(res)->tp_name);
399            Py_DECREF(res);
400            return NULL;
401        }
402        return res;
403    }
404}
405
406PyObject *
407_PyObject_Str(PyObject *v)
408{
409    PyObject *res;
410    int type_ok;
411    if (v == NULL)
412        return PyString_FromString("<NULL>");
413    if (PyString_CheckExact(v)) {
414        Py_INCREF(v);
415        return v;
416    }
417#ifdef Py_USING_UNICODE
418    if (PyUnicode_CheckExact(v)) {
419        Py_INCREF(v);
420        return v;
421    }
422#endif
423    if (Py_TYPE(v)->tp_str == NULL)
424        return PyObject_Repr(v);
425
426    /* It is possible for a type to have a tp_str representation that loops
427       infinitely. */
428    if (Py_EnterRecursiveCall(" while getting the str of an object"))
429        return NULL;
430    res = (*Py_TYPE(v)->tp_str)(v);
431    Py_LeaveRecursiveCall();
432    if (res == NULL)
433        return NULL;
434    type_ok = PyString_Check(res);
435#ifdef Py_USING_UNICODE
436    type_ok = type_ok || PyUnicode_Check(res);
437#endif
438    if (!type_ok) {
439        PyErr_Format(PyExc_TypeError,
440                     "__str__ returned non-string (type %.200s)",
441                     Py_TYPE(res)->tp_name);
442        Py_DECREF(res);
443        return NULL;
444    }
445    return res;
446}
447
448PyObject *
449PyObject_Str(PyObject *v)
450{
451    PyObject *res = _PyObject_Str(v);
452    if (res == NULL)
453        return NULL;
454#ifdef Py_USING_UNICODE
455    if (PyUnicode_Check(res)) {
456        PyObject* str;
457        str = PyUnicode_AsEncodedString(res, NULL, NULL);
458        Py_DECREF(res);
459        if (str)
460            res = str;
461        else
462            return NULL;
463    }
464#endif
465    assert(PyString_Check(res));
466    return res;
467}
468
469#ifdef Py_USING_UNICODE
470PyObject *
471PyObject_Unicode(PyObject *v)
472{
473    PyObject *res;
474    PyObject *func;
475    PyObject *str;
476    int unicode_method_found = 0;
477    static PyObject *unicodestr = NULL;
478
479    if (v == NULL) {
480        res = PyString_FromString("<NULL>");
481        if (res == NULL)
482            return NULL;
483        str = PyUnicode_FromEncodedObject(res, NULL, "strict");
484        Py_DECREF(res);
485        return str;
486    } else if (PyUnicode_CheckExact(v)) {
487        Py_INCREF(v);
488        return v;
489    }
490
491    if (PyInstance_Check(v)) {
492        /* We're an instance of a classic class */
493        /* Try __unicode__ from the instance -- alas we have no type */
494        if (!unicodestr) {
495            unicodestr = PyString_InternFromString("__unicode__");
496            if (!unicodestr)
497                return NULL;
498        }
499        func = PyObject_GetAttr(v, unicodestr);
500        if (func != NULL) {
501            unicode_method_found = 1;
502            res = PyObject_CallFunctionObjArgs(func, NULL);
503            Py_DECREF(func);
504        }
505        else {
506            PyErr_Clear();
507        }
508    }
509    else {
510        /* Not a classic class instance, try __unicode__. */
511        func = _PyObject_LookupSpecial(v, "__unicode__", &unicodestr);
512        if (func != NULL) {
513            unicode_method_found = 1;
514            res = PyObject_CallFunctionObjArgs(func, NULL);
515            Py_DECREF(func);
516        }
517        else if (PyErr_Occurred())
518            return NULL;
519    }
520
521    /* Didn't find __unicode__ */
522    if (!unicode_method_found) {
523        if (PyUnicode_Check(v)) {
524            /* For a Unicode subtype that's didn't overwrite __unicode__,
525               return a true Unicode object with the same data. */
526            return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
527                                         PyUnicode_GET_SIZE(v));
528        }
529        if (PyString_CheckExact(v)) {
530            Py_INCREF(v);
531            res = v;
532        }
533        else {
534            if (Py_TYPE(v)->tp_str != NULL)
535                res = (*Py_TYPE(v)->tp_str)(v);
536            else
537                res = PyObject_Repr(v);
538        }
539    }
540
541    if (res == NULL)
542        return NULL;
543    if (!PyUnicode_Check(res)) {
544        str = PyUnicode_FromEncodedObject(res, NULL, "strict");
545        Py_DECREF(res);
546        res = str;
547    }
548    return res;
549}
550#endif
551
552
553/* Helper to warn about deprecated tp_compare return values.  Return:
554   -2 for an exception;
555   -1 if v <  w;
556    0 if v == w;
557    1 if v  > w.
558   (This function cannot return 2.)
559*/
560static int
561adjust_tp_compare(int c)
562{
563    if (PyErr_Occurred()) {
564        if (c != -1 && c != -2) {
565            PyObject *t, *v, *tb;
566            PyErr_Fetch(&t, &v, &tb);
567            if (PyErr_Warn(PyExc_RuntimeWarning,
568                           "tp_compare didn't return -1 or -2 "
569                           "for exception") < 0) {
570                Py_XDECREF(t);
571                Py_XDECREF(v);
572                Py_XDECREF(tb);
573            }
574            else
575                PyErr_Restore(t, v, tb);
576        }
577        return -2;
578    }
579    else if (c < -1 || c > 1) {
580        if (PyErr_Warn(PyExc_RuntimeWarning,
581                       "tp_compare didn't return -1, 0 or 1") < 0)
582            return -2;
583        else
584            return c < -1 ? -1 : 1;
585    }
586    else {
587        assert(c >= -1 && c <= 1);
588        return c;
589    }
590}
591
592
593/* Macro to get the tp_richcompare field of a type if defined */
594#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
595             ? (t)->tp_richcompare : NULL)
596
597/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
598int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
599
600/* Try a genuine rich comparison, returning an object.  Return:
601   NULL for exception;
602   NotImplemented if this particular rich comparison is not implemented or
603     undefined;
604   some object not equal to NotImplemented if it is implemented
605     (this latter object may not be a Boolean).
606*/
607static PyObject *
608try_rich_compare(PyObject *v, PyObject *w, int op)
609{
610    richcmpfunc f;
611    PyObject *res;
612
613    if (v->ob_type != w->ob_type &&
614        PyType_IsSubtype(w->ob_type, v->ob_type) &&
615        (f = RICHCOMPARE(w->ob_type)) != NULL) {
616        res = (*f)(w, v, _Py_SwappedOp[op]);
617        if (res != Py_NotImplemented)
618            return res;
619        Py_DECREF(res);
620    }
621    if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
622        res = (*f)(v, w, op);
623        if (res != Py_NotImplemented)
624            return res;
625        Py_DECREF(res);
626    }
627    if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
628        return (*f)(w, v, _Py_SwappedOp[op]);
629    }
630    res = Py_NotImplemented;
631    Py_INCREF(res);
632    return res;
633}
634
635/* Try a genuine rich comparison, returning an int.  Return:
636   -1 for exception (including the case where try_rich_compare() returns an
637      object that's not a Boolean);
638    0 if the outcome is false;
639    1 if the outcome is true;
640    2 if this particular rich comparison is not implemented or undefined.
641*/
642static int
643try_rich_compare_bool(PyObject *v, PyObject *w, int op)
644{
645    PyObject *res;
646    int ok;
647
648    if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
649        return 2; /* Shortcut, avoid INCREF+DECREF */
650    res = try_rich_compare(v, w, op);
651    if (res == NULL)
652        return -1;
653    if (res == Py_NotImplemented) {
654        Py_DECREF(res);
655        return 2;
656    }
657    ok = PyObject_IsTrue(res);
658    Py_DECREF(res);
659    return ok;
660}
661
662/* Try rich comparisons to determine a 3-way comparison.  Return:
663   -2 for an exception;
664   -1 if v  < w;
665    0 if v == w;
666    1 if v  > w;
667    2 if this particular rich comparison is not implemented or undefined.
668*/
669static int
670try_rich_to_3way_compare(PyObject *v, PyObject *w)
671{
672    static struct { int op; int outcome; } tries[3] = {
673        /* Try this operator, and if it is true, use this outcome: */
674        {Py_EQ, 0},
675        {Py_LT, -1},
676        {Py_GT, 1},
677    };
678    int i;
679
680    if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
681        return 2; /* Shortcut */
682
683    for (i = 0; i < 3; i++) {
684        switch (try_rich_compare_bool(v, w, tries[i].op)) {
685        case -1:
686            return -2;
687        case 1:
688            return tries[i].outcome;
689        }
690    }
691
692    return 2;
693}
694
695/* Try a 3-way comparison, returning an int.  Return:
696   -2 for an exception;
697   -1 if v <  w;
698    0 if v == w;
699    1 if v  > w;
700    2 if this particular 3-way comparison is not implemented or undefined.
701*/
702static int
703try_3way_compare(PyObject *v, PyObject *w)
704{
705    int c;
706    cmpfunc f;
707
708    /* Comparisons involving instances are given to instance_compare,
709       which has the same return conventions as this function. */
710
711    f = v->ob_type->tp_compare;
712    if (PyInstance_Check(v))
713        return (*f)(v, w);
714    if (PyInstance_Check(w))
715        return (*w->ob_type->tp_compare)(v, w);
716
717    /* If both have the same (non-NULL) tp_compare, use it. */
718    if (f != NULL && f == w->ob_type->tp_compare) {
719        c = (*f)(v, w);
720        return adjust_tp_compare(c);
721    }
722
723    /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
724    if (f == _PyObject_SlotCompare ||
725        w->ob_type->tp_compare == _PyObject_SlotCompare)
726        return _PyObject_SlotCompare(v, w);
727
728    /* If we're here, v and w,
729        a) are not instances;
730        b) have different types or a type without tp_compare; and
731        c) don't have a user-defined tp_compare.
732       tp_compare implementations in C assume that both arguments
733       have their type, so we give up if the coercion fails or if
734       it yields types which are still incompatible (which can
735       happen with a user-defined nb_coerce).
736    */
737    c = PyNumber_CoerceEx(&v, &w);
738    if (c < 0)
739        return -2;
740    if (c > 0)
741        return 2;
742    f = v->ob_type->tp_compare;
743    if (f != NULL && f == w->ob_type->tp_compare) {
744        c = (*f)(v, w);
745        Py_DECREF(v);
746        Py_DECREF(w);
747        return adjust_tp_compare(c);
748    }
749
750    /* No comparison defined */
751    Py_DECREF(v);
752    Py_DECREF(w);
753    return 2;
754}
755
756/* Final fallback 3-way comparison, returning an int.  Return:
757   -2 if an error occurred;
758   -1 if v <  w;
759    0 if v == w;
760    1 if v >  w.
761*/
762static int
763default_3way_compare(PyObject *v, PyObject *w)
764{
765    int c;
766    const char *vname, *wname;
767
768    if (v->ob_type == w->ob_type) {
769        /* When comparing these pointers, they must be cast to
770         * integer types (i.e. Py_uintptr_t, our spelling of C9X's
771         * uintptr_t).  ANSI specifies that pointer compares other
772         * than == and != to non-related structures are undefined.
773         */
774        Py_uintptr_t vv = (Py_uintptr_t)v;
775        Py_uintptr_t ww = (Py_uintptr_t)w;
776        return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
777    }
778
779    /* None is smaller than anything */
780    if (v == Py_None)
781        return -1;
782    if (w == Py_None)
783        return 1;
784
785    /* different type: compare type names; numbers are smaller */
786    if (PyNumber_Check(v))
787        vname = "";
788    else
789        vname = v->ob_type->tp_name;
790    if (PyNumber_Check(w))
791        wname = "";
792    else
793        wname = w->ob_type->tp_name;
794    c = strcmp(vname, wname);
795    if (c < 0)
796        return -1;
797    if (c > 0)
798        return 1;
799    /* Same type name, or (more likely) incomparable numeric types */
800    return ((Py_uintptr_t)(v->ob_type) < (
801        Py_uintptr_t)(w->ob_type)) ? -1 : 1;
802}
803
804/* Do a 3-way comparison, by hook or by crook.  Return:
805   -2 for an exception (but see below);
806   -1 if v <  w;
807    0 if v == w;
808    1 if v >  w;
809   BUT: if the object implements a tp_compare function, it returns
810   whatever this function returns (whether with an exception or not).
811*/
812static int
813do_cmp(PyObject *v, PyObject *w)
814{
815    int c;
816    cmpfunc f;
817
818    if (v->ob_type == w->ob_type
819        && (f = v->ob_type->tp_compare) != NULL) {
820        c = (*f)(v, w);
821        if (PyInstance_Check(v)) {
822            /* Instance tp_compare has a different signature.
823               But if it returns undefined we fall through. */
824            if (c != 2)
825                return c;
826            /* Else fall through to try_rich_to_3way_compare() */
827        }
828        else
829            return adjust_tp_compare(c);
830    }
831    /* We only get here if one of the following is true:
832       a) v and w have different types
833       b) v and w have the same type, which doesn't have tp_compare
834       c) v and w are instances, and either __cmp__ is not defined or
835          __cmp__ returns NotImplemented
836    */
837    c = try_rich_to_3way_compare(v, w);
838    if (c < 2)
839        return c;
840    c = try_3way_compare(v, w);
841    if (c < 2)
842        return c;
843    return default_3way_compare(v, w);
844}
845
846/* Compare v to w.  Return
847   -1 if v <  w or exception (PyErr_Occurred() true in latter case).
848    0 if v == w.
849    1 if v > w.
850   XXX The docs (C API manual) say the return value is undefined in case
851   XXX of error.
852*/
853int
854PyObject_Compare(PyObject *v, PyObject *w)
855{
856    int result;
857
858    if (v == NULL || w == NULL) {
859        PyErr_BadInternalCall();
860        return -1;
861    }
862    if (v == w)
863        return 0;
864    if (Py_EnterRecursiveCall(" in cmp"))
865        return -1;
866    result = do_cmp(v, w);
867    Py_LeaveRecursiveCall();
868    return result < 0 ? -1 : result;
869}
870
871/* Return (new reference to) Py_True or Py_False. */
872static PyObject *
873convert_3way_to_object(int op, int c)
874{
875    PyObject *result;
876    switch (op) {
877    case Py_LT: c = c <  0; break;
878    case Py_LE: c = c <= 0; break;
879    case Py_EQ: c = c == 0; break;
880    case Py_NE: c = c != 0; break;
881    case Py_GT: c = c >  0; break;
882    case Py_GE: c = c >= 0; break;
883    }
884    result = c ? Py_True : Py_False;
885    Py_INCREF(result);
886    return result;
887}
888
889/* We want a rich comparison but don't have one.  Try a 3-way cmp instead.
890   Return
891   NULL      if error
892   Py_True   if v op w
893   Py_False  if not (v op w)
894*/
895static PyObject *
896try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
897{
898    int c;
899
900    c = try_3way_compare(v, w);
901    if (c >= 2) {
902
903        /* Py3K warning if types are not equal and comparison isn't == or !=  */
904        if (Py_Py3kWarningFlag &&
905            v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
906            PyErr_WarnEx(PyExc_DeprecationWarning,
907                       "comparing unequal types not supported "
908                       "in 3.x", 1) < 0) {
909            return NULL;
910        }
911
912        c = default_3way_compare(v, w);
913    }
914    if (c <= -2)
915        return NULL;
916    return convert_3way_to_object(op, c);
917}
918
919/* Do rich comparison on v and w.  Return
920   NULL      if error
921   Else a new reference to an object other than Py_NotImplemented, usually(?):
922   Py_True   if v op w
923   Py_False  if not (v op w)
924*/
925static PyObject *
926do_richcmp(PyObject *v, PyObject *w, int op)
927{
928    PyObject *res;
929
930    res = try_rich_compare(v, w, op);
931    if (res != Py_NotImplemented)
932        return res;
933    Py_DECREF(res);
934
935    return try_3way_to_rich_compare(v, w, op);
936}
937
938/* Return:
939   NULL for exception;
940   some object not equal to NotImplemented if it is implemented
941     (this latter object may not be a Boolean).
942*/
943PyObject *
944PyObject_RichCompare(PyObject *v, PyObject *w, int op)
945{
946    PyObject *res;
947
948    assert(Py_LT <= op && op <= Py_GE);
949    if (Py_EnterRecursiveCall(" in cmp"))
950        return NULL;
951
952    /* If the types are equal, and not old-style instances, try to
953       get out cheap (don't bother with coercions etc.). */
954    if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
955        cmpfunc fcmp;
956        richcmpfunc frich = RICHCOMPARE(v->ob_type);
957        /* If the type has richcmp, try it first.  try_rich_compare
958           tries it two-sided, which is not needed since we've a
959           single type only. */
960        if (frich != NULL) {
961            res = (*frich)(v, w, op);
962            if (res != Py_NotImplemented)
963                goto Done;
964            Py_DECREF(res);
965        }
966        /* No richcmp, or this particular richmp not implemented.
967           Try 3-way cmp. */
968        fcmp = v->ob_type->tp_compare;
969        if (fcmp != NULL) {
970            int c = (*fcmp)(v, w);
971            c = adjust_tp_compare(c);
972            if (c == -2) {
973                res = NULL;
974                goto Done;
975            }
976            res = convert_3way_to_object(op, c);
977            goto Done;
978        }
979    }
980
981    /* Fast path not taken, or couldn't deliver a useful result. */
982    res = do_richcmp(v, w, op);
983Done:
984    Py_LeaveRecursiveCall();
985    return res;
986}
987
988/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
989int
990PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
991{
992    PyObject *res;
993    int ok;
994
995    /* Quick result when objects are the same.
996       Guarantees that identity implies equality. */
997    if (v == w) {
998        if (op == Py_EQ)
999            return 1;
1000        else if (op == Py_NE)
1001            return 0;
1002    }
1003
1004    res = PyObject_RichCompare(v, w, op);
1005    if (res == NULL)
1006        return -1;
1007    if (PyBool_Check(res))
1008        ok = (res == Py_True);
1009    else
1010        ok = PyObject_IsTrue(res);
1011    Py_DECREF(res);
1012    return ok;
1013}
1014
1015/* Set of hash utility functions to help maintaining the invariant that
1016    if a==b then hash(a)==hash(b)
1017
1018   All the utility functions (_Py_Hash*()) return "-1" to signify an error.
1019*/
1020
1021long
1022_Py_HashDouble(double v)
1023{
1024    double intpart, fractpart;
1025    int expo;
1026    long hipart;
1027    long x;             /* the final hash value */
1028    /* This is designed so that Python numbers of different types
1029     * that compare equal hash to the same value; otherwise comparisons
1030     * of mapping keys will turn out weird.
1031     */
1032
1033    if (!Py_IS_FINITE(v)) {
1034        if (Py_IS_INFINITY(v))
1035            return v < 0 ? -271828 : 314159;
1036        else
1037            return 0;
1038    }
1039    fractpart = modf(v, &intpart);
1040    if (fractpart == 0.0) {
1041        /* This must return the same hash as an equal int or long. */
1042        if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
1043            /* Convert to long and use its hash. */
1044            PyObject *plong;                    /* converted to Python long */
1045            plong = PyLong_FromDouble(v);
1046            if (plong == NULL)
1047                return -1;
1048            x = PyObject_Hash(plong);
1049            Py_DECREF(plong);
1050            return x;
1051        }
1052        /* Fits in a C long == a Python int, so is its own hash. */
1053        x = (long)intpart;
1054        if (x == -1)
1055            x = -2;
1056        return x;
1057    }
1058    /* The fractional part is non-zero, so we don't have to worry about
1059     * making this match the hash of some other type.
1060     * Use frexp to get at the bits in the double.
1061     * Since the VAX D double format has 56 mantissa bits, which is the
1062     * most of any double format in use, each of these parts may have as
1063     * many as (but no more than) 56 significant bits.
1064     * So, assuming sizeof(long) >= 4, each part can be broken into two
1065     * longs; frexp and multiplication are used to do that.
1066     * Also, since the Cray double format has 15 exponent bits, which is
1067     * the most of any double format in use, shifting the exponent field
1068     * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
1069     */
1070    v = frexp(v, &expo);
1071    v *= 2147483648.0;          /* 2**31 */
1072    hipart = (long)v;           /* take the top 32 bits */
1073    v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
1074    x = hipart + (long)v + (expo << 15);
1075    if (x == -1)
1076        x = -2;
1077    return x;
1078}
1079
1080long
1081_Py_HashPointer(void *p)
1082{
1083    long x;
1084    size_t y = (size_t)p;
1085    /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
1086       excessive hash collisions for dicts and sets */
1087    y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
1088    x = (long)y;
1089    if (x == -1)
1090        x = -2;
1091    return x;
1092}
1093
1094long
1095PyObject_HashNotImplemented(PyObject *self)
1096{
1097    PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
1098                 self->ob_type->tp_name);
1099    return -1;
1100}
1101
1102_Py_HashSecret_t _Py_HashSecret;
1103
1104long
1105PyObject_Hash(PyObject *v)
1106{
1107    PyTypeObject *tp = v->ob_type;
1108    if (tp->tp_hash != NULL)
1109        return (*tp->tp_hash)(v);
1110    /* To keep to the general practice that inheriting
1111     * solely from object in C code should work without
1112     * an explicit call to PyType_Ready, we implicitly call
1113     * PyType_Ready here and then check the tp_hash slot again
1114     */
1115    if (tp->tp_dict == NULL) {
1116        if (PyType_Ready(tp) < 0)
1117            return -1;
1118        if (tp->tp_hash != NULL)
1119            return (*tp->tp_hash)(v);
1120    }
1121    if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
1122        return _Py_HashPointer(v); /* Use address as hash value */
1123    }
1124    /* If there's a cmp but no hash defined, the object can't be hashed */
1125    return PyObject_HashNotImplemented(v);
1126}
1127
1128PyObject *
1129PyObject_GetAttrString(PyObject *v, const char *name)
1130{
1131    PyObject *w, *res;
1132
1133    if (Py_TYPE(v)->tp_getattr != NULL)
1134        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
1135    w = PyString_InternFromString(name);
1136    if (w == NULL)
1137        return NULL;
1138    res = PyObject_GetAttr(v, w);
1139    Py_XDECREF(w);
1140    return res;
1141}
1142
1143int
1144PyObject_HasAttrString(PyObject *v, const char *name)
1145{
1146    PyObject *res = PyObject_GetAttrString(v, name);
1147    if (res != NULL) {
1148        Py_DECREF(res);
1149        return 1;
1150    }
1151    PyErr_Clear();
1152    return 0;
1153}
1154
1155int
1156PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
1157{
1158    PyObject *s;
1159    int res;
1160
1161    if (Py_TYPE(v)->tp_setattr != NULL)
1162        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
1163    s = PyString_InternFromString(name);
1164    if (s == NULL)
1165        return -1;
1166    res = PyObject_SetAttr(v, s, w);
1167    Py_XDECREF(s);
1168    return res;
1169}
1170
1171PyObject *
1172PyObject_GetAttr(PyObject *v, PyObject *name)
1173{
1174    PyTypeObject *tp = Py_TYPE(v);
1175
1176    if (!PyString_Check(name)) {
1177#ifdef Py_USING_UNICODE
1178        /* The Unicode to string conversion is done here because the
1179           existing tp_getattro slots expect a string object as name
1180           and we wouldn't want to break those. */
1181        if (PyUnicode_Check(name)) {
1182            name = _PyUnicode_AsDefaultEncodedString(name, NULL);
1183            if (name == NULL)
1184                return NULL;
1185        }
1186        else
1187#endif
1188        {
1189            PyErr_Format(PyExc_TypeError,
1190                         "attribute name must be string, not '%.200s'",
1191                         Py_TYPE(name)->tp_name);
1192            return NULL;
1193        }
1194    }
1195    if (tp->tp_getattro != NULL)
1196        return (*tp->tp_getattro)(v, name);
1197    if (tp->tp_getattr != NULL)
1198        return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
1199    PyErr_Format(PyExc_AttributeError,
1200                 "'%.50s' object has no attribute '%.400s'",
1201                 tp->tp_name, PyString_AS_STRING(name));
1202    return NULL;
1203}
1204
1205int
1206PyObject_HasAttr(PyObject *v, PyObject *name)
1207{
1208    PyObject *res = PyObject_GetAttr(v, name);
1209    if (res != NULL) {
1210        Py_DECREF(res);
1211        return 1;
1212    }
1213    PyErr_Clear();
1214    return 0;
1215}
1216
1217int
1218PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
1219{
1220    PyTypeObject *tp = Py_TYPE(v);
1221    int err;
1222
1223    if (!PyString_Check(name)){
1224#ifdef Py_USING_UNICODE
1225        /* The Unicode to string conversion is done here because the
1226           existing tp_setattro slots expect a string object as name
1227           and we wouldn't want to break those. */
1228        if (PyUnicode_Check(name)) {
1229            name = PyUnicode_AsEncodedString(name, NULL, NULL);
1230            if (name == NULL)
1231                return -1;
1232        }
1233        else
1234#endif
1235        {
1236            PyErr_Format(PyExc_TypeError,
1237                         "attribute name must be string, not '%.200s'",
1238                         Py_TYPE(name)->tp_name);
1239            return -1;
1240        }
1241    }
1242    else
1243        Py_INCREF(name);
1244
1245    PyString_InternInPlace(&name);
1246    if (tp->tp_setattro != NULL) {
1247        err = (*tp->tp_setattro)(v, name, value);
1248        Py_DECREF(name);
1249        return err;
1250    }
1251    if (tp->tp_setattr != NULL) {
1252        err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
1253        Py_DECREF(name);
1254        return err;
1255    }
1256    Py_DECREF(name);
1257    if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
1258        PyErr_Format(PyExc_TypeError,
1259                     "'%.100s' object has no attributes "
1260                     "(%s .%.100s)",
1261                     tp->tp_name,
1262                     value==NULL ? "del" : "assign to",
1263                     PyString_AS_STRING(name));
1264    else
1265        PyErr_Format(PyExc_TypeError,
1266                     "'%.100s' object has only read-only attributes "
1267                     "(%s .%.100s)",
1268                     tp->tp_name,
1269                     value==NULL ? "del" : "assign to",
1270                     PyString_AS_STRING(name));
1271    return -1;
1272}
1273
1274/* Helper to get a pointer to an object's __dict__ slot, if any */
1275
1276PyObject **
1277_PyObject_GetDictPtr(PyObject *obj)
1278{
1279    Py_ssize_t dictoffset;
1280    PyTypeObject *tp = Py_TYPE(obj);
1281
1282    if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
1283        return NULL;
1284    dictoffset = tp->tp_dictoffset;
1285    if (dictoffset == 0)
1286        return NULL;
1287    if (dictoffset < 0) {
1288        Py_ssize_t tsize;
1289        size_t size;
1290
1291        tsize = ((PyVarObject *)obj)->ob_size;
1292        if (tsize < 0)
1293            tsize = -tsize;
1294        size = _PyObject_VAR_SIZE(tp, tsize);
1295
1296        dictoffset += (long)size;
1297        assert(dictoffset > 0);
1298        assert(dictoffset % SIZEOF_VOID_P == 0);
1299    }
1300    return (PyObject **) ((char *)obj + dictoffset);
1301}
1302
1303PyObject *
1304PyObject_SelfIter(PyObject *obj)
1305{
1306    Py_INCREF(obj);
1307    return obj;
1308}
1309
1310/* Helper used when the __next__ method is removed from a type:
1311   tp_iternext is never NULL and can be safely called without checking
1312   on every iteration.
1313 */
1314
1315PyObject *
1316_PyObject_NextNotImplemented(PyObject *self)
1317{
1318    PyErr_Format(PyExc_TypeError,
1319                 "'%.200s' object is not iterable",
1320                 Py_TYPE(self)->tp_name);
1321    return NULL;
1322}
1323
1324/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
1325
1326PyObject *
1327_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
1328{
1329    PyTypeObject *tp = Py_TYPE(obj);
1330    PyObject *descr = NULL;
1331    PyObject *res = NULL;
1332    descrgetfunc f;
1333    Py_ssize_t dictoffset;
1334    PyObject **dictptr;
1335
1336    if (!PyString_Check(name)){
1337#ifdef Py_USING_UNICODE
1338        /* The Unicode to string conversion is done here because the
1339           existing tp_setattro slots expect a string object as name
1340           and we wouldn't want to break those. */
1341        if (PyUnicode_Check(name)) {
1342            name = PyUnicode_AsEncodedString(name, NULL, NULL);
1343            if (name == NULL)
1344                return NULL;
1345        }
1346        else
1347#endif
1348        {
1349            PyErr_Format(PyExc_TypeError,
1350                         "attribute name must be string, not '%.200s'",
1351                         Py_TYPE(name)->tp_name);
1352            return NULL;
1353        }
1354    }
1355    else
1356        Py_INCREF(name);
1357
1358    if (tp->tp_dict == NULL) {
1359        if (PyType_Ready(tp) < 0)
1360            goto done;
1361    }
1362
1363#if 0 /* XXX this is not quite _PyType_Lookup anymore */
1364    /* Inline _PyType_Lookup */
1365    {
1366        Py_ssize_t i, n;
1367        PyObject *mro, *base, *dict;
1368
1369        /* Look in tp_dict of types in MRO */
1370        mro = tp->tp_mro;
1371        assert(mro != NULL);
1372        assert(PyTuple_Check(mro));
1373        n = PyTuple_GET_SIZE(mro);
1374        for (i = 0; i < n; i++) {
1375            base = PyTuple_GET_ITEM(mro, i);
1376            if (PyClass_Check(base))
1377                dict = ((PyClassObject *)base)->cl_dict;
1378            else {
1379                assert(PyType_Check(base));
1380                dict = ((PyTypeObject *)base)->tp_dict;
1381            }
1382            assert(dict && PyDict_Check(dict));
1383            descr = PyDict_GetItem(dict, name);
1384            if (descr != NULL)
1385                break;
1386        }
1387    }
1388#else
1389    descr = _PyType_Lookup(tp, name);
1390#endif
1391
1392    Py_XINCREF(descr);
1393
1394    f = NULL;
1395    if (descr != NULL &&
1396        PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1397        f = descr->ob_type->tp_descr_get;
1398        if (f != NULL && PyDescr_IsData(descr)) {
1399            res = f(descr, obj, (PyObject *)obj->ob_type);
1400            Py_DECREF(descr);
1401            goto done;
1402        }
1403    }
1404
1405    if (dict == NULL) {
1406        /* Inline _PyObject_GetDictPtr */
1407        dictoffset = tp->tp_dictoffset;
1408        if (dictoffset != 0) {
1409            if (dictoffset < 0) {
1410                Py_ssize_t tsize;
1411                size_t size;
1412
1413                tsize = ((PyVarObject *)obj)->ob_size;
1414                if (tsize < 0)
1415                    tsize = -tsize;
1416                size = _PyObject_VAR_SIZE(tp, tsize);
1417
1418                dictoffset += (long)size;
1419                assert(dictoffset > 0);
1420                assert(dictoffset % SIZEOF_VOID_P == 0);
1421            }
1422            dictptr = (PyObject **) ((char *)obj + dictoffset);
1423            dict = *dictptr;
1424        }
1425    }
1426    if (dict != NULL) {
1427        Py_INCREF(dict);
1428        res = PyDict_GetItem(dict, name);
1429        if (res != NULL) {
1430            Py_INCREF(res);
1431            Py_XDECREF(descr);
1432            Py_DECREF(dict);
1433            goto done;
1434        }
1435        Py_DECREF(dict);
1436    }
1437
1438    if (f != NULL) {
1439        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1440        Py_DECREF(descr);
1441        goto done;
1442    }
1443
1444    if (descr != NULL) {
1445        res = descr;
1446        /* descr was already increfed above */
1447        goto done;
1448    }
1449
1450    PyErr_Format(PyExc_AttributeError,
1451                 "'%.50s' object has no attribute '%.400s'",
1452                 tp->tp_name, PyString_AS_STRING(name));
1453  done:
1454    Py_DECREF(name);
1455    return res;
1456}
1457
1458PyObject *
1459PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1460{
1461    return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1462}
1463
1464int
1465_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1466                                 PyObject *value, PyObject *dict)
1467{
1468    PyTypeObject *tp = Py_TYPE(obj);
1469    PyObject *descr;
1470    descrsetfunc f;
1471    PyObject **dictptr;
1472    int res = -1;
1473
1474    if (!PyString_Check(name)){
1475#ifdef Py_USING_UNICODE
1476        /* The Unicode to string conversion is done here because the
1477           existing tp_setattro slots expect a string object as name
1478           and we wouldn't want to break those. */
1479        if (PyUnicode_Check(name)) {
1480            name = PyUnicode_AsEncodedString(name, NULL, NULL);
1481            if (name == NULL)
1482                return -1;
1483        }
1484        else
1485#endif
1486        {
1487            PyErr_Format(PyExc_TypeError,
1488                         "attribute name must be string, not '%.200s'",
1489                         Py_TYPE(name)->tp_name);
1490            return -1;
1491        }
1492    }
1493    else
1494        Py_INCREF(name);
1495
1496    if (tp->tp_dict == NULL) {
1497        if (PyType_Ready(tp) < 0)
1498            goto done;
1499    }
1500
1501    descr = _PyType_Lookup(tp, name);
1502    f = NULL;
1503    if (descr != NULL &&
1504        PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
1505        f = descr->ob_type->tp_descr_set;
1506        if (f != NULL && PyDescr_IsData(descr)) {
1507            res = f(descr, obj, value);
1508            goto done;
1509        }
1510    }
1511
1512    if (dict == NULL) {
1513        dictptr = _PyObject_GetDictPtr(obj);
1514        if (dictptr != NULL) {
1515            dict = *dictptr;
1516            if (dict == NULL && value != NULL) {
1517                dict = PyDict_New();
1518                if (dict == NULL)
1519                    goto done;
1520                *dictptr = dict;
1521            }
1522        }
1523    }
1524    if (dict != NULL) {
1525        Py_INCREF(dict);
1526        if (value == NULL)
1527            res = PyDict_DelItem(dict, name);
1528        else
1529            res = PyDict_SetItem(dict, name, value);
1530        if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1531            PyErr_SetObject(PyExc_AttributeError, name);
1532        Py_DECREF(dict);
1533        goto done;
1534    }
1535
1536    if (f != NULL) {
1537        res = f(descr, obj, value);
1538        goto done;
1539    }
1540
1541    if (descr == NULL) {
1542        PyErr_Format(PyExc_AttributeError,
1543                     "'%.100s' object has no attribute '%.200s'",
1544                     tp->tp_name, PyString_AS_STRING(name));
1545        goto done;
1546    }
1547
1548    PyErr_Format(PyExc_AttributeError,
1549                 "'%.50s' object attribute '%.400s' is read-only",
1550                 tp->tp_name, PyString_AS_STRING(name));
1551  done:
1552    Py_DECREF(name);
1553    return res;
1554}
1555
1556int
1557PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1558{
1559    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1560}
1561
1562
1563/* Test a value used as condition, e.g., in a for or if statement.
1564   Return -1 if an error occurred */
1565
1566int
1567PyObject_IsTrue(PyObject *v)
1568{
1569    Py_ssize_t res;
1570    if (v == Py_True)
1571        return 1;
1572    if (v == Py_False)
1573        return 0;
1574    if (v == Py_None)
1575        return 0;
1576    else if (v->ob_type->tp_as_number != NULL &&
1577             v->ob_type->tp_as_number->nb_nonzero != NULL)
1578        res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
1579    else if (v->ob_type->tp_as_mapping != NULL &&
1580             v->ob_type->tp_as_mapping->mp_length != NULL)
1581        res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1582    else if (v->ob_type->tp_as_sequence != NULL &&
1583             v->ob_type->tp_as_sequence->sq_length != NULL)
1584        res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1585    else
1586        return 1;
1587    /* if it is negative, it should be either -1 or -2 */
1588    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
1589}
1590
1591/* equivalent of 'not v'
1592   Return -1 if an error occurred */
1593
1594int
1595PyObject_Not(PyObject *v)
1596{
1597    int res;
1598    res = PyObject_IsTrue(v);
1599    if (res < 0)
1600        return res;
1601    return res == 0;
1602}
1603
1604/* Coerce two numeric types to the "larger" one.
1605   Increment the reference count on each argument.
1606   Return value:
1607   -1 if an error occurred;
1608   0 if the coercion succeeded (and then the reference counts are increased);
1609   1 if no coercion is possible (and no error is raised).
1610*/
1611int
1612PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
1613{
1614    register PyObject *v = *pv;
1615    register PyObject *w = *pw;
1616    int res;
1617
1618    /* Shortcut only for old-style types */
1619    if (v->ob_type == w->ob_type &&
1620        !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
1621    {
1622        Py_INCREF(v);
1623        Py_INCREF(w);
1624        return 0;
1625    }
1626    if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
1627        res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
1628        if (res <= 0)
1629            return res;
1630    }
1631    if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
1632        res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
1633        if (res <= 0)
1634            return res;
1635    }
1636    return 1;
1637}
1638
1639/* Coerce two numeric types to the "larger" one.
1640   Increment the reference count on each argument.
1641   Return -1 and raise an exception if no coercion is possible
1642   (and then no reference count is incremented).
1643*/
1644int
1645PyNumber_Coerce(PyObject **pv, PyObject **pw)
1646{
1647    int err = PyNumber_CoerceEx(pv, pw);
1648    if (err <= 0)
1649        return err;
1650    PyErr_SetString(PyExc_TypeError, "number coercion failed");
1651    return -1;
1652}
1653
1654
1655/* Test whether an object can be called */
1656
1657int
1658PyCallable_Check(PyObject *x)
1659{
1660    if (x == NULL)
1661        return 0;
1662    if (PyInstance_Check(x)) {
1663        PyObject *call = PyObject_GetAttrString(x, "__call__");
1664        if (call == NULL) {
1665            PyErr_Clear();
1666            return 0;
1667        }
1668        /* Could test recursively but don't, for fear of endless
1669           recursion if some joker sets self.__call__ = self */
1670        Py_DECREF(call);
1671        return 1;
1672    }
1673    else {
1674        return x->ob_type->tp_call != NULL;
1675    }
1676}
1677
1678/* ------------------------- PyObject_Dir() helpers ------------------------- */
1679
1680/* Helper for PyObject_Dir.
1681   Merge the __dict__ of aclass into dict, and recursively also all
1682   the __dict__s of aclass's base classes.  The order of merging isn't
1683   defined, as it's expected that only the final set of dict keys is
1684   interesting.
1685   Return 0 on success, -1 on error.
1686*/
1687
1688static int
1689merge_class_dict(PyObject* dict, PyObject* aclass)
1690{
1691    PyObject *classdict;
1692    PyObject *bases;
1693
1694    assert(PyDict_Check(dict));
1695    assert(aclass);
1696
1697    /* Merge in the type's dict (if any). */
1698    classdict = PyObject_GetAttrString(aclass, "__dict__");
1699    if (classdict == NULL)
1700        PyErr_Clear();
1701    else {
1702        int status = PyDict_Update(dict, classdict);
1703        Py_DECREF(classdict);
1704        if (status < 0)
1705            return -1;
1706    }
1707
1708    /* Recursively merge in the base types' (if any) dicts. */
1709    bases = PyObject_GetAttrString(aclass, "__bases__");
1710    if (bases == NULL)
1711        PyErr_Clear();
1712    else {
1713        /* We have no guarantee that bases is a real tuple */
1714        Py_ssize_t i, n;
1715        n = PySequence_Size(bases); /* This better be right */
1716        if (n < 0)
1717            PyErr_Clear();
1718        else {
1719            for (i = 0; i < n; i++) {
1720                int status;
1721                PyObject *base = PySequence_GetItem(bases, i);
1722                if (base == NULL) {
1723                    Py_DECREF(bases);
1724                    return -1;
1725                }
1726                status = merge_class_dict(dict, base);
1727                Py_DECREF(base);
1728                if (status < 0) {
1729                    Py_DECREF(bases);
1730                    return -1;
1731                }
1732            }
1733        }
1734        Py_DECREF(bases);
1735    }
1736    return 0;
1737}
1738
1739/* Helper for PyObject_Dir.
1740   If obj has an attr named attrname that's a list, merge its string
1741   elements into keys of dict.
1742   Return 0 on success, -1 on error.  Errors due to not finding the attr,
1743   or the attr not being a list, are suppressed.
1744*/
1745
1746static int
1747merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
1748{
1749    PyObject *list;
1750    int result = 0;
1751
1752    assert(PyDict_Check(dict));
1753    assert(obj);
1754    assert(attrname);
1755
1756    list = PyObject_GetAttrString(obj, attrname);
1757    if (list == NULL)
1758        PyErr_Clear();
1759
1760    else if (PyList_Check(list)) {
1761        int i;
1762        for (i = 0; i < PyList_GET_SIZE(list); ++i) {
1763            PyObject *item = PyList_GET_ITEM(list, i);
1764            if (PyString_Check(item)) {
1765                result = PyDict_SetItem(dict, item, Py_None);
1766                if (result < 0)
1767                    break;
1768            }
1769        }
1770        if (Py_Py3kWarningFlag &&
1771            (strcmp(attrname, "__members__") == 0 ||
1772             strcmp(attrname, "__methods__") == 0)) {
1773            if (PyErr_WarnEx(PyExc_DeprecationWarning,
1774                           "__members__ and __methods__ not "
1775                           "supported in 3.x", 1) < 0) {
1776                Py_XDECREF(list);
1777                return -1;
1778            }
1779        }
1780    }
1781
1782    Py_XDECREF(list);
1783    return result;
1784}
1785
1786/* Helper for PyObject_Dir without arguments: returns the local scope. */
1787static PyObject *
1788_dir_locals(void)
1789{
1790    PyObject *names;
1791    PyObject *locals = PyEval_GetLocals();
1792
1793    if (locals == NULL) {
1794        PyErr_SetString(PyExc_SystemError, "frame does not exist");
1795        return NULL;
1796    }
1797
1798    names = PyMapping_Keys(locals);
1799    if (!names)
1800        return NULL;
1801    if (!PyList_Check(names)) {
1802        PyErr_Format(PyExc_TypeError,
1803            "dir(): expected keys() of locals to be a list, "
1804            "not '%.200s'", Py_TYPE(names)->tp_name);
1805        Py_DECREF(names);
1806        return NULL;
1807    }
1808    /* the locals don't need to be DECREF'd */
1809    return names;
1810}
1811
1812/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
1813   We deliberately don't suck up its __class__, as methods belonging to the
1814   metaclass would probably be more confusing than helpful.
1815*/
1816static PyObject *
1817_specialized_dir_type(PyObject *obj)
1818{
1819    PyObject *result = NULL;
1820    PyObject *dict = PyDict_New();
1821
1822    if (dict != NULL && merge_class_dict(dict, obj) == 0)
1823        result = PyDict_Keys(dict);
1824
1825    Py_XDECREF(dict);
1826    return result;
1827}
1828
1829/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1830static PyObject *
1831_specialized_dir_module(PyObject *obj)
1832{
1833    PyObject *result = NULL;
1834    PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
1835
1836    if (dict != NULL) {
1837        if (PyDict_Check(dict))
1838            result = PyDict_Keys(dict);
1839        else {
1840            char *name = PyModule_GetName(obj);
1841            if (name)
1842                PyErr_Format(PyExc_TypeError,
1843                             "%.200s.__dict__ is not a dictionary",
1844                             name);
1845        }
1846    }
1847
1848    Py_XDECREF(dict);
1849    return result;
1850}
1851
1852/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1853   and recursively up the __class__.__bases__ chain.
1854*/
1855static PyObject *
1856_generic_dir(PyObject *obj)
1857{
1858    PyObject *result = NULL;
1859    PyObject *dict = NULL;
1860    PyObject *itsclass = NULL;
1861
1862    /* Get __dict__ (which may or may not be a real dict...) */
1863    dict = PyObject_GetAttrString(obj, "__dict__");
1864    if (dict == NULL) {
1865        PyErr_Clear();
1866        dict = PyDict_New();
1867    }
1868    else if (!PyDict_Check(dict)) {
1869        Py_DECREF(dict);
1870        dict = PyDict_New();
1871    }
1872    else {
1873        /* Copy __dict__ to avoid mutating it. */
1874        PyObject *temp = PyDict_Copy(dict);
1875        Py_DECREF(dict);
1876        dict = temp;
1877    }
1878
1879    if (dict == NULL)
1880        goto error;
1881
1882    /* Merge in __members__ and __methods__ (if any).
1883     * This is removed in Python 3000. */
1884    if (merge_list_attr(dict, obj, "__members__") < 0)
1885        goto error;
1886    if (merge_list_attr(dict, obj, "__methods__") < 0)
1887        goto error;
1888
1889    /* Merge in attrs reachable from its class. */
1890    itsclass = PyObject_GetAttrString(obj, "__class__");
1891    if (itsclass == NULL)
1892        /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1893                       __class__ exists? */
1894        PyErr_Clear();
1895    else {
1896        if (merge_class_dict(dict, itsclass) != 0)
1897            goto error;
1898    }
1899
1900    result = PyDict_Keys(dict);
1901    /* fall through */
1902error:
1903    Py_XDECREF(itsclass);
1904    Py_XDECREF(dict);
1905    return result;
1906}
1907
1908/* Helper for PyObject_Dir: object introspection.
1909   This calls one of the above specialized versions if no __dir__ method
1910   exists. */
1911static PyObject *
1912_dir_object(PyObject *obj)
1913{
1914    PyObject *result = NULL;
1915    static PyObject *dir_str = NULL;
1916    PyObject *dirfunc;
1917
1918    assert(obj);
1919    if (PyInstance_Check(obj)) {
1920        dirfunc = PyObject_GetAttrString(obj, "__dir__");
1921        if (dirfunc == NULL) {
1922            if (PyErr_ExceptionMatches(PyExc_AttributeError))
1923                PyErr_Clear();
1924            else
1925                return NULL;
1926        }
1927    }
1928    else {
1929        dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str);
1930        if (PyErr_Occurred())
1931            return NULL;
1932    }
1933    if (dirfunc == NULL) {
1934        /* use default implementation */
1935        if (PyModule_Check(obj))
1936            result = _specialized_dir_module(obj);
1937        else if (PyType_Check(obj) || PyClass_Check(obj))
1938            result = _specialized_dir_type(obj);
1939        else
1940            result = _generic_dir(obj);
1941    }
1942    else {
1943        /* use __dir__ */
1944        result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
1945        Py_DECREF(dirfunc);
1946        if (result == NULL)
1947            return NULL;
1948
1949        /* result must be a list */
1950        /* XXX(gbrandl): could also check if all items are strings */
1951        if (!PyList_Check(result)) {
1952            PyErr_Format(PyExc_TypeError,
1953                         "__dir__() must return a list, not %.200s",
1954                         Py_TYPE(result)->tp_name);
1955            Py_DECREF(result);
1956            result = NULL;
1957        }
1958    }
1959
1960    return result;
1961}
1962
1963/* Implementation of dir() -- if obj is NULL, returns the names in the current
1964   (local) scope.  Otherwise, performs introspection of the object: returns a
1965   sorted list of attribute names (supposedly) accessible from the object
1966*/
1967PyObject *
1968PyObject_Dir(PyObject *obj)
1969{
1970    PyObject * result;
1971
1972    if (obj == NULL)
1973        /* no object -- introspect the locals */
1974        result = _dir_locals();
1975    else
1976        /* object -- introspect the object */
1977        result = _dir_object(obj);
1978
1979    assert(result == NULL || PyList_Check(result));
1980
1981    if (result != NULL && PyList_Sort(result) != 0) {
1982        /* sorting the list failed */
1983        Py_DECREF(result);
1984        result = NULL;
1985    }
1986
1987    return result;
1988}
1989
1990/*
1991NoObject is usable as a non-NULL undefined value, used by the macro None.
1992There is (and should be!) no way to create other objects of this type,
1993so there is exactly one (which is indestructible, by the way).
1994(XXX This type and the type of NotImplemented below should be unified.)
1995*/
1996
1997/* ARGSUSED */
1998static PyObject *
1999none_repr(PyObject *op)
2000{
2001    return PyString_FromString("None");
2002}
2003
2004/* ARGUSED */
2005static void
2006none_dealloc(PyObject* ignore)
2007{
2008    /* This should never get called, but we also don't want to SEGV if
2009     * we accidentally decref None out of existence.
2010     */
2011    Py_FatalError("deallocating None");
2012}
2013
2014
2015static PyTypeObject PyNone_Type = {
2016    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2017    "NoneType",
2018    0,
2019    0,
2020    none_dealloc,       /*tp_dealloc*/ /*never called*/
2021    0,                  /*tp_print*/
2022    0,                  /*tp_getattr*/
2023    0,                  /*tp_setattr*/
2024    0,                  /*tp_compare*/
2025    none_repr,          /*tp_repr*/
2026    0,                  /*tp_as_number*/
2027    0,                  /*tp_as_sequence*/
2028    0,                  /*tp_as_mapping*/
2029    (hashfunc)_Py_HashPointer, /*tp_hash */
2030};
2031
2032PyObject _Py_NoneStruct = {
2033  _PyObject_EXTRA_INIT
2034  1, &PyNone_Type
2035};
2036
2037/* NotImplemented is an object that can be used to signal that an
2038   operation is not implemented for the given type combination. */
2039
2040static PyObject *
2041NotImplemented_repr(PyObject *op)
2042{
2043    return PyString_FromString("NotImplemented");
2044}
2045
2046static PyTypeObject PyNotImplemented_Type = {
2047    PyVarObject_HEAD_INIT(&PyType_Type, 0)
2048    "NotImplementedType",
2049    0,
2050    0,
2051    none_dealloc,       /*tp_dealloc*/ /*never called*/
2052    0,                  /*tp_print*/
2053    0,                  /*tp_getattr*/
2054    0,                  /*tp_setattr*/
2055    0,                  /*tp_compare*/
2056    NotImplemented_repr, /*tp_repr*/
2057    0,                  /*tp_as_number*/
2058    0,                  /*tp_as_sequence*/
2059    0,                  /*tp_as_mapping*/
2060    0,                  /*tp_hash */
2061};
2062
2063PyObject _Py_NotImplementedStruct = {
2064    _PyObject_EXTRA_INIT
2065    1, &PyNotImplemented_Type
2066};
2067
2068void
2069_Py_ReadyTypes(void)
2070{
2071    if (PyType_Ready(&PyType_Type) < 0)
2072        Py_FatalError("Can't initialize type type");
2073
2074    if (PyType_Ready(&_PyWeakref_RefType) < 0)
2075        Py_FatalError("Can't initialize weakref type");
2076
2077    if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
2078        Py_FatalError("Can't initialize callable weakref proxy type");
2079
2080    if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
2081        Py_FatalError("Can't initialize weakref proxy type");
2082
2083    if (PyType_Ready(&PyBool_Type) < 0)
2084        Py_FatalError("Can't initialize bool type");
2085
2086    if (PyType_Ready(&PyString_Type) < 0)
2087        Py_FatalError("Can't initialize str type");
2088
2089    if (PyType_Ready(&PyByteArray_Type) < 0)
2090        Py_FatalError("Can't initialize bytearray type");
2091
2092    if (PyType_Ready(&PyList_Type) < 0)
2093        Py_FatalError("Can't initialize list type");
2094
2095    if (PyType_Ready(&PyNone_Type) < 0)
2096        Py_FatalError("Can't initialize None type");
2097
2098    if (PyType_Ready(&PyNotImplemented_Type) < 0)
2099        Py_FatalError("Can't initialize NotImplemented type");
2100
2101    if (PyType_Ready(&PyTraceBack_Type) < 0)
2102        Py_FatalError("Can't initialize traceback type");
2103
2104    if (PyType_Ready(&PySuper_Type) < 0)
2105        Py_FatalError("Can't initialize super type");
2106
2107    if (PyType_Ready(&PyBaseObject_Type) < 0)
2108        Py_FatalError("Can't initialize object type");
2109
2110    if (PyType_Ready(&PyRange_Type) < 0)
2111        Py_FatalError("Can't initialize xrange type");
2112
2113    if (PyType_Ready(&PyDict_Type) < 0)
2114        Py_FatalError("Can't initialize dict type");
2115
2116    if (PyType_Ready(&PySet_Type) < 0)
2117        Py_FatalError("Can't initialize set type");
2118
2119#ifdef Py_USING_UNICODE
2120    if (PyType_Ready(&PyUnicode_Type) < 0)
2121        Py_FatalError("Can't initialize unicode type");
2122#endif
2123
2124    if (PyType_Ready(&PySlice_Type) < 0)
2125        Py_FatalError("Can't initialize slice type");
2126
2127    if (PyType_Ready(&PyStaticMethod_Type) < 0)
2128        Py_FatalError("Can't initialize static method type");
2129
2130#ifndef WITHOUT_COMPLEX
2131    if (PyType_Ready(&PyComplex_Type) < 0)
2132        Py_FatalError("Can't initialize complex type");
2133#endif
2134
2135    if (PyType_Ready(&PyFloat_Type) < 0)
2136        Py_FatalError("Can't initialize float type");
2137
2138    if (PyType_Ready(&PyBuffer_Type) < 0)
2139        Py_FatalError("Can't initialize buffer type");
2140
2141    if (PyType_Ready(&PyLong_Type) < 0)
2142        Py_FatalError("Can't initialize long type");
2143
2144    if (PyType_Ready(&PyInt_Type) < 0)
2145        Py_FatalError("Can't initialize int type");
2146
2147    if (PyType_Ready(&PyFrozenSet_Type) < 0)
2148        Py_FatalError("Can't initialize frozenset type");
2149
2150    if (PyType_Ready(&PyProperty_Type) < 0)
2151        Py_FatalError("Can't initialize property type");
2152
2153    if (PyType_Ready(&PyMemoryView_Type) < 0)
2154        Py_FatalError("Can't initialize memoryview type");
2155
2156    if (PyType_Ready(&PyTuple_Type) < 0)
2157        Py_FatalError("Can't initialize tuple type");
2158
2159    if (PyType_Ready(&PyEnum_Type) < 0)
2160        Py_FatalError("Can't initialize enumerate type");
2161
2162    if (PyType_Ready(&PyReversed_Type) < 0)
2163        Py_FatalError("Can't initialize reversed type");
2164
2165    if (PyType_Ready(&PyCode_Type) < 0)
2166        Py_FatalError("Can't initialize code type");
2167
2168    if (PyType_Ready(&PyFrame_Type) < 0)
2169        Py_FatalError("Can't initialize frame type");
2170
2171    if (PyType_Ready(&PyCFunction_Type) < 0)
2172        Py_FatalError("Can't initialize builtin function type");
2173
2174    if (PyType_Ready(&PyMethod_Type) < 0)
2175        Py_FatalError("Can't initialize method type");
2176
2177    if (PyType_Ready(&PyFunction_Type) < 0)
2178        Py_FatalError("Can't initialize function type");
2179
2180    if (PyType_Ready(&PyClass_Type) < 0)
2181        Py_FatalError("Can't initialize class type");
2182
2183    if (PyType_Ready(&PyDictProxy_Type) < 0)
2184        Py_FatalError("Can't initialize dict proxy type");
2185
2186    if (PyType_Ready(&PyGen_Type) < 0)
2187        Py_FatalError("Can't initialize generator type");
2188
2189    if (PyType_Ready(&PyGetSetDescr_Type) < 0)
2190        Py_FatalError("Can't initialize get-set descriptor type");
2191
2192    if (PyType_Ready(&PyWrapperDescr_Type) < 0)
2193        Py_FatalError("Can't initialize wrapper type");
2194
2195    if (PyType_Ready(&PyInstance_Type) < 0)
2196        Py_FatalError("Can't initialize instance type");
2197
2198    if (PyType_Ready(&PyEllipsis_Type) < 0)
2199        Py_FatalError("Can't initialize ellipsis type");
2200
2201    if (PyType_Ready(&PyMemberDescr_Type) < 0)
2202        Py_FatalError("Can't initialize member descriptor type");
2203
2204    if (PyType_Ready(&PyFile_Type) < 0)
2205        Py_FatalError("Can't initialize file type");
2206
2207    if (PyType_Ready(&PyCapsule_Type) < 0)
2208        Py_FatalError("Can't initialize capsule type");
2209
2210    if (PyType_Ready(&PyCell_Type) < 0)
2211        Py_FatalError("Can't initialize cell type");
2212
2213    if (PyType_Ready(&PyCallIter_Type) < 0)
2214        Py_FatalError("Can't initialize call iter type");
2215
2216    if (PyType_Ready(&PySeqIter_Type) < 0)
2217        Py_FatalError("Can't initialize sequence iterator type");
2218}
2219
2220
2221#ifdef Py_TRACE_REFS
2222
2223void
2224_Py_NewReference(PyObject *op)
2225{
2226    _Py_INC_REFTOTAL;
2227    op->ob_refcnt = 1;
2228    _Py_AddToAllObjects(op, 1);
2229    _Py_INC_TPALLOCS(op);
2230}
2231
2232void
2233_Py_ForgetReference(register PyObject *op)
2234{
2235#ifdef SLOW_UNREF_CHECK
2236    register PyObject *p;
2237#endif
2238    if (op->ob_refcnt < 0)
2239        Py_FatalError("UNREF negative refcnt");
2240    if (op == &refchain ||
2241        op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
2242        Py_FatalError("UNREF invalid object");
2243#ifdef SLOW_UNREF_CHECK
2244    for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
2245        if (p == op)
2246            break;
2247    }
2248    if (p == &refchain) /* Not found */
2249        Py_FatalError("UNREF unknown object");
2250#endif
2251    op->_ob_next->_ob_prev = op->_ob_prev;
2252    op->_ob_prev->_ob_next = op->_ob_next;
2253    op->_ob_next = op->_ob_prev = NULL;
2254    _Py_INC_TPFREES(op);
2255}
2256
2257void
2258_Py_Dealloc(PyObject *op)
2259{
2260    destructor dealloc = Py_TYPE(op)->tp_dealloc;
2261    _Py_ForgetReference(op);
2262    (*dealloc)(op);
2263}
2264
2265/* Print all live objects.  Because PyObject_Print is called, the
2266 * interpreter must be in a healthy state.
2267 */
2268void
2269_Py_PrintReferences(FILE *fp)
2270{
2271    PyObject *op;
2272    fprintf(fp, "Remaining objects:\n");
2273    for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
2274        fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
2275        if (PyObject_Print(op, fp, 0) != 0)
2276            PyErr_Clear();
2277        putc('\n', fp);
2278    }
2279}
2280
2281/* Print the addresses of all live objects.  Unlike _Py_PrintReferences, this
2282 * doesn't make any calls to the Python C API, so is always safe to call.
2283 */
2284void
2285_Py_PrintReferenceAddresses(FILE *fp)
2286{
2287    PyObject *op;
2288    fprintf(fp, "Remaining object addresses:\n");
2289    for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
2290        fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
2291            op->ob_refcnt, Py_TYPE(op)->tp_name);
2292}
2293
2294PyObject *
2295_Py_GetObjects(PyObject *self, PyObject *args)
2296{
2297    int i, n;
2298    PyObject *t = NULL;
2299    PyObject *res, *op;
2300
2301    if (!PyArg_ParseTuple(args, "i|O", &n, &t))
2302        return NULL;
2303    op = refchain._ob_next;
2304    res = PyList_New(0);
2305    if (res == NULL)
2306        return NULL;
2307    for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
2308        while (op == self || op == args || op == res || op == t ||
2309               (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
2310            op = op->_ob_next;
2311            if (op == &refchain)
2312                return res;
2313        }
2314        if (PyList_Append(res, op) < 0) {
2315            Py_DECREF(res);
2316            return NULL;
2317        }
2318        op = op->_ob_next;
2319    }
2320    return res;
2321}
2322
2323#endif
2324
2325
2326/* Hack to force loading of capsule.o */
2327PyTypeObject *_Py_capsule_hack = &PyCapsule_Type;
2328
2329
2330/* Hack to force loading of cobject.o */
2331PyTypeObject *_Py_cobject_hack = &PyCObject_Type;
2332
2333
2334/* Hack to force loading of abstract.o */
2335Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
2336
2337
2338/* Python's malloc wrappers (see pymem.h) */
2339
2340void *
2341PyMem_Malloc(size_t nbytes)
2342{
2343    return PyMem_MALLOC(nbytes);
2344}
2345
2346void *
2347PyMem_Realloc(void *p, size_t nbytes)
2348{
2349    return PyMem_REALLOC(p, nbytes);
2350}
2351
2352void
2353PyMem_Free(void *p)
2354{
2355    PyMem_FREE(p);
2356}
2357
2358
2359/* These methods are used to control infinite recursion in repr, str, print,
2360   etc.  Container objects that may recursively contain themselves,
2361   e.g. builtin dictionaries and lists, should use Py_ReprEnter() and
2362   Py_ReprLeave() to avoid infinite recursion.
2363
2364   Py_ReprEnter() returns 0 the first time it is called for a particular
2365   object and 1 every time thereafter.  It returns -1 if an exception
2366   occurred.  Py_ReprLeave() has no return value.
2367
2368   See dictobject.c and listobject.c for examples of use.
2369*/
2370
2371#define KEY "Py_Repr"
2372
2373int
2374Py_ReprEnter(PyObject *obj)
2375{
2376    PyObject *dict;
2377    PyObject *list;
2378    Py_ssize_t i;
2379
2380    dict = PyThreadState_GetDict();
2381    if (dict == NULL)
2382        return 0;
2383    list = PyDict_GetItemString(dict, KEY);
2384    if (list == NULL) {
2385        list = PyList_New(0);
2386        if (list == NULL)
2387            return -1;
2388        if (PyDict_SetItemString(dict, KEY, list) < 0)
2389            return -1;
2390        Py_DECREF(list);
2391    }
2392    i = PyList_GET_SIZE(list);
2393    while (--i >= 0) {
2394        if (PyList_GET_ITEM(list, i) == obj)
2395            return 1;
2396    }
2397    PyList_Append(list, obj);
2398    return 0;
2399}
2400
2401void
2402Py_ReprLeave(PyObject *obj)
2403{
2404    PyObject *dict;
2405    PyObject *list;
2406    Py_ssize_t i;
2407
2408    dict = PyThreadState_GetDict();
2409    if (dict == NULL)
2410        return;
2411    list = PyDict_GetItemString(dict, KEY);
2412    if (list == NULL || !PyList_Check(list))
2413        return;
2414    i = PyList_GET_SIZE(list);
2415    /* Count backwards because we always expect obj to be list[-1] */
2416    while (--i >= 0) {
2417        if (PyList_GET_ITEM(list, i) == obj) {
2418            PyList_SetSlice(list, i, i + 1, NULL);
2419            break;
2420        }
2421    }
2422}
2423
2424/* Trashcan support. */
2425
2426/* Current call-stack depth of tp_dealloc calls. */
2427int _PyTrash_delete_nesting = 0;
2428
2429/* List of objects that still need to be cleaned up, singly linked via their
2430 * gc headers' gc_prev pointers.
2431 */
2432PyObject *_PyTrash_delete_later = NULL;
2433
2434/* Add op to the _PyTrash_delete_later list.  Called when the current
2435 * call-stack depth gets large.  op must be a currently untracked gc'ed
2436 * object, with refcount 0.  Py_DECREF must already have been called on it.
2437 */
2438void
2439_PyTrash_deposit_object(PyObject *op)
2440{
2441    assert(PyObject_IS_GC(op));
2442    assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2443    assert(op->ob_refcnt == 0);
2444    _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
2445    _PyTrash_delete_later = op;
2446}
2447
2448/* The equivalent API, using per-thread state recursion info */
2449void
2450_PyTrash_thread_deposit_object(PyObject *op)
2451{
2452    PyThreadState *tstate = PyThreadState_GET();
2453    assert(PyObject_IS_GC(op));
2454    assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
2455    assert(op->ob_refcnt == 0);
2456    _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *) tstate->trash_delete_later;
2457    tstate->trash_delete_later = op;
2458}
2459
2460/* Dealloccate all the objects in the _PyTrash_delete_later list.  Called when
2461 * the call-stack unwinds again.
2462 */
2463void
2464_PyTrash_destroy_chain(void)
2465{
2466    while (_PyTrash_delete_later) {
2467        PyObject *op = _PyTrash_delete_later;
2468        destructor dealloc = Py_TYPE(op)->tp_dealloc;
2469
2470        _PyTrash_delete_later =
2471            (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2472
2473        /* Call the deallocator directly.  This used to try to
2474         * fool Py_DECREF into calling it indirectly, but
2475         * Py_DECREF was already called on this object, and in
2476         * assorted non-release builds calling Py_DECREF again ends
2477         * up distorting allocation statistics.
2478         */
2479        assert(op->ob_refcnt == 0);
2480        ++_PyTrash_delete_nesting;
2481        (*dealloc)(op);
2482        --_PyTrash_delete_nesting;
2483    }
2484}
2485
2486/* The equivalent API, using per-thread state recursion info */
2487void
2488_PyTrash_thread_destroy_chain(void)
2489{
2490    PyThreadState *tstate = PyThreadState_GET();
2491    while (tstate->trash_delete_later) {
2492        PyObject *op = tstate->trash_delete_later;
2493        destructor dealloc = Py_TYPE(op)->tp_dealloc;
2494
2495        tstate->trash_delete_later =
2496            (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
2497
2498        /* Call the deallocator directly.  This used to try to
2499         * fool Py_DECREF into calling it indirectly, but
2500         * Py_DECREF was already called on this object, and in
2501         * assorted non-release builds calling Py_DECREF again ends
2502         * up distorting allocation statistics.
2503         */
2504        assert(op->ob_refcnt == 0);
2505        ++tstate->trash_delete_nesting;
2506        (*dealloc)(op);
2507        --tstate->trash_delete_nesting;
2508    }
2509}
2510
2511#ifdef __cplusplus
2512}
2513#endif
2514