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