object.c revision 4ead7c7be8089de7cab5db7d2a75e6bec5b55f10
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 && !PyUnicode_Check(res)) {
382        PyErr_Format(PyExc_TypeError,
383                     "__repr__ returned non-string (type %.200s)",
384                     res->ob_type->tp_name);
385        Py_DECREF(res);
386        return NULL;
387    }
388    return res;
389}
390
391PyObject *
392PyObject_Str(PyObject *v)
393{
394    PyObject *res;
395    if (PyErr_CheckSignals())
396        return NULL;
397#ifdef USE_STACKCHECK
398    if (PyOS_CheckStack()) {
399        PyErr_SetString(PyExc_MemoryError, "stack overflow");
400        return NULL;
401    }
402#endif
403    if (v == NULL)
404        return PyUnicode_FromString("<NULL>");
405    if (PyUnicode_CheckExact(v)) {
406        if (PyUnicode_READY(v) < 0)
407            return NULL;
408        Py_INCREF(v);
409        return v;
410    }
411    if (Py_TYPE(v)->tp_str == NULL)
412        return PyObject_Repr(v);
413
414    /* It is possible for a type to have a tp_str representation that loops
415       infinitely. */
416    if (Py_EnterRecursiveCall(" while getting the str of an object"))
417        return NULL;
418    res = (*Py_TYPE(v)->tp_str)(v);
419    Py_LeaveRecursiveCall();
420    if (res == NULL)
421        return NULL;
422    if (!PyUnicode_Check(res)) {
423        PyErr_Format(PyExc_TypeError,
424                     "__str__ returned non-string (type %.200s)",
425                     Py_TYPE(res)->tp_name);
426        Py_DECREF(res);
427        return NULL;
428    }
429    if (PyUnicode_READY(res) < 0)
430        return NULL;
431    assert(_PyUnicode_CheckConsistency(res, 1));
432    return res;
433}
434
435PyObject *
436PyObject_ASCII(PyObject *v)
437{
438    PyObject *repr, *ascii, *res;
439
440    repr = PyObject_Repr(v);
441    if (repr == NULL)
442        return NULL;
443
444    /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
445    ascii = _PyUnicode_AsASCIIString(repr, "backslashreplace");
446    Py_DECREF(repr);
447    if (ascii == NULL)
448        return NULL;
449
450    res = PyUnicode_DecodeASCII(
451        PyBytes_AS_STRING(ascii),
452        PyBytes_GET_SIZE(ascii),
453        NULL);
454
455    Py_DECREF(ascii);
456    return res;
457}
458
459PyObject *
460PyObject_Bytes(PyObject *v)
461{
462    PyObject *result, *func;
463    static PyObject *bytesstring = NULL;
464
465    if (v == NULL)
466        return PyBytes_FromString("<NULL>");
467
468    if (PyBytes_CheckExact(v)) {
469        Py_INCREF(v);
470        return v;
471    }
472
473    func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring);
474    if (func != NULL) {
475        result = PyObject_CallFunctionObjArgs(func, NULL);
476        Py_DECREF(func);
477        if (result == NULL)
478            return NULL;
479        if (!PyBytes_Check(result)) {
480            PyErr_Format(PyExc_TypeError,
481                         "__bytes__ returned non-bytes (type %.200s)",
482                         Py_TYPE(result)->tp_name);
483            Py_DECREF(result);
484            return NULL;
485        }
486        return result;
487    }
488    else if (PyErr_Occurred())
489        return NULL;
490    return PyBytes_FromObject(v);
491}
492
493/* For Python 3.0.1 and later, the old three-way comparison has been
494   completely removed in favour of rich comparisons.  PyObject_Compare() and
495   PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
496   The old tp_compare slot has been renamed to tp_reserved, and should no
497   longer be used.  Use tp_richcompare instead.
498
499   See (*) below for practical amendments.
500
501   tp_richcompare gets called with a first argument of the appropriate type
502   and a second object of an arbitrary type.  We never do any kind of
503   coercion.
504
505   The tp_richcompare slot should return an object, as follows:
506
507    NULL if an exception occurred
508    NotImplemented if the requested comparison is not implemented
509    any other false value if the requested comparison is false
510    any other true value if the requested comparison is true
511
512  The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
513  NotImplemented.
514
515  (*) Practical amendments:
516
517  - If rich comparison returns NotImplemented, == and != are decided by
518    comparing the object pointer (i.e. falling back to the base object
519    implementation).
520
521*/
522
523/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
524int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
525
526static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
527
528/* Perform a rich comparison, raising TypeError when the requested comparison
529   operator is not supported. */
530static PyObject *
531do_richcompare(PyObject *v, PyObject *w, int op)
532{
533    richcmpfunc f;
534    PyObject *res;
535    int checked_reverse_op = 0;
536
537    if (v->ob_type != w->ob_type &&
538        PyType_IsSubtype(w->ob_type, v->ob_type) &&
539        (f = w->ob_type->tp_richcompare) != NULL) {
540        checked_reverse_op = 1;
541        res = (*f)(w, v, _Py_SwappedOp[op]);
542        if (res != Py_NotImplemented)
543            return res;
544        Py_DECREF(res);
545    }
546    if ((f = v->ob_type->tp_richcompare) != NULL) {
547        res = (*f)(v, w, op);
548        if (res != Py_NotImplemented)
549            return res;
550        Py_DECREF(res);
551    }
552    if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
553        res = (*f)(w, v, _Py_SwappedOp[op]);
554        if (res != Py_NotImplemented)
555            return res;
556        Py_DECREF(res);
557    }
558    /* If neither object implements it, provide a sensible default
559       for == and !=, but raise an exception for ordering. */
560    switch (op) {
561    case Py_EQ:
562        res = (v == w) ? Py_True : Py_False;
563        break;
564    case Py_NE:
565        res = (v != w) ? Py_True : Py_False;
566        break;
567    default:
568        /* XXX Special-case None so it doesn't show as NoneType() */
569        PyErr_Format(PyExc_TypeError,
570                     "unorderable types: %.100s() %s %.100s()",
571                     v->ob_type->tp_name,
572                     opstrings[op],
573                     w->ob_type->tp_name);
574        return NULL;
575    }
576    Py_INCREF(res);
577    return res;
578}
579
580/* Perform a rich comparison with object result.  This wraps do_richcompare()
581   with a check for NULL arguments and a recursion check. */
582
583PyObject *
584PyObject_RichCompare(PyObject *v, PyObject *w, int op)
585{
586    PyObject *res;
587
588    assert(Py_LT <= op && op <= Py_GE);
589    if (v == NULL || w == NULL) {
590        if (!PyErr_Occurred())
591            PyErr_BadInternalCall();
592        return NULL;
593    }
594    if (Py_EnterRecursiveCall(" in comparison"))
595        return NULL;
596    res = do_richcompare(v, w, op);
597    Py_LeaveRecursiveCall();
598    return res;
599}
600
601/* Perform a rich comparison with integer result.  This wraps
602   PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
603int
604PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
605{
606    PyObject *res;
607    int ok;
608
609    /* Quick result when objects are the same.
610       Guarantees that identity implies equality. */
611    if (v == w) {
612        if (op == Py_EQ)
613            return 1;
614        else if (op == Py_NE)
615            return 0;
616    }
617
618    res = PyObject_RichCompare(v, w, op);
619    if (res == NULL)
620        return -1;
621    if (PyBool_Check(res))
622        ok = (res == Py_True);
623    else
624        ok = PyObject_IsTrue(res);
625    Py_DECREF(res);
626    return ok;
627}
628
629/* Set of hash utility functions to help maintaining the invariant that
630    if a==b then hash(a)==hash(b)
631
632   All the utility functions (_Py_Hash*()) return "-1" to signify an error.
633*/
634
635/* For numeric types, the hash of a number x is based on the reduction
636   of x modulo the prime P = 2**_PyHASH_BITS - 1.  It's designed so that
637   hash(x) == hash(y) whenever x and y are numerically equal, even if
638   x and y have different types.
639
640   A quick summary of the hashing strategy:
641
642   (1) First define the 'reduction of x modulo P' for any rational
643   number x; this is a standard extension of the usual notion of
644   reduction modulo P for integers.  If x == p/q (written in lowest
645   terms), the reduction is interpreted as the reduction of p times
646   the inverse of the reduction of q, all modulo P; if q is exactly
647   divisible by P then define the reduction to be infinity.  So we've
648   got a well-defined map
649
650      reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
651
652   (2) Now for a rational number x, define hash(x) by:
653
654      reduce(x)   if x >= 0
655      -reduce(-x) if x < 0
656
657   If the result of the reduction is infinity (this is impossible for
658   integers, floats and Decimals) then use the predefined hash value
659   _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
660   _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
661   hashes of float and Decimal infinities and nans.
662
663   A selling point for the above strategy is that it makes it possible
664   to compute hashes of decimal and binary floating-point numbers
665   efficiently, even if the exponent of the binary or decimal number
666   is large.  The key point is that
667
668      reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
669
670   provided that {reduce(x), reduce(y)} != {0, infinity}.  The reduction of a
671   binary or decimal float is never infinity, since the denominator is a power
672   of 2 (for binary) or a divisor of a power of 10 (for decimal).  So we have,
673   for nonnegative x,
674
675      reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
676
677      reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
678
679   and reduce(10**e) can be computed efficiently by the usual modular
680   exponentiation algorithm.  For reduce(2**e) it's even better: since
681   P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
682   by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
683
684   */
685
686Py_hash_t
687_Py_HashDouble(double v)
688{
689    int e, sign;
690    double m;
691    Py_uhash_t x, y;
692
693    if (!Py_IS_FINITE(v)) {
694        if (Py_IS_INFINITY(v))
695            return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
696        else
697            return _PyHASH_NAN;
698    }
699
700    m = frexp(v, &e);
701
702    sign = 1;
703    if (m < 0) {
704        sign = -1;
705        m = -m;
706    }
707
708    /* process 28 bits at a time;  this should work well both for binary
709       and hexadecimal floating point. */
710    x = 0;
711    while (m) {
712        x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
713        m *= 268435456.0;  /* 2**28 */
714        e -= 28;
715        y = (Py_uhash_t)m;  /* pull out integer part */
716        m -= y;
717        x += y;
718        if (x >= _PyHASH_MODULUS)
719            x -= _PyHASH_MODULUS;
720    }
721
722    /* adjust for the exponent;  first reduce it modulo _PyHASH_BITS */
723    e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
724    x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
725
726    x = x * sign;
727    if (x == (Py_uhash_t)-1)
728        x = (Py_uhash_t)-2;
729    return (Py_hash_t)x;
730}
731
732Py_hash_t
733_Py_HashPointer(void *p)
734{
735    Py_hash_t x;
736    size_t y = (size_t)p;
737    /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
738       excessive hash collisions for dicts and sets */
739    y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
740    x = (Py_hash_t)y;
741    if (x == -1)
742        x = -2;
743    return x;
744}
745
746Py_hash_t
747PyObject_HashNotImplemented(PyObject *v)
748{
749    PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
750                 Py_TYPE(v)->tp_name);
751    return -1;
752}
753
754Py_hash_t
755PyObject_Hash(PyObject *v)
756{
757    PyTypeObject *tp = Py_TYPE(v);
758    if (tp->tp_hash != NULL)
759        return (*tp->tp_hash)(v);
760    /* To keep to the general practice that inheriting
761     * solely from object in C code should work without
762     * an explicit call to PyType_Ready, we implicitly call
763     * PyType_Ready here and then check the tp_hash slot again
764     */
765    if (tp->tp_dict == NULL) {
766        if (PyType_Ready(tp) < 0)
767            return -1;
768        if (tp->tp_hash != NULL)
769            return (*tp->tp_hash)(v);
770    }
771    /* Otherwise, the object can't be hashed */
772    return PyObject_HashNotImplemented(v);
773}
774
775PyObject *
776PyObject_GetAttrString(PyObject *v, const char *name)
777{
778    PyObject *w, *res;
779
780    if (Py_TYPE(v)->tp_getattr != NULL)
781        return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
782    w = PyUnicode_InternFromString(name);
783    if (w == NULL)
784        return NULL;
785    res = PyObject_GetAttr(v, w);
786    Py_XDECREF(w);
787    return res;
788}
789
790int
791PyObject_HasAttrString(PyObject *v, const char *name)
792{
793    PyObject *res = PyObject_GetAttrString(v, name);
794    if (res != NULL) {
795        Py_DECREF(res);
796        return 1;
797    }
798    PyErr_Clear();
799    return 0;
800}
801
802int
803PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
804{
805    PyObject *s;
806    int res;
807
808    if (Py_TYPE(v)->tp_setattr != NULL)
809        return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
810    s = PyUnicode_InternFromString(name);
811    if (s == NULL)
812        return -1;
813    res = PyObject_SetAttr(v, s, w);
814    Py_XDECREF(s);
815    return res;
816}
817
818PyObject *
819_PyObject_GetAttrId(PyObject *v, _Py_Identifier *name)
820{
821    PyObject *result;
822    PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
823    if (!oname)
824        return NULL;
825    result = PyObject_GetAttr(v, oname);
826    return result;
827}
828
829int
830_PyObject_HasAttrId(PyObject *v, _Py_Identifier *name)
831{
832    int result;
833    PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
834    if (!oname)
835        return -1;
836    result = PyObject_HasAttr(v, oname);
837    return result;
838}
839
840int
841_PyObject_SetAttrId(PyObject *v, _Py_Identifier *name, PyObject *w)
842{
843    int result;
844    PyObject *oname = _PyUnicode_FromId(name); /* borrowed */
845    if (!oname)
846        return -1;
847    result = PyObject_SetAttr(v, oname, w);
848    return result;
849}
850
851PyObject *
852PyObject_GetAttr(PyObject *v, PyObject *name)
853{
854    PyTypeObject *tp = Py_TYPE(v);
855
856    if (!PyUnicode_Check(name)) {
857        PyErr_Format(PyExc_TypeError,
858                     "attribute name must be string, not '%.200s'",
859                     name->ob_type->tp_name);
860        return NULL;
861    }
862    if (tp->tp_getattro != NULL)
863        return (*tp->tp_getattro)(v, name);
864    if (tp->tp_getattr != NULL) {
865        char *name_str = _PyUnicode_AsString(name);
866        if (name_str == NULL)
867            return NULL;
868        return (*tp->tp_getattr)(v, name_str);
869    }
870    PyErr_Format(PyExc_AttributeError,
871                 "'%.50s' object has no attribute '%U'",
872                 tp->tp_name, name);
873    return NULL;
874}
875
876int
877PyObject_HasAttr(PyObject *v, PyObject *name)
878{
879    PyObject *res = PyObject_GetAttr(v, name);
880    if (res != NULL) {
881        Py_DECREF(res);
882        return 1;
883    }
884    PyErr_Clear();
885    return 0;
886}
887
888int
889PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
890{
891    PyTypeObject *tp = Py_TYPE(v);
892    int err;
893
894    if (!PyUnicode_Check(name)) {
895        PyErr_Format(PyExc_TypeError,
896                     "attribute name must be string, not '%.200s'",
897                     name->ob_type->tp_name);
898        return -1;
899    }
900    Py_INCREF(name);
901
902    PyUnicode_InternInPlace(&name);
903    if (tp->tp_setattro != NULL) {
904        err = (*tp->tp_setattro)(v, name, value);
905        Py_DECREF(name);
906        return err;
907    }
908    if (tp->tp_setattr != NULL) {
909        char *name_str = _PyUnicode_AsString(name);
910        if (name_str == NULL)
911            return -1;
912        err = (*tp->tp_setattr)(v, name_str, value);
913        Py_DECREF(name);
914        return err;
915    }
916    Py_DECREF(name);
917    assert(name->ob_refcnt >= 1);
918    if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
919        PyErr_Format(PyExc_TypeError,
920                     "'%.100s' object has no attributes "
921                     "(%s .%U)",
922                     tp->tp_name,
923                     value==NULL ? "del" : "assign to",
924                     name);
925    else
926        PyErr_Format(PyExc_TypeError,
927                     "'%.100s' object has only read-only attributes "
928                     "(%s .%U)",
929                     tp->tp_name,
930                     value==NULL ? "del" : "assign to",
931                     name);
932    return -1;
933}
934
935/* Helper to get a pointer to an object's __dict__ slot, if any */
936
937PyObject **
938_PyObject_GetDictPtr(PyObject *obj)
939{
940    Py_ssize_t dictoffset;
941    PyTypeObject *tp = Py_TYPE(obj);
942
943    dictoffset = tp->tp_dictoffset;
944    if (dictoffset == 0)
945        return NULL;
946    if (dictoffset < 0) {
947        Py_ssize_t tsize;
948        size_t size;
949
950        tsize = ((PyVarObject *)obj)->ob_size;
951        if (tsize < 0)
952            tsize = -tsize;
953        size = _PyObject_VAR_SIZE(tp, tsize);
954
955        dictoffset += (long)size;
956        assert(dictoffset > 0);
957        assert(dictoffset % SIZEOF_VOID_P == 0);
958    }
959    return (PyObject **) ((char *)obj + dictoffset);
960}
961
962PyObject *
963PyObject_SelfIter(PyObject *obj)
964{
965    Py_INCREF(obj);
966    return obj;
967}
968
969/* Helper used when the __next__ method is removed from a type:
970   tp_iternext is never NULL and can be safely called without checking
971   on every iteration.
972 */
973
974PyObject *
975_PyObject_NextNotImplemented(PyObject *self)
976{
977    PyErr_Format(PyExc_TypeError,
978                 "'%.200s' object is not iterable",
979                 Py_TYPE(self)->tp_name);
980    return NULL;
981}
982
983/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
984
985PyObject *
986_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
987{
988    PyTypeObject *tp = Py_TYPE(obj);
989    PyObject *descr = NULL;
990    PyObject *res = NULL;
991    descrgetfunc f;
992    Py_ssize_t dictoffset;
993    PyObject **dictptr;
994
995    if (!PyUnicode_Check(name)){
996        PyErr_Format(PyExc_TypeError,
997                     "attribute name must be string, not '%.200s'",
998                     name->ob_type->tp_name);
999        return NULL;
1000    }
1001    else
1002        Py_INCREF(name);
1003
1004    if (tp->tp_dict == NULL) {
1005        if (PyType_Ready(tp) < 0)
1006            goto done;
1007    }
1008
1009    descr = _PyType_Lookup(tp, name);
1010    Py_XINCREF(descr);
1011
1012    f = NULL;
1013    if (descr != NULL) {
1014        f = descr->ob_type->tp_descr_get;
1015        if (f != NULL && PyDescr_IsData(descr)) {
1016            res = f(descr, obj, (PyObject *)obj->ob_type);
1017            Py_DECREF(descr);
1018            goto done;
1019        }
1020    }
1021
1022    if (dict == NULL) {
1023        /* Inline _PyObject_GetDictPtr */
1024        dictoffset = tp->tp_dictoffset;
1025        if (dictoffset != 0) {
1026            if (dictoffset < 0) {
1027                Py_ssize_t tsize;
1028                size_t size;
1029
1030                tsize = ((PyVarObject *)obj)->ob_size;
1031                if (tsize < 0)
1032                    tsize = -tsize;
1033                size = _PyObject_VAR_SIZE(tp, tsize);
1034
1035                dictoffset += (long)size;
1036                assert(dictoffset > 0);
1037                assert(dictoffset % SIZEOF_VOID_P == 0);
1038            }
1039            dictptr = (PyObject **) ((char *)obj + dictoffset);
1040            dict = *dictptr;
1041        }
1042    }
1043    if (dict != NULL) {
1044        Py_INCREF(dict);
1045        res = PyDict_GetItem(dict, name);
1046        if (res != NULL) {
1047            Py_INCREF(res);
1048            Py_XDECREF(descr);
1049            Py_DECREF(dict);
1050            goto done;
1051        }
1052        Py_DECREF(dict);
1053    }
1054
1055    if (f != NULL) {
1056        res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1057        Py_DECREF(descr);
1058        goto done;
1059    }
1060
1061    if (descr != NULL) {
1062        res = descr;
1063        /* descr was already increfed above */
1064        goto done;
1065    }
1066
1067    PyErr_Format(PyExc_AttributeError,
1068                 "'%.50s' object has no attribute '%U'",
1069                 tp->tp_name, name);
1070  done:
1071    Py_DECREF(name);
1072    return res;
1073}
1074
1075PyObject *
1076PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1077{
1078    return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1079}
1080
1081int
1082_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1083                                 PyObject *value, PyObject *dict)
1084{
1085    PyTypeObject *tp = Py_TYPE(obj);
1086    PyObject *descr;
1087    descrsetfunc f;
1088    PyObject **dictptr;
1089    int res = -1;
1090
1091    if (!PyUnicode_Check(name)){
1092        PyErr_Format(PyExc_TypeError,
1093                     "attribute name must be string, not '%.200s'",
1094                     name->ob_type->tp_name);
1095        return -1;
1096    }
1097    else
1098        Py_INCREF(name);
1099
1100    if (tp->tp_dict == NULL) {
1101        if (PyType_Ready(tp) < 0)
1102            goto done;
1103    }
1104
1105    descr = _PyType_Lookup(tp, name);
1106    f = NULL;
1107    if (descr != NULL) {
1108        f = descr->ob_type->tp_descr_set;
1109        if (f != NULL && PyDescr_IsData(descr)) {
1110            res = f(descr, obj, value);
1111            goto done;
1112        }
1113    }
1114
1115    if (dict == NULL) {
1116        dictptr = _PyObject_GetDictPtr(obj);
1117        if (dictptr != NULL) {
1118            dict = *dictptr;
1119            if (dict == NULL && value != NULL) {
1120                dict = PyDict_New();
1121                if (dict == NULL)
1122                    goto done;
1123                *dictptr = dict;
1124            }
1125        }
1126    }
1127    if (dict != NULL) {
1128        Py_INCREF(dict);
1129        if (value == NULL)
1130            res = PyDict_DelItem(dict, name);
1131        else
1132            res = PyDict_SetItem(dict, name, value);
1133        if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1134            PyErr_SetObject(PyExc_AttributeError, name);
1135        Py_DECREF(dict);
1136        goto done;
1137    }
1138
1139    if (f != NULL) {
1140        res = f(descr, obj, value);
1141        goto done;
1142    }
1143
1144    if (descr == NULL) {
1145        PyErr_Format(PyExc_AttributeError,
1146                     "'%.100s' object has no attribute '%U'",
1147                     tp->tp_name, name);
1148        goto done;
1149    }
1150
1151    PyErr_Format(PyExc_AttributeError,
1152                 "'%.50s' object attribute '%U' is read-only",
1153                 tp->tp_name, name);
1154  done:
1155    Py_DECREF(name);
1156    return res;
1157}
1158
1159int
1160PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1161{
1162    return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1163}
1164
1165
1166/* Test a value used as condition, e.g., in a for or if statement.
1167   Return -1 if an error occurred */
1168
1169int
1170PyObject_IsTrue(PyObject *v)
1171{
1172    Py_ssize_t res;
1173    if (v == Py_True)
1174        return 1;
1175    if (v == Py_False)
1176        return 0;
1177    if (v == Py_None)
1178        return 0;
1179    else if (v->ob_type->tp_as_number != NULL &&
1180             v->ob_type->tp_as_number->nb_bool != NULL)
1181        res = (*v->ob_type->tp_as_number->nb_bool)(v);
1182    else if (v->ob_type->tp_as_mapping != NULL &&
1183             v->ob_type->tp_as_mapping->mp_length != NULL)
1184        res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1185    else if (v->ob_type->tp_as_sequence != NULL &&
1186             v->ob_type->tp_as_sequence->sq_length != NULL)
1187        res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1188    else
1189        return 1;
1190    /* if it is negative, it should be either -1 or -2 */
1191    return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
1192}
1193
1194/* equivalent of 'not v'
1195   Return -1 if an error occurred */
1196
1197int
1198PyObject_Not(PyObject *v)
1199{
1200    int res;
1201    res = PyObject_IsTrue(v);
1202    if (res < 0)
1203        return res;
1204    return res == 0;
1205}
1206
1207/* Test whether an object can be called */
1208
1209int
1210PyCallable_Check(PyObject *x)
1211{
1212    if (x == NULL)
1213        return 0;
1214    return x->ob_type->tp_call != NULL;
1215}
1216
1217
1218/* Helper for PyObject_Dir without arguments: returns the local scope. */
1219static PyObject *
1220_dir_locals(void)
1221{
1222    PyObject *names;
1223    PyObject *locals = PyEval_GetLocals();
1224
1225    if (locals == NULL) {
1226        PyErr_SetString(PyExc_SystemError, "frame does not exist");
1227        return NULL;
1228    }
1229
1230    names = PyMapping_Keys(locals);
1231    if (!names)
1232        return NULL;
1233    if (!PyList_Check(names)) {
1234        PyErr_Format(PyExc_TypeError,
1235            "dir(): expected keys() of locals to be a list, "
1236            "not '%.200s'", Py_TYPE(names)->tp_name);
1237        Py_DECREF(names);
1238        return NULL;
1239    }
1240    if (PyList_Sort(names)) {
1241        Py_DECREF(names);
1242        return NULL;
1243    }
1244    /* the locals don't need to be DECREF'd */
1245    return names;
1246}
1247
1248/* Helper for PyObject_Dir: object introspection. */
1249static PyObject *
1250_dir_object(PyObject *obj)
1251{
1252    PyObject *result, *sorted;
1253    static PyObject *dir_str = NULL;
1254    PyObject *dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str);
1255
1256    assert(obj);
1257    if (dirfunc == NULL) {
1258        if (!PyErr_Occurred())
1259            PyErr_SetString(PyExc_TypeError, "object does not provide __dir__");
1260        return NULL;
1261    }
1262    /* use __dir__ */
1263    result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
1264    Py_DECREF(dirfunc);
1265    if (result == NULL)
1266        return NULL;
1267    /* return sorted(result) */
1268    sorted = PySequence_List(result);
1269    Py_DECREF(result);
1270    if (sorted == NULL)
1271        return NULL;
1272    if (PyList_Sort(sorted)) {
1273        Py_DECREF(sorted);
1274        return NULL;
1275    }
1276    return sorted;
1277}
1278
1279/* Implementation of dir() -- if obj is NULL, returns the names in the current
1280   (local) scope.  Otherwise, performs introspection of the object: returns a
1281   sorted list of attribute names (supposedly) accessible from the object
1282*/
1283PyObject *
1284PyObject_Dir(PyObject *obj)
1285{
1286    return (obj == NULL) ? _dir_locals() : _dir_object(obj);
1287}
1288
1289/*
1290None is a non-NULL undefined value.
1291There is (and should be!) no way to create other objects of this type,
1292so there is exactly one (which is indestructible, by the way).
1293*/
1294
1295/* ARGSUSED */
1296static PyObject *
1297none_repr(PyObject *op)
1298{
1299    return PyUnicode_FromString("None");
1300}
1301
1302/* ARGUSED */
1303static void
1304none_dealloc(PyObject* ignore)
1305{
1306    /* This should never get called, but we also don't want to SEGV if
1307     * we accidentally decref None out of existence.
1308     */
1309    Py_FatalError("deallocating None");
1310}
1311
1312static PyObject *
1313none_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1314{
1315    if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1316        PyErr_SetString(PyExc_TypeError, "NoneType takes no arguments");
1317        return NULL;
1318    }
1319    Py_RETURN_NONE;
1320}
1321
1322static int
1323none_bool(PyObject *v)
1324{
1325    return 0;
1326}
1327
1328static PyNumberMethods none_as_number = {
1329    0,                          /* nb_add */
1330    0,                          /* nb_subtract */
1331    0,                          /* nb_multiply */
1332    0,                          /* nb_remainder */
1333    0,                          /* nb_divmod */
1334    0,                          /* nb_power */
1335    0,                          /* nb_negative */
1336    0,                          /* nb_positive */
1337    0,                          /* nb_absolute */
1338    (inquiry)none_bool,         /* nb_bool */
1339    0,                          /* nb_invert */
1340    0,                          /* nb_lshift */
1341    0,                          /* nb_rshift */
1342    0,                          /* nb_and */
1343    0,                          /* nb_xor */
1344    0,                          /* nb_or */
1345    0,                          /* nb_int */
1346    0,                          /* nb_reserved */
1347    0,                          /* nb_float */
1348    0,                          /* nb_inplace_add */
1349    0,                          /* nb_inplace_subtract */
1350    0,                          /* nb_inplace_multiply */
1351    0,                          /* nb_inplace_remainder */
1352    0,                          /* nb_inplace_power */
1353    0,                          /* nb_inplace_lshift */
1354    0,                          /* nb_inplace_rshift */
1355    0,                          /* nb_inplace_and */
1356    0,                          /* nb_inplace_xor */
1357    0,                          /* nb_inplace_or */
1358    0,                          /* nb_floor_divide */
1359    0,                          /* nb_true_divide */
1360    0,                          /* nb_inplace_floor_divide */
1361    0,                          /* nb_inplace_true_divide */
1362    0,                          /* nb_index */
1363};
1364
1365static PyTypeObject PyNone_Type = {
1366    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1367    "NoneType",
1368    0,
1369    0,
1370    none_dealloc,       /*tp_dealloc*/ /*never called*/
1371    0,                  /*tp_print*/
1372    0,                  /*tp_getattr*/
1373    0,                  /*tp_setattr*/
1374    0,                  /*tp_reserved*/
1375    none_repr,          /*tp_repr*/
1376    &none_as_number,    /*tp_as_number*/
1377    0,                  /*tp_as_sequence*/
1378    0,                  /*tp_as_mapping*/
1379    0,                  /*tp_hash */
1380    0,                  /*tp_call */
1381    0,                  /*tp_str */
1382    0,                  /*tp_getattro */
1383    0,                  /*tp_setattro */
1384    0,                  /*tp_as_buffer */
1385    Py_TPFLAGS_DEFAULT, /*tp_flags */
1386    0,                  /*tp_doc */
1387    0,                  /*tp_traverse */
1388    0,                  /*tp_clear */
1389    0,                  /*tp_richcompare */
1390    0,                  /*tp_weaklistoffset */
1391    0,                  /*tp_iter */
1392    0,                  /*tp_iternext */
1393    0,                  /*tp_methods */
1394    0,                  /*tp_members */
1395    0,                  /*tp_getset */
1396    0,                  /*tp_base */
1397    0,                  /*tp_dict */
1398    0,                  /*tp_descr_get */
1399    0,                  /*tp_descr_set */
1400    0,                  /*tp_dictoffset */
1401    0,                  /*tp_init */
1402    0,                  /*tp_alloc */
1403    none_new,           /*tp_new */
1404};
1405
1406PyObject _Py_NoneStruct = {
1407  _PyObject_EXTRA_INIT
1408  1, &PyNone_Type
1409};
1410
1411/* NotImplemented is an object that can be used to signal that an
1412   operation is not implemented for the given type combination. */
1413
1414static PyObject *
1415NotImplemented_repr(PyObject *op)
1416{
1417    return PyUnicode_FromString("NotImplemented");
1418}
1419
1420static PyObject *
1421notimplemented_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
1422{
1423    if (PyTuple_GET_SIZE(args) || (kwargs && PyDict_Size(kwargs))) {
1424        PyErr_SetString(PyExc_TypeError, "NotImplementedType takes no arguments");
1425        return NULL;
1426    }
1427    Py_RETURN_NOTIMPLEMENTED;
1428}
1429
1430static PyTypeObject PyNotImplemented_Type = {
1431    PyVarObject_HEAD_INIT(&PyType_Type, 0)
1432    "NotImplementedType",
1433    0,
1434    0,
1435    none_dealloc,       /*tp_dealloc*/ /*never called*/
1436    0,                  /*tp_print*/
1437    0,                  /*tp_getattr*/
1438    0,                  /*tp_setattr*/
1439    0,                  /*tp_reserved*/
1440    NotImplemented_repr, /*tp_repr*/
1441    0,                  /*tp_as_number*/
1442    0,                  /*tp_as_sequence*/
1443    0,                  /*tp_as_mapping*/
1444    0,                  /*tp_hash */
1445    0,                  /*tp_call */
1446    0,                  /*tp_str */
1447    0,                  /*tp_getattro */
1448    0,                  /*tp_setattro */
1449    0,                  /*tp_as_buffer */
1450    Py_TPFLAGS_DEFAULT, /*tp_flags */
1451    0,                  /*tp_doc */
1452    0,                  /*tp_traverse */
1453    0,                  /*tp_clear */
1454    0,                  /*tp_richcompare */
1455    0,                  /*tp_weaklistoffset */
1456    0,                  /*tp_iter */
1457    0,                  /*tp_iternext */
1458    0,                  /*tp_methods */
1459    0,                  /*tp_members */
1460    0,                  /*tp_getset */
1461    0,                  /*tp_base */
1462    0,                  /*tp_dict */
1463    0,                  /*tp_descr_get */
1464    0,                  /*tp_descr_set */
1465    0,                  /*tp_dictoffset */
1466    0,                  /*tp_init */
1467    0,                  /*tp_alloc */
1468    notimplemented_new, /*tp_new */
1469};
1470
1471PyObject _Py_NotImplementedStruct = {
1472    _PyObject_EXTRA_INIT
1473    1, &PyNotImplemented_Type
1474};
1475
1476void
1477_Py_ReadyTypes(void)
1478{
1479    if (PyType_Ready(&PyType_Type) < 0)
1480        Py_FatalError("Can't initialize type type");
1481
1482    if (PyType_Ready(&_PyWeakref_RefType) < 0)
1483        Py_FatalError("Can't initialize weakref type");
1484
1485    if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1486        Py_FatalError("Can't initialize callable weakref proxy type");
1487
1488    if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1489        Py_FatalError("Can't initialize weakref proxy type");
1490
1491    if (PyType_Ready(&PyBool_Type) < 0)
1492        Py_FatalError("Can't initialize bool type");
1493
1494    if (PyType_Ready(&PyByteArray_Type) < 0)
1495        Py_FatalError("Can't initialize bytearray type");
1496
1497    if (PyType_Ready(&PyBytes_Type) < 0)
1498        Py_FatalError("Can't initialize 'str'");
1499
1500    if (PyType_Ready(&PyList_Type) < 0)
1501        Py_FatalError("Can't initialize list type");
1502
1503    if (PyType_Ready(&PyNone_Type) < 0)
1504        Py_FatalError("Can't initialize None type");
1505
1506    if (PyType_Ready(&PyNotImplemented_Type) < 0)
1507        Py_FatalError("Can't initialize NotImplemented type");
1508
1509    if (PyType_Ready(&PyTraceBack_Type) < 0)
1510        Py_FatalError("Can't initialize traceback type");
1511
1512    if (PyType_Ready(&PySuper_Type) < 0)
1513        Py_FatalError("Can't initialize super type");
1514
1515    if (PyType_Ready(&PyBaseObject_Type) < 0)
1516        Py_FatalError("Can't initialize object type");
1517
1518    if (PyType_Ready(&PyRange_Type) < 0)
1519        Py_FatalError("Can't initialize range type");
1520
1521    if (PyType_Ready(&PyDict_Type) < 0)
1522        Py_FatalError("Can't initialize dict type");
1523
1524    if (PyType_Ready(&PySet_Type) < 0)
1525        Py_FatalError("Can't initialize set type");
1526
1527    if (PyType_Ready(&PyUnicode_Type) < 0)
1528        Py_FatalError("Can't initialize str type");
1529
1530    if (PyType_Ready(&PySlice_Type) < 0)
1531        Py_FatalError("Can't initialize slice type");
1532
1533    if (PyType_Ready(&PyStaticMethod_Type) < 0)
1534        Py_FatalError("Can't initialize static method type");
1535
1536    if (PyType_Ready(&PyComplex_Type) < 0)
1537        Py_FatalError("Can't initialize complex type");
1538
1539    if (PyType_Ready(&PyFloat_Type) < 0)
1540        Py_FatalError("Can't initialize float type");
1541
1542    if (PyType_Ready(&PyLong_Type) < 0)
1543        Py_FatalError("Can't initialize int type");
1544
1545    if (PyType_Ready(&PyFrozenSet_Type) < 0)
1546        Py_FatalError("Can't initialize frozenset type");
1547
1548    if (PyType_Ready(&PyProperty_Type) < 0)
1549        Py_FatalError("Can't initialize property type");
1550
1551    if (PyType_Ready(&PyMemoryView_Type) < 0)
1552        Py_FatalError("Can't initialize memoryview type");
1553
1554    if (PyType_Ready(&PyTuple_Type) < 0)
1555        Py_FatalError("Can't initialize tuple type");
1556
1557    if (PyType_Ready(&PyEnum_Type) < 0)
1558        Py_FatalError("Can't initialize enumerate type");
1559
1560    if (PyType_Ready(&PyReversed_Type) < 0)
1561        Py_FatalError("Can't initialize reversed type");
1562
1563    if (PyType_Ready(&PyStdPrinter_Type) < 0)
1564        Py_FatalError("Can't initialize StdPrinter");
1565
1566    if (PyType_Ready(&PyCode_Type) < 0)
1567        Py_FatalError("Can't initialize code type");
1568
1569    if (PyType_Ready(&PyFrame_Type) < 0)
1570        Py_FatalError("Can't initialize frame type");
1571
1572    if (PyType_Ready(&PyCFunction_Type) < 0)
1573        Py_FatalError("Can't initialize builtin function type");
1574
1575    if (PyType_Ready(&PyMethod_Type) < 0)
1576        Py_FatalError("Can't initialize method type");
1577
1578    if (PyType_Ready(&PyFunction_Type) < 0)
1579        Py_FatalError("Can't initialize function type");
1580
1581    if (PyType_Ready(&PyDictProxy_Type) < 0)
1582        Py_FatalError("Can't initialize dict proxy type");
1583
1584    if (PyType_Ready(&PyGen_Type) < 0)
1585        Py_FatalError("Can't initialize generator type");
1586
1587    if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1588        Py_FatalError("Can't initialize get-set descriptor type");
1589
1590    if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1591        Py_FatalError("Can't initialize wrapper type");
1592
1593    if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1594        Py_FatalError("Can't initialize method wrapper type");
1595
1596    if (PyType_Ready(&PyEllipsis_Type) < 0)
1597        Py_FatalError("Can't initialize ellipsis type");
1598
1599    if (PyType_Ready(&PyMemberDescr_Type) < 0)
1600        Py_FatalError("Can't initialize member descriptor type");
1601
1602    if (PyType_Ready(&PyFilter_Type) < 0)
1603        Py_FatalError("Can't initialize filter type");
1604
1605    if (PyType_Ready(&PyMap_Type) < 0)
1606        Py_FatalError("Can't initialize map type");
1607
1608    if (PyType_Ready(&PyZip_Type) < 0)
1609        Py_FatalError("Can't initialize zip type");
1610}
1611
1612
1613#ifdef Py_TRACE_REFS
1614
1615void
1616_Py_NewReference(PyObject *op)
1617{
1618    _Py_INC_REFTOTAL;
1619    op->ob_refcnt = 1;
1620    _Py_AddToAllObjects(op, 1);
1621    _Py_INC_TPALLOCS(op);
1622}
1623
1624void
1625_Py_ForgetReference(register PyObject *op)
1626{
1627#ifdef SLOW_UNREF_CHECK
1628    register PyObject *p;
1629#endif
1630    if (op->ob_refcnt < 0)
1631        Py_FatalError("UNREF negative refcnt");
1632    if (op == &refchain ||
1633        op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1634        fprintf(stderr, "* ob\n");
1635        _PyObject_Dump(op);
1636        fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1637        _PyObject_Dump(op->_ob_prev->_ob_next);
1638        fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1639        _PyObject_Dump(op->_ob_next->_ob_prev);
1640        Py_FatalError("UNREF invalid object");
1641    }
1642#ifdef SLOW_UNREF_CHECK
1643    for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1644        if (p == op)
1645            break;
1646    }
1647    if (p == &refchain) /* Not found */
1648        Py_FatalError("UNREF unknown object");
1649#endif
1650    op->_ob_next->_ob_prev = op->_ob_prev;
1651    op->_ob_prev->_ob_next = op->_ob_next;
1652    op->_ob_next = op->_ob_prev = NULL;
1653    _Py_INC_TPFREES(op);
1654}
1655
1656void
1657_Py_Dealloc(PyObject *op)
1658{
1659    destructor dealloc = Py_TYPE(op)->tp_dealloc;
1660    _Py_ForgetReference(op);
1661    (*dealloc)(op);
1662}
1663
1664/* Print all live objects.  Because PyObject_Print is called, the
1665 * interpreter must be in a healthy state.
1666 */
1667void
1668_Py_PrintReferences(FILE *fp)
1669{
1670    PyObject *op;
1671    fprintf(fp, "Remaining objects:\n");
1672    for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1673        fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1674        if (PyObject_Print(op, fp, 0) != 0)
1675            PyErr_Clear();
1676        putc('\n', fp);
1677    }
1678}
1679
1680/* Print the addresses of all live objects.  Unlike _Py_PrintReferences, this
1681 * doesn't make any calls to the Python C API, so is always safe to call.
1682 */
1683void
1684_Py_PrintReferenceAddresses(FILE *fp)
1685{
1686    PyObject *op;
1687    fprintf(fp, "Remaining object addresses:\n");
1688    for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1689        fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1690            op->ob_refcnt, Py_TYPE(op)->tp_name);
1691}
1692
1693PyObject *
1694_Py_GetObjects(PyObject *self, PyObject *args)
1695{
1696    int i, n;
1697    PyObject *t = NULL;
1698    PyObject *res, *op;
1699
1700    if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1701        return NULL;
1702    op = refchain._ob_next;
1703    res = PyList_New(0);
1704    if (res == NULL)
1705        return NULL;
1706    for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1707        while (op == self || op == args || op == res || op == t ||
1708               (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1709            op = op->_ob_next;
1710            if (op == &refchain)
1711                return res;
1712        }
1713        if (PyList_Append(res, op) < 0) {
1714            Py_DECREF(res);
1715            return NULL;
1716        }
1717        op = op->_ob_next;
1718    }
1719    return res;
1720}
1721
1722#endif
1723
1724/* Hack to force loading of pycapsule.o */
1725PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1726
1727
1728/* Hack to force loading of abstract.o */
1729Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
1730
1731
1732/* Python's malloc wrappers (see pymem.h) */
1733
1734void *
1735PyMem_Malloc(size_t nbytes)
1736{
1737    return PyMem_MALLOC(nbytes);
1738}
1739
1740void *
1741PyMem_Realloc(void *p, size_t nbytes)
1742{
1743    return PyMem_REALLOC(p, nbytes);
1744}
1745
1746void
1747PyMem_Free(void *p)
1748{
1749    PyMem_FREE(p);
1750}
1751
1752
1753/* These methods are used to control infinite recursion in repr, str, print,
1754   etc.  Container objects that may recursively contain themselves,
1755   e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1756   Py_ReprLeave() to avoid infinite recursion.
1757
1758   Py_ReprEnter() returns 0 the first time it is called for a particular
1759   object and 1 every time thereafter.  It returns -1 if an exception
1760   occurred.  Py_ReprLeave() has no return value.
1761
1762   See dictobject.c and listobject.c for examples of use.
1763*/
1764
1765#define KEY "Py_Repr"
1766
1767int
1768Py_ReprEnter(PyObject *obj)
1769{
1770    PyObject *dict;
1771    PyObject *list;
1772    Py_ssize_t i;
1773
1774    dict = PyThreadState_GetDict();
1775    if (dict == NULL)
1776        return 0;
1777    list = PyDict_GetItemString(dict, KEY);
1778    if (list == NULL) {
1779        list = PyList_New(0);
1780        if (list == NULL)
1781            return -1;
1782        if (PyDict_SetItemString(dict, KEY, list) < 0)
1783            return -1;
1784        Py_DECREF(list);
1785    }
1786    i = PyList_GET_SIZE(list);
1787    while (--i >= 0) {
1788        if (PyList_GET_ITEM(list, i) == obj)
1789            return 1;
1790    }
1791    PyList_Append(list, obj);
1792    return 0;
1793}
1794
1795void
1796Py_ReprLeave(PyObject *obj)
1797{
1798    PyObject *dict;
1799    PyObject *list;
1800    Py_ssize_t i;
1801
1802    dict = PyThreadState_GetDict();
1803    if (dict == NULL)
1804        return;
1805    list = PyDict_GetItemString(dict, KEY);
1806    if (list == NULL || !PyList_Check(list))
1807        return;
1808    i = PyList_GET_SIZE(list);
1809    /* Count backwards because we always expect obj to be list[-1] */
1810    while (--i >= 0) {
1811        if (PyList_GET_ITEM(list, i) == obj) {
1812            PyList_SetSlice(list, i, i + 1, NULL);
1813            break;
1814        }
1815    }
1816}
1817
1818/* Trashcan support. */
1819
1820/* Current call-stack depth of tp_dealloc calls. */
1821int _PyTrash_delete_nesting = 0;
1822
1823/* List of objects that still need to be cleaned up, singly linked via their
1824 * gc headers' gc_prev pointers.
1825 */
1826PyObject *_PyTrash_delete_later = NULL;
1827
1828/* Add op to the _PyTrash_delete_later list.  Called when the current
1829 * call-stack depth gets large.  op must be a currently untracked gc'ed
1830 * object, with refcount 0.  Py_DECREF must already have been called on it.
1831 */
1832void
1833_PyTrash_deposit_object(PyObject *op)
1834{
1835    assert(PyObject_IS_GC(op));
1836    assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1837    assert(op->ob_refcnt == 0);
1838    _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1839    _PyTrash_delete_later = op;
1840}
1841
1842/* Dealloccate all the objects in the _PyTrash_delete_later list.  Called when
1843 * the call-stack unwinds again.
1844 */
1845void
1846_PyTrash_destroy_chain(void)
1847{
1848    while (_PyTrash_delete_later) {
1849        PyObject *op = _PyTrash_delete_later;
1850        destructor dealloc = Py_TYPE(op)->tp_dealloc;
1851
1852        _PyTrash_delete_later =
1853            (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
1854
1855        /* Call the deallocator directly.  This used to try to
1856         * fool Py_DECREF into calling it indirectly, but
1857         * Py_DECREF was already called on this object, and in
1858         * assorted non-release builds calling Py_DECREF again ends
1859         * up distorting allocation statistics.
1860         */
1861        assert(op->ob_refcnt == 0);
1862        ++_PyTrash_delete_nesting;
1863        (*dealloc)(op);
1864        --_PyTrash_delete_nesting;
1865    }
1866}
1867
1868#ifndef Py_TRACE_REFS
1869/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
1870   Define this here, so we can undefine the macro. */
1871#undef _Py_Dealloc
1872PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
1873void
1874_Py_Dealloc(PyObject *op)
1875{
1876    _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
1877    (*Py_TYPE(op)->tp_dealloc)(op);
1878}
1879#endif
1880
1881#ifdef __cplusplus
1882}
1883#endif
1884