summaryrefslogtreecommitdiffstats
path: root/Include/objimpl.h
blob: c2938227eac2a2b236b34e04dbab4d0ac60dfdb1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/* The PyObject_ memory family:  high-level object memory interfaces.
   See pymem.h for the low-level PyMem_ family.
*/

#ifndef Py_OBJIMPL_H
#define Py_OBJIMPL_H

#include "pymem.h"

#ifdef __cplusplus
extern "C" {
#endif

/* BEWARE:

   Each interface exports both functions and macros.  Extension modules should
   use the functions, to ensure binary compatibility across Python versions.
   Because the Python implementation is free to change internal details, and
   the macros may (or may not) expose details for speed, if you do use the
   macros you must recompile your extensions with each Python release.

   Never mix calls to PyObject_ memory functions with calls to the platform
   malloc/realloc/ calloc/free, or with calls to PyMem_.
*/

/*
Functions and macros for modules that implement new object types.

 - PyObject_New(type, typeobj) allocates memory for a new object of the given
   type, and initializes part of it.  'type' must be the C structure type used
   to represent the object, and 'typeobj' the address of the corresponding
   type object.  Reference count and type pointer are filled in; the rest of
   the bytes of the object are *undefined*!  The resulting expression type is
   'type *'.  The size of the object is determined by the tp_basicsize field
   of the type object.

 - PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size
   object with room for n items.  In addition to the refcount and type pointer
   fields, this also fills in the ob_size field.

 - PyObject_Del(op) releases the memory allocated for an object.  It does not
   run a destructor -- it only frees the memory.  PyObject_Free is identical.

 - PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't
   allocate memory.  Instead of a 'type' parameter, they take a pointer to a
   new object (allocated by an arbitrary allocator), and initialize its object
   header fields.

Note that objects created with PyObject_{New, NewVar} are allocated using the
specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is
enabled.  In addition, a special debugging allocator is used if PYMALLOC_DEBUG
is also #defined.

In case a specific form of memory management is needed (for example, if you
must use the platform malloc heap(s), or shared memory, or C++ local storage or
operator new), you must first allocate the object with your custom allocator,
then pass its pointer to PyObject_{Init, InitVar} for filling in its Python-
specific fields:  reference count, type pointer, possibly others.  You should
be aware that Python no control over these objects because they don't
cooperate with the Python memory manager.  Such objects may not be eligible
for automatic garbage collection and you have to make sure that they are
released accordingly whenever their destructor gets called (cf. the specific
form of memory management you're using).

Unless you have specific memory management requirements, use
PyObject_{New, NewVar, Del}.
*/

/*
 * Raw object memory interface
 * ===========================
 */

/* Functions to call the same malloc/realloc/free as used by Python's
   object allocator.  If WITH_PYMALLOC is enabled, these may differ from
   the platform malloc/realloc/free.  The Python object allocator is
   designed for fast, cache-conscious allocation of many "small" objects,
   and with low hidden memory overhead.

   PyObject_Malloc(0) returns a unique non-NULL pointer if possible.

   PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n).
   PyObject_Realloc(p != NULL, 0) does not return  NULL, or free the memory
   at p.

   Returned pointers must be checked for NULL explicitly; no action is
   performed on failure other than to return NULL (no warning it printed, no
   exception is set, etc).

   For allocating objects, use PyObject_{New, NewVar} instead whenever
   possible.  The PyObject_{Malloc, Realloc, Free} family is exposed
   so that you can exploit Python's small-block allocator for non-object
   uses.  If you must use these routines to allocate object memory, make sure
   the object gets initialized via PyObject_{Init, InitVar} after obtaining
   the raw memory.
*/
extern DL_IMPORT(void *) PyObject_Malloc(size_t);
extern DL_IMPORT(void *) PyObject_Realloc(void *, size_t);
extern DL_IMPORT(void) PyObject_Free(void *);


/* Macros */
#ifdef WITH_PYMALLOC
#ifdef PYMALLOC_DEBUG
DL_IMPORT(void *) _PyObject_DebugMalloc(size_t nbytes);
DL_IMPORT(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
DL_IMPORT(void) _PyObject_DebugFree(void *p);
DL_IMPORT(void) _PyObject_DebugDumpAddress(const void *p);
DL_IMPORT(void) _PyObject_DebugCheckAddress(const void *p);
DL_IMPORT(void) _PyObject_DebugMallocStats(void);
#define PyObject_MALLOC		_PyObject_DebugMalloc
#define PyObject_Malloc		_PyObject_DebugMalloc
#define PyObject_REALLOC	_PyObject_DebugRealloc
#define PyObject_Realloc	_PyObject_DebugRealloc
#define PyObject_FREE		_PyObject_DebugFree
#define PyObject_Free		_PyObject_DebugFree

#else	/* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
#define PyObject_MALLOC		PyObject_Malloc
#define PyObject_REALLOC	PyObject_Realloc
#define PyObject_FREE		PyObject_Free
#endif

#else	/* ! WITH_PYMALLOC */
#define PyObject_MALLOC		PyMem_MALLOC
#define PyObject_REALLOC	PyMem_REALLOC
/* This is an odd one!  For backward compatability with old extensions, the
   PyMem "release memory" functions have to invoke the object allocator's
   free() function.  When pymalloc isn't enabled, that leaves us using
   the platform free(). */
#define PyObject_FREE		free

#endif	/* WITH_PYMALLOC */

#define PyObject_Del		PyObject_Free
#define PyObject_DEL		PyObject_FREE

/* for source compatibility with 2.2 */
#define _PyObject_Del		PyObject_Free

/*
 * Generic object allocator interface
 * ==================================
 */

/* Functions */
extern DL_IMPORT(PyObject *) PyObject_Init(PyObject *, PyTypeObject *);
extern DL_IMPORT(PyVarObject *) PyObject_InitVar(PyVarObject *,
                                                 PyTypeObject *, int);
extern DL_IMPORT(PyObject *) _PyObject_New(PyTypeObject *);
extern DL_IMPORT(PyVarObject *) _PyObject_NewVar(PyTypeObject *, int);

#define PyObject_New(type, typeobj) \
		( (type *) _PyObject_New(typeobj) )
#define PyObject_NewVar(type, typeobj, n) \
		( (type *) _PyObject_NewVar((typeobj), (n)) )

/* Macros trading binary compatibility for speed. See also pymem.h.
   Note that these macros expect non-NULL object pointers.*/
#define PyObject_INIT(op, typeobj) \
	( (op)->ob_type = (typeobj), _Py_NewReference((PyObject *)(op)), (op) )
#define PyObject_INIT_VAR(op, typeobj, size) \
	( (op)->ob_size = (size), PyObject_INIT((op), (typeobj)) )

#define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )

/* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a
   vrbl-size object with nitems items, exclusive of gc overhead (if any).  The
   value is rounded up to the closest multiple of sizeof(void *), in order to
   ensure that pointer fields at the end of the object are correctly aligned
   for the platform (this is of special importance for subclasses of, e.g.,
   str or long, so that pointers can be stored after the embedded data).

   Note that there's no memory wastage in doing this, as malloc has to
   return (at worst) pointer-aligned memory anyway.
*/
#if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0
#   error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
#endif

#define _PyObject_VAR_SIZE(typeobj, nitems)	\
	(size_t)				\
	( ( (typeobj)->tp_basicsize +		\
	    (nitems)*(typeobj)->tp_itemsize +	\
	    (SIZEOF_VOID_P - 1)			\
	  ) & ~(SIZEOF_VOID_P - 1)		\
	)

#define PyObject_NEW(type, typeobj) \
( (type *) PyObject_Init( \
	(PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )

#define PyObject_NEW_VAR(type, typeobj, n) \
( (type *) PyObject_InitVar( \
      (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE((typeobj),(n)) ),\
      (typeobj), (n)) )

/* This example code implements an object constructor with a custom
   allocator, where PyObject_New is inlined, and shows the important
   distinction between two steps (at least):
       1) the actual allocation of the object storage;
       2) the initialization of the Python specific fields
          in this storage with PyObject_{Init, InitVar}.

   PyObject *
   YourObject_New(...)
   {
       PyObject *op;

       op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
       if (op == NULL)
           return PyErr_NoMemory();

       PyObject_Init(op, &YourTypeStruct);

       op->ob_field = value;
       ...
       return op;
   }

   Note that in C++, the use of the new operator usually implies that
   the 1st step is performed automatically for you, so in a C++ class
   constructor you would start directly with PyObject_Init/InitVar
*/

/*
 * Garbage Collection Support
 * ==========================
 *
 * Some of the functions and macros below are always defined; when
 * WITH_CYCLE_GC is undefined, they simply don't do anything different
 * than their non-GC counterparts.
 */

/* Test if a type has a GC head */
#define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)

/* Test if an object has a GC head */
#define PyObject_IS_GC(o) (PyType_IS_GC((o)->ob_type) && \
	((o)->ob_type->tp_is_gc == NULL || (o)->ob_type->tp_is_gc(o)))

extern DL_IMPORT(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, int);
#define PyObject_GC_Resize(type, op, n) \
		( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) )

/* for source compatibility with 2.2 */
#define _PyObject_GC_Del PyObject_GC_Del

#ifdef WITH_CYCLE_GC

/* GC information is stored BEFORE the object structure. */
typedef union _gc_head {
	struct {
		union _gc_head *gc_next; /* not NULL if object is tracked */
		union _gc_head *gc_prev;
		int gc_refs;
	} gc;
	long double dummy;  /* force worst-case alignment */
} PyGC_Head;

extern PyGC_Head _PyGC_generation0;

#define _Py_AS_GC(o) ((PyGC_Head *)(o)-1)

/* Tell the GC to track this object.  NB: While the object is tracked the
 * collector it must be safe to call the ob_traverse method. */
#define _PyObject_GC_TRACK(o) do { \
	PyGC_Head *g = _Py_AS_GC(o); \
	if (g->gc.gc_next != NULL) \
		Py_FatalError("GC object already in linked list"); \
	g->gc.gc_next = &_PyGC_generation0; \
	g->gc.gc_prev = _PyGC_generation0.gc.gc_prev; \
	g->gc.gc_prev->gc.gc_next = g; \
	_PyGC_generation0.gc.gc_prev = g; \
    } while (0);

/* Tell the GC to stop tracking this object. */
#define _PyObject_GC_UNTRACK(o) do { \
	PyGC_Head *g = _Py_AS_GC(o); \
	g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \
	g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \
	g->gc.gc_next = NULL; \
    } while (0);

