1 /* The PyObject_ memory family:  high-level object memory interfaces.
2    See pymem.h for the low-level PyMem_ family.
3 */
4 
5 #ifndef Py_OBJIMPL_H
6 #define Py_OBJIMPL_H
7 
8 #include "pymem.h"
9 
10 #ifdef __cplusplus
11 extern "C" {
12 #endif
13 
14 /* BEWARE:
15 
16    Each interface exports both functions and macros.  Extension modules should
17    use the functions, to ensure binary compatibility across Python versions.
18    Because the Python implementation is free to change internal details, and
19    the macros may (or may not) expose details for speed, if you do use the
20    macros you must recompile your extensions with each Python release.
21 
22    Never mix calls to PyObject_ memory functions with calls to the platform
23    malloc/realloc/ calloc/free, or with calls to PyMem_.
24 */
25 
26 /*
27 Functions and macros for modules that implement new object types.
28 
29  - PyObject_New(type, typeobj) allocates memory for a new object of the given
30    type, and initializes part of it.  'type' must be the C structure type used
31    to represent the object, and 'typeobj' the address of the corresponding
32    type object.  Reference count and type pointer are filled in; the rest of
33    the bytes of the object are *undefined*!  The resulting expression type is
34    'type *'.  The size of the object is determined by the tp_basicsize field
35    of the type object.
36 
37  - PyObject_NewVar(type, typeobj, n) is similar but allocates a variable-size
38    object with room for n items.  In addition to the refcount and type pointer
39    fields, this also fills in the ob_size field.
40 
41  - PyObject_Del(op) releases the memory allocated for an object.  It does not
42    run a destructor -- it only frees the memory.  PyObject_Free is identical.
43 
44  - PyObject_Init(op, typeobj) and PyObject_InitVar(op, typeobj, n) don't
45    allocate memory.  Instead of a 'type' parameter, they take a pointer to a
46    new object (allocated by an arbitrary allocator), and initialize its object
47    header fields.
48 
49 Note that objects created with PyObject_{New, NewVar} are allocated using the
50 specialized Python allocator (implemented in obmalloc.c), if WITH_PYMALLOC is
51 enabled.  In addition, a special debugging allocator is used if PYMALLOC_DEBUG
52 is also #defined.
53 
54 In case a specific form of memory management is needed (for example, if you
55 must use the platform malloc heap(s), or shared memory, or C++ local storage or
56 operator new), you must first allocate the object with your custom allocator,
57 then pass its pointer to PyObject_{Init, InitVar} for filling in its Python-
58 specific fields:  reference count, type pointer, possibly others.  You should
59 be aware that Python has no control over these objects because they don't
60 cooperate with the Python memory manager.  Such objects may not be eligible
61 for automatic garbage collection and you have to make sure that they are
62 released accordingly whenever their destructor gets called (cf. the specific
63 form of memory management you're using).
64 
65 Unless you have specific memory management requirements, use
66 PyObject_{New, NewVar, Del}.
67 */
68 
69 /*
70  * Raw object memory interface
71  * ===========================
72  */
73 
74 /* Functions to call the same malloc/realloc/free as used by Python's
75    object allocator.  If WITH_PYMALLOC is enabled, these may differ from
76    the platform malloc/realloc/free.  The Python object allocator is
77    designed for fast, cache-conscious allocation of many "small" objects,
78    and with low hidden memory overhead.
79 
80    PyObject_Malloc(0) returns a unique non-NULL pointer if possible.
81 
82    PyObject_Realloc(NULL, n) acts like PyObject_Malloc(n).
83    PyObject_Realloc(p != NULL, 0) does not return  NULL, or free the memory
84    at p.
85 
86    Returned pointers must be checked for NULL explicitly; no action is
87    performed on failure other than to return NULL (no warning it printed, no
88    exception is set, etc).
89 
90    For allocating objects, use PyObject_{New, NewVar} instead whenever
91    possible.  The PyObject_{Malloc, Realloc, Free} family is exposed
92    so that you can exploit Python's small-block allocator for non-object
93    uses.  If you must use these routines to allocate object memory, make sure
94    the object gets initialized via PyObject_{Init, InitVar} after obtaining
95    the raw memory.
96 */
97 PyAPI_FUNC(void *) PyObject_Malloc(size_t size);
98 #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 >= 0x03050000
99 PyAPI_FUNC(void *) PyObject_Calloc(size_t nelem, size_t elsize);
100 #endif
101 PyAPI_FUNC(void *) PyObject_Realloc(void *ptr, size_t new_size);
102 PyAPI_FUNC(void) PyObject_Free(void *ptr);
103 
104 
105 /* Macros */
106 #define PyObject_MALLOC         PyObject_Malloc
107 #define PyObject_REALLOC        PyObject_Realloc
108 #define PyObject_FREE           PyObject_Free
109 #define PyObject_Del            PyObject_Free
110 #define PyObject_DEL            PyObject_Free
111 
112 
113 /*
114  * Generic object allocator interface
115  * ==================================
116  */
117 
118 /* Functions */
119 PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *);
120 PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *,
121                                                  PyTypeObject *, Py_ssize_t);
122 PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *);
123 PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t);
124 
125 #define PyObject_New(type, typeobj) \
126                 ( (type *) _PyObject_New(typeobj) )
127 #define PyObject_NewVar(type, typeobj, n) \
128                 ( (type *) _PyObject_NewVar((typeobj), (n)) )
129 
130 /* Inline functions trading binary compatibility for speed:
131    PyObject_INIT() is the fast version of PyObject_Init(), and
132    PyObject_INIT_VAR() is the fast version of PyObject_InitVar.
133    See also pymem.h.
134 
135    These inline functions expect non-NULL object pointers. */
136 static inline PyObject*
_PyObject_INIT(PyObject * op,PyTypeObject * typeobj)137 _PyObject_INIT(PyObject *op, PyTypeObject *typeobj)
138 {
139     assert(op != NULL);
140     Py_TYPE(op) = typeobj;
141     if (PyType_GetFlags(typeobj) & Py_TPFLAGS_HEAPTYPE) {
142         Py_INCREF(typeobj);
143     }
144     _Py_NewReference(op);
145     return op;
146 }
147 
148 #define PyObject_INIT(op, typeobj) \
149     _PyObject_INIT(_PyObject_CAST(op), (typeobj))
150 
151 static inline PyVarObject*
_PyObject_INIT_VAR(PyVarObject * op,PyTypeObject * typeobj,Py_ssize_t size)152 _PyObject_INIT_VAR(PyVarObject *op, PyTypeObject *typeobj, Py_ssize_t size)
153 {
154     assert(op != NULL);
155     Py_SIZE(op) = size;
156     PyObject_INIT((PyObject *)op, typeobj);
157     return op;
158 }
159 
160 #define PyObject_INIT_VAR(op, typeobj, size) \
161     _PyObject_INIT_VAR(_PyVarObject_CAST(op), (typeobj), (size))
162 
163 #define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize )
164 
165 /* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a
166    vrbl-size object with nitems items, exclusive of gc overhead (if any).  The
167    value is rounded up to the closest multiple of sizeof(void *), in order to
168    ensure that pointer fields at the end of the object are correctly aligned
169    for the platform (this is of special importance for subclasses of, e.g.,
170    str or int, so that pointers can be stored after the embedded data).
171 
172    Note that there's no memory wastage in doing this, as malloc has to
173    return (at worst) pointer-aligned memory anyway.
174 */
175 #if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0
176 #   error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2"
177 #endif
178 
179 #define _PyObject_VAR_SIZE(typeobj, nitems)     \
180     _Py_SIZE_ROUND_UP((typeobj)->tp_basicsize + \
181         (nitems)*(typeobj)->tp_itemsize,        \
182         SIZEOF_VOID_P)
183 
184 #define PyObject_NEW(type, typeobj) \
185 ( (type *) PyObject_Init( \
186     (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) )
187 
188 #define PyObject_NEW_VAR(type, typeobj, n) \
189 ( (type *) PyObject_InitVar( \
190       (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE((typeobj),(n)) ),\
191       (typeobj), (n)) )
192 
193 /* This example code implements an object constructor with a custom
194    allocator, where PyObject_New is inlined, and shows the important
195    distinction between two steps (at least):
196        1) the actual allocation of the object storage;
197        2) the initialization of the Python specific fields
198       in this storage with PyObject_{Init, InitVar}.
199 
200    PyObject *
201    YourObject_New(...)
202    {
203        PyObject *op;
204 
205        op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct));
206        if (op == NULL)
207        return PyErr_NoMemory();
208 
209        PyObject_Init(op, &YourTypeStruct);
210 
211        op->ob_field = value;
212        ...
213        return op;
214    }
215 
216    Note that in C++, the use of the new operator usually implies that
217    the 1st step is performed automatically for you, so in a C++ class
218    constructor you would start directly with PyObject_Init/InitVar
219 */
220 
221 
222 
223 /*
224  * Garbage Collection Support
225  * ==========================
226  */
227 
228 /* C equivalent of gc.collect() which ignores the state of gc.enabled. */
229 PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void);
230 
231 /* Test if a type has a GC head */
232 #define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC)
233 
234 PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t);
235 #define PyObject_GC_Resize(type, op, n) \
236                 ( (type *) _PyObject_GC_Resize(_PyVarObject_CAST(op), (n)) )
237 
238 
239 
240 PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *);
241 PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t);
242 
243 /* Tell the GC to track this object.
244  *
245  * See also private _PyObject_GC_TRACK() macro. */
246 PyAPI_FUNC(void) PyObject_GC_Track(void *);
247 
248 /* Tell the GC to stop tracking this object.
249  *
250  * See also private _PyObject_GC_UNTRACK() macro. */
251 PyAPI_FUNC(void) PyObject_GC_UnTrack(void *);
252 
253 PyAPI_FUNC(void) PyObject_GC_Del(void *);
254 
255 #define PyObject_GC_New(type, typeobj) \
256                 ( (type *) _PyObject_GC_New(typeobj) )
257 #define PyObject_GC_NewVar(type, typeobj, n) \
258                 ( (type *) _PyObject_GC_NewVar((typeobj), (n)) )
259 
260 
261 /* Utility macro to help write tp_traverse functions.
262  * To use this macro, the tp_traverse function must name its arguments
263  * "visit" and "arg".  This is intended to keep tp_traverse functions
264  * looking as much alike as possible.
265  */
266 #define Py_VISIT(op)                                                    \
267     do {                                                                \
268         if (op) {                                                       \
269             int vret = visit(_PyObject_CAST(op), arg);                  \
270             if (vret)                                                   \
271                 return vret;                                            \
272         }                                                               \
273     } while (0)
274 
275 #ifndef Py_LIMITED_API
276 #  define Py_CPYTHON_OBJIMPL_H
277 #  include  "cpython/objimpl.h"
278 #  undef Py_CPYTHON_OBJIMPL_H
279 #endif
280 
281 #ifdef __cplusplus
282 }
283 #endif
284 #endif /* !Py_OBJIMPL_H */
285