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