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 #ifndef Py_LIMITED_API 105 /* This function returns the number of allocated memory blocks, regardless of size */ 106 PyAPI_FUNC(Py_ssize_t) _Py_GetAllocatedBlocks(void); 107 #endif /* !Py_LIMITED_API */ 108 109 /* Macros */ 110 #ifdef WITH_PYMALLOC 111 #ifndef Py_LIMITED_API 112 PyAPI_FUNC(int) _PyObject_DebugMallocStats(FILE *out); 113 #endif /* #ifndef Py_LIMITED_API */ 114 #endif 115 116 /* Macros */ 117 #define PyObject_MALLOC PyObject_Malloc 118 #define PyObject_REALLOC PyObject_Realloc 119 #define PyObject_FREE PyObject_Free 120 #define PyObject_Del PyObject_Free 121 #define PyObject_DEL PyObject_Free 122 123 124 /* 125 * Generic object allocator interface 126 * ================================== 127 */ 128 129 /* Functions */ 130 PyAPI_FUNC(PyObject *) PyObject_Init(PyObject *, PyTypeObject *); 131 PyAPI_FUNC(PyVarObject *) PyObject_InitVar(PyVarObject *, 132 PyTypeObject *, Py_ssize_t); 133 PyAPI_FUNC(PyObject *) _PyObject_New(PyTypeObject *); 134 PyAPI_FUNC(PyVarObject *) _PyObject_NewVar(PyTypeObject *, Py_ssize_t); 135 136 #define PyObject_New(type, typeobj) \ 137 ( (type *) _PyObject_New(typeobj) ) 138 #define PyObject_NewVar(type, typeobj, n) \ 139 ( (type *) _PyObject_NewVar((typeobj), (n)) ) 140 141 /* Macros trading binary compatibility for speed. See also pymem.h. 142 Note that these macros expect non-NULL object pointers.*/ 143 #define PyObject_INIT(op, typeobj) \ 144 ( Py_TYPE(op) = (typeobj), _Py_NewReference((PyObject *)(op)), (op) ) 145 #define PyObject_INIT_VAR(op, typeobj, size) \ 146 ( Py_SIZE(op) = (size), PyObject_INIT((op), (typeobj)) ) 147 148 #define _PyObject_SIZE(typeobj) ( (typeobj)->tp_basicsize ) 149 150 /* _PyObject_VAR_SIZE returns the number of bytes (as size_t) allocated for a 151 vrbl-size object with nitems items, exclusive of gc overhead (if any). The 152 value is rounded up to the closest multiple of sizeof(void *), in order to 153 ensure that pointer fields at the end of the object are correctly aligned 154 for the platform (this is of special importance for subclasses of, e.g., 155 str or int, so that pointers can be stored after the embedded data). 156 157 Note that there's no memory wastage in doing this, as malloc has to 158 return (at worst) pointer-aligned memory anyway. 159 */ 160 #if ((SIZEOF_VOID_P - 1) & SIZEOF_VOID_P) != 0 161 # error "_PyObject_VAR_SIZE requires SIZEOF_VOID_P be a power of 2" 162 #endif 163 164 #define _PyObject_VAR_SIZE(typeobj, nitems) \ 165 _Py_SIZE_ROUND_UP((typeobj)->tp_basicsize + \ 166 (nitems)*(typeobj)->tp_itemsize, \ 167 SIZEOF_VOID_P) 168 169 #define PyObject_NEW(type, typeobj) \ 170 ( (type *) PyObject_Init( \ 171 (PyObject *) PyObject_MALLOC( _PyObject_SIZE(typeobj) ), (typeobj)) ) 172 173 #define PyObject_NEW_VAR(type, typeobj, n) \ 174 ( (type *) PyObject_InitVar( \ 175 (PyVarObject *) PyObject_MALLOC(_PyObject_VAR_SIZE((typeobj),(n)) ),\ 176 (typeobj), (n)) ) 177 178 /* This example code implements an object constructor with a custom 179 allocator, where PyObject_New is inlined, and shows the important 180 distinction between two steps (at least): 181 1) the actual allocation of the object storage; 182 2) the initialization of the Python specific fields 183 in this storage with PyObject_{Init, InitVar}. 184 185 PyObject * 186 YourObject_New(...) 187 { 188 PyObject *op; 189 190 op = (PyObject *) Your_Allocator(_PyObject_SIZE(YourTypeStruct)); 191 if (op == NULL) 192 return PyErr_NoMemory(); 193 194 PyObject_Init(op, &YourTypeStruct); 195 196 op->ob_field = value; 197 ... 198 return op; 199 } 200 201 Note that in C++, the use of the new operator usually implies that 202 the 1st step is performed automatically for you, so in a C++ class 203 constructor you would start directly with PyObject_Init/InitVar 204 */ 205 206 #ifndef Py_LIMITED_API 207 typedef struct { 208 /* user context passed as the first argument to the 2 functions */ 209 void *ctx; 210 211 /* allocate an arena of size bytes */ 212 void* (*alloc) (void *ctx, size_t size); 213 214 /* free an arena */ 215 void (*free) (void *ctx, void *ptr, size_t size); 216 } PyObjectArenaAllocator; 217 218 /* Get the arena allocator. */ 219 PyAPI_FUNC(void) PyObject_GetArenaAllocator(PyObjectArenaAllocator *allocator); 220 221 /* Set the arena allocator. */ 222 PyAPI_FUNC(void) PyObject_SetArenaAllocator(PyObjectArenaAllocator *allocator); 223 #endif 224 225 226 /* 227 * Garbage Collection Support 228 * ========================== 229 */ 230 231 /* C equivalent of gc.collect() which ignores the state of gc.enabled. */ 232 PyAPI_FUNC(Py_ssize_t) PyGC_Collect(void); 233 234 #ifndef Py_LIMITED_API 235 PyAPI_FUNC(Py_ssize_t) _PyGC_CollectNoFail(void); 236 PyAPI_FUNC(Py_ssize_t) _PyGC_CollectIfEnabled(void); 237 #endif 238 239 /* Test if a type has a GC head */ 240 #define PyType_IS_GC(t) PyType_HasFeature((t), Py_TPFLAGS_HAVE_GC) 241 242 /* Test if an object has a GC head */ 243 #define PyObject_IS_GC(o) (PyType_IS_GC(Py_TYPE(o)) && \ 244 (Py_TYPE(o)->tp_is_gc == NULL || Py_TYPE(o)->tp_is_gc(o))) 245 246 PyAPI_FUNC(PyVarObject *) _PyObject_GC_Resize(PyVarObject *, Py_ssize_t); 247 #define PyObject_GC_Resize(type, op, n) \ 248 ( (type *) _PyObject_GC_Resize((PyVarObject *)(op), (n)) ) 249 250 /* GC information is stored BEFORE the object structure. */ 251 #ifndef Py_LIMITED_API 252 typedef union _gc_head { 253 struct { 254 union _gc_head *gc_next; 255 union _gc_head *gc_prev; 256 Py_ssize_t gc_refs; 257 } gc; 258 double dummy; /* force worst-case alignment */ 259 } PyGC_Head; 260 261 extern PyGC_Head *_PyGC_generation0; 262 263 #define _Py_AS_GC(o) ((PyGC_Head *)(o)-1) 264 265 /* Bit 0 is set when tp_finalize is called */ 266 #define _PyGC_REFS_MASK_FINALIZED (1 << 0) 267 /* The (N-1) most significant bits contain the gc state / refcount */ 268 #define _PyGC_REFS_SHIFT (1) 269 #define _PyGC_REFS_MASK (((size_t) -1) << _PyGC_REFS_SHIFT) 270 271 #define _PyGCHead_REFS(g) ((g)->gc.gc_refs >> _PyGC_REFS_SHIFT) 272 #define _PyGCHead_SET_REFS(g, v) do { \ 273 (g)->gc.gc_refs = ((g)->gc.gc_refs & ~_PyGC_REFS_MASK) \ 274 | (((size_t)(v)) << _PyGC_REFS_SHIFT); \ 275 } while (0) 276 #define _PyGCHead_DECREF(g) ((g)->gc.gc_refs -= 1 << _PyGC_REFS_SHIFT) 277 278 #define _PyGCHead_FINALIZED(g) (((g)->gc.gc_refs & _PyGC_REFS_MASK_FINALIZED) != 0) 279 #define _PyGCHead_SET_FINALIZED(g, v) do { \ 280 (g)->gc.gc_refs = ((g)->gc.gc_refs & ~_PyGC_REFS_MASK_FINALIZED) \ 281 | (v != 0); \ 282 } while (0) 283 284 #define _PyGC_FINALIZED(o) _PyGCHead_FINALIZED(_Py_AS_GC(o)) 285 #define _PyGC_SET_FINALIZED(o, v) _PyGCHead_SET_FINALIZED(_Py_AS_GC(o), v) 286 287 #define _PyGC_REFS(o) _PyGCHead_REFS(_Py_AS_GC(o)) 288 289 #define _PyGC_REFS_UNTRACKED (-2) 290 #define _PyGC_REFS_REACHABLE (-3) 291 #define _PyGC_REFS_TENTATIVELY_UNREACHABLE (-4) 292 293 /* Tell the GC to track this object. NB: While the object is tracked the 294 * collector it must be safe to call the ob_traverse method. */ 295 #define _PyObject_GC_TRACK(o) do { \ 296 PyGC_Head *g = _Py_AS_GC(o); \ 297 if (_PyGCHead_REFS(g) != _PyGC_REFS_UNTRACKED) \ 298 Py_FatalError("GC object already tracked"); \ 299 _PyGCHead_SET_REFS(g, _PyGC_REFS_REACHABLE); \ 300 g->gc.gc_next = _PyGC_generation0; \ 301 g->gc.gc_prev = _PyGC_generation0->gc.gc_prev; \ 302 g->gc.gc_prev->gc.gc_next = g; \ 303 _PyGC_generation0->gc.gc_prev = g; \ 304 } while (0); 305 306 /* Tell the GC to stop tracking this object. 307 * gc_next doesn't need to be set to NULL, but doing so is a good 308 * way to provoke memory errors if calling code is confused. 309 */ 310 #define _PyObject_GC_UNTRACK(o) do { \ 311 PyGC_Head *g = _Py_AS_GC(o); \ 312 assert(_PyGCHead_REFS(g) != _PyGC_REFS_UNTRACKED); \ 313 _PyGCHead_SET_REFS(g, _PyGC_REFS_UNTRACKED); \ 314 g->gc.gc_prev->gc.gc_next = g->gc.gc_next; \ 315 g->gc.gc_next->gc.gc_prev = g->gc.gc_prev; \ 316 g->gc.gc_next = NULL; \ 317 } while (0); 318 319 /* True if the object is currently tracked by the GC. */ 320 #define _PyObject_GC_IS_TRACKED(o) \ 321 (_PyGC_REFS(o) != _PyGC_REFS_UNTRACKED) 322 323 /* True if the object may be tracked by the GC in the future, or already is. 324 This can be useful to implement some optimizations. */ 325 #define _PyObject_GC_MAY_BE_TRACKED(obj) \ 326 (PyObject_IS_GC(obj) && \ 327 (!PyTuple_CheckExact(obj) || _PyObject_GC_IS_TRACKED(obj))) 328 #endif /* Py_LIMITED_API */ 329 330 #ifndef Py_LIMITED_API 331 PyAPI_FUNC(PyObject *) _PyObject_GC_Malloc(size_t size); 332 PyAPI_FUNC(PyObject *) _PyObject_GC_Calloc(size_t size); 333 #endif /* !Py_LIMITED_API */ 334 PyAPI_FUNC(PyObject *) _PyObject_GC_New(PyTypeObject *); 335 PyAPI_FUNC(PyVarObject *) _PyObject_GC_NewVar(PyTypeObject *, Py_ssize_t); 336 PyAPI_FUNC(void) PyObject_GC_Track(void *); 337 PyAPI_FUNC(void) PyObject_GC_UnTrack(void *); 338 PyAPI_FUNC(void) PyObject_GC_Del(void *); 339 340 #define PyObject_GC_New(type, typeobj) \ 341 ( (type *) _PyObject_GC_New(typeobj) ) 342 #define PyObject_GC_NewVar(type, typeobj, n) \ 343 ( (type *) _PyObject_GC_NewVar((typeobj), (n)) ) 344 345 346 /* Utility macro to help write tp_traverse functions. 347 * To use this macro, the tp_traverse function must name its arguments 348 * "visit" and "arg". This is intended to keep tp_traverse functions 349 * looking as much alike as possible. 350 */ 351 #define Py_VISIT(op) \ 352 do { \ 353 if (op) { \ 354 int vret = visit((PyObject *)(op), arg); \ 355 if (vret) \ 356 return vret; \ 357 } \ 358 } while (0) 359 360 361 /* Test if a type supports weak references */ 362 #define PyType_SUPPORTS_WEAKREFS(t) ((t)->tp_weaklistoffset > 0) 363 364 #define PyObject_GET_WEAKREFS_LISTPTR(o) \ 365 ((PyObject **) (((char *) (o)) + Py_TYPE(o)->tp_weaklistoffset)) 366 367 #ifdef __cplusplus 368 } 369 #endif 370 #endif /* !Py_OBJIMPL_H */ 371