+++ /dev/null
-/*\r
-\r
- Reference Cycle Garbage Collection\r
- ==================================\r
-\r
- Neil Schemenauer <nas@arctrix.com>\r
-\r
- Based on a post on the python-dev list. Ideas from Guido van Rossum,\r
- Eric Tiedemann, and various others.\r
-\r
- http://www.arctrix.com/nas/python/gc/\r
- http://www.python.org/pipermail/python-dev/2000-March/003869.html\r
- http://www.python.org/pipermail/python-dev/2000-March/004010.html\r
- http://www.python.org/pipermail/python-dev/2000-March/004022.html\r
-\r
- For a highlevel view of the collection process, read the collect\r
- function.\r
-\r
-*/\r
-\r
-#include "Python.h"\r
-#include "frameobject.h" /* for PyFrame_ClearFreeList */\r
-\r
-/* Get an object's GC head */\r
-#define AS_GC(o) ((PyGC_Head *)(o)-1)\r
-\r
-/* Get the object given the GC head */\r
-#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))\r
-\r
-/*** Global GC state ***/\r
-\r
-struct gc_generation {\r
- PyGC_Head head;\r
- int threshold; /* collection threshold */\r
- int count; /* count of allocations or collections of younger\r
- generations */\r
-};\r
-\r
-#define NUM_GENERATIONS 3\r
-#define GEN_HEAD(n) (&generations[n].head)\r
-\r
-/* linked lists of container objects */\r
-static struct gc_generation generations[NUM_GENERATIONS] = {\r
- /* PyGC_Head, threshold, count */\r
- {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},\r
- {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},\r
- {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},\r
-};\r
-\r
-PyGC_Head *_PyGC_generation0 = GEN_HEAD(0);\r
-\r
-static int enabled = 1; /* automatic collection enabled? */\r
-\r
-/* true if we are currently running the collector */\r
-static int collecting = 0;\r
-\r
-/* list of uncollectable objects */\r
-static PyObject *garbage = NULL;\r
-\r
-/* Python string to use if unhandled exception occurs */\r
-static PyObject *gc_str = NULL;\r
-\r
-/* Python string used to look for __del__ attribute. */\r
-static PyObject *delstr = NULL;\r
-\r
-/* This is the number of objects who survived the last full collection. It\r
- approximates the number of long lived objects tracked by the GC.\r
-\r
- (by "full collection", we mean a collection of the oldest generation).\r
-*/\r
-static Py_ssize_t long_lived_total = 0;\r
-\r
-/* This is the number of objects who survived all "non-full" collections,\r
- and are awaiting to undergo a full collection for the first time.\r
-\r
-*/\r
-static Py_ssize_t long_lived_pending = 0;\r
-\r
-/*\r
- NOTE: about the counting of long-lived objects.\r
-\r
- To limit the cost of garbage collection, there are two strategies;\r
- - make each collection faster, e.g. by scanning fewer objects\r
- - do less collections\r
- This heuristic is about the latter strategy.\r
-\r
- In addition to the various configurable thresholds, we only trigger a\r
- full collection if the ratio\r
- long_lived_pending / long_lived_total\r
- is above a given value (hardwired to 25%).\r
-\r
- The reason is that, while "non-full" collections (i.e., collections of\r
- the young and middle generations) will always examine roughly the same\r
- number of objects -- determined by the aforementioned thresholds --,\r
- the cost of a full collection is proportional to the total number of\r
- long-lived objects, which is virtually unbounded.\r
-\r
- Indeed, it has been remarked that doing a full collection every\r
- <constant number> of object creations entails a dramatic performance\r
- degradation in workloads which consist in creating and storing lots of\r
- long-lived objects (e.g. building a large list of GC-tracked objects would\r
- show quadratic performance, instead of linear as expected: see issue #4074).\r
-\r
- Using the above ratio, instead, yields amortized linear performance in\r
- the total number of objects (the effect of which can be summarized\r
- thusly: "each full garbage collection is more and more costly as the\r
- number of objects grows, but we do fewer and fewer of them").\r
-\r
- This heuristic was suggested by Martin von Löwis on python-dev in\r
- June 2008. His original analysis and proposal can be found at:\r
- http://mail.python.org/pipermail/python-dev/2008-June/080579.html\r
-*/\r
-\r
-/*\r
- NOTE: about untracking of mutable objects.\r
-\r
- Certain types of container cannot participate in a reference cycle, and\r
- so do not need to be tracked by the garbage collector. Untracking these\r
- objects reduces the cost of garbage collections. However, determining\r
- which objects may be untracked is not free, and the costs must be\r
- weighed against the benefits for garbage collection.\r
-\r
- There are two possible strategies for when to untrack a container:\r
-\r
- i) When the container is created.\r
- ii) When the container is examined by the garbage collector.\r
-\r
- Tuples containing only immutable objects (integers, strings etc, and\r
- recursively, tuples of immutable objects) do not need to be tracked.\r
- The interpreter creates a large number of tuples, many of which will\r
- not survive until garbage collection. It is therefore not worthwhile\r
- to untrack eligible tuples at creation time.\r
-\r
- Instead, all tuples except the empty tuple are tracked when created.\r
- During garbage collection it is determined whether any surviving tuples\r
- can be untracked. A tuple can be untracked if all of its contents are\r
- already not tracked. Tuples are examined for untracking in all garbage\r
- collection cycles. It may take more than one cycle to untrack a tuple.\r
-\r
- Dictionaries containing only immutable objects also do not need to be\r
- tracked. Dictionaries are untracked when created. If a tracked item is\r
- inserted into a dictionary (either as a key or value), the dictionary\r
- becomes tracked. During a full garbage collection (all generations),\r
- the collector will untrack any dictionaries whose contents are not\r
- tracked.\r
-\r
- The module provides the python function is_tracked(obj), which returns\r
- the CURRENT tracking status of the object. Subsequent garbage\r
- collections may change the tracking status of the object.\r
-\r
- Untracking of certain containers was introduced in issue #4688, and\r
- the algorithm was refined in response to issue #14775.\r
-*/\r
-\r
-/* set for debugging information */\r
-#define DEBUG_STATS (1<<0) /* print collection statistics */\r
-#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */\r
-#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */\r
-#define DEBUG_INSTANCES (1<<3) /* print instances */\r
-#define DEBUG_OBJECTS (1<<4) /* print other objects */\r
-#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */\r
-#define DEBUG_LEAK DEBUG_COLLECTABLE | \\r
- DEBUG_UNCOLLECTABLE | \\r
- DEBUG_INSTANCES | \\r
- DEBUG_OBJECTS | \\r
- DEBUG_SAVEALL\r
-static int debug;\r
-static PyObject *tmod = NULL;\r
-\r
-/*--------------------------------------------------------------------------\r
-gc_refs values.\r
-\r
-Between collections, every gc'ed object has one of two gc_refs values:\r
-\r
-GC_UNTRACKED\r
- The initial state; objects returned by PyObject_GC_Malloc are in this\r
- state. The object doesn't live in any generation list, and its\r
- tp_traverse slot must not be called.\r
-\r
-GC_REACHABLE\r
- The object lives in some generation list, and its tp_traverse is safe to\r
- call. An object transitions to GC_REACHABLE when PyObject_GC_Track\r
- is called.\r
-\r
-During a collection, gc_refs can temporarily take on other states:\r
-\r
->= 0\r
- At the start of a collection, update_refs() copies the true refcount\r
- to gc_refs, for each object in the generation being collected.\r
- subtract_refs() then adjusts gc_refs so that it equals the number of\r
- times an object is referenced directly from outside the generation\r
- being collected.\r
- gc_refs remains >= 0 throughout these steps.\r
-\r
-GC_TENTATIVELY_UNREACHABLE\r
- move_unreachable() then moves objects not reachable (whether directly or\r
- indirectly) from outside the generation into an "unreachable" set.\r
- Objects that are found to be reachable have gc_refs set to GC_REACHABLE\r
- again. Objects that are found to be unreachable have gc_refs set to\r
- GC_TENTATIVELY_UNREACHABLE. It's "tentatively" because the pass doing\r
- this can't be sure until it ends, and GC_TENTATIVELY_UNREACHABLE may\r
- transition back to GC_REACHABLE.\r
-\r
- Only objects with GC_TENTATIVELY_UNREACHABLE still set are candidates\r
- for collection. If it's decided not to collect such an object (e.g.,\r
- it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.\r
-----------------------------------------------------------------------------\r
-*/\r
-#define GC_UNTRACKED _PyGC_REFS_UNTRACKED\r
-#define GC_REACHABLE _PyGC_REFS_REACHABLE\r
-#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE\r
-\r
-#define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED)\r
-#define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE)\r
-#define IS_TENTATIVELY_UNREACHABLE(o) ( \\r
- (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)\r
-\r
-/*** list functions ***/\r
-\r
-static void\r
-gc_list_init(PyGC_Head *list)\r
-{\r
- list->gc.gc_prev = list;\r
- list->gc.gc_next = list;\r
-}\r
-\r
-static int\r
-gc_list_is_empty(PyGC_Head *list)\r
-{\r
- return (list->gc.gc_next == list);\r
-}\r
-\r
-#if 0\r
-/* This became unused after gc_list_move() was introduced. */\r
-/* Append `node` to `list`. */\r
-static void\r
-gc_list_append(PyGC_Head *node, PyGC_Head *list)\r
-{\r
- node->gc.gc_next = list;\r
- node->gc.gc_prev = list->gc.gc_prev;\r
- node->gc.gc_prev->gc.gc_next = node;\r
- list->gc.gc_prev = node;\r
-}\r
-#endif\r
-\r
-/* Remove `node` from the gc list it's currently in. */\r
-static void\r
-gc_list_remove(PyGC_Head *node)\r
-{\r
- node->gc.gc_prev->gc.gc_next = node->gc.gc_next;\r
- node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;\r
- node->gc.gc_next = NULL; /* object is not currently tracked */\r
-}\r
-\r
-/* Move `node` from the gc list it's currently in (which is not explicitly\r
- * named here) to the end of `list`. This is semantically the same as\r
- * gc_list_remove(node) followed by gc_list_append(node, list).\r
- */\r
-static void\r
-gc_list_move(PyGC_Head *node, PyGC_Head *list)\r
-{\r
- PyGC_Head *new_prev;\r
- PyGC_Head *current_prev = node->gc.gc_prev;\r
- PyGC_Head *current_next = node->gc.gc_next;\r
- /* Unlink from current list. */\r
- current_prev->gc.gc_next = current_next;\r
- current_next->gc.gc_prev = current_prev;\r
- /* Relink at end of new list. */\r
- new_prev = node->gc.gc_prev = list->gc.gc_prev;\r
- new_prev->gc.gc_next = list->gc.gc_prev = node;\r
- node->gc.gc_next = list;\r
-}\r
-\r
-/* append list `from` onto list `to`; `from` becomes an empty list */\r
-static void\r
-gc_list_merge(PyGC_Head *from, PyGC_Head *to)\r
-{\r
- PyGC_Head *tail;\r
- assert(from != to);\r
- if (!gc_list_is_empty(from)) {\r
- tail = to->gc.gc_prev;\r
- tail->gc.gc_next = from->gc.gc_next;\r
- tail->gc.gc_next->gc.gc_prev = tail;\r
- to->gc.gc_prev = from->gc.gc_prev;\r
- to->gc.gc_prev->gc.gc_next = to;\r
- }\r
- gc_list_init(from);\r
-}\r
-\r
-static Py_ssize_t\r
-gc_list_size(PyGC_Head *list)\r
-{\r
- PyGC_Head *gc;\r
- Py_ssize_t n = 0;\r
- for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {\r
- n++;\r
- }\r
- return n;\r
-}\r
-\r
-/* Append objects in a GC list to a Python list.\r
- * Return 0 if all OK, < 0 if error (out of memory for list).\r
- */\r
-static int\r
-append_objects(PyObject *py_list, PyGC_Head *gc_list)\r
-{\r
- PyGC_Head *gc;\r
- for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {\r
- PyObject *op = FROM_GC(gc);\r
- if (op != py_list) {\r
- if (PyList_Append(py_list, op)) {\r
- return -1; /* exception */\r
- }\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-/*** end of list stuff ***/\r
-\r
-\r
-/* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 for all objects\r
- * in containers, and is GC_REACHABLE for all tracked gc objects not in\r
- * containers.\r
- */\r
-static void\r
-update_refs(PyGC_Head *containers)\r
-{\r
- PyGC_Head *gc = containers->gc.gc_next;\r
- for (; gc != containers; gc = gc->gc.gc_next) {\r
- assert(gc->gc.gc_refs == GC_REACHABLE);\r
- gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));\r
- /* Python's cyclic gc should never see an incoming refcount\r
- * of 0: if something decref'ed to 0, it should have been\r
- * deallocated immediately at that time.\r
- * Possible cause (if the assert triggers): a tp_dealloc\r
- * routine left a gc-aware object tracked during its teardown\r
- * phase, and did something-- or allowed something to happen --\r
- * that called back into Python. gc can trigger then, and may\r
- * see the still-tracked dying object. Before this assert\r
- * was added, such mistakes went on to allow gc to try to\r
- * delete the object again. In a debug build, that caused\r
- * a mysterious segfault, when _Py_ForgetReference tried\r
- * to remove the object from the doubly-linked list of all\r
- * objects a second time. In a release build, an actual\r
- * double deallocation occurred, which leads to corruption\r
- * of the allocator's internal bookkeeping pointers. That's\r
- * so serious that maybe this should be a release-build\r
- * check instead of an assert?\r
- */\r
- assert(gc->gc.gc_refs != 0);\r
- }\r
-}\r
-\r
-/* A traversal callback for subtract_refs. */\r
-static int\r
-visit_decref(PyObject *op, void *data)\r
-{\r
- assert(op != NULL);\r
- if (PyObject_IS_GC(op)) {\r
- PyGC_Head *gc = AS_GC(op);\r
- /* We're only interested in gc_refs for objects in the\r
- * generation being collected, which can be recognized\r
- * because only they have positive gc_refs.\r
- */\r
- assert(gc->gc.gc_refs != 0); /* else refcount was too small */\r
- if (gc->gc.gc_refs > 0)\r
- gc->gc.gc_refs--;\r
- }\r
- return 0;\r
-}\r
-\r
-/* Subtract internal references from gc_refs. After this, gc_refs is >= 0\r
- * for all objects in containers, and is GC_REACHABLE for all tracked gc\r
- * objects not in containers. The ones with gc_refs > 0 are directly\r
- * reachable from outside containers, and so can't be collected.\r
- */\r
-static void\r
-subtract_refs(PyGC_Head *containers)\r
-{\r
- traverseproc traverse;\r
- PyGC_Head *gc = containers->gc.gc_next;\r
- for (; gc != containers; gc=gc->gc.gc_next) {\r
- traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;\r
- (void) traverse(FROM_GC(gc),\r
- (visitproc)visit_decref,\r
- NULL);\r
- }\r
-}\r
-\r
-/* A traversal callback for move_unreachable. */\r
-static int\r
-visit_reachable(PyObject *op, PyGC_Head *reachable)\r
-{\r
- if (PyObject_IS_GC(op)) {\r
- PyGC_Head *gc = AS_GC(op);\r
- const Py_ssize_t gc_refs = gc->gc.gc_refs;\r
-\r
- if (gc_refs == 0) {\r
- /* This is in move_unreachable's 'young' list, but\r
- * the traversal hasn't yet gotten to it. All\r
- * we need to do is tell move_unreachable that it's\r
- * reachable.\r
- */\r
- gc->gc.gc_refs = 1;\r
- }\r
- else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {\r
- /* This had gc_refs = 0 when move_unreachable got\r
- * to it, but turns out it's reachable after all.\r
- * Move it back to move_unreachable's 'young' list,\r
- * and move_unreachable will eventually get to it\r
- * again.\r
- */\r
- gc_list_move(gc, reachable);\r
- gc->gc.gc_refs = 1;\r
- }\r
- /* Else there's nothing to do.\r
- * If gc_refs > 0, it must be in move_unreachable's 'young'\r
- * list, and move_unreachable will eventually get to it.\r
- * If gc_refs == GC_REACHABLE, it's either in some other\r
- * generation so we don't care about it, or move_unreachable\r
- * already dealt with it.\r
- * If gc_refs == GC_UNTRACKED, it must be ignored.\r
- */\r
- else {\r
- assert(gc_refs > 0\r
- || gc_refs == GC_REACHABLE\r
- || gc_refs == GC_UNTRACKED);\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-/* Move the unreachable objects from young to unreachable. After this,\r
- * all objects in young have gc_refs = GC_REACHABLE, and all objects in\r
- * unreachable have gc_refs = GC_TENTATIVELY_UNREACHABLE. All tracked\r
- * gc objects not in young or unreachable still have gc_refs = GC_REACHABLE.\r
- * All objects in young after this are directly or indirectly reachable\r
- * from outside the original young; and all objects in unreachable are\r
- * not.\r
- */\r
-static void\r
-move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)\r
-{\r
- PyGC_Head *gc = young->gc.gc_next;\r
-\r
- /* Invariants: all objects "to the left" of us in young have gc_refs\r
- * = GC_REACHABLE, and are indeed reachable (directly or indirectly)\r
- * from outside the young list as it was at entry. All other objects\r
- * from the original young "to the left" of us are in unreachable now,\r
- * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the\r
- * left of us in 'young' now have been scanned, and no objects here\r
- * or to the right have been scanned yet.\r
- */\r
-\r
- while (gc != young) {\r
- PyGC_Head *next;\r
-\r
- if (gc->gc.gc_refs) {\r
- /* gc is definitely reachable from outside the\r
- * original 'young'. Mark it as such, and traverse\r
- * its pointers to find any other objects that may\r
- * be directly reachable from it. Note that the\r
- * call to tp_traverse may append objects to young,\r
- * so we have to wait until it returns to determine\r
- * the next object to visit.\r
- */\r
- PyObject *op = FROM_GC(gc);\r
- traverseproc traverse = Py_TYPE(op)->tp_traverse;\r
- assert(gc->gc.gc_refs > 0);\r
- gc->gc.gc_refs = GC_REACHABLE;\r
- (void) traverse(op,\r
- (visitproc)visit_reachable,\r
- (void *)young);\r
- next = gc->gc.gc_next;\r
- if (PyTuple_CheckExact(op)) {\r
- _PyTuple_MaybeUntrack(op);\r
- }\r
- }\r
- else {\r
- /* This *may* be unreachable. To make progress,\r
- * assume it is. gc isn't directly reachable from\r
- * any object we've already traversed, but may be\r
- * reachable from an object we haven't gotten to yet.\r
- * visit_reachable will eventually move gc back into\r
- * young if that's so, and we'll see it again.\r
- */\r
- next = gc->gc.gc_next;\r
- gc_list_move(gc, unreachable);\r
- gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;\r
- }\r
- gc = next;\r
- }\r
-}\r
-\r
-/* Return true if object has a finalization method.\r
- * CAUTION: An instance of an old-style class has to be checked for a\r
- *__del__ method, and earlier versions of this used to call PyObject_HasAttr,\r
- * which in turn could call the class's __getattr__ hook (if any). That\r
- * could invoke arbitrary Python code, mutating the object graph in arbitrary\r
- * ways, and that was the source of some excruciatingly subtle bugs.\r
- */\r
-static int\r
-has_finalizer(PyObject *op)\r
-{\r
- if (PyInstance_Check(op)) {\r
- assert(delstr != NULL);\r
- return _PyInstance_Lookup(op, delstr) != NULL;\r
- }\r
- else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))\r
- return op->ob_type->tp_del != NULL;\r
- else if (PyGen_CheckExact(op))\r
- return PyGen_NeedsFinalizing((PyGenObject *)op);\r
- else\r
- return 0;\r
-}\r
-\r
-/* Try to untrack all currently tracked dictionaries */\r
-static void\r
-untrack_dicts(PyGC_Head *head)\r
-{\r
- PyGC_Head *next, *gc = head->gc.gc_next;\r
- while (gc != head) {\r
- PyObject *op = FROM_GC(gc);\r
- next = gc->gc.gc_next;\r
- if (PyDict_CheckExact(op))\r
- _PyDict_MaybeUntrack(op);\r
- gc = next;\r
- }\r
-}\r
-\r
-/* Move the objects in unreachable with __del__ methods into `finalizers`.\r
- * Objects moved into `finalizers` have gc_refs set to GC_REACHABLE; the\r
- * objects remaining in unreachable are left at GC_TENTATIVELY_UNREACHABLE.\r
- */\r
-static void\r
-move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)\r
-{\r
- PyGC_Head *gc;\r
- PyGC_Head *next;\r
-\r
- /* March over unreachable. Move objects with finalizers into\r
- * `finalizers`.\r
- */\r
- for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {\r
- PyObject *op = FROM_GC(gc);\r
-\r
- assert(IS_TENTATIVELY_UNREACHABLE(op));\r
- next = gc->gc.gc_next;\r
-\r
- if (has_finalizer(op)) {\r
- gc_list_move(gc, finalizers);\r
- gc->gc.gc_refs = GC_REACHABLE;\r
- }\r
- }\r
-}\r
-\r
-/* A traversal callback for move_finalizer_reachable. */\r
-static int\r
-visit_move(PyObject *op, PyGC_Head *tolist)\r
-{\r
- if (PyObject_IS_GC(op)) {\r
- if (IS_TENTATIVELY_UNREACHABLE(op)) {\r
- PyGC_Head *gc = AS_GC(op);\r
- gc_list_move(gc, tolist);\r
- gc->gc.gc_refs = GC_REACHABLE;\r
- }\r
- }\r
- return 0;\r
-}\r
-\r
-/* Move objects that are reachable from finalizers, from the unreachable set\r
- * into finalizers set.\r
- */\r
-static void\r
-move_finalizer_reachable(PyGC_Head *finalizers)\r
-{\r
- traverseproc traverse;\r
- PyGC_Head *gc = finalizers->gc.gc_next;\r
- for (; gc != finalizers; gc = gc->gc.gc_next) {\r
- /* Note that the finalizers list may grow during this. */\r
- traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;\r
- (void) traverse(FROM_GC(gc),\r
- (visitproc)visit_move,\r
- (void *)finalizers);\r
- }\r
-}\r
-\r
-/* Clear all weakrefs to unreachable objects, and if such a weakref has a\r
- * callback, invoke it if necessary. Note that it's possible for such\r
- * weakrefs to be outside the unreachable set -- indeed, those are precisely\r
- * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for\r
- * overview & some details. Some weakrefs with callbacks may be reclaimed\r
- * directly by this routine; the number reclaimed is the return value. Other\r
- * weakrefs with callbacks may be moved into the `old` generation. Objects\r
- * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in\r
- * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,\r
- * no object in `unreachable` is weakly referenced anymore.\r
- */\r
-static int\r
-handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)\r
-{\r
- PyGC_Head *gc;\r
- PyObject *op; /* generally FROM_GC(gc) */\r
- PyWeakReference *wr; /* generally a cast of op */\r
- PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */\r
- PyGC_Head *next;\r
- int num_freed = 0;\r
-\r
- gc_list_init(&wrcb_to_call);\r
-\r
- /* Clear all weakrefs to the objects in unreachable. If such a weakref\r
- * also has a callback, move it into `wrcb_to_call` if the callback\r
- * needs to be invoked. Note that we cannot invoke any callbacks until\r
- * all weakrefs to unreachable objects are cleared, lest the callback\r
- * resurrect an unreachable object via a still-active weakref. We\r
- * make another pass over wrcb_to_call, invoking callbacks, after this\r
- * pass completes.\r
- */\r
- for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {\r
- PyWeakReference **wrlist;\r
-\r
- op = FROM_GC(gc);\r
- assert(IS_TENTATIVELY_UNREACHABLE(op));\r
- next = gc->gc.gc_next;\r
-\r
- if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))\r
- continue;\r
-\r
- /* It supports weakrefs. Does it have any? */\r
- wrlist = (PyWeakReference **)\r
- PyObject_GET_WEAKREFS_LISTPTR(op);\r
-\r
- /* `op` may have some weakrefs. March over the list, clear\r
- * all the weakrefs, and move the weakrefs with callbacks\r
- * that must be called into wrcb_to_call.\r
- */\r
- for (wr = *wrlist; wr != NULL; wr = *wrlist) {\r
- PyGC_Head *wrasgc; /* AS_GC(wr) */\r
-\r
- /* _PyWeakref_ClearRef clears the weakref but leaves\r
- * the callback pointer intact. Obscure: it also\r
- * changes *wrlist.\r
- */\r
- assert(wr->wr_object == op);\r
- _PyWeakref_ClearRef(wr);\r
- assert(wr->wr_object == Py_None);\r
- if (wr->wr_callback == NULL)\r
- continue; /* no callback */\r
-\r
- /* Headache time. `op` is going away, and is weakly referenced by\r
- * `wr`, which has a callback. Should the callback be invoked? If wr\r
- * is also trash, no:\r
- *\r
- * 1. There's no need to call it. The object and the weakref are\r
- * both going away, so it's legitimate to pretend the weakref is\r
- * going away first. The user has to ensure a weakref outlives its\r
- * referent if they want a guarantee that the wr callback will get\r
- * invoked.\r
- *\r
- * 2. It may be catastrophic to call it. If the callback is also in\r
- * cyclic trash (CT), then although the CT is unreachable from\r
- * outside the current generation, CT may be reachable from the\r
- * callback. Then the callback could resurrect insane objects.\r
- *\r
- * Since the callback is never needed and may be unsafe in this case,\r
- * wr is simply left in the unreachable set. Note that because we\r
- * already called _PyWeakref_ClearRef(wr), its callback will never\r
- * trigger.\r
- *\r
- * OTOH, if wr isn't part of CT, we should invoke the callback: the\r
- * weakref outlived the trash. Note that since wr isn't CT in this\r
- * case, its callback can't be CT either -- wr acted as an external\r
- * root to this generation, and therefore its callback did too. So\r
- * nothing in CT is reachable from the callback either, so it's hard\r
- * to imagine how calling it later could create a problem for us. wr\r
- * is moved to wrcb_to_call in this case.\r
- */\r
- if (IS_TENTATIVELY_UNREACHABLE(wr))\r
- continue;\r
- assert(IS_REACHABLE(wr));\r
-\r
- /* Create a new reference so that wr can't go away\r
- * before we can process it again.\r
- */\r
- Py_INCREF(wr);\r
-\r
- /* Move wr to wrcb_to_call, for the next pass. */\r
- wrasgc = AS_GC(wr);\r
- assert(wrasgc != next); /* wrasgc is reachable, but\r
- next isn't, so they can't\r
- be the same */\r
- gc_list_move(wrasgc, &wrcb_to_call);\r
- }\r
- }\r
-\r
- /* Invoke the callbacks we decided to honor. It's safe to invoke them\r
- * because they can't reference unreachable objects.\r
- */\r
- while (! gc_list_is_empty(&wrcb_to_call)) {\r
- PyObject *temp;\r
- PyObject *callback;\r
-\r
- gc = wrcb_to_call.gc.gc_next;\r
- op = FROM_GC(gc);\r
- assert(IS_REACHABLE(op));\r
- assert(PyWeakref_Check(op));\r
- wr = (PyWeakReference *)op;\r
- callback = wr->wr_callback;\r
- assert(callback != NULL);\r
-\r
- /* copy-paste of weakrefobject.c's handle_callback() */\r
- temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);\r
- if (temp == NULL)\r
- PyErr_WriteUnraisable(callback);\r
- else\r
- Py_DECREF(temp);\r
-\r
- /* Give up the reference we created in the first pass. When\r
- * op's refcount hits 0 (which it may or may not do right now),\r
- * op's tp_dealloc will decref op->wr_callback too. Note\r
- * that the refcount probably will hit 0 now, and because this\r
- * weakref was reachable to begin with, gc didn't already\r
- * add it to its count of freed objects. Example: a reachable\r
- * weak value dict maps some key to this reachable weakref.\r
- * The callback removes this key->weakref mapping from the\r
- * dict, leaving no other references to the weakref (excepting\r
- * ours).\r
- */\r
- Py_DECREF(op);\r
- if (wrcb_to_call.gc.gc_next == gc) {\r
- /* object is still alive -- move it */\r
- gc_list_move(gc, old);\r
- }\r
- else\r
- ++num_freed;\r
- }\r
-\r
- return num_freed;\r
-}\r
-\r
-static void\r
-debug_instance(char *msg, PyInstanceObject *inst)\r
-{\r
- char *cname;\r
- /* simple version of instance_repr */\r
- PyObject *classname = inst->in_class->cl_name;\r
- if (classname != NULL && PyString_Check(classname))\r
- cname = PyString_AsString(classname);\r
- else\r
- cname = "?";\r
- PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",\r
- msg, cname, inst);\r
-}\r
-\r
-static void\r
-debug_cycle(char *msg, PyObject *op)\r
-{\r
- if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {\r
- debug_instance(msg, (PyInstanceObject *)op);\r
- }\r
- else if (debug & DEBUG_OBJECTS) {\r
- PySys_WriteStderr("gc: %.100s <%.100s %p>\n",\r
- msg, Py_TYPE(op)->tp_name, op);\r
- }\r
-}\r
-\r
-/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable\r
- * only from such cycles).\r
- * If DEBUG_SAVEALL, all objects in finalizers are appended to the module\r
- * garbage list (a Python list), else only the objects in finalizers with\r
- * __del__ methods are appended to garbage. All objects in finalizers are\r
- * merged into the old list regardless.\r
- * Returns 0 if all OK, <0 on error (out of memory to grow the garbage list).\r
- * The finalizers list is made empty on a successful return.\r
- */\r
-static int\r
-handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)\r
-{\r
- PyGC_Head *gc = finalizers->gc.gc_next;\r
-\r
- if (garbage == NULL) {\r
- garbage = PyList_New(0);\r
- if (garbage == NULL)\r
- Py_FatalError("gc couldn't create gc.garbage list");\r
- }\r
- for (; gc != finalizers; gc = gc->gc.gc_next) {\r
- PyObject *op = FROM_GC(gc);\r
-\r
- if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {\r
- if (PyList_Append(garbage, op) < 0)\r
- return -1;\r
- }\r
- }\r
-\r
- gc_list_merge(finalizers, old);\r
- return 0;\r
-}\r
-\r
-/* Break reference cycles by clearing the containers involved. This is\r
- * tricky business as the lists can be changing and we don't know which\r
- * objects may be freed. It is possible I screwed something up here.\r
- */\r
-static void\r
-delete_garbage(PyGC_Head *collectable, PyGC_Head *old)\r
-{\r
- inquiry clear;\r
-\r
- while (!gc_list_is_empty(collectable)) {\r
- PyGC_Head *gc = collectable->gc.gc_next;\r
- PyObject *op = FROM_GC(gc);\r
-\r
- assert(IS_TENTATIVELY_UNREACHABLE(op));\r
- if (debug & DEBUG_SAVEALL) {\r
- PyList_Append(garbage, op);\r
- }\r
- else {\r
- if ((clear = Py_TYPE(op)->tp_clear) != NULL) {\r
- Py_INCREF(op);\r
- clear(op);\r
- Py_DECREF(op);\r
- }\r
- }\r
- if (collectable->gc.gc_next == gc) {\r
- /* object is still alive, move it, it may die later */\r
- gc_list_move(gc, old);\r
- gc->gc.gc_refs = GC_REACHABLE;\r
- }\r
- }\r
-}\r
-\r
-/* Clear all free lists\r
- * All free lists are cleared during the collection of the highest generation.\r
- * Allocated items in the free list may keep a pymalloc arena occupied.\r
- * Clearing the free lists may give back memory to the OS earlier.\r
- */\r
-static void\r
-clear_freelists(void)\r
-{\r
- (void)PyMethod_ClearFreeList();\r
- (void)PyFrame_ClearFreeList();\r
- (void)PyCFunction_ClearFreeList();\r
- (void)PyTuple_ClearFreeList();\r
-#ifdef Py_USING_UNICODE\r
- (void)PyUnicode_ClearFreeList();\r
-#endif\r
- (void)PyInt_ClearFreeList();\r
- (void)PyFloat_ClearFreeList();\r
-}\r
-\r
-static double\r
-get_time(void)\r
-{\r
- double result = 0;\r
- if (tmod != NULL) {\r
- PyObject *f = PyObject_CallMethod(tmod, "time", NULL);\r
- if (f == NULL) {\r
- PyErr_Clear();\r
- }\r
- else {\r
- if (PyFloat_Check(f))\r
- result = PyFloat_AsDouble(f);\r
- Py_DECREF(f);\r
- }\r
- }\r
- return result;\r
-}\r
-\r
-/* This is the main function. Read this to understand how the\r
- * collection process works. */\r
-static Py_ssize_t\r
-collect(int generation)\r
-{\r
- int i;\r
- Py_ssize_t m = 0; /* # objects collected */\r
- Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */\r
- PyGC_Head *young; /* the generation we are examining */\r
- PyGC_Head *old; /* next older generation */\r
- PyGC_Head unreachable; /* non-problematic unreachable trash */\r
- PyGC_Head finalizers; /* objects with, & reachable from, __del__ */\r
- PyGC_Head *gc;\r
- double t1 = 0.0;\r
-\r
- if (delstr == NULL) {\r
- delstr = PyString_InternFromString("__del__");\r
- if (delstr == NULL)\r
- Py_FatalError("gc couldn't allocate \"__del__\"");\r
- }\r
-\r
- if (debug & DEBUG_STATS) {\r
- PySys_WriteStderr("gc: collecting generation %d...\n",\r
- generation);\r
- PySys_WriteStderr("gc: objects in each generation:");\r
- for (i = 0; i < NUM_GENERATIONS; i++)\r
- PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",\r
- gc_list_size(GEN_HEAD(i)));\r
- t1 = get_time();\r
- PySys_WriteStderr("\n");\r
- }\r
-\r
- /* update collection and allocation counters */\r
- if (generation+1 < NUM_GENERATIONS)\r
- generations[generation+1].count += 1;\r
- for (i = 0; i <= generation; i++)\r
- generations[i].count = 0;\r
-\r
- /* merge younger generations with one we are currently collecting */\r
- for (i = 0; i < generation; i++) {\r
- gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));\r
- }\r
-\r
- /* handy references */\r
- young = GEN_HEAD(generation);\r
- if (generation < NUM_GENERATIONS-1)\r
- old = GEN_HEAD(generation+1);\r
- else\r
- old = young;\r
-\r
- /* Using ob_refcnt and gc_refs, calculate which objects in the\r
- * container set are reachable from outside the set (i.e., have a\r
- * refcount greater than 0 when all the references within the\r
- * set are taken into account).\r
- */\r
- update_refs(young);\r
- subtract_refs(young);\r
-\r
- /* Leave everything reachable from outside young in young, and move\r
- * everything else (in young) to unreachable.\r
- * NOTE: This used to move the reachable objects into a reachable\r
- * set instead. But most things usually turn out to be reachable,\r
- * so it's more efficient to move the unreachable things.\r
- */\r
- gc_list_init(&unreachable);\r
- move_unreachable(young, &unreachable);\r
-\r
- /* Move reachable objects to next generation. */\r
- if (young != old) {\r
- if (generation == NUM_GENERATIONS - 2) {\r
- long_lived_pending += gc_list_size(young);\r
- }\r
- gc_list_merge(young, old);\r
- }\r
- else {\r
- /* We only untrack dicts in full collections, to avoid quadratic\r
- dict build-up. See issue #14775. */\r
- untrack_dicts(young);\r
- long_lived_pending = 0;\r
- long_lived_total = gc_list_size(young);\r
- }\r
-\r
- /* All objects in unreachable are trash, but objects reachable from\r
- * finalizers can't safely be deleted. Python programmers should take\r
- * care not to create such things. For Python, finalizers means\r
- * instance objects with __del__ methods. Weakrefs with callbacks\r
- * can also call arbitrary Python code but they will be dealt with by\r
- * handle_weakrefs().\r
- */\r
- gc_list_init(&finalizers);\r
- move_finalizers(&unreachable, &finalizers);\r
- /* finalizers contains the unreachable objects with a finalizer;\r
- * unreachable objects reachable *from* those are also uncollectable,\r
- * and we move those into the finalizers list too.\r
- */\r
- move_finalizer_reachable(&finalizers);\r
-\r
- /* Collect statistics on collectable objects found and print\r
- * debugging information.\r
- */\r
- for (gc = unreachable.gc.gc_next; gc != &unreachable;\r
- gc = gc->gc.gc_next) {\r
- m++;\r
- if (debug & DEBUG_COLLECTABLE) {\r
- debug_cycle("collectable", FROM_GC(gc));\r
- }\r
- }\r
-\r
- /* Clear weakrefs and invoke callbacks as necessary. */\r
- m += handle_weakrefs(&unreachable, old);\r
-\r
- /* Call tp_clear on objects in the unreachable set. This will cause\r
- * the reference cycles to be broken. It may also cause some objects\r
- * in finalizers to be freed.\r
- */\r
- delete_garbage(&unreachable, old);\r
-\r
- /* Collect statistics on uncollectable objects found and print\r
- * debugging information. */\r
- for (gc = finalizers.gc.gc_next;\r
- gc != &finalizers;\r
- gc = gc->gc.gc_next) {\r
- n++;\r
- if (debug & DEBUG_UNCOLLECTABLE)\r
- debug_cycle("uncollectable", FROM_GC(gc));\r
- }\r
- if (debug & DEBUG_STATS) {\r
- double t2 = get_time();\r
- if (m == 0 && n == 0)\r
- PySys_WriteStderr("gc: done");\r
- else\r
- PySys_WriteStderr(\r
- "gc: done, "\r
- "%" PY_FORMAT_SIZE_T "d unreachable, "\r
- "%" PY_FORMAT_SIZE_T "d uncollectable",\r
- n+m, n);\r
- if (t1 && t2) {\r
- PySys_WriteStderr(", %.4fs elapsed", t2-t1);\r
- }\r
- PySys_WriteStderr(".\n");\r
- }\r
-\r
- /* Append instances in the uncollectable set to a Python\r
- * reachable list of garbage. The programmer has to deal with\r
- * this if they insist on creating this type of structure.\r
- */\r
- (void)handle_finalizers(&finalizers, old);\r
-\r
- /* Clear free list only during the collection of the highest\r
- * generation */\r
- if (generation == NUM_GENERATIONS-1) {\r
- clear_freelists();\r
- }\r
-\r
- if (PyErr_Occurred()) {\r
- if (gc_str == NULL)\r
- gc_str = PyString_FromString("garbage collection");\r
- PyErr_WriteUnraisable(gc_str);\r
- Py_FatalError("unexpected exception during garbage collection");\r
- }\r
- return n+m;\r
-}\r
-\r
-static Py_ssize_t\r
-collect_generations(void)\r
-{\r
- int i;\r
- Py_ssize_t n = 0;\r
-\r
- /* Find the oldest generation (highest numbered) where the count\r
- * exceeds the threshold. Objects in the that generation and\r
- * generations younger than it will be collected. */\r
- for (i = NUM_GENERATIONS-1; i >= 0; i--) {\r
- if (generations[i].count > generations[i].threshold) {\r
- /* Avoid quadratic performance degradation in number\r
- of tracked objects. See comments at the beginning\r
- of this file, and issue #4074.\r
- */\r
- if (i == NUM_GENERATIONS - 1\r
- && long_lived_pending < long_lived_total / 4)\r
- continue;\r
- n = collect(i);\r
- break;\r
- }\r
- }\r
- return n;\r
-}\r
-\r
-PyDoc_STRVAR(gc_enable__doc__,\r
-"enable() -> None\n"\r
-"\n"\r
-"Enable automatic garbage collection.\n");\r
-\r
-static PyObject *\r
-gc_enable(PyObject *self, PyObject *noargs)\r
-{\r
- enabled = 1;\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(gc_disable__doc__,\r
-"disable() -> None\n"\r
-"\n"\r
-"Disable automatic garbage collection.\n");\r
-\r
-static PyObject *\r
-gc_disable(PyObject *self, PyObject *noargs)\r
-{\r
- enabled = 0;\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(gc_isenabled__doc__,\r
-"isenabled() -> status\n"\r
-"\n"\r
-"Returns true if automatic garbage collection is enabled.\n");\r
-\r
-static PyObject *\r
-gc_isenabled(PyObject *self, PyObject *noargs)\r
-{\r
- return PyBool_FromLong((long)enabled);\r
-}\r
-\r
-PyDoc_STRVAR(gc_collect__doc__,\r
-"collect([generation]) -> n\n"\r
-"\n"\r
-"With no arguments, run a full collection. The optional argument\n"\r
-"may be an integer specifying which generation to collect. A ValueError\n"\r
-"is raised if the generation number is invalid.\n\n"\r
-"The number of unreachable objects is returned.\n");\r
-\r
-static PyObject *\r
-gc_collect(PyObject *self, PyObject *args, PyObject *kws)\r
-{\r
- static char *keywords[] = {"generation", NULL};\r
- int genarg = NUM_GENERATIONS - 1;\r
- Py_ssize_t n;\r
-\r
- if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))\r
- return NULL;\r
-\r
- else if (genarg < 0 || genarg >= NUM_GENERATIONS) {\r
- PyErr_SetString(PyExc_ValueError, "invalid generation");\r
- return NULL;\r
- }\r
-\r
- if (collecting)\r
- n = 0; /* already collecting, don't do anything */\r
- else {\r
- collecting = 1;\r
- n = collect(genarg);\r
- collecting = 0;\r
- }\r
-\r
- return PyInt_FromSsize_t(n);\r
-}\r
-\r
-PyDoc_STRVAR(gc_set_debug__doc__,\r
-"set_debug(flags) -> None\n"\r
-"\n"\r
-"Set the garbage collection debugging flags. Debugging information is\n"\r
-"written to sys.stderr.\n"\r
-"\n"\r
-"flags is an integer and can have the following bits turned on:\n"\r
-"\n"\r
-" DEBUG_STATS - Print statistics during collection.\n"\r
-" DEBUG_COLLECTABLE - Print collectable objects found.\n"\r
-" DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects found.\n"\r
-" DEBUG_INSTANCES - Print instance objects.\n"\r
-" DEBUG_OBJECTS - Print objects other than instances.\n"\r
-" DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.\n"\r
-" DEBUG_LEAK - Debug leaking programs (everything but STATS).\n");\r
-\r
-static PyObject *\r
-gc_set_debug(PyObject *self, PyObject *args)\r
-{\r
- if (!PyArg_ParseTuple(args, "i:set_debug", &debug))\r
- return NULL;\r
-\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(gc_get_debug__doc__,\r
-"get_debug() -> flags\n"\r
-"\n"\r
-"Get the garbage collection debugging flags.\n");\r
-\r
-static PyObject *\r
-gc_get_debug(PyObject *self, PyObject *noargs)\r
-{\r
- return Py_BuildValue("i", debug);\r
-}\r
-\r
-PyDoc_STRVAR(gc_set_thresh__doc__,\r
-"set_threshold(threshold0, [threshold1, threshold2]) -> None\n"\r
-"\n"\r
-"Sets the collection thresholds. Setting threshold0 to zero disables\n"\r
-"collection.\n");\r
-\r
-static PyObject *\r
-gc_set_thresh(PyObject *self, PyObject *args)\r
-{\r
- int i;\r
- if (!PyArg_ParseTuple(args, "i|ii:set_threshold",\r
- &generations[0].threshold,\r
- &generations[1].threshold,\r
- &generations[2].threshold))\r
- return NULL;\r
- for (i = 2; i < NUM_GENERATIONS; i++) {\r
- /* generations higher than 2 get the same threshold */\r
- generations[i].threshold = generations[2].threshold;\r
- }\r
-\r
- Py_INCREF(Py_None);\r
- return Py_None;\r
-}\r
-\r
-PyDoc_STRVAR(gc_get_thresh__doc__,\r
-"get_threshold() -> (threshold0, threshold1, threshold2)\n"\r
-"\n"\r
-"Return the current collection thresholds\n");\r
-\r
-static PyObject *\r
-gc_get_thresh(PyObject *self, PyObject *noargs)\r
-{\r
- return Py_BuildValue("(iii)",\r
- generations[0].threshold,\r
- generations[1].threshold,\r
- generations[2].threshold);\r
-}\r
-\r
-PyDoc_STRVAR(gc_get_count__doc__,\r
-"get_count() -> (count0, count1, count2)\n"\r
-"\n"\r
-"Return the current collection counts\n");\r
-\r
-static PyObject *\r
-gc_get_count(PyObject *self, PyObject *noargs)\r
-{\r
- return Py_BuildValue("(iii)",\r
- generations[0].count,\r
- generations[1].count,\r
- generations[2].count);\r
-}\r
-\r
-static int\r
-referrersvisit(PyObject* obj, PyObject *objs)\r
-{\r
- Py_ssize_t i;\r
- for (i = 0; i < PyTuple_GET_SIZE(objs); i++)\r
- if (PyTuple_GET_ITEM(objs, i) == obj)\r
- return 1;\r
- return 0;\r
-}\r
-\r
-static int\r
-gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)\r
-{\r
- PyGC_Head *gc;\r
- PyObject *obj;\r
- traverseproc traverse;\r
- for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {\r
- obj = FROM_GC(gc);\r
- traverse = Py_TYPE(obj)->tp_traverse;\r
- if (obj == objs || obj == resultlist)\r
- continue;\r
- if (traverse(obj, (visitproc)referrersvisit, objs)) {\r
- if (PyList_Append(resultlist, obj) < 0)\r
- return 0; /* error */\r
- }\r
- }\r
- return 1; /* no error */\r
-}\r
-\r
-PyDoc_STRVAR(gc_get_referrers__doc__,\r
-"get_referrers(*objs) -> list\n\\r
-Return the list of objects that directly refer to any of objs.");\r
-\r
-static PyObject *\r
-gc_get_referrers(PyObject *self, PyObject *args)\r
-{\r
- int i;\r
- PyObject *result = PyList_New(0);\r
- if (!result) return NULL;\r
-\r
- for (i = 0; i < NUM_GENERATIONS; i++) {\r
- if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {\r
- Py_DECREF(result);\r
- return NULL;\r
- }\r
- }\r
- return result;\r
-}\r
-\r
-/* Append obj to list; return true if error (out of memory), false if OK. */\r
-static int\r
-referentsvisit(PyObject *obj, PyObject *list)\r
-{\r
- return PyList_Append(list, obj) < 0;\r
-}\r
-\r
-PyDoc_STRVAR(gc_get_referents__doc__,\r
-"get_referents(*objs) -> list\n\\r
-Return the list of objects that are directly referred to by objs.");\r
-\r
-static PyObject *\r
-gc_get_referents(PyObject *self, PyObject *args)\r
-{\r
- Py_ssize_t i;\r
- PyObject *result = PyList_New(0);\r
-\r
- if (result == NULL)\r
- return NULL;\r
-\r
- for (i = 0; i < PyTuple_GET_SIZE(args); i++) {\r
- traverseproc traverse;\r
- PyObject *obj = PyTuple_GET_ITEM(args, i);\r
-\r
- if (! PyObject_IS_GC(obj))\r
- continue;\r
- traverse = Py_TYPE(obj)->tp_traverse;\r
- if (! traverse)\r
- continue;\r
- if (traverse(obj, (visitproc)referentsvisit, result)) {\r
- Py_DECREF(result);\r
- return NULL;\r
- }\r
- }\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(gc_get_objects__doc__,\r
-"get_objects() -> [...]\n"\r
-"\n"\r
-"Return a list of objects tracked by the collector (excluding the list\n"\r
-"returned).\n");\r
-\r
-static PyObject *\r
-gc_get_objects(PyObject *self, PyObject *noargs)\r
-{\r
- int i;\r
- PyObject* result;\r
-\r
- result = PyList_New(0);\r
- if (result == NULL)\r
- return NULL;\r
- for (i = 0; i < NUM_GENERATIONS; i++) {\r
- if (append_objects(result, GEN_HEAD(i))) {\r
- Py_DECREF(result);\r
- return NULL;\r
- }\r
- }\r
- return result;\r
-}\r
-\r
-PyDoc_STRVAR(gc_is_tracked__doc__,\r
-"is_tracked(obj) -> bool\n"\r
-"\n"\r
-"Returns true if the object is tracked by the garbage collector.\n"\r
-"Simple atomic objects will return false.\n"\r
-);\r
-\r
-static PyObject *\r
-gc_is_tracked(PyObject *self, PyObject *obj)\r
-{\r
- PyObject *result;\r
-\r
- if (PyObject_IS_GC(obj) && IS_TRACKED(obj))\r
- result = Py_True;\r
- else\r
- result = Py_False;\r
- Py_INCREF(result);\r
- return result;\r
-}\r
-\r
-\r
-PyDoc_STRVAR(gc__doc__,\r
-"This module provides access to the garbage collector for reference cycles.\n"\r
-"\n"\r
-"enable() -- Enable automatic garbage collection.\n"\r
-"disable() -- Disable automatic garbage collection.\n"\r
-"isenabled() -- Returns true if automatic collection is enabled.\n"\r
-"collect() -- Do a full collection right now.\n"\r
-"get_count() -- Return the current collection counts.\n"\r
-"set_debug() -- Set debugging flags.\n"\r
-"get_debug() -- Get debugging flags.\n"\r
-"set_threshold() -- Set the collection thresholds.\n"\r
-"get_threshold() -- Return the current the collection thresholds.\n"\r
-"get_objects() -- Return a list of all objects tracked by the collector.\n"\r
-"is_tracked() -- Returns true if a given object is tracked.\n"\r
-"get_referrers() -- Return the list of objects that refer to an object.\n"\r
-"get_referents() -- Return the list of objects that an object refers to.\n");\r
-\r
-static PyMethodDef GcMethods[] = {\r
- {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},\r
- {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},\r
- {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},\r
- {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},\r
- {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},\r
- {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},\r
- {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},\r
- {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},\r
- {"collect", (PyCFunction)gc_collect,\r
- METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},\r
- {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},\r
- {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__},\r
- {"get_referrers", gc_get_referrers, METH_VARARGS,\r
- gc_get_referrers__doc__},\r
- {"get_referents", gc_get_referents, METH_VARARGS,\r
- gc_get_referents__doc__},\r
- {NULL, NULL} /* Sentinel */\r
-};\r
-\r
-PyMODINIT_FUNC\r
-initgc(void)\r
-{\r
- PyObject *m;\r
-\r
- m = Py_InitModule4("gc",\r
- GcMethods,\r
- gc__doc__,\r
- NULL,\r
- PYTHON_API_VERSION);\r
- if (m == NULL)\r
- return;\r
-\r
- if (garbage == NULL) {\r
- garbage = PyList_New(0);\r
- if (garbage == NULL)\r
- return;\r
- }\r
- Py_INCREF(garbage);\r
- if (PyModule_AddObject(m, "garbage", garbage) < 0)\r
- return;\r
-\r
- /* Importing can't be done in collect() because collect()\r
- * can be called via PyGC_Collect() in Py_Finalize().\r
- * This wouldn't be a problem, except that <initialized> is\r
- * reset to 0 before calling collect which trips up\r
- * the import and triggers an assertion.\r
- */\r
- if (tmod == NULL) {\r
- tmod = PyImport_ImportModuleNoBlock("time");\r
- if (tmod == NULL)\r
- PyErr_Clear();\r
- }\r
-\r
-#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return\r
- ADD_INT(DEBUG_STATS);\r
- ADD_INT(DEBUG_COLLECTABLE);\r
- ADD_INT(DEBUG_UNCOLLECTABLE);\r
- ADD_INT(DEBUG_INSTANCES);\r
- ADD_INT(DEBUG_OBJECTS);\r
- ADD_INT(DEBUG_SAVEALL);\r
- ADD_INT(DEBUG_LEAK);\r
-#undef ADD_INT\r
-}\r
-\r
-/* API to invoke gc.collect() from C */\r
-Py_ssize_t\r
-PyGC_Collect(void)\r
-{\r
- Py_ssize_t n;\r
-\r
- if (collecting)\r
- n = 0; /* already collecting, don't do anything */\r
- else {\r
- collecting = 1;\r
- n = collect(NUM_GENERATIONS - 1);\r
- collecting = 0;\r
- }\r
-\r
- return n;\r
-}\r
-\r
-/* for debugging */\r
-void\r
-_PyGC_Dump(PyGC_Head *g)\r
-{\r
- _PyObject_Dump(FROM_GC(g));\r
-}\r
-\r
-/* extension modules might be compiled with GC support so these\r
- functions must always be available */\r
-\r
-#undef PyObject_GC_Track\r
-#undef PyObject_GC_UnTrack\r
-#undef PyObject_GC_Del\r
-#undef _PyObject_GC_Malloc\r
-\r
-void\r
-PyObject_GC_Track(void *op)\r
-{\r
- _PyObject_GC_TRACK(op);\r
-}\r
-\r
-/* for binary compatibility with 2.2 */\r
-void\r
-_PyObject_GC_Track(PyObject *op)\r
-{\r
- PyObject_GC_Track(op);\r
-}\r
-\r
-void\r
-PyObject_GC_UnTrack(void *op)\r
-{\r
- /* Obscure: the Py_TRASHCAN mechanism requires that we be able to\r
- * call PyObject_GC_UnTrack twice on an object.\r
- */\r
- if (IS_TRACKED(op))\r
- _PyObject_GC_UNTRACK(op);\r
-}\r
-\r
-/* for binary compatibility with 2.2 */\r
-void\r
-_PyObject_GC_UnTrack(PyObject *op)\r
-{\r
- PyObject_GC_UnTrack(op);\r
-}\r
-\r
-PyObject *\r
-_PyObject_GC_Malloc(size_t basicsize)\r
-{\r
- PyObject *op;\r
- PyGC_Head *g;\r
- if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))\r
- return PyErr_NoMemory();\r
- g = (PyGC_Head *)PyObject_MALLOC(\r
- sizeof(PyGC_Head) + basicsize);\r
- if (g == NULL)\r
- return PyErr_NoMemory();\r
- g->gc.gc_refs = GC_UNTRACKED;\r
- generations[0].count++; /* number of allocated GC objects */\r
- if (generations[0].count > generations[0].threshold &&\r
- enabled &&\r
- generations[0].threshold &&\r
- !collecting &&\r
- !PyErr_Occurred()) {\r
- collecting = 1;\r
- collect_generations();\r
- collecting = 0;\r
- }\r
- op = FROM_GC(g);\r
- return op;\r
-}\r
-\r
-PyObject *\r
-_PyObject_GC_New(PyTypeObject *tp)\r
-{\r
- PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));\r
- if (op != NULL)\r
- op = PyObject_INIT(op, tp);\r
- return op;\r
-}\r
-\r
-PyVarObject *\r
-_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)\r
-{\r
- const size_t size = _PyObject_VAR_SIZE(tp, nitems);\r
- PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);\r
- if (op != NULL)\r
- op = PyObject_INIT_VAR(op, tp, nitems);\r
- return op;\r
-}\r
-\r
-PyVarObject *\r
-_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)\r
-{\r
- const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);\r
- PyGC_Head *g = AS_GC(op);\r
- if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))\r
- return (PyVarObject *)PyErr_NoMemory();\r
- g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);\r
- if (g == NULL)\r
- return (PyVarObject *)PyErr_NoMemory();\r
- op = (PyVarObject *) FROM_GC(g);\r
- Py_SIZE(op) = nitems;\r
- return op;\r
-}\r
-\r
-void\r
-PyObject_GC_Del(void *op)\r
-{\r
- PyGC_Head *g = AS_GC(op);\r
- if (IS_TRACKED(op))\r
- gc_list_remove(g);\r
- if (generations[0].count > 0) {\r
- generations[0].count--;\r
- }\r
- PyObject_FREE(g);\r
-}\r
-\r
-/* for binary compatibility with 2.2 */\r
-#undef _PyObject_GC_Del\r
-void\r
-_PyObject_GC_Del(PyObject *op)\r
-{\r
- PyObject_GC_Del(op);\r
-}\r