1 #ifndef Py_CPYTHON_OBJECT_H
2 #  error "this header file must not be included directly"
3 #endif
4 
5 #ifdef __cplusplus
6 extern "C" {
7 #endif
8 
9 /********************* String Literals ****************************************/
10 /* This structure helps managing static strings. The basic usage goes like this:
11    Instead of doing
12 
13        r = PyObject_CallMethod(o, "foo", "args", ...);
14 
15    do
16 
17        _Py_IDENTIFIER(foo);
18        ...
19        r = _PyObject_CallMethodId(o, &PyId_foo, "args", ...);
20 
21    PyId_foo is a static variable, either on block level or file level. On first
22    usage, the string "foo" is interned, and the structures are linked. On interpreter
23    shutdown, all strings are released (through _PyUnicode_ClearStaticStrings).
24 
25    Alternatively, _Py_static_string allows choosing the variable name.
26    _PyUnicode_FromId returns a borrowed reference to the interned string.
27    _PyObject_{Get,Set,Has}AttrId are __getattr__ versions using _Py_Identifier*.
28 */
29 typedef struct _Py_Identifier {
30     struct _Py_Identifier *next;
31     const char* string;
32     PyObject *object;
33 } _Py_Identifier;
34 
35 #define _Py_static_string_init(value) { .next = NULL, .string = value, .object = NULL }
36 #define _Py_static_string(varname, value)  static _Py_Identifier varname = _Py_static_string_init(value)
37 #define _Py_IDENTIFIER(varname) _Py_static_string(PyId_##varname, #varname)
38 
39 /* buffer interface */
40 typedef struct bufferinfo {
41     void *buf;
42     PyObject *obj;        /* owned reference */
43     Py_ssize_t len;
44     Py_ssize_t itemsize;  /* This is Py_ssize_t so it can be
45                              pointed to by strides in simple case.*/
46     int readonly;
47     int ndim;
48     char *format;
49     Py_ssize_t *shape;
50     Py_ssize_t *strides;
51     Py_ssize_t *suboffsets;
52     void *internal;
53 } Py_buffer;
54 
55 typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
56 typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
57 
58 typedef PyObject *(*vectorcallfunc)(PyObject *callable, PyObject *const *args,
59                                     size_t nargsf, PyObject *kwnames);
60 
61 /* Maximum number of dimensions */
62 #define PyBUF_MAX_NDIM 64
63 
64 /* Flags for getting buffers */
65 #define PyBUF_SIMPLE 0
66 #define PyBUF_WRITABLE 0x0001
67 /*  we used to include an E, backwards compatible alias  */
68 #define PyBUF_WRITEABLE PyBUF_WRITABLE
69 #define PyBUF_FORMAT 0x0004
70 #define PyBUF_ND 0x0008
71 #define PyBUF_STRIDES (0x0010 | PyBUF_ND)
72 #define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
73 #define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
74 #define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
75 #define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
76 
77 #define PyBUF_CONTIG (PyBUF_ND | PyBUF_WRITABLE)
78 #define PyBUF_CONTIG_RO (PyBUF_ND)
79 
80 #define PyBUF_STRIDED (PyBUF_STRIDES | PyBUF_WRITABLE)
81 #define PyBUF_STRIDED_RO (PyBUF_STRIDES)
82 
83 #define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_WRITABLE | PyBUF_FORMAT)
84 #define PyBUF_RECORDS_RO (PyBUF_STRIDES | PyBUF_FORMAT)
85 
86 #define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_WRITABLE | PyBUF_FORMAT)
87 #define PyBUF_FULL_RO (PyBUF_INDIRECT | PyBUF_FORMAT)
88 
89 
90 #define PyBUF_READ  0x100
91 #define PyBUF_WRITE 0x200
92 /* End buffer interface */
93 
94 
95 typedef struct {
96     /* Number implementations must check *both*
97        arguments for proper type and implement the necessary conversions
98        in the slot functions themselves. */
99 
100     binaryfunc nb_add;
101     binaryfunc nb_subtract;
102     binaryfunc nb_multiply;
103     binaryfunc nb_remainder;
104     binaryfunc nb_divmod;
105     ternaryfunc nb_power;
106     unaryfunc nb_negative;
107     unaryfunc nb_positive;
108     unaryfunc nb_absolute;
109     inquiry nb_bool;
110     unaryfunc nb_invert;
111     binaryfunc nb_lshift;
112     binaryfunc nb_rshift;
113     binaryfunc nb_and;
114     binaryfunc nb_xor;
115     binaryfunc nb_or;
116     unaryfunc nb_int;
117     void *nb_reserved;  /* the slot formerly known as nb_long */
118     unaryfunc nb_float;
119 
120     binaryfunc nb_inplace_add;
121     binaryfunc nb_inplace_subtract;
122     binaryfunc nb_inplace_multiply;
123     binaryfunc nb_inplace_remainder;
124     ternaryfunc nb_inplace_power;
125     binaryfunc nb_inplace_lshift;
126     binaryfunc nb_inplace_rshift;
127     binaryfunc nb_inplace_and;
128     binaryfunc nb_inplace_xor;
129     binaryfunc nb_inplace_or;
130 
131     binaryfunc nb_floor_divide;
132     binaryfunc nb_true_divide;
133     binaryfunc nb_inplace_floor_divide;
134     binaryfunc nb_inplace_true_divide;
135 
136     unaryfunc nb_index;
137 
138     binaryfunc nb_matrix_multiply;
139     binaryfunc nb_inplace_matrix_multiply;
140 } PyNumberMethods;
141 
142 typedef struct {
143     lenfunc sq_length;
144     binaryfunc sq_concat;
145     ssizeargfunc sq_repeat;
146     ssizeargfunc sq_item;
147     void *was_sq_slice;
148     ssizeobjargproc sq_ass_item;
149     void *was_sq_ass_slice;
150     objobjproc sq_contains;
151 
152     binaryfunc sq_inplace_concat;
153     ssizeargfunc sq_inplace_repeat;
154 } PySequenceMethods;
155 
156 typedef struct {
157     lenfunc mp_length;
158     binaryfunc mp_subscript;
159     objobjargproc mp_ass_subscript;
160 } PyMappingMethods;
161 
162 typedef struct {
163     unaryfunc am_await;
164     unaryfunc am_aiter;
165     unaryfunc am_anext;
166 } PyAsyncMethods;
167 
168 typedef struct {
169      getbufferproc bf_getbuffer;
170      releasebufferproc bf_releasebuffer;
171 } PyBufferProcs;
172 
173 /* Allow printfunc in the tp_vectorcall_offset slot for
174  * backwards-compatibility */
175 typedef Py_ssize_t printfunc;
176 
177 typedef struct _typeobject {
178     PyObject_VAR_HEAD
179     const char *tp_name; /* For printing, in format "<module>.<name>" */
180     Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
181 
182     /* Methods to implement standard operations */
183 
184     destructor tp_dealloc;
185     Py_ssize_t tp_vectorcall_offset;
186     getattrfunc tp_getattr;
187     setattrfunc tp_setattr;
188     PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
189                                     or tp_reserved (Python 3) */
190     reprfunc tp_repr;
191 
192     /* Method suites for standard classes */
193 
194     PyNumberMethods *tp_as_number;
195     PySequenceMethods *tp_as_sequence;
196     PyMappingMethods *tp_as_mapping;
197 
198     /* More standard operations (here for binary compatibility) */
199 
200     hashfunc tp_hash;
201     ternaryfunc tp_call;
202     reprfunc tp_str;
203     getattrofunc tp_getattro;
204     setattrofunc tp_setattro;
205 
206     /* Functions to access object as input/output buffer */
207     PyBufferProcs *tp_as_buffer;
208 
209     /* Flags to define presence of optional/expanded features */
210     unsigned long tp_flags;
211 
212     const char *tp_doc; /* Documentation string */
213 
214     /* Assigned meaning in release 2.0 */
215     /* call function for all accessible objects */
216     traverseproc tp_traverse;
217 
218     /* delete references to contained objects */
219     inquiry tp_clear;
220 
221     /* Assigned meaning in release 2.1 */
222     /* rich comparisons */
223     richcmpfunc tp_richcompare;
224 
225     /* weak reference enabler */
226     Py_ssize_t tp_weaklistoffset;
227 
228     /* Iterators */
229     getiterfunc tp_iter;
230     iternextfunc tp_iternext;
231 
232     /* Attribute descriptor and subclassing stuff */
233     struct PyMethodDef *tp_methods;
234     struct PyMemberDef *tp_members;
235     struct PyGetSetDef *tp_getset;
236     struct _typeobject *tp_base;
237     PyObject *tp_dict;
238     descrgetfunc tp_descr_get;
239     descrsetfunc tp_descr_set;
240     Py_ssize_t tp_dictoffset;
241     initproc tp_init;
242     allocfunc tp_alloc;
243     newfunc tp_new;
244     freefunc tp_free; /* Low-level free-memory routine */
245     inquiry tp_is_gc; /* For PyObject_IS_GC */
246     PyObject *tp_bases;
247     PyObject *tp_mro; /* method resolution order */
248     PyObject *tp_cache;
249     PyObject *tp_subclasses;
250     PyObject *tp_weaklist;
251     destructor tp_del;
252 
253     /* Type attribute cache version tag. Added in version 2.6 */
254     unsigned int tp_version_tag;
255 
256     destructor tp_finalize;
257     vectorcallfunc tp_vectorcall;
258 
259     /* bpo-37250: kept for backwards compatibility in CPython 3.8 only */
260     Py_DEPRECATED(3.8) int (*tp_print)(PyObject *, FILE *, int);
261 
262 #ifdef COUNT_ALLOCS
263     /* these must be last and never explicitly initialized */
264     Py_ssize_t tp_allocs;
265     Py_ssize_t tp_frees;
266     Py_ssize_t tp_maxalloc;
267     struct _typeobject *tp_prev;
268     struct _typeobject *tp_next;
269 #endif
270 } PyTypeObject;
271 
272 /* The *real* layout of a type object when allocated on the heap */
273 typedef struct _heaptypeobject {
274     /* Note: there's a dependency on the order of these members
275        in slotptr() in typeobject.c . */
276     PyTypeObject ht_type;
277     PyAsyncMethods as_async;
278     PyNumberMethods as_number;
279     PyMappingMethods as_mapping;
280     PySequenceMethods as_sequence; /* as_sequence comes after as_mapping,
281                                       so that the mapping wins when both
282                                       the mapping and the sequence define
283                                       a given operator (e.g. __getitem__).
284                                       see add_operators() in typeobject.c . */
285     PyBufferProcs as_buffer;
286     PyObject *ht_name, *ht_slots, *ht_qualname;
287     struct _dictkeysobject *ht_cached_keys;
288     /* here are optional user slots, followed by the members. */
289 } PyHeapTypeObject;
290 
291 /* access macro to the members which are floating "behind" the object */
292 #define PyHeapType_GET_MEMBERS(etype) \
293     ((PyMemberDef *)(((char *)etype) + Py_TYPE(etype)->tp_basicsize))
294 
295 PyAPI_FUNC(const char *) _PyType_Name(PyTypeObject *);
296 PyAPI_FUNC(PyObject *) _PyType_Lookup(PyTypeObject *, PyObject *);
297 PyAPI_FUNC(PyObject *) _PyType_LookupId(PyTypeObject *, _Py_Identifier *);
298 PyAPI_FUNC(PyObject *) _PyObject_LookupSpecial(PyObject *, _Py_Identifier *);
299 PyAPI_FUNC(PyTypeObject *) _PyType_CalculateMetaclass(PyTypeObject *, PyObject *);
300 PyAPI_FUNC(PyObject *) _PyType_GetDocFromInternalDoc(const char *, const char *);
301 PyAPI_FUNC(PyObject *) _PyType_GetTextSignatureFromInternalDoc(const char *, const char *);
302 
303 struct _Py_Identifier;
304 PyAPI_FUNC(int) PyObject_Print(PyObject *, FILE *, int);
305 PyAPI_FUNC(void) _Py_BreakPoint(void);
306 PyAPI_FUNC(void) _PyObject_Dump(PyObject *);
307 PyAPI_FUNC(int) _PyObject_IsFreed(PyObject *);
308 
309 PyAPI_FUNC(int) _PyObject_IsAbstract(PyObject *);
310 PyAPI_FUNC(PyObject *) _PyObject_GetAttrId(PyObject *, struct _Py_Identifier *);
311 PyAPI_FUNC(int) _PyObject_SetAttrId(PyObject *, struct _Py_Identifier *, PyObject *);
312 PyAPI_FUNC(int) _PyObject_HasAttrId(PyObject *, struct _Py_Identifier *);
313 /* Replacements of PyObject_GetAttr() and _PyObject_GetAttrId() which
314    don't raise AttributeError.
315 
316    Return 1 and set *result != NULL if an attribute is found.
317    Return 0 and set *result == NULL if an attribute is not found;
318    an AttributeError is silenced.
319    Return -1 and set *result == NULL if an error other than AttributeError
320    is raised.
321 */
322 PyAPI_FUNC(int) _PyObject_LookupAttr(PyObject *, PyObject *, PyObject **);
323 PyAPI_FUNC(int) _PyObject_LookupAttrId(PyObject *, struct _Py_Identifier *, PyObject **);
324 PyAPI_FUNC(PyObject **) _PyObject_GetDictPtr(PyObject *);
325 PyAPI_FUNC(PyObject *) _PyObject_NextNotImplemented(PyObject *);
326 PyAPI_FUNC(void) PyObject_CallFinalizer(PyObject *);
327 PyAPI_FUNC(int) PyObject_CallFinalizerFromDealloc(PyObject *);
328 
329 /* Same as PyObject_Generic{Get,Set}Attr, but passing the attributes
330    dict as the last parameter. */
331 PyAPI_FUNC(PyObject *)
332 _PyObject_GenericGetAttrWithDict(PyObject *, PyObject *, PyObject *, int);
333 PyAPI_FUNC(int)
334 _PyObject_GenericSetAttrWithDict(PyObject *, PyObject *,
335                                  PyObject *, PyObject *);
336 
337 #define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)
338 
_Py_Dealloc_inline(PyObject * op)339 static inline void _Py_Dealloc_inline(PyObject *op)
340 {
341     destructor dealloc = Py_TYPE(op)->tp_dealloc;
342 #ifdef Py_TRACE_REFS
343     _Py_ForgetReference(op);
344 #else
345     _Py_INC_TPFREES(op);
346 #endif
347     (*dealloc)(op);
348 }
349 #define _Py_Dealloc(op) _Py_Dealloc_inline(op)
350 
351 
352 /* Safely decref `op` and set `op` to `op2`.
353  *
354  * As in case of Py_CLEAR "the obvious" code can be deadly:
355  *
356  *     Py_DECREF(op);
357  *     op = op2;
358  *
359  * The safe way is:
360  *
361  *      Py_SETREF(op, op2);
362  *
363  * That arranges to set `op` to `op2` _before_ decref'ing, so that any code
364  * triggered as a side-effect of `op` getting torn down no longer believes
365  * `op` points to a valid object.
366  *
367  * Py_XSETREF is a variant of Py_SETREF that uses Py_XDECREF instead of
368  * Py_DECREF.
369  */
370 
371 #define Py_SETREF(op, op2)                      \
372     do {                                        \
373         PyObject *_py_tmp = _PyObject_CAST(op); \
374         (op) = (op2);                           \
375         Py_DECREF(_py_tmp);                     \
376     } while (0)
377 
378 #define Py_XSETREF(op, op2)                     \
379     do {                                        \
380         PyObject *_py_tmp = _PyObject_CAST(op); \
381         (op) = (op2);                           \
382         Py_XDECREF(_py_tmp);                    \
383     } while (0)
384 
385 
386 PyAPI_DATA(PyTypeObject) _PyNone_Type;
387 PyAPI_DATA(PyTypeObject) _PyNotImplemented_Type;
388 
389 /* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE.
390  * Defined in object.c.
391  */
392 PyAPI_DATA(int) _Py_SwappedOp[];
393 
394 /* This is the old private API, invoked by the macros before 3.2.4.
395    Kept for binary compatibility of extensions using the stable ABI. */
396 PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);
397 PyAPI_FUNC(void) _PyTrash_destroy_chain(void);
398 
399 PyAPI_FUNC(void)
400 _PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks,
401                        size_t sizeof_block);
402 PyAPI_FUNC(void)
403 _PyObject_DebugTypeStats(FILE *out);
404 
405 /* Define a pair of assertion macros:
406    _PyObject_ASSERT_FROM(), _PyObject_ASSERT_WITH_MSG() and _PyObject_ASSERT().
407 
408    These work like the regular C assert(), in that they will abort the
409    process with a message on stderr if the given condition fails to hold,
410    but compile away to nothing if NDEBUG is defined.
411 
412    However, before aborting, Python will also try to call _PyObject_Dump() on
413    the given object.  This may be of use when investigating bugs in which a
414    particular object is corrupt (e.g. buggy a tp_visit method in an extension
415    module breaking the garbage collector), to help locate the broken objects.
416 
417    The WITH_MSG variant allows you to supply an additional message that Python
418    will attempt to print to stderr, after the object dump. */
419 #ifdef NDEBUG
420    /* No debugging: compile away the assertions: */
421 #  define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
422     ((void)0)
423 #else
424    /* With debugging: generate checks: */
425 #  define _PyObject_ASSERT_FROM(obj, expr, msg, filename, lineno, func) \
426     ((expr) \
427       ? (void)(0) \
428       : _PyObject_AssertFailed((obj), Py_STRINGIFY(expr), \
429                                (msg), (filename), (lineno), (func)))
430 #endif
431 
432 #define _PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
433     _PyObject_ASSERT_FROM(obj, expr, msg, __FILE__, __LINE__, __func__)
434 #define _PyObject_ASSERT(obj, expr) \
435     _PyObject_ASSERT_WITH_MSG(obj, expr, NULL)
436 
437 #define _PyObject_ASSERT_FAILED_MSG(obj, msg) \
438     _PyObject_AssertFailed((obj), NULL, (msg), __FILE__, __LINE__, __func__)
439 
440 /* Declare and define _PyObject_AssertFailed() even when NDEBUG is defined,
441    to avoid causing compiler/linker errors when building extensions without
442    NDEBUG against a Python built with NDEBUG defined.
443 
444    msg, expr and function can be NULL. */
445 PyAPI_FUNC(void) _PyObject_AssertFailed(
446     PyObject *obj,
447     const char *expr,
448     const char *msg,
449     const char *file,
450     int line,
451     const char *function);
452 
453 /* Check if an object is consistent. For example, ensure that the reference
454    counter is greater than or equal to 1, and ensure that ob_type is not NULL.
455 
456    Call _PyObject_AssertFailed() if the object is inconsistent.
457 
458    If check_content is zero, only check header fields: reduce the overhead.
459 
460    The function always return 1. The return value is just here to be able to
461    write:
462 
463    assert(_PyObject_CheckConsistency(obj, 1)); */
464 PyAPI_FUNC(int) _PyObject_CheckConsistency(
465     PyObject *op,
466     int check_content);
467 
468 #ifdef __cplusplus
469 }
470 #endif
471