blob: 17e5069ef513943c35828a0b27c357bad3cb8062 [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Generic object operations; and implementation of None (NoObject) */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossumc0b618a1997-05-02 03:12:38 +00004#include "Python.h"
Benjamin Petersonfd838e62009-04-20 02:09:13 +00005#include "frameobject.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00006
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00007#ifdef __cplusplus
8extern "C" {
9#endif
10
Tim Peters34592512002-07-11 06:23:50 +000011#ifdef Py_REF_DEBUG
Neal Norwitz84632ee2006-03-04 20:00:59 +000012Py_ssize_t _Py_RefTotal;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000013
14Py_ssize_t
15_Py_GetRefTotal(void)
16{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000017 PyObject *o;
18 Py_ssize_t total = _Py_RefTotal;
19 /* ignore the references to the dummy object of the dicts and sets
20 because they are not reliable and not useful (now that the
21 hash table code is well-tested) */
22 o = _PyDict_Dummy();
23 if (o != NULL)
24 total -= o->ob_refcnt;
25 o = _PySet_Dummy();
26 if (o != NULL)
27 total -= o->ob_refcnt;
28 return total;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000029}
30#endif /* Py_REF_DEBUG */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000031
Mark Hammonda2905272002-07-29 13:42:14 +000032int Py_DivisionWarningFlag;
Guido van Rossum393661d2001-08-31 17:40:15 +000033
Guido van Rossum3f5da241990-12-20 15:06:42 +000034/* Object allocation routines used by NEWOBJ and NEWVAROBJ macros.
35 These are used by the individual routines for object creation.
36 Do not call them otherwise, they do not initialize the object! */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000037
Tim Peters78be7992003-03-23 02:51:01 +000038#ifdef Py_TRACE_REFS
Tim Peters7571a0f2003-03-23 17:52:28 +000039/* Head of circular doubly-linked list of all objects. These are linked
40 * together via the _ob_prev and _ob_next members of a PyObject, which
41 * exist only in a Py_TRACE_REFS build.
42 */
Tim Peters78be7992003-03-23 02:51:01 +000043static PyObject refchain = {&refchain, &refchain};
Tim Peters36eb4df2003-03-23 03:33:13 +000044
Tim Peters7571a0f2003-03-23 17:52:28 +000045/* Insert op at the front of the list of all objects. If force is true,
46 * op is added even if _ob_prev and _ob_next are non-NULL already. If
47 * force is false amd _ob_prev or _ob_next are non-NULL, do nothing.
48 * force should be true if and only if op points to freshly allocated,
49 * uninitialized memory, or you've unlinked op from the list and are
Tim Peters51f8d382003-03-23 18:06:08 +000050 * relinking it into the front.
Tim Peters7571a0f2003-03-23 17:52:28 +000051 * Note that objects are normally added to the list via _Py_NewReference,
52 * which is called by PyObject_Init. Not all objects are initialized that
53 * way, though; exceptions include statically allocated type objects, and
54 * statically allocated singletons (like Py_True and Py_None).
55 */
Tim Peters36eb4df2003-03-23 03:33:13 +000056void
Tim Peters7571a0f2003-03-23 17:52:28 +000057_Py_AddToAllObjects(PyObject *op, int force)
Tim Peters36eb4df2003-03-23 03:33:13 +000058{
Tim Peters7571a0f2003-03-23 17:52:28 +000059#ifdef Py_DEBUG
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000060 if (!force) {
61 /* If it's initialized memory, op must be in or out of
62 * the list unambiguously.
63 */
64 assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
65 }
Tim Peters78be7992003-03-23 02:51:01 +000066#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000067 if (force || op->_ob_prev == NULL) {
68 op->_ob_next = refchain._ob_next;
69 op->_ob_prev = &refchain;
70 refchain._ob_next->_ob_prev = op;
71 refchain._ob_next = op;
72 }
Tim Peters7571a0f2003-03-23 17:52:28 +000073}
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000074#endif /* Py_TRACE_REFS */
Tim Peters78be7992003-03-23 02:51:01 +000075
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000076#ifdef COUNT_ALLOCS
Guido van Rossumc0b618a1997-05-02 03:12:38 +000077static PyTypeObject *type_list;
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000078/* All types are added to type_list, at least when
79 they get one object created. That makes them
80 immortal, which unfortunately contributes to
81 garbage itself. If unlist_types_without_objects
82 is set, they will be removed from the type_list
83 once the last object is deallocated. */
Benjamin Petersona4a37fe2009-01-11 17:13:55 +000084static int unlist_types_without_objects;
85extern Py_ssize_t tuple_zero_allocs, fast_tuple_allocs;
86extern Py_ssize_t quick_int_allocs, quick_neg_int_allocs;
87extern Py_ssize_t null_strings, one_strings;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000088void
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000089dump_counts(FILE* f)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000090{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000091 PyTypeObject *tp;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +000092
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000093 for (tp = type_list; tp; tp = tp->tp_next)
94 fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
95 "freed: %" PY_FORMAT_SIZE_T "d, "
96 "max in use: %" PY_FORMAT_SIZE_T "d\n",
97 tp->tp_name, tp->tp_allocs, tp->tp_frees,
98 tp->tp_maxalloc);
99 fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
100 "empty: %" PY_FORMAT_SIZE_T "d\n",
101 fast_tuple_allocs, tuple_zero_allocs);
102 fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
103 "neg: %" PY_FORMAT_SIZE_T "d\n",
104 quick_int_allocs, quick_neg_int_allocs);
105 fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
106 "1-strings: %" PY_FORMAT_SIZE_T "d\n",
107 null_strings, one_strings);
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000108}
109
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000110PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000111get_counts(void)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000112{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000113 PyTypeObject *tp;
114 PyObject *result;
115 PyObject *v;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000116
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000117 result = PyList_New(0);
118 if (result == NULL)
119 return NULL;
120 for (tp = type_list; tp; tp = tp->tp_next) {
121 v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
122 tp->tp_frees, tp->tp_maxalloc);
123 if (v == NULL) {
124 Py_DECREF(result);
125 return NULL;
126 }
127 if (PyList_Append(result, v) < 0) {
128 Py_DECREF(v);
129 Py_DECREF(result);
130 return NULL;
131 }
132 Py_DECREF(v);
133 }
134 return result;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +0000135}
136
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000137void
Fred Drake100814d2000-07-09 15:48:49 +0000138inc_count(PyTypeObject *tp)
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000139{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000140 if (tp->tp_next == NULL && tp->tp_prev == NULL) {
141 /* first time; insert in linked list */
142 if (tp->tp_next != NULL) /* sanity check */
143 Py_FatalError("XXX inc_count sanity check");
144 if (type_list)
145 type_list->tp_prev = tp;
146 tp->tp_next = type_list;
147 /* Note that as of Python 2.2, heap-allocated type objects
148 * can go away, but this code requires that they stay alive
149 * until program exit. That's why we're careful with
150 * refcounts here. type_list gets a new reference to tp,
151 * while ownership of the reference type_list used to hold
152 * (if any) was transferred to tp->tp_next in the line above.
153 * tp is thus effectively immortal after this.
154 */
155 Py_INCREF(tp);
156 type_list = tp;
Tim Peters3e40c7f2003-03-23 03:04:32 +0000157#ifdef Py_TRACE_REFS
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000158 /* Also insert in the doubly-linked list of all objects,
159 * if not already there.
160 */
161 _Py_AddToAllObjects((PyObject *)tp, 0);
Tim Peters78be7992003-03-23 02:51:01 +0000162#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000163 }
164 tp->tp_allocs++;
165 if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
166 tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000167}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000168
169void dec_count(PyTypeObject *tp)
170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000171 tp->tp_frees++;
172 if (unlist_types_without_objects &&
173 tp->tp_allocs == tp->tp_frees) {
174 /* unlink the type from type_list */
175 if (tp->tp_prev)
176 tp->tp_prev->tp_next = tp->tp_next;
177 else
178 type_list = tp->tp_next;
179 if (tp->tp_next)
180 tp->tp_next->tp_prev = tp->tp_prev;
181 tp->tp_next = tp->tp_prev = NULL;
182 Py_DECREF(tp);
183 }
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000184}
185
Sjoerd Mullendera9c3c221993-10-11 12:54:31 +0000186#endif
187
Tim Peters7c321a82002-07-09 02:57:01 +0000188#ifdef Py_REF_DEBUG
189/* Log a fatal error; doesn't return. */
190void
191_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000193 char buf[300];
Tim Peters7c321a82002-07-09 02:57:01 +0000194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000195 PyOS_snprintf(buf, sizeof(buf),
196 "%s:%i object at %p has negative ref count "
197 "%" PY_FORMAT_SIZE_T "d",
198 fname, lineno, op, op->ob_refcnt);
199 Py_FatalError(buf);
Tim Peters7c321a82002-07-09 02:57:01 +0000200}
201
202#endif /* Py_REF_DEBUG */
203
Thomas Heller1328b522004-04-22 17:23:49 +0000204void
205Py_IncRef(PyObject *o)
206{
207 Py_XINCREF(o);
208}
209
210void
211Py_DecRef(PyObject *o)
212{
213 Py_XDECREF(o);
214}
215
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000216PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000217PyObject_Init(PyObject *op, PyTypeObject *tp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000218{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000219 if (op == NULL)
220 return PyErr_NoMemory();
221 /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
222 Py_TYPE(op) = tp;
223 _Py_NewReference(op);
224 return op;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000225}
226
Guido van Rossumb18618d2000-05-03 23:44:39 +0000227PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000228PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000229{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000230 if (op == NULL)
231 return (PyVarObject *) PyErr_NoMemory();
232 /* Any changes should be reflected in PyObject_INIT_VAR */
233 op->ob_size = size;
234 Py_TYPE(op) = tp;
235 _Py_NewReference((PyObject *)op);
236 return op;
Guido van Rossumb18618d2000-05-03 23:44:39 +0000237}
238
239PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000240_PyObject_New(PyTypeObject *tp)
Guido van Rossumb18618d2000-05-03 23:44:39 +0000241{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000242 PyObject *op;
243 op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
244 if (op == NULL)
245 return PyErr_NoMemory();
246 return PyObject_INIT(op, tp);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000247}
248
Guido van Rossumd0c87ee1997-05-15 21:31:03 +0000249PyVarObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +0000250_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000252 PyVarObject *op;
253 const size_t size = _PyObject_VAR_SIZE(tp, nitems);
254 op = (PyVarObject *) PyObject_MALLOC(size);
255 if (op == NULL)
256 return (PyVarObject *)PyErr_NoMemory();
257 return PyObject_INIT_VAR(op, tp, nitems);
Guido van Rossumb18618d2000-05-03 23:44:39 +0000258}
259
Antoine Pitrouc47bd4a2010-07-27 22:08:27 +0000260int
261PyObject_Print(PyObject *op, FILE *fp, int flags)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000263 int ret = 0;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000264 if (PyErr_CheckSignals())
265 return -1;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000266#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000267 if (PyOS_CheckStack()) {
268 PyErr_SetString(PyExc_MemoryError, "stack overflow");
269 return -1;
270 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000271#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000272 clearerr(fp); /* Clear any previous error condition */
273 if (op == NULL) {
274 Py_BEGIN_ALLOW_THREADS
275 fprintf(fp, "<nil>");
276 Py_END_ALLOW_THREADS
277 }
278 else {
279 if (op->ob_refcnt <= 0)
280 /* XXX(twouters) cast refcount to long until %zd is
281 universally available */
282 Py_BEGIN_ALLOW_THREADS
283 fprintf(fp, "<refcnt %ld at %p>",
284 (long)op->ob_refcnt, op);
285 Py_END_ALLOW_THREADS
286 else {
287 PyObject *s;
288 if (flags & Py_PRINT_RAW)
289 s = PyObject_Str(op);
290 else
291 s = PyObject_Repr(op);
292 if (s == NULL)
293 ret = -1;
294 else if (PyBytes_Check(s)) {
295 fwrite(PyBytes_AS_STRING(s), 1,
296 PyBytes_GET_SIZE(s), fp);
297 }
298 else if (PyUnicode_Check(s)) {
299 PyObject *t;
Victor Stinner372ac5e2010-05-17 01:26:01 +0000300 t = PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(s),
301 PyUnicode_GET_SIZE(s),
302 "backslashreplace");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000303 if (t == NULL)
304 ret = 0;
305 else {
306 fwrite(PyBytes_AS_STRING(t), 1,
307 PyBytes_GET_SIZE(t), fp);
Victor Stinnerba6b4302010-05-17 09:33:42 +0000308 Py_DECREF(t);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000309 }
310 }
311 else {
312 PyErr_Format(PyExc_TypeError,
313 "str() or repr() returned '%.100s'",
314 s->ob_type->tp_name);
315 ret = -1;
316 }
317 Py_XDECREF(s);
318 }
319 }
320 if (ret == 0) {
321 if (ferror(fp)) {
322 PyErr_SetFromErrno(PyExc_IOError);
323 clearerr(fp);
324 ret = -1;
325 }
326 }
327 return ret;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000328}
329
Guido van Rossum38938152006-08-21 23:36:26 +0000330/* For debugging convenience. Set a breakpoint here and call it from your DLL */
331void
Thomas Woutersb2137042007-02-01 18:02:27 +0000332_Py_BreakPoint(void)
Guido van Rossum38938152006-08-21 23:36:26 +0000333{
334}
335
Neal Norwitz1a997502003-01-13 20:13:12 +0000336
Barry Warsaw9bf16442001-01-23 16:24:35 +0000337/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
Guido van Rossum38938152006-08-21 23:36:26 +0000338void
339_PyObject_Dump(PyObject* op)
Barry Warsaw9bf16442001-01-23 16:24:35 +0000340{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000341 if (op == NULL)
342 fprintf(stderr, "NULL\n");
343 else {
Georg Brandldfd73442009-04-05 11:47:34 +0000344#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 PyGILState_STATE gil;
Georg Brandldfd73442009-04-05 11:47:34 +0000346#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000347 fprintf(stderr, "object : ");
Georg Brandldfd73442009-04-05 11:47:34 +0000348#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000349 gil = PyGILState_Ensure();
Georg Brandldfd73442009-04-05 11:47:34 +0000350#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 (void)PyObject_Print(op, stderr, 0);
Georg Brandldfd73442009-04-05 11:47:34 +0000352#ifdef WITH_THREAD
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000353 PyGILState_Release(gil);
Georg Brandldfd73442009-04-05 11:47:34 +0000354#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000355 /* XXX(twouters) cast refcount to long until %zd is
356 universally available */
357 fprintf(stderr, "\n"
358 "type : %s\n"
359 "refcount: %ld\n"
360 "address : %p\n",
361 Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
362 (long)op->ob_refcnt,
363 op);
364 }
Barry Warsaw9bf16442001-01-23 16:24:35 +0000365}
Barry Warsaw903138f2001-01-23 16:33:18 +0000366
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000367PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000368PyObject_Repr(PyObject *v)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000369{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000370 PyObject *res;
371 if (PyErr_CheckSignals())
372 return NULL;
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000373#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000374 if (PyOS_CheckStack()) {
375 PyErr_SetString(PyExc_MemoryError, "stack overflow");
376 return NULL;
377 }
Guido van Rossum9b00dfa1998-04-28 16:06:54 +0000378#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000379 if (v == NULL)
380 return PyUnicode_FromString("<NULL>");
381 if (Py_TYPE(v)->tp_repr == NULL)
382 return PyUnicode_FromFormat("<%s object at %p>",
383 v->ob_type->tp_name, v);
384 res = (*v->ob_type->tp_repr)(v);
385 if (res != NULL && !PyUnicode_Check(res)) {
386 PyErr_Format(PyExc_TypeError,
387 "__repr__ returned non-string (type %.200s)",
388 res->ob_type->tp_name);
389 Py_DECREF(res);
390 return NULL;
391 }
392 return res;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +0000393}
394
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000395PyObject *
Guido van Rossum98297ee2007-11-06 21:34:58 +0000396PyObject_Str(PyObject *v)
Guido van Rossumc6004111993-11-05 10:22:19 +0000397{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000398 PyObject *res;
399 if (PyErr_CheckSignals())
400 return NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000401#ifdef USE_STACKCHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000402 if (PyOS_CheckStack()) {
403 PyErr_SetString(PyExc_MemoryError, "stack overflow");
404 return NULL;
405 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000406#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000407 if (v == NULL)
408 return PyUnicode_FromString("<NULL>");
409 if (PyUnicode_CheckExact(v)) {
410 Py_INCREF(v);
411 return v;
412 }
413 if (Py_TYPE(v)->tp_str == NULL)
414 return PyObject_Repr(v);
Guido van Rossum4f288ab2001-05-01 16:53:37 +0000415
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 /* It is possible for a type to have a tp_str representation that loops
417 infinitely. */
418 if (Py_EnterRecursiveCall(" while getting the str of an object"))
419 return NULL;
420 res = (*Py_TYPE(v)->tp_str)(v);
421 Py_LeaveRecursiveCall();
422 if (res == NULL)
423 return NULL;
424 if (!PyUnicode_Check(res)) {
425 PyErr_Format(PyExc_TypeError,
426 "__str__ returned non-string (type %.200s)",
427 Py_TYPE(res)->tp_name);
428 Py_DECREF(res);
429 return NULL;
430 }
431 return res;
Neil Schemenauercf52c072005-08-12 17:34:58 +0000432}
433
Georg Brandl559e5d72008-06-11 18:37:52 +0000434PyObject *
435PyObject_ASCII(PyObject *v)
436{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000437 PyObject *repr, *ascii, *res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000438
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000439 repr = PyObject_Repr(v);
440 if (repr == NULL)
441 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000442
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 /* repr is guaranteed to be a PyUnicode object by PyObject_Repr */
444 ascii = PyUnicode_EncodeASCII(
445 PyUnicode_AS_UNICODE(repr),
446 PyUnicode_GET_SIZE(repr),
447 "backslashreplace");
Georg Brandl559e5d72008-06-11 18:37:52 +0000448
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000449 Py_DECREF(repr);
450 if (ascii == NULL)
451 return NULL;
Georg Brandl559e5d72008-06-11 18:37:52 +0000452
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000453 res = PyUnicode_DecodeASCII(
454 PyBytes_AS_STRING(ascii),
455 PyBytes_GET_SIZE(ascii),
456 NULL);
457
458 Py_DECREF(ascii);
459 return res;
Georg Brandl559e5d72008-06-11 18:37:52 +0000460}
Guido van Rossuma3af41d2001-01-18 22:07:06 +0000461
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000462PyObject *
463PyObject_Bytes(PyObject *v)
464{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000465 PyObject *result, *func;
466 static PyObject *bytesstring = NULL;
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000468 if (v == NULL)
469 return PyBytes_FromString("<NULL>");
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000470
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000471 if (PyBytes_CheckExact(v)) {
472 Py_INCREF(v);
473 return v;
474 }
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000476 func = _PyObject_LookupSpecial(v, "__bytes__", &bytesstring);
477 if (func != NULL) {
478 result = PyObject_CallFunctionObjArgs(func, NULL);
479 Py_DECREF(func);
480 if (result == NULL)
Benjamin Peterson41ece392010-09-11 16:39:57 +0000481 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000482 if (!PyBytes_Check(result)) {
Benjamin Peterson41ece392010-09-11 16:39:57 +0000483 PyErr_Format(PyExc_TypeError,
484 "__bytes__ returned non-bytes (type %.200s)",
485 Py_TYPE(result)->tp_name);
486 Py_DECREF(result);
487 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 }
489 return result;
490 }
491 else if (PyErr_Occurred())
492 return NULL;
493 return PyBytes_FromObject(v);
Benjamin Petersonc15a0732008-08-26 16:46:47 +0000494}
495
Mark Dickinsonc008a172009-02-01 13:59:22 +0000496/* For Python 3.0.1 and later, the old three-way comparison has been
497 completely removed in favour of rich comparisons. PyObject_Compare() and
498 PyObject_Cmp() are gone, and the builtin cmp function no longer exists.
Mark Dickinsone94c6792009-02-02 20:36:42 +0000499 The old tp_compare slot has been renamed to tp_reserved, and should no
Mark Dickinsonc008a172009-02-01 13:59:22 +0000500 longer be used. Use tp_richcompare instead.
Guido van Rossum98297ee2007-11-06 21:34:58 +0000501
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000502 See (*) below for practical amendments.
503
Mark Dickinsonc008a172009-02-01 13:59:22 +0000504 tp_richcompare gets called with a first argument of the appropriate type
505 and a second object of an arbitrary type. We never do any kind of
506 coercion.
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000507
Mark Dickinsonc008a172009-02-01 13:59:22 +0000508 The tp_richcompare slot should return an object, as follows:
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000509
510 NULL if an exception occurred
511 NotImplemented if the requested comparison is not implemented
512 any other false value if the requested comparison is false
513 any other true value if the requested comparison is true
514
515 The PyObject_RichCompare[Bool]() wrappers raise TypeError when they get
516 NotImplemented.
517
518 (*) Practical amendments:
519
520 - If rich comparison returns NotImplemented, == and != are decided by
521 comparing the object pointer (i.e. falling back to the base object
522 implementation).
523
Guido van Rossuma4073002002-05-31 20:03:54 +0000524*/
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000525
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000526/* Map rich comparison operators to their swapped version, e.g. LT <--> GT */
Brett Cannona5ca2e72004-09-25 01:37:24 +0000527int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +0000528
Guido van Rossum9a4e95c2006-12-19 21:35:46 +0000529static char *opstrings[] = {"<", "<=", "==", "!=", ">", ">="};
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000530
531/* Perform a rich comparison, raising TypeError when the requested comparison
532 operator is not supported. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000533static PyObject *
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000534do_richcompare(PyObject *v, PyObject *w, int op)
Guido van Rossume797ec12001-01-17 15:24:28 +0000535{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000536 richcmpfunc f;
537 PyObject *res;
538 int checked_reverse_op = 0;
Guido van Rossume797ec12001-01-17 15:24:28 +0000539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000540 if (v->ob_type != w->ob_type &&
541 PyType_IsSubtype(w->ob_type, v->ob_type) &&
542 (f = w->ob_type->tp_richcompare) != NULL) {
543 checked_reverse_op = 1;
544 res = (*f)(w, v, _Py_SwappedOp[op]);
545 if (res != Py_NotImplemented)
546 return res;
547 Py_DECREF(res);
548 }
549 if ((f = v->ob_type->tp_richcompare) != NULL) {
550 res = (*f)(v, w, op);
551 if (res != Py_NotImplemented)
552 return res;
553 Py_DECREF(res);
554 }
555 if (!checked_reverse_op && (f = w->ob_type->tp_richcompare) != NULL) {
556 res = (*f)(w, v, _Py_SwappedOp[op]);
557 if (res != Py_NotImplemented)
558 return res;
559 Py_DECREF(res);
560 }
561 /* If neither object implements it, provide a sensible default
562 for == and !=, but raise an exception for ordering. */
563 switch (op) {
564 case Py_EQ:
565 res = (v == w) ? Py_True : Py_False;
566 break;
567 case Py_NE:
568 res = (v != w) ? Py_True : Py_False;
569 break;
570 default:
571 /* XXX Special-case None so it doesn't show as NoneType() */
572 PyErr_Format(PyExc_TypeError,
573 "unorderable types: %.100s() %s %.100s()",
574 v->ob_type->tp_name,
575 opstrings[op],
576 w->ob_type->tp_name);
577 return NULL;
578 }
579 Py_INCREF(res);
580 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000581}
582
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000583/* Perform a rich comparison with object result. This wraps do_richcompare()
584 with a check for NULL arguments and a recursion check. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000585
Guido van Rossume797ec12001-01-17 15:24:28 +0000586PyObject *
587PyObject_RichCompare(PyObject *v, PyObject *w, int op)
588{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 PyObject *res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 assert(Py_LT <= op && op <= Py_GE);
592 if (v == NULL || w == NULL) {
593 if (!PyErr_Occurred())
594 PyErr_BadInternalCall();
595 return NULL;
596 }
597 if (Py_EnterRecursiveCall(" in comparison"))
598 return NULL;
599 res = do_richcompare(v, w, op);
600 Py_LeaveRecursiveCall();
601 return res;
Guido van Rossume797ec12001-01-17 15:24:28 +0000602}
603
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000604/* Perform a rich comparison with integer result. This wraps
605 PyObject_RichCompare(), returning -1 for error, 0 for false, 1 for true. */
Guido van Rossume797ec12001-01-17 15:24:28 +0000606int
607PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
608{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000609 PyObject *res;
610 int ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000612 /* Quick result when objects are the same.
613 Guarantees that identity implies equality. */
614 if (v == w) {
615 if (op == Py_EQ)
616 return 1;
617 else if (op == Py_NE)
618 return 0;
619 }
Mark Dickinson4a1f5932008-11-12 23:23:36 +0000620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000621 res = PyObject_RichCompare(v, w, op);
622 if (res == NULL)
623 return -1;
624 if (PyBool_Check(res))
625 ok = (res == Py_True);
626 else
627 ok = PyObject_IsTrue(res);
628 Py_DECREF(res);
629 return ok;
Guido van Rossume797ec12001-01-17 15:24:28 +0000630}
Fred Drake13634cf2000-06-29 19:17:04 +0000631
632/* Set of hash utility functions to help maintaining the invariant that
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000633 if a==b then hash(a)==hash(b)
Fred Drake13634cf2000-06-29 19:17:04 +0000634
635 All the utility functions (_Py_Hash*()) return "-1" to signify an error.
636*/
637
Mark Dickinsondc787d22010-05-23 13:33:13 +0000638/* For numeric types, the hash of a number x is based on the reduction
639 of x modulo the prime P = 2**_PyHASH_BITS - 1. It's designed so that
640 hash(x) == hash(y) whenever x and y are numerically equal, even if
641 x and y have different types.
642
643 A quick summary of the hashing strategy:
644
645 (1) First define the 'reduction of x modulo P' for any rational
646 number x; this is a standard extension of the usual notion of
647 reduction modulo P for integers. If x == p/q (written in lowest
648 terms), the reduction is interpreted as the reduction of p times
649 the inverse of the reduction of q, all modulo P; if q is exactly
650 divisible by P then define the reduction to be infinity. So we've
651 got a well-defined map
652
653 reduce : { rational numbers } -> { 0, 1, 2, ..., P-1, infinity }.
654
655 (2) Now for a rational number x, define hash(x) by:
656
657 reduce(x) if x >= 0
658 -reduce(-x) if x < 0
659
660 If the result of the reduction is infinity (this is impossible for
661 integers, floats and Decimals) then use the predefined hash value
662 _PyHASH_INF for x >= 0, or -_PyHASH_INF for x < 0, instead.
663 _PyHASH_INF, -_PyHASH_INF and _PyHASH_NAN are also used for the
664 hashes of float and Decimal infinities and nans.
665
666 A selling point for the above strategy is that it makes it possible
667 to compute hashes of decimal and binary floating-point numbers
668 efficiently, even if the exponent of the binary or decimal number
669 is large. The key point is that
670
671 reduce(x * y) == reduce(x) * reduce(y) (modulo _PyHASH_MODULUS)
672
673 provided that {reduce(x), reduce(y)} != {0, infinity}. The reduction of a
674 binary or decimal float is never infinity, since the denominator is a power
675 of 2 (for binary) or a divisor of a power of 10 (for decimal). So we have,
676 for nonnegative x,
677
678 reduce(x * 2**e) == reduce(x) * reduce(2**e) % _PyHASH_MODULUS
679
680 reduce(x * 10**e) == reduce(x) * reduce(10**e) % _PyHASH_MODULUS
681
682 and reduce(10**e) can be computed efficiently by the usual modular
683 exponentiation algorithm. For reduce(2**e) it's even better: since
684 P is of the form 2**n-1, reduce(2**e) is 2**(e mod n), and multiplication
685 by 2**(e mod n) modulo 2**n-1 just amounts to a rotation of bits.
686
687 */
688
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000689Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000690_Py_HashDouble(double v)
Fred Drake13634cf2000-06-29 19:17:04 +0000691{
Mark Dickinsondc787d22010-05-23 13:33:13 +0000692 int e, sign;
693 double m;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000694 Py_uhash_t x, y;
Tim Peters39dce292000-08-15 03:34:48 +0000695
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000696 if (!Py_IS_FINITE(v)) {
697 if (Py_IS_INFINITY(v))
Mark Dickinsondc787d22010-05-23 13:33:13 +0000698 return v > 0 ? _PyHASH_INF : -_PyHASH_INF;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000699 else
Mark Dickinsondc787d22010-05-23 13:33:13 +0000700 return _PyHASH_NAN;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000701 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000702
703 m = frexp(v, &e);
704
705 sign = 1;
706 if (m < 0) {
707 sign = -1;
708 m = -m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000709 }
Mark Dickinsondc787d22010-05-23 13:33:13 +0000710
711 /* process 28 bits at a time; this should work well both for binary
712 and hexadecimal floating point. */
713 x = 0;
714 while (m) {
715 x = ((x << 28) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - 28);
716 m *= 268435456.0; /* 2**28 */
717 e -= 28;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000718 y = (Py_uhash_t)m; /* pull out integer part */
Mark Dickinsondc787d22010-05-23 13:33:13 +0000719 m -= y;
720 x += y;
721 if (x >= _PyHASH_MODULUS)
722 x -= _PyHASH_MODULUS;
723 }
724
725 /* adjust for the exponent; first reduce it modulo _PyHASH_BITS */
726 e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);
727 x = ((x << e) & _PyHASH_MODULUS) | x >> (_PyHASH_BITS - e);
728
729 x = x * sign;
Benjamin Peterson8035bc52010-10-23 16:20:50 +0000730 if (x == (Py_uhash_t)-1)
731 x = (Py_uhash_t)-2;
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000732 return (Py_hash_t)x;
Fred Drake13634cf2000-06-29 19:17:04 +0000733}
734
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000735Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000736_Py_HashPointer(void *p)
Fred Drake13634cf2000-06-29 19:17:04 +0000737{
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000738 Py_hash_t x;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000739 size_t y = (size_t)p;
740 /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
741 excessive hash collisions for dicts and sets */
742 y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000743 x = (Py_hash_t)y;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000744 if (x == -1)
745 x = -2;
746 return x;
Fred Drake13634cf2000-06-29 19:17:04 +0000747}
748
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000749Py_hash_t
Nick Coghland1abd252008-07-15 15:46:38 +0000750PyObject_HashNotImplemented(PyObject *v)
751{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000752 PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
753 Py_TYPE(v)->tp_name);
754 return -1;
Nick Coghland1abd252008-07-15 15:46:38 +0000755}
Fred Drake13634cf2000-06-29 19:17:04 +0000756
Benjamin Peterson8f67d082010-10-17 20:54:53 +0000757Py_hash_t
Fred Drake100814d2000-07-09 15:48:49 +0000758PyObject_Hash(PyObject *v)
Guido van Rossum9bfef441993-03-29 10:43:31 +0000759{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000760 PyTypeObject *tp = Py_TYPE(v);
761 if (tp->tp_hash != NULL)
762 return (*tp->tp_hash)(v);
763 /* To keep to the general practice that inheriting
764 * solely from object in C code should work without
765 * an explicit call to PyType_Ready, we implicitly call
766 * PyType_Ready here and then check the tp_hash slot again
767 */
768 if (tp->tp_dict == NULL) {
769 if (PyType_Ready(tp) < 0)
770 return -1;
771 if (tp->tp_hash != NULL)
772 return (*tp->tp_hash)(v);
773 }
774 /* Otherwise, the object can't be hashed */
775 return PyObject_HashNotImplemented(v);
Guido van Rossum9bfef441993-03-29 10:43:31 +0000776}
777
Guido van Rossumc0b618a1997-05-02 03:12:38 +0000778PyObject *
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000779PyObject_GetAttrString(PyObject *v, const char *name)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000780{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000781 PyObject *w, *res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000782
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000783 if (Py_TYPE(v)->tp_getattr != NULL)
784 return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
785 w = PyUnicode_InternFromString(name);
786 if (w == NULL)
787 return NULL;
788 res = PyObject_GetAttr(v, w);
789 Py_XDECREF(w);
790 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000791}
792
793int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000794PyObject_HasAttrString(PyObject *v, const char *name)
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000795{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000796 PyObject *res = PyObject_GetAttrString(v, name);
797 if (res != NULL) {
798 Py_DECREF(res);
799 return 1;
800 }
801 PyErr_Clear();
802 return 0;
Guido van Rossumed18fdc1993-07-11 19:55:34 +0000803}
804
805int
Jeremy Hyltonaf68c872005-12-10 18:50:16 +0000806PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
Guido van Rossum3f5da241990-12-20 15:06:42 +0000807{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000808 PyObject *s;
809 int res;
Guido van Rossumd8eb1b31996-08-09 20:52:03 +0000810
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000811 if (Py_TYPE(v)->tp_setattr != NULL)
812 return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
813 s = PyUnicode_InternFromString(name);
814 if (s == NULL)
815 return -1;
816 res = PyObject_SetAttr(v, s, w);
817 Py_XDECREF(s);
818 return res;
Guido van Rossum3f5da241990-12-20 15:06:42 +0000819}
820
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000821PyObject *
Fred Drake100814d2000-07-09 15:48:49 +0000822PyObject_GetAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000823{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000824 PyTypeObject *tp = Py_TYPE(v);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000825
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000826 if (!PyUnicode_Check(name)) {
827 PyErr_Format(PyExc_TypeError,
828 "attribute name must be string, not '%.200s'",
829 name->ob_type->tp_name);
830 return NULL;
831 }
832 if (tp->tp_getattro != NULL)
833 return (*tp->tp_getattro)(v, name);
834 if (tp->tp_getattr != NULL) {
835 char *name_str = _PyUnicode_AsString(name);
836 if (name_str == NULL)
837 return NULL;
838 return (*tp->tp_getattr)(v, name_str);
839 }
840 PyErr_Format(PyExc_AttributeError,
841 "'%.50s' object has no attribute '%U'",
842 tp->tp_name, name);
843 return NULL;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000844}
845
846int
Fred Drake100814d2000-07-09 15:48:49 +0000847PyObject_HasAttr(PyObject *v, PyObject *name)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 PyObject *res = PyObject_GetAttr(v, name);
850 if (res != NULL) {
851 Py_DECREF(res);
852 return 1;
853 }
854 PyErr_Clear();
855 return 0;
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000856}
857
858int
Fred Drake100814d2000-07-09 15:48:49 +0000859PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
Guido van Rossum98ff96a1997-05-20 18:34:44 +0000860{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000861 PyTypeObject *tp = Py_TYPE(v);
862 int err;
Marc-André Lemburge44e5072000-09-18 16:20:57 +0000863
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000864 if (!PyUnicode_Check(name)) {
865 PyErr_Format(PyExc_TypeError,
866 "attribute name must be string, not '%.200s'",
867 name->ob_type->tp_name);
868 return -1;
869 }
870 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000871
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000872 PyUnicode_InternInPlace(&name);
873 if (tp->tp_setattro != NULL) {
874 err = (*tp->tp_setattro)(v, name, value);
875 Py_DECREF(name);
876 return err;
877 }
878 if (tp->tp_setattr != NULL) {
879 char *name_str = _PyUnicode_AsString(name);
880 if (name_str == NULL)
881 return -1;
882 err = (*tp->tp_setattr)(v, name_str, value);
883 Py_DECREF(name);
884 return err;
885 }
886 Py_DECREF(name);
887 assert(name->ob_refcnt >= 1);
888 if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
889 PyErr_Format(PyExc_TypeError,
890 "'%.100s' object has no attributes "
891 "(%s .%U)",
892 tp->tp_name,
893 value==NULL ? "del" : "assign to",
894 name);
895 else
896 PyErr_Format(PyExc_TypeError,
897 "'%.100s' object has only read-only attributes "
898 "(%s .%U)",
899 tp->tp_name,
900 value==NULL ? "del" : "assign to",
901 name);
902 return -1;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000903}
904
905/* Helper to get a pointer to an object's __dict__ slot, if any */
906
907PyObject **
908_PyObject_GetDictPtr(PyObject *obj)
909{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000910 Py_ssize_t dictoffset;
911 PyTypeObject *tp = Py_TYPE(obj);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000913 dictoffset = tp->tp_dictoffset;
914 if (dictoffset == 0)
915 return NULL;
916 if (dictoffset < 0) {
917 Py_ssize_t tsize;
918 size_t size;
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000919
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000920 tsize = ((PyVarObject *)obj)->ob_size;
921 if (tsize < 0)
922 tsize = -tsize;
923 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossum2eb0b872002-03-01 22:24:49 +0000924
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000925 dictoffset += (long)size;
926 assert(dictoffset > 0);
927 assert(dictoffset % SIZEOF_VOID_P == 0);
928 }
929 return (PyObject **) ((char *)obj + dictoffset);
Tim Peters6d6c1a32001-08-02 04:15:00 +0000930}
931
Tim Peters6d6c1a32001-08-02 04:15:00 +0000932PyObject *
Raymond Hettinger1da1dbf2003-03-17 19:46:11 +0000933PyObject_SelfIter(PyObject *obj)
Raymond Hettinger01538262003-03-17 08:24:35 +0000934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000935 Py_INCREF(obj);
936 return obj;
Raymond Hettinger01538262003-03-17 08:24:35 +0000937}
938
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +0000939/* Helper used when the __next__ method is removed from a type:
940 tp_iternext is never NULL and can be safely called without checking
941 on every iteration.
942 */
943
944PyObject *
945_PyObject_NextNotImplemented(PyObject *self)
946{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 PyErr_Format(PyExc_TypeError,
948 "'%.200s' object is not iterable",
949 Py_TYPE(self)->tp_name);
950 return NULL;
Amaury Forgeot d'Arcf343e012009-01-12 23:58:21 +0000951}
952
Michael W. Hudson1593f502004-09-14 17:09:47 +0000953/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
954
Raymond Hettinger01538262003-03-17 08:24:35 +0000955PyObject *
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000956_PyObject_GenericGetAttrWithDict(PyObject *obj, PyObject *name, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +0000957{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000958 PyTypeObject *tp = Py_TYPE(obj);
959 PyObject *descr = NULL;
960 PyObject *res = NULL;
961 descrgetfunc f;
962 Py_ssize_t dictoffset;
963 PyObject **dictptr;
Tim Peters6d6c1a32001-08-02 04:15:00 +0000964
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000965 if (!PyUnicode_Check(name)){
966 PyErr_Format(PyExc_TypeError,
967 "attribute name must be string, not '%.200s'",
968 name->ob_type->tp_name);
969 return NULL;
970 }
971 else
972 Py_INCREF(name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +0000973
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000974 if (tp->tp_dict == NULL) {
975 if (PyType_Ready(tp) < 0)
976 goto done;
977 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000978
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000979 descr = _PyType_Lookup(tp, name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000980 Py_XINCREF(descr);
Michael W. Hudsonb2c7de42003-08-15 13:07:47 +0000981
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000982 f = NULL;
983 if (descr != NULL) {
984 f = descr->ob_type->tp_descr_get;
985 if (f != NULL && PyDescr_IsData(descr)) {
986 res = f(descr, obj, (PyObject *)obj->ob_type);
987 Py_DECREF(descr);
988 goto done;
989 }
990 }
Tim Peters6d6c1a32001-08-02 04:15:00 +0000991
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +0000992 if (dict == NULL) {
993 /* Inline _PyObject_GetDictPtr */
994 dictoffset = tp->tp_dictoffset;
995 if (dictoffset != 0) {
996 if (dictoffset < 0) {
997 Py_ssize_t tsize;
998 size_t size;
Guido van Rossumc66ff442002-08-19 16:50:48 +0000999
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001000 tsize = ((PyVarObject *)obj)->ob_size;
1001 if (tsize < 0)
1002 tsize = -tsize;
1003 size = _PyObject_VAR_SIZE(tp, tsize);
Guido van Rossumc66ff442002-08-19 16:50:48 +00001004
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001005 dictoffset += (long)size;
1006 assert(dictoffset > 0);
1007 assert(dictoffset % SIZEOF_VOID_P == 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001008 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001009 dictptr = (PyObject **) ((char *)obj + dictoffset);
1010 dict = *dictptr;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001011 }
1012 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001013 if (dict != NULL) {
1014 Py_INCREF(dict);
1015 res = PyDict_GetItem(dict, name);
1016 if (res != NULL) {
1017 Py_INCREF(res);
1018 Py_XDECREF(descr);
1019 Py_DECREF(dict);
1020 goto done;
1021 }
1022 Py_DECREF(dict);
1023 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001024
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001025 if (f != NULL) {
1026 res = f(descr, obj, (PyObject *)Py_TYPE(obj));
1027 Py_DECREF(descr);
1028 goto done;
1029 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001030
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001031 if (descr != NULL) {
1032 res = descr;
1033 /* descr was already increfed above */
1034 goto done;
1035 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001036
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001037 PyErr_Format(PyExc_AttributeError,
1038 "'%.50s' object has no attribute '%U'",
1039 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001040 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001041 Py_DECREF(name);
1042 return res;
Tim Peters6d6c1a32001-08-02 04:15:00 +00001043}
1044
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001045PyObject *
1046PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
1047{
1048 return _PyObject_GenericGetAttrWithDict(obj, name, NULL);
1049}
1050
Tim Peters6d6c1a32001-08-02 04:15:00 +00001051int
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001052_PyObject_GenericSetAttrWithDict(PyObject *obj, PyObject *name,
1053 PyObject *value, PyObject *dict)
Tim Peters6d6c1a32001-08-02 04:15:00 +00001054{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001055 PyTypeObject *tp = Py_TYPE(obj);
1056 PyObject *descr;
1057 descrsetfunc f;
1058 PyObject **dictptr;
1059 int res = -1;
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001060
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001061 if (!PyUnicode_Check(name)){
1062 PyErr_Format(PyExc_TypeError,
1063 "attribute name must be string, not '%.200s'",
1064 name->ob_type->tp_name);
1065 return -1;
1066 }
1067 else
1068 Py_INCREF(name);
Tim Peters6d6c1a32001-08-02 04:15:00 +00001069
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001070 if (tp->tp_dict == NULL) {
1071 if (PyType_Ready(tp) < 0)
1072 goto done;
1073 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001074
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001075 descr = _PyType_Lookup(tp, name);
1076 f = NULL;
1077 if (descr != NULL) {
1078 f = descr->ob_type->tp_descr_set;
1079 if (f != NULL && PyDescr_IsData(descr)) {
1080 res = f(descr, obj, value);
1081 goto done;
1082 }
1083 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001084
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001085 if (dict == NULL) {
1086 dictptr = _PyObject_GetDictPtr(obj);
1087 if (dictptr != NULL) {
1088 dict = *dictptr;
1089 if (dict == NULL && value != NULL) {
1090 dict = PyDict_New();
1091 if (dict == NULL)
1092 goto done;
1093 *dictptr = dict;
1094 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001095 }
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001096 }
1097 if (dict != NULL) {
1098 Py_INCREF(dict);
1099 if (value == NULL)
1100 res = PyDict_DelItem(dict, name);
1101 else
1102 res = PyDict_SetItem(dict, name, value);
1103 if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
1104 PyErr_SetObject(PyExc_AttributeError, name);
1105 Py_DECREF(dict);
1106 goto done;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001107 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001108
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001109 if (f != NULL) {
1110 res = f(descr, obj, value);
1111 goto done;
1112 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001113
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001114 if (descr == NULL) {
1115 PyErr_Format(PyExc_AttributeError,
1116 "'%.100s' object has no attribute '%U'",
1117 tp->tp_name, name);
1118 goto done;
1119 }
Tim Peters6d6c1a32001-08-02 04:15:00 +00001120
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001121 PyErr_Format(PyExc_AttributeError,
1122 "'%.50s' object attribute '%U' is read-only",
1123 tp->tp_name, name);
Guido van Rossumebca9fc2001-12-04 15:54:53 +00001124 done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001125 Py_DECREF(name);
1126 return res;
Guido van Rossum98ff96a1997-05-20 18:34:44 +00001127}
1128
Antoine Pitrou1a9a9d52010-08-28 18:17:03 +00001129int
1130PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
1131{
1132 return _PyObject_GenericSetAttrWithDict(obj, name, value, NULL);
1133}
1134
1135
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001136/* Test a value used as condition, e.g., in a for or if statement.
1137 Return -1 if an error occurred */
1138
1139int
Fred Drake100814d2000-07-09 15:48:49 +00001140PyObject_IsTrue(PyObject *v)
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001141{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001142 Py_ssize_t res;
1143 if (v == Py_True)
1144 return 1;
1145 if (v == Py_False)
1146 return 0;
1147 if (v == Py_None)
1148 return 0;
1149 else if (v->ob_type->tp_as_number != NULL &&
1150 v->ob_type->tp_as_number->nb_bool != NULL)
1151 res = (*v->ob_type->tp_as_number->nb_bool)(v);
1152 else if (v->ob_type->tp_as_mapping != NULL &&
1153 v->ob_type->tp_as_mapping->mp_length != NULL)
1154 res = (*v->ob_type->tp_as_mapping->mp_length)(v);
1155 else if (v->ob_type->tp_as_sequence != NULL &&
1156 v->ob_type->tp_as_sequence->sq_length != NULL)
1157 res = (*v->ob_type->tp_as_sequence->sq_length)(v);
1158 else
1159 return 1;
1160 /* if it is negative, it should be either -1 or -2 */
1161 return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
Guido van Rossum6ac258d1993-05-12 08:24:20 +00001162}
1163
Tim Peters803526b2002-07-07 05:13:56 +00001164/* equivalent of 'not v'
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001165 Return -1 if an error occurred */
1166
1167int
Fred Drake100814d2000-07-09 15:48:49 +00001168PyObject_Not(PyObject *v)
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001169{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001170 int res;
1171 res = PyObject_IsTrue(v);
1172 if (res < 0)
1173 return res;
1174 return res == 0;
Guido van Rossumc3d3f961998-04-09 17:53:59 +00001175}
1176
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001177/* Test whether an object can be called */
1178
1179int
Fred Drake100814d2000-07-09 15:48:49 +00001180PyCallable_Check(PyObject *x)
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001181{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001182 if (x == NULL)
1183 return 0;
1184 return x->ob_type->tp_call != NULL;
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001185}
1186
Georg Brandle32b4222007-03-10 22:13:27 +00001187/* ------------------------- PyObject_Dir() helpers ------------------------- */
1188
Tim Peters7eea37e2001-09-04 22:08:56 +00001189/* Helper for PyObject_Dir.
1190 Merge the __dict__ of aclass into dict, and recursively also all
1191 the __dict__s of aclass's base classes. The order of merging isn't
1192 defined, as it's expected that only the final set of dict keys is
1193 interesting.
1194 Return 0 on success, -1 on error.
1195*/
1196
1197static int
1198merge_class_dict(PyObject* dict, PyObject* aclass)
1199{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001200 PyObject *classdict;
1201 PyObject *bases;
Tim Peters7eea37e2001-09-04 22:08:56 +00001202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001203 assert(PyDict_Check(dict));
1204 assert(aclass);
Tim Peters7eea37e2001-09-04 22:08:56 +00001205
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001206 /* Merge in the type's dict (if any). */
1207 classdict = PyObject_GetAttrString(aclass, "__dict__");
1208 if (classdict == NULL)
1209 PyErr_Clear();
1210 else {
1211 int status = PyDict_Update(dict, classdict);
1212 Py_DECREF(classdict);
1213 if (status < 0)
1214 return -1;
1215 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001216
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001217 /* Recursively merge in the base types' (if any) dicts. */
1218 bases = PyObject_GetAttrString(aclass, "__bases__");
1219 if (bases == NULL)
1220 PyErr_Clear();
1221 else {
1222 /* We have no guarantee that bases is a real tuple */
1223 Py_ssize_t i, n;
1224 n = PySequence_Size(bases); /* This better be right */
1225 if (n < 0)
1226 PyErr_Clear();
1227 else {
1228 for (i = 0; i < n; i++) {
1229 int status;
1230 PyObject *base = PySequence_GetItem(bases, i);
1231 if (base == NULL) {
1232 Py_DECREF(bases);
1233 return -1;
1234 }
1235 status = merge_class_dict(dict, base);
1236 Py_DECREF(base);
1237 if (status < 0) {
1238 Py_DECREF(bases);
1239 return -1;
1240 }
1241 }
1242 }
1243 Py_DECREF(bases);
1244 }
1245 return 0;
Tim Peters7eea37e2001-09-04 22:08:56 +00001246}
1247
Georg Brandle32b4222007-03-10 22:13:27 +00001248/* Helper for PyObject_Dir without arguments: returns the local scope. */
1249static PyObject *
Guido van Rossumad7d8d12007-04-13 01:39:34 +00001250_dir_locals(void)
Tim Peters305b5852001-09-17 02:38:46 +00001251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001252 PyObject *names;
1253 PyObject *locals = PyEval_GetLocals();
Tim Peters305b5852001-09-17 02:38:46 +00001254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001255 if (locals == NULL) {
1256 PyErr_SetString(PyExc_SystemError, "frame does not exist");
1257 return NULL;
1258 }
Tim Peters305b5852001-09-17 02:38:46 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 names = PyMapping_Keys(locals);
1261 if (!names)
1262 return NULL;
1263 if (!PyList_Check(names)) {
1264 PyErr_Format(PyExc_TypeError,
1265 "dir(): expected keys() of locals to be a list, "
1266 "not '%.200s'", Py_TYPE(names)->tp_name);
1267 Py_DECREF(names);
1268 return NULL;
1269 }
1270 /* the locals don't need to be DECREF'd */
1271 return names;
Georg Brandle32b4222007-03-10 22:13:27 +00001272}
1273
1274/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
Guido van Rossum98297ee2007-11-06 21:34:58 +00001275 We deliberately don't suck up its __class__, as methods belonging to the
1276 metaclass would probably be more confusing than helpful.
Georg Brandle32b4222007-03-10 22:13:27 +00001277*/
Guido van Rossum98297ee2007-11-06 21:34:58 +00001278static PyObject *
Georg Brandle32b4222007-03-10 22:13:27 +00001279_specialized_dir_type(PyObject *obj)
1280{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001281 PyObject *result = NULL;
1282 PyObject *dict = PyDict_New();
Georg Brandle32b4222007-03-10 22:13:27 +00001283
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001284 if (dict != NULL && merge_class_dict(dict, obj) == 0)
1285 result = PyDict_Keys(dict);
Georg Brandle32b4222007-03-10 22:13:27 +00001286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001287 Py_XDECREF(dict);
1288 return result;
Tim Peters305b5852001-09-17 02:38:46 +00001289}
1290
Georg Brandle32b4222007-03-10 22:13:27 +00001291/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
1292static PyObject *
1293_specialized_dir_module(PyObject *obj)
Tim Peters7eea37e2001-09-04 22:08:56 +00001294{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001295 PyObject *result = NULL;
1296 PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
Tim Peters7eea37e2001-09-04 22:08:56 +00001297
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 if (dict != NULL) {
1299 if (PyDict_Check(dict))
1300 result = PyDict_Keys(dict);
1301 else {
1302 const char *name = PyModule_GetName(obj);
1303 if (name)
1304 PyErr_Format(PyExc_TypeError,
1305 "%.200s.__dict__ is not a dictionary",
1306 name);
1307 }
1308 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001309
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001310 Py_XDECREF(dict);
1311 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001312}
Tim Peters7eea37e2001-09-04 22:08:56 +00001313
Georg Brandle32b4222007-03-10 22:13:27 +00001314/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
1315 and recursively up the __class__.__bases__ chain.
1316*/
1317static PyObject *
1318_generic_dir(PyObject *obj)
1319{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001320 PyObject *result = NULL;
1321 PyObject *dict = NULL;
1322 PyObject *itsclass = NULL;
Guido van Rossum98297ee2007-11-06 21:34:58 +00001323
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001324 /* Get __dict__ (which may or may not be a real dict...) */
1325 dict = PyObject_GetAttrString(obj, "__dict__");
1326 if (dict == NULL) {
1327 PyErr_Clear();
1328 dict = PyDict_New();
1329 }
1330 else if (!PyDict_Check(dict)) {
1331 Py_DECREF(dict);
1332 dict = PyDict_New();
1333 }
1334 else {
1335 /* Copy __dict__ to avoid mutating it. */
1336 PyObject *temp = PyDict_Copy(dict);
1337 Py_DECREF(dict);
1338 dict = temp;
1339 }
Tim Peters7eea37e2001-09-04 22:08:56 +00001340
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001341 if (dict == NULL)
1342 goto error;
Tim Peters7eea37e2001-09-04 22:08:56 +00001343
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001344 /* Merge in attrs reachable from its class. */
1345 itsclass = PyObject_GetAttrString(obj, "__class__");
1346 if (itsclass == NULL)
1347 /* XXX(tomer): Perhaps fall back to obj->ob_type if no
1348 __class__ exists? */
1349 PyErr_Clear();
1350 else {
1351 if (merge_class_dict(dict, itsclass) != 0)
1352 goto error;
1353 }
Georg Brandle32b4222007-03-10 22:13:27 +00001354
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001355 result = PyDict_Keys(dict);
1356 /* fall through */
Georg Brandle32b4222007-03-10 22:13:27 +00001357error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001358 Py_XDECREF(itsclass);
1359 Py_XDECREF(dict);
1360 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001361}
1362
1363/* Helper for PyObject_Dir: object introspection.
1364 This calls one of the above specialized versions if no __dir__ method
1365 exists. */
1366static PyObject *
1367_dir_object(PyObject *obj)
1368{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001369 PyObject * result = NULL;
1370 PyObject * dirfunc = PyObject_GetAttrString((PyObject*)obj->ob_type,
1371 "__dir__");
Georg Brandle32b4222007-03-10 22:13:27 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 assert(obj);
1374 if (dirfunc == NULL) {
1375 /* use default implementation */
1376 PyErr_Clear();
1377 if (PyModule_Check(obj))
1378 result = _specialized_dir_module(obj);
1379 else if (PyType_Check(obj))
1380 result = _specialized_dir_type(obj);
1381 else
1382 result = _generic_dir(obj);
1383 }
1384 else {
1385 /* use __dir__ */
1386 result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
1387 Py_DECREF(dirfunc);
1388 if (result == NULL)
1389 return NULL;
Georg Brandle32b4222007-03-10 22:13:27 +00001390
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001391 /* result must be a list */
1392 /* XXX(gbrandl): could also check if all items are strings */
1393 if (!PyList_Check(result)) {
1394 PyErr_Format(PyExc_TypeError,
1395 "__dir__() must return a list, not %.200s",
1396 Py_TYPE(result)->tp_name);
1397 Py_DECREF(result);
1398 result = NULL;
1399 }
1400 }
Georg Brandle32b4222007-03-10 22:13:27 +00001401
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001403}
1404
1405/* Implementation of dir() -- if obj is NULL, returns the names in the current
1406 (local) scope. Otherwise, performs introspection of the object: returns a
1407 sorted list of attribute names (supposedly) accessible from the object
1408*/
1409PyObject *
1410PyObject_Dir(PyObject *obj)
1411{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001412 PyObject * result;
Georg Brandle32b4222007-03-10 22:13:27 +00001413
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 if (obj == NULL)
1415 /* no object -- introspect the locals */
1416 result = _dir_locals();
1417 else
1418 /* object -- introspect the object */
1419 result = _dir_object(obj);
Georg Brandle32b4222007-03-10 22:13:27 +00001420
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001421 assert(result == NULL || PyList_Check(result));
Georg Brandle32b4222007-03-10 22:13:27 +00001422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (result != NULL && PyList_Sort(result) != 0) {
1424 /* sorting the list failed */
1425 Py_DECREF(result);
1426 result = NULL;
1427 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001428
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 return result;
Tim Peters7eea37e2001-09-04 22:08:56 +00001430}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001431
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001432/*
1433NoObject is usable as a non-NULL undefined value, used by the macro None.
1434There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001435so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001436(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001437*/
1438
Guido van Rossum0c182a11992-03-27 17:26:13 +00001439/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001440static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001441none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001442{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001444}
1445
Barry Warsaw9bf16442001-01-23 16:24:35 +00001446/* ARGUSED */
1447static void
Tim Peters803526b2002-07-07 05:13:56 +00001448none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001450 /* This should never get called, but we also don't want to SEGV if
1451 * we accidentally decref None out of existence.
1452 */
1453 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001454}
1455
1456
Guido van Rossumba21a492001-08-16 08:17:26 +00001457static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001458 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1459 "NoneType",
1460 0,
1461 0,
1462 none_dealloc, /*tp_dealloc*/ /*never called*/
1463 0, /*tp_print*/
1464 0, /*tp_getattr*/
1465 0, /*tp_setattr*/
1466 0, /*tp_reserved*/
1467 none_repr, /*tp_repr*/
1468 0, /*tp_as_number*/
1469 0, /*tp_as_sequence*/
1470 0, /*tp_as_mapping*/
1471 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001472};
1473
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001474PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001475 _PyObject_EXTRA_INIT
1476 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001477};
1478
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001479/* NotImplemented is an object that can be used to signal that an
1480 operation is not implemented for the given type combination. */
1481
1482static PyObject *
1483NotImplemented_repr(PyObject *op)
1484{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001485 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001486}
1487
1488static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001489 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1490 "NotImplementedType",
1491 0,
1492 0,
1493 none_dealloc, /*tp_dealloc*/ /*never called*/
1494 0, /*tp_print*/
1495 0, /*tp_getattr*/
1496 0, /*tp_setattr*/
1497 0, /*tp_reserved*/
1498 NotImplemented_repr, /*tp_repr*/
1499 0, /*tp_as_number*/
1500 0, /*tp_as_sequence*/
1501 0, /*tp_as_mapping*/
1502 0, /*tp_hash */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001503};
1504
1505PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 _PyObject_EXTRA_INIT
1507 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001508};
1509
Guido van Rossumba21a492001-08-16 08:17:26 +00001510void
1511_Py_ReadyTypes(void)
1512{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001513 if (PyType_Ready(&PyType_Type) < 0)
1514 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001515
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001516 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1517 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001518
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001519 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1520 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001522 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1523 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001524
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001525 if (PyType_Ready(&PyBool_Type) < 0)
1526 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001527
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001528 if (PyType_Ready(&PyByteArray_Type) < 0)
1529 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001530
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001531 if (PyType_Ready(&PyBytes_Type) < 0)
1532 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001533
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001534 if (PyType_Ready(&PyList_Type) < 0)
1535 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001536
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 if (PyType_Ready(&PyNone_Type) < 0)
1538 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001539
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 if (PyType_Ready(Py_Ellipsis->ob_type) < 0)
1541 Py_FatalError("Can't initialize type(Ellipsis)");
Guido van Rossum50e9fb92006-08-17 05:42:55 +00001542
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001543 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1544 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001545
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001546 if (PyType_Ready(&PyTraceBack_Type) < 0)
1547 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001548
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001549 if (PyType_Ready(&PySuper_Type) < 0)
1550 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001551
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001552 if (PyType_Ready(&PyBaseObject_Type) < 0)
1553 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001554
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 if (PyType_Ready(&PyRange_Type) < 0)
1556 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001557
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 if (PyType_Ready(&PyDict_Type) < 0)
1559 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001560
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001561 if (PyType_Ready(&PySet_Type) < 0)
1562 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001563
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001564 if (PyType_Ready(&PyUnicode_Type) < 0)
1565 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001567 if (PyType_Ready(&PySlice_Type) < 0)
1568 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001570 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1571 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001572
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 if (PyType_Ready(&PyComplex_Type) < 0)
1574 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001575
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001576 if (PyType_Ready(&PyFloat_Type) < 0)
1577 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001578
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001579 if (PyType_Ready(&PyLong_Type) < 0)
1580 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001581
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001582 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1583 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001585 if (PyType_Ready(&PyProperty_Type) < 0)
1586 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001587
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 if (PyType_Ready(&PyMemoryView_Type) < 0)
1589 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001590
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001591 if (PyType_Ready(&PyTuple_Type) < 0)
1592 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001593
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 if (PyType_Ready(&PyEnum_Type) < 0)
1595 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001596
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 if (PyType_Ready(&PyReversed_Type) < 0)
1598 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001599
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001600 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1601 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001602
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001603 if (PyType_Ready(&PyCode_Type) < 0)
1604 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001605
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001606 if (PyType_Ready(&PyFrame_Type) < 0)
1607 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001608
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001609 if (PyType_Ready(&PyCFunction_Type) < 0)
1610 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001611
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001612 if (PyType_Ready(&PyMethod_Type) < 0)
1613 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001614
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 if (PyType_Ready(&PyFunction_Type) < 0)
1616 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (PyType_Ready(&PyDictProxy_Type) < 0)
1619 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001620
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001621 if (PyType_Ready(&PyGen_Type) < 0)
1622 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001623
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1625 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001626
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001627 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1628 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001629
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001630 if (PyType_Ready(&PyEllipsis_Type) < 0)
1631 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001632
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001633 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1634 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001635
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001636 if (PyType_Ready(&PyFilter_Type) < 0)
1637 Py_FatalError("Can't initialize filter type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001638
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001639 if (PyType_Ready(&PyMap_Type) < 0)
1640 Py_FatalError("Can't initialize map type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001641
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 if (PyType_Ready(&PyZip_Type) < 0)
1643 Py_FatalError("Can't initialize zip type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001644}
1645
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001646
Guido van Rossum84a90321996-05-22 16:34:47 +00001647#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001648
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001649void
Fred Drake100814d2000-07-09 15:48:49 +00001650_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001651{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 _Py_INC_REFTOTAL;
1653 op->ob_refcnt = 1;
1654 _Py_AddToAllObjects(op, 1);
1655 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001656}
1657
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001658void
Fred Drake100814d2000-07-09 15:48:49 +00001659_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001660{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001661#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001662 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001663#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (op->ob_refcnt < 0)
1665 Py_FatalError("UNREF negative refcnt");
1666 if (op == &refchain ||
1667 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1668 fprintf(stderr, "* ob\n");
1669 _PyObject_Dump(op);
1670 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1671 _PyObject_Dump(op->_ob_prev->_ob_next);
1672 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1673 _PyObject_Dump(op->_ob_next->_ob_prev);
1674 Py_FatalError("UNREF invalid object");
1675 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001676#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1678 if (p == op)
1679 break;
1680 }
1681 if (p == &refchain) /* Not found */
1682 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001683#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 op->_ob_next->_ob_prev = op->_ob_prev;
1685 op->_ob_prev->_ob_next = op->_ob_next;
1686 op->_ob_next = op->_ob_prev = NULL;
1687 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001688}
1689
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001690void
Fred Drake100814d2000-07-09 15:48:49 +00001691_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001692{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001693 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1694 _Py_ForgetReference(op);
1695 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001696}
1697
Tim Peters269b2a62003-04-17 19:52:29 +00001698/* Print all live objects. Because PyObject_Print is called, the
1699 * interpreter must be in a healthy state.
1700 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001701void
Fred Drake100814d2000-07-09 15:48:49 +00001702_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 PyObject *op;
1705 fprintf(fp, "Remaining objects:\n");
1706 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1707 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1708 if (PyObject_Print(op, fp, 0) != 0)
1709 PyErr_Clear();
1710 putc('\n', fp);
1711 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001712}
1713
Tim Peters269b2a62003-04-17 19:52:29 +00001714/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1715 * doesn't make any calls to the Python C API, so is always safe to call.
1716 */
1717void
1718_Py_PrintReferenceAddresses(FILE *fp)
1719{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001720 PyObject *op;
1721 fprintf(fp, "Remaining object addresses:\n");
1722 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1723 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1724 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001725}
1726
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001727PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001728_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001729{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001730 int i, n;
1731 PyObject *t = NULL;
1732 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001733
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001734 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1735 return NULL;
1736 op = refchain._ob_next;
1737 res = PyList_New(0);
1738 if (res == NULL)
1739 return NULL;
1740 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1741 while (op == self || op == args || op == res || op == t ||
1742 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1743 op = op->_ob_next;
1744 if (op == &refchain)
1745 return res;
1746 }
1747 if (PyList_Append(res, op) < 0) {
1748 Py_DECREF(res);
1749 return NULL;
1750 }
1751 op = op->_ob_next;
1752 }
1753 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001754}
1755
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001756#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001757
Benjamin Petersonb173f782009-05-05 22:31:58 +00001758/* Hack to force loading of pycapsule.o */
1759PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1760
1761
Guido van Rossum84a90321996-05-22 16:34:47 +00001762/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001763Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001764
1765
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001766/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001767
Thomas Wouters334fb892000-07-25 12:56:38 +00001768void *
Fred Drake100814d2000-07-09 15:48:49 +00001769PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001770{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001771 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001772}
1773
Thomas Wouters334fb892000-07-25 12:56:38 +00001774void *
1775PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001776{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001777 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001778}
1779
1780void
Thomas Wouters334fb892000-07-25 12:56:38 +00001781PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001782{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00001784}
1785
1786
Guido van Rossum86610361998-04-10 22:32:46 +00001787/* These methods are used to control infinite recursion in repr, str, print,
1788 etc. Container objects that may recursively contain themselves,
1789 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1790 Py_ReprLeave() to avoid infinite recursion.
1791
1792 Py_ReprEnter() returns 0 the first time it is called for a particular
1793 object and 1 every time thereafter. It returns -1 if an exception
1794 occurred. Py_ReprLeave() has no return value.
1795
1796 See dictobject.c and listobject.c for examples of use.
1797*/
1798
1799#define KEY "Py_Repr"
1800
1801int
Fred Drake100814d2000-07-09 15:48:49 +00001802Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001803{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001804 PyObject *dict;
1805 PyObject *list;
1806 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001807
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001808 dict = PyThreadState_GetDict();
1809 if (dict == NULL)
1810 return 0;
1811 list = PyDict_GetItemString(dict, KEY);
1812 if (list == NULL) {
1813 list = PyList_New(0);
1814 if (list == NULL)
1815 return -1;
1816 if (PyDict_SetItemString(dict, KEY, list) < 0)
1817 return -1;
1818 Py_DECREF(list);
1819 }
1820 i = PyList_GET_SIZE(list);
1821 while (--i >= 0) {
1822 if (PyList_GET_ITEM(list, i) == obj)
1823 return 1;
1824 }
1825 PyList_Append(list, obj);
1826 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001827}
1828
1829void
Fred Drake100814d2000-07-09 15:48:49 +00001830Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001831{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001832 PyObject *dict;
1833 PyObject *list;
1834 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001835
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 dict = PyThreadState_GetDict();
1837 if (dict == NULL)
1838 return;
1839 list = PyDict_GetItemString(dict, KEY);
1840 if (list == NULL || !PyList_Check(list))
1841 return;
1842 i = PyList_GET_SIZE(list);
1843 /* Count backwards because we always expect obj to be list[-1] */
1844 while (--i >= 0) {
1845 if (PyList_GET_ITEM(list, i) == obj) {
1846 PyList_SetSlice(list, i, i + 1, NULL);
1847 break;
1848 }
1849 }
Guido van Rossum86610361998-04-10 22:32:46 +00001850}
Guido van Rossumd724b232000-03-13 16:01:29 +00001851
Tim Peters803526b2002-07-07 05:13:56 +00001852/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001853
Tim Peters803526b2002-07-07 05:13:56 +00001854/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001855int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001856
Tim Peters803526b2002-07-07 05:13:56 +00001857/* List of objects that still need to be cleaned up, singly linked via their
1858 * gc headers' gc_prev pointers.
1859 */
1860PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001861
Tim Peters803526b2002-07-07 05:13:56 +00001862/* Add op to the _PyTrash_delete_later list. Called when the current
1863 * call-stack depth gets large. op must be a currently untracked gc'ed
1864 * object, with refcount 0. Py_DECREF must already have been called on it.
1865 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001866void
Fred Drake100814d2000-07-09 15:48:49 +00001867_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001868{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 assert(PyObject_IS_GC(op));
1870 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1871 assert(op->ob_refcnt == 0);
1872 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1873 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001874}
1875
Tim Peters803526b2002-07-07 05:13:56 +00001876/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1877 * the call-stack unwinds again.
1878 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001879void
Fred Drake100814d2000-07-09 15:48:49 +00001880_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001881{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001882 while (_PyTrash_delete_later) {
1883 PyObject *op = _PyTrash_delete_later;
1884 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001885
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 _PyTrash_delete_later =
1887 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001888
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001889 /* Call the deallocator directly. This used to try to
1890 * fool Py_DECREF into calling it indirectly, but
1891 * Py_DECREF was already called on this object, and in
1892 * assorted non-release builds calling Py_DECREF again ends
1893 * up distorting allocation statistics.
1894 */
1895 assert(op->ob_refcnt == 0);
1896 ++_PyTrash_delete_nesting;
1897 (*dealloc)(op);
1898 --_PyTrash_delete_nesting;
1899 }
Guido van Rossumd724b232000-03-13 16:01:29 +00001900}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001901
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001902#ifndef Py_TRACE_REFS
1903/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
1904 Define this here, so we can undefine the macro. */
1905#undef _Py_Dealloc
1906PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
1907void
1908_Py_Dealloc(PyObject *op)
1909{
1910 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
1911 (*Py_TYPE(op)->tp_dealloc)(op);
1912}
1913#endif
1914
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001915#ifdef __cplusplus
1916}
1917#endif