nsCycleCollector.cpp 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. //
  6. // This file implements a garbage-cycle collector based on the paper
  7. //
  8. // Concurrent Cycle Collection in Reference Counted Systems
  9. // Bacon & Rajan (2001), ECOOP 2001 / Springer LNCS vol 2072
  10. //
  11. // We are not using the concurrent or acyclic cases of that paper; so
  12. // the green, red and orange colors are not used.
  13. //
  14. // The collector is based on tracking pointers of four colors:
  15. //
  16. // Black nodes are definitely live. If we ever determine a node is
  17. // black, it's ok to forget about, drop from our records.
  18. //
  19. // White nodes are definitely garbage cycles. Once we finish with our
  20. // scanning, we unlink all the white nodes and expect that by
  21. // unlinking them they will self-destruct (since a garbage cycle is
  22. // only keeping itself alive with internal links, by definition).
  23. //
  24. // Snow-white is an addition to the original algorithm. Snow-white object
  25. // has reference count zero and is just waiting for deletion.
  26. //
  27. // Grey nodes are being scanned. Nodes that turn grey will turn
  28. // either black if we determine that they're live, or white if we
  29. // determine that they're a garbage cycle. After the main collection
  30. // algorithm there should be no grey nodes.
  31. //
  32. // Purple nodes are *candidates* for being scanned. They are nodes we
  33. // haven't begun scanning yet because they're not old enough, or we're
  34. // still partway through the algorithm.
  35. //
  36. // XPCOM objects participating in garbage-cycle collection are obliged
  37. // to inform us when they ought to turn purple; that is, when their
  38. // refcount transitions from N+1 -> N, for nonzero N. Furthermore we
  39. // require that *after* an XPCOM object has informed us of turning
  40. // purple, they will tell us when they either transition back to being
  41. // black (incremented refcount) or are ultimately deleted.
  42. // Incremental cycle collection
  43. //
  44. // Beyond the simple state machine required to implement incremental
  45. // collection, the CC needs to be able to compensate for things the browser
  46. // is doing during the collection. There are two kinds of problems. For each
  47. // of these, there are two cases to deal with: purple-buffered C++ objects
  48. // and JS objects.
  49. // The first problem is that an object in the CC's graph can become garbage.
  50. // This is bad because the CC touches the objects in its graph at every
  51. // stage of its operation.
  52. //
  53. // All cycle collected C++ objects that die during a cycle collection
  54. // will end up actually getting deleted by the SnowWhiteKiller. Before
  55. // the SWK deletes an object, it checks if an ICC is running, and if so,
  56. // if the object is in the graph. If it is, the CC clears mPointer and
  57. // mParticipant so it does not point to the raw object any more. Because
  58. // objects could die any time the CC returns to the mutator, any time the CC
  59. // accesses a PtrInfo it must perform a null check on mParticipant to
  60. // ensure the object has not gone away.
  61. //
  62. // JS objects don't always run finalizers, so the CC can't remove them from
  63. // the graph when they die. Fortunately, JS objects can only die during a GC,
  64. // so if a GC is begun during an ICC, the browser synchronously finishes off
  65. // the ICC, which clears the entire CC graph. If the GC and CC are scheduled
  66. // properly, this should be rare.
  67. //
  68. // The second problem is that objects in the graph can be changed, say by
  69. // being addrefed or released, or by having a field updated, after the object
  70. // has been added to the graph. The problem is that ICC can miss a newly
  71. // created reference to an object, and end up unlinking an object that is
  72. // actually alive.
  73. //
  74. // The basic idea of the solution, from "An on-the-fly Reference Counting
  75. // Garbage Collector for Java" by Levanoni and Petrank, is to notice if an
  76. // object has had an additional reference to it created during the collection,
  77. // and if so, don't collect it during the current collection. This avoids having
  78. // to rerun the scan as in Bacon & Rajan 2001.
  79. //
  80. // For cycle collected C++ objects, we modify AddRef to place the object in
  81. // the purple buffer, in addition to Release. Then, in the CC, we treat any
  82. // objects in the purple buffer as being alive, after graph building has
  83. // completed. Because they are in the purple buffer, they will be suspected
  84. // in the next CC, so there's no danger of leaks. This is imprecise, because
  85. // we will treat as live an object that has been Released but not AddRefed
  86. // during graph building, but that's probably rare enough that the additional
  87. // bookkeeping overhead is not worthwhile.
  88. //
  89. // For JS objects, the cycle collector is only looking at gray objects. If a
  90. // gray object is touched during ICC, it will be made black by UnmarkGray.
  91. // Thus, if a JS object has become black during the ICC, we treat it as live.
  92. // Merged JS zones have to be handled specially: we scan all zone globals.
  93. // If any are black, we treat the zone as being black.
  94. // Safety
  95. //
  96. // An XPCOM object is either scan-safe or scan-unsafe, purple-safe or
  97. // purple-unsafe.
  98. //
  99. // An nsISupports object is scan-safe if:
  100. //
  101. // - It can be QI'ed to |nsXPCOMCycleCollectionParticipant|, though
  102. // this operation loses ISupports identity (like nsIClassInfo).
  103. // - Additionally, the operation |traverse| on the resulting
  104. // nsXPCOMCycleCollectionParticipant does not cause *any* refcount
  105. // adjustment to occur (no AddRef / Release calls).
  106. //
  107. // A non-nsISupports ("native") object is scan-safe by explicitly
  108. // providing its nsCycleCollectionParticipant.
  109. //
  110. // An object is purple-safe if it satisfies the following properties:
  111. //
  112. // - The object is scan-safe.
  113. //
  114. // When we receive a pointer |ptr| via
  115. // |nsCycleCollector::suspect(ptr)|, we assume it is purple-safe. We
  116. // can check the scan-safety, but have no way to ensure the
  117. // purple-safety; objects must obey, or else the entire system falls
  118. // apart. Don't involve an object in this scheme if you can't
  119. // guarantee its purple-safety. The easiest way to ensure that an
  120. // object is purple-safe is to use nsCycleCollectingAutoRefCnt.
  121. //
  122. // When we have a scannable set of purple nodes ready, we begin
  123. // our walks. During the walks, the nodes we |traverse| should only
  124. // feed us more scan-safe nodes, and should not adjust the refcounts
  125. // of those nodes.
  126. //
  127. // We do not |AddRef| or |Release| any objects during scanning. We
  128. // rely on the purple-safety of the roots that call |suspect| to
  129. // hold, such that we will clear the pointer from the purple buffer
  130. // entry to the object before it is destroyed. The pointers that are
  131. // merely scan-safe we hold only for the duration of scanning, and
  132. // there should be no objects released from the scan-safe set during
  133. // the scan.
  134. //
  135. // We *do* call |Root| and |Unroot| on every white object, on
  136. // either side of the calls to |Unlink|. This keeps the set of white
  137. // objects alive during the unlinking.
  138. //
  139. #if !defined(__MINGW32__)
  140. #ifdef WIN32
  141. #include <crtdbg.h>
  142. #include <errno.h>
  143. #endif
  144. #endif
  145. #include "base/process_util.h"
  146. #include "mozilla/ArrayUtils.h"
  147. #include "mozilla/AutoRestore.h"
  148. #include "mozilla/CycleCollectedJSContext.h"
  149. #include "mozilla/DebugOnly.h"
  150. #include "mozilla/HoldDropJSObjects.h"
  151. /* This must occur *after* base/process_util.h to avoid typedefs conflicts. */
  152. #include "mozilla/LinkedList.h"
  153. #include "mozilla/MemoryReporting.h"
  154. #include "mozilla/Move.h"
  155. #include "mozilla/SegmentedVector.h"
  156. #include "nsCycleCollectionParticipant.h"
  157. #include "nsCycleCollectionNoteRootCallback.h"
  158. #include "nsDeque.h"
  159. #include "nsCycleCollector.h"
  160. #include "nsThreadUtils.h"
  161. #include "nsXULAppAPI.h"
  162. #include "prenv.h"
  163. #include "nsPrintfCString.h"
  164. #include "nsTArray.h"
  165. #include "nsIConsoleService.h"
  166. #include "mozilla/Attributes.h"
  167. #include "nsICycleCollectorListener.h"
  168. #include "nsIMemoryReporter.h"
  169. #include "nsIFile.h"
  170. #include "nsDumpUtils.h"
  171. #include "xpcpublic.h"
  172. #include "GeckoProfiler.h"
  173. #include <stdint.h>
  174. #include <stdio.h>
  175. #include "mozilla/AutoGlobalTimelineMarker.h"
  176. #include "mozilla/Likely.h"
  177. #include "mozilla/PoisonIOInterposer.h"
  178. #include "mozilla/ThreadLocal.h"
  179. using namespace mozilla;
  180. //#define COLLECT_TIME_DEBUG
  181. // Enable assertions that are useful for diagnosing errors in graph construction.
  182. //#define DEBUG_CC_GRAPH
  183. #define DEFAULT_SHUTDOWN_COLLECTIONS 5
  184. // One to do the freeing, then another to detect there is no more work to do.
  185. #define NORMAL_SHUTDOWN_COLLECTIONS 2
  186. // Cycle collector environment variables
  187. //
  188. // MOZ_CC_LOG_ALL: If defined, always log cycle collector heaps.
  189. //
  190. // MOZ_CC_LOG_SHUTDOWN: If defined, log cycle collector heaps at shutdown.
  191. //
  192. // MOZ_CC_LOG_THREAD: If set to "main", only automatically log main thread
  193. // CCs. If set to "worker", only automatically log worker CCs. If set to "all",
  194. // log either. The default value is "all". This must be used with either
  195. // MOZ_CC_LOG_ALL or MOZ_CC_LOG_SHUTDOWN for it to do anything.
  196. //
  197. // MOZ_CC_LOG_PROCESS: If set to "main", only automatically log main process
  198. // CCs. If set to "content", only automatically log tab CCs. If set to
  199. // "plugins", only automatically log plugin CCs. If set to "all", log
  200. // everything. The default value is "all". This must be used with either
  201. // MOZ_CC_LOG_ALL or MOZ_CC_LOG_SHUTDOWN for it to do anything.
  202. //
  203. // MOZ_CC_ALL_TRACES: If set to "all", any cycle collector
  204. // logging done will be WantAllTraces, which disables
  205. // various cycle collector optimizations to give a fuller picture of
  206. // the heap. If set to "shutdown", only shutdown logging will be WantAllTraces.
  207. // The default is none.
  208. //
  209. // MOZ_CC_RUN_DURING_SHUTDOWN: In non-DEBUG or builds, if this is set,
  210. // run cycle collections at shutdown.
  211. //
  212. // MOZ_CC_LOG_DIRECTORY: The directory in which logs are placed (such as
  213. // logs from MOZ_CC_LOG_ALL and MOZ_CC_LOG_SHUTDOWN, or other uses
  214. // of nsICycleCollectorListener)
  215. // Various parameters of this collector can be tuned using environment
  216. // variables.
  217. struct nsCycleCollectorParams
  218. {
  219. bool mLogAll;
  220. bool mLogShutdown;
  221. bool mAllTracesAll;
  222. bool mAllTracesShutdown;
  223. bool mLogThisThread;
  224. nsCycleCollectorParams() :
  225. mLogAll(PR_GetEnv("MOZ_CC_LOG_ALL") != nullptr),
  226. mLogShutdown(PR_GetEnv("MOZ_CC_LOG_SHUTDOWN") != nullptr),
  227. mAllTracesAll(false),
  228. mAllTracesShutdown(false)
  229. {
  230. const char* logThreadEnv = PR_GetEnv("MOZ_CC_LOG_THREAD");
  231. bool threadLogging = true;
  232. if (logThreadEnv && !!strcmp(logThreadEnv, "all")) {
  233. if (NS_IsMainThread()) {
  234. threadLogging = !strcmp(logThreadEnv, "main");
  235. } else {
  236. threadLogging = !strcmp(logThreadEnv, "worker");
  237. }
  238. }
  239. const char* logProcessEnv = PR_GetEnv("MOZ_CC_LOG_PROCESS");
  240. bool processLogging = true;
  241. if (logProcessEnv && !!strcmp(logProcessEnv, "all")) {
  242. switch (XRE_GetProcessType()) {
  243. case GeckoProcessType_Default:
  244. processLogging = !strcmp(logProcessEnv, "main");
  245. break;
  246. case GeckoProcessType_Plugin:
  247. processLogging = !strcmp(logProcessEnv, "plugins");
  248. break;
  249. case GeckoProcessType_Content:
  250. processLogging = !strcmp(logProcessEnv, "content");
  251. break;
  252. default:
  253. processLogging = false;
  254. break;
  255. }
  256. }
  257. mLogThisThread = threadLogging && processLogging;
  258. const char* allTracesEnv = PR_GetEnv("MOZ_CC_ALL_TRACES");
  259. if (allTracesEnv) {
  260. if (!strcmp(allTracesEnv, "all")) {
  261. mAllTracesAll = true;
  262. } else if (!strcmp(allTracesEnv, "shutdown")) {
  263. mAllTracesShutdown = true;
  264. }
  265. }
  266. }
  267. bool LogThisCC(bool aIsShutdown)
  268. {
  269. return (mLogAll || (aIsShutdown && mLogShutdown)) && mLogThisThread;
  270. }
  271. bool AllTracesThisCC(bool aIsShutdown)
  272. {
  273. return mAllTracesAll || (aIsShutdown && mAllTracesShutdown);
  274. }
  275. };
  276. #ifdef COLLECT_TIME_DEBUG
  277. class TimeLog
  278. {
  279. public:
  280. TimeLog() : mLastCheckpoint(TimeStamp::Now())
  281. {
  282. }
  283. void
  284. Checkpoint(const char* aEvent)
  285. {
  286. TimeStamp now = TimeStamp::Now();
  287. double dur = (now - mLastCheckpoint).ToMilliseconds();
  288. if (dur >= 0.5) {
  289. printf("cc: %s took %.1fms\n", aEvent, dur);
  290. }
  291. mLastCheckpoint = now;
  292. }
  293. private:
  294. TimeStamp mLastCheckpoint;
  295. };
  296. #else
  297. class TimeLog
  298. {
  299. public:
  300. TimeLog()
  301. {
  302. }
  303. void Checkpoint(const char* aEvent)
  304. {
  305. }
  306. };
  307. #endif
  308. ////////////////////////////////////////////////////////////////////////
  309. // Base types
  310. ////////////////////////////////////////////////////////////////////////
  311. struct PtrInfo;
  312. class EdgePool
  313. {
  314. public:
  315. // EdgePool allocates arrays of void*, primarily to hold PtrInfo*.
  316. // However, at the end of a block, the last two pointers are a null
  317. // and then a void** pointing to the next block. This allows
  318. // EdgePool::Iterators to be a single word but still capable of crossing
  319. // block boundaries.
  320. EdgePool()
  321. {
  322. mSentinelAndBlocks[0].block = nullptr;
  323. mSentinelAndBlocks[1].block = nullptr;
  324. }
  325. ~EdgePool()
  326. {
  327. MOZ_ASSERT(!mSentinelAndBlocks[0].block &&
  328. !mSentinelAndBlocks[1].block,
  329. "Didn't call Clear()?");
  330. }
  331. void Clear()
  332. {
  333. EdgeBlock* b = EdgeBlocks();
  334. while (b) {
  335. EdgeBlock* next = b->Next();
  336. delete b;
  337. b = next;
  338. }
  339. mSentinelAndBlocks[0].block = nullptr;
  340. mSentinelAndBlocks[1].block = nullptr;
  341. }
  342. #ifdef DEBUG
  343. bool IsEmpty()
  344. {
  345. return !mSentinelAndBlocks[0].block &&
  346. !mSentinelAndBlocks[1].block;
  347. }
  348. #endif
  349. private:
  350. struct EdgeBlock;
  351. union PtrInfoOrBlock
  352. {
  353. // Use a union to avoid reinterpret_cast and the ensuing
  354. // potential aliasing bugs.
  355. PtrInfo* ptrInfo;
  356. EdgeBlock* block;
  357. };
  358. struct EdgeBlock
  359. {
  360. enum { EdgeBlockSize = 16 * 1024 };
  361. PtrInfoOrBlock mPointers[EdgeBlockSize];
  362. EdgeBlock()
  363. {
  364. mPointers[EdgeBlockSize - 2].block = nullptr; // sentinel
  365. mPointers[EdgeBlockSize - 1].block = nullptr; // next block pointer
  366. }
  367. EdgeBlock*& Next()
  368. {
  369. return mPointers[EdgeBlockSize - 1].block;
  370. }
  371. PtrInfoOrBlock* Start()
  372. {
  373. return &mPointers[0];
  374. }
  375. PtrInfoOrBlock* End()
  376. {
  377. return &mPointers[EdgeBlockSize - 2];
  378. }
  379. };
  380. // Store the null sentinel so that we can have valid iterators
  381. // before adding any edges and without adding any blocks.
  382. PtrInfoOrBlock mSentinelAndBlocks[2];
  383. EdgeBlock*& EdgeBlocks()
  384. {
  385. return mSentinelAndBlocks[1].block;
  386. }
  387. EdgeBlock* EdgeBlocks() const
  388. {
  389. return mSentinelAndBlocks[1].block;
  390. }
  391. public:
  392. class Iterator
  393. {
  394. public:
  395. Iterator() : mPointer(nullptr) {}
  396. explicit Iterator(PtrInfoOrBlock* aPointer) : mPointer(aPointer) {}
  397. Iterator(const Iterator& aOther) : mPointer(aOther.mPointer) {}
  398. Iterator& operator++()
  399. {
  400. if (!mPointer->ptrInfo) {
  401. // Null pointer is a sentinel for link to the next block.
  402. mPointer = (mPointer + 1)->block->mPointers;
  403. }
  404. ++mPointer;
  405. return *this;
  406. }
  407. PtrInfo* operator*() const
  408. {
  409. if (!mPointer->ptrInfo) {
  410. // Null pointer is a sentinel for link to the next block.
  411. return (mPointer + 1)->block->mPointers->ptrInfo;
  412. }
  413. return mPointer->ptrInfo;
  414. }
  415. bool operator==(const Iterator& aOther) const
  416. {
  417. return mPointer == aOther.mPointer;
  418. }
  419. bool operator!=(const Iterator& aOther) const
  420. {
  421. return mPointer != aOther.mPointer;
  422. }
  423. #ifdef DEBUG_CC_GRAPH
  424. bool Initialized() const
  425. {
  426. return mPointer != nullptr;
  427. }
  428. #endif
  429. private:
  430. PtrInfoOrBlock* mPointer;
  431. };
  432. class Builder;
  433. friend class Builder;
  434. class Builder
  435. {
  436. public:
  437. explicit Builder(EdgePool& aPool)
  438. : mCurrent(&aPool.mSentinelAndBlocks[0])
  439. , mBlockEnd(&aPool.mSentinelAndBlocks[0])
  440. , mNextBlockPtr(&aPool.EdgeBlocks())
  441. {
  442. }
  443. Iterator Mark()
  444. {
  445. return Iterator(mCurrent);
  446. }
  447. void Add(PtrInfo* aEdge)
  448. {
  449. if (mCurrent == mBlockEnd) {
  450. EdgeBlock* b = new EdgeBlock();
  451. *mNextBlockPtr = b;
  452. mCurrent = b->Start();
  453. mBlockEnd = b->End();
  454. mNextBlockPtr = &b->Next();
  455. }
  456. (mCurrent++)->ptrInfo = aEdge;
  457. }
  458. private:
  459. // mBlockEnd points to space for null sentinel
  460. PtrInfoOrBlock* mCurrent;
  461. PtrInfoOrBlock* mBlockEnd;
  462. EdgeBlock** mNextBlockPtr;
  463. };
  464. size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
  465. {
  466. size_t n = 0;
  467. EdgeBlock* b = EdgeBlocks();
  468. while (b) {
  469. n += aMallocSizeOf(b);
  470. b = b->Next();
  471. }
  472. return n;
  473. }
  474. };
  475. #ifdef DEBUG_CC_GRAPH
  476. #define CC_GRAPH_ASSERT(b) MOZ_ASSERT(b)
  477. #else
  478. #define CC_GRAPH_ASSERT(b)
  479. #endif
  480. enum NodeColor { black, white, grey };
  481. // This structure should be kept as small as possible; we may expect
  482. // hundreds of thousands of them to be allocated and touched
  483. // repeatedly during each cycle collection.
  484. struct PtrInfo
  485. {
  486. void* mPointer;
  487. nsCycleCollectionParticipant* mParticipant;
  488. uint32_t mColor : 2;
  489. uint32_t mInternalRefs : 30;
  490. uint32_t mRefCount;
  491. private:
  492. EdgePool::Iterator mFirstChild;
  493. static const uint32_t kInitialRefCount = UINT32_MAX - 1;
  494. public:
  495. PtrInfo(void* aPointer, nsCycleCollectionParticipant* aParticipant)
  496. : mPointer(aPointer),
  497. mParticipant(aParticipant),
  498. mColor(grey),
  499. mInternalRefs(0),
  500. mRefCount(kInitialRefCount),
  501. mFirstChild()
  502. {
  503. MOZ_ASSERT(aParticipant);
  504. // We initialize mRefCount to a large non-zero value so
  505. // that it doesn't look like a JS object to the cycle collector
  506. // in the case where the object dies before being traversed.
  507. MOZ_ASSERT(!IsGrayJS() && !IsBlackJS());
  508. }
  509. // Allow NodePool::NodeBlock's constructor to compile.
  510. PtrInfo()
  511. {
  512. NS_NOTREACHED("should never be called");
  513. }
  514. bool IsGrayJS() const
  515. {
  516. return mRefCount == 0;
  517. }
  518. bool IsBlackJS() const
  519. {
  520. return mRefCount == UINT32_MAX;
  521. }
  522. bool WasTraversed() const
  523. {
  524. return mRefCount != kInitialRefCount;
  525. }
  526. EdgePool::Iterator FirstChild() const
  527. {
  528. CC_GRAPH_ASSERT(mFirstChild.Initialized());
  529. return mFirstChild;
  530. }
  531. // this PtrInfo must be part of a NodePool
  532. EdgePool::Iterator LastChild() const
  533. {
  534. CC_GRAPH_ASSERT((this + 1)->mFirstChild.Initialized());
  535. return (this + 1)->mFirstChild;
  536. }
  537. void SetFirstChild(EdgePool::Iterator aFirstChild)
  538. {
  539. CC_GRAPH_ASSERT(aFirstChild.Initialized());
  540. mFirstChild = aFirstChild;
  541. }
  542. // this PtrInfo must be part of a NodePool
  543. void SetLastChild(EdgePool::Iterator aLastChild)
  544. {
  545. CC_GRAPH_ASSERT(aLastChild.Initialized());
  546. (this + 1)->mFirstChild = aLastChild;
  547. }
  548. };
  549. /**
  550. * A structure designed to be used like a linked list of PtrInfo, except
  551. * it allocates many PtrInfos at a time.
  552. */
  553. class NodePool
  554. {
  555. private:
  556. // The -2 allows us to use |NodeBlockSize + 1| for |mEntries|, and fit
  557. // |mNext|, all without causing slop.
  558. enum { NodeBlockSize = 4 * 1024 - 2 };
  559. struct NodeBlock
  560. {
  561. // We create and destroy NodeBlock using moz_xmalloc/free rather than new
  562. // and delete to avoid calling its constructor and destructor.
  563. NodeBlock()
  564. {
  565. NS_NOTREACHED("should never be called");
  566. // Ensure NodeBlock is the right size (see the comment on NodeBlockSize
  567. // above).
  568. static_assert(
  569. sizeof(NodeBlock) == 81904 || // 32-bit; equals 19.996 x 4 KiB pages
  570. sizeof(NodeBlock) == 131048, // 64-bit; equals 31.994 x 4 KiB pages
  571. "ill-sized NodeBlock"
  572. );
  573. }
  574. ~NodeBlock()
  575. {
  576. NS_NOTREACHED("should never be called");
  577. }
  578. NodeBlock* mNext;
  579. PtrInfo mEntries[NodeBlockSize + 1]; // +1 to store last child of last node
  580. };
  581. public:
  582. NodePool()
  583. : mBlocks(nullptr)
  584. , mLast(nullptr)
  585. {
  586. }
  587. ~NodePool()
  588. {
  589. MOZ_ASSERT(!mBlocks, "Didn't call Clear()?");
  590. }
  591. void Clear()
  592. {
  593. NodeBlock* b = mBlocks;
  594. while (b) {
  595. NodeBlock* n = b->mNext;
  596. free(b);
  597. b = n;
  598. }
  599. mBlocks = nullptr;
  600. mLast = nullptr;
  601. }
  602. #ifdef DEBUG
  603. bool IsEmpty()
  604. {
  605. return !mBlocks && !mLast;
  606. }
  607. #endif
  608. class Builder;
  609. friend class Builder;
  610. class Builder
  611. {
  612. public:
  613. explicit Builder(NodePool& aPool)
  614. : mNextBlock(&aPool.mBlocks)
  615. , mNext(aPool.mLast)
  616. , mBlockEnd(nullptr)
  617. {
  618. MOZ_ASSERT(!aPool.mBlocks && !aPool.mLast, "pool not empty");
  619. }
  620. PtrInfo* Add(void* aPointer, nsCycleCollectionParticipant* aParticipant)
  621. {
  622. if (mNext == mBlockEnd) {
  623. NodeBlock* block = static_cast<NodeBlock*>(malloc(sizeof(NodeBlock)));
  624. if (!block) {
  625. return nullptr;
  626. }
  627. *mNextBlock = block;
  628. mNext = block->mEntries;
  629. mBlockEnd = block->mEntries + NodeBlockSize;
  630. block->mNext = nullptr;
  631. mNextBlock = &block->mNext;
  632. }
  633. return new (mozilla::KnownNotNull, mNext++) PtrInfo(aPointer, aParticipant);
  634. }
  635. private:
  636. NodeBlock** mNextBlock;
  637. PtrInfo*& mNext;
  638. PtrInfo* mBlockEnd;
  639. };
  640. class Enumerator;
  641. friend class Enumerator;
  642. class Enumerator
  643. {
  644. public:
  645. explicit Enumerator(NodePool& aPool)
  646. : mFirstBlock(aPool.mBlocks)
  647. , mCurBlock(nullptr)
  648. , mNext(nullptr)
  649. , mBlockEnd(nullptr)
  650. , mLast(aPool.mLast)
  651. {
  652. }
  653. bool IsDone() const
  654. {
  655. return mNext == mLast;
  656. }
  657. bool AtBlockEnd() const
  658. {
  659. return mNext == mBlockEnd;
  660. }
  661. PtrInfo* GetNext()
  662. {
  663. MOZ_ASSERT(!IsDone(), "calling GetNext when done");
  664. if (mNext == mBlockEnd) {
  665. NodeBlock* nextBlock = mCurBlock ? mCurBlock->mNext : mFirstBlock;
  666. mNext = nextBlock->mEntries;
  667. mBlockEnd = mNext + NodeBlockSize;
  668. mCurBlock = nextBlock;
  669. }
  670. return mNext++;
  671. }
  672. private:
  673. // mFirstBlock is a reference to allow an Enumerator to be constructed
  674. // for an empty graph.
  675. NodeBlock*& mFirstBlock;
  676. NodeBlock* mCurBlock;
  677. // mNext is the next value we want to return, unless mNext == mBlockEnd
  678. // NB: mLast is a reference to allow enumerating while building!
  679. PtrInfo* mNext;
  680. PtrInfo* mBlockEnd;
  681. PtrInfo*& mLast;
  682. };
  683. size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
  684. {
  685. // We don't measure the things pointed to by mEntries[] because those
  686. // pointers are non-owning.
  687. size_t n = 0;
  688. NodeBlock* b = mBlocks;
  689. while (b) {
  690. n += aMallocSizeOf(b);
  691. b = b->mNext;
  692. }
  693. return n;
  694. }
  695. private:
  696. NodeBlock* mBlocks;
  697. PtrInfo* mLast;
  698. };
  699. // Declarations for mPtrToNodeMap.
  700. struct PtrToNodeEntry : public PLDHashEntryHdr
  701. {
  702. // The key is mNode->mPointer
  703. PtrInfo* mNode;
  704. };
  705. static bool
  706. PtrToNodeMatchEntry(const PLDHashEntryHdr* aEntry, const void* aKey)
  707. {
  708. const PtrToNodeEntry* n = static_cast<const PtrToNodeEntry*>(aEntry);
  709. return n->mNode->mPointer == aKey;
  710. }
  711. static PLDHashTableOps PtrNodeOps = {
  712. PLDHashTable::HashVoidPtrKeyStub,
  713. PtrToNodeMatchEntry,
  714. PLDHashTable::MoveEntryStub,
  715. PLDHashTable::ClearEntryStub,
  716. nullptr
  717. };
  718. struct WeakMapping
  719. {
  720. // map and key will be null if the corresponding objects are GC marked
  721. PtrInfo* mMap;
  722. PtrInfo* mKey;
  723. PtrInfo* mKeyDelegate;
  724. PtrInfo* mVal;
  725. };
  726. class CCGraphBuilder;
  727. struct CCGraph
  728. {
  729. NodePool mNodes;
  730. EdgePool mEdges;
  731. nsTArray<WeakMapping> mWeakMaps;
  732. uint32_t mRootCount;
  733. private:
  734. PLDHashTable mPtrToNodeMap;
  735. bool mOutOfMemory;
  736. static const uint32_t kInitialMapLength = 16384;
  737. public:
  738. CCGraph()
  739. : mRootCount(0)
  740. , mPtrToNodeMap(&PtrNodeOps, sizeof(PtrToNodeEntry), kInitialMapLength)
  741. , mOutOfMemory(false)
  742. {}
  743. ~CCGraph() {}
  744. void Init()
  745. {
  746. MOZ_ASSERT(IsEmpty(), "Failed to call CCGraph::Clear");
  747. }
  748. void Clear()
  749. {
  750. mNodes.Clear();
  751. mEdges.Clear();
  752. mWeakMaps.Clear();
  753. mRootCount = 0;
  754. mPtrToNodeMap.ClearAndPrepareForLength(kInitialMapLength);
  755. mOutOfMemory = false;
  756. }
  757. #ifdef DEBUG
  758. bool IsEmpty()
  759. {
  760. return mNodes.IsEmpty() && mEdges.IsEmpty() &&
  761. mWeakMaps.IsEmpty() && mRootCount == 0 &&
  762. mPtrToNodeMap.EntryCount() == 0;
  763. }
  764. #endif
  765. PtrInfo* FindNode(void* aPtr);
  766. PtrToNodeEntry* AddNodeToMap(void* aPtr);
  767. void RemoveObjectFromMap(void* aObject);
  768. uint32_t MapCount() const
  769. {
  770. return mPtrToNodeMap.EntryCount();
  771. }
  772. size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const
  773. {
  774. size_t n = 0;
  775. n += mNodes.SizeOfExcludingThis(aMallocSizeOf);
  776. n += mEdges.SizeOfExcludingThis(aMallocSizeOf);
  777. // We don't measure what the WeakMappings point to, because the
  778. // pointers are non-owning.
  779. n += mWeakMaps.ShallowSizeOfExcludingThis(aMallocSizeOf);
  780. n += mPtrToNodeMap.ShallowSizeOfExcludingThis(aMallocSizeOf);
  781. return n;
  782. }
  783. private:
  784. PtrToNodeEntry* FindNodeEntry(void* aPtr)
  785. {
  786. return static_cast<PtrToNodeEntry*>(mPtrToNodeMap.Search(aPtr));
  787. }
  788. };
  789. PtrInfo*
  790. CCGraph::FindNode(void* aPtr)
  791. {
  792. PtrToNodeEntry* e = FindNodeEntry(aPtr);
  793. return e ? e->mNode : nullptr;
  794. }
  795. PtrToNodeEntry*
  796. CCGraph::AddNodeToMap(void* aPtr)
  797. {
  798. JS::AutoSuppressGCAnalysis suppress;
  799. if (mOutOfMemory) {
  800. return nullptr;
  801. }
  802. auto e = static_cast<PtrToNodeEntry*>(mPtrToNodeMap.Add(aPtr, fallible));
  803. if (!e) {
  804. mOutOfMemory = true;
  805. MOZ_ASSERT(false, "Ran out of memory while building cycle collector graph");
  806. return nullptr;
  807. }
  808. return e;
  809. }
  810. void
  811. CCGraph::RemoveObjectFromMap(void* aObj)
  812. {
  813. PtrToNodeEntry* e = FindNodeEntry(aObj);
  814. PtrInfo* pinfo = e ? e->mNode : nullptr;
  815. if (pinfo) {
  816. mPtrToNodeMap.RemoveEntry(e);
  817. pinfo->mPointer = nullptr;
  818. pinfo->mParticipant = nullptr;
  819. }
  820. }
  821. static nsISupports*
  822. CanonicalizeXPCOMParticipant(nsISupports* aIn)
  823. {
  824. nsISupports* out = nullptr;
  825. aIn->QueryInterface(NS_GET_IID(nsCycleCollectionISupports),
  826. reinterpret_cast<void**>(&out));
  827. return out;
  828. }
  829. static inline void
  830. ToParticipant(nsISupports* aPtr, nsXPCOMCycleCollectionParticipant** aCp);
  831. static void
  832. CanonicalizeParticipant(void** aParti, nsCycleCollectionParticipant** aCp)
  833. {
  834. // If the participant is null, this is an nsISupports participant,
  835. // so we must QI to get the real participant.
  836. if (!*aCp) {
  837. nsISupports* nsparti = static_cast<nsISupports*>(*aParti);
  838. nsparti = CanonicalizeXPCOMParticipant(nsparti);
  839. NS_ASSERTION(nsparti,
  840. "Don't add objects that don't participate in collection!");
  841. nsXPCOMCycleCollectionParticipant* xcp;
  842. ToParticipant(nsparti, &xcp);
  843. *aParti = nsparti;
  844. *aCp = xcp;
  845. }
  846. }
  847. struct nsPurpleBufferEntry
  848. {
  849. nsPurpleBufferEntry(void* aObject, nsCycleCollectingAutoRefCnt* aRefCnt,
  850. nsCycleCollectionParticipant* aParticipant)
  851. : mObject(aObject)
  852. , mRefCnt(aRefCnt)
  853. , mParticipant(aParticipant)
  854. {}
  855. nsPurpleBufferEntry(nsPurpleBufferEntry&& aOther)
  856. : mObject(nullptr)
  857. , mRefCnt(nullptr)
  858. , mParticipant(nullptr)
  859. {
  860. Swap(aOther);
  861. }
  862. void Swap(nsPurpleBufferEntry& aOther) {
  863. std::swap(mObject, aOther.mObject);
  864. std::swap(mRefCnt, aOther.mRefCnt);
  865. std::swap(mParticipant, aOther.mParticipant);
  866. }
  867. void Clear() {
  868. mRefCnt->RemoveFromPurpleBuffer();
  869. mRefCnt = nullptr;
  870. mObject = nullptr;
  871. mParticipant = nullptr;
  872. }
  873. ~nsPurpleBufferEntry() {
  874. if (mRefCnt) {
  875. mRefCnt->RemoveFromPurpleBuffer();
  876. }
  877. }
  878. void* mObject;
  879. nsCycleCollectingAutoRefCnt* mRefCnt;
  880. nsCycleCollectionParticipant* mParticipant; // nullptr for nsISupports
  881. };
  882. class nsCycleCollector;
  883. struct nsPurpleBuffer
  884. {
  885. private:
  886. uint32_t mCount;
  887. // Try to match the size of a jemalloc bucket, to minimize slop bytes.
  888. // - On 32-bit platforms sizeof(nsPurpleBufferEntry) is 12, so mEntries'
  889. // Segment is 16,372 bytes.
  890. // - On 64-bit platforms sizeof(nsPurpleBufferEntry) is 24, so mEntries'
  891. // Segment is 32,760 bytes.
  892. static const uint32_t kEntriesPerSegment = 1365;
  893. static const size_t kSegmentSize =
  894. sizeof(nsPurpleBufferEntry) * kEntriesPerSegment;
  895. typedef
  896. SegmentedVector<nsPurpleBufferEntry, kSegmentSize, InfallibleAllocPolicy>
  897. PurpleBufferVector;
  898. PurpleBufferVector mEntries;
  899. public:
  900. nsPurpleBuffer()
  901. : mCount(0)
  902. {
  903. static_assert(
  904. sizeof(PurpleBufferVector::Segment) == 16372 || // 32-bit
  905. sizeof(PurpleBufferVector::Segment) == 32760 || // 64-bit
  906. sizeof(PurpleBufferVector::Segment) == 32744, // 64-bit Windows
  907. "ill-sized nsPurpleBuffer::mEntries");
  908. }
  909. ~nsPurpleBuffer()
  910. {}
  911. // This method compacts mEntries.
  912. template<class PurpleVisitor>
  913. void VisitEntries(PurpleVisitor& aVisitor) {
  914. if (mEntries.IsEmpty()) {
  915. return;
  916. }
  917. uint32_t oldLength = mEntries.Length();
  918. uint32_t newLength = 0;
  919. auto revIter = mEntries.IterFromLast();
  920. auto iter = mEntries.Iter();
  921. // After iteration this points to the first empty entry.
  922. auto firstEmptyIter = mEntries.Iter();
  923. auto iterFromLastEntry = mEntries.IterFromLast();
  924. for (; !iter.Done(); iter.Next()) {
  925. nsPurpleBufferEntry& e = iter.Get();
  926. if (e.mObject) {
  927. aVisitor.Visit(*this, &e);
  928. }
  929. // Visit call above may have cleared the entry, or the entry was empty
  930. // already.
  931. if (!e.mObject) {
  932. // Try to find a non-empty entry from the end of the vector.
  933. for (; !revIter.Done(); revIter.Prev()) {
  934. nsPurpleBufferEntry& otherEntry = revIter.Get();
  935. if (&e == &otherEntry) {
  936. break;
  937. }
  938. if (otherEntry.mObject) {
  939. aVisitor.Visit(*this, &otherEntry);
  940. // Visit may have cleared otherEntry.
  941. if (otherEntry.mObject) {
  942. e.Swap(otherEntry);
  943. revIter.Prev(); // We've swapped this now empty entry.
  944. break;
  945. }
  946. }
  947. }
  948. }
  949. // Entry is non-empty even after the Visit call, ensure it is kept
  950. // in mEntries.
  951. if (e.mObject) {
  952. firstEmptyIter.Next();
  953. ++newLength;
  954. }
  955. if (&e == &revIter.Get()) {
  956. break;
  957. }
  958. }
  959. // There were some empty entries.
  960. if (oldLength != newLength) {
  961. // While visiting entries, some new ones were possibly added. This can
  962. // happen during CanSkip. Move all such new entries to be after other
  963. // entries. Note, we don't call Visit on newly added entries!
  964. if (&iterFromLastEntry.Get() != &mEntries.GetLast()) {
  965. iterFromLastEntry.Next(); // Now pointing to the first added entry.
  966. auto& iterForNewEntries = iterFromLastEntry;
  967. while (!iterForNewEntries.Done()) {
  968. MOZ_ASSERT(!firstEmptyIter.Done());
  969. MOZ_ASSERT(!firstEmptyIter.Get().mObject);
  970. firstEmptyIter.Get().Swap(iterForNewEntries.Get());
  971. firstEmptyIter.Next();
  972. iterForNewEntries.Next();
  973. ++newLength; // We keep all the new entries.
  974. }
  975. }
  976. mEntries.PopLastN(oldLength - newLength);
  977. }
  978. }
  979. void FreeBlocks() {
  980. mCount = 0;
  981. mEntries.Clear();
  982. }
  983. void SelectPointers(CCGraphBuilder& aBuilder);
  984. // RemoveSkippable removes entries from the purple buffer synchronously
  985. // (1) if aAsyncSnowWhiteFreeing is false and nsPurpleBufferEntry::mRefCnt is 0 or
  986. // (2) if the object's nsXPCOMCycleCollectionParticipant::CanSkip() returns true or
  987. // (3) if nsPurpleBufferEntry::mRefCnt->IsPurple() is false.
  988. // (4) If removeChildlessNodes is true, then any nodes in the purple buffer
  989. // that will have no children in the cycle collector graph will also be
  990. // removed. CanSkip() may be run on these children.
  991. void RemoveSkippable(nsCycleCollector* aCollector,
  992. bool aRemoveChildlessNodes,
  993. bool aAsyncSnowWhiteFreeing,
  994. CC_ForgetSkippableCallback aCb);
  995. MOZ_ALWAYS_INLINE void Put(void* aObject, nsCycleCollectionParticipant* aCp,
  996. nsCycleCollectingAutoRefCnt* aRefCnt) {
  997. nsPurpleBufferEntry entry(aObject, aRefCnt, aCp);
  998. Unused << mEntries.Append(Move(entry));
  999. MOZ_ASSERT(!entry.mRefCnt, "CC: PurpleBufferEntry:Put() Move failed!");
  1000. ++mCount;
  1001. }
  1002. void Remove(nsPurpleBufferEntry* aEntry) {
  1003. MOZ_ASSERT(mCount != 0, "must have entries");
  1004. --mCount;
  1005. aEntry->Clear();
  1006. }
  1007. uint32_t Count() const {
  1008. return mCount;
  1009. }
  1010. size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const {
  1011. return mEntries.SizeOfExcludingThis(aMallocSizeOf);
  1012. }
  1013. };
  1014. static bool
  1015. AddPurpleRoot(CCGraphBuilder& aBuilder, void* aRoot,
  1016. nsCycleCollectionParticipant* aParti);
  1017. struct SelectPointersVisitor
  1018. {
  1019. explicit SelectPointersVisitor(CCGraphBuilder& aBuilder)
  1020. : mBuilder(aBuilder)
  1021. {
  1022. }
  1023. void
  1024. Visit(nsPurpleBuffer& aBuffer, nsPurpleBufferEntry* aEntry)
  1025. {
  1026. MOZ_ASSERT(aEntry->mObject, "Null object in purple buffer");
  1027. MOZ_ASSERT(aEntry->mRefCnt->get() != 0,
  1028. "SelectPointersVisitor: snow-white object in the purple buffer");
  1029. if (!aEntry->mRefCnt->IsPurple() ||
  1030. AddPurpleRoot(mBuilder, aEntry->mObject, aEntry->mParticipant)) {
  1031. aBuffer.Remove(aEntry);
  1032. }
  1033. }
  1034. private:
  1035. CCGraphBuilder& mBuilder;
  1036. };
  1037. void
  1038. nsPurpleBuffer::SelectPointers(CCGraphBuilder& aBuilder) {
  1039. SelectPointersVisitor visitor(aBuilder);
  1040. VisitEntries(visitor);
  1041. NS_ASSERTION(mCount == 0, "AddPurpleRoot failed");
  1042. if (mCount == 0) {
  1043. FreeBlocks();
  1044. }
  1045. }
  1046. enum ccPhase
  1047. {
  1048. IdlePhase,
  1049. GraphBuildingPhase,
  1050. ScanAndCollectWhitePhase,
  1051. CleanupPhase
  1052. };
  1053. enum ccType
  1054. {
  1055. SliceCC, /* If a CC is in progress, continue it. Otherwise, start a new one. */
  1056. ManualCC, /* Explicitly triggered. */
  1057. ShutdownCC /* Shutdown CC, used for finding leaks. */
  1058. };
  1059. ////////////////////////////////////////////////////////////////////////
  1060. // Top level structure for the cycle collector.
  1061. ////////////////////////////////////////////////////////////////////////
  1062. using js::SliceBudget;
  1063. class JSPurpleBuffer;
  1064. class nsCycleCollector : public nsIMemoryReporter
  1065. {
  1066. public:
  1067. NS_DECL_ISUPPORTS
  1068. NS_DECL_NSIMEMORYREPORTER
  1069. private:
  1070. bool mActivelyCollecting;
  1071. bool mFreeingSnowWhite;
  1072. // mScanInProgress should be false when we're collecting white objects.
  1073. bool mScanInProgress;
  1074. CycleCollectorResults mResults;
  1075. TimeStamp mCollectionStart;
  1076. CycleCollectedJSContext* mJSContext;
  1077. ccPhase mIncrementalPhase;
  1078. CCGraph mGraph;
  1079. nsAutoPtr<CCGraphBuilder> mBuilder;
  1080. RefPtr<nsCycleCollectorLogger> mLogger;
  1081. #ifdef DEBUG
  1082. void* mThread;
  1083. #endif
  1084. nsCycleCollectorParams mParams;
  1085. uint32_t mWhiteNodeCount;
  1086. CC_BeforeUnlinkCallback mBeforeUnlinkCB;
  1087. CC_ForgetSkippableCallback mForgetSkippableCB;
  1088. nsPurpleBuffer mPurpleBuf;
  1089. uint32_t mUnmergedNeeded;
  1090. uint32_t mMergedInARow;
  1091. RefPtr<JSPurpleBuffer> mJSPurpleBuffer;
  1092. private:
  1093. virtual ~nsCycleCollector();
  1094. public:
  1095. nsCycleCollector();
  1096. void RegisterJSContext(CycleCollectedJSContext* aJSContext);
  1097. void ForgetJSContext();
  1098. void SetBeforeUnlinkCallback(CC_BeforeUnlinkCallback aBeforeUnlinkCB)
  1099. {
  1100. CheckThreadSafety();
  1101. mBeforeUnlinkCB = aBeforeUnlinkCB;
  1102. }
  1103. void SetForgetSkippableCallback(CC_ForgetSkippableCallback aForgetSkippableCB)
  1104. {
  1105. CheckThreadSafety();
  1106. mForgetSkippableCB = aForgetSkippableCB;
  1107. }
  1108. void Suspect(void* aPtr, nsCycleCollectionParticipant* aCp,
  1109. nsCycleCollectingAutoRefCnt* aRefCnt);
  1110. uint32_t SuspectedCount();
  1111. void ForgetSkippable(bool aRemoveChildlessNodes, bool aAsyncSnowWhiteFreeing);
  1112. bool FreeSnowWhite(bool aUntilNoSWInPurpleBuffer);
  1113. // This method assumes its argument is already canonicalized.
  1114. void RemoveObjectFromGraph(void* aPtr);
  1115. void PrepareForGarbageCollection();
  1116. void FinishAnyCurrentCollection();
  1117. bool Collect(ccType aCCType,
  1118. SliceBudget& aBudget,
  1119. nsICycleCollectorListener* aManualListener,
  1120. bool aPreferShorterSlices = false);
  1121. void Shutdown(bool aDoCollect);
  1122. bool IsIdle() const { return mIncrementalPhase == IdlePhase; }
  1123. void SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf,
  1124. size_t* aObjectSize,
  1125. size_t* aGraphSize,
  1126. size_t* aPurpleBufferSize) const;
  1127. JSPurpleBuffer* GetJSPurpleBuffer();
  1128. CycleCollectedJSContext* Context() { return mJSContext; }
  1129. private:
  1130. void CheckThreadSafety();
  1131. void ShutdownCollect();
  1132. void FixGrayBits(bool aForceGC, TimeLog& aTimeLog);
  1133. bool IsIncrementalGCInProgress();
  1134. void FinishAnyIncrementalGCInProgress();
  1135. bool ShouldMergeZones(ccType aCCType);
  1136. void BeginCollection(ccType aCCType, nsICycleCollectorListener* aManualListener);
  1137. void MarkRoots(SliceBudget& aBudget);
  1138. void ScanRoots(bool aFullySynchGraphBuild);
  1139. void ScanIncrementalRoots();
  1140. void ScanWhiteNodes(bool aFullySynchGraphBuild);
  1141. void ScanBlackNodes();
  1142. void ScanWeakMaps();
  1143. // returns whether anything was collected
  1144. bool CollectWhite();
  1145. void CleanupAfterCollection();
  1146. };
  1147. NS_IMPL_ISUPPORTS(nsCycleCollector, nsIMemoryReporter)
  1148. /**
  1149. * GraphWalker is templatized over a Visitor class that must provide
  1150. * the following two methods:
  1151. *
  1152. * bool ShouldVisitNode(PtrInfo const *pi);
  1153. * void VisitNode(PtrInfo *pi);
  1154. */
  1155. template<class Visitor>
  1156. class GraphWalker
  1157. {
  1158. private:
  1159. Visitor mVisitor;
  1160. void DoWalk(nsDeque& aQueue);
  1161. void CheckedPush(nsDeque& aQueue, PtrInfo* aPi)
  1162. {
  1163. if (!aPi) {
  1164. MOZ_CRASH();
  1165. }
  1166. if (!aQueue.Push(aPi, fallible)) {
  1167. mVisitor.Failed();
  1168. }
  1169. }
  1170. public:
  1171. void Walk(PtrInfo* aPi);
  1172. void WalkFromRoots(CCGraph& aGraph);
  1173. // copy-constructing the visitor should be cheap, and less
  1174. // indirection than using a reference
  1175. explicit GraphWalker(const Visitor aVisitor) : mVisitor(aVisitor)
  1176. {
  1177. }
  1178. };
  1179. ////////////////////////////////////////////////////////////////////////
  1180. // The static collector struct
  1181. ////////////////////////////////////////////////////////////////////////
  1182. struct CollectorData
  1183. {
  1184. RefPtr<nsCycleCollector> mCollector;
  1185. CycleCollectedJSContext* mContext;
  1186. };
  1187. static MOZ_THREAD_LOCAL(CollectorData*) sCollectorData;
  1188. ////////////////////////////////////////////////////////////////////////
  1189. // Utility functions
  1190. ////////////////////////////////////////////////////////////////////////
  1191. static inline void
  1192. ToParticipant(nsISupports* aPtr, nsXPCOMCycleCollectionParticipant** aCp)
  1193. {
  1194. // We use QI to move from an nsISupports to an
  1195. // nsXPCOMCycleCollectionParticipant, which is a per-class singleton helper
  1196. // object that implements traversal and unlinking logic for the nsISupports
  1197. // in question.
  1198. *aCp = nullptr;
  1199. CallQueryInterface(aPtr, aCp);
  1200. }
  1201. template<class Visitor>
  1202. MOZ_NEVER_INLINE void
  1203. GraphWalker<Visitor>::Walk(PtrInfo* aPi)
  1204. {
  1205. nsDeque queue;
  1206. CheckedPush(queue, aPi);
  1207. DoWalk(queue);
  1208. }
  1209. template<class Visitor>
  1210. MOZ_NEVER_INLINE void
  1211. GraphWalker<Visitor>::WalkFromRoots(CCGraph& aGraph)
  1212. {
  1213. nsDeque queue;
  1214. NodePool::Enumerator etor(aGraph.mNodes);
  1215. for (uint32_t i = 0; i < aGraph.mRootCount; ++i) {
  1216. CheckedPush(queue, etor.GetNext());
  1217. }
  1218. DoWalk(queue);
  1219. }
  1220. template<class Visitor>
  1221. MOZ_NEVER_INLINE void
  1222. GraphWalker<Visitor>::DoWalk(nsDeque& aQueue)
  1223. {
  1224. // Use a aQueue to match the breadth-first traversal used when we
  1225. // built the graph, for hopefully-better locality.
  1226. while (aQueue.GetSize() > 0) {
  1227. PtrInfo* pi = static_cast<PtrInfo*>(aQueue.PopFront());
  1228. if (pi->WasTraversed() && mVisitor.ShouldVisitNode(pi)) {
  1229. mVisitor.VisitNode(pi);
  1230. for (EdgePool::Iterator child = pi->FirstChild(),
  1231. child_end = pi->LastChild();
  1232. child != child_end; ++child) {
  1233. CheckedPush(aQueue, *child);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. struct CCGraphDescriber : public LinkedListElement<CCGraphDescriber>
  1239. {
  1240. CCGraphDescriber()
  1241. : mAddress("0x"), mCnt(0), mType(eUnknown)
  1242. {
  1243. }
  1244. enum Type
  1245. {
  1246. eRefCountedObject,
  1247. eGCedObject,
  1248. eGCMarkedObject,
  1249. eEdge,
  1250. eRoot,
  1251. eGarbage,
  1252. eUnknown
  1253. };
  1254. nsCString mAddress;
  1255. nsCString mName;
  1256. nsCString mCompartmentOrToAddress;
  1257. uint32_t mCnt;
  1258. Type mType;
  1259. };
  1260. class LogStringMessageAsync : public CancelableRunnable
  1261. {
  1262. public:
  1263. explicit LogStringMessageAsync(const nsAString& aMsg) : mMsg(aMsg)
  1264. {}
  1265. NS_IMETHOD Run() override
  1266. {
  1267. nsCOMPtr<nsIConsoleService> cs =
  1268. do_GetService(NS_CONSOLESERVICE_CONTRACTID);
  1269. if (cs) {
  1270. cs->LogStringMessage(mMsg.get());
  1271. }
  1272. return NS_OK;
  1273. }
  1274. private:
  1275. nsString mMsg;
  1276. };
  1277. class nsCycleCollectorLogSinkToFile final : public nsICycleCollectorLogSink
  1278. {
  1279. public:
  1280. NS_DECL_ISUPPORTS
  1281. nsCycleCollectorLogSinkToFile() :
  1282. mProcessIdentifier(base::GetCurrentProcId()),
  1283. mGCLog("gc-edges"), mCCLog("cc-edges")
  1284. {
  1285. }
  1286. NS_IMETHOD GetFilenameIdentifier(nsAString& aIdentifier) override
  1287. {
  1288. aIdentifier = mFilenameIdentifier;
  1289. return NS_OK;
  1290. }
  1291. NS_IMETHOD SetFilenameIdentifier(const nsAString& aIdentifier) override
  1292. {
  1293. mFilenameIdentifier = aIdentifier;
  1294. return NS_OK;
  1295. }
  1296. NS_IMETHOD GetProcessIdentifier(int32_t* aIdentifier) override
  1297. {
  1298. *aIdentifier = mProcessIdentifier;
  1299. return NS_OK;
  1300. }
  1301. NS_IMETHOD SetProcessIdentifier(int32_t aIdentifier) override
  1302. {
  1303. mProcessIdentifier = aIdentifier;
  1304. return NS_OK;
  1305. }
  1306. NS_IMETHOD GetGcLog(nsIFile** aPath) override
  1307. {
  1308. NS_IF_ADDREF(*aPath = mGCLog.mFile);
  1309. return NS_OK;
  1310. }
  1311. NS_IMETHOD GetCcLog(nsIFile** aPath) override
  1312. {
  1313. NS_IF_ADDREF(*aPath = mCCLog.mFile);
  1314. return NS_OK;
  1315. }
  1316. NS_IMETHOD Open(FILE** aGCLog, FILE** aCCLog) override
  1317. {
  1318. nsresult rv;
  1319. if (mGCLog.mStream || mCCLog.mStream) {
  1320. return NS_ERROR_UNEXPECTED;
  1321. }
  1322. rv = OpenLog(&mGCLog);
  1323. NS_ENSURE_SUCCESS(rv, rv);
  1324. *aGCLog = mGCLog.mStream;
  1325. rv = OpenLog(&mCCLog);
  1326. NS_ENSURE_SUCCESS(rv, rv);
  1327. *aCCLog = mCCLog.mStream;
  1328. return NS_OK;
  1329. }
  1330. NS_IMETHOD CloseGCLog() override
  1331. {
  1332. if (!mGCLog.mStream) {
  1333. return NS_ERROR_UNEXPECTED;
  1334. }
  1335. CloseLog(&mGCLog, NS_LITERAL_STRING("Garbage"));
  1336. return NS_OK;
  1337. }
  1338. NS_IMETHOD CloseCCLog() override
  1339. {
  1340. if (!mCCLog.mStream) {
  1341. return NS_ERROR_UNEXPECTED;
  1342. }
  1343. CloseLog(&mCCLog, NS_LITERAL_STRING("Cycle"));
  1344. return NS_OK;
  1345. }
  1346. private:
  1347. ~nsCycleCollectorLogSinkToFile()
  1348. {
  1349. if (mGCLog.mStream) {
  1350. MozillaUnRegisterDebugFILE(mGCLog.mStream);
  1351. fclose(mGCLog.mStream);
  1352. }
  1353. if (mCCLog.mStream) {
  1354. MozillaUnRegisterDebugFILE(mCCLog.mStream);
  1355. fclose(mCCLog.mStream);
  1356. }
  1357. }
  1358. struct FileInfo
  1359. {
  1360. const char* const mPrefix;
  1361. nsCOMPtr<nsIFile> mFile;
  1362. FILE* mStream;
  1363. explicit FileInfo(const char* aPrefix) : mPrefix(aPrefix), mStream(nullptr) { }
  1364. };
  1365. /**
  1366. * Create a new file named something like aPrefix.$PID.$IDENTIFIER.log in
  1367. * $MOZ_CC_LOG_DIRECTORY or in the system's temp directory. No existing
  1368. * file will be overwritten; if aPrefix.$PID.$IDENTIFIER.log exists, we'll
  1369. * try a file named something like aPrefix.$PID.$IDENTIFIER-1.log, and so
  1370. * on.
  1371. */
  1372. already_AddRefed<nsIFile> CreateTempFile(const char* aPrefix)
  1373. {
  1374. nsPrintfCString filename("%s.%d%s%s.log",
  1375. aPrefix,
  1376. mProcessIdentifier,
  1377. mFilenameIdentifier.IsEmpty() ? "" : ".",
  1378. NS_ConvertUTF16toUTF8(mFilenameIdentifier).get());
  1379. // Get the log directory either from $MOZ_CC_LOG_DIRECTORY or from
  1380. // the fallback directories in OpenTempFile. We don't use an nsCOMPtr
  1381. // here because OpenTempFile uses an in/out param and getter_AddRefs
  1382. // wouldn't work.
  1383. nsIFile* logFile = nullptr;
  1384. if (char* env = PR_GetEnv("MOZ_CC_LOG_DIRECTORY")) {
  1385. NS_NewNativeLocalFile(nsCString(env), /* followLinks = */ true,
  1386. &logFile);
  1387. }
  1388. // On Android or B2G, this function will open a file named
  1389. // aFilename under a memory-reporting-specific folder
  1390. // (/data/local/tmp/memory-reports). Otherwise, it will open a
  1391. // file named aFilename under "NS_OS_TEMP_DIR".
  1392. nsresult rv = nsDumpUtils::OpenTempFile(filename, &logFile,
  1393. NS_LITERAL_CSTRING("memory-reports"));
  1394. if (NS_FAILED(rv)) {
  1395. NS_IF_RELEASE(logFile);
  1396. return nullptr;
  1397. }
  1398. return dont_AddRef(logFile);
  1399. }
  1400. nsresult OpenLog(FileInfo* aLog)
  1401. {
  1402. // Initially create the log in a file starting with "incomplete-".
  1403. // We'll move the file and strip off the "incomplete-" once the dump
  1404. // completes. (We do this because we don't want scripts which poll
  1405. // the filesystem looking for GC/CC dumps to grab a file before we're
  1406. // finished writing to it.)
  1407. nsAutoCString incomplete;
  1408. incomplete += "incomplete-";
  1409. incomplete += aLog->mPrefix;
  1410. MOZ_ASSERT(!aLog->mFile);
  1411. aLog->mFile = CreateTempFile(incomplete.get());
  1412. if (NS_WARN_IF(!aLog->mFile)) {
  1413. return NS_ERROR_UNEXPECTED;
  1414. }
  1415. MOZ_ASSERT(!aLog->mStream);
  1416. nsresult rv = aLog->mFile->OpenANSIFileDesc("w", &aLog->mStream);
  1417. if (NS_WARN_IF(NS_FAILED(rv))) {
  1418. return NS_ERROR_UNEXPECTED;
  1419. }
  1420. MozillaRegisterDebugFILE(aLog->mStream);
  1421. return NS_OK;
  1422. }
  1423. nsresult CloseLog(FileInfo* aLog, const nsAString& aCollectorKind)
  1424. {
  1425. MOZ_ASSERT(aLog->mStream);
  1426. MOZ_ASSERT(aLog->mFile);
  1427. MozillaUnRegisterDebugFILE(aLog->mStream);
  1428. fclose(aLog->mStream);
  1429. aLog->mStream = nullptr;
  1430. // Strip off "incomplete-".
  1431. nsCOMPtr<nsIFile> logFileFinalDestination =
  1432. CreateTempFile(aLog->mPrefix);
  1433. if (NS_WARN_IF(!logFileFinalDestination)) {
  1434. return NS_ERROR_UNEXPECTED;
  1435. }
  1436. nsAutoString logFileFinalDestinationName;
  1437. logFileFinalDestination->GetLeafName(logFileFinalDestinationName);
  1438. if (NS_WARN_IF(logFileFinalDestinationName.IsEmpty())) {
  1439. return NS_ERROR_UNEXPECTED;
  1440. }
  1441. aLog->mFile->MoveTo(/* directory */ nullptr, logFileFinalDestinationName);
  1442. // Save the file path.
  1443. aLog->mFile = logFileFinalDestination;
  1444. // Log to the error console.
  1445. nsAutoString logPath;
  1446. logFileFinalDestination->GetPath(logPath);
  1447. nsAutoString msg = aCollectorKind +
  1448. NS_LITERAL_STRING(" Collector log dumped to ") + logPath;
  1449. // We don't want any JS to run between ScanRoots and CollectWhite calls,
  1450. // and since ScanRoots calls this method, better to log the message
  1451. // asynchronously.
  1452. RefPtr<LogStringMessageAsync> log = new LogStringMessageAsync(msg);
  1453. NS_DispatchToCurrentThread(log);
  1454. return NS_OK;
  1455. }
  1456. int32_t mProcessIdentifier;
  1457. nsString mFilenameIdentifier;
  1458. FileInfo mGCLog;
  1459. FileInfo mCCLog;
  1460. };
  1461. NS_IMPL_ISUPPORTS(nsCycleCollectorLogSinkToFile, nsICycleCollectorLogSink)
  1462. class nsCycleCollectorLogger final : public nsICycleCollectorListener
  1463. {
  1464. ~nsCycleCollectorLogger()
  1465. {
  1466. ClearDescribers();
  1467. }
  1468. public:
  1469. nsCycleCollectorLogger()
  1470. : mLogSink(nsCycleCollector_createLogSink())
  1471. , mWantAllTraces(false)
  1472. , mDisableLog(false)
  1473. , mWantAfterProcessing(false)
  1474. , mCCLog(nullptr)
  1475. {
  1476. }
  1477. NS_DECL_ISUPPORTS
  1478. void SetAllTraces()
  1479. {
  1480. mWantAllTraces = true;
  1481. }
  1482. bool IsAllTraces()
  1483. {
  1484. return mWantAllTraces;
  1485. }
  1486. NS_IMETHOD AllTraces(nsICycleCollectorListener** aListener) override
  1487. {
  1488. SetAllTraces();
  1489. NS_ADDREF(*aListener = this);
  1490. return NS_OK;
  1491. }
  1492. NS_IMETHOD GetWantAllTraces(bool* aAllTraces) override
  1493. {
  1494. *aAllTraces = mWantAllTraces;
  1495. return NS_OK;
  1496. }
  1497. NS_IMETHOD GetDisableLog(bool* aDisableLog) override
  1498. {
  1499. *aDisableLog = mDisableLog;
  1500. return NS_OK;
  1501. }
  1502. NS_IMETHOD SetDisableLog(bool aDisableLog) override
  1503. {
  1504. mDisableLog = aDisableLog;
  1505. return NS_OK;
  1506. }
  1507. NS_IMETHOD GetWantAfterProcessing(bool* aWantAfterProcessing) override
  1508. {
  1509. *aWantAfterProcessing = mWantAfterProcessing;
  1510. return NS_OK;
  1511. }
  1512. NS_IMETHOD SetWantAfterProcessing(bool aWantAfterProcessing) override
  1513. {
  1514. mWantAfterProcessing = aWantAfterProcessing;
  1515. return NS_OK;
  1516. }
  1517. NS_IMETHOD GetLogSink(nsICycleCollectorLogSink** aLogSink) override
  1518. {
  1519. NS_ADDREF(*aLogSink = mLogSink);
  1520. return NS_OK;
  1521. }
  1522. NS_IMETHOD SetLogSink(nsICycleCollectorLogSink* aLogSink) override
  1523. {
  1524. if (!aLogSink) {
  1525. return NS_ERROR_INVALID_ARG;
  1526. }
  1527. mLogSink = aLogSink;
  1528. return NS_OK;
  1529. }
  1530. nsresult Begin()
  1531. {
  1532. nsresult rv;
  1533. mCurrentAddress.AssignLiteral("0x");
  1534. ClearDescribers();
  1535. if (mDisableLog) {
  1536. return NS_OK;
  1537. }
  1538. FILE* gcLog;
  1539. rv = mLogSink->Open(&gcLog, &mCCLog);
  1540. NS_ENSURE_SUCCESS(rv, rv);
  1541. // Dump the JS heap.
  1542. CollectorData* data = sCollectorData.get();
  1543. if (data && data->mContext) {
  1544. data->mContext->DumpJSHeap(gcLog);
  1545. }
  1546. rv = mLogSink->CloseGCLog();
  1547. NS_ENSURE_SUCCESS(rv, rv);
  1548. fprintf(mCCLog, "# WantAllTraces=%s\n", mWantAllTraces ? "true" : "false");
  1549. return NS_OK;
  1550. }
  1551. void NoteRefCountedObject(uint64_t aAddress, uint32_t aRefCount,
  1552. const char* aObjectDescription)
  1553. {
  1554. if (!mDisableLog) {
  1555. fprintf(mCCLog, "%p [rc=%u] %s\n", (void*)aAddress, aRefCount,
  1556. aObjectDescription);
  1557. }
  1558. if (mWantAfterProcessing) {
  1559. CCGraphDescriber* d = new CCGraphDescriber();
  1560. mDescribers.insertBack(d);
  1561. mCurrentAddress.AssignLiteral("0x");
  1562. mCurrentAddress.AppendInt(aAddress, 16);
  1563. d->mType = CCGraphDescriber::eRefCountedObject;
  1564. d->mAddress = mCurrentAddress;
  1565. d->mCnt = aRefCount;
  1566. d->mName.Append(aObjectDescription);
  1567. }
  1568. }
  1569. void NoteGCedObject(uint64_t aAddress, bool aMarked,
  1570. const char* aObjectDescription,
  1571. uint64_t aCompartmentAddress)
  1572. {
  1573. if (!mDisableLog) {
  1574. fprintf(mCCLog, "%p [gc%s] %s\n", (void*)aAddress,
  1575. aMarked ? ".marked" : "", aObjectDescription);
  1576. }
  1577. if (mWantAfterProcessing) {
  1578. CCGraphDescriber* d = new CCGraphDescriber();
  1579. mDescribers.insertBack(d);
  1580. mCurrentAddress.AssignLiteral("0x");
  1581. mCurrentAddress.AppendInt(aAddress, 16);
  1582. d->mType = aMarked ? CCGraphDescriber::eGCMarkedObject :
  1583. CCGraphDescriber::eGCedObject;
  1584. d->mAddress = mCurrentAddress;
  1585. d->mName.Append(aObjectDescription);
  1586. if (aCompartmentAddress) {
  1587. d->mCompartmentOrToAddress.AssignLiteral("0x");
  1588. d->mCompartmentOrToAddress.AppendInt(aCompartmentAddress, 16);
  1589. } else {
  1590. d->mCompartmentOrToAddress.SetIsVoid(true);
  1591. }
  1592. }
  1593. }
  1594. void NoteEdge(uint64_t aToAddress, const char* aEdgeName)
  1595. {
  1596. if (!mDisableLog) {
  1597. fprintf(mCCLog, "> %p %s\n", (void*)aToAddress, aEdgeName);
  1598. }
  1599. if (mWantAfterProcessing) {
  1600. CCGraphDescriber* d = new CCGraphDescriber();
  1601. mDescribers.insertBack(d);
  1602. d->mType = CCGraphDescriber::eEdge;
  1603. d->mAddress = mCurrentAddress;
  1604. d->mCompartmentOrToAddress.AssignLiteral("0x");
  1605. d->mCompartmentOrToAddress.AppendInt(aToAddress, 16);
  1606. d->mName.Append(aEdgeName);
  1607. }
  1608. }
  1609. void NoteWeakMapEntry(uint64_t aMap, uint64_t aKey,
  1610. uint64_t aKeyDelegate, uint64_t aValue)
  1611. {
  1612. if (!mDisableLog) {
  1613. fprintf(mCCLog, "WeakMapEntry map=%p key=%p keyDelegate=%p value=%p\n",
  1614. (void*)aMap, (void*)aKey, (void*)aKeyDelegate, (void*)aValue);
  1615. }
  1616. // We don't support after-processing for weak map entries.
  1617. }
  1618. void NoteIncrementalRoot(uint64_t aAddress)
  1619. {
  1620. if (!mDisableLog) {
  1621. fprintf(mCCLog, "IncrementalRoot %p\n", (void*)aAddress);
  1622. }
  1623. // We don't support after-processing for incremental roots.
  1624. }
  1625. void BeginResults()
  1626. {
  1627. if (!mDisableLog) {
  1628. fputs("==========\n", mCCLog);
  1629. }
  1630. }
  1631. void DescribeRoot(uint64_t aAddress, uint32_t aKnownEdges)
  1632. {
  1633. if (!mDisableLog) {
  1634. fprintf(mCCLog, "%p [known=%u]\n", (void*)aAddress, aKnownEdges);
  1635. }
  1636. if (mWantAfterProcessing) {
  1637. CCGraphDescriber* d = new CCGraphDescriber();
  1638. mDescribers.insertBack(d);
  1639. d->mType = CCGraphDescriber::eRoot;
  1640. d->mAddress.AppendInt(aAddress, 16);
  1641. d->mCnt = aKnownEdges;
  1642. }
  1643. }
  1644. void DescribeGarbage(uint64_t aAddress)
  1645. {
  1646. if (!mDisableLog) {
  1647. fprintf(mCCLog, "%p [garbage]\n", (void*)aAddress);
  1648. }
  1649. if (mWantAfterProcessing) {
  1650. CCGraphDescriber* d = new CCGraphDescriber();
  1651. mDescribers.insertBack(d);
  1652. d->mType = CCGraphDescriber::eGarbage;
  1653. d->mAddress.AppendInt(aAddress, 16);
  1654. }
  1655. }
  1656. void End()
  1657. {
  1658. if (!mDisableLog) {
  1659. mCCLog = nullptr;
  1660. Unused << NS_WARN_IF(NS_FAILED(mLogSink->CloseCCLog()));
  1661. }
  1662. }
  1663. NS_IMETHOD ProcessNext(nsICycleCollectorHandler* aHandler,
  1664. bool* aCanContinue) override
  1665. {
  1666. if (NS_WARN_IF(!aHandler) || NS_WARN_IF(!mWantAfterProcessing)) {
  1667. return NS_ERROR_UNEXPECTED;
  1668. }
  1669. CCGraphDescriber* d = mDescribers.popFirst();
  1670. if (d) {
  1671. switch (d->mType) {
  1672. case CCGraphDescriber::eRefCountedObject:
  1673. aHandler->NoteRefCountedObject(d->mAddress,
  1674. d->mCnt,
  1675. d->mName);
  1676. break;
  1677. case CCGraphDescriber::eGCedObject:
  1678. case CCGraphDescriber::eGCMarkedObject:
  1679. aHandler->NoteGCedObject(d->mAddress,
  1680. d->mType ==
  1681. CCGraphDescriber::eGCMarkedObject,
  1682. d->mName,
  1683. d->mCompartmentOrToAddress);
  1684. break;
  1685. case CCGraphDescriber::eEdge:
  1686. aHandler->NoteEdge(d->mAddress,
  1687. d->mCompartmentOrToAddress,
  1688. d->mName);
  1689. break;
  1690. case CCGraphDescriber::eRoot:
  1691. aHandler->DescribeRoot(d->mAddress,
  1692. d->mCnt);
  1693. break;
  1694. case CCGraphDescriber::eGarbage:
  1695. aHandler->DescribeGarbage(d->mAddress);
  1696. break;
  1697. case CCGraphDescriber::eUnknown:
  1698. NS_NOTREACHED("CCGraphDescriber::eUnknown");
  1699. break;
  1700. }
  1701. delete d;
  1702. }
  1703. if (!(*aCanContinue = !mDescribers.isEmpty())) {
  1704. mCurrentAddress.AssignLiteral("0x");
  1705. }
  1706. return NS_OK;
  1707. }
  1708. NS_IMETHOD AsLogger(nsCycleCollectorLogger** aRetVal) override
  1709. {
  1710. RefPtr<nsCycleCollectorLogger> rval = this;
  1711. rval.forget(aRetVal);
  1712. return NS_OK;
  1713. }
  1714. private:
  1715. void ClearDescribers()
  1716. {
  1717. CCGraphDescriber* d;
  1718. while ((d = mDescribers.popFirst())) {
  1719. delete d;
  1720. }
  1721. }
  1722. nsCOMPtr<nsICycleCollectorLogSink> mLogSink;
  1723. bool mWantAllTraces;
  1724. bool mDisableLog;
  1725. bool mWantAfterProcessing;
  1726. nsCString mCurrentAddress;
  1727. mozilla::LinkedList<CCGraphDescriber> mDescribers;
  1728. FILE* mCCLog;
  1729. };
  1730. NS_IMPL_ISUPPORTS(nsCycleCollectorLogger, nsICycleCollectorListener)
  1731. nsresult
  1732. nsCycleCollectorLoggerConstructor(nsISupports* aOuter,
  1733. const nsIID& aIID,
  1734. void** aInstancePtr)
  1735. {
  1736. if (NS_WARN_IF(aOuter)) {
  1737. return NS_ERROR_NO_AGGREGATION;
  1738. }
  1739. nsISupports* logger = new nsCycleCollectorLogger();
  1740. return logger->QueryInterface(aIID, aInstancePtr);
  1741. }
  1742. static bool
  1743. GCThingIsGrayCCThing(JS::GCCellPtr thing)
  1744. {
  1745. return AddToCCKind(thing.kind()) &&
  1746. JS::GCThingIsMarkedGray(thing);
  1747. }
  1748. static bool
  1749. ValueIsGrayCCThing(const JS::Value& value)
  1750. {
  1751. return AddToCCKind(value.traceKind()) &&
  1752. JS::GCThingIsMarkedGray(value.toGCCellPtr());
  1753. }
  1754. ////////////////////////////////////////////////////////////////////////
  1755. // Bacon & Rajan's |MarkRoots| routine.
  1756. ////////////////////////////////////////////////////////////////////////
  1757. class CCGraphBuilder final : public nsCycleCollectionTraversalCallback,
  1758. public nsCycleCollectionNoteRootCallback
  1759. {
  1760. private:
  1761. CCGraph& mGraph;
  1762. CycleCollectorResults& mResults;
  1763. NodePool::Builder mNodeBuilder;
  1764. EdgePool::Builder mEdgeBuilder;
  1765. MOZ_INIT_OUTSIDE_CTOR PtrInfo* mCurrPi;
  1766. nsCycleCollectionParticipant* mJSParticipant;
  1767. nsCycleCollectionParticipant* mJSZoneParticipant;
  1768. nsCString mNextEdgeName;
  1769. RefPtr<nsCycleCollectorLogger> mLogger;
  1770. bool mMergeZones;
  1771. nsAutoPtr<NodePool::Enumerator> mCurrNode;
  1772. public:
  1773. CCGraphBuilder(CCGraph& aGraph,
  1774. CycleCollectorResults& aResults,
  1775. CycleCollectedJSContext* aJSContext,
  1776. nsCycleCollectorLogger* aLogger,
  1777. bool aMergeZones);
  1778. virtual ~CCGraphBuilder();
  1779. bool WantAllTraces() const
  1780. {
  1781. return nsCycleCollectionNoteRootCallback::WantAllTraces();
  1782. }
  1783. bool AddPurpleRoot(void* aRoot, nsCycleCollectionParticipant* aParti);
  1784. // This is called when all roots have been added to the graph, to prepare for BuildGraph().
  1785. void DoneAddingRoots();
  1786. // Do some work traversing nodes in the graph. Returns true if this graph building is finished.
  1787. bool BuildGraph(SliceBudget& aBudget);
  1788. private:
  1789. PtrInfo* AddNode(void* aPtr, nsCycleCollectionParticipant* aParticipant);
  1790. PtrInfo* AddWeakMapNode(JS::GCCellPtr aThing);
  1791. PtrInfo* AddWeakMapNode(JSObject* aObject);
  1792. void SetFirstChild()
  1793. {
  1794. mCurrPi->SetFirstChild(mEdgeBuilder.Mark());
  1795. }
  1796. void SetLastChild()
  1797. {
  1798. mCurrPi->SetLastChild(mEdgeBuilder.Mark());
  1799. }
  1800. public:
  1801. // nsCycleCollectionNoteRootCallback methods.
  1802. NS_IMETHOD_(void) NoteXPCOMRoot(nsISupports* aRoot);
  1803. NS_IMETHOD_(void) NoteJSRoot(JSObject* aRoot);
  1804. NS_IMETHOD_(void) NoteNativeRoot(void* aRoot,
  1805. nsCycleCollectionParticipant* aParticipant);
  1806. NS_IMETHOD_(void) NoteWeakMapping(JSObject* aMap, JS::GCCellPtr aKey,
  1807. JSObject* aKdelegate, JS::GCCellPtr aVal);
  1808. // nsCycleCollectionTraversalCallback methods.
  1809. NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt aRefCount,
  1810. const char* aObjName);
  1811. NS_IMETHOD_(void) DescribeGCedNode(bool aIsMarked, const char* aObjName,
  1812. uint64_t aCompartmentAddress);
  1813. NS_IMETHOD_(void) NoteXPCOMChild(nsISupports* aChild);
  1814. NS_IMETHOD_(void) NoteJSChild(const JS::GCCellPtr& aThing);
  1815. NS_IMETHOD_(void) NoteNativeChild(void* aChild,
  1816. nsCycleCollectionParticipant* aParticipant);
  1817. NS_IMETHOD_(void) NoteNextEdgeName(const char* aName);
  1818. private:
  1819. void NoteJSChild(JS::GCCellPtr aChild);
  1820. NS_IMETHOD_(void) NoteRoot(void* aRoot,
  1821. nsCycleCollectionParticipant* aParticipant)
  1822. {
  1823. MOZ_ASSERT(aRoot);
  1824. MOZ_ASSERT(aParticipant);
  1825. if (!aParticipant->CanSkipInCC(aRoot) || MOZ_UNLIKELY(WantAllTraces())) {
  1826. AddNode(aRoot, aParticipant);
  1827. }
  1828. }
  1829. NS_IMETHOD_(void) NoteChild(void* aChild, nsCycleCollectionParticipant* aCp,
  1830. nsCString& aEdgeName)
  1831. {
  1832. PtrInfo* childPi = AddNode(aChild, aCp);
  1833. if (!childPi) {
  1834. return;
  1835. }
  1836. mEdgeBuilder.Add(childPi);
  1837. if (mLogger) {
  1838. mLogger->NoteEdge((uint64_t)aChild, aEdgeName.get());
  1839. }
  1840. ++childPi->mInternalRefs;
  1841. }
  1842. JS::Zone* MergeZone(JS::GCCellPtr aGcthing)
  1843. {
  1844. if (!mMergeZones) {
  1845. return nullptr;
  1846. }
  1847. JS::Zone* zone = JS::GetTenuredGCThingZone(aGcthing);
  1848. if (js::IsSystemZone(zone)) {
  1849. return nullptr;
  1850. }
  1851. return zone;
  1852. }
  1853. };
  1854. CCGraphBuilder::CCGraphBuilder(CCGraph& aGraph,
  1855. CycleCollectorResults& aResults,
  1856. CycleCollectedJSContext* aJSContext,
  1857. nsCycleCollectorLogger* aLogger,
  1858. bool aMergeZones)
  1859. : mGraph(aGraph)
  1860. , mResults(aResults)
  1861. , mNodeBuilder(aGraph.mNodes)
  1862. , mEdgeBuilder(aGraph.mEdges)
  1863. , mJSParticipant(nullptr)
  1864. , mJSZoneParticipant(nullptr)
  1865. , mLogger(aLogger)
  1866. , mMergeZones(aMergeZones)
  1867. {
  1868. if (aJSContext) {
  1869. mJSParticipant = aJSContext->GCThingParticipant();
  1870. mJSZoneParticipant = aJSContext->ZoneParticipant();
  1871. }
  1872. if (mLogger) {
  1873. mFlags |= nsCycleCollectionTraversalCallback::WANT_DEBUG_INFO;
  1874. if (mLogger->IsAllTraces()) {
  1875. mFlags |= nsCycleCollectionTraversalCallback::WANT_ALL_TRACES;
  1876. mWantAllTraces = true; // for nsCycleCollectionNoteRootCallback
  1877. }
  1878. }
  1879. mMergeZones = mMergeZones && MOZ_LIKELY(!WantAllTraces());
  1880. MOZ_ASSERT(nsCycleCollectionNoteRootCallback::WantAllTraces() ==
  1881. nsCycleCollectionTraversalCallback::WantAllTraces());
  1882. }
  1883. CCGraphBuilder::~CCGraphBuilder()
  1884. {
  1885. }
  1886. PtrInfo*
  1887. CCGraphBuilder::AddNode(void* aPtr, nsCycleCollectionParticipant* aParticipant)
  1888. {
  1889. PtrToNodeEntry* e = mGraph.AddNodeToMap(aPtr);
  1890. if (!e) {
  1891. return nullptr;
  1892. }
  1893. PtrInfo* result;
  1894. if (!e->mNode) {
  1895. // New entry.
  1896. result = mNodeBuilder.Add(aPtr, aParticipant);
  1897. if (!result) {
  1898. return nullptr;
  1899. }
  1900. e->mNode = result;
  1901. NS_ASSERTION(result, "mNodeBuilder.Add returned null");
  1902. } else {
  1903. result = e->mNode;
  1904. MOZ_ASSERT(result->mParticipant == aParticipant,
  1905. "nsCycleCollectionParticipant shouldn't change!");
  1906. }
  1907. return result;
  1908. }
  1909. bool
  1910. CCGraphBuilder::AddPurpleRoot(void* aRoot, nsCycleCollectionParticipant* aParti)
  1911. {
  1912. CanonicalizeParticipant(&aRoot, &aParti);
  1913. if (WantAllTraces() || !aParti->CanSkipInCC(aRoot)) {
  1914. PtrInfo* pinfo = AddNode(aRoot, aParti);
  1915. if (!pinfo) {
  1916. return false;
  1917. }
  1918. }
  1919. return true;
  1920. }
  1921. void
  1922. CCGraphBuilder::DoneAddingRoots()
  1923. {
  1924. // We've finished adding roots, and everything in the graph is a root.
  1925. mGraph.mRootCount = mGraph.MapCount();
  1926. mCurrNode = new NodePool::Enumerator(mGraph.mNodes);
  1927. }
  1928. MOZ_NEVER_INLINE bool
  1929. CCGraphBuilder::BuildGraph(SliceBudget& aBudget)
  1930. {
  1931. const intptr_t kNumNodesBetweenTimeChecks = 1000;
  1932. const intptr_t kStep = SliceBudget::CounterReset / kNumNodesBetweenTimeChecks;
  1933. MOZ_ASSERT(mCurrNode);
  1934. while (!aBudget.isOverBudget() && !mCurrNode->IsDone()) {
  1935. PtrInfo* pi = mCurrNode->GetNext();
  1936. if (!pi) {
  1937. MOZ_CRASH();
  1938. }
  1939. mCurrPi = pi;
  1940. // We need to call SetFirstChild() even on deleted nodes, to set their
  1941. // firstChild() that may be read by a prior non-deleted neighbor.
  1942. SetFirstChild();
  1943. if (pi->mParticipant) {
  1944. nsresult rv = pi->mParticipant->TraverseNativeAndJS(pi->mPointer, *this);
  1945. MOZ_RELEASE_ASSERT(!NS_FAILED(rv), "Cycle collector Traverse method failed");
  1946. }
  1947. if (mCurrNode->AtBlockEnd()) {
  1948. SetLastChild();
  1949. }
  1950. aBudget.step(kStep);
  1951. }
  1952. if (!mCurrNode->IsDone()) {
  1953. return false;
  1954. }
  1955. if (mGraph.mRootCount > 0) {
  1956. SetLastChild();
  1957. }
  1958. mCurrNode = nullptr;
  1959. return true;
  1960. }
  1961. NS_IMETHODIMP_(void)
  1962. CCGraphBuilder::NoteXPCOMRoot(nsISupports* aRoot)
  1963. {
  1964. aRoot = CanonicalizeXPCOMParticipant(aRoot);
  1965. NS_ASSERTION(aRoot,
  1966. "Don't add objects that don't participate in collection!");
  1967. nsXPCOMCycleCollectionParticipant* cp;
  1968. ToParticipant(aRoot, &cp);
  1969. NoteRoot(aRoot, cp);
  1970. }
  1971. NS_IMETHODIMP_(void)
  1972. CCGraphBuilder::NoteJSRoot(JSObject* aRoot)
  1973. {
  1974. if (JS::Zone* zone = MergeZone(JS::GCCellPtr(aRoot))) {
  1975. NoteRoot(zone, mJSZoneParticipant);
  1976. } else {
  1977. NoteRoot(aRoot, mJSParticipant);
  1978. }
  1979. }
  1980. NS_IMETHODIMP_(void)
  1981. CCGraphBuilder::NoteNativeRoot(void* aRoot,
  1982. nsCycleCollectionParticipant* aParticipant)
  1983. {
  1984. NoteRoot(aRoot, aParticipant);
  1985. }
  1986. NS_IMETHODIMP_(void)
  1987. CCGraphBuilder::DescribeRefCountedNode(nsrefcnt aRefCount, const char* aObjName)
  1988. {
  1989. MOZ_RELEASE_ASSERT(aRefCount != 0, "CCed refcounted object has zero refcount");
  1990. MOZ_RELEASE_ASSERT(aRefCount != UINT32_MAX, "CCed refcounted object has overflowing refcount");
  1991. mResults.mVisitedRefCounted++;
  1992. if (mLogger) {
  1993. mLogger->NoteRefCountedObject((uint64_t)mCurrPi->mPointer, aRefCount,
  1994. aObjName);
  1995. }
  1996. mCurrPi->mRefCount = aRefCount;
  1997. }
  1998. NS_IMETHODIMP_(void)
  1999. CCGraphBuilder::DescribeGCedNode(bool aIsMarked, const char* aObjName,
  2000. uint64_t aCompartmentAddress)
  2001. {
  2002. uint32_t refCount = aIsMarked ? UINT32_MAX : 0;
  2003. mResults.mVisitedGCed++;
  2004. if (mLogger) {
  2005. mLogger->NoteGCedObject((uint64_t)mCurrPi->mPointer, aIsMarked,
  2006. aObjName, aCompartmentAddress);
  2007. }
  2008. mCurrPi->mRefCount = refCount;
  2009. }
  2010. NS_IMETHODIMP_(void)
  2011. CCGraphBuilder::NoteXPCOMChild(nsISupports* aChild)
  2012. {
  2013. nsCString edgeName;
  2014. if (WantDebugInfo()) {
  2015. edgeName.Assign(mNextEdgeName);
  2016. mNextEdgeName.Truncate();
  2017. }
  2018. if (!aChild || !(aChild = CanonicalizeXPCOMParticipant(aChild))) {
  2019. return;
  2020. }
  2021. nsXPCOMCycleCollectionParticipant* cp;
  2022. ToParticipant(aChild, &cp);
  2023. if (cp && (!cp->CanSkipThis(aChild) || WantAllTraces())) {
  2024. NoteChild(aChild, cp, edgeName);
  2025. }
  2026. }
  2027. NS_IMETHODIMP_(void)
  2028. CCGraphBuilder::NoteNativeChild(void* aChild,
  2029. nsCycleCollectionParticipant* aParticipant)
  2030. {
  2031. nsCString edgeName;
  2032. if (WantDebugInfo()) {
  2033. edgeName.Assign(mNextEdgeName);
  2034. mNextEdgeName.Truncate();
  2035. }
  2036. if (!aChild) {
  2037. return;
  2038. }
  2039. MOZ_ASSERT(aParticipant, "Need a nsCycleCollectionParticipant!");
  2040. if (!aParticipant->CanSkipThis(aChild) || WantAllTraces()) {
  2041. NoteChild(aChild, aParticipant, edgeName);
  2042. }
  2043. }
  2044. NS_IMETHODIMP_(void)
  2045. CCGraphBuilder::NoteJSChild(const JS::GCCellPtr& aChild)
  2046. {
  2047. if (!aChild) {
  2048. return;
  2049. }
  2050. nsCString edgeName;
  2051. if (MOZ_UNLIKELY(WantDebugInfo())) {
  2052. edgeName.Assign(mNextEdgeName);
  2053. mNextEdgeName.Truncate();
  2054. }
  2055. if (GCThingIsGrayCCThing(aChild) || MOZ_UNLIKELY(WantAllTraces())) {
  2056. if (JS::Zone* zone = MergeZone(aChild)) {
  2057. NoteChild(zone, mJSZoneParticipant, edgeName);
  2058. } else {
  2059. NoteChild(aChild.asCell(), mJSParticipant, edgeName);
  2060. }
  2061. }
  2062. }
  2063. NS_IMETHODIMP_(void)
  2064. CCGraphBuilder::NoteNextEdgeName(const char* aName)
  2065. {
  2066. if (WantDebugInfo()) {
  2067. mNextEdgeName = aName;
  2068. }
  2069. }
  2070. PtrInfo*
  2071. CCGraphBuilder::AddWeakMapNode(JS::GCCellPtr aNode)
  2072. {
  2073. MOZ_ASSERT(aNode, "Weak map node should be non-null.");
  2074. if (!GCThingIsGrayCCThing(aNode) && !WantAllTraces()) {
  2075. return nullptr;
  2076. }
  2077. if (JS::Zone* zone = MergeZone(aNode)) {
  2078. return AddNode(zone, mJSZoneParticipant);
  2079. }
  2080. return AddNode(aNode.asCell(), mJSParticipant);
  2081. }
  2082. PtrInfo*
  2083. CCGraphBuilder::AddWeakMapNode(JSObject* aObject)
  2084. {
  2085. return AddWeakMapNode(JS::GCCellPtr(aObject));
  2086. }
  2087. NS_IMETHODIMP_(void)
  2088. CCGraphBuilder::NoteWeakMapping(JSObject* aMap, JS::GCCellPtr aKey,
  2089. JSObject* aKdelegate, JS::GCCellPtr aVal)
  2090. {
  2091. // Don't try to optimize away the entry here, as we've already attempted to
  2092. // do that in TraceWeakMapping in nsXPConnect.
  2093. WeakMapping* mapping = mGraph.mWeakMaps.AppendElement();
  2094. mapping->mMap = aMap ? AddWeakMapNode(aMap) : nullptr;
  2095. mapping->mKey = aKey ? AddWeakMapNode(aKey) : nullptr;
  2096. mapping->mKeyDelegate = aKdelegate ? AddWeakMapNode(aKdelegate) : mapping->mKey;
  2097. mapping->mVal = aVal ? AddWeakMapNode(aVal) : nullptr;
  2098. if (mLogger) {
  2099. mLogger->NoteWeakMapEntry((uint64_t)aMap, aKey ? aKey.unsafeAsInteger() : 0,
  2100. (uint64_t)aKdelegate,
  2101. aVal ? aVal.unsafeAsInteger() : 0);
  2102. }
  2103. }
  2104. static bool
  2105. AddPurpleRoot(CCGraphBuilder& aBuilder, void* aRoot,
  2106. nsCycleCollectionParticipant* aParti)
  2107. {
  2108. return aBuilder.AddPurpleRoot(aRoot, aParti);
  2109. }
  2110. // MayHaveChild() will be false after a Traverse if the object does
  2111. // not have any children the CC will visit.
  2112. class ChildFinder : public nsCycleCollectionTraversalCallback
  2113. {
  2114. public:
  2115. ChildFinder() : mMayHaveChild(false)
  2116. {
  2117. }
  2118. // The logic of the Note*Child functions must mirror that of their
  2119. // respective functions in CCGraphBuilder.
  2120. NS_IMETHOD_(void) NoteXPCOMChild(nsISupports* aChild);
  2121. NS_IMETHOD_(void) NoteNativeChild(void* aChild,
  2122. nsCycleCollectionParticipant* aHelper);
  2123. NS_IMETHOD_(void) NoteJSChild(const JS::GCCellPtr& aThing);
  2124. NS_IMETHOD_(void) DescribeRefCountedNode(nsrefcnt aRefcount,
  2125. const char* aObjname)
  2126. {
  2127. }
  2128. NS_IMETHOD_(void) DescribeGCedNode(bool aIsMarked,
  2129. const char* aObjname,
  2130. uint64_t aCompartmentAddress)
  2131. {
  2132. }
  2133. NS_IMETHOD_(void) NoteNextEdgeName(const char* aName)
  2134. {
  2135. }
  2136. bool MayHaveChild()
  2137. {
  2138. return mMayHaveChild;
  2139. }
  2140. private:
  2141. bool mMayHaveChild;
  2142. };
  2143. NS_IMETHODIMP_(void)
  2144. ChildFinder::NoteXPCOMChild(nsISupports* aChild)
  2145. {
  2146. if (!aChild || !(aChild = CanonicalizeXPCOMParticipant(aChild))) {
  2147. return;
  2148. }
  2149. nsXPCOMCycleCollectionParticipant* cp;
  2150. ToParticipant(aChild, &cp);
  2151. if (cp && !cp->CanSkip(aChild, true)) {
  2152. mMayHaveChild = true;
  2153. }
  2154. }
  2155. NS_IMETHODIMP_(void)
  2156. ChildFinder::NoteNativeChild(void* aChild,
  2157. nsCycleCollectionParticipant* aHelper)
  2158. {
  2159. if (!aChild) {
  2160. return;
  2161. }
  2162. MOZ_ASSERT(aHelper, "Native child must have a participant");
  2163. if (!aHelper->CanSkip(aChild, true)) {
  2164. mMayHaveChild = true;
  2165. }
  2166. }
  2167. NS_IMETHODIMP_(void)
  2168. ChildFinder::NoteJSChild(const JS::GCCellPtr& aChild)
  2169. {
  2170. if (aChild && JS::GCThingIsMarkedGray(aChild)) {
  2171. mMayHaveChild = true;
  2172. }
  2173. }
  2174. static bool
  2175. MayHaveChild(void* aObj, nsCycleCollectionParticipant* aCp)
  2176. {
  2177. ChildFinder cf;
  2178. aCp->TraverseNativeAndJS(aObj, cf);
  2179. return cf.MayHaveChild();
  2180. }
  2181. // JSPurpleBuffer keeps references to GCThings which might affect the
  2182. // next cycle collection. It is owned only by itself and during unlink its
  2183. // self reference is broken down and the object ends up killing itself.
  2184. // If GC happens before CC, references to GCthings and the self reference are
  2185. // removed.
  2186. class JSPurpleBuffer
  2187. {
  2188. ~JSPurpleBuffer()
  2189. {
  2190. MOZ_ASSERT(mValues.IsEmpty());
  2191. MOZ_ASSERT(mObjects.IsEmpty());
  2192. }
  2193. public:
  2194. explicit JSPurpleBuffer(RefPtr<JSPurpleBuffer>& aReferenceToThis)
  2195. : mReferenceToThis(aReferenceToThis)
  2196. , mValues(kSegmentSize)
  2197. , mObjects(kSegmentSize)
  2198. {
  2199. mReferenceToThis = this;
  2200. mozilla::HoldJSObjects(this);
  2201. }
  2202. void Destroy()
  2203. {
  2204. mReferenceToThis = nullptr;
  2205. mValues.Clear();
  2206. mObjects.Clear();
  2207. mozilla::DropJSObjects(this);
  2208. }
  2209. NS_INLINE_DECL_CYCLE_COLLECTING_NATIVE_REFCOUNTING(JSPurpleBuffer)
  2210. NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_NATIVE_CLASS(JSPurpleBuffer)
  2211. RefPtr<JSPurpleBuffer>& mReferenceToThis;
  2212. // These are raw pointers instead of Heap<T> because we only need Heap<T> for
  2213. // pointers which may point into the nursery. The purple buffer never contains
  2214. // pointers to the nursery because nursery gcthings can never be gray and only
  2215. // gray things can be inserted into the purple buffer.
  2216. static const size_t kSegmentSize = 512;
  2217. SegmentedVector<JS::Value, kSegmentSize, InfallibleAllocPolicy> mValues;
  2218. SegmentedVector<JSObject*, kSegmentSize, InfallibleAllocPolicy> mObjects;
  2219. };
  2220. NS_IMPL_CYCLE_COLLECTION_CLASS(JSPurpleBuffer)
  2221. NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(JSPurpleBuffer)
  2222. tmp->Destroy();
  2223. NS_IMPL_CYCLE_COLLECTION_UNLINK_END
  2224. NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(JSPurpleBuffer)
  2225. CycleCollectionNoteChild(cb, tmp, "self");
  2226. NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  2227. #define NS_TRACE_SEGMENTED_ARRAY(_field, _type) \
  2228. { \
  2229. for (auto iter = tmp->_field.Iter(); !iter.Done(); iter.Next()) { \
  2230. js::gc::CallTraceCallbackOnNonHeap<_type, TraceCallbacks>( \
  2231. &iter.Get(), aCallbacks, #_field, aClosure); \
  2232. } \
  2233. }
  2234. NS_IMPL_CYCLE_COLLECTION_TRACE_BEGIN(JSPurpleBuffer)
  2235. NS_TRACE_SEGMENTED_ARRAY(mValues, JS::Value)
  2236. NS_TRACE_SEGMENTED_ARRAY(mObjects, JSObject*)
  2237. NS_IMPL_CYCLE_COLLECTION_TRACE_END
  2238. NS_IMPL_CYCLE_COLLECTION_ROOT_NATIVE(JSPurpleBuffer, AddRef)
  2239. NS_IMPL_CYCLE_COLLECTION_UNROOT_NATIVE(JSPurpleBuffer, Release)
  2240. class SnowWhiteKiller : public TraceCallbacks
  2241. {
  2242. struct SnowWhiteObject
  2243. {
  2244. void* mPointer;
  2245. nsCycleCollectionParticipant* mParticipant;
  2246. nsCycleCollectingAutoRefCnt* mRefCnt;
  2247. };
  2248. // Segments are 4 KiB on 32-bit and 8 KiB on 64-bit.
  2249. static const size_t kSegmentSize = sizeof(void*) * 1024;
  2250. typedef SegmentedVector<SnowWhiteObject, kSegmentSize, InfallibleAllocPolicy>
  2251. ObjectsVector;
  2252. public:
  2253. explicit SnowWhiteKiller(nsCycleCollector* aCollector)
  2254. : mCollector(aCollector)
  2255. , mObjects(kSegmentSize)
  2256. {
  2257. MOZ_ASSERT(mCollector, "Calling SnowWhiteKiller after nsCC went away");
  2258. }
  2259. ~SnowWhiteKiller()
  2260. {
  2261. for (auto iter = mObjects.Iter(); !iter.Done(); iter.Next()) {
  2262. SnowWhiteObject& o = iter.Get();
  2263. if (!o.mRefCnt->get() && !o.mRefCnt->IsInPurpleBuffer()) {
  2264. mCollector->RemoveObjectFromGraph(o.mPointer);
  2265. o.mRefCnt->stabilizeForDeletion();
  2266. {
  2267. JS::AutoEnterCycleCollection autocc(mCollector->Context()->Context());
  2268. o.mParticipant->Trace(o.mPointer, *this, nullptr);
  2269. }
  2270. o.mParticipant->DeleteCycleCollectable(o.mPointer);
  2271. }
  2272. }
  2273. }
  2274. void
  2275. Visit(nsPurpleBuffer& aBuffer, nsPurpleBufferEntry* aEntry)
  2276. {
  2277. MOZ_ASSERT(aEntry->mObject, "Null object in purple buffer");
  2278. if (!aEntry->mRefCnt->get()) {
  2279. void* o = aEntry->mObject;
  2280. nsCycleCollectionParticipant* cp = aEntry->mParticipant;
  2281. CanonicalizeParticipant(&o, &cp);
  2282. SnowWhiteObject swo = { o, cp, aEntry->mRefCnt };
  2283. mObjects.InfallibleAppend(swo);
  2284. aBuffer.Remove(aEntry);
  2285. }
  2286. }
  2287. bool HasSnowWhiteObjects() const
  2288. {
  2289. return !mObjects.IsEmpty();
  2290. }
  2291. virtual void Trace(JS::Heap<JS::Value>* aValue, const char* aName,
  2292. void* aClosure) const override
  2293. {
  2294. const JS::Value& val = aValue->unbarrieredGet();
  2295. if (val.isGCThing() && ValueIsGrayCCThing(val)) {
  2296. MOZ_ASSERT(!js::gc::IsInsideNursery(val.toGCThing()));
  2297. mCollector->GetJSPurpleBuffer()->mValues.InfallibleAppend(val);
  2298. }
  2299. }
  2300. virtual void Trace(JS::Heap<jsid>* aId, const char* aName,
  2301. void* aClosure) const override
  2302. {
  2303. }
  2304. void AppendJSObjectToPurpleBuffer(JSObject* obj) const
  2305. {
  2306. if (obj && JS::ObjectIsMarkedGray(obj)) {
  2307. MOZ_ASSERT(JS::ObjectIsTenured(obj));
  2308. mCollector->GetJSPurpleBuffer()->mObjects.InfallibleAppend(obj);
  2309. }
  2310. }
  2311. virtual void Trace(JS::Heap<JSObject*>* aObject, const char* aName,
  2312. void* aClosure) const override
  2313. {
  2314. AppendJSObjectToPurpleBuffer(aObject->unbarrieredGet());
  2315. }
  2316. virtual void Trace(JSObject** aObject, const char* aName,
  2317. void* aClosure) const override
  2318. {
  2319. AppendJSObjectToPurpleBuffer(*aObject);
  2320. }
  2321. virtual void Trace(JS::TenuredHeap<JSObject*>* aObject, const char* aName,
  2322. void* aClosure) const override
  2323. {
  2324. AppendJSObjectToPurpleBuffer(aObject->unbarrieredGetPtr());
  2325. }
  2326. virtual void Trace(JS::Heap<JSString*>* aString, const char* aName,
  2327. void* aClosure) const override
  2328. {
  2329. }
  2330. virtual void Trace(JS::Heap<JSScript*>* aScript, const char* aName,
  2331. void* aClosure) const override
  2332. {
  2333. }
  2334. virtual void Trace(JS::Heap<JSFunction*>* aFunction, const char* aName,
  2335. void* aClosure) const override
  2336. {
  2337. }
  2338. private:
  2339. RefPtr<nsCycleCollector> mCollector;
  2340. ObjectsVector mObjects;
  2341. };
  2342. class RemoveSkippableVisitor : public SnowWhiteKiller
  2343. {
  2344. public:
  2345. RemoveSkippableVisitor(nsCycleCollector* aCollector,
  2346. bool aRemoveChildlessNodes,
  2347. bool aAsyncSnowWhiteFreeing,
  2348. CC_ForgetSkippableCallback aCb)
  2349. : SnowWhiteKiller(aCollector)
  2350. , mRemoveChildlessNodes(aRemoveChildlessNodes)
  2351. , mAsyncSnowWhiteFreeing(aAsyncSnowWhiteFreeing)
  2352. , mDispatchedDeferredDeletion(false)
  2353. , mCallback(aCb)
  2354. {
  2355. }
  2356. ~RemoveSkippableVisitor()
  2357. {
  2358. // Note, we must call the callback before SnowWhiteKiller calls
  2359. // DeleteCycleCollectable!
  2360. if (mCallback) {
  2361. mCallback();
  2362. }
  2363. if (HasSnowWhiteObjects()) {
  2364. // Effectively a continuation.
  2365. nsCycleCollector_dispatchDeferredDeletion(true);
  2366. }
  2367. }
  2368. void
  2369. Visit(nsPurpleBuffer& aBuffer, nsPurpleBufferEntry* aEntry)
  2370. {
  2371. MOZ_ASSERT(aEntry->mObject, "null mObject in purple buffer");
  2372. if (!aEntry->mRefCnt->get()) {
  2373. if (!mAsyncSnowWhiteFreeing) {
  2374. SnowWhiteKiller::Visit(aBuffer, aEntry);
  2375. } else if (!mDispatchedDeferredDeletion) {
  2376. mDispatchedDeferredDeletion = true;
  2377. nsCycleCollector_dispatchDeferredDeletion(false);
  2378. }
  2379. return;
  2380. }
  2381. void* o = aEntry->mObject;
  2382. nsCycleCollectionParticipant* cp = aEntry->mParticipant;
  2383. CanonicalizeParticipant(&o, &cp);
  2384. if (aEntry->mRefCnt->IsPurple() && !cp->CanSkip(o, false) &&
  2385. (!mRemoveChildlessNodes || MayHaveChild(o, cp))) {
  2386. return;
  2387. }
  2388. aBuffer.Remove(aEntry);
  2389. }
  2390. private:
  2391. bool mRemoveChildlessNodes;
  2392. bool mAsyncSnowWhiteFreeing;
  2393. bool mDispatchedDeferredDeletion;
  2394. CC_ForgetSkippableCallback mCallback;
  2395. };
  2396. void
  2397. nsPurpleBuffer::RemoveSkippable(nsCycleCollector* aCollector,
  2398. bool aRemoveChildlessNodes,
  2399. bool aAsyncSnowWhiteFreeing,
  2400. CC_ForgetSkippableCallback aCb)
  2401. {
  2402. RemoveSkippableVisitor visitor(aCollector, aRemoveChildlessNodes,
  2403. aAsyncSnowWhiteFreeing, aCb);
  2404. VisitEntries(visitor);
  2405. }
  2406. bool
  2407. nsCycleCollector::FreeSnowWhite(bool aUntilNoSWInPurpleBuffer)
  2408. {
  2409. CheckThreadSafety();
  2410. if (mFreeingSnowWhite) {
  2411. return false;
  2412. }
  2413. AutoRestore<bool> ar(mFreeingSnowWhite);
  2414. mFreeingSnowWhite = true;
  2415. bool hadSnowWhiteObjects = false;
  2416. do {
  2417. SnowWhiteKiller visitor(this);
  2418. mPurpleBuf.VisitEntries(visitor);
  2419. hadSnowWhiteObjects = hadSnowWhiteObjects ||
  2420. visitor.HasSnowWhiteObjects();
  2421. if (!visitor.HasSnowWhiteObjects()) {
  2422. break;
  2423. }
  2424. } while (aUntilNoSWInPurpleBuffer);
  2425. return hadSnowWhiteObjects;
  2426. }
  2427. void
  2428. nsCycleCollector::ForgetSkippable(bool aRemoveChildlessNodes,
  2429. bool aAsyncSnowWhiteFreeing)
  2430. {
  2431. CheckThreadSafety();
  2432. // Avoid this when we're aleady dealing with snow-white objects.
  2433. if (mFreeingSnowWhite) {
  2434. return;
  2435. }
  2436. mozilla::Maybe<mozilla::AutoGlobalTimelineMarker> marker;
  2437. if (NS_IsMainThread()) {
  2438. marker.emplace("nsCycleCollector::ForgetSkippable", MarkerStackRequest::NO_STACK);
  2439. }
  2440. // If we remove things from the purple buffer during graph building, we may
  2441. // lose track of an object that was mutated during graph building.
  2442. MOZ_ASSERT(IsIdle());
  2443. if (mJSContext) {
  2444. mJSContext->PrepareForForgetSkippable();
  2445. }
  2446. MOZ_ASSERT(!mScanInProgress,
  2447. "Don't forget skippable or free snow-white while scan is in progress.");
  2448. mPurpleBuf.RemoveSkippable(this, aRemoveChildlessNodes,
  2449. aAsyncSnowWhiteFreeing, mForgetSkippableCB);
  2450. }
  2451. MOZ_NEVER_INLINE void
  2452. nsCycleCollector::MarkRoots(SliceBudget& aBudget)
  2453. {
  2454. JS::AutoAssertNoGC nogc;
  2455. TimeLog timeLog;
  2456. AutoRestore<bool> ar(mScanInProgress);
  2457. MOZ_RELEASE_ASSERT(!mScanInProgress);
  2458. mScanInProgress = true;
  2459. MOZ_ASSERT(mIncrementalPhase == GraphBuildingPhase);
  2460. JS::AutoEnterCycleCollection autocc(Context()->Context());
  2461. bool doneBuilding = mBuilder->BuildGraph(aBudget);
  2462. if (!doneBuilding) {
  2463. timeLog.Checkpoint("MarkRoots()");
  2464. return;
  2465. }
  2466. mBuilder = nullptr;
  2467. mIncrementalPhase = ScanAndCollectWhitePhase;
  2468. timeLog.Checkpoint("MarkRoots()");
  2469. }
  2470. ////////////////////////////////////////////////////////////////////////
  2471. // Bacon & Rajan's |ScanRoots| routine.
  2472. ////////////////////////////////////////////////////////////////////////
  2473. struct ScanBlackVisitor
  2474. {
  2475. ScanBlackVisitor(uint32_t& aWhiteNodeCount, bool& aFailed)
  2476. : mWhiteNodeCount(aWhiteNodeCount), mFailed(aFailed)
  2477. {
  2478. }
  2479. bool ShouldVisitNode(PtrInfo const* aPi)
  2480. {
  2481. return aPi->mColor != black;
  2482. }
  2483. MOZ_NEVER_INLINE void VisitNode(PtrInfo* aPi)
  2484. {
  2485. if (aPi->mColor == white) {
  2486. --mWhiteNodeCount;
  2487. }
  2488. aPi->mColor = black;
  2489. }
  2490. void Failed()
  2491. {
  2492. mFailed = true;
  2493. }
  2494. private:
  2495. uint32_t& mWhiteNodeCount;
  2496. bool& mFailed;
  2497. };
  2498. static void
  2499. FloodBlackNode(uint32_t& aWhiteNodeCount, bool& aFailed, PtrInfo* aPi)
  2500. {
  2501. GraphWalker<ScanBlackVisitor>(ScanBlackVisitor(aWhiteNodeCount,
  2502. aFailed)).Walk(aPi);
  2503. MOZ_ASSERT(aPi->mColor == black || !aPi->WasTraversed(),
  2504. "FloodBlackNode should make aPi black");
  2505. }
  2506. // Iterate over the WeakMaps. If we mark anything while iterating
  2507. // over the WeakMaps, we must iterate over all of the WeakMaps again.
  2508. void
  2509. nsCycleCollector::ScanWeakMaps()
  2510. {
  2511. bool anyChanged;
  2512. bool failed = false;
  2513. do {
  2514. anyChanged = false;
  2515. for (uint32_t i = 0; i < mGraph.mWeakMaps.Length(); i++) {
  2516. WeakMapping* wm = &mGraph.mWeakMaps[i];
  2517. // If any of these are null, the original object was marked black.
  2518. uint32_t mColor = wm->mMap ? wm->mMap->mColor : black;
  2519. uint32_t kColor = wm->mKey ? wm->mKey->mColor : black;
  2520. uint32_t kdColor = wm->mKeyDelegate ? wm->mKeyDelegate->mColor : black;
  2521. uint32_t vColor = wm->mVal ? wm->mVal->mColor : black;
  2522. MOZ_ASSERT(mColor != grey, "Uncolored weak map");
  2523. MOZ_ASSERT(kColor != grey, "Uncolored weak map key");
  2524. MOZ_ASSERT(kdColor != grey, "Uncolored weak map key delegate");
  2525. MOZ_ASSERT(vColor != grey, "Uncolored weak map value");
  2526. if (mColor == black && kColor != black && kdColor == black) {
  2527. FloodBlackNode(mWhiteNodeCount, failed, wm->mKey);
  2528. anyChanged = true;
  2529. }
  2530. if (mColor == black && kColor == black && vColor != black) {
  2531. FloodBlackNode(mWhiteNodeCount, failed, wm->mVal);
  2532. anyChanged = true;
  2533. }
  2534. }
  2535. } while (anyChanged);
  2536. if (failed) {
  2537. MOZ_ASSERT(false, "Ran out of memory in ScanWeakMaps");
  2538. }
  2539. }
  2540. // Flood black from any objects in the purple buffer that are in the CC graph.
  2541. class PurpleScanBlackVisitor
  2542. {
  2543. public:
  2544. PurpleScanBlackVisitor(CCGraph& aGraph, nsCycleCollectorLogger* aLogger,
  2545. uint32_t& aCount, bool& aFailed)
  2546. : mGraph(aGraph), mLogger(aLogger), mCount(aCount), mFailed(aFailed)
  2547. {
  2548. }
  2549. void
  2550. Visit(nsPurpleBuffer& aBuffer, nsPurpleBufferEntry* aEntry)
  2551. {
  2552. MOZ_ASSERT(aEntry->mObject,
  2553. "Entries with null mObject shouldn't be in the purple buffer.");
  2554. MOZ_ASSERT(aEntry->mRefCnt->get() != 0,
  2555. "Snow-white objects shouldn't be in the purple buffer.");
  2556. void* obj = aEntry->mObject;
  2557. if (!aEntry->mParticipant) {
  2558. obj = CanonicalizeXPCOMParticipant(static_cast<nsISupports*>(obj));
  2559. MOZ_ASSERT(obj, "Don't add objects that don't participate in collection!");
  2560. }
  2561. PtrInfo* pi = mGraph.FindNode(obj);
  2562. if (!pi) {
  2563. return;
  2564. }
  2565. MOZ_ASSERT(pi->mParticipant, "No dead objects should be in the purple buffer.");
  2566. if (MOZ_UNLIKELY(mLogger)) {
  2567. mLogger->NoteIncrementalRoot((uint64_t)pi->mPointer);
  2568. }
  2569. if (pi->mColor == black) {
  2570. return;
  2571. }
  2572. FloodBlackNode(mCount, mFailed, pi);
  2573. }
  2574. private:
  2575. CCGraph& mGraph;
  2576. RefPtr<nsCycleCollectorLogger> mLogger;
  2577. uint32_t& mCount;
  2578. bool& mFailed;
  2579. };
  2580. // Objects that have been stored somewhere since the start of incremental graph building must
  2581. // be treated as live for this cycle collection, because we may not have accurate information
  2582. // about who holds references to them.
  2583. void
  2584. nsCycleCollector::ScanIncrementalRoots()
  2585. {
  2586. TimeLog timeLog;
  2587. // Reference counted objects:
  2588. // We cleared the purple buffer at the start of the current ICC, so if a
  2589. // refcounted object is purple, it may have been AddRef'd during the current
  2590. // ICC. (It may also have only been released.) If that is the case, we cannot
  2591. // be sure that the set of things pointing to the object in the CC graph
  2592. // is accurate. Therefore, for safety, we treat any purple objects as being
  2593. // live during the current CC. We don't remove anything from the purple
  2594. // buffer here, so these objects will be suspected and freed in the next CC
  2595. // if they are garbage.
  2596. bool failed = false;
  2597. PurpleScanBlackVisitor purpleScanBlackVisitor(mGraph, mLogger,
  2598. mWhiteNodeCount, failed);
  2599. mPurpleBuf.VisitEntries(purpleScanBlackVisitor);
  2600. timeLog.Checkpoint("ScanIncrementalRoots::fix purple");
  2601. bool hasJSContext = !!mJSContext;
  2602. nsCycleCollectionParticipant* jsParticipant =
  2603. hasJSContext ? mJSContext->GCThingParticipant() : nullptr;
  2604. nsCycleCollectionParticipant* zoneParticipant =
  2605. hasJSContext ? mJSContext->ZoneParticipant() : nullptr;
  2606. bool hasLogger = !!mLogger;
  2607. NodePool::Enumerator etor(mGraph.mNodes);
  2608. while (!etor.IsDone()) {
  2609. PtrInfo* pi = etor.GetNext();
  2610. // As an optimization, if an object has already been determined to be live,
  2611. // don't consider it further. We can't do this if there is a listener,
  2612. // because the listener wants to know the complete set of incremental roots.
  2613. if (pi->mColor == black && MOZ_LIKELY(!hasLogger)) {
  2614. continue;
  2615. }
  2616. // Garbage collected objects:
  2617. // If a GCed object was added to the graph with a refcount of zero, and is
  2618. // now marked black by the GC, it was probably gray before and was exposed
  2619. // to active JS, so it may have been stored somewhere, so it needs to be
  2620. // treated as live.
  2621. if (pi->IsGrayJS() && MOZ_LIKELY(hasJSContext)) {
  2622. // If the object is still marked gray by the GC, nothing could have gotten
  2623. // hold of it, so it isn't an incremental root.
  2624. if (pi->mParticipant == jsParticipant) {
  2625. JS::GCCellPtr ptr(pi->mPointer, JS::GCThingTraceKind(pi->mPointer));
  2626. if (GCThingIsGrayCCThing(ptr)) {
  2627. continue;
  2628. }
  2629. } else if (pi->mParticipant == zoneParticipant) {
  2630. JS::Zone* zone = static_cast<JS::Zone*>(pi->mPointer);
  2631. if (js::ZoneGlobalsAreAllGray(zone)) {
  2632. continue;
  2633. }
  2634. } else {
  2635. MOZ_ASSERT(false, "Non-JS thing with 0 refcount? Treating as live.");
  2636. }
  2637. } else if (!pi->mParticipant && pi->WasTraversed()) {
  2638. // Dead traversed refcounted objects:
  2639. // If the object was traversed, it must have been alive at the start of
  2640. // the CC, and thus had a positive refcount. It is dead now, so its
  2641. // refcount must have decreased at some point during the CC. Therefore,
  2642. // it would be in the purple buffer if it wasn't dead, so treat it as an
  2643. // incremental root.
  2644. //
  2645. // This should not cause leaks because as the object died it should have
  2646. // released anything it held onto, which will add them to the purple
  2647. // buffer, which will cause them to be considered in the next CC.
  2648. } else {
  2649. continue;
  2650. }
  2651. // At this point, pi must be an incremental root.
  2652. // If there's a listener, tell it about this root. We don't bother with the
  2653. // optimization of skipping the Walk() if pi is black: it will just return
  2654. // without doing anything and there's no need to make this case faster.
  2655. if (MOZ_UNLIKELY(hasLogger) && pi->mPointer) {
  2656. // Dead objects aren't logged. See bug 1031370.
  2657. mLogger->NoteIncrementalRoot((uint64_t)pi->mPointer);
  2658. }
  2659. FloodBlackNode(mWhiteNodeCount, failed, pi);
  2660. }
  2661. timeLog.Checkpoint("ScanIncrementalRoots::fix nodes");
  2662. if (failed) {
  2663. NS_ASSERTION(false, "Ran out of memory in ScanIncrementalRoots");
  2664. }
  2665. }
  2666. // Mark nodes white and make sure their refcounts are ok.
  2667. // No nodes are marked black during this pass to ensure that refcount
  2668. // checking is run on all nodes not marked black by ScanIncrementalRoots.
  2669. void
  2670. nsCycleCollector::ScanWhiteNodes(bool aFullySynchGraphBuild)
  2671. {
  2672. NodePool::Enumerator nodeEnum(mGraph.mNodes);
  2673. while (!nodeEnum.IsDone()) {
  2674. PtrInfo* pi = nodeEnum.GetNext();
  2675. if (pi->mColor == black) {
  2676. // Incremental roots can be in a nonsensical state, so don't
  2677. // check them. This will miss checking nodes that are merely
  2678. // reachable from incremental roots.
  2679. MOZ_ASSERT(!aFullySynchGraphBuild,
  2680. "In a synch CC, no nodes should be marked black early on.");
  2681. continue;
  2682. }
  2683. MOZ_ASSERT(pi->mColor == grey);
  2684. if (!pi->WasTraversed()) {
  2685. // This node was deleted before it was traversed, so there's no reason
  2686. // to look at it.
  2687. MOZ_ASSERT(!pi->mParticipant, "Live nodes should all have been traversed");
  2688. continue;
  2689. }
  2690. if (pi->mInternalRefs == pi->mRefCount || pi->IsGrayJS()) {
  2691. pi->mColor = white;
  2692. ++mWhiteNodeCount;
  2693. continue;
  2694. }
  2695. if (pi->mInternalRefs > pi->mRefCount) {
  2696. MOZ_CRASH();
  2697. }
  2698. // This node will get marked black in the next pass.
  2699. }
  2700. }
  2701. // Any remaining grey nodes that haven't already been deleted must be alive,
  2702. // so mark them and their children black. Any nodes that are black must have
  2703. // already had their children marked black, so there's no need to look at them
  2704. // again. This pass may turn some white nodes to black.
  2705. void
  2706. nsCycleCollector::ScanBlackNodes()
  2707. {
  2708. bool failed = false;
  2709. NodePool::Enumerator nodeEnum(mGraph.mNodes);
  2710. while (!nodeEnum.IsDone()) {
  2711. PtrInfo* pi = nodeEnum.GetNext();
  2712. if (pi->mColor == grey && pi->WasTraversed()) {
  2713. FloodBlackNode(mWhiteNodeCount, failed, pi);
  2714. }
  2715. }
  2716. if (failed) {
  2717. NS_ASSERTION(false, "Ran out of memory in ScanBlackNodes");
  2718. }
  2719. }
  2720. void
  2721. nsCycleCollector::ScanRoots(bool aFullySynchGraphBuild)
  2722. {
  2723. JS::AutoAssertNoGC nogc;
  2724. AutoRestore<bool> ar(mScanInProgress);
  2725. MOZ_RELEASE_ASSERT(!mScanInProgress);
  2726. mScanInProgress = true;
  2727. mWhiteNodeCount = 0;
  2728. MOZ_ASSERT(mIncrementalPhase == ScanAndCollectWhitePhase);
  2729. JS::AutoEnterCycleCollection autocc(Context()->Context());
  2730. if (!aFullySynchGraphBuild) {
  2731. ScanIncrementalRoots();
  2732. }
  2733. TimeLog timeLog;
  2734. ScanWhiteNodes(aFullySynchGraphBuild);
  2735. timeLog.Checkpoint("ScanRoots::ScanWhiteNodes");
  2736. ScanBlackNodes();
  2737. timeLog.Checkpoint("ScanRoots::ScanBlackNodes");
  2738. // Scanning weak maps must be done last.
  2739. ScanWeakMaps();
  2740. timeLog.Checkpoint("ScanRoots::ScanWeakMaps");
  2741. if (mLogger) {
  2742. mLogger->BeginResults();
  2743. NodePool::Enumerator etor(mGraph.mNodes);
  2744. while (!etor.IsDone()) {
  2745. PtrInfo* pi = etor.GetNext();
  2746. if (!pi->WasTraversed()) {
  2747. continue;
  2748. }
  2749. switch (pi->mColor) {
  2750. case black:
  2751. if (!pi->IsGrayJS() && !pi->IsBlackJS() &&
  2752. pi->mInternalRefs != pi->mRefCount) {
  2753. mLogger->DescribeRoot((uint64_t)pi->mPointer,
  2754. pi->mInternalRefs);
  2755. }
  2756. break;
  2757. case white:
  2758. mLogger->DescribeGarbage((uint64_t)pi->mPointer);
  2759. break;
  2760. case grey:
  2761. MOZ_ASSERT(false, "All traversed objects should be black or white");
  2762. break;
  2763. }
  2764. }
  2765. mLogger->End();
  2766. mLogger = nullptr;
  2767. timeLog.Checkpoint("ScanRoots::listener");
  2768. }
  2769. }
  2770. ////////////////////////////////////////////////////////////////////////
  2771. // Bacon & Rajan's |CollectWhite| routine, somewhat modified.
  2772. ////////////////////////////////////////////////////////////////////////
  2773. bool
  2774. nsCycleCollector::CollectWhite()
  2775. {
  2776. // Explanation of "somewhat modified": we have no way to collect the
  2777. // set of whites "all at once", we have to ask each of them to drop
  2778. // their outgoing links and assume this will cause the garbage cycle
  2779. // to *mostly* self-destruct (except for the reference we continue
  2780. // to hold).
  2781. //
  2782. // To do this "safely" we must make sure that the white nodes we're
  2783. // operating on are stable for the duration of our operation. So we
  2784. // make 3 sets of calls to language runtimes:
  2785. //
  2786. // - Root(whites), which should pin the whites in memory.
  2787. // - Unlink(whites), which drops outgoing links on each white.
  2788. // - Unroot(whites), which returns the whites to normal GC.
  2789. // Segments are 4 KiB on 32-bit and 8 KiB on 64-bit.
  2790. static const size_t kSegmentSize = sizeof(void*) * 1024;
  2791. SegmentedVector<PtrInfo*, kSegmentSize, InfallibleAllocPolicy>
  2792. whiteNodes(kSegmentSize);
  2793. TimeLog timeLog;
  2794. MOZ_ASSERT(mIncrementalPhase == ScanAndCollectWhitePhase);
  2795. uint32_t numWhiteNodes = 0;
  2796. uint32_t numWhiteGCed = 0;
  2797. uint32_t numWhiteJSZones = 0;
  2798. {
  2799. JS::AutoAssertNoGC nogc;
  2800. bool hasJSContext = !!mJSContext;
  2801. nsCycleCollectionParticipant* zoneParticipant =
  2802. hasJSContext ? mJSContext->ZoneParticipant() : nullptr;
  2803. NodePool::Enumerator etor(mGraph.mNodes);
  2804. while (!etor.IsDone()) {
  2805. PtrInfo* pinfo = etor.GetNext();
  2806. if (pinfo->mColor == white && pinfo->mParticipant) {
  2807. if (pinfo->IsGrayJS()) {
  2808. MOZ_ASSERT(mJSContext);
  2809. ++numWhiteGCed;
  2810. JS::Zone* zone;
  2811. if (MOZ_UNLIKELY(pinfo->mParticipant == zoneParticipant)) {
  2812. ++numWhiteJSZones;
  2813. zone = static_cast<JS::Zone*>(pinfo->mPointer);
  2814. } else {
  2815. JS::GCCellPtr ptr(pinfo->mPointer, JS::GCThingTraceKind(pinfo->mPointer));
  2816. zone = JS::GetTenuredGCThingZone(ptr);
  2817. }
  2818. mJSContext->AddZoneWaitingForGC(zone);
  2819. } else {
  2820. whiteNodes.InfallibleAppend(pinfo);
  2821. pinfo->mParticipant->Root(pinfo->mPointer);
  2822. ++numWhiteNodes;
  2823. }
  2824. }
  2825. }
  2826. }
  2827. mResults.mFreedRefCounted += numWhiteNodes;
  2828. mResults.mFreedGCed += numWhiteGCed;
  2829. mResults.mFreedJSZones += numWhiteJSZones;
  2830. timeLog.Checkpoint("CollectWhite::Root");
  2831. if (mBeforeUnlinkCB) {
  2832. mBeforeUnlinkCB();
  2833. timeLog.Checkpoint("CollectWhite::BeforeUnlinkCB");
  2834. }
  2835. // Unlink() can trigger a GC, so do not touch any JS or anything
  2836. // else not in whiteNodes after here.
  2837. for (auto iter = whiteNodes.Iter(); !iter.Done(); iter.Next()) {
  2838. PtrInfo* pinfo = iter.Get();
  2839. MOZ_ASSERT(pinfo->mParticipant,
  2840. "Unlink shouldn't see objects removed from graph.");
  2841. pinfo->mParticipant->Unlink(pinfo->mPointer);
  2842. #ifdef DEBUG
  2843. if (mJSContext) {
  2844. mJSContext->AssertNoObjectsToTrace(pinfo->mPointer);
  2845. }
  2846. #endif
  2847. }
  2848. timeLog.Checkpoint("CollectWhite::Unlink");
  2849. JS::AutoAssertNoGC nogc;
  2850. for (auto iter = whiteNodes.Iter(); !iter.Done(); iter.Next()) {
  2851. PtrInfo* pinfo = iter.Get();
  2852. MOZ_ASSERT(pinfo->mParticipant,
  2853. "Unroot shouldn't see objects removed from graph.");
  2854. pinfo->mParticipant->Unroot(pinfo->mPointer);
  2855. }
  2856. timeLog.Checkpoint("CollectWhite::Unroot");
  2857. nsCycleCollector_dispatchDeferredDeletion(false, true);
  2858. timeLog.Checkpoint("CollectWhite::dispatchDeferredDeletion");
  2859. mIncrementalPhase = CleanupPhase;
  2860. return numWhiteNodes > 0 || numWhiteGCed > 0 || numWhiteJSZones > 0;
  2861. }
  2862. ////////////////////////
  2863. // Memory reporting
  2864. ////////////////////////
  2865. MOZ_DEFINE_MALLOC_SIZE_OF(CycleCollectorMallocSizeOf)
  2866. NS_IMETHODIMP
  2867. nsCycleCollector::CollectReports(nsIHandleReportCallback* aHandleReport,
  2868. nsISupports* aData, bool aAnonymize)
  2869. {
  2870. size_t objectSize, graphSize, purpleBufferSize;
  2871. SizeOfIncludingThis(CycleCollectorMallocSizeOf,
  2872. &objectSize, &graphSize,
  2873. &purpleBufferSize);
  2874. if (objectSize > 0) {
  2875. MOZ_COLLECT_REPORT(
  2876. "explicit/cycle-collector/collector-object", KIND_HEAP, UNITS_BYTES,
  2877. objectSize,
  2878. "Memory used for the cycle collector object itself.");
  2879. }
  2880. if (graphSize > 0) {
  2881. MOZ_COLLECT_REPORT(
  2882. "explicit/cycle-collector/graph", KIND_HEAP, UNITS_BYTES,
  2883. graphSize,
  2884. "Memory used for the cycle collector's graph. This should be zero when "
  2885. "the collector is idle.");
  2886. }
  2887. if (purpleBufferSize > 0) {
  2888. MOZ_COLLECT_REPORT(
  2889. "explicit/cycle-collector/purple-buffer", KIND_HEAP, UNITS_BYTES,
  2890. purpleBufferSize,
  2891. "Memory used for the cycle collector's purple buffer.");
  2892. }
  2893. return NS_OK;
  2894. };
  2895. ////////////////////////////////////////////////////////////////////////
  2896. // Collector implementation
  2897. ////////////////////////////////////////////////////////////////////////
  2898. nsCycleCollector::nsCycleCollector() :
  2899. mActivelyCollecting(false),
  2900. mFreeingSnowWhite(false),
  2901. mScanInProgress(false),
  2902. mJSContext(nullptr),
  2903. mIncrementalPhase(IdlePhase),
  2904. #ifdef DEBUG
  2905. mThread(NS_GetCurrentThread()),
  2906. #endif
  2907. mWhiteNodeCount(0),
  2908. mBeforeUnlinkCB(nullptr),
  2909. mForgetSkippableCB(nullptr),
  2910. mUnmergedNeeded(0),
  2911. mMergedInARow(0)
  2912. {
  2913. }
  2914. nsCycleCollector::~nsCycleCollector()
  2915. {
  2916. UnregisterWeakMemoryReporter(this);
  2917. }
  2918. void
  2919. nsCycleCollector::RegisterJSContext(CycleCollectedJSContext* aJSContext)
  2920. {
  2921. MOZ_RELEASE_ASSERT(!mJSContext, "Multiple registrations of JS context in cycle collector");
  2922. mJSContext = aJSContext;
  2923. if (!NS_IsMainThread()) {
  2924. return;
  2925. }
  2926. // We can't register as a reporter in nsCycleCollector() because that runs
  2927. // before the memory reporter manager is initialized. So we do it here
  2928. // instead.
  2929. RegisterWeakMemoryReporter(this);
  2930. }
  2931. void
  2932. nsCycleCollector::ForgetJSContext()
  2933. {
  2934. MOZ_RELEASE_ASSERT(mJSContext, "Forgetting JS context in cycle collector before a JS context was registered");
  2935. mJSContext = nullptr;
  2936. }
  2937. #ifdef DEBUG
  2938. static bool
  2939. HasParticipant(void* aPtr, nsCycleCollectionParticipant* aParti)
  2940. {
  2941. if (aParti) {
  2942. return true;
  2943. }
  2944. nsXPCOMCycleCollectionParticipant* xcp;
  2945. ToParticipant(static_cast<nsISupports*>(aPtr), &xcp);
  2946. return xcp != nullptr;
  2947. }
  2948. #endif
  2949. MOZ_ALWAYS_INLINE void
  2950. nsCycleCollector::Suspect(void* aPtr, nsCycleCollectionParticipant* aParti,
  2951. nsCycleCollectingAutoRefCnt* aRefCnt)
  2952. {
  2953. CheckThreadSafety();
  2954. // Don't call AddRef or Release of a CCed object in a Traverse() method.
  2955. MOZ_ASSERT(!mScanInProgress, "Attempted to call Suspect() while a scan was in progress");
  2956. if (MOZ_UNLIKELY(mScanInProgress)) {
  2957. return;
  2958. }
  2959. MOZ_ASSERT(aPtr, "Don't suspect null pointers");
  2960. MOZ_ASSERT(HasParticipant(aPtr, aParti),
  2961. "Suspected nsISupports pointer must QI to nsXPCOMCycleCollectionParticipant");
  2962. mPurpleBuf.Put(aPtr, aParti, aRefCnt);
  2963. }
  2964. void
  2965. nsCycleCollector::CheckThreadSafety()
  2966. {
  2967. #ifdef DEBUG
  2968. nsIThread* currentThread = NS_GetCurrentThread();
  2969. // XXXkhuey we can be called so late in shutdown that NS_GetCurrentThread
  2970. // returns null (after the thread manager has shut down)
  2971. MOZ_ASSERT(mThread == currentThread || !currentThread);
  2972. #endif
  2973. }
  2974. // The cycle collector uses the mark bitmap to discover what JS objects
  2975. // were reachable only from XPConnect roots that might participate in
  2976. // cycles. We ask the JS context whether we need to force a GC before
  2977. // this CC. It returns true on startup (before the mark bits have been set),
  2978. // and also when UnmarkGray has run out of stack. We also force GCs on shut
  2979. // down to collect cycles involving both DOM and JS.
  2980. void
  2981. nsCycleCollector::FixGrayBits(bool aForceGC, TimeLog& aTimeLog)
  2982. {
  2983. CheckThreadSafety();
  2984. if (!mJSContext) {
  2985. return;
  2986. }
  2987. if (!aForceGC) {
  2988. mJSContext->FixWeakMappingGrayBits();
  2989. aTimeLog.Checkpoint("FixWeakMappingGrayBits");
  2990. bool needGC = !mJSContext->AreGCGrayBitsValid();
  2991. if (!needGC) {
  2992. return;
  2993. }
  2994. mResults.mForcedGC = true;
  2995. }
  2996. mJSContext->GarbageCollect(aForceGC ? JS::gcreason::SHUTDOWN_CC :
  2997. JS::gcreason::CC_FORCED);
  2998. aTimeLog.Checkpoint("FixGrayBits GC");
  2999. }
  3000. bool
  3001. nsCycleCollector::IsIncrementalGCInProgress()
  3002. {
  3003. return mJSContext && JS::IsIncrementalGCInProgress(mJSContext->Context());
  3004. }
  3005. void
  3006. nsCycleCollector::FinishAnyIncrementalGCInProgress()
  3007. {
  3008. if (IsIncrementalGCInProgress()) {
  3009. NS_WARNING("Finishing incremental GC in progress during CC");
  3010. JS::PrepareForIncrementalGC(mJSContext->Context());
  3011. JS::FinishIncrementalGC(mJSContext->Context(), JS::gcreason::CC_FORCED);
  3012. }
  3013. }
  3014. void
  3015. nsCycleCollector::CleanupAfterCollection()
  3016. {
  3017. TimeLog timeLog;
  3018. MOZ_ASSERT(mIncrementalPhase == CleanupPhase);
  3019. mGraph.Clear();
  3020. timeLog.Checkpoint("CleanupAfterCollection::mGraph.Clear()");
  3021. #ifdef COLLECT_TIME_DEBUG
  3022. uint32_t interval =
  3023. (uint32_t)((TimeStamp::Now() - mCollectionStart).ToMilliseconds());
  3024. printf("cc: total cycle collector time was %ums in %u slices\n", interval,
  3025. mResults.mNumSlices);
  3026. printf("cc: visited %u ref counted and %u GCed objects, freed %d ref counted and %d GCed objects",
  3027. mResults.mVisitedRefCounted, mResults.mVisitedGCed,
  3028. mResults.mFreedRefCounted, mResults.mFreedGCed);
  3029. uint32_t numVisited = mResults.mVisitedRefCounted + mResults.mVisitedGCed;
  3030. if (numVisited > 1000) {
  3031. uint32_t numFreed = mResults.mFreedRefCounted + mResults.mFreedGCed;
  3032. printf(" (%d%%)", 100 * numFreed / numVisited);
  3033. }
  3034. printf(".\ncc: \n");
  3035. #endif
  3036. if (mJSContext) {
  3037. mJSContext->FinalizeDeferredThings(mResults.mAnyManual
  3038. ? CycleCollectedJSContext::FinalizeNow
  3039. : CycleCollectedJSContext::FinalizeIncrementally);
  3040. mJSContext->EndCycleCollectionCallback(mResults);
  3041. timeLog.Checkpoint("CleanupAfterCollection::EndCycleCollectionCallback()");
  3042. }
  3043. mIncrementalPhase = IdlePhase;
  3044. }
  3045. void
  3046. nsCycleCollector::ShutdownCollect()
  3047. {
  3048. FinishAnyIncrementalGCInProgress();
  3049. SliceBudget unlimitedBudget = SliceBudget::unlimited();
  3050. uint32_t i;
  3051. for (i = 0; i < DEFAULT_SHUTDOWN_COLLECTIONS; ++i) {
  3052. if (!Collect(ShutdownCC, unlimitedBudget, nullptr)) {
  3053. break;
  3054. }
  3055. }
  3056. NS_WARNING_ASSERTION(i < NORMAL_SHUTDOWN_COLLECTIONS, "Extra shutdown CC");
  3057. }
  3058. static void
  3059. PrintPhase(const char* aPhase)
  3060. {
  3061. #ifdef DEBUG_PHASES
  3062. printf("cc: begin %s on %s\n", aPhase,
  3063. NS_IsMainThread() ? "mainthread" : "worker");
  3064. #endif
  3065. }
  3066. bool
  3067. nsCycleCollector::Collect(ccType aCCType,
  3068. SliceBudget& aBudget,
  3069. nsICycleCollectorListener* aManualListener,
  3070. bool aPreferShorterSlices)
  3071. {
  3072. CheckThreadSafety();
  3073. // This can legitimately happen in a few cases. See bug 383651.
  3074. if (mActivelyCollecting || mFreeingSnowWhite) {
  3075. return false;
  3076. }
  3077. mActivelyCollecting = true;
  3078. MOZ_ASSERT(!IsIncrementalGCInProgress());
  3079. mozilla::Maybe<mozilla::AutoGlobalTimelineMarker> marker;
  3080. if (NS_IsMainThread()) {
  3081. marker.emplace("nsCycleCollector::Collect", MarkerStackRequest::NO_STACK);
  3082. }
  3083. bool startedIdle = IsIdle();
  3084. bool collectedAny = false;
  3085. // If the CC started idle, it will call BeginCollection, which
  3086. // will do FreeSnowWhite, so it doesn't need to be done here.
  3087. if (!startedIdle) {
  3088. TimeLog timeLog;
  3089. FreeSnowWhite(true);
  3090. timeLog.Checkpoint("Collect::FreeSnowWhite");
  3091. }
  3092. if (aCCType != SliceCC) {
  3093. mResults.mAnyManual = true;
  3094. }
  3095. ++mResults.mNumSlices;
  3096. bool continueSlice = aBudget.isUnlimited() || !aPreferShorterSlices;
  3097. do {
  3098. switch (mIncrementalPhase) {
  3099. case IdlePhase:
  3100. PrintPhase("BeginCollection");
  3101. BeginCollection(aCCType, aManualListener);
  3102. break;
  3103. case GraphBuildingPhase:
  3104. PrintPhase("MarkRoots");
  3105. MarkRoots(aBudget);
  3106. // Only continue this slice if we're running synchronously or the
  3107. // next phase will probably be short, to reduce the max pause for this
  3108. // collection.
  3109. // (There's no need to check if we've finished graph building, because
  3110. // if we haven't, we've already exceeded our budget, and will finish
  3111. // this slice anyways.)
  3112. continueSlice = aBudget.isUnlimited() ||
  3113. (mResults.mNumSlices < 3 && !aPreferShorterSlices);
  3114. break;
  3115. case ScanAndCollectWhitePhase:
  3116. // We do ScanRoots and CollectWhite in a single slice to ensure
  3117. // that we won't unlink a live object if a weak reference is
  3118. // promoted to a strong reference after ScanRoots has finished.
  3119. // See bug 926533.
  3120. PrintPhase("ScanRoots");
  3121. ScanRoots(startedIdle);
  3122. PrintPhase("CollectWhite");
  3123. collectedAny = CollectWhite();
  3124. break;
  3125. case CleanupPhase:
  3126. PrintPhase("CleanupAfterCollection");
  3127. CleanupAfterCollection();
  3128. continueSlice = false;
  3129. break;
  3130. }
  3131. if (continueSlice) {
  3132. // Force SliceBudget::isOverBudget to check the time.
  3133. aBudget.step(SliceBudget::CounterReset);
  3134. continueSlice = !aBudget.isOverBudget();
  3135. }
  3136. } while (continueSlice);
  3137. // Clear mActivelyCollecting here to ensure that a recursive call to
  3138. // Collect() does something.
  3139. mActivelyCollecting = false;
  3140. if (aCCType != SliceCC && !startedIdle) {
  3141. // We were in the middle of an incremental CC (using its own listener).
  3142. // Somebody has forced a CC, so after having finished out the current CC,
  3143. // run the CC again using the new listener.
  3144. MOZ_ASSERT(IsIdle());
  3145. if (Collect(aCCType, aBudget, aManualListener)) {
  3146. collectedAny = true;
  3147. }
  3148. }
  3149. MOZ_ASSERT_IF(aCCType != SliceCC, IsIdle());
  3150. return collectedAny;
  3151. }
  3152. // Any JS objects we have in the graph could die when we GC, but we
  3153. // don't want to abandon the current CC, because the graph contains
  3154. // information about purple roots. So we synchronously finish off
  3155. // the current CC.
  3156. void
  3157. nsCycleCollector::PrepareForGarbageCollection()
  3158. {
  3159. if (IsIdle()) {
  3160. MOZ_ASSERT(mGraph.IsEmpty(), "Non-empty graph when idle");
  3161. MOZ_ASSERT(!mBuilder, "Non-null builder when idle");
  3162. if (mJSPurpleBuffer) {
  3163. mJSPurpleBuffer->Destroy();
  3164. }
  3165. return;
  3166. }
  3167. FinishAnyCurrentCollection();
  3168. }
  3169. void
  3170. nsCycleCollector::FinishAnyCurrentCollection()
  3171. {
  3172. if (IsIdle()) {
  3173. return;
  3174. }
  3175. SliceBudget unlimitedBudget = SliceBudget::unlimited();
  3176. PrintPhase("FinishAnyCurrentCollection");
  3177. // Use SliceCC because we only want to finish the CC in progress.
  3178. Collect(SliceCC, unlimitedBudget, nullptr);
  3179. // It is only okay for Collect() to have failed to finish the
  3180. // current CC if we're reentering the CC at some point past
  3181. // graph building. We need to be past the point where the CC will
  3182. // look at JS objects so that it is safe to GC.
  3183. MOZ_ASSERT(IsIdle() ||
  3184. (mActivelyCollecting && mIncrementalPhase != GraphBuildingPhase),
  3185. "Reentered CC during graph building");
  3186. }
  3187. // Don't merge too many times in a row, and do at least a minimum
  3188. // number of unmerged CCs in a row.
  3189. static const uint32_t kMinConsecutiveUnmerged = 3;
  3190. static const uint32_t kMaxConsecutiveMerged = 3;
  3191. bool
  3192. nsCycleCollector::ShouldMergeZones(ccType aCCType)
  3193. {
  3194. if (!mJSContext) {
  3195. return false;
  3196. }
  3197. MOZ_ASSERT(mUnmergedNeeded <= kMinConsecutiveUnmerged);
  3198. MOZ_ASSERT(mMergedInARow <= kMaxConsecutiveMerged);
  3199. if (mMergedInARow == kMaxConsecutiveMerged) {
  3200. MOZ_ASSERT(mUnmergedNeeded == 0);
  3201. mUnmergedNeeded = kMinConsecutiveUnmerged;
  3202. }
  3203. if (mUnmergedNeeded > 0) {
  3204. mUnmergedNeeded--;
  3205. mMergedInARow = 0;
  3206. return false;
  3207. }
  3208. if (aCCType == SliceCC && mJSContext->UsefulToMergeZones()) {
  3209. mMergedInARow++;
  3210. return true;
  3211. } else {
  3212. mMergedInARow = 0;
  3213. return false;
  3214. }
  3215. }
  3216. void
  3217. nsCycleCollector::BeginCollection(ccType aCCType,
  3218. nsICycleCollectorListener* aManualListener)
  3219. {
  3220. TimeLog timeLog;
  3221. MOZ_ASSERT(IsIdle());
  3222. mCollectionStart = TimeStamp::Now();
  3223. if (mJSContext) {
  3224. mJSContext->BeginCycleCollectionCallback();
  3225. timeLog.Checkpoint("BeginCycleCollectionCallback()");
  3226. }
  3227. bool isShutdown = (aCCType == ShutdownCC);
  3228. // Set up the listener for this CC.
  3229. MOZ_ASSERT_IF(isShutdown, !aManualListener);
  3230. MOZ_ASSERT(!mLogger, "Forgot to clear a previous listener?");
  3231. if (aManualListener) {
  3232. aManualListener->AsLogger(getter_AddRefs(mLogger));
  3233. }
  3234. aManualListener = nullptr;
  3235. if (!mLogger && mParams.LogThisCC(isShutdown)) {
  3236. mLogger = new nsCycleCollectorLogger();
  3237. if (mParams.AllTracesThisCC(isShutdown)) {
  3238. mLogger->SetAllTraces();
  3239. }
  3240. }
  3241. // On a WantAllTraces CC, force a synchronous global GC to prevent
  3242. // hijinks from ForgetSkippable and compartmental GCs.
  3243. bool forceGC = isShutdown || (mLogger && mLogger->IsAllTraces());
  3244. // BeginCycleCollectionCallback() might have started an IGC, and we need
  3245. // to finish it before we run FixGrayBits.
  3246. FinishAnyIncrementalGCInProgress();
  3247. timeLog.Checkpoint("Pre-FixGrayBits finish IGC");
  3248. FixGrayBits(forceGC, timeLog);
  3249. FreeSnowWhite(true);
  3250. timeLog.Checkpoint("BeginCollection FreeSnowWhite");
  3251. if (mLogger && NS_FAILED(mLogger->Begin())) {
  3252. mLogger = nullptr;
  3253. }
  3254. // FreeSnowWhite could potentially have started an IGC, which we need
  3255. // to finish before we look at any JS roots.
  3256. FinishAnyIncrementalGCInProgress();
  3257. timeLog.Checkpoint("Post-FreeSnowWhite finish IGC");
  3258. // Set up the data structures for building the graph.
  3259. JS::AutoAssertNoGC nogc;
  3260. JS::AutoEnterCycleCollection autocc(mJSContext->Context());
  3261. mGraph.Init();
  3262. mResults.Init();
  3263. mResults.mAnyManual = (aCCType != SliceCC);
  3264. bool mergeZones = ShouldMergeZones(aCCType);
  3265. mResults.mMergedZones = mergeZones;
  3266. MOZ_ASSERT(!mBuilder, "Forgot to clear mBuilder");
  3267. mBuilder = new CCGraphBuilder(mGraph, mResults, mJSContext, mLogger,
  3268. mergeZones);
  3269. timeLog.Checkpoint("BeginCollection prepare graph builder");
  3270. if (mJSContext) {
  3271. mJSContext->TraverseRoots(*mBuilder);
  3272. timeLog.Checkpoint("mJSContext->TraverseRoots()");
  3273. }
  3274. AutoRestore<bool> ar(mScanInProgress);
  3275. MOZ_RELEASE_ASSERT(!mScanInProgress);
  3276. mScanInProgress = true;
  3277. mPurpleBuf.SelectPointers(*mBuilder);
  3278. timeLog.Checkpoint("SelectPointers()");
  3279. mBuilder->DoneAddingRoots();
  3280. mIncrementalPhase = GraphBuildingPhase;
  3281. }
  3282. uint32_t
  3283. nsCycleCollector::SuspectedCount()
  3284. {
  3285. CheckThreadSafety();
  3286. return mPurpleBuf.Count();
  3287. }
  3288. void
  3289. nsCycleCollector::Shutdown(bool aDoCollect)
  3290. {
  3291. CheckThreadSafety();
  3292. // Always delete snow white objects.
  3293. FreeSnowWhite(true);
  3294. if (aDoCollect) {
  3295. ShutdownCollect();
  3296. }
  3297. }
  3298. void
  3299. nsCycleCollector::RemoveObjectFromGraph(void* aObj)
  3300. {
  3301. if (IsIdle()) {
  3302. return;
  3303. }
  3304. mGraph.RemoveObjectFromMap(aObj);
  3305. }
  3306. void
  3307. nsCycleCollector::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf,
  3308. size_t* aObjectSize,
  3309. size_t* aGraphSize,
  3310. size_t* aPurpleBufferSize) const
  3311. {
  3312. *aObjectSize = aMallocSizeOf(this);
  3313. *aGraphSize = mGraph.SizeOfExcludingThis(aMallocSizeOf);
  3314. *aPurpleBufferSize = mPurpleBuf.SizeOfExcludingThis(aMallocSizeOf);
  3315. // These fields are deliberately not measured:
  3316. // - mJSContext: because it's non-owning and measured by JS reporters.
  3317. // - mParams: because it only contains scalars.
  3318. }
  3319. JSPurpleBuffer*
  3320. nsCycleCollector::GetJSPurpleBuffer()
  3321. {
  3322. if (!mJSPurpleBuffer) {
  3323. // The Release call here confuses the GC analysis.
  3324. JS::AutoSuppressGCAnalysis nogc;
  3325. // JSPurpleBuffer keeps itself alive, but we need to create it in such way
  3326. // that it ends up in the normal purple buffer. That happens when
  3327. // nsRefPtr goes out of the scope and calls Release.
  3328. RefPtr<JSPurpleBuffer> pb = new JSPurpleBuffer(mJSPurpleBuffer);
  3329. }
  3330. return mJSPurpleBuffer;
  3331. }
  3332. ////////////////////////////////////////////////////////////////////////
  3333. // Module public API (exported in nsCycleCollector.h)
  3334. // Just functions that redirect into the singleton, once it's built.
  3335. ////////////////////////////////////////////////////////////////////////
  3336. void
  3337. nsCycleCollector_registerJSContext(CycleCollectedJSContext* aCx)
  3338. {
  3339. CollectorData* data = sCollectorData.get();
  3340. // We should have started the cycle collector by now.
  3341. MOZ_ASSERT(data);
  3342. MOZ_ASSERT(data->mCollector);
  3343. // But we shouldn't already have a context.
  3344. MOZ_ASSERT(!data->mContext);
  3345. data->mContext = aCx;
  3346. data->mCollector->RegisterJSContext(aCx);
  3347. }
  3348. void
  3349. nsCycleCollector_forgetJSContext()
  3350. {
  3351. CollectorData* data = sCollectorData.get();
  3352. // We should have started the cycle collector by now.
  3353. MOZ_ASSERT(data);
  3354. // And we shouldn't have already forgotten our context.
  3355. MOZ_ASSERT(data->mContext);
  3356. // But it may have shutdown already.
  3357. if (data->mCollector) {
  3358. data->mCollector->ForgetJSContext();
  3359. data->mContext = nullptr;
  3360. } else {
  3361. data->mContext = nullptr;
  3362. delete data;
  3363. sCollectorData.set(nullptr);
  3364. }
  3365. }
  3366. /* static */ CycleCollectedJSContext*
  3367. CycleCollectedJSContext::Get()
  3368. {
  3369. CollectorData* data = sCollectorData.get();
  3370. if (data) {
  3371. return data->mContext;
  3372. }
  3373. return nullptr;
  3374. }
  3375. MOZ_NEVER_INLINE static void
  3376. SuspectAfterShutdown(void* aPtr, nsCycleCollectionParticipant* aCp,
  3377. nsCycleCollectingAutoRefCnt* aRefCnt,
  3378. bool* aShouldDelete)
  3379. {
  3380. if (aRefCnt->get() == 0) {
  3381. if (!aShouldDelete) {
  3382. // The CC is shut down, so we can't be in the middle of an ICC.
  3383. CanonicalizeParticipant(&aPtr, &aCp);
  3384. aRefCnt->stabilizeForDeletion();
  3385. aCp->DeleteCycleCollectable(aPtr);
  3386. } else {
  3387. *aShouldDelete = true;
  3388. }
  3389. } else {
  3390. // Make sure we'll get called again.
  3391. aRefCnt->RemoveFromPurpleBuffer();
  3392. }
  3393. }
  3394. void
  3395. NS_CycleCollectorSuspect3(void* aPtr, nsCycleCollectionParticipant* aCp,
  3396. nsCycleCollectingAutoRefCnt* aRefCnt,
  3397. bool* aShouldDelete)
  3398. {
  3399. CollectorData* data = sCollectorData.get();
  3400. // We should have started the cycle collector by now.
  3401. MOZ_ASSERT(data);
  3402. if (MOZ_LIKELY(data->mCollector)) {
  3403. data->mCollector->Suspect(aPtr, aCp, aRefCnt);
  3404. return;
  3405. }
  3406. SuspectAfterShutdown(aPtr, aCp, aRefCnt, aShouldDelete);
  3407. }
  3408. uint32_t
  3409. nsCycleCollector_suspectedCount()
  3410. {
  3411. CollectorData* data = sCollectorData.get();
  3412. // We should have started the cycle collector by now.
  3413. MOZ_ASSERT(data);
  3414. if (!data->mCollector) {
  3415. return 0;
  3416. }
  3417. return data->mCollector->SuspectedCount();
  3418. }
  3419. bool
  3420. nsCycleCollector_init()
  3421. {
  3422. #ifdef DEBUG
  3423. static bool sInitialized;
  3424. MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!");
  3425. MOZ_ASSERT(!sInitialized, "Called twice!?");
  3426. sInitialized = true;
  3427. #endif
  3428. return sCollectorData.init();
  3429. }
  3430. void
  3431. nsCycleCollector_startup()
  3432. {
  3433. if (sCollectorData.get()) {
  3434. MOZ_CRASH();
  3435. }
  3436. CollectorData* data = new CollectorData;
  3437. data->mCollector = new nsCycleCollector();
  3438. data->mContext = nullptr;
  3439. sCollectorData.set(data);
  3440. }
  3441. void
  3442. nsCycleCollector_setBeforeUnlinkCallback(CC_BeforeUnlinkCallback aCB)
  3443. {
  3444. CollectorData* data = sCollectorData.get();
  3445. // We should have started the cycle collector by now.
  3446. MOZ_ASSERT(data);
  3447. MOZ_ASSERT(data->mCollector);
  3448. data->mCollector->SetBeforeUnlinkCallback(aCB);
  3449. }
  3450. void
  3451. nsCycleCollector_setForgetSkippableCallback(CC_ForgetSkippableCallback aCB)
  3452. {
  3453. CollectorData* data = sCollectorData.get();
  3454. // We should have started the cycle collector by now.
  3455. MOZ_ASSERT(data);
  3456. MOZ_ASSERT(data->mCollector);
  3457. data->mCollector->SetForgetSkippableCallback(aCB);
  3458. }
  3459. void
  3460. nsCycleCollector_forgetSkippable(bool aRemoveChildlessNodes,
  3461. bool aAsyncSnowWhiteFreeing)
  3462. {
  3463. CollectorData* data = sCollectorData.get();
  3464. // We should have started the cycle collector by now.
  3465. MOZ_ASSERT(data);
  3466. MOZ_ASSERT(data->mCollector);
  3467. PROFILER_LABEL("nsCycleCollector", "forgetSkippable",
  3468. js::ProfileEntry::Category::CC);
  3469. TimeLog timeLog;
  3470. data->mCollector->ForgetSkippable(aRemoveChildlessNodes,
  3471. aAsyncSnowWhiteFreeing);
  3472. timeLog.Checkpoint("ForgetSkippable()");
  3473. }
  3474. void
  3475. nsCycleCollector_dispatchDeferredDeletion(bool aContinuation, bool aPurge)
  3476. {
  3477. CycleCollectedJSContext* cx = CycleCollectedJSContext::Get();
  3478. if (cx) {
  3479. cx->DispatchDeferredDeletion(aContinuation, aPurge);
  3480. }
  3481. }
  3482. bool
  3483. nsCycleCollector_doDeferredDeletion()
  3484. {
  3485. CollectorData* data = sCollectorData.get();
  3486. // We should have started the cycle collector by now.
  3487. MOZ_ASSERT(data);
  3488. MOZ_ASSERT(data->mCollector);
  3489. MOZ_ASSERT(data->mContext);
  3490. return data->mCollector->FreeSnowWhite(false);
  3491. }
  3492. already_AddRefed<nsICycleCollectorLogSink>
  3493. nsCycleCollector_createLogSink()
  3494. {
  3495. nsCOMPtr<nsICycleCollectorLogSink> sink = new nsCycleCollectorLogSinkToFile();
  3496. return sink.forget();
  3497. }
  3498. void
  3499. nsCycleCollector_collect(nsICycleCollectorListener* aManualListener)
  3500. {
  3501. CollectorData* data = sCollectorData.get();
  3502. // We should have started the cycle collector by now.
  3503. MOZ_ASSERT(data);
  3504. MOZ_ASSERT(data->mCollector);
  3505. PROFILER_LABEL("nsCycleCollector", "collect",
  3506. js::ProfileEntry::Category::CC);
  3507. SliceBudget unlimitedBudget = SliceBudget::unlimited();
  3508. data->mCollector->Collect(ManualCC, unlimitedBudget, aManualListener);
  3509. }
  3510. void
  3511. nsCycleCollector_collectSlice(SliceBudget& budget,
  3512. bool aPreferShorterSlices)
  3513. {
  3514. CollectorData* data = sCollectorData.get();
  3515. // We should have started the cycle collector by now.
  3516. MOZ_ASSERT(data);
  3517. MOZ_ASSERT(data->mCollector);
  3518. PROFILER_LABEL("nsCycleCollector", "collectSlice",
  3519. js::ProfileEntry::Category::CC);
  3520. data->mCollector->Collect(SliceCC, budget, nullptr, aPreferShorterSlices);
  3521. }
  3522. void
  3523. nsCycleCollector_prepareForGarbageCollection()
  3524. {
  3525. CollectorData* data = sCollectorData.get();
  3526. MOZ_ASSERT(data);
  3527. if (!data->mCollector) {
  3528. return;
  3529. }
  3530. data->mCollector->PrepareForGarbageCollection();
  3531. }
  3532. void
  3533. nsCycleCollector_finishAnyCurrentCollection()
  3534. {
  3535. CollectorData* data = sCollectorData.get();
  3536. MOZ_ASSERT(data);
  3537. if (!data->mCollector) {
  3538. return;
  3539. }
  3540. data->mCollector->FinishAnyCurrentCollection();
  3541. }
  3542. void
  3543. nsCycleCollector_shutdown(bool aDoCollect)
  3544. {
  3545. CollectorData* data = sCollectorData.get();
  3546. if (data) {
  3547. MOZ_ASSERT(data->mCollector);
  3548. PROFILER_LABEL("nsCycleCollector", "shutdown",
  3549. js::ProfileEntry::Category::CC);
  3550. data->mCollector->Shutdown(aDoCollect);
  3551. data->mCollector = nullptr;
  3552. if (data->mContext) {
  3553. // Run any remaining tasks that may have been enqueued via
  3554. // RunInStableState during the final cycle collection.
  3555. data->mContext->ProcessStableStateQueue();
  3556. }
  3557. if (!data->mContext) {
  3558. delete data;
  3559. sCollectorData.set(nullptr);
  3560. }
  3561. }
  3562. }