blob: 694e7e719e94b2bac449e16c8abc387ff0fea1e7 [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{
Benjamin Peterson7963a352011-05-23 16:11:05 -05001369 PyObject *result = NULL;
1370 static PyObject *dir_str = NULL;
1371 PyObject *dirfunc = _PyObject_LookupSpecial(obj, "__dir__", &dir_str);
Georg Brandle32b4222007-03-10 22:13:27 +00001372
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001373 assert(obj);
1374 if (dirfunc == NULL) {
Benjamin Peterson7963a352011-05-23 16:11:05 -05001375 if (PyErr_Occurred())
1376 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001377 /* use default implementation */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001378 if (PyModule_Check(obj))
1379 result = _specialized_dir_module(obj);
1380 else if (PyType_Check(obj))
1381 result = _specialized_dir_type(obj);
1382 else
1383 result = _generic_dir(obj);
1384 }
1385 else {
1386 /* use __dir__ */
Benjamin Peterson7963a352011-05-23 16:11:05 -05001387 result = PyObject_CallFunctionObjArgs(dirfunc, NULL);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001388 Py_DECREF(dirfunc);
1389 if (result == NULL)
1390 return NULL;
Georg Brandle32b4222007-03-10 22:13:27 +00001391
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001392 /* result must be a list */
1393 /* XXX(gbrandl): could also check if all items are strings */
1394 if (!PyList_Check(result)) {
1395 PyErr_Format(PyExc_TypeError,
1396 "__dir__() must return a list, not %.200s",
1397 Py_TYPE(result)->tp_name);
1398 Py_DECREF(result);
1399 result = NULL;
1400 }
1401 }
Georg Brandle32b4222007-03-10 22:13:27 +00001402
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001403 return result;
Georg Brandle32b4222007-03-10 22:13:27 +00001404}
1405
1406/* Implementation of dir() -- if obj is NULL, returns the names in the current
1407 (local) scope. Otherwise, performs introspection of the object: returns a
1408 sorted list of attribute names (supposedly) accessible from the object
1409*/
1410PyObject *
1411PyObject_Dir(PyObject *obj)
1412{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001413 PyObject * result;
Georg Brandle32b4222007-03-10 22:13:27 +00001414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 if (obj == NULL)
1416 /* no object -- introspect the locals */
1417 result = _dir_locals();
1418 else
1419 /* object -- introspect the object */
1420 result = _dir_object(obj);
Georg Brandle32b4222007-03-10 22:13:27 +00001421
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001422 assert(result == NULL || PyList_Check(result));
Georg Brandle32b4222007-03-10 22:13:27 +00001423
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001424 if (result != NULL && PyList_Sort(result) != 0) {
1425 /* sorting the list failed */
1426 Py_DECREF(result);
1427 result = NULL;
1428 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001429
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 return result;
Tim Peters7eea37e2001-09-04 22:08:56 +00001431}
Guido van Rossum49b11fe1995-01-26 00:38:22 +00001432
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001433/*
1434NoObject is usable as a non-NULL undefined value, used by the macro None.
1435There is (and should be!) no way to create other objects of this type,
Guido van Rossum3f5da241990-12-20 15:06:42 +00001436so there is exactly one (which is indestructible, by the way).
Guido van Rossumba21a492001-08-16 08:17:26 +00001437(XXX This type and the type of NotImplemented below should be unified.)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001438*/
1439
Guido van Rossum0c182a11992-03-27 17:26:13 +00001440/* ARGSUSED */
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001441static PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001442none_repr(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001443{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001444 return PyUnicode_FromString("None");
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001445}
1446
Barry Warsaw9bf16442001-01-23 16:24:35 +00001447/* ARGUSED */
1448static void
Tim Peters803526b2002-07-07 05:13:56 +00001449none_dealloc(PyObject* ignore)
Barry Warsaw9bf16442001-01-23 16:24:35 +00001450{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001451 /* This should never get called, but we also don't want to SEGV if
1452 * we accidentally decref None out of existence.
1453 */
1454 Py_FatalError("deallocating None");
Barry Warsaw9bf16442001-01-23 16:24:35 +00001455}
1456
1457
Guido van Rossumba21a492001-08-16 08:17:26 +00001458static PyTypeObject PyNone_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001459 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1460 "NoneType",
1461 0,
1462 0,
1463 none_dealloc, /*tp_dealloc*/ /*never called*/
1464 0, /*tp_print*/
1465 0, /*tp_getattr*/
1466 0, /*tp_setattr*/
1467 0, /*tp_reserved*/
1468 none_repr, /*tp_repr*/
1469 0, /*tp_as_number*/
1470 0, /*tp_as_sequence*/
1471 0, /*tp_as_mapping*/
1472 0, /*tp_hash */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001473};
1474
Guido van Rossumc0b618a1997-05-02 03:12:38 +00001475PyObject _Py_NoneStruct = {
Martin v. Löwis9f2e3462007-07-21 17:22:18 +00001476 _PyObject_EXTRA_INIT
1477 1, &PyNone_Type
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001478};
1479
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001480/* NotImplemented is an object that can be used to signal that an
1481 operation is not implemented for the given type combination. */
1482
1483static PyObject *
1484NotImplemented_repr(PyObject *op)
1485{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 return PyUnicode_FromString("NotImplemented");
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001487}
1488
1489static PyTypeObject PyNotImplemented_Type = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001490 PyVarObject_HEAD_INIT(&PyType_Type, 0)
1491 "NotImplementedType",
1492 0,
1493 0,
1494 none_dealloc, /*tp_dealloc*/ /*never called*/
1495 0, /*tp_print*/
1496 0, /*tp_getattr*/
1497 0, /*tp_setattr*/
1498 0, /*tp_reserved*/
1499 NotImplemented_repr, /*tp_repr*/
1500 0, /*tp_as_number*/
1501 0, /*tp_as_sequence*/
1502 0, /*tp_as_mapping*/
1503 0, /*tp_hash */
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001504};
1505
1506PyObject _Py_NotImplementedStruct = {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001507 _PyObject_EXTRA_INIT
1508 1, &PyNotImplemented_Type
Neil Schemenauer5ed85ec2001-01-04 01:48:10 +00001509};
1510
Guido van Rossumba21a492001-08-16 08:17:26 +00001511void
1512_Py_ReadyTypes(void)
1513{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001514 if (PyType_Ready(&PyType_Type) < 0)
1515 Py_FatalError("Can't initialize type type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001516
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001517 if (PyType_Ready(&_PyWeakref_RefType) < 0)
1518 Py_FatalError("Can't initialize weakref type");
Fred Drake0a4dd392004-07-02 18:57:45 +00001519
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001520 if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
1521 Py_FatalError("Can't initialize callable weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001522
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001523 if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
1524 Py_FatalError("Can't initialize weakref proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001525
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001526 if (PyType_Ready(&PyBool_Type) < 0)
1527 Py_FatalError("Can't initialize bool type");
Guido van Rossum77f6a652002-04-03 22:41:51 +00001528
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 if (PyType_Ready(&PyByteArray_Type) < 0)
1530 Py_FatalError("Can't initialize bytearray type");
Guido van Rossum4dfe8a12006-04-22 23:28:04 +00001531
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 if (PyType_Ready(&PyBytes_Type) < 0)
1533 Py_FatalError("Can't initialize 'str'");
Guido van Rossumcacfc072002-05-24 19:01:59 +00001534
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001535 if (PyType_Ready(&PyList_Type) < 0)
1536 Py_FatalError("Can't initialize list type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001537
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001538 if (PyType_Ready(&PyNone_Type) < 0)
1539 Py_FatalError("Can't initialize None type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001540
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001541 if (PyType_Ready(&PyNotImplemented_Type) < 0)
1542 Py_FatalError("Can't initialize NotImplemented type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001543
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001544 if (PyType_Ready(&PyTraceBack_Type) < 0)
1545 Py_FatalError("Can't initialize traceback type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001546
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 if (PyType_Ready(&PySuper_Type) < 0)
1548 Py_FatalError("Can't initialize super type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001549
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 if (PyType_Ready(&PyBaseObject_Type) < 0)
1551 Py_FatalError("Can't initialize object type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001552
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001553 if (PyType_Ready(&PyRange_Type) < 0)
1554 Py_FatalError("Can't initialize range type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001555
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001556 if (PyType_Ready(&PyDict_Type) < 0)
1557 Py_FatalError("Can't initialize dict type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001559 if (PyType_Ready(&PySet_Type) < 0)
1560 Py_FatalError("Can't initialize set type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001561
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001562 if (PyType_Ready(&PyUnicode_Type) < 0)
1563 Py_FatalError("Can't initialize str type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001564
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 if (PyType_Ready(&PySlice_Type) < 0)
1566 Py_FatalError("Can't initialize slice type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001567
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001568 if (PyType_Ready(&PyStaticMethod_Type) < 0)
1569 Py_FatalError("Can't initialize static method type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001571 if (PyType_Ready(&PyComplex_Type) < 0)
1572 Py_FatalError("Can't initialize complex type");
Skip Montanaroba1e0f42009-10-18 14:25:35 +00001573
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001574 if (PyType_Ready(&PyFloat_Type) < 0)
1575 Py_FatalError("Can't initialize float type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001577 if (PyType_Ready(&PyLong_Type) < 0)
1578 Py_FatalError("Can't initialize int type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001579
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 if (PyType_Ready(&PyFrozenSet_Type) < 0)
1581 Py_FatalError("Can't initialize frozenset type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001582
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001583 if (PyType_Ready(&PyProperty_Type) < 0)
1584 Py_FatalError("Can't initialize property type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001585
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (PyType_Ready(&PyMemoryView_Type) < 0)
1587 Py_FatalError("Can't initialize memoryview type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001589 if (PyType_Ready(&PyTuple_Type) < 0)
1590 Py_FatalError("Can't initialize tuple type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001591
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001592 if (PyType_Ready(&PyEnum_Type) < 0)
1593 Py_FatalError("Can't initialize enumerate type");
Benjamin Petersonae937c02009-04-18 20:54:08 +00001594
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001595 if (PyType_Ready(&PyReversed_Type) < 0)
1596 Py_FatalError("Can't initialize reversed type");
Guido van Rossum47b9ff62006-08-24 00:41:19 +00001597
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001598 if (PyType_Ready(&PyStdPrinter_Type) < 0)
1599 Py_FatalError("Can't initialize StdPrinter");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001600
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001601 if (PyType_Ready(&PyCode_Type) < 0)
1602 Py_FatalError("Can't initialize code type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001603
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001604 if (PyType_Ready(&PyFrame_Type) < 0)
1605 Py_FatalError("Can't initialize frame type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (PyType_Ready(&PyCFunction_Type) < 0)
1608 Py_FatalError("Can't initialize builtin function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001610 if (PyType_Ready(&PyMethod_Type) < 0)
1611 Py_FatalError("Can't initialize method type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001612
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001613 if (PyType_Ready(&PyFunction_Type) < 0)
1614 Py_FatalError("Can't initialize function type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001615
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 if (PyType_Ready(&PyDictProxy_Type) < 0)
1617 Py_FatalError("Can't initialize dict proxy type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001618
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001619 if (PyType_Ready(&PyGen_Type) < 0)
1620 Py_FatalError("Can't initialize generator type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001621
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001622 if (PyType_Ready(&PyGetSetDescr_Type) < 0)
1623 Py_FatalError("Can't initialize get-set descriptor type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001624
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001625 if (PyType_Ready(&PyWrapperDescr_Type) < 0)
1626 Py_FatalError("Can't initialize wrapper type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001627
Benjamin Petersoneff61f62011-09-01 16:32:31 -04001628 if (PyType_Ready(&_PyMethodWrapper_Type) < 0)
1629 Py_FatalError("Can't initialize method wrapper type");
1630
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001631 if (PyType_Ready(&PyEllipsis_Type) < 0)
1632 Py_FatalError("Can't initialize ellipsis type");
Benjamin Petersonfd838e62009-04-20 02:09:13 +00001633
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 if (PyType_Ready(&PyMemberDescr_Type) < 0)
1635 Py_FatalError("Can't initialize member descriptor type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001636
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001637 if (PyType_Ready(&PyFilter_Type) < 0)
1638 Py_FatalError("Can't initialize filter type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001640 if (PyType_Ready(&PyMap_Type) < 0)
1641 Py_FatalError("Can't initialize map type");
Benjamin Peterson8bc5b682009-05-09 18:10:51 +00001642
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001643 if (PyType_Ready(&PyZip_Type) < 0)
1644 Py_FatalError("Can't initialize zip type");
Guido van Rossumba21a492001-08-16 08:17:26 +00001645}
1646
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001647
Guido van Rossum84a90321996-05-22 16:34:47 +00001648#ifdef Py_TRACE_REFS
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001649
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001650void
Fred Drake100814d2000-07-09 15:48:49 +00001651_Py_NewReference(PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001652{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001653 _Py_INC_REFTOTAL;
1654 op->ob_refcnt = 1;
1655 _Py_AddToAllObjects(op, 1);
1656 _Py_INC_TPALLOCS(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001657}
1658
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001659void
Fred Drake100814d2000-07-09 15:48:49 +00001660_Py_ForgetReference(register PyObject *op)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001661{
Guido van Rossumbffd6832000-01-20 22:32:56 +00001662#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001663 register PyObject *p;
Guido van Rossumbffd6832000-01-20 22:32:56 +00001664#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001665 if (op->ob_refcnt < 0)
1666 Py_FatalError("UNREF negative refcnt");
1667 if (op == &refchain ||
1668 op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op) {
1669 fprintf(stderr, "* ob\n");
1670 _PyObject_Dump(op);
1671 fprintf(stderr, "* op->_ob_prev->_ob_next\n");
1672 _PyObject_Dump(op->_ob_prev->_ob_next);
1673 fprintf(stderr, "* op->_ob_next->_ob_prev\n");
1674 _PyObject_Dump(op->_ob_next->_ob_prev);
1675 Py_FatalError("UNREF invalid object");
1676 }
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001677#ifdef SLOW_UNREF_CHECK
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001678 for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
1679 if (p == op)
1680 break;
1681 }
1682 if (p == &refchain) /* Not found */
1683 Py_FatalError("UNREF unknown object");
Guido van Rossum2e8f6141992-09-03 20:32:55 +00001684#endif
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 op->_ob_next->_ob_prev = op->_ob_prev;
1686 op->_ob_prev->_ob_next = op->_ob_next;
1687 op->_ob_next = op->_ob_prev = NULL;
1688 _Py_INC_TPFREES(op);
Guido van Rossum3f5da241990-12-20 15:06:42 +00001689}
1690
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001691void
Fred Drake100814d2000-07-09 15:48:49 +00001692_Py_Dealloc(PyObject *op)
Guido van Rossum3f5da241990-12-20 15:06:42 +00001693{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001694 destructor dealloc = Py_TYPE(op)->tp_dealloc;
1695 _Py_ForgetReference(op);
1696 (*dealloc)(op);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001697}
1698
Tim Peters269b2a62003-04-17 19:52:29 +00001699/* Print all live objects. Because PyObject_Print is called, the
1700 * interpreter must be in a healthy state.
1701 */
Guido van Rossumaacdc9d1996-08-12 21:32:12 +00001702void
Fred Drake100814d2000-07-09 15:48:49 +00001703_Py_PrintReferences(FILE *fp)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001704{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001705 PyObject *op;
1706 fprintf(fp, "Remaining objects:\n");
1707 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
1708 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
1709 if (PyObject_Print(op, fp, 0) != 0)
1710 PyErr_Clear();
1711 putc('\n', fp);
1712 }
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001713}
1714
Tim Peters269b2a62003-04-17 19:52:29 +00001715/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
1716 * doesn't make any calls to the Python C API, so is always safe to call.
1717 */
1718void
1719_Py_PrintReferenceAddresses(FILE *fp)
1720{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001721 PyObject *op;
1722 fprintf(fp, "Remaining object addresses:\n");
1723 for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
1724 fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
1725 op->ob_refcnt, Py_TYPE(op)->tp_name);
Tim Peters269b2a62003-04-17 19:52:29 +00001726}
1727
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001728PyObject *
Fred Drake100814d2000-07-09 15:48:49 +00001729_Py_GetObjects(PyObject *self, PyObject *args)
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001731 int i, n;
1732 PyObject *t = NULL;
1733 PyObject *res, *op;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001734
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001735 if (!PyArg_ParseTuple(args, "i|O", &n, &t))
1736 return NULL;
1737 op = refchain._ob_next;
1738 res = PyList_New(0);
1739 if (res == NULL)
1740 return NULL;
1741 for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
1742 while (op == self || op == args || op == res || op == t ||
1743 (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
1744 op = op->_ob_next;
1745 if (op == &refchain)
1746 return res;
1747 }
1748 if (PyList_Append(res, op) < 0) {
1749 Py_DECREF(res);
1750 return NULL;
1751 }
1752 op = op->_ob_next;
1753 }
1754 return res;
Sjoerd Mullender6ec3c651995-08-29 09:18:14 +00001755}
1756
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00001757#endif
Guido van Rossum97ead3f1996-01-12 01:24:09 +00001758
Benjamin Petersonb173f782009-05-05 22:31:58 +00001759/* Hack to force loading of pycapsule.o */
1760PyTypeObject *_PyCapsule_hack = &PyCapsule_Type;
1761
1762
Guido van Rossum84a90321996-05-22 16:34:47 +00001763/* Hack to force loading of abstract.o */
Martin v. Löwis18e16552006-02-15 17:27:45 +00001764Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
Guido van Rossume09fb551997-08-05 02:04:34 +00001765
1766
Andrew M. Kuchling1582a3a2000-08-16 12:27:23 +00001767/* Python's malloc wrappers (see pymem.h) */
Guido van Rossume09fb551997-08-05 02:04:34 +00001768
Thomas Wouters334fb892000-07-25 12:56:38 +00001769void *
Fred Drake100814d2000-07-09 15:48:49 +00001770PyMem_Malloc(size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001771{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 return PyMem_MALLOC(nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001773}
1774
Thomas Wouters334fb892000-07-25 12:56:38 +00001775void *
1776PyMem_Realloc(void *p, size_t nbytes)
Guido van Rossume09fb551997-08-05 02:04:34 +00001777{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001778 return PyMem_REALLOC(p, nbytes);
Guido van Rossume09fb551997-08-05 02:04:34 +00001779}
1780
1781void
Thomas Wouters334fb892000-07-25 12:56:38 +00001782PyMem_Free(void *p)
Guido van Rossume09fb551997-08-05 02:04:34 +00001783{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001784 PyMem_FREE(p);
Guido van Rossumb18618d2000-05-03 23:44:39 +00001785}
1786
1787
Guido van Rossum86610361998-04-10 22:32:46 +00001788/* These methods are used to control infinite recursion in repr, str, print,
1789 etc. Container objects that may recursively contain themselves,
1790 e.g. builtin dictionaries and lists, should used Py_ReprEnter() and
1791 Py_ReprLeave() to avoid infinite recursion.
1792
1793 Py_ReprEnter() returns 0 the first time it is called for a particular
1794 object and 1 every time thereafter. It returns -1 if an exception
1795 occurred. Py_ReprLeave() has no return value.
1796
1797 See dictobject.c and listobject.c for examples of use.
1798*/
1799
1800#define KEY "Py_Repr"
1801
1802int
Fred Drake100814d2000-07-09 15:48:49 +00001803Py_ReprEnter(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001804{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyObject *dict;
1806 PyObject *list;
1807 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001808
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001809 dict = PyThreadState_GetDict();
1810 if (dict == NULL)
1811 return 0;
1812 list = PyDict_GetItemString(dict, KEY);
1813 if (list == NULL) {
1814 list = PyList_New(0);
1815 if (list == NULL)
1816 return -1;
1817 if (PyDict_SetItemString(dict, KEY, list) < 0)
1818 return -1;
1819 Py_DECREF(list);
1820 }
1821 i = PyList_GET_SIZE(list);
1822 while (--i >= 0) {
1823 if (PyList_GET_ITEM(list, i) == obj)
1824 return 1;
1825 }
1826 PyList_Append(list, obj);
1827 return 0;
Guido van Rossum86610361998-04-10 22:32:46 +00001828}
1829
1830void
Fred Drake100814d2000-07-09 15:48:49 +00001831Py_ReprLeave(PyObject *obj)
Guido van Rossum86610361998-04-10 22:32:46 +00001832{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001833 PyObject *dict;
1834 PyObject *list;
1835 Py_ssize_t i;
Guido van Rossum86610361998-04-10 22:32:46 +00001836
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001837 dict = PyThreadState_GetDict();
1838 if (dict == NULL)
1839 return;
1840 list = PyDict_GetItemString(dict, KEY);
1841 if (list == NULL || !PyList_Check(list))
1842 return;
1843 i = PyList_GET_SIZE(list);
1844 /* Count backwards because we always expect obj to be list[-1] */
1845 while (--i >= 0) {
1846 if (PyList_GET_ITEM(list, i) == obj) {
1847 PyList_SetSlice(list, i, i + 1, NULL);
1848 break;
1849 }
1850 }
Guido van Rossum86610361998-04-10 22:32:46 +00001851}
Guido van Rossumd724b232000-03-13 16:01:29 +00001852
Tim Peters803526b2002-07-07 05:13:56 +00001853/* Trashcan support. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001854
Tim Peters803526b2002-07-07 05:13:56 +00001855/* Current call-stack depth of tp_dealloc calls. */
Guido van Rossumd724b232000-03-13 16:01:29 +00001856int _PyTrash_delete_nesting = 0;
Guido van Rossume92e6102000-04-24 15:40:53 +00001857
Tim Peters803526b2002-07-07 05:13:56 +00001858/* List of objects that still need to be cleaned up, singly linked via their
1859 * gc headers' gc_prev pointers.
1860 */
1861PyObject *_PyTrash_delete_later = NULL;
Guido van Rossumd724b232000-03-13 16:01:29 +00001862
Tim Peters803526b2002-07-07 05:13:56 +00001863/* Add op to the _PyTrash_delete_later list. Called when the current
1864 * call-stack depth gets large. op must be a currently untracked gc'ed
1865 * object, with refcount 0. Py_DECREF must already have been called on it.
1866 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001867void
Fred Drake100814d2000-07-09 15:48:49 +00001868_PyTrash_deposit_object(PyObject *op)
Guido van Rossumd724b232000-03-13 16:01:29 +00001869{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001870 assert(PyObject_IS_GC(op));
1871 assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
1872 assert(op->ob_refcnt == 0);
1873 _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
1874 _PyTrash_delete_later = op;
Guido van Rossumd724b232000-03-13 16:01:29 +00001875}
1876
Tim Peters803526b2002-07-07 05:13:56 +00001877/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
1878 * the call-stack unwinds again.
1879 */
Guido van Rossumd724b232000-03-13 16:01:29 +00001880void
Fred Drake100814d2000-07-09 15:48:49 +00001881_PyTrash_destroy_chain(void)
Guido van Rossumd724b232000-03-13 16:01:29 +00001882{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001883 while (_PyTrash_delete_later) {
1884 PyObject *op = _PyTrash_delete_later;
1885 destructor dealloc = Py_TYPE(op)->tp_dealloc;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001886
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 _PyTrash_delete_later =
1888 (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
Neil Schemenauerf589c052002-03-29 03:05:54 +00001889
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001890 /* Call the deallocator directly. This used to try to
1891 * fool Py_DECREF into calling it indirectly, but
1892 * Py_DECREF was already called on this object, and in
1893 * assorted non-release builds calling Py_DECREF again ends
1894 * up distorting allocation statistics.
1895 */
1896 assert(op->ob_refcnt == 0);
1897 ++_PyTrash_delete_nesting;
1898 (*dealloc)(op);
1899 --_PyTrash_delete_nesting;
1900 }
Guido van Rossumd724b232000-03-13 16:01:29 +00001901}
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001902
Martin v. Löwis4d0d4712010-12-03 20:14:31 +00001903#ifndef Py_TRACE_REFS
1904/* For Py_LIMITED_API, we need an out-of-line version of _Py_Dealloc.
1905 Define this here, so we can undefine the macro. */
1906#undef _Py_Dealloc
1907PyAPI_FUNC(void) _Py_Dealloc(PyObject *);
1908void
1909_Py_Dealloc(PyObject *op)
1910{
1911 _Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA
1912 (*Py_TYPE(op)->tp_dealloc)(op);
1913}
1914#endif
1915
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001916#ifdef __cplusplus
1917}
1918#endif