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