extern DL_IMPORT(PyObject *) _PyObject_GC_Malloc(size_t);
extern DL_IMPORT(PyObject *) _PyObject_GC_New(PyTypeObject *);
extern DL_IMPORT(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, int);
extern DL_IMPORT(void) PyObject_GC_Track(void *);
extern DL_IMPORT(void) PyObject_GC_UnTrack(void *);
extern DL_IMPORT(void) PyObject_GC_Del(void *);

#define PyObject_GC_New(type, typeobj) \
		( (type *) _PyObject_GC_New(typeobj) )
#define PyObject_GC_NewVar(type, typeobj, n) \
		( (type *) _PyObject_GC_NewVar((typeobj), (n)) )


#else /* !WITH_CYCLE_GC */

#define _PyObject_GC_Malloc	PyObject_Malloc
#define PyObject_GC_New		PyObject_New
#define PyObject_GC_NewVar	PyObject_NewVar
#define PyObject_GC_Del		PyObject_Del
#define _PyObject_GC_TRACK(op)
#define _PyObject_GC_UNTRACK(op)
#define PyObject_GC_Track(op)
#define PyObject_GC_UnTrack(op)

#endif

/* This is here for the sake of backwards compatibility.  Extensions that
 * use the old GC API will still compile but the objects will not be
 * tracked by the GC. */
#define PyGC_HEAD_SIZE 0
#define PyObject_GC_Init(op)
#define PyObject_GC_Fini(op)
#define PyObject_AS_GC(op) (op)
#define PyObject_FROM_GC(op) (op)


/* Test if a type supports weak references */
#define PyType_SUPPORTS_WEAKREFS(t) \
        (PyType_HasFeature((t), Py_TPFLAGS_HAVE_WEAKREFS) \
         && ((t)->tp_weaklistoffset > 0))

#define PyObject_GET_WEAKREFS_LISTPTR(o) \
	((PyObject **) (((char *) (o)) + (o)->ob_type->tp_weaklistoffset))

#ifdef __cplusplus
}
#endif
#endif /* !Py_OBJIMPL_H */