gcmodule.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447
  1. /*
  2. Reference Cycle Garbage Collection
  3. ==================================
  4. Neil Schemenauer <nas@arctrix.com>
  5. Based on a post on the python-dev list. Ideas from Guido van Rossum,
  6. Eric Tiedemann, and various others.
  7. http://www.arctrix.com/nas/python/gc/
  8. The following mailing list threads provide a historical perspective on
  9. the design of this module. Note that a fair amount of refinement has
  10. occurred since those discussions.
  11. http://mail.python.org/pipermail/python-dev/2000-March/002385.html
  12. http://mail.python.org/pipermail/python-dev/2000-March/002434.html
  13. http://mail.python.org/pipermail/python-dev/2000-March/002497.html
  14. For a highlevel view of the collection process, read the collect
  15. function.
  16. */
  17. #include "Python.h"
  18. #include "pycore_context.h"
  19. #include "pycore_initconfig.h"
  20. #include "pycore_interp.h" // PyInterpreterState.gc
  21. #include "pycore_object.h"
  22. #include "pycore_pyerrors.h"
  23. #include "pycore_pystate.h" // _PyThreadState_GET()
  24. #include "pydtrace.h"
  25. typedef struct _gc_runtime_state GCState;
  26. /*[clinic input]
  27. module gc
  28. [clinic start generated code]*/
  29. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=b5c9690ecc842d79]*/
  30. #ifdef Py_DEBUG
  31. # ifndef GC_NDEBUG
  32. # define GC_DEBUG
  33. # endif
  34. #endif
  35. #define GC_NEXT _PyGCHead_NEXT
  36. #define GC_PREV _PyGCHead_PREV
  37. // update_refs() set this bit for all objects in current generation.
  38. // subtract_refs() and move_unreachable() uses this to distinguish
  39. // visited object is in GCing or not.
  40. //
  41. // move_unreachable() removes this flag from reachable objects.
  42. // Only unreachable objects have this flag.
  43. //
  44. // No objects in interpreter have this flag after GC ends.
  45. #define PREV_MASK_COLLECTING _PyGC_PREV_MASK_COLLECTING
  46. // Lowest bit of _gc_next is used for UNREACHABLE flag.
  47. //
  48. // This flag represents the object is in unreachable list in move_unreachable()
  49. //
  50. // Although this flag is used only in move_unreachable(), move_unreachable()
  51. // doesn't clear this flag to skip unnecessary iteration.
  52. // move_legacy_finalizers() removes this flag instead.
  53. // Between them, unreachable list is not normal list and we can not use
  54. // most gc_list_* functions for it.
  55. #define NEXT_MASK_UNREACHABLE (1)
  56. /* Get an object's GC head */
  57. #define AS_GC(o) ((PyGC_Head *)(((char *)(o))-sizeof(PyGC_Head)))
  58. /* Get the object given the GC head */
  59. #define FROM_GC(g) ((PyObject *)(((char *)(g))+sizeof(PyGC_Head)))
  60. static inline int
  61. gc_is_collecting(PyGC_Head *g)
  62. {
  63. return (g->_gc_prev & PREV_MASK_COLLECTING) != 0;
  64. }
  65. static inline void
  66. gc_clear_collecting(PyGC_Head *g)
  67. {
  68. g->_gc_prev &= ~PREV_MASK_COLLECTING;
  69. }
  70. static inline Py_ssize_t
  71. gc_get_refs(PyGC_Head *g)
  72. {
  73. return (Py_ssize_t)(g->_gc_prev >> _PyGC_PREV_SHIFT);
  74. }
  75. static inline void
  76. gc_set_refs(PyGC_Head *g, Py_ssize_t refs)
  77. {
  78. g->_gc_prev = (g->_gc_prev & ~_PyGC_PREV_MASK)
  79. | ((uintptr_t)(refs) << _PyGC_PREV_SHIFT);
  80. }
  81. static inline void
  82. gc_reset_refs(PyGC_Head *g, Py_ssize_t refs)
  83. {
  84. g->_gc_prev = (g->_gc_prev & _PyGC_PREV_MASK_FINALIZED)
  85. | PREV_MASK_COLLECTING
  86. | ((uintptr_t)(refs) << _PyGC_PREV_SHIFT);
  87. }
  88. static inline void
  89. gc_decref(PyGC_Head *g)
  90. {
  91. _PyObject_ASSERT_WITH_MSG(FROM_GC(g),
  92. gc_get_refs(g) > 0,
  93. "refcount is too small");
  94. g->_gc_prev -= 1 << _PyGC_PREV_SHIFT;
  95. }
  96. /* set for debugging information */
  97. #define DEBUG_STATS (1<<0) /* print collection statistics */
  98. #define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
  99. #define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
  100. #define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
  101. #define DEBUG_LEAK DEBUG_COLLECTABLE | \
  102. DEBUG_UNCOLLECTABLE | \
  103. DEBUG_SAVEALL
  104. #define GEN_HEAD(gcstate, n) (&(gcstate)->generations[n].head)
  105. static GCState *
  106. get_gc_state(void)
  107. {
  108. PyInterpreterState *interp = _PyInterpreterState_GET();
  109. return &interp->gc;
  110. }
  111. void
  112. _PyGC_InitState(GCState *gcstate)
  113. {
  114. #define INIT_HEAD(GEN) \
  115. do { \
  116. GEN.head._gc_next = (uintptr_t)&GEN.head; \
  117. GEN.head._gc_prev = (uintptr_t)&GEN.head; \
  118. } while (0)
  119. for (int i = 0; i < NUM_GENERATIONS; i++) {
  120. assert(gcstate->generations[i].count == 0);
  121. INIT_HEAD(gcstate->generations[i]);
  122. };
  123. gcstate->generation0 = GEN_HEAD(gcstate, 0);
  124. INIT_HEAD(gcstate->permanent_generation);
  125. #undef INIT_HEAD
  126. }
  127. PyStatus
  128. _PyGC_Init(PyInterpreterState *interp)
  129. {
  130. GCState *gcstate = &interp->gc;
  131. gcstate->garbage = PyList_New(0);
  132. if (gcstate->garbage == NULL) {
  133. return _PyStatus_NO_MEMORY();
  134. }
  135. gcstate->callbacks = PyList_New(0);
  136. if (gcstate->callbacks == NULL) {
  137. return _PyStatus_NO_MEMORY();
  138. }
  139. return _PyStatus_OK();
  140. }
  141. /*
  142. _gc_prev values
  143. ---------------
  144. Between collections, _gc_prev is used for doubly linked list.
  145. Lowest two bits of _gc_prev are used for flags.
  146. PREV_MASK_COLLECTING is used only while collecting and cleared before GC ends
  147. or _PyObject_GC_UNTRACK() is called.
  148. During a collection, _gc_prev is temporary used for gc_refs, and the gc list
  149. is singly linked until _gc_prev is restored.
  150. gc_refs
  151. At the start of a collection, update_refs() copies the true refcount
  152. to gc_refs, for each object in the generation being collected.
  153. subtract_refs() then adjusts gc_refs so that it equals the number of
  154. times an object is referenced directly from outside the generation
  155. being collected.
  156. PREV_MASK_COLLECTING
  157. Objects in generation being collected are marked PREV_MASK_COLLECTING in
  158. update_refs().
  159. _gc_next values
  160. ---------------
  161. _gc_next takes these values:
  162. 0
  163. The object is not tracked
  164. != 0
  165. Pointer to the next object in the GC list.
  166. Additionally, lowest bit is used temporary for
  167. NEXT_MASK_UNREACHABLE flag described below.
  168. NEXT_MASK_UNREACHABLE
  169. move_unreachable() then moves objects not reachable (whether directly or
  170. indirectly) from outside the generation into an "unreachable" set and
  171. set this flag.
  172. Objects that are found to be reachable have gc_refs set to 1.
  173. When this flag is set for the reachable object, the object must be in
  174. "unreachable" set.
  175. The flag is unset and the object is moved back to "reachable" set.
  176. move_legacy_finalizers() will remove this flag from "unreachable" set.
  177. */
  178. /*** list functions ***/
  179. static inline void
  180. gc_list_init(PyGC_Head *list)
  181. {
  182. // List header must not have flags.
  183. // We can assign pointer by simple cast.
  184. list->_gc_prev = (uintptr_t)list;
  185. list->_gc_next = (uintptr_t)list;
  186. }
  187. static inline int
  188. gc_list_is_empty(PyGC_Head *list)
  189. {
  190. return (list->_gc_next == (uintptr_t)list);
  191. }
  192. /* Append `node` to `list`. */
  193. static inline void
  194. gc_list_append(PyGC_Head *node, PyGC_Head *list)
  195. {
  196. PyGC_Head *last = (PyGC_Head *)list->_gc_prev;
  197. // last <-> node
  198. _PyGCHead_SET_PREV(node, last);
  199. _PyGCHead_SET_NEXT(last, node);
  200. // node <-> list
  201. _PyGCHead_SET_NEXT(node, list);
  202. list->_gc_prev = (uintptr_t)node;
  203. }
  204. /* Remove `node` from the gc list it's currently in. */
  205. static inline void
  206. gc_list_remove(PyGC_Head *node)
  207. {
  208. PyGC_Head *prev = GC_PREV(node);
  209. PyGC_Head *next = GC_NEXT(node);
  210. _PyGCHead_SET_NEXT(prev, next);
  211. _PyGCHead_SET_PREV(next, prev);
  212. node->_gc_next = 0; /* object is not currently tracked */
  213. }
  214. /* Move `node` from the gc list it's currently in (which is not explicitly
  215. * named here) to the end of `list`. This is semantically the same as
  216. * gc_list_remove(node) followed by gc_list_append(node, list).
  217. */
  218. static void
  219. gc_list_move(PyGC_Head *node, PyGC_Head *list)
  220. {
  221. /* Unlink from current list. */
  222. PyGC_Head *from_prev = GC_PREV(node);
  223. PyGC_Head *from_next = GC_NEXT(node);
  224. _PyGCHead_SET_NEXT(from_prev, from_next);
  225. _PyGCHead_SET_PREV(from_next, from_prev);
  226. /* Relink at end of new list. */
  227. // list must not have flags. So we can skip macros.
  228. PyGC_Head *to_prev = (PyGC_Head*)list->_gc_prev;
  229. _PyGCHead_SET_PREV(node, to_prev);
  230. _PyGCHead_SET_NEXT(to_prev, node);
  231. list->_gc_prev = (uintptr_t)node;
  232. _PyGCHead_SET_NEXT(node, list);
  233. }
  234. /* append list `from` onto list `to`; `from` becomes an empty list */
  235. static void
  236. gc_list_merge(PyGC_Head *from, PyGC_Head *to)
  237. {
  238. assert(from != to);
  239. if (!gc_list_is_empty(from)) {
  240. PyGC_Head *to_tail = GC_PREV(to);
  241. PyGC_Head *from_head = GC_NEXT(from);
  242. PyGC_Head *from_tail = GC_PREV(from);
  243. assert(from_head != from);
  244. assert(from_tail != from);
  245. _PyGCHead_SET_NEXT(to_tail, from_head);
  246. _PyGCHead_SET_PREV(from_head, to_tail);
  247. _PyGCHead_SET_NEXT(from_tail, to);
  248. _PyGCHead_SET_PREV(to, from_tail);
  249. }
  250. gc_list_init(from);
  251. }
  252. static Py_ssize_t
  253. gc_list_size(PyGC_Head *list)
  254. {
  255. PyGC_Head *gc;
  256. Py_ssize_t n = 0;
  257. for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc)) {
  258. n++;
  259. }
  260. return n;
  261. }
  262. /* Walk the list and mark all objects as non-collecting */
  263. static inline void
  264. gc_list_clear_collecting(PyGC_Head *collectable)
  265. {
  266. PyGC_Head *gc;
  267. for (gc = GC_NEXT(collectable); gc != collectable; gc = GC_NEXT(gc)) {
  268. gc_clear_collecting(gc);
  269. }
  270. }
  271. /* Append objects in a GC list to a Python list.
  272. * Return 0 if all OK, < 0 if error (out of memory for list)
  273. */
  274. static int
  275. append_objects(PyObject *py_list, PyGC_Head *gc_list)
  276. {
  277. PyGC_Head *gc;
  278. for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) {
  279. PyObject *op = FROM_GC(gc);
  280. if (op != py_list) {
  281. if (PyList_Append(py_list, op)) {
  282. return -1; /* exception */
  283. }
  284. }
  285. }
  286. return 0;
  287. }
  288. // Constants for validate_list's flags argument.
  289. enum flagstates {collecting_clear_unreachable_clear,
  290. collecting_clear_unreachable_set,
  291. collecting_set_unreachable_clear,
  292. collecting_set_unreachable_set};
  293. #ifdef GC_DEBUG
  294. // validate_list checks list consistency. And it works as document
  295. // describing when flags are expected to be set / unset.
  296. // `head` must be a doubly-linked gc list, although it's fine (expected!) if
  297. // the prev and next pointers are "polluted" with flags.
  298. // What's checked:
  299. // - The `head` pointers are not polluted.
  300. // - The objects' PREV_MASK_COLLECTING and NEXT_MASK_UNREACHABLE flags are all
  301. // `set or clear, as specified by the 'flags' argument.
  302. // - The prev and next pointers are mutually consistent.
  303. static void
  304. validate_list(PyGC_Head *head, enum flagstates flags)
  305. {
  306. assert((head->_gc_prev & PREV_MASK_COLLECTING) == 0);
  307. assert((head->_gc_next & NEXT_MASK_UNREACHABLE) == 0);
  308. uintptr_t prev_value = 0, next_value = 0;
  309. switch (flags) {
  310. case collecting_clear_unreachable_clear:
  311. break;
  312. case collecting_set_unreachable_clear:
  313. prev_value = PREV_MASK_COLLECTING;
  314. break;
  315. case collecting_clear_unreachable_set:
  316. next_value = NEXT_MASK_UNREACHABLE;
  317. break;
  318. case collecting_set_unreachable_set:
  319. prev_value = PREV_MASK_COLLECTING;
  320. next_value = NEXT_MASK_UNREACHABLE;
  321. break;
  322. default:
  323. assert(! "bad internal flags argument");
  324. }
  325. PyGC_Head *prev = head;
  326. PyGC_Head *gc = GC_NEXT(head);
  327. while (gc != head) {
  328. PyGC_Head *trueprev = GC_PREV(gc);
  329. PyGC_Head *truenext = (PyGC_Head *)(gc->_gc_next & ~NEXT_MASK_UNREACHABLE);
  330. assert(truenext != NULL);
  331. assert(trueprev == prev);
  332. assert((gc->_gc_prev & PREV_MASK_COLLECTING) == prev_value);
  333. assert((gc->_gc_next & NEXT_MASK_UNREACHABLE) == next_value);
  334. prev = gc;
  335. gc = truenext;
  336. }
  337. assert(prev == GC_PREV(head));
  338. }
  339. #else
  340. #define validate_list(x, y) do{}while(0)
  341. #endif
  342. /*** end of list stuff ***/
  343. /* Set all gc_refs = ob_refcnt. After this, gc_refs is > 0 and
  344. * PREV_MASK_COLLECTING bit is set for all objects in containers.
  345. */
  346. static void
  347. update_refs(PyGC_Head *containers)
  348. {
  349. PyGC_Head *next;
  350. PyGC_Head *gc = GC_NEXT(containers);
  351. while (gc != containers) {
  352. next = GC_NEXT(gc);
  353. /* Move any object that might have become immortal to the
  354. * permanent generation as the reference count is not accurately
  355. * reflecting the actual number of live references to this object
  356. */
  357. if (_Py_IsImmortal(FROM_GC(gc))) {
  358. gc_list_move(gc, &get_gc_state()->permanent_generation.head);
  359. gc = next;
  360. continue;
  361. }
  362. gc_reset_refs(gc, Py_REFCNT(FROM_GC(gc)));
  363. /* Python's cyclic gc should never see an incoming refcount
  364. * of 0: if something decref'ed to 0, it should have been
  365. * deallocated immediately at that time.
  366. * Possible cause (if the assert triggers): a tp_dealloc
  367. * routine left a gc-aware object tracked during its teardown
  368. * phase, and did something-- or allowed something to happen --
  369. * that called back into Python. gc can trigger then, and may
  370. * see the still-tracked dying object. Before this assert
  371. * was added, such mistakes went on to allow gc to try to
  372. * delete the object again. In a debug build, that caused
  373. * a mysterious segfault, when _Py_ForgetReference tried
  374. * to remove the object from the doubly-linked list of all
  375. * objects a second time. In a release build, an actual
  376. * double deallocation occurred, which leads to corruption
  377. * of the allocator's internal bookkeeping pointers. That's
  378. * so serious that maybe this should be a release-build
  379. * check instead of an assert?
  380. */
  381. _PyObject_ASSERT(FROM_GC(gc), gc_get_refs(gc) != 0);
  382. gc = next;
  383. }
  384. }
  385. /* A traversal callback for subtract_refs. */
  386. static int
  387. visit_decref(PyObject *op, void *parent)
  388. {
  389. _PyObject_ASSERT(_PyObject_CAST(parent), !_PyObject_IsFreed(op));
  390. if (_PyObject_IS_GC(op)) {
  391. PyGC_Head *gc = AS_GC(op);
  392. /* We're only interested in gc_refs for objects in the
  393. * generation being collected, which can be recognized
  394. * because only they have positive gc_refs.
  395. */
  396. if (gc_is_collecting(gc)) {
  397. gc_decref(gc);
  398. }
  399. }
  400. return 0;
  401. }
  402. /* Subtract internal references from gc_refs. After this, gc_refs is >= 0
  403. * for all objects in containers, and is GC_REACHABLE for all tracked gc
  404. * objects not in containers. The ones with gc_refs > 0 are directly
  405. * reachable from outside containers, and so can't be collected.
  406. */
  407. static void
  408. subtract_refs(PyGC_Head *containers)
  409. {
  410. traverseproc traverse;
  411. PyGC_Head *gc = GC_NEXT(containers);
  412. for (; gc != containers; gc = GC_NEXT(gc)) {
  413. PyObject *op = FROM_GC(gc);
  414. traverse = Py_TYPE(op)->tp_traverse;
  415. (void) traverse(op,
  416. (visitproc)visit_decref,
  417. op);
  418. }
  419. }
  420. /* A traversal callback for move_unreachable. */
  421. static int
  422. visit_reachable(PyObject *op, PyGC_Head *reachable)
  423. {
  424. if (!_PyObject_IS_GC(op)) {
  425. return 0;
  426. }
  427. PyGC_Head *gc = AS_GC(op);
  428. const Py_ssize_t gc_refs = gc_get_refs(gc);
  429. // Ignore objects in other generation.
  430. // This also skips objects "to the left" of the current position in
  431. // move_unreachable's scan of the 'young' list - they've already been
  432. // traversed, and no longer have the PREV_MASK_COLLECTING flag.
  433. if (! gc_is_collecting(gc)) {
  434. return 0;
  435. }
  436. // It would be a logic error elsewhere if the collecting flag were set on
  437. // an untracked object.
  438. assert(gc->_gc_next != 0);
  439. if (gc->_gc_next & NEXT_MASK_UNREACHABLE) {
  440. /* This had gc_refs = 0 when move_unreachable got
  441. * to it, but turns out it's reachable after all.
  442. * Move it back to move_unreachable's 'young' list,
  443. * and move_unreachable will eventually get to it
  444. * again.
  445. */
  446. // Manually unlink gc from unreachable list because the list functions
  447. // don't work right in the presence of NEXT_MASK_UNREACHABLE flags.
  448. PyGC_Head *prev = GC_PREV(gc);
  449. PyGC_Head *next = (PyGC_Head*)(gc->_gc_next & ~NEXT_MASK_UNREACHABLE);
  450. _PyObject_ASSERT(FROM_GC(prev),
  451. prev->_gc_next & NEXT_MASK_UNREACHABLE);
  452. _PyObject_ASSERT(FROM_GC(next),
  453. next->_gc_next & NEXT_MASK_UNREACHABLE);
  454. prev->_gc_next = gc->_gc_next; // copy NEXT_MASK_UNREACHABLE
  455. _PyGCHead_SET_PREV(next, prev);
  456. gc_list_append(gc, reachable);
  457. gc_set_refs(gc, 1);
  458. }
  459. else if (gc_refs == 0) {
  460. /* This is in move_unreachable's 'young' list, but
  461. * the traversal hasn't yet gotten to it. All
  462. * we need to do is tell move_unreachable that it's
  463. * reachable.
  464. */
  465. gc_set_refs(gc, 1);
  466. }
  467. /* Else there's nothing to do.
  468. * If gc_refs > 0, it must be in move_unreachable's 'young'
  469. * list, and move_unreachable will eventually get to it.
  470. */
  471. else {
  472. _PyObject_ASSERT_WITH_MSG(op, gc_refs > 0, "refcount is too small");
  473. }
  474. return 0;
  475. }
  476. /* Move the unreachable objects from young to unreachable. After this,
  477. * all objects in young don't have PREV_MASK_COLLECTING flag and
  478. * unreachable have the flag.
  479. * All objects in young after this are directly or indirectly reachable
  480. * from outside the original young; and all objects in unreachable are
  481. * not.
  482. *
  483. * This function restores _gc_prev pointer. young and unreachable are
  484. * doubly linked list after this function.
  485. * But _gc_next in unreachable list has NEXT_MASK_UNREACHABLE flag.
  486. * So we can not gc_list_* functions for unreachable until we remove the flag.
  487. */
  488. static void
  489. move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
  490. {
  491. // previous elem in the young list, used for restore gc_prev.
  492. PyGC_Head *prev = young;
  493. PyGC_Head *gc = GC_NEXT(young);
  494. /* Invariants: all objects "to the left" of us in young are reachable
  495. * (directly or indirectly) from outside the young list as it was at entry.
  496. *
  497. * All other objects from the original young "to the left" of us are in
  498. * unreachable now, and have NEXT_MASK_UNREACHABLE. All objects to the
  499. * left of us in 'young' now have been scanned, and no objects here
  500. * or to the right have been scanned yet.
  501. */
  502. while (gc != young) {
  503. if (gc_get_refs(gc)) {
  504. /* gc is definitely reachable from outside the
  505. * original 'young'. Mark it as such, and traverse
  506. * its pointers to find any other objects that may
  507. * be directly reachable from it. Note that the
  508. * call to tp_traverse may append objects to young,
  509. * so we have to wait until it returns to determine
  510. * the next object to visit.
  511. */
  512. PyObject *op = FROM_GC(gc);
  513. traverseproc traverse = Py_TYPE(op)->tp_traverse;
  514. _PyObject_ASSERT_WITH_MSG(op, gc_get_refs(gc) > 0,
  515. "refcount is too small");
  516. // NOTE: visit_reachable may change gc->_gc_next when
  517. // young->_gc_prev == gc. Don't do gc = GC_NEXT(gc) before!
  518. (void) traverse(op,
  519. (visitproc)visit_reachable,
  520. (void *)young);
  521. // relink gc_prev to prev element.
  522. _PyGCHead_SET_PREV(gc, prev);
  523. // gc is not COLLECTING state after here.
  524. gc_clear_collecting(gc);
  525. prev = gc;
  526. }
  527. else {
  528. /* This *may* be unreachable. To make progress,
  529. * assume it is. gc isn't directly reachable from
  530. * any object we've already traversed, but may be
  531. * reachable from an object we haven't gotten to yet.
  532. * visit_reachable will eventually move gc back into
  533. * young if that's so, and we'll see it again.
  534. */
  535. // Move gc to unreachable.
  536. // No need to gc->next->prev = prev because it is single linked.
  537. prev->_gc_next = gc->_gc_next;
  538. // We can't use gc_list_append() here because we use
  539. // NEXT_MASK_UNREACHABLE here.
  540. PyGC_Head *last = GC_PREV(unreachable);
  541. // NOTE: Since all objects in unreachable set has
  542. // NEXT_MASK_UNREACHABLE flag, we set it unconditionally.
  543. // But this may pollute the unreachable list head's 'next' pointer
  544. // too. That's semantically senseless but expedient here - the
  545. // damage is repaired when this function ends.
  546. last->_gc_next = (NEXT_MASK_UNREACHABLE | (uintptr_t)gc);
  547. _PyGCHead_SET_PREV(gc, last);
  548. gc->_gc_next = (NEXT_MASK_UNREACHABLE | (uintptr_t)unreachable);
  549. unreachable->_gc_prev = (uintptr_t)gc;
  550. }
  551. gc = (PyGC_Head*)prev->_gc_next;
  552. }
  553. // young->_gc_prev must be last element remained in the list.
  554. young->_gc_prev = (uintptr_t)prev;
  555. // don't let the pollution of the list head's next pointer leak
  556. unreachable->_gc_next &= ~NEXT_MASK_UNREACHABLE;
  557. }
  558. static void
  559. untrack_tuples(PyGC_Head *head)
  560. {
  561. PyGC_Head *next, *gc = GC_NEXT(head);
  562. while (gc != head) {
  563. PyObject *op = FROM_GC(gc);
  564. next = GC_NEXT(gc);
  565. if (PyTuple_CheckExact(op)) {
  566. _PyTuple_MaybeUntrack(op);
  567. }
  568. gc = next;
  569. }
  570. }
  571. /* Try to untrack all currently tracked dictionaries */
  572. static void
  573. untrack_dicts(PyGC_Head *head)
  574. {
  575. PyGC_Head *next, *gc = GC_NEXT(head);
  576. while (gc != head) {
  577. PyObject *op = FROM_GC(gc);
  578. next = GC_NEXT(gc);
  579. if (PyDict_CheckExact(op)) {
  580. _PyDict_MaybeUntrack(op);
  581. }
  582. gc = next;
  583. }
  584. }
  585. /* Return true if object has a pre-PEP 442 finalization method. */
  586. static int
  587. has_legacy_finalizer(PyObject *op)
  588. {
  589. return Py_TYPE(op)->tp_del != NULL;
  590. }
  591. /* Move the objects in unreachable with tp_del slots into `finalizers`.
  592. *
  593. * This function also removes NEXT_MASK_UNREACHABLE flag
  594. * from _gc_next in unreachable.
  595. */
  596. static void
  597. move_legacy_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
  598. {
  599. PyGC_Head *gc, *next;
  600. assert((unreachable->_gc_next & NEXT_MASK_UNREACHABLE) == 0);
  601. /* March over unreachable. Move objects with finalizers into
  602. * `finalizers`.
  603. */
  604. for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
  605. PyObject *op = FROM_GC(gc);
  606. _PyObject_ASSERT(op, gc->_gc_next & NEXT_MASK_UNREACHABLE);
  607. gc->_gc_next &= ~NEXT_MASK_UNREACHABLE;
  608. next = (PyGC_Head*)gc->_gc_next;
  609. if (has_legacy_finalizer(op)) {
  610. gc_clear_collecting(gc);
  611. gc_list_move(gc, finalizers);
  612. }
  613. }
  614. }
  615. static inline void
  616. clear_unreachable_mask(PyGC_Head *unreachable)
  617. {
  618. /* Check that the list head does not have the unreachable bit set */
  619. assert(((uintptr_t)unreachable & NEXT_MASK_UNREACHABLE) == 0);
  620. PyGC_Head *gc, *next;
  621. assert((unreachable->_gc_next & NEXT_MASK_UNREACHABLE) == 0);
  622. for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
  623. _PyObject_ASSERT((PyObject*)FROM_GC(gc), gc->_gc_next & NEXT_MASK_UNREACHABLE);
  624. gc->_gc_next &= ~NEXT_MASK_UNREACHABLE;
  625. next = (PyGC_Head*)gc->_gc_next;
  626. }
  627. validate_list(unreachable, collecting_set_unreachable_clear);
  628. }
  629. /* A traversal callback for move_legacy_finalizer_reachable. */
  630. static int
  631. visit_move(PyObject *op, PyGC_Head *tolist)
  632. {
  633. if (_PyObject_IS_GC(op)) {
  634. PyGC_Head *gc = AS_GC(op);
  635. if (gc_is_collecting(gc)) {
  636. gc_list_move(gc, tolist);
  637. gc_clear_collecting(gc);
  638. }
  639. }
  640. return 0;
  641. }
  642. /* Move objects that are reachable from finalizers, from the unreachable set
  643. * into finalizers set.
  644. */
  645. static void
  646. move_legacy_finalizer_reachable(PyGC_Head *finalizers)
  647. {
  648. traverseproc traverse;
  649. PyGC_Head *gc = GC_NEXT(finalizers);
  650. for (; gc != finalizers; gc = GC_NEXT(gc)) {
  651. /* Note that the finalizers list may grow during this. */
  652. traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
  653. (void) traverse(FROM_GC(gc),
  654. (visitproc)visit_move,
  655. (void *)finalizers);
  656. }
  657. }
  658. /* Clear all weakrefs to unreachable objects, and if such a weakref has a
  659. * callback, invoke it if necessary. Note that it's possible for such
  660. * weakrefs to be outside the unreachable set -- indeed, those are precisely
  661. * the weakrefs whose callbacks must be invoked. See gc_weakref.txt for
  662. * overview & some details. Some weakrefs with callbacks may be reclaimed
  663. * directly by this routine; the number reclaimed is the return value. Other
  664. * weakrefs with callbacks may be moved into the `old` generation. Objects
  665. * moved into `old` have gc_refs set to GC_REACHABLE; the objects remaining in
  666. * unreachable are left at GC_TENTATIVELY_UNREACHABLE. When this returns,
  667. * no object in `unreachable` is weakly referenced anymore.
  668. */
  669. static int
  670. handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
  671. {
  672. PyGC_Head *gc;
  673. PyObject *op; /* generally FROM_GC(gc) */
  674. PyWeakReference *wr; /* generally a cast of op */
  675. PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
  676. PyGC_Head *next;
  677. int num_freed = 0;
  678. gc_list_init(&wrcb_to_call);
  679. /* Clear all weakrefs to the objects in unreachable. If such a weakref
  680. * also has a callback, move it into `wrcb_to_call` if the callback
  681. * needs to be invoked. Note that we cannot invoke any callbacks until
  682. * all weakrefs to unreachable objects are cleared, lest the callback
  683. * resurrect an unreachable object via a still-active weakref. We
  684. * make another pass over wrcb_to_call, invoking callbacks, after this
  685. * pass completes.
  686. */
  687. for (gc = GC_NEXT(unreachable); gc != unreachable; gc = next) {
  688. PyWeakReference **wrlist;
  689. op = FROM_GC(gc);
  690. next = GC_NEXT(gc);
  691. if (PyWeakref_Check(op)) {
  692. /* A weakref inside the unreachable set must be cleared. If we
  693. * allow its callback to execute inside delete_garbage(), it
  694. * could expose objects that have tp_clear already called on
  695. * them. Or, it could resurrect unreachable objects. One way
  696. * this can happen is if some container objects do not implement
  697. * tp_traverse. Then, wr_object can be outside the unreachable
  698. * set but can be deallocated as a result of breaking the
  699. * reference cycle. If we don't clear the weakref, the callback
  700. * will run and potentially cause a crash. See bpo-38006 for
  701. * one example.
  702. */
  703. _PyWeakref_ClearRef((PyWeakReference *)op);
  704. }
  705. if (! _PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
  706. continue;
  707. /* It supports weakrefs. Does it have any?
  708. *
  709. * This is never triggered for static types so we can avoid the
  710. * (slightly) more costly _PyObject_GET_WEAKREFS_LISTPTR().
  711. */
  712. wrlist = _PyObject_GET_WEAKREFS_LISTPTR_FROM_OFFSET(op);
  713. /* `op` may have some weakrefs. March over the list, clear
  714. * all the weakrefs, and move the weakrefs with callbacks
  715. * that must be called into wrcb_to_call.
  716. */
  717. for (wr = *wrlist; wr != NULL; wr = *wrlist) {
  718. PyGC_Head *wrasgc; /* AS_GC(wr) */
  719. /* _PyWeakref_ClearRef clears the weakref but leaves
  720. * the callback pointer intact. Obscure: it also
  721. * changes *wrlist.
  722. */
  723. _PyObject_ASSERT((PyObject *)wr, wr->wr_object == op);
  724. _PyWeakref_ClearRef(wr);
  725. _PyObject_ASSERT((PyObject *)wr, wr->wr_object == Py_None);
  726. if (wr->wr_callback == NULL) {
  727. /* no callback */
  728. continue;
  729. }
  730. /* Headache time. `op` is going away, and is weakly referenced by
  731. * `wr`, which has a callback. Should the callback be invoked? If wr
  732. * is also trash, no:
  733. *
  734. * 1. There's no need to call it. The object and the weakref are
  735. * both going away, so it's legitimate to pretend the weakref is
  736. * going away first. The user has to ensure a weakref outlives its
  737. * referent if they want a guarantee that the wr callback will get
  738. * invoked.
  739. *
  740. * 2. It may be catastrophic to call it. If the callback is also in
  741. * cyclic trash (CT), then although the CT is unreachable from
  742. * outside the current generation, CT may be reachable from the
  743. * callback. Then the callback could resurrect insane objects.
  744. *
  745. * Since the callback is never needed and may be unsafe in this case,
  746. * wr is simply left in the unreachable set. Note that because we
  747. * already called _PyWeakref_ClearRef(wr), its callback will never
  748. * trigger.
  749. *
  750. * OTOH, if wr isn't part of CT, we should invoke the callback: the
  751. * weakref outlived the trash. Note that since wr isn't CT in this
  752. * case, its callback can't be CT either -- wr acted as an external
  753. * root to this generation, and therefore its callback did too. So
  754. * nothing in CT is reachable from the callback either, so it's hard
  755. * to imagine how calling it later could create a problem for us. wr
  756. * is moved to wrcb_to_call in this case.
  757. */
  758. if (gc_is_collecting(AS_GC(wr))) {
  759. /* it should already have been cleared above */
  760. assert(wr->wr_object == Py_None);
  761. continue;
  762. }
  763. /* Create a new reference so that wr can't go away
  764. * before we can process it again.
  765. */
  766. Py_INCREF(wr);
  767. /* Move wr to wrcb_to_call, for the next pass. */
  768. wrasgc = AS_GC(wr);
  769. assert(wrasgc != next); /* wrasgc is reachable, but
  770. next isn't, so they can't
  771. be the same */
  772. gc_list_move(wrasgc, &wrcb_to_call);
  773. }
  774. }
  775. /* Invoke the callbacks we decided to honor. It's safe to invoke them
  776. * because they can't reference unreachable objects.
  777. */
  778. while (! gc_list_is_empty(&wrcb_to_call)) {
  779. PyObject *temp;
  780. PyObject *callback;
  781. gc = (PyGC_Head*)wrcb_to_call._gc_next;
  782. op = FROM_GC(gc);
  783. _PyObject_ASSERT(op, PyWeakref_Check(op));
  784. wr = (PyWeakReference *)op;
  785. callback = wr->wr_callback;
  786. _PyObject_ASSERT(op, callback != NULL);
  787. /* copy-paste of weakrefobject.c's handle_callback() */
  788. temp = PyObject_CallOneArg(callback, (PyObject *)wr);
  789. if (temp == NULL)
  790. PyErr_WriteUnraisable(callback);
  791. else
  792. Py_DECREF(temp);
  793. /* Give up the reference we created in the first pass. When
  794. * op's refcount hits 0 (which it may or may not do right now),
  795. * op's tp_dealloc will decref op->wr_callback too. Note
  796. * that the refcount probably will hit 0 now, and because this
  797. * weakref was reachable to begin with, gc didn't already
  798. * add it to its count of freed objects. Example: a reachable
  799. * weak value dict maps some key to this reachable weakref.
  800. * The callback removes this key->weakref mapping from the
  801. * dict, leaving no other references to the weakref (excepting
  802. * ours).
  803. */
  804. Py_DECREF(op);
  805. if (wrcb_to_call._gc_next == (uintptr_t)gc) {
  806. /* object is still alive -- move it */
  807. gc_list_move(gc, old);
  808. }
  809. else {
  810. ++num_freed;
  811. }
  812. }
  813. return num_freed;
  814. }
  815. static void
  816. debug_cycle(const char *msg, PyObject *op)
  817. {
  818. PySys_FormatStderr("gc: %s <%s %p>\n",
  819. msg, Py_TYPE(op)->tp_name, op);
  820. }
  821. /* Handle uncollectable garbage (cycles with tp_del slots, and stuff reachable
  822. * only from such cycles).
  823. * If DEBUG_SAVEALL, all objects in finalizers are appended to the module
  824. * garbage list (a Python list), else only the objects in finalizers with
  825. * __del__ methods are appended to garbage. All objects in finalizers are
  826. * merged into the old list regardless.
  827. */
  828. static void
  829. handle_legacy_finalizers(PyThreadState *tstate,
  830. GCState *gcstate,
  831. PyGC_Head *finalizers, PyGC_Head *old)
  832. {
  833. assert(!_PyErr_Occurred(tstate));
  834. assert(gcstate->garbage != NULL);
  835. PyGC_Head *gc = GC_NEXT(finalizers);
  836. for (; gc != finalizers; gc = GC_NEXT(gc)) {
  837. PyObject *op = FROM_GC(gc);
  838. if ((gcstate->debug & DEBUG_SAVEALL) || has_legacy_finalizer(op)) {
  839. if (PyList_Append(gcstate->garbage, op) < 0) {
  840. _PyErr_Clear(tstate);
  841. break;
  842. }
  843. }
  844. }
  845. gc_list_merge(finalizers, old);
  846. }
  847. /* Run first-time finalizers (if any) on all the objects in collectable.
  848. * Note that this may remove some (or even all) of the objects from the
  849. * list, due to refcounts falling to 0.
  850. */
  851. static void
  852. finalize_garbage(PyThreadState *tstate, PyGC_Head *collectable)
  853. {
  854. destructor finalize;
  855. PyGC_Head seen;
  856. /* While we're going through the loop, `finalize(op)` may cause op, or
  857. * other objects, to be reclaimed via refcounts falling to zero. So
  858. * there's little we can rely on about the structure of the input
  859. * `collectable` list across iterations. For safety, we always take the
  860. * first object in that list and move it to a temporary `seen` list.
  861. * If objects vanish from the `collectable` and `seen` lists we don't
  862. * care.
  863. */
  864. gc_list_init(&seen);
  865. while (!gc_list_is_empty(collectable)) {
  866. PyGC_Head *gc = GC_NEXT(collectable);
  867. PyObject *op = FROM_GC(gc);
  868. gc_list_move(gc, &seen);
  869. if (!_PyGCHead_FINALIZED(gc) &&
  870. (finalize = Py_TYPE(op)->tp_finalize) != NULL) {
  871. _PyGCHead_SET_FINALIZED(gc);
  872. Py_INCREF(op);
  873. finalize(op);
  874. assert(!_PyErr_Occurred(tstate));
  875. Py_DECREF(op);
  876. }
  877. }
  878. gc_list_merge(&seen, collectable);
  879. }
  880. /* Break reference cycles by clearing the containers involved. This is
  881. * tricky business as the lists can be changing and we don't know which
  882. * objects may be freed. It is possible I screwed something up here.
  883. */
  884. static void
  885. delete_garbage(PyThreadState *tstate, GCState *gcstate,
  886. PyGC_Head *collectable, PyGC_Head *old)
  887. {
  888. assert(!_PyErr_Occurred(tstate));
  889. while (!gc_list_is_empty(collectable)) {
  890. PyGC_Head *gc = GC_NEXT(collectable);
  891. PyObject *op = FROM_GC(gc);
  892. _PyObject_ASSERT_WITH_MSG(op, Py_REFCNT(op) > 0,
  893. "refcount is too small");
  894. if (gcstate->debug & DEBUG_SAVEALL) {
  895. assert(gcstate->garbage != NULL);
  896. if (PyList_Append(gcstate->garbage, op) < 0) {
  897. _PyErr_Clear(tstate);
  898. }
  899. }
  900. else {
  901. inquiry clear;
  902. if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
  903. Py_INCREF(op);
  904. (void) clear(op);
  905. if (_PyErr_Occurred(tstate)) {
  906. _PyErr_WriteUnraisableMsg("in tp_clear of",
  907. (PyObject*)Py_TYPE(op));
  908. }
  909. Py_DECREF(op);
  910. }
  911. }
  912. if (GC_NEXT(collectable) == gc) {
  913. /* object is still alive, move it, it may die later */
  914. gc_clear_collecting(gc);
  915. gc_list_move(gc, old);
  916. }
  917. }
  918. }
  919. /* Clear all free lists
  920. * All free lists are cleared during the collection of the highest generation.
  921. * Allocated items in the free list may keep a pymalloc arena occupied.
  922. * Clearing the free lists may give back memory to the OS earlier.
  923. */
  924. static void
  925. clear_freelists(PyInterpreterState *interp)
  926. {
  927. _PyTuple_ClearFreeList(interp);
  928. _PyFloat_ClearFreeList(interp);
  929. _PyList_ClearFreeList(interp);
  930. _PyDict_ClearFreeList(interp);
  931. _PyAsyncGen_ClearFreeLists(interp);
  932. _PyContext_ClearFreeList(interp);
  933. }
  934. // Show stats for objects in each generations
  935. static void
  936. show_stats_each_generations(GCState *gcstate)
  937. {
  938. char buf[100];
  939. size_t pos = 0;
  940. for (int i = 0; i < NUM_GENERATIONS && pos < sizeof(buf); i++) {
  941. pos += PyOS_snprintf(buf+pos, sizeof(buf)-pos,
  942. " %zd",
  943. gc_list_size(GEN_HEAD(gcstate, i)));
  944. }
  945. PySys_FormatStderr(
  946. "gc: objects in each generation:%s\n"
  947. "gc: objects in permanent generation: %zd\n",
  948. buf, gc_list_size(&gcstate->permanent_generation.head));
  949. }
  950. /* Deduce which objects among "base" are unreachable from outside the list
  951. and move them to 'unreachable'. The process consist in the following steps:
  952. 1. Copy all reference counts to a different field (gc_prev is used to hold
  953. this copy to save memory).
  954. 2. Traverse all objects in "base" and visit all referred objects using
  955. "tp_traverse" and for every visited object, subtract 1 to the reference
  956. count (the one that we copied in the previous step). After this step, all
  957. objects that can be reached directly from outside must have strictly positive
  958. reference count, while all unreachable objects must have a count of exactly 0.
  959. 3. Identify all unreachable objects (the ones with 0 reference count) and move
  960. them to the "unreachable" list. This step also needs to move back to "base" all
  961. objects that were initially marked as unreachable but are referred transitively
  962. by the reachable objects (the ones with strictly positive reference count).
  963. Contracts:
  964. * The "base" has to be a valid list with no mask set.
  965. * The "unreachable" list must be uninitialized (this function calls
  966. gc_list_init over 'unreachable').
  967. IMPORTANT: This function leaves 'unreachable' with the NEXT_MASK_UNREACHABLE
  968. flag set but it does not clear it to skip unnecessary iteration. Before the
  969. flag is cleared (for example, by using 'clear_unreachable_mask' function or
  970. by a call to 'move_legacy_finalizers'), the 'unreachable' list is not a normal
  971. list and we can not use most gc_list_* functions for it. */
  972. static inline void
  973. deduce_unreachable(PyGC_Head *base, PyGC_Head *unreachable) {
  974. validate_list(base, collecting_clear_unreachable_clear);
  975. /* Using ob_refcnt and gc_refs, calculate which objects in the
  976. * container set are reachable from outside the set (i.e., have a
  977. * refcount greater than 0 when all the references within the
  978. * set are taken into account).
  979. */
  980. update_refs(base); // gc_prev is used for gc_refs
  981. subtract_refs(base);
  982. /* Leave everything reachable from outside base in base, and move
  983. * everything else (in base) to unreachable.
  984. *
  985. * NOTE: This used to move the reachable objects into a reachable
  986. * set instead. But most things usually turn out to be reachable,
  987. * so it's more efficient to move the unreachable things. It "sounds slick"
  988. * to move the unreachable objects, until you think about it - the reason it
  989. * pays isn't actually obvious.
  990. *
  991. * Suppose we create objects A, B, C in that order. They appear in the young
  992. * generation in the same order. If B points to A, and C to B, and C is
  993. * reachable from outside, then the adjusted refcounts will be 0, 0, and 1
  994. * respectively.
  995. *
  996. * When move_unreachable finds A, A is moved to the unreachable list. The
  997. * same for B when it's first encountered. Then C is traversed, B is moved
  998. * _back_ to the reachable list. B is eventually traversed, and then A is
  999. * moved back to the reachable list.
  1000. *
  1001. * So instead of not moving at all, the reachable objects B and A are moved
  1002. * twice each. Why is this a win? A straightforward algorithm to move the
  1003. * reachable objects instead would move A, B, and C once each.
  1004. *
  1005. * The key is that this dance leaves the objects in order C, B, A - it's
  1006. * reversed from the original order. On all _subsequent_ scans, none of
  1007. * them will move. Since most objects aren't in cycles, this can save an
  1008. * unbounded number of moves across an unbounded number of later collections.
  1009. * It can cost more only the first time the chain is scanned.
  1010. *
  1011. * Drawback: move_unreachable is also used to find out what's still trash
  1012. * after finalizers may resurrect objects. In _that_ case most unreachable
  1013. * objects will remain unreachable, so it would be more efficient to move
  1014. * the reachable objects instead. But this is a one-time cost, probably not
  1015. * worth complicating the code to speed just a little.
  1016. */
  1017. gc_list_init(unreachable);
  1018. move_unreachable(base, unreachable); // gc_prev is pointer again
  1019. validate_list(base, collecting_clear_unreachable_clear);
  1020. validate_list(unreachable, collecting_set_unreachable_set);
  1021. }
  1022. /* Handle objects that may have resurrected after a call to 'finalize_garbage', moving
  1023. them to 'old_generation' and placing the rest on 'still_unreachable'.
  1024. Contracts:
  1025. * After this function 'unreachable' must not be used anymore and 'still_unreachable'
  1026. will contain the objects that did not resurrect.
  1027. * The "still_unreachable" list must be uninitialized (this function calls
  1028. gc_list_init over 'still_unreachable').
  1029. IMPORTANT: After a call to this function, the 'still_unreachable' set will have the
  1030. PREV_MARK_COLLECTING set, but the objects in this set are going to be removed so
  1031. we can skip the expense of clearing the flag to avoid extra iteration. */
  1032. static inline void
  1033. handle_resurrected_objects(PyGC_Head *unreachable, PyGC_Head* still_unreachable,
  1034. PyGC_Head *old_generation)
  1035. {
  1036. // Remove the PREV_MASK_COLLECTING from unreachable
  1037. // to prepare it for a new call to 'deduce_unreachable'
  1038. gc_list_clear_collecting(unreachable);
  1039. // After the call to deduce_unreachable, the 'still_unreachable' set will
  1040. // have the PREV_MARK_COLLECTING set, but the objects are going to be
  1041. // removed so we can skip the expense of clearing the flag.
  1042. PyGC_Head* resurrected = unreachable;
  1043. deduce_unreachable(resurrected, still_unreachable);
  1044. clear_unreachable_mask(still_unreachable);
  1045. // Move the resurrected objects to the old generation for future collection.
  1046. gc_list_merge(resurrected, old_generation);
  1047. }
  1048. /* This is the main function. Read this to understand how the
  1049. * collection process works. */
  1050. static Py_ssize_t
  1051. gc_collect_main(PyThreadState *tstate, int generation,
  1052. Py_ssize_t *n_collected, Py_ssize_t *n_uncollectable,
  1053. int nofail)
  1054. {
  1055. int i;
  1056. Py_ssize_t m = 0; /* # objects collected */
  1057. Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
  1058. PyGC_Head *young; /* the generation we are examining */
  1059. PyGC_Head *old; /* next older generation */
  1060. PyGC_Head unreachable; /* non-problematic unreachable trash */
  1061. PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
  1062. PyGC_Head *gc;
  1063. _PyTime_t t1 = 0; /* initialize to prevent a compiler warning */
  1064. GCState *gcstate = &tstate->interp->gc;
  1065. // gc_collect_main() must not be called before _PyGC_Init
  1066. // or after _PyGC_Fini()
  1067. assert(gcstate->garbage != NULL);
  1068. assert(!_PyErr_Occurred(tstate));
  1069. if (gcstate->debug & DEBUG_STATS) {
  1070. PySys_WriteStderr("gc: collecting generation %d...\n", generation);
  1071. show_stats_each_generations(gcstate);
  1072. t1 = _PyTime_GetPerfCounter();
  1073. }
  1074. if (PyDTrace_GC_START_ENABLED())
  1075. PyDTrace_GC_START(generation);
  1076. /* update collection and allocation counters */
  1077. if (generation+1 < NUM_GENERATIONS)
  1078. gcstate->generations[generation+1].count += 1;
  1079. for (i = 0; i <= generation; i++)
  1080. gcstate->generations[i].count = 0;
  1081. /* merge younger generations with one we are currently collecting */
  1082. for (i = 0; i < generation; i++) {
  1083. gc_list_merge(GEN_HEAD(gcstate, i), GEN_HEAD(gcstate, generation));
  1084. }
  1085. /* handy references */
  1086. young = GEN_HEAD(gcstate, generation);
  1087. if (generation < NUM_GENERATIONS-1)
  1088. old = GEN_HEAD(gcstate, generation+1);
  1089. else
  1090. old = young;
  1091. validate_list(old, collecting_clear_unreachable_clear);
  1092. deduce_unreachable(young, &unreachable);
  1093. untrack_tuples(young);
  1094. /* Move reachable objects to next generation. */
  1095. if (young != old) {
  1096. if (generation == NUM_GENERATIONS - 2) {
  1097. gcstate->long_lived_pending += gc_list_size(young);
  1098. }
  1099. gc_list_merge(young, old);
  1100. }
  1101. else {
  1102. /* We only un-track dicts in full collections, to avoid quadratic
  1103. dict build-up. See issue #14775. */
  1104. untrack_dicts(young);
  1105. gcstate->long_lived_pending = 0;
  1106. gcstate->long_lived_total = gc_list_size(young);
  1107. }
  1108. /* All objects in unreachable are trash, but objects reachable from
  1109. * legacy finalizers (e.g. tp_del) can't safely be deleted.
  1110. */
  1111. gc_list_init(&finalizers);
  1112. // NEXT_MASK_UNREACHABLE is cleared here.
  1113. // After move_legacy_finalizers(), unreachable is normal list.
  1114. move_legacy_finalizers(&unreachable, &finalizers);
  1115. /* finalizers contains the unreachable objects with a legacy finalizer;
  1116. * unreachable objects reachable *from* those are also uncollectable,
  1117. * and we move those into the finalizers list too.
  1118. */
  1119. move_legacy_finalizer_reachable(&finalizers);
  1120. validate_list(&finalizers, collecting_clear_unreachable_clear);
  1121. validate_list(&unreachable, collecting_set_unreachable_clear);
  1122. /* Print debugging information. */
  1123. if (gcstate->debug & DEBUG_COLLECTABLE) {
  1124. for (gc = GC_NEXT(&unreachable); gc != &unreachable; gc = GC_NEXT(gc)) {
  1125. debug_cycle("collectable", FROM_GC(gc));
  1126. }
  1127. }
  1128. /* Clear weakrefs and invoke callbacks as necessary. */
  1129. m += handle_weakrefs(&unreachable, old);
  1130. validate_list(old, collecting_clear_unreachable_clear);
  1131. validate_list(&unreachable, collecting_set_unreachable_clear);
  1132. /* Call tp_finalize on objects which have one. */
  1133. finalize_garbage(tstate, &unreachable);
  1134. /* Handle any objects that may have resurrected after the call
  1135. * to 'finalize_garbage' and continue the collection with the
  1136. * objects that are still unreachable */
  1137. PyGC_Head final_unreachable;
  1138. handle_resurrected_objects(&unreachable, &final_unreachable, old);
  1139. /* Call tp_clear on objects in the final_unreachable set. This will cause
  1140. * the reference cycles to be broken. It may also cause some objects
  1141. * in finalizers to be freed.
  1142. */
  1143. m += gc_list_size(&final_unreachable);
  1144. delete_garbage(tstate, gcstate, &final_unreachable, old);
  1145. /* Collect statistics on uncollectable objects found and print
  1146. * debugging information. */
  1147. for (gc = GC_NEXT(&finalizers); gc != &finalizers; gc = GC_NEXT(gc)) {
  1148. n++;
  1149. if (gcstate->debug & DEBUG_UNCOLLECTABLE)
  1150. debug_cycle("uncollectable", FROM_GC(gc));
  1151. }
  1152. if (gcstate->debug & DEBUG_STATS) {
  1153. double d = _PyTime_AsSecondsDouble(_PyTime_GetPerfCounter() - t1);
  1154. PySys_WriteStderr(
  1155. "gc: done, %zd unreachable, %zd uncollectable, %.4fs elapsed\n",
  1156. n+m, n, d);
  1157. }
  1158. /* Append instances in the uncollectable set to a Python
  1159. * reachable list of garbage. The programmer has to deal with
  1160. * this if they insist on creating this type of structure.
  1161. */
  1162. handle_legacy_finalizers(tstate, gcstate, &finalizers, old);
  1163. validate_list(old, collecting_clear_unreachable_clear);
  1164. /* Clear free list only during the collection of the highest
  1165. * generation */
  1166. if (generation == NUM_GENERATIONS-1) {
  1167. clear_freelists(tstate->interp);
  1168. }
  1169. if (_PyErr_Occurred(tstate)) {
  1170. if (nofail) {
  1171. _PyErr_Clear(tstate);
  1172. }
  1173. else {
  1174. _PyErr_WriteUnraisableMsg("in garbage collection", NULL);
  1175. }
  1176. }
  1177. /* Update stats */
  1178. if (n_collected) {
  1179. *n_collected = m;
  1180. }
  1181. if (n_uncollectable) {
  1182. *n_uncollectable = n;
  1183. }
  1184. struct gc_generation_stats *stats = &gcstate->generation_stats[generation];
  1185. stats->collections++;
  1186. stats->collected += m;
  1187. stats->uncollectable += n;
  1188. if (PyDTrace_GC_DONE_ENABLED()) {
  1189. PyDTrace_GC_DONE(n + m);
  1190. }
  1191. assert(!_PyErr_Occurred(tstate));
  1192. return n + m;
  1193. }
  1194. /* Invoke progress callbacks to notify clients that garbage collection
  1195. * is starting or stopping
  1196. */
  1197. static void
  1198. invoke_gc_callback(PyThreadState *tstate, const char *phase,
  1199. int generation, Py_ssize_t collected,
  1200. Py_ssize_t uncollectable)
  1201. {
  1202. assert(!_PyErr_Occurred(tstate));
  1203. /* we may get called very early */
  1204. GCState *gcstate = &tstate->interp->gc;
  1205. if (gcstate->callbacks == NULL) {
  1206. return;
  1207. }
  1208. /* The local variable cannot be rebound, check it for sanity */
  1209. assert(PyList_CheckExact(gcstate->callbacks));
  1210. PyObject *info = NULL;
  1211. if (PyList_GET_SIZE(gcstate->callbacks) != 0) {
  1212. info = Py_BuildValue("{sisnsn}",
  1213. "generation", generation,
  1214. "collected", collected,
  1215. "uncollectable", uncollectable);
  1216. if (info == NULL) {
  1217. PyErr_WriteUnraisable(NULL);
  1218. return;
  1219. }
  1220. }
  1221. PyObject *phase_obj = PyUnicode_FromString(phase);
  1222. if (phase_obj == NULL) {
  1223. Py_XDECREF(info);
  1224. PyErr_WriteUnraisable(NULL);
  1225. return;
  1226. }
  1227. PyObject *stack[] = {phase_obj, info};
  1228. for (Py_ssize_t i=0; i<PyList_GET_SIZE(gcstate->callbacks); i++) {
  1229. PyObject *r, *cb = PyList_GET_ITEM(gcstate->callbacks, i);
  1230. Py_INCREF(cb); /* make sure cb doesn't go away */
  1231. r = PyObject_Vectorcall(cb, stack, 2, NULL);
  1232. if (r == NULL) {
  1233. PyErr_WriteUnraisable(cb);
  1234. }
  1235. else {
  1236. Py_DECREF(r);
  1237. }
  1238. Py_DECREF(cb);
  1239. }
  1240. Py_DECREF(phase_obj);
  1241. Py_XDECREF(info);
  1242. assert(!_PyErr_Occurred(tstate));
  1243. }
  1244. /* Perform garbage collection of a generation and invoke
  1245. * progress callbacks.
  1246. */
  1247. static Py_ssize_t
  1248. gc_collect_with_callback(PyThreadState *tstate, int generation)
  1249. {
  1250. assert(!_PyErr_Occurred(tstate));
  1251. Py_ssize_t result, collected, uncollectable;
  1252. invoke_gc_callback(tstate, "start", generation, 0, 0);
  1253. result = gc_collect_main(tstate, generation, &collected, &uncollectable, 0);
  1254. invoke_gc_callback(tstate, "stop", generation, collected, uncollectable);
  1255. assert(!_PyErr_Occurred(tstate));
  1256. return result;
  1257. }
  1258. static Py_ssize_t
  1259. gc_collect_generations(PyThreadState *tstate)
  1260. {
  1261. GCState *gcstate = &tstate->interp->gc;
  1262. /* Find the oldest generation (highest numbered) where the count
  1263. * exceeds the threshold. Objects in the that generation and
  1264. * generations younger than it will be collected. */
  1265. Py_ssize_t n = 0;
  1266. for (int i = NUM_GENERATIONS-1; i >= 0; i--) {
  1267. if (gcstate->generations[i].count > gcstate->generations[i].threshold) {
  1268. /* Avoid quadratic performance degradation in number
  1269. of tracked objects (see also issue #4074):
  1270. To limit the cost of garbage collection, there are two strategies;
  1271. - make each collection faster, e.g. by scanning fewer objects
  1272. - do less collections
  1273. This heuristic is about the latter strategy.
  1274. In addition to the various configurable thresholds, we only trigger a
  1275. full collection if the ratio
  1276. long_lived_pending / long_lived_total
  1277. is above a given value (hardwired to 25%).
  1278. The reason is that, while "non-full" collections (i.e., collections of
  1279. the young and middle generations) will always examine roughly the same
  1280. number of objects -- determined by the aforementioned thresholds --,
  1281. the cost of a full collection is proportional to the total number of
  1282. long-lived objects, which is virtually unbounded.
  1283. Indeed, it has been remarked that doing a full collection every
  1284. <constant number> of object creations entails a dramatic performance
  1285. degradation in workloads which consist in creating and storing lots of
  1286. long-lived objects (e.g. building a large list of GC-tracked objects would
  1287. show quadratic performance, instead of linear as expected: see issue #4074).
  1288. Using the above ratio, instead, yields amortized linear performance in
  1289. the total number of objects (the effect of which can be summarized
  1290. thusly: "each full garbage collection is more and more costly as the
  1291. number of objects grows, but we do fewer and fewer of them").
  1292. This heuristic was suggested by Martin von Löwis on python-dev in
  1293. June 2008. His original analysis and proposal can be found at:
  1294. http://mail.python.org/pipermail/python-dev/2008-June/080579.html
  1295. */
  1296. if (i == NUM_GENERATIONS - 1
  1297. && gcstate->long_lived_pending < gcstate->long_lived_total / 4)
  1298. continue;
  1299. n = gc_collect_with_callback(tstate, i);
  1300. break;
  1301. }
  1302. }
  1303. return n;
  1304. }
  1305. #include "clinic/gcmodule.c.h"
  1306. /*[clinic input]
  1307. gc.enable
  1308. Enable automatic garbage collection.
  1309. [clinic start generated code]*/
  1310. static PyObject *
  1311. gc_enable_impl(PyObject *module)
  1312. /*[clinic end generated code: output=45a427e9dce9155c input=81ac4940ca579707]*/
  1313. {
  1314. PyGC_Enable();
  1315. Py_RETURN_NONE;
  1316. }
  1317. /*[clinic input]
  1318. gc.disable
  1319. Disable automatic garbage collection.
  1320. [clinic start generated code]*/
  1321. static PyObject *
  1322. gc_disable_impl(PyObject *module)
  1323. /*[clinic end generated code: output=97d1030f7aa9d279 input=8c2e5a14e800d83b]*/
  1324. {
  1325. PyGC_Disable();
  1326. Py_RETURN_NONE;
  1327. }
  1328. /*[clinic input]
  1329. gc.isenabled -> bool
  1330. Returns true if automatic garbage collection is enabled.
  1331. [clinic start generated code]*/
  1332. static int
  1333. gc_isenabled_impl(PyObject *module)
  1334. /*[clinic end generated code: output=1874298331c49130 input=30005e0422373b31]*/
  1335. {
  1336. return PyGC_IsEnabled();
  1337. }
  1338. /*[clinic input]
  1339. gc.collect -> Py_ssize_t
  1340. generation: int(c_default="NUM_GENERATIONS - 1") = 2
  1341. Run the garbage collector.
  1342. With no arguments, run a full collection. The optional argument
  1343. may be an integer specifying which generation to collect. A ValueError
  1344. is raised if the generation number is invalid.
  1345. The number of unreachable objects is returned.
  1346. [clinic start generated code]*/
  1347. static Py_ssize_t
  1348. gc_collect_impl(PyObject *module, int generation)
  1349. /*[clinic end generated code: output=b697e633043233c7 input=40720128b682d879]*/
  1350. {
  1351. PyThreadState *tstate = _PyThreadState_GET();
  1352. if (generation < 0 || generation >= NUM_GENERATIONS) {
  1353. _PyErr_SetString(tstate, PyExc_ValueError, "invalid generation");
  1354. return -1;
  1355. }
  1356. GCState *gcstate = &tstate->interp->gc;
  1357. Py_ssize_t n;
  1358. if (gcstate->collecting) {
  1359. /* already collecting, don't do anything */
  1360. n = 0;
  1361. }
  1362. else {
  1363. gcstate->collecting = 1;
  1364. n = gc_collect_with_callback(tstate, generation);
  1365. gcstate->collecting = 0;
  1366. }
  1367. return n;
  1368. }
  1369. /*[clinic input]
  1370. gc.set_debug
  1371. flags: int
  1372. An integer that can have the following bits turned on:
  1373. DEBUG_STATS - Print statistics during collection.
  1374. DEBUG_COLLECTABLE - Print collectable objects found.
  1375. DEBUG_UNCOLLECTABLE - Print unreachable but uncollectable objects
  1376. found.
  1377. DEBUG_SAVEALL - Save objects to gc.garbage rather than freeing them.
  1378. DEBUG_LEAK - Debug leaking programs (everything but STATS).
  1379. /
  1380. Set the garbage collection debugging flags.
  1381. Debugging information is written to sys.stderr.
  1382. [clinic start generated code]*/
  1383. static PyObject *
  1384. gc_set_debug_impl(PyObject *module, int flags)
  1385. /*[clinic end generated code: output=7c8366575486b228 input=5e5ce15e84fbed15]*/
  1386. {
  1387. GCState *gcstate = get_gc_state();
  1388. gcstate->debug = flags;
  1389. Py_RETURN_NONE;
  1390. }
  1391. /*[clinic input]
  1392. gc.get_debug -> int
  1393. Get the garbage collection debugging flags.
  1394. [clinic start generated code]*/
  1395. static int
  1396. gc_get_debug_impl(PyObject *module)
  1397. /*[clinic end generated code: output=91242f3506cd1e50 input=91a101e1c3b98366]*/
  1398. {
  1399. GCState *gcstate = get_gc_state();
  1400. return gcstate->debug;
  1401. }
  1402. PyDoc_STRVAR(gc_set_thresh__doc__,
  1403. "set_threshold(threshold0, [threshold1, threshold2]) -> None\n"
  1404. "\n"
  1405. "Sets the collection thresholds. Setting threshold0 to zero disables\n"
  1406. "collection.\n");
  1407. static PyObject *
  1408. gc_set_threshold(PyObject *self, PyObject *args)
  1409. {
  1410. GCState *gcstate = get_gc_state();
  1411. if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
  1412. &gcstate->generations[0].threshold,
  1413. &gcstate->generations[1].threshold,
  1414. &gcstate->generations[2].threshold))
  1415. return NULL;
  1416. for (int i = 3; i < NUM_GENERATIONS; i++) {
  1417. /* generations higher than 2 get the same threshold */
  1418. gcstate->generations[i].threshold = gcstate->generations[2].threshold;
  1419. }
  1420. Py_RETURN_NONE;
  1421. }
  1422. /*[clinic input]
  1423. gc.get_threshold
  1424. Return the current collection thresholds.
  1425. [clinic start generated code]*/
  1426. static PyObject *
  1427. gc_get_threshold_impl(PyObject *module)
  1428. /*[clinic end generated code: output=7902bc9f41ecbbd8 input=286d79918034d6e6]*/
  1429. {
  1430. GCState *gcstate = get_gc_state();
  1431. return Py_BuildValue("(iii)",
  1432. gcstate->generations[0].threshold,
  1433. gcstate->generations[1].threshold,
  1434. gcstate->generations[2].threshold);
  1435. }
  1436. /*[clinic input]
  1437. gc.get_count
  1438. Return a three-tuple of the current collection counts.
  1439. [clinic start generated code]*/
  1440. static PyObject *
  1441. gc_get_count_impl(PyObject *module)
  1442. /*[clinic end generated code: output=354012e67b16398f input=a392794a08251751]*/
  1443. {
  1444. GCState *gcstate = get_gc_state();
  1445. return Py_BuildValue("(iii)",
  1446. gcstate->generations[0].count,
  1447. gcstate->generations[1].count,
  1448. gcstate->generations[2].count);
  1449. }
  1450. static int
  1451. referrersvisit(PyObject* obj, PyObject *objs)
  1452. {
  1453. Py_ssize_t i;
  1454. for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
  1455. if (PyTuple_GET_ITEM(objs, i) == obj)
  1456. return 1;
  1457. return 0;
  1458. }
  1459. static int
  1460. gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
  1461. {
  1462. PyGC_Head *gc;
  1463. PyObject *obj;
  1464. traverseproc traverse;
  1465. for (gc = GC_NEXT(list); gc != list; gc = GC_NEXT(gc)) {
  1466. obj = FROM_GC(gc);
  1467. traverse = Py_TYPE(obj)->tp_traverse;
  1468. if (obj == objs || obj == resultlist)
  1469. continue;
  1470. if (traverse(obj, (visitproc)referrersvisit, objs)) {
  1471. if (PyList_Append(resultlist, obj) < 0)
  1472. return 0; /* error */
  1473. }
  1474. }
  1475. return 1; /* no error */
  1476. }
  1477. PyDoc_STRVAR(gc_get_referrers__doc__,
  1478. "get_referrers(*objs) -> list\n\
  1479. Return the list of objects that directly refer to any of objs.");
  1480. static PyObject *
  1481. gc_get_referrers(PyObject *self, PyObject *args)
  1482. {
  1483. if (PySys_Audit("gc.get_referrers", "(O)", args) < 0) {
  1484. return NULL;
  1485. }
  1486. PyObject *result = PyList_New(0);
  1487. if (!result) {
  1488. return NULL;
  1489. }
  1490. GCState *gcstate = get_gc_state();
  1491. for (int i = 0; i < NUM_GENERATIONS; i++) {
  1492. if (!(gc_referrers_for(args, GEN_HEAD(gcstate, i), result))) {
  1493. Py_DECREF(result);
  1494. return NULL;
  1495. }
  1496. }
  1497. return result;
  1498. }
  1499. /* Append obj to list; return true if error (out of memory), false if OK. */
  1500. static int
  1501. referentsvisit(PyObject *obj, PyObject *list)
  1502. {
  1503. return PyList_Append(list, obj) < 0;
  1504. }
  1505. PyDoc_STRVAR(gc_get_referents__doc__,
  1506. "get_referents(*objs) -> list\n\
  1507. Return the list of objects that are directly referred to by objs.");
  1508. static PyObject *
  1509. gc_get_referents(PyObject *self, PyObject *args)
  1510. {
  1511. Py_ssize_t i;
  1512. if (PySys_Audit("gc.get_referents", "(O)", args) < 0) {
  1513. return NULL;
  1514. }
  1515. PyObject *result = PyList_New(0);
  1516. if (result == NULL)
  1517. return NULL;
  1518. for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
  1519. traverseproc traverse;
  1520. PyObject *obj = PyTuple_GET_ITEM(args, i);
  1521. if (!_PyObject_IS_GC(obj))
  1522. continue;
  1523. traverse = Py_TYPE(obj)->tp_traverse;
  1524. if (! traverse)
  1525. continue;
  1526. if (traverse(obj, (visitproc)referentsvisit, result)) {
  1527. Py_DECREF(result);
  1528. return NULL;
  1529. }
  1530. }
  1531. return result;
  1532. }
  1533. /*[clinic input]
  1534. gc.get_objects
  1535. generation: Py_ssize_t(accept={int, NoneType}, c_default="-1") = None
  1536. Generation to extract the objects from.
  1537. Return a list of objects tracked by the collector (excluding the list returned).
  1538. If generation is not None, return only the objects tracked by the collector
  1539. that are in that generation.
  1540. [clinic start generated code]*/
  1541. static PyObject *
  1542. gc_get_objects_impl(PyObject *module, Py_ssize_t generation)
  1543. /*[clinic end generated code: output=48b35fea4ba6cb0e input=ef7da9df9806754c]*/
  1544. {
  1545. PyThreadState *tstate = _PyThreadState_GET();
  1546. int i;
  1547. PyObject* result;
  1548. GCState *gcstate = &tstate->interp->gc;
  1549. if (PySys_Audit("gc.get_objects", "n", generation) < 0) {
  1550. return NULL;
  1551. }
  1552. result = PyList_New(0);
  1553. if (result == NULL) {
  1554. return NULL;
  1555. }
  1556. /* If generation is passed, we extract only that generation */
  1557. if (generation != -1) {
  1558. if (generation >= NUM_GENERATIONS) {
  1559. _PyErr_Format(tstate, PyExc_ValueError,
  1560. "generation parameter must be less than the number of "
  1561. "available generations (%i)",
  1562. NUM_GENERATIONS);
  1563. goto error;
  1564. }
  1565. if (generation < 0) {
  1566. _PyErr_SetString(tstate, PyExc_ValueError,
  1567. "generation parameter cannot be negative");
  1568. goto error;
  1569. }
  1570. if (append_objects(result, GEN_HEAD(gcstate, generation))) {
  1571. goto error;
  1572. }
  1573. return result;
  1574. }
  1575. /* If generation is not passed or None, get all objects from all generations */
  1576. for (i = 0; i < NUM_GENERATIONS; i++) {
  1577. if (append_objects(result, GEN_HEAD(gcstate, i))) {
  1578. goto error;
  1579. }
  1580. }
  1581. return result;
  1582. error:
  1583. Py_DECREF(result);
  1584. return NULL;
  1585. }
  1586. /*[clinic input]
  1587. gc.get_stats
  1588. Return a list of dictionaries containing per-generation statistics.
  1589. [clinic start generated code]*/
  1590. static PyObject *
  1591. gc_get_stats_impl(PyObject *module)
  1592. /*[clinic end generated code: output=a8ab1d8a5d26f3ab input=1ef4ed9d17b1a470]*/
  1593. {
  1594. int i;
  1595. struct gc_generation_stats stats[NUM_GENERATIONS], *st;
  1596. /* To get consistent values despite allocations while constructing
  1597. the result list, we use a snapshot of the running stats. */
  1598. GCState *gcstate = get_gc_state();
  1599. for (i = 0; i < NUM_GENERATIONS; i++) {
  1600. stats[i] = gcstate->generation_stats[i];
  1601. }
  1602. PyObject *result = PyList_New(0);
  1603. if (result == NULL)
  1604. return NULL;
  1605. for (i = 0; i < NUM_GENERATIONS; i++) {
  1606. PyObject *dict;
  1607. st = &stats[i];
  1608. dict = Py_BuildValue("{snsnsn}",
  1609. "collections", st->collections,
  1610. "collected", st->collected,
  1611. "uncollectable", st->uncollectable
  1612. );
  1613. if (dict == NULL)
  1614. goto error;
  1615. if (PyList_Append(result, dict)) {
  1616. Py_DECREF(dict);
  1617. goto error;
  1618. }
  1619. Py_DECREF(dict);
  1620. }
  1621. return result;
  1622. error:
  1623. Py_XDECREF(result);
  1624. return NULL;
  1625. }
  1626. /*[clinic input]
  1627. gc.is_tracked
  1628. obj: object
  1629. /
  1630. Returns true if the object is tracked by the garbage collector.
  1631. Simple atomic objects will return false.
  1632. [clinic start generated code]*/
  1633. static PyObject *
  1634. gc_is_tracked(PyObject *module, PyObject *obj)
  1635. /*[clinic end generated code: output=14f0103423b28e31 input=d83057f170ea2723]*/
  1636. {
  1637. PyObject *result;
  1638. if (_PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj))
  1639. result = Py_True;
  1640. else
  1641. result = Py_False;
  1642. return Py_NewRef(result);
  1643. }
  1644. /*[clinic input]
  1645. gc.is_finalized
  1646. obj: object
  1647. /
  1648. Returns true if the object has been already finalized by the GC.
  1649. [clinic start generated code]*/
  1650. static PyObject *
  1651. gc_is_finalized(PyObject *module, PyObject *obj)
  1652. /*[clinic end generated code: output=e1516ac119a918ed input=201d0c58f69ae390]*/
  1653. {
  1654. if (_PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(AS_GC(obj))) {
  1655. Py_RETURN_TRUE;
  1656. }
  1657. Py_RETURN_FALSE;
  1658. }
  1659. /*[clinic input]
  1660. gc.freeze
  1661. Freeze all current tracked objects and ignore them for future collections.
  1662. This can be used before a POSIX fork() call to make the gc copy-on-write friendly.
  1663. Note: collection before a POSIX fork() call may free pages for future allocation
  1664. which can cause copy-on-write.
  1665. [clinic start generated code]*/
  1666. static PyObject *
  1667. gc_freeze_impl(PyObject *module)
  1668. /*[clinic end generated code: output=502159d9cdc4c139 input=b602b16ac5febbe5]*/
  1669. {
  1670. GCState *gcstate = get_gc_state();
  1671. for (int i = 0; i < NUM_GENERATIONS; ++i) {
  1672. gc_list_merge(GEN_HEAD(gcstate, i), &gcstate->permanent_generation.head);
  1673. gcstate->generations[i].count = 0;
  1674. }
  1675. Py_RETURN_NONE;
  1676. }
  1677. /*[clinic input]
  1678. gc.unfreeze
  1679. Unfreeze all objects in the permanent generation.
  1680. Put all objects in the permanent generation back into oldest generation.
  1681. [clinic start generated code]*/
  1682. static PyObject *
  1683. gc_unfreeze_impl(PyObject *module)
  1684. /*[clinic end generated code: output=1c15f2043b25e169 input=2dd52b170f4cef6c]*/
  1685. {
  1686. GCState *gcstate = get_gc_state();
  1687. gc_list_merge(&gcstate->permanent_generation.head,
  1688. GEN_HEAD(gcstate, NUM_GENERATIONS-1));
  1689. Py_RETURN_NONE;
  1690. }
  1691. /*[clinic input]
  1692. gc.get_freeze_count -> Py_ssize_t
  1693. Return the number of objects in the permanent generation.
  1694. [clinic start generated code]*/
  1695. static Py_ssize_t
  1696. gc_get_freeze_count_impl(PyObject *module)
  1697. /*[clinic end generated code: output=61cbd9f43aa032e1 input=45ffbc65cfe2a6ed]*/
  1698. {
  1699. GCState *gcstate = get_gc_state();
  1700. return gc_list_size(&gcstate->permanent_generation.head);
  1701. }
  1702. PyDoc_STRVAR(gc__doc__,
  1703. "This module provides access to the garbage collector for reference cycles.\n"
  1704. "\n"
  1705. "enable() -- Enable automatic garbage collection.\n"
  1706. "disable() -- Disable automatic garbage collection.\n"
  1707. "isenabled() -- Returns true if automatic collection is enabled.\n"
  1708. "collect() -- Do a full collection right now.\n"
  1709. "get_count() -- Return the current collection counts.\n"
  1710. "get_stats() -- Return list of dictionaries containing per-generation stats.\n"
  1711. "set_debug() -- Set debugging flags.\n"
  1712. "get_debug() -- Get debugging flags.\n"
  1713. "set_threshold() -- Set the collection thresholds.\n"
  1714. "get_threshold() -- Return the current the collection thresholds.\n"
  1715. "get_objects() -- Return a list of all objects tracked by the collector.\n"
  1716. "is_tracked() -- Returns true if a given object is tracked.\n"
  1717. "is_finalized() -- Returns true if a given object has been already finalized.\n"
  1718. "get_referrers() -- Return the list of objects that refer to an object.\n"
  1719. "get_referents() -- Return the list of objects that an object refers to.\n"
  1720. "freeze() -- Freeze all tracked objects and ignore them for future collections.\n"
  1721. "unfreeze() -- Unfreeze all objects in the permanent generation.\n"
  1722. "get_freeze_count() -- Return the number of objects in the permanent generation.\n");
  1723. static PyMethodDef GcMethods[] = {
  1724. GC_ENABLE_METHODDEF
  1725. GC_DISABLE_METHODDEF
  1726. GC_ISENABLED_METHODDEF
  1727. GC_SET_DEBUG_METHODDEF
  1728. GC_GET_DEBUG_METHODDEF
  1729. GC_GET_COUNT_METHODDEF
  1730. {"set_threshold", gc_set_threshold, METH_VARARGS, gc_set_thresh__doc__},
  1731. GC_GET_THRESHOLD_METHODDEF
  1732. GC_COLLECT_METHODDEF
  1733. GC_GET_OBJECTS_METHODDEF
  1734. GC_GET_STATS_METHODDEF
  1735. GC_IS_TRACKED_METHODDEF
  1736. GC_IS_FINALIZED_METHODDEF
  1737. {"get_referrers", gc_get_referrers, METH_VARARGS,
  1738. gc_get_referrers__doc__},
  1739. {"get_referents", gc_get_referents, METH_VARARGS,
  1740. gc_get_referents__doc__},
  1741. GC_FREEZE_METHODDEF
  1742. GC_UNFREEZE_METHODDEF
  1743. GC_GET_FREEZE_COUNT_METHODDEF
  1744. {NULL, NULL} /* Sentinel */
  1745. };
  1746. static int
  1747. gcmodule_exec(PyObject *module)
  1748. {
  1749. GCState *gcstate = get_gc_state();
  1750. /* garbage and callbacks are initialized by _PyGC_Init() early in
  1751. * interpreter lifecycle. */
  1752. assert(gcstate->garbage != NULL);
  1753. if (PyModule_AddObjectRef(module, "garbage", gcstate->garbage) < 0) {
  1754. return -1;
  1755. }
  1756. assert(gcstate->callbacks != NULL);
  1757. if (PyModule_AddObjectRef(module, "callbacks", gcstate->callbacks) < 0) {
  1758. return -1;
  1759. }
  1760. #define ADD_INT(NAME) if (PyModule_AddIntConstant(module, #NAME, NAME) < 0) { return -1; }
  1761. ADD_INT(DEBUG_STATS);
  1762. ADD_INT(DEBUG_COLLECTABLE);
  1763. ADD_INT(DEBUG_UNCOLLECTABLE);
  1764. ADD_INT(DEBUG_SAVEALL);
  1765. ADD_INT(DEBUG_LEAK);
  1766. #undef ADD_INT
  1767. return 0;
  1768. }
  1769. static PyModuleDef_Slot gcmodule_slots[] = {
  1770. {Py_mod_exec, gcmodule_exec},
  1771. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1772. {0, NULL}
  1773. };
  1774. static struct PyModuleDef gcmodule = {
  1775. PyModuleDef_HEAD_INIT,
  1776. .m_name = "gc",
  1777. .m_doc = gc__doc__,
  1778. .m_size = 0, // per interpreter state, see: get_gc_state()
  1779. .m_methods = GcMethods,
  1780. .m_slots = gcmodule_slots
  1781. };
  1782. PyMODINIT_FUNC
  1783. PyInit_gc(void)
  1784. {
  1785. return PyModuleDef_Init(&gcmodule);
  1786. }
  1787. /* C API for controlling the state of the garbage collector */
  1788. int
  1789. PyGC_Enable(void)
  1790. {
  1791. GCState *gcstate = get_gc_state();
  1792. int old_state = gcstate->enabled;
  1793. gcstate->enabled = 1;
  1794. return old_state;
  1795. }
  1796. int
  1797. PyGC_Disable(void)
  1798. {
  1799. GCState *gcstate = get_gc_state();
  1800. int old_state = gcstate->enabled;
  1801. gcstate->enabled = 0;
  1802. return old_state;
  1803. }
  1804. int
  1805. PyGC_IsEnabled(void)
  1806. {
  1807. GCState *gcstate = get_gc_state();
  1808. return gcstate->enabled;
  1809. }
  1810. /* Public API to invoke gc.collect() from C */
  1811. Py_ssize_t
  1812. PyGC_Collect(void)
  1813. {
  1814. PyThreadState *tstate = _PyThreadState_GET();
  1815. GCState *gcstate = &tstate->interp->gc;
  1816. if (!gcstate->enabled) {
  1817. return 0;
  1818. }
  1819. Py_ssize_t n;
  1820. if (gcstate->collecting) {
  1821. /* already collecting, don't do anything */
  1822. n = 0;
  1823. }
  1824. else {
  1825. gcstate->collecting = 1;
  1826. PyObject *exc = _PyErr_GetRaisedException(tstate);
  1827. n = gc_collect_with_callback(tstate, NUM_GENERATIONS - 1);
  1828. _PyErr_SetRaisedException(tstate, exc);
  1829. gcstate->collecting = 0;
  1830. }
  1831. return n;
  1832. }
  1833. Py_ssize_t
  1834. _PyGC_CollectNoFail(PyThreadState *tstate)
  1835. {
  1836. /* Ideally, this function is only called on interpreter shutdown,
  1837. and therefore not recursively. Unfortunately, when there are daemon
  1838. threads, a daemon thread can start a cyclic garbage collection
  1839. during interpreter shutdown (and then never finish it).
  1840. See http://bugs.python.org/issue8713#msg195178 for an example.
  1841. */
  1842. GCState *gcstate = &tstate->interp->gc;
  1843. if (gcstate->collecting) {
  1844. return 0;
  1845. }
  1846. Py_ssize_t n;
  1847. gcstate->collecting = 1;
  1848. n = gc_collect_main(tstate, NUM_GENERATIONS - 1, NULL, NULL, 1);
  1849. gcstate->collecting = 0;
  1850. return n;
  1851. }
  1852. void
  1853. _PyGC_DumpShutdownStats(PyInterpreterState *interp)
  1854. {
  1855. GCState *gcstate = &interp->gc;
  1856. if (!(gcstate->debug & DEBUG_SAVEALL)
  1857. && gcstate->garbage != NULL && PyList_GET_SIZE(gcstate->garbage) > 0) {
  1858. const char *message;
  1859. if (gcstate->debug & DEBUG_UNCOLLECTABLE)
  1860. message = "gc: %zd uncollectable objects at " \
  1861. "shutdown";
  1862. else
  1863. message = "gc: %zd uncollectable objects at " \
  1864. "shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them";
  1865. /* PyErr_WarnFormat does too many things and we are at shutdown,
  1866. the warnings module's dependencies (e.g. linecache) may be gone
  1867. already. */
  1868. if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
  1869. "gc", NULL, message,
  1870. PyList_GET_SIZE(gcstate->garbage)))
  1871. PyErr_WriteUnraisable(NULL);
  1872. if (gcstate->debug & DEBUG_UNCOLLECTABLE) {
  1873. PyObject *repr = NULL, *bytes = NULL;
  1874. repr = PyObject_Repr(gcstate->garbage);
  1875. if (!repr || !(bytes = PyUnicode_EncodeFSDefault(repr)))
  1876. PyErr_WriteUnraisable(gcstate->garbage);
  1877. else {
  1878. PySys_WriteStderr(
  1879. " %s\n",
  1880. PyBytes_AS_STRING(bytes)
  1881. );
  1882. }
  1883. Py_XDECREF(repr);
  1884. Py_XDECREF(bytes);
  1885. }
  1886. }
  1887. }
  1888. void
  1889. _PyGC_Fini(PyInterpreterState *interp)
  1890. {
  1891. GCState *gcstate = &interp->gc;
  1892. Py_CLEAR(gcstate->garbage);
  1893. Py_CLEAR(gcstate->callbacks);
  1894. /* We expect that none of this interpreters objects are shared
  1895. with other interpreters.
  1896. See https://github.com/python/cpython/issues/90228. */
  1897. }
  1898. /* for debugging */
  1899. void
  1900. _PyGC_Dump(PyGC_Head *g)
  1901. {
  1902. _PyObject_Dump(FROM_GC(g));
  1903. }
  1904. #ifdef Py_DEBUG
  1905. static int
  1906. visit_validate(PyObject *op, void *parent_raw)
  1907. {
  1908. PyObject *parent = _PyObject_CAST(parent_raw);
  1909. if (_PyObject_IsFreed(op)) {
  1910. _PyObject_ASSERT_FAILED_MSG(parent,
  1911. "PyObject_GC_Track() object is not valid");
  1912. }
  1913. return 0;
  1914. }
  1915. #endif
  1916. /* extension modules might be compiled with GC support so these
  1917. functions must always be available */
  1918. void
  1919. PyObject_GC_Track(void *op_raw)
  1920. {
  1921. PyObject *op = _PyObject_CAST(op_raw);
  1922. if (_PyObject_GC_IS_TRACKED(op)) {
  1923. _PyObject_ASSERT_FAILED_MSG(op,
  1924. "object already tracked "
  1925. "by the garbage collector");
  1926. }
  1927. _PyObject_GC_TRACK(op);
  1928. #ifdef Py_DEBUG
  1929. /* Check that the object is valid: validate objects traversed
  1930. by tp_traverse() */
  1931. traverseproc traverse = Py_TYPE(op)->tp_traverse;
  1932. (void)traverse(op, visit_validate, op);
  1933. #endif
  1934. }
  1935. void
  1936. PyObject_GC_UnTrack(void *op_raw)
  1937. {
  1938. PyObject *op = _PyObject_CAST(op_raw);
  1939. /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
  1940. * call PyObject_GC_UnTrack twice on an object.
  1941. */
  1942. if (_PyObject_GC_IS_TRACKED(op)) {
  1943. _PyObject_GC_UNTRACK(op);
  1944. }
  1945. }
  1946. int
  1947. PyObject_IS_GC(PyObject *obj)
  1948. {
  1949. return _PyObject_IS_GC(obj);
  1950. }
  1951. void
  1952. _Py_ScheduleGC(PyInterpreterState *interp)
  1953. {
  1954. GCState *gcstate = &interp->gc;
  1955. if (gcstate->collecting == 1) {
  1956. return;
  1957. }
  1958. struct _ceval_state *ceval = &interp->ceval;
  1959. if (!_Py_atomic_load_relaxed(&ceval->gc_scheduled)) {
  1960. _Py_atomic_store_relaxed(&ceval->gc_scheduled, 1);
  1961. _Py_atomic_store_relaxed(&ceval->eval_breaker, 1);
  1962. }
  1963. }
  1964. void
  1965. _PyObject_GC_Link(PyObject *op)
  1966. {
  1967. PyGC_Head *g = AS_GC(op);
  1968. assert(((uintptr_t)g & (sizeof(uintptr_t)-1)) == 0); // g must be correctly aligned
  1969. PyThreadState *tstate = _PyThreadState_GET();
  1970. GCState *gcstate = &tstate->interp->gc;
  1971. g->_gc_next = 0;
  1972. g->_gc_prev = 0;
  1973. gcstate->generations[0].count++; /* number of allocated GC objects */
  1974. if (gcstate->generations[0].count > gcstate->generations[0].threshold &&
  1975. gcstate->enabled &&
  1976. gcstate->generations[0].threshold &&
  1977. !gcstate->collecting &&
  1978. !_PyErr_Occurred(tstate))
  1979. {
  1980. _Py_ScheduleGC(tstate->interp);
  1981. }
  1982. }
  1983. void
  1984. _Py_RunGC(PyThreadState *tstate)
  1985. {
  1986. GCState *gcstate = &tstate->interp->gc;
  1987. if (!gcstate->enabled) {
  1988. return;
  1989. }
  1990. gcstate->collecting = 1;
  1991. gc_collect_generations(tstate);
  1992. gcstate->collecting = 0;
  1993. }
  1994. static PyObject *
  1995. gc_alloc(size_t basicsize, size_t presize)
  1996. {
  1997. PyThreadState *tstate = _PyThreadState_GET();
  1998. if (basicsize > PY_SSIZE_T_MAX - presize) {
  1999. return _PyErr_NoMemory(tstate);
  2000. }
  2001. size_t size = presize + basicsize;
  2002. char *mem = PyObject_Malloc(size);
  2003. if (mem == NULL) {
  2004. return _PyErr_NoMemory(tstate);
  2005. }
  2006. ((PyObject **)mem)[0] = NULL;
  2007. ((PyObject **)mem)[1] = NULL;
  2008. PyObject *op = (PyObject *)(mem + presize);
  2009. _PyObject_GC_Link(op);
  2010. return op;
  2011. }
  2012. PyObject *
  2013. _PyObject_GC_New(PyTypeObject *tp)
  2014. {
  2015. size_t presize = _PyType_PreHeaderSize(tp);
  2016. PyObject *op = gc_alloc(_PyObject_SIZE(tp), presize);
  2017. if (op == NULL) {
  2018. return NULL;
  2019. }
  2020. _PyObject_Init(op, tp);
  2021. return op;
  2022. }
  2023. PyVarObject *
  2024. _PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
  2025. {
  2026. PyVarObject *op;
  2027. if (nitems < 0) {
  2028. PyErr_BadInternalCall();
  2029. return NULL;
  2030. }
  2031. size_t presize = _PyType_PreHeaderSize(tp);
  2032. size_t size = _PyObject_VAR_SIZE(tp, nitems);
  2033. op = (PyVarObject *)gc_alloc(size, presize);
  2034. if (op == NULL) {
  2035. return NULL;
  2036. }
  2037. _PyObject_InitVar(op, tp, nitems);
  2038. return op;
  2039. }
  2040. PyObject *
  2041. PyUnstable_Object_GC_NewWithExtraData(PyTypeObject *tp, size_t extra_size)
  2042. {
  2043. size_t presize = _PyType_PreHeaderSize(tp);
  2044. PyObject *op = gc_alloc(_PyObject_SIZE(tp) + extra_size, presize);
  2045. if (op == NULL) {
  2046. return NULL;
  2047. }
  2048. memset(op, 0, _PyObject_SIZE(tp) + extra_size);
  2049. _PyObject_Init(op, tp);
  2050. return op;
  2051. }
  2052. PyVarObject *
  2053. _PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
  2054. {
  2055. const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
  2056. const size_t presize = _PyType_PreHeaderSize(((PyObject *)op)->ob_type);
  2057. _PyObject_ASSERT((PyObject *)op, !_PyObject_GC_IS_TRACKED(op));
  2058. if (basicsize > (size_t)PY_SSIZE_T_MAX - presize) {
  2059. return (PyVarObject *)PyErr_NoMemory();
  2060. }
  2061. char *mem = (char *)op - presize;
  2062. mem = (char *)PyObject_Realloc(mem, presize + basicsize);
  2063. if (mem == NULL) {
  2064. return (PyVarObject *)PyErr_NoMemory();
  2065. }
  2066. op = (PyVarObject *) (mem + presize);
  2067. Py_SET_SIZE(op, nitems);
  2068. return op;
  2069. }
  2070. void
  2071. PyObject_GC_Del(void *op)
  2072. {
  2073. size_t presize = _PyType_PreHeaderSize(((PyObject *)op)->ob_type);
  2074. PyGC_Head *g = AS_GC(op);
  2075. if (_PyObject_GC_IS_TRACKED(op)) {
  2076. gc_list_remove(g);
  2077. #ifdef Py_DEBUG
  2078. PyObject *exc = PyErr_GetRaisedException();
  2079. if (PyErr_WarnExplicitFormat(PyExc_ResourceWarning, "gc", 0,
  2080. "gc", NULL, "Object of type %s is not untracked before destruction",
  2081. ((PyObject*)op)->ob_type->tp_name)) {
  2082. PyErr_WriteUnraisable(NULL);
  2083. }
  2084. PyErr_SetRaisedException(exc);
  2085. #endif
  2086. }
  2087. GCState *gcstate = get_gc_state();
  2088. if (gcstate->generations[0].count > 0) {
  2089. gcstate->generations[0].count--;
  2090. }
  2091. PyObject_Free(((char *)op)-presize);
  2092. }
  2093. int
  2094. PyObject_GC_IsTracked(PyObject* obj)
  2095. {
  2096. if (_PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj)) {
  2097. return 1;
  2098. }
  2099. return 0;
  2100. }
  2101. int
  2102. PyObject_GC_IsFinalized(PyObject *obj)
  2103. {
  2104. if (_PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(AS_GC(obj))) {
  2105. return 1;
  2106. }
  2107. return 0;
  2108. }
  2109. void
  2110. PyUnstable_GC_VisitObjects(gcvisitobjects_t callback, void *arg)
  2111. {
  2112. size_t i;
  2113. GCState *gcstate = get_gc_state();
  2114. int origenstate = gcstate->enabled;
  2115. gcstate->enabled = 0;
  2116. for (i = 0; i < NUM_GENERATIONS; i++) {
  2117. PyGC_Head *gc_list, *gc;
  2118. gc_list = GEN_HEAD(gcstate, i);
  2119. for (gc = GC_NEXT(gc_list); gc != gc_list; gc = GC_NEXT(gc)) {
  2120. PyObject *op = FROM_GC(gc);
  2121. Py_INCREF(op);
  2122. int res = callback(op, arg);
  2123. Py_DECREF(op);
  2124. if (!res) {
  2125. goto done;
  2126. }
  2127. }
  2128. }
  2129. done:
  2130. gcstate->enabled = origenstate;
  2131. }