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