cinap_lenrekadd hg and python4bb9e2215 years agoHistory
868 lines · 31.5 KB · C
RawDownload
/* Set if the type is 'ready' -- fully initialized */#define Py_TPFLAGS_READY (1L<<12) /* Set while the type is being 'readied', to prevent recursive ready calls */#define Py_TPFLAGS_READYING (1L<<13) /* Objects support garbage collection (see objimp.h) */#define Py_TPFLAGS_HAVE_GC (1L<<14) /* These two bits are preserved for Stackless Python, next after this is 17 */#ifdef STACKLESS#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION (3L<<15)#else#define Py_TPFLAGS_HAVE_STACKLESS_EXTENSION 0#endif /* Objects support nb_index in PyNumberMethods */#define Py_TPFLAGS_HAVE_INDEX (1L<<17) #define Py_TPFLAGS_DEFAULT  ( \                             Py_TPFLAGS_HAVE_GETCHARBUFFER | \                             Py_TPFLAGS_HAVE_SEQUENCE_IN | \                             Py_TPFLAGS_HAVE_INPLACEOPS | \                             Py_TPFLAGS_HAVE_RICHCOMPARE | \                             Py_TPFLAGS_HAVE_WEAKREFS | \                             Py_TPFLAGS_HAVE_ITER | \                             Py_TPFLAGS_HAVE_CLASS | \                             Py_TPFLAGS_HAVE_STACKLESS_EXTENSION | \                             Py_TPFLAGS_HAVE_INDEX | \                            0) #define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)  /*The macros Py_INCREF(op) and Py_DECREF(op) are used to increment or decrementreference counts.  Py_DECREF calls the object's deallocator function whenthe refcount falls to 0; forobjects that don't contain references to other objects or heap memorythis can be the standard function free().  Both macros can be usedwherever a void expression is allowed.  The argument must not be aNIL pointer.  If it may be NIL, use Py_XINCREF/Py_XDECREF instead.The macro _Py_NewReference(op) initialize reference counts to 1, andin special builds (Py_REF_DEBUG, Py_TRACE_REFS) performs additionalbookkeeping appropriate to the special build. We assume that the reference count field can never overflow; this canbe proven when the size of the field is the same as the pointer size, sowe ignore the possibility.  Provided a C int is at least 32 bits (whichis implicitly assumed in many parts of this code), that's enough forabout 2**31 references to an object. XXX The following became out of date in Python 2.2, but I'm not sureXXX what the full truth is now.  Certainly, heap-allocated type objectsXXX can and should be deallocated.Type objects should never be deallocated; the type pointer in an objectis not considered to be a reference to the type object, to savecomplications in the deallocation function.  (This is actually adecision that's up to the implementer of each new type so if you want,you can count such references to the type object.) *** WARNING*** The Py_DECREF macro must have a side-effect-free argumentsince it may evaluate its argument multiple times.  (The alternativewould be to mace it a proper function or assign it to a global temporaryvariable first, both of which are slower; and in a multi-threadedenvironment the global variable trick is not safe.)*/ /* First define a pile of simple helper macros, one set per special * build symbol.  These either expand to the obvious things, or to * nothing at all when the special mode isn't in effect.  The main * macros can later be defined just once then, yet expand to different * things depending on which special build options are and aren't in effect. * Trust me <wink>:  while painful, this is 20x easier to understand than, * e.g, defining _Py_NewReference five different times in a maze of nested * #ifdefs (we used to do that -- it was impenetrable). */#ifdef Py_REF_DEBUGPyAPI_DATA(Py_ssize_t) _Py_RefTotal;PyAPI_FUNC(void) _Py_NegativeRefcount(const char *fname,					    int lineno, PyObject *op);PyAPI_FUNC(PyObject *) _PyDict_Dummy(void);PyAPI_FUNC(PyObject *) _PySet_Dummy(void);PyAPI_FUNC(Py_ssize_t) _Py_GetRefTotal(void);#define _Py_INC_REFTOTAL	_Py_RefTotal++#define _Py_DEC_REFTOTAL	_Py_RefTotal--#define _Py_REF_DEBUG_COMMA	,#define _Py_CHECK_REFCNT(OP)					\{	if ((OP)->ob_refcnt < 0)				\		_Py_NegativeRefcount(__FILE__, __LINE__,	\				     (PyObject *)(OP));		\}#else#define _Py_INC_REFTOTAL#define _Py_DEC_REFTOTAL#define _Py_REF_DEBUG_COMMA#define _Py_CHECK_REFCNT(OP)	/* a semicolon */;#endif /* Py_REF_DEBUG */ #ifdef COUNT_ALLOCSPyAPI_FUNC(void) inc_count(PyTypeObject *);PyAPI_FUNC(void) dec_count(PyTypeObject *);#define _Py_INC_TPALLOCS(OP)	inc_count((OP)->ob_type)#define _Py_INC_TPFREES(OP)	dec_count((OP)->ob_type)#define _Py_DEC_TPFREES(OP)	(OP)->ob_type->tp_frees--#define _Py_COUNT_ALLOCS_COMMA	,#else#define _Py_INC_TPALLOCS(OP)#define _Py_INC_TPFREES(OP)#define _Py_DEC_TPFREES(OP)#define _Py_COUNT_ALLOCS_COMMA#endif /* COUNT_ALLOCS */ #ifdef Py_TRACE_REFS/* Py_TRACE_REFS is such major surgery that we call external routines. */PyAPI_FUNC(void) _Py_NewReference(PyObject *);PyAPI_FUNC(void) _Py_ForgetReference(PyObject *);PyAPI_FUNC(void) _Py_Dealloc(PyObject *);PyAPI_FUNC(void) _Py_PrintReferences(FILE *);PyAPI_FUNC(void) _Py_PrintReferenceAddresses(FILE *);PyAPI_FUNC(void) _Py_AddToAllObjects(PyObject *, int force); #else/* Without Py_TRACE_REFS, there's little enough to do that we expand code * inline. */#define _Py_NewReference(op) (				\	_Py_INC_TPALLOCS(op) _Py_COUNT_ALLOCS_COMMA	\	_Py_INC_REFTOTAL  _Py_REF_DEBUG_COMMA		\	(op)->ob_refcnt = 1) #define _Py_ForgetReference(op) _Py_INC_TPFREES(op) #define _Py_Dealloc(op) (				\	_Py_INC_TPFREES(op) _Py_COUNT_ALLOCS_COMMA	\	(*(op)->ob_type->tp_dealloc)((PyObject *)(op)))#endif /* !Py_TRACE_REFS */ #define Py_INCREF(op) (				\	_Py_INC_REFTOTAL  _Py_REF_DEBUG_COMMA	\	(op)->ob_refcnt++) #define Py_DECREF(op)					\	if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA	\	    --(op)->ob_refcnt != 0)			\		_Py_CHECK_REFCNT(op)			\	else						\		_Py_Dealloc((PyObject *)(op)) /* Safely decref `op` and set `op` to NULL, especially useful in tp_clear * and tp_dealloc implementatons. * * Note that "the obvious" code can be deadly: * *     Py_XDECREF(op); *     op = NULL; * * Typically, `op` is something like self->containee, and `self` is done * using its `containee` member.  In the code sequence above, suppose * `containee` is non-NULL with a refcount of 1.  Its refcount falls to * 0 on the first line, which can trigger an arbitrary amount of code, * possibly including finalizers (like __del__ methods or weakref callbacks) * coded in Python, which in turn can release the GIL and allow other threads * to run, etc.  Such code may even invoke methods of `self` again, or cause * cyclic gc to trigger, but-- oops! --self->containee still points to the * object being torn down, and it may be in an insane state while being torn * down.  This has in fact been a rich historic source of miserable (rare & * hard-to-diagnose) segfaulting (and other) bugs. * * The safe way is: * *      Py_CLEAR(op); * * That arranges to set `op` to NULL _before_ decref'ing, so that any code * triggered as a side-effect of `op` getting torn down no longer believes * `op` points to a valid object. * * There are cases where it's safe to use the naive code, but they're brittle. * For example, if `op` points to a Python integer, you know that destroying * one of those can't cause problems -- but in part that relies on that * Python integers aren't currently weakly referencable.  Best practice is * to use Py_CLEAR() even if you can't think of a reason for why you need to. */#define Py_CLEAR(op)				\        do {                            	\                if (op) {			\                        PyObject *tmp = (PyObject *)(op);	\                        (op) = NULL;		\                        Py_DECREF(tmp);		\                }				\        } while (0) /* Macros to use in case the object pointer may be NULL: */#define Py_XINCREF(op) if ((op) == NULL) ; else Py_INCREF(op)#define Py_XDECREF(op) if ((op) == NULL) ; else Py_DECREF(op) /*These are provided as conveniences to Python runtime embedders, so thatthey can have object code that is not dependent on Python compilation flags.*/PyAPI_FUNC(void) Py_IncRef(PyObject *);PyAPI_FUNC(void) Py_DecRef(PyObject *); /*_Py_NoneStruct is an object of undefined type which can be used in contextswhere NULL (nil) is not suitable (since NULL often means 'error'). Don't forget to apply Py_INCREF() when returning this value!!!*/PyAPI_DATA(PyObject) _Py_NoneStruct; /* Don't use this directly */#define Py_None (&_Py_NoneStruct) /* Macro for returning Py_None from a function */#define Py_RETURN_NONE return Py_INCREF(Py_None), Py_None /*Py_NotImplemented is a singleton used to signal that an operation isnot implemented for a given type combination.*/PyAPI_DATA(PyObject) _Py_NotImplementedStruct; /* Don't use this directly */#define Py_NotImplemented (&_Py_NotImplementedStruct) /* Rich comparison opcodes */#define Py_LT 0#define Py_LE 1#define Py_EQ 2#define Py_NE 3#define Py_GT 4#define Py_GE 5 /* Maps Py_LT to Py_GT, ..., Py_GE to Py_LE. * Defined in object.c. */PyAPI_DATA(int) _Py_SwappedOp[]; /*Define staticforward and statichere for source compatibility with oldC extensions. The staticforward define was needed to support certain broken Ccompilers (notably SCO ODT 3.0, perhaps early AIX as well) botched thestatic keyword when it was used with a forward declaration of a staticinitialized structure.  Standard C allows the forward declaration withstatic, and we've decided to stop catering to broken C compilers.(In fact, we expect that the compilers are all fixed eight years later.)*/ #define staticforward static#define statichere static  /*More conventions================ Argument Checking----------------- Functions that take objects as arguments normally don't check for nilarguments, but they do check the type of the argument, and return anerror if the function doesn't apply to the type. Failure Modes------------- Functions may fail for a variety of reasons, including running out ofmemory.  This is communicated to the caller in two ways: an error stringis set (see errors.h), and the function result differs: functions thatnormally return a pointer return NULL for failure, functions returningan integer return -1 (which could be a legal return value too!), andother functions return 0 for success and -1 for failure.Callers should always check for errors before using the result.  Ifan error was set, the caller must either explicitly clear it, or passthe error on to its caller. Reference Counts---------------- It takes a while to get used to the proper usage of reference counts. Functions that create an object set the reference count to 1; such newobjects must be stored somewhere or destroyed again with Py_DECREF().Some functions that 'store' objects, such as PyTuple_SetItem() andPyList_SetItem(),don't increment the reference count of the object, since the mostfrequent use is to store a fresh object.  Functions that 'retrieve'objects, such as PyTuple_GetItem() and PyDict_GetItemString(), alsodon't incrementthe reference count, since most frequently the object is only looked atquickly.  Thus, to retrieve an object and store it again, the callermust call Py_INCREF() explicitly. NOTE: functions that 'consume' a reference count, likePyList_SetItem(), consume the reference even if the object wasn'tsuccessfully stored, to simplify error handling. It seems attractive to make other functions that take an object asargument consume a reference count; however, this may quickly getconfusing (even the current practice is already confusing).  Considerit carefully, it may save lots of calls to Py_INCREF() and Py_DECREF() attimes.*/  /* Trashcan mechanism, thanks to Christian Tismer. When deallocating a container object, it's possible to trigger an unboundedchain of deallocations, as each Py_DECREF in turn drops the refcount on "thenext" object in the chain to 0.  This can easily lead to stack faults, andespecially in threads (which typically have less stack space to work with). A container object that participates in cyclic gc can avoid this bybracketing the body of its tp_dealloc function with a pair of macros: static voidmytype_dealloc(mytype *p){        ... declarations go here ...  	PyObject_GC_UnTrack(p);	   // must untrack first	Py_TRASHCAN_SAFE_BEGIN(p)	... The body of the deallocator goes here, including all calls ...	... to Py_DECREF on contained objects.                         ...	Py_TRASHCAN_SAFE_END(p)} CAUTION:  Never return from the middle of the body!  If the body needs to"get out early", put a label immediately before the Py_TRASHCAN_SAFE_ENDcall, and goto it.  Else the call-depth counter (see below) will stayabove 0 forever, and the trashcan will never get emptied. How it works:  The BEGIN macro increments a call-depth counter.  So longas this counter is small, the body of the deallocator is run directly withoutfurther ado.  But if the counter gets large, it instead adds p to a list ofobjects to be deallocated later, skips the body of the deallocator, andresumes execution after the END macro.  The tp_dealloc routine then returnswithout deallocating anything (and so unbounded call-stack depth is avoided). When the call stack finishes unwinding again, code generated by the END macronotices this, and calls another routine to deallocate all the objects thatmay have been added to the list of deferred deallocations.  In effect, achain of N deallocations is broken into N / PyTrash_UNWIND_LEVEL pieces,with the call stack never exceeding a depth of PyTrash_UNWIND_LEVEL.*/ PyAPI_FUNC(void) _PyTrash_deposit_object(PyObject*);PyAPI_FUNC(void) _PyTrash_destroy_chain(void);PyAPI_DATA(int) _PyTrash_delete_nesting;PyAPI_DATA(PyObject *) _PyTrash_delete_later; #define PyTrash_UNWIND_LEVEL 50 #define Py_TRASHCAN_SAFE_BEGIN(op) \	if (_PyTrash_delete_nesting < PyTrash_UNWIND_LEVEL) { \		++_PyTrash_delete_nesting;		/* The body of the deallocator is here. */#define Py_TRASHCAN_SAFE_END(op) \		--_PyTrash_delete_nesting; \		if (_PyTrash_delete_later && _PyTrash_delete_nesting <= 0) \			_PyTrash_destroy_chain(); \	} \	else \		_PyTrash_deposit_object((PyObject*)op); #ifdef __cplusplus}#endif#endif /* !Py_OBJECT_H */

Lines 501–868 of 868. Previous lines