gc.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912
  1. //#define BF_GC_DISABLED
  2. //#define BF_GC_LOG_ENABLED
  3. #define _WIN32_WINNT _WIN32_WINNT_WIN8
  4. // This spits out interesting stats periodically to the console
  5. #define BF_GC_PRINTSTATS
  6. //TEMPORARY
  7. //#define BF_GC_DEBUGSWEEP
  8. //#define BF_GC_EMPTYSCAN
  9. // Disable efficient new mass-freeing in TCMalloc
  10. //#define BF_GC_USE_OLD_FREE
  11. #ifdef BF_DEBUG
  12. // Useful for tracing down memory corruption -- memory isn't returned to TCMalloc, it's just marked as freed. You'll run out eventually
  13. //#define BF_NO_FREE_MEMORY
  14. // Old and not too useful
  15. //#define BG_GC_TRACKPTRS
  16. #endif
  17. #if defined BF_OBJECT_TRACK_ALLOCNUM && defined BF_NO_FREE_MEMORY
  18. //#define BF_GC_VERIFY_SWEEP_IDS
  19. #endif
  20. //#define BF_SECTION_NURSERY
  21. #ifdef BF_PLATFORM_WINDOWS
  22. #include <direct.h>
  23. #endif
  24. #include "gc.h"
  25. #ifdef BF_GC_SUPPORTED
  26. #include <fstream>
  27. #include "BeefySysLib/Common.h"
  28. #include "BeefySysLib/BFApp.h"
  29. #include "BeefySysLib/util/CritSect.h"
  30. #include "BeefySysLib/util/BeefPerf.h"
  31. #include "BeefySysLib/util/HashSet.h"
  32. #include "BeefySysLib/util/Dictionary.h"
  33. #include "BeefySysLib/util/BinaryHeap.h"
  34. #include <unordered_set>
  35. #include "../rt/BfObjects.h"
  36. #include "../rt/Thread.h"
  37. #ifdef BF_PLATFORM_WINDOWS
  38. #include <psapi.h>
  39. #endif
  40. #ifndef BF_TCMALLOC_DISABLED
  41. #define TCMALLOC_NO_MALLOCGUARD
  42. #define TCMALLOC_NAMESPACE tcmalloc_obj
  43. #define TCMALLOC_EXTERN static
  44. #include "gperftools/src/tcmalloc.cc"
  45. #else
  46. #define tc_malloc malloc
  47. #define tc_free free
  48. #endif
  49. USING_NS_BF;
  50. //System::Threading::Thread* gMainThread;
  51. #include "BeefySysLib/util/PerfTimer.h"
  52. /*#include "BeefyRtCPP/MonitorManager.h"
  53. #include "BeefyRtCPP/InternalThread.h"
  54. #include "BeefyRtCPP/ReflectionData.h"
  55. #include "BeefyRtCPP/RtCommon_inl.h"
  56. #include "BeefyRtCPP/BFArray.h"
  57. #include "BeefyRtCPP/Reflection.h"*/
  58. extern "C" GCDbgData gGCDbgData = { 0 };
  59. void BfLog(const char* fmt ...)
  60. {
  61. static int lineNum = 0;
  62. lineNum++;
  63. static FILE* fp = fopen("dbg_bf.txt", "wb");
  64. va_list argList;
  65. va_start(argList, fmt);
  66. String aResult = vformat(fmt, argList);
  67. va_end(argList);
  68. aResult = StrFormat("%d ", lineNum) + aResult;
  69. fwrite(aResult.c_str(), 1, aResult.length(), fp);
  70. fflush(fp);
  71. }
  72. //////////////////////////////////////////////////////////////////////////
  73. using Beefy::CritSect;
  74. BF_TLS_DECLSPEC BFGC::ThreadInfo* BFGC::ThreadInfo::sCurThreadInfo;
  75. HANDLE gGCHeap = 0;
  76. #ifdef _DEBUG
  77. bool gGCGetAllocStats = true;
  78. #else
  79. bool gGCGetAllocStats = false;
  80. #endif
  81. #ifdef BF_GC_VERIFY_SWEEP_IDS
  82. static std::set<int> allocIdSet;
  83. static int maxAllocNum = 0;
  84. #endif
  85. int gGCAllocCount = 0;
  86. int gGCAllocBytes = 0;
  87. std::vector<int> gGCAllocCountMap;
  88. std::vector<int> gGCAllocSizeMap;
  89. struct TCMallocRecord
  90. {
  91. void* mPtr;
  92. int mSize;
  93. };
  94. static std::vector<TCMallocRecord> gTCMallocRecords;
  95. void TCMalloc_RecordAlloc(void* ptr, int size)
  96. {
  97. TCMallocRecord mallocRecord = { ptr, size };
  98. gTCMallocRecords.push_back(mallocRecord);
  99. }
  100. static void TCMalloc_FreeAllocs()
  101. {
  102. for (auto& record : gTCMallocRecords)
  103. {
  104. ::VirtualFree(record.mPtr, 0, MEM_RELEASE);
  105. }
  106. gTCMallocRecords.clear();
  107. }
  108. void PatchWindowsFunctions()
  109. {
  110. // For TCMalloc, don't really patch
  111. }
  112. #ifdef BG_GC_TRACKPTRS
  113. boost::unordered_set<void*> gTrackPtr;
  114. #endif
  115. void BFMarkThreadPoolJobs()
  116. {
  117. }
  118. #ifndef BF_MONOTOUCH
  119. void BFMarkCOMObjects()
  120. {
  121. }
  122. void BFIMarkStackData(BFIThreadData* bfiThreadData)
  123. {
  124. }
  125. #endif
  126. /*void* sDbgPtr0 = NULL;
  127. void* sDbgPtr1 = NULL;
  128. void* sDbgPtr2 = NULL;*/
  129. void BFGC::MarkMembers(bf::System::Object* obj)
  130. {
  131. //BP_ZONE("MarkMembers");
  132. /*if ((obj == sDbgPtr0) || (obj == sDbgPtr1) || (obj == sDbgPtr2))
  133. {
  134. int a = 0;
  135. }*/
  136. if (((obj->mObjectFlags & BF_OBJECTFLAG_DELETED) != 0) && (!mMarkingDeleted))
  137. {
  138. mMarkingDeleted = true;
  139. gBfRtDbgCallbacks.Object_GCMarkMembers(obj);
  140. mMarkingDeleted = false;
  141. }
  142. else
  143. {
  144. gBfRtDbgCallbacks.Object_GCMarkMembers(obj);
  145. }
  146. }
  147. static void MarkObject(bf::System::Object* obj)
  148. {
  149. if ((obj != NULL) && ((obj->mObjectFlags & (BF_OBJECTFLAG_MARK_ID_MASK)) != BFGC::sCurMarkId))
  150. gBFGC.MarkFromGCThread(obj);
  151. }
  152. //////////////////////////////////////////////////////////////////////////
  153. //AtomicOps_x86CPUFeatureStruct AtomicOps_Internalx86CPUFeatures;
  154. namespace tcmalloc
  155. {
  156. extern "C" int RunningOnValgrind(void)
  157. {
  158. return 0;
  159. }
  160. }
  161. ////////////////////////////////////////////
  162. BFGC::ThreadInfo::~ThreadInfo()
  163. {
  164. if (mThreadHandle != NULL)
  165. BfpThread_Release(mThreadHandle);
  166. if (mThreadInfo != NULL)
  167. BfpThreadInfo_Release(mThreadInfo);
  168. }
  169. bool BFGC::ThreadInfo::WantsSuspend()
  170. {
  171. #ifndef BP_DISABLED
  172. BfpThreadId threadId = BpManager::Get()->mThreadId;
  173. return threadId != (BfpThreadId)mThreadId;
  174. #else
  175. return true;
  176. #endif
  177. }
  178. void BFGC::ThreadInfo::CalcStackStart()
  179. {
  180. intptr stackBase;
  181. int stackLimit;
  182. BfpThreadInfo_GetStackInfo(mThreadInfo, &stackBase, &stackLimit, BfpThreadInfoFlags_NoCache, NULL);
  183. mStackStart = stackBase;
  184. }
  185. //////////////////////////////////////////////////////////////////////////
  186. #ifdef BF_GC_LOG_ENABLED
  187. class GCLog
  188. {
  189. public:
  190. enum
  191. {
  192. EVENT_ALLOC,
  193. EVENT_GC_START, // cycle#
  194. EVENT_GC_UNFREEZE, // cycle#
  195. EVENT_MARK,
  196. EVENT_WB_MARK,
  197. EVENT_THREAD_STARTED,
  198. EVENT_THREAD_DONE,
  199. EVENT_SCAN_THREAD,
  200. EVENT_CONSERVATIVE_SCAN,
  201. EVENT_FOUND_TARGET,
  202. EVENT_FINALIZE_LIST,
  203. EVENT_LEAK,
  204. EVENT_DELETE,
  205. EVENT_FOUND,
  206. EVENT_FREE,
  207. EVENT_WB_MOVE,
  208. EVENT_WEAK_REF,
  209. EVENT_STRONG_REF,
  210. EVENT_WEAKREF_MARKED,
  211. EVENT_WEAK,
  212. EVENT_RESURRECT,
  213. EVENT_WAS_RESURRECT,
  214. EVENT_GC_DONE
  215. };
  216. class Entry
  217. {
  218. public:
  219. int mEvent;
  220. intptr mParam1;
  221. intptr mParam2;
  222. intptr mParam3;
  223. };
  224. Beefy::CritSect mCritSect;
  225. static const int BUFFSIZE = 4*1024*1024;
  226. static const int BUFFSIZE_MASK = BUFFSIZE-1;
  227. Entry mBuffer[BUFFSIZE];
  228. volatile int mHead;
  229. volatile int mTail;
  230. volatile bool mWriting;
  231. public:
  232. GCLog()
  233. {
  234. mWriting = false;
  235. }
  236. void Log(int event, intptr param1 = 0, intptr param2 = 0, intptr param3 = 0)
  237. {
  238. if (mWriting)
  239. {
  240. // Not a strict guarantee, but should keep us from only messing up
  241. // more than a single element of the log while we're writing it
  242. Beefy::AutoCrit autoCrit(mCritSect);
  243. return;
  244. }
  245. BF_FULL_MEMORY_FENCE();
  246. Entry entry = {event, param1, param2, param3};
  247. int prevHead;
  248. int nextHead;
  249. while (true)
  250. {
  251. prevHead = mHead;
  252. nextHead = (mHead + 1) & BUFFSIZE_MASK;
  253. if (nextHead == mTail)
  254. {
  255. int prevTail = mTail;
  256. int nextTail = (mTail + 1) & BUFFSIZE_MASK;
  257. if (::InterlockedCompareExchange((uint32*)&mTail, nextTail, prevTail) != prevTail)
  258. continue; // Try again
  259. }
  260. if (::InterlockedCompareExchange((uint32*)&mHead, nextHead, prevHead) == prevHead)
  261. break;
  262. }
  263. mBuffer[prevHead] = entry;
  264. }
  265. const char* GetNameStr(bf::System::Type* type)
  266. {
  267. static Beefy::String str;
  268. if (type == NULL)
  269. return "NULL";
  270. try
  271. {
  272. bf::System::Type* bfTypeRoot = (bf::System::Type*)type;
  273. str = type->GetFullName();
  274. return str.c_str();
  275. }
  276. catch (...)
  277. {
  278. return "<invalid>";
  279. }
  280. }
  281. #pragma warning(disable:4477)
  282. void Write()
  283. {
  284. Beefy::AutoCrit autoCrit(mCritSect);
  285. wchar_t str[MAX_PATH];
  286. GetCurrentDirectoryW(MAX_PATH, str);
  287. FILE* fp = fopen("c:\\temp\\gclog.txt", "w");
  288. mWriting = true;
  289. int sampleHead = mHead;
  290. BF_FULL_MEMORY_FENCE();
  291. int sampleTail = mTail;
  292. BF_FULL_MEMORY_FENCE();
  293. int pos = sampleTail;
  294. while (pos != sampleHead)
  295. {
  296. Entry ent = mBuffer[pos];
  297. switch (ent.mEvent)
  298. {
  299. case EVENT_ALLOC:
  300. fprintf(fp, "Alloc:%p Type:%s\n", ent.mParam1, GetNameStr((bf::System::Type*)ent.mParam2));
  301. break;
  302. case EVENT_GC_START:
  303. fprintf(fp, "GCStart MarkId:%d Tick:%d\n", ent.mParam1, ent.mParam2);
  304. break;
  305. case EVENT_GC_UNFREEZE:
  306. fprintf(fp, "GCUnfreeze MarkId:%d Tick:%d\n", ent.mParam1, ent.mParam2);
  307. break;
  308. case EVENT_MARK:
  309. fprintf(fp, "GCMark Obj:%p Flags:0x%X Parent:%p\n", ent.mParam1, ent.mParam2, ent.mParam3);
  310. break;
  311. case EVENT_WB_MARK:
  312. fprintf(fp, "WriteBarrierMark Obj:%p Type:%s Thread:%p\n", ent.mParam1, GetNameStr((bf::System::Type*)ent.mParam2), ent.mParam3);
  313. break;
  314. case EVENT_WB_MOVE:
  315. fprintf(fp, "WriteBarrier Entry Move Obj:%p Type:%s Thread:%p\n", ent.mParam1, GetNameStr((bf::System::Type*) ent.mParam2), ent.mParam3);
  316. break;
  317. case EVENT_FOUND_TARGET:
  318. fprintf(fp, "Heap Scan Found Target:%p Type:%s Flags:%d\n", ent.mParam1, GetNameStr((bf::System::Type*)ent.mParam2), ent.mParam3);
  319. break;
  320. case EVENT_FINALIZE_LIST:
  321. fprintf(fp, "On Finalize List:%p\n", ent.mParam1);
  322. break;
  323. case EVENT_LEAK:
  324. fprintf(fp, "Leak Detected:%p Type:%s\n", ent.mParam1, GetNameStr((bf::System::Type*)ent.mParam2));
  325. break;
  326. case EVENT_FOUND:
  327. fprintf(fp, "Found Obj:%p Flags:0x%X\n", ent.mParam1, ent.mParam2);
  328. break;
  329. case EVENT_FREE:
  330. fprintf(fp, "Free Obj:%p\n", ent.mParam1);
  331. break;
  332. case EVENT_DELETE:
  333. fprintf(fp, "Delete Obj:%p\n", ent.mParam1);
  334. break;
  335. case EVENT_THREAD_STARTED:
  336. fprintf(fp, "ThreadStarted:%p TID:%d\n", ent.mParam1, ent.mParam2);
  337. break;
  338. case EVENT_THREAD_DONE:
  339. fprintf(fp, "ThreadDone:%p\n", ent.mParam1);
  340. break;
  341. case EVENT_SCAN_THREAD:
  342. fprintf(fp, "ScanThread:%p Id:%d\n", ent.mParam1, ent.mParam2);
  343. break;
  344. case EVENT_CONSERVATIVE_SCAN:
  345. fprintf(fp, "ConservativeScan:%p to %p\n", ent.mParam1, ent.mParam2);
  346. break;
  347. case EVENT_GC_DONE:
  348. fprintf(fp, "GCDone MarkCount:%d HadOverflow:%d\n", ent.mParam1, ent.mParam2);
  349. break;
  350. default:
  351. BF_FATAL("Unknown event");
  352. break;
  353. }
  354. pos = (pos + 1) & BUFFSIZE_MASK;
  355. }
  356. fclose(fp);
  357. mWriting = false;
  358. }
  359. };
  360. GCLog gGCLog;
  361. void BFGCLogWrite()
  362. {
  363. gGCLog.Write();
  364. }
  365. #define BFLOG(cmd) gGCLog.Log(cmd)
  366. #define BFLOG1(cmd, param1) gGCLog.Log(cmd, param1)
  367. #define BFLOG2(cmd, param1, param2) gGCLog.Log(cmd, param1, param2)
  368. #define BFLOG3(cmd, param1, param2, param3) gGCLog.Log(cmd, param1, param2, param3)
  369. #else
  370. #define BFLOG(cmd)
  371. #define BFLOG1(cmd, param1)
  372. #define BFLOG2(cmd, param1, param2)
  373. #define BFLOG3(cmd, param1, param2, param3)
  374. void BFGCLogWrite() {}
  375. #endif
  376. void BFGCLogAlloc(bf::System::Object* obj, bf::System::Type* objType, int allocNum)
  377. {
  378. BFLOG3(GCLog::EVENT_ALLOC, (intptr)obj, (intptr)objType, allocNum);
  379. }
  380. BfDbgInternalThread* GetCurrentInternalThread()
  381. {
  382. return NULL;
  383. }
  384. ////////////////////////////////////////////
  385. static void CheckTcIntegrity()
  386. {
  387. auto pageHeap = Static::pageheap();
  388. if (pageHeap == NULL)
  389. return;
  390. #ifdef BF64
  391. //BP_ZONE("CheckTcIntegrity");
  392. Beefy::HashSet<tcmalloc_obj::Span*> spanSet;
  393. int interiorLen = PageHeap::PageMap::INTERIOR_LENGTH;
  394. int leafLen = PageHeap::PageMap::LEAF_LENGTH;
  395. for (int pageIdx1 = 0; pageIdx1 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx1++)
  396. {
  397. PageHeap::PageMap::Node* node1 = Static::pageheap()->pagemap_.root_->ptrs[pageIdx1];
  398. if (node1 == NULL)
  399. continue;
  400. for (int pageIdx2 = 0; pageIdx2 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx2++)
  401. {
  402. PageHeap::PageMap::Node* node2 = node1->ptrs[pageIdx2];
  403. if (node2 == NULL)
  404. continue;
  405. for (int pageIdx3 = 0; pageIdx3 < PageHeap::PageMap::LEAF_LENGTH; pageIdx3++)
  406. {
  407. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)node2->ptrs[pageIdx3];
  408. if (span != NULL)
  409. {
  410. int expectedStartPage = ((pageIdx1 * PageHeap::PageMap::INTERIOR_LENGTH) + pageIdx2) * PageHeap::PageMap::LEAF_LENGTH + pageIdx3;
  411. if (span->start == expectedStartPage)
  412. {
  413. auto result = spanSet.Add(span);
  414. BF_ASSERT(result);
  415. }
  416. }
  417. }
  418. }
  419. }
  420. int spansFound = spanSet.size();
  421. #endif
  422. }
  423. ////////////////////////////////////////////
  424. void BFCheckSuspended()
  425. {
  426. BfInternalThread* internalThread = (BfInternalThread*)GetCurrentInternalThread();
  427. if ((internalThread != NULL) && (internalThread->mIsSuspended))
  428. {
  429. internalThread = (BfInternalThread*)GetCurrentInternalThread();
  430. printf("IsSuspended\n");
  431. }
  432. BF_ASSERT((internalThread == NULL) || (!internalThread->mIsSuspended));
  433. }
  434. void* BfObjectAllocate(intptr size, bf::System::Type* objType)
  435. {
  436. bf::System::Object* obj = (bf::System::Object*)tc_malloc(size);
  437. BFLOG2(GCLog::EVENT_ALLOC, (intptr)obj, (intptr)objType);
  438. //CheckTcIntegrity();
  439. gBFGC.mBytesRequested += size;
  440. // #ifdef BF_GC_PRINTSTATS
  441. // ::InterlockedIncrement((volatile uint32*)&gBFGC.mTotalAllocs);
  442. // #endif
  443. #ifdef BG_GC_TRACKPTRS
  444. {
  445. Beefy::AutoCrit autoCrit(gBFGC.mCritSect);
  446. BF_LOGASSERT(gTrackPtr.find(obj) == gTrackPtr.end());
  447. gTrackPtr.insert(obj);
  448. }
  449. #endif
  450. #ifdef _DEBUG
  451. BF_LOGASSERT((obj->mAllocCheckPtr == 0) || (size > kMaxSize));
  452. #endif
  453. //memset((void*)obj, 0, size);
  454. #ifdef BF_OBJECT_TRACK_ALLOCNUM
  455. obj->mAllocNum = (int)::InterlockedIncrement((volatile uint32*) &BfObject::sCurAllocNum);
  456. #endif
  457. #ifdef BF_SECTION_NURSERY
  458. BfInternalThread* internalThread = (BfInternalThread*)bf::System::Threading::Thread::CurrentInternalThread_internal();
  459. if ((internalThread != NULL) && (internalThread->mSectionDepth == 1))
  460. internalThread->mSectionNursery.PushUnsafe(obj);
  461. #endif
  462. gBFGC.mAllocSinceLastGC += size;
  463. return obj;
  464. }
  465. //////////////////////////////////////////////////////////////////////////
  466. #define BF_GC_MAX_PENDING_OBJECT_COUNT 16*1024
  467. ///
  468. ///
  469. class BFFinalizeData
  470. {
  471. public:
  472. int mFinalizeCount;
  473. bool mInFinalizeList;
  474. public:
  475. BFFinalizeData()
  476. {
  477. mFinalizeCount = 1;
  478. mInFinalizeList = false;
  479. }
  480. };
  481. ///
  482. BFGC gBFGC;
  483. int volatile BFGC::sCurMarkId = 1;
  484. int volatile BFGC::sAllocFlags = 1;
  485. int gBFCRTAllocSize = 0;
  486. BFGC::BFGC()
  487. {
  488. mRunning = false;
  489. mExiting = false;
  490. mPaused = false;
  491. mShutdown = false;
  492. mForceDecommit = false;
  493. mCollectFailed = false;
  494. mLastCollectFrame = 0;
  495. mSkipMark = false;
  496. mGracelessShutdown = false;
  497. mMainThreadTLSPtr = NULL;
  498. mHadPendingGCDataOverflow = false;
  499. mCurPendingGCSize = 0;
  500. mMaxPendingGCSize = 0;
  501. mCollectIdx = 0;
  502. mStackScanIdx = 0;
  503. mMarkDepthCount = 0;
  504. mMarkingDeleted = false;
  505. mCurMutatorMarkCount = 0;
  506. mCurGCMarkCount = 0;
  507. mCurFreedBytes = 0;
  508. sCurMarkId = 1;
  509. mQueueMarkObjects = false;
  510. //mEphemeronTombstone = NULL;
  511. mWaitingForGC = false;
  512. mCollectRequested = false;
  513. mAllocSinceLastGC = 0;
  514. mFullGCTriggered = false;
  515. mDebugDumpState = 0;
  516. mCurScanIdx = 1;
  517. mTotalAllocs = 0;
  518. mTotalFrees = 0;
  519. mLastFreeCount = 0;
  520. mBytesFreed = 0;
  521. mBytesRequested = 0;
  522. mRequestedSizesInvalid = false;
  523. mDisplayFreedObjects = false;
  524. mHadRootError = false;
  525. mCurLiveObjectCount = 0;
  526. mFreeSinceLastGC = 0;
  527. // Default to just over two 60Hz frames
  528. // This keeps stack scanning from adding excessive costs to a 30Hz app, or
  529. // from impacting two successive frames in a triple-buffered 60Hz app where
  530. // only one slow frame could be absorbed
  531. mMultiStackScanWait = 35;
  532. // By default we collect after freeing 64MB
  533. mFreeTrigger = 64*1024*1024;
  534. mMaxPausePercentage = 20;
  535. mMaxRawDeferredObjectFreePercentage = 30;
  536. // Zero means to run continuously. -1 means don't trigger on a time base
  537. // Defaults to collecting every 2 seconds
  538. mFullGCPeriod = 2000;
  539. mGCThread = NULL;
  540. gGCDbgData.mDbgFlags = gBfRtDbgFlags;
  541. ThreadCache::InitTSD();
  542. if (UNLIKELY(Static::pageheap() == NULL)) ThreadCache::InitModule();
  543. gGCDbgData.mObjRootPtr = Static::pageheap()->pagemap_.root_;
  544. for (int i = 0; i < kNumClasses; i++)
  545. gGCDbgData.mSizeClasses[i] = Static::sizemap()->ByteSizeForClass(i);
  546. mStats = NULL;
  547. Beefy::String memName = StrFormat("BFGC_stats_%d", GetCurrentProcessId());
  548. auto* fileMapping = ::CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(Stats), memName.c_str());
  549. if (fileMapping != NULL)
  550. {
  551. mStats = (Stats*)MapViewOfFile(fileMapping, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(Stats));
  552. mStats->mHeapSize = 0;
  553. }
  554. RawInit();
  555. }
  556. BFGC::~BFGC()
  557. {
  558. //::HeapDestroy(gGCHeap);
  559. //gGCHeap = NULL;
  560. Beefy::AutoCrit autoCrit(mCritSect);
  561. for (auto thread : mThreadList)
  562. {
  563. delete thread;
  564. }
  565. }
  566. /*inline T BFWB(typename BFToType<T>::type::BFBaseObjectInObject obj)
  567. {
  568. if ((obj != NULL) && ((obj->mBFMonitorPtrAndObjFlags & (BF_OBJECTFLAG_MARK_ID_MASK)) != BFGC::sCurMarkId))
  569. gBFGC.MarkFromMutator(obj, 0);
  570. return (T) obj;
  571. }*/
  572. /*void BFGC::RegisterRoot(bf::System::Object* obj)
  573. {
  574. Beefy::AutoCrit autoCrit(mCritSect);
  575. mExplicitRoots.push_back(obj);
  576. if (mRunning)
  577. BFWB(obj);
  578. }*/
  579. #ifdef BF32
  580. static tcmalloc_obj::Span* TCGetSpanAt(void* addr)
  581. {
  582. int checkPageId = (int)((uintptr)addr >> kPageShift);
  583. int checkRootIdx = checkPageId >> PageHeap::PageMap::LEAF_BITS;
  584. int checkLeafIdx = checkPageId & (PageHeap::PageMap::LEAF_LENGTH - 1);
  585. PageHeap::PageMap::Leaf* rootLeaf = Static::pageheap()->pagemap_.root_[checkRootIdx];
  586. if (rootLeaf == NULL)
  587. return NULL;
  588. auto span = (tcmalloc_obj::Span*)rootLeaf->values[checkLeafIdx];
  589. // intptr pageSize = (intptr)1 << kPageShift;
  590. // int spanSize = pageSize * span->length;
  591. // void* spanStart = (void*)((intptr)span->start << kPageShift);
  592. // void* spanEnd = (void*)((intptr)spanStart + spanSize);
  593. // if ((addr >= spanStart) && (addr < spanEnd))
  594. // return span;
  595. return span;
  596. }
  597. #else
  598. static tcmalloc_obj::Span* TCGetSpanAt(void* addr)
  599. {
  600. int64 checkPageId = (int64)((uintptr)addr >> kPageShift);
  601. int pageIdx1 = (int)(checkPageId >> (PageHeap::PageMap::LEAF_BITS + PageHeap::PageMap::INTERIOR_BITS));
  602. int pageIdx2 = (int)((checkPageId >> PageHeap::PageMap::LEAF_BITS) & (PageHeap::PageMap::INTERIOR_LENGTH-1));
  603. int pageIdx3 = (int)(checkPageId & (PageHeap::PageMap::LEAF_LENGTH-1));
  604. PageHeap::PageMap::Node* node1 = Static::pageheap()->pagemap_.root_->ptrs[pageIdx1];
  605. if (node1 == NULL)
  606. return NULL;
  607. PageHeap::PageMap::Node* node2 = node1->ptrs[pageIdx2];
  608. if (node2 == NULL)
  609. return NULL;
  610. auto span = (tcmalloc_obj::Span*)node2->ptrs[pageIdx3];
  611. return span;
  612. // if (span == NULL)
  613. // return NULL;
  614. // intptr pageSize = (intptr)1 << kPageShift;
  615. // int spanSize = pageSize * span->length;
  616. // void* spanStart = (void*)((intptr)span->start << kPageShift);
  617. // void* spanEnd = (void*)((intptr)spanStart + spanSize);
  618. // if ((addr >= spanStart) && (addr < spanEnd))
  619. // return span;
  620. // return NULL;
  621. }
  622. #endif
  623. int gTargetFoundCount = 0;
  624. int gMarkTargetCount = 0;
  625. int gMarkTargetMutatorCount = 0;
  626. int BFGetObjectSize(bf::System::Object* obj)
  627. {
  628. // auto span = TCGetSpanAt(obj);
  629. // int elementSize = Static::sizemap()->ByteSizeForClass(span->sizeclass);
  630. // if (elementSize != 0)
  631. // return elementSize;
  632. // intptr pageSize = (intptr)1 << kPageShift;
  633. // int spanSize = pageSize * span->length;
  634. // return spanSize;
  635. const PageID p = reinterpret_cast<uintptr_t>(obj) >> kPageShift;
  636. size_t cl = Static::pageheap()->GetSizeClassIfCached(p);
  637. int allocSize = 0;
  638. if (cl == 0)
  639. {
  640. auto span = Static::pageheap()->GetDescriptor(p);
  641. if (span != NULL)
  642. {
  643. cl = span->sizeclass;
  644. if (cl == 0)
  645. {
  646. allocSize = span->length << kPageShift;
  647. }
  648. }
  649. }
  650. if (cl != 0)
  651. allocSize = Static::sizemap()->class_to_size(cl);
  652. return allocSize;
  653. }
  654. void BFCheckObjectSize(bf::System::Object* obj, int size)
  655. {
  656. if (gBFGC.mRunning)
  657. {
  658. BF_ASSERT(BFGetObjectSize(obj) == size);
  659. }
  660. }
  661. void BFGC::ConservativeScan(void* startAddr, int length)
  662. {
  663. if ((gBfRtDbgFlags & BfRtFlags_ObjectHasDebugFlags) == 0)
  664. return;
  665. BFLOG2(GCLog::EVENT_CONSERVATIVE_SCAN, (intptr)startAddr, (intptr)startAddr + length);
  666. void* ptr = (void*)((intptr)startAddr & ~((sizeof(intptr)-1)));
  667. void* endAddr = (uint8*)startAddr + length;
  668. __try
  669. {
  670. while (ptr < endAddr)
  671. {
  672. void* addr = *(void**)ptr;
  673. MarkFromGCThread((bf::System::Object*)addr);
  674. ptr = (uint8*)ptr + sizeof(intptr);
  675. }
  676. }
  677. __except (EXCEPTION_EXECUTE_HANDLER)
  678. {
  679. }
  680. }
  681. static tcmalloc_obj::Span* gLastSpan = NULL;
  682. bool BFGC::IsHeapObject(bf::System::Object* obj)
  683. {
  684. //BP_ZONE("IsHeapObject");
  685. if ((obj >= tcmalloc_obj::PageHeap::sAddressStart) && (obj < tcmalloc_obj::PageHeap::sAddressEnd))
  686. {
  687. tcmalloc_obj::Span* span = TCGetSpanAt(obj);
  688. gLastSpan = span;
  689. return span != NULL;
  690. }
  691. return false;
  692. }
  693. /*void BFGC::MarkTypeStatics(BFTypeRoot* checkType)
  694. {
  695. BFTypeRoot* innerCheckType = (BFTypeRoot*)checkType->mFirstNestedType;
  696. while (innerCheckType != NULL)
  697. {
  698. MarkTypeStatics(innerCheckType);
  699. innerCheckType = (BFTypeRoot*)innerCheckType->mNextSibling;
  700. }
  701. if (checkType->mTypeRootData->mTypeFlags & BF_TYPEFLAG_GENERIC_DEF_TYPE)
  702. return;
  703. if (checkType->mTypeRootData->mBFMarkStatics != NULL)
  704. checkType->mTypeRootData->mBFMarkStatics();
  705. }
  706. void BFGC::MarkStatics()
  707. {
  708. BFMark(bf::System::Object::sTypeLockObject);
  709. BFAppDomain* bfDomain = BFAppDomain::GetAppDomain();
  710. for (int assemblyIdx = 0; assemblyIdx < (int) bfDomain->mBFAssemblyVector.size(); assemblyIdx++)
  711. {
  712. BFAssembly* assembly = bfDomain->mBFAssemblyVector[assemblyIdx];
  713. BFTypeRoot* outerCheckType = (BFTypeRoot*)assembly->mFirstType;
  714. while (outerCheckType != NULL)
  715. {
  716. MarkTypeStatics(outerCheckType);
  717. outerCheckType = (BFTypeRoot*)outerCheckType->mNextSibling;
  718. }
  719. }
  720. BFType::BFMarkStatics();
  721. }*/
  722. void BFGC::MarkStatics()
  723. {
  724. bf::System::GC::DoMarkAllStaticMembers();
  725. //MarkObject(gMainThread);
  726. }
  727. void BFGC::ObjectDeleteRequested(bf::System::Object* obj)
  728. {
  729. if (mFreeTrigger >= 0)
  730. {
  731. int objSize = BFGetObjectSize(obj);
  732. if (BfpSystem_InterlockedExchangeAdd32((uint32*)&mFreeSinceLastGC, (uint32)objSize) + objSize >= mFreeTrigger)
  733. {
  734. mFreeSinceLastGC = 0;
  735. Collect(true);
  736. }
  737. BFLOG1(GCLog::EVENT_DELETE, (intptr)obj);
  738. }
  739. }
  740. bool BFGC::HandlePendingGCData()
  741. {
  742. int count = 0;
  743. while (true)
  744. {
  745. if (mOrderedPendingGCData.IsEmpty())
  746. break;
  747. mCurPendingGCSize = 0;
  748. bf::System::Object* obj = mOrderedPendingGCData.Pop();
  749. MarkMembers(obj);
  750. count++;
  751. if (mCurPendingGCSize > mMaxPendingGCSize)
  752. mMaxPendingGCSize = mCurPendingGCSize;
  753. }
  754. return count > 0;
  755. }
  756. void BFGC::SweepSpan(tcmalloc_obj::Span* span, int expectedStartPage)
  757. {
  758. if ((gBfRtDbgFlags & BfRtFlags_ObjectHasDebugFlags) == 0)
  759. return;
  760. if (span->location != tcmalloc_obj::Span::IN_USE)
  761. return;
  762. if (span->start != expectedStartPage)
  763. {
  764. // This check covers when a new multi-page span is being put into place
  765. // and we catch after the first block, and it also catches the case
  766. // when the allocator splits a span and the pagemap can hold a reference
  767. // to a span that no longer covers that location.
  768. // For both of these cases we ignore the span. Remember, the worst case
  769. // here is that we'll miss a sweep of an object, which would just delay it's
  770. // cleanup until next GC cycle. Because the GC is the sole freer of spans,
  771. // there can never be a case where we find a valid span and then the span
  772. // changes sizeclass or location before we can scan the memory it points to.
  773. //
  774. // This also covers the case where a page spans over a radix map section and
  775. // we catch it on an outer loop again
  776. return;
  777. }
  778. intptr pageSize = (intptr)1<<kPageShift;
  779. intptr spanSize = pageSize * span->length;
  780. void* spanStart = (void*)((intptr)span->start << kPageShift);
  781. void* spanEnd = (void*)((intptr)spanStart + spanSize);
  782. void* spanPtr = spanStart;
  783. BF_LOGASSERT((spanStart >= tcmalloc_obj::PageHeap::sAddressStart) && (spanEnd <= tcmalloc_obj::PageHeap::sAddressEnd));
  784. intptr elementSize = Static::sizemap()->ByteSizeForClass(span->sizeclass);
  785. if (elementSize == 0)
  786. elementSize = spanSize;
  787. BF_LOGASSERT(elementSize >= sizeof(bf::System::Object));
  788. while (spanPtr <= (uint8*)spanEnd - elementSize)
  789. {
  790. //objCheckCount++;
  791. bf::System::Object* obj = (bf::System::Object*)spanPtr;
  792. #ifdef TARGET_TYPE
  793. if ((obj->mAllocCheckPtr != 0) && (obj->mBFVData->mType == TARGET_TYPE))
  794. {
  795. //sweepFoundCount++;
  796. }
  797. #endif
  798. // Mark 0 means 'just allocated'. 'deleteMarkId' is the last one. 'invalidMarkId' should be impossible because we'd either be deleted or marked as leaked before
  799. int deleteMarkId = mCurMarkId - 1;
  800. if (deleteMarkId == 0)
  801. deleteMarkId = 3;
  802. int invalidMarkId = deleteMarkId - 1;
  803. if (invalidMarkId == 0)
  804. invalidMarkId = 3;
  805. bool showAllAsLeaks = !mRunning;
  806. if (obj->mAllocCheckPtr != 0)
  807. {
  808. #ifdef BF_GC_VERIFY_SWEEP_IDS
  809. BF_LOGASSERT(obj->mAllocNum != 0);
  810. BF_LOGASSERT(allocIdSet.find(obj->mAllocNum) == allocIdSet.end());
  811. allocIdSet.insert(obj->mAllocNum);
  812. #endif
  813. mCurSweepFoundCount++;
  814. int objectFlags = obj->mObjectFlags;
  815. if (objectFlags == 0)
  816. mCurSweepFoundPermanentCount++;
  817. BFLOG2(GCLog::EVENT_FOUND, (intptr)obj, obj->mObjectFlags);
  818. int markId = objectFlags & BF_OBJECTFLAG_MARK_ID_MASK;
  819. if ((mCollectFailed) && (markId != mCurMarkId))
  820. {
  821. obj->mObjectFlags = (BfObjectFlags)((obj->mObjectFlags & ~BF_OBJECTFLAG_MARK_ID_MASK) | mCurMarkId);
  822. markId = mCurMarkId;
  823. }
  824. BF_ASSERT(markId != invalidMarkId);
  825. if (markId == 0)
  826. {
  827. // Newly-allocated! Set mark flag now...
  828. //obj->mObjectFlags = (BfObjectFlags)(obj->mObjectFlags | mCurMarkId);
  829. // Newly-allocated! Ignore, it will have its mark set soon (rare race condition)
  830. }
  831. else if ((markId == deleteMarkId) || (mSweepInfo.mShowAllAsLeaks))
  832. {
  833. if ((objectFlags & BF_OBJECTFLAG_DELETED) == 0)
  834. {
  835. if (!mSweepInfo.mEmptyScan)
  836. {
  837. // We set this to cause an error like:
  838. // Deleting an object that was detected as leaked (internal error)
  839. obj->mObjectFlags = (BfObjectFlags)(objectFlags | BF_OBJECTFLAG_STACK_ALLOC);
  840. if (!mHadRootError)
  841. {
  842. mSweepInfo.mLeakCount++;
  843. if (mSweepInfo.mLeakCount <= 1024 * 1024) // Have SOME limit
  844. {
  845. mSweepInfo.mLeakObjects.push_back(obj);
  846. }
  847. BFLOG2(GCLog::EVENT_LEAK, (intptr)obj, (intptr)obj->_GetType());
  848. #ifdef BF_GC_LOG_ENABLED
  849. gGCLog.Write();
  850. #endif
  851. }
  852. }
  853. }
  854. else
  855. {
  856. if (!mSweepInfo.mEmptyScan)
  857. {
  858. BFLOG1(GCLog::EVENT_FINALIZE_LIST, (intptr)obj);
  859. //obj->mObjectFlags = (BfObjectFlags) (obj->mObjectFlags & ~BF_OBJECTFLAG_FINALIZE_MAP);
  860. mFinalizeList.push_back(obj);
  861. }
  862. }
  863. }
  864. else
  865. mCurLiveObjectCount++;
  866. }
  867. spanPtr = (void*)((intptr)spanPtr + elementSize);
  868. }
  869. }
  870. void BFGC::Sweep()
  871. {
  872. BP_ZONE("Sweep");
  873. mCurLiveObjectCount = 0;
  874. auto pageHeap = Static::pageheap();
  875. if (pageHeap == NULL)
  876. return;
  877. #ifdef BF_GC_VERIFY_SWEEP_IDS
  878. maxAllocNum = bf::System::Object::sCurAllocNum;
  879. allocIdSet.clear();
  880. #endif
  881. int leafCheckCount = 0;
  882. int bits = kAddressBits;
  883. int leafLen = PageHeap::PageMap::LEAF_LENGTH;
  884. #ifdef BF32
  885. for (int rootIdx = 0; rootIdx < PageHeap::PageMap::ROOT_LENGTH; rootIdx++)
  886. {
  887. PageHeap::PageMap::Leaf* rootLeaf = Static::pageheap()->pagemap_.root_[rootIdx];
  888. if (rootLeaf == NULL)
  889. continue;
  890. for (int leafIdx = 0; leafIdx < PageHeap::PageMap::LEAF_LENGTH; leafIdx++)
  891. {
  892. leafCheckCount++;
  893. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)rootLeaf->values[leafIdx];
  894. if (span != NULL)
  895. {
  896. int expectedStartPage = (rootIdx * PageHeap::PageMap::LEAF_LENGTH) + leafIdx;
  897. SweepSpan(span, expectedStartPage);
  898. // We may be tempted to advance by span->length here, BUT
  899. // let us just scan all leafs becuause span data is
  900. // sometimes invalid and a long invalid span can cause
  901. // us to skip over an actual valid span
  902. }
  903. }
  904. }
  905. #else
  906. int interiorLen = PageHeap::PageMap::INTERIOR_LENGTH;
  907. for (int pageIdx1 = 0; pageIdx1 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx1++)
  908. {
  909. PageHeap::PageMap::Node* node1 = Static::pageheap()->pagemap_.root_->ptrs[pageIdx1];
  910. if (node1 == NULL)
  911. continue;
  912. for (int pageIdx2 = 0; pageIdx2 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx2++)
  913. {
  914. PageHeap::PageMap::Node* node2 = node1->ptrs[pageIdx2];
  915. if (node2 == NULL)
  916. continue;
  917. for (int pageIdx3 = 0; pageIdx3 < PageHeap::PageMap::LEAF_LENGTH; pageIdx3++)
  918. {
  919. leafCheckCount++;
  920. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)node2->ptrs[pageIdx3];
  921. if (span != NULL)
  922. {
  923. int expectedStartPage = ((pageIdx1 * PageHeap::PageMap::INTERIOR_LENGTH) + pageIdx2) * PageHeap::PageMap::LEAF_LENGTH + pageIdx3;
  924. SweepSpan(span, expectedStartPage);
  925. // We may be tempted to advance by span->length here, BUT
  926. // let us just scan all leafs becuause span data is
  927. // sometimes invalid and a long invalid span can cause
  928. // us to skip over an actual valid span
  929. }
  930. }
  931. }
  932. }
  933. #endif
  934. #ifdef BF_GC_VERIFY_SWEEP_IDS
  935. for (int allocNum = 1; allocNum < maxAllocNum; allocNum++)
  936. {
  937. BF_LOGASSERT(allocIdSet.find(allocNum) != allocIdSet.end());
  938. }
  939. #endif
  940. }
  941. extern Beefy::StringT<0> gDbgErrorString;
  942. void BFGC::ProcessSweepInfo()
  943. {
  944. if (mSweepInfo.mLeakCount > 0)
  945. {
  946. if (mSweepInfo.mShowAllAsLeaks)
  947. {
  948. // We aren't certain of the mark flags, so force the issue
  949. mCurMarkId = 0;
  950. for (auto obj : mSweepInfo.mLeakObjects)
  951. {
  952. obj->mObjectFlags = (BfObjectFlags)((obj->mObjectFlags & ~BF_OBJECTFLAG_MARK_ID_MASK) | mCurMarkId);
  953. }
  954. mCurMarkId = 1;
  955. }
  956. for (auto obj : mSweepInfo.mLeakObjects)
  957. {
  958. MarkMembers(obj);
  959. }
  960. //::MessageBoxA(NULL, "Leak", "Leak", MB_OK);
  961. //#if 0
  962. Beefy::StringT<1024> errorStr = StrFormat("%d object memory leak%s detected.\nMouse over an 'i' icon in the Output panel to view a leaked object and its allocation stack trace.",
  963. mSweepInfo.mLeakCount, (mSweepInfo.mLeakCount != 1) ? "s" : "");
  964. gDbgErrorString = errorStr;
  965. gDbgErrorString += "\n";
  966. #ifdef BF_GC_DEBUGSWEEP
  967. Sleep(100);
  968. #endif
  969. for (int pass = 0; pass < 2; pass++)
  970. {
  971. int passLeakCount = 0;
  972. for (auto obj : mSweepInfo.mLeakObjects)
  973. {
  974. bool wantsNoRefs = pass == 0;
  975. bool hasNoRefs = (obj->mObjectFlags & BF_OBJECTFLAG_MARK_ID_MASK) != mCurMarkId;
  976. if (hasNoRefs != wantsNoRefs)
  977. continue;
  978. Beefy::String typeName = obj->GetTypeName();
  979. if (passLeakCount == 0)
  980. {
  981. Beefy::String header = (pass == 0) ? " Unreferenced:\n" : " Referenced by other leaked objects:\n";
  982. errorStr += "\x1";
  983. errorStr += "TEXT\t";
  984. errorStr += header;
  985. gDbgErrorString += header;
  986. }
  987. if (passLeakCount == 20000) // Only display so many...
  988. break;
  989. errorStr += "\x1";
  990. errorStr += StrFormat("LEAK\t(System.Object)0x%@\n", obj);
  991. errorStr += StrFormat(" (%s)0x%@\n", typeName.c_str(), obj);
  992. if (gDbgErrorString.length() < 256)
  993. gDbgErrorString += StrFormat(" (%s)0x%@\n", typeName.c_str(), obj);
  994. passLeakCount++;
  995. }
  996. }
  997. //TODO: Testing!
  998. //OutputDebugStrF(gDbgErrorString.c_str());
  999. gBfRtDbgCallbacks.SetErrorString(gDbgErrorString.c_str());
  1000. gBfRtDbgCallbacks.DebugMessageData_SetupError(errorStr.c_str(), 1);
  1001. mCritSect.Unlock();
  1002. BF_DEBUG_BREAK();
  1003. mCritSect.Lock();
  1004. for (auto obj : mSweepInfo.mLeakObjects)
  1005. {
  1006. // Allow continuing
  1007. obj->mObjectFlags = (BfObjectFlags)((obj->mObjectFlags & ~BF_OBJECTFLAG_MARK_ID_MASK) | mCurMarkId);
  1008. }
  1009. }
  1010. mSweepInfo.Clear();
  1011. }
  1012. void BFGC::ReleasePendingSpanObjects(Span* span)
  1013. {
  1014. if (span->freeingObjects != NULL)
  1015. {
  1016. Static::central_cache()[span->sizeclass].ReleasePendingSpanObjects(span);
  1017. span->freeingObjects = NULL;
  1018. span->freeingObjectsTail = NULL;
  1019. }
  1020. }
  1021. void BFGC::ReleasePendingObjects()
  1022. {
  1023. BP_ZONE("ReleasePendingObjects");
  1024. auto pageHeap = Static::pageheap();
  1025. if (pageHeap == NULL)
  1026. return;
  1027. #ifdef BF_GC_VERIFY_SWEEP_IDS
  1028. maxAllocNum = bf::System::Object::sCurAllocNum;
  1029. allocIdSet.clear();
  1030. #endif
  1031. int leafCheckCount = 0;
  1032. #ifdef BF32
  1033. for (int rootIdx = 0; rootIdx < PageHeap::PageMap::ROOT_LENGTH; rootIdx++)
  1034. {
  1035. PageHeap::PageMap::Leaf* rootLeaf = Static::pageheap()->pagemap_.root_[rootIdx];
  1036. if (rootLeaf == NULL)
  1037. continue;
  1038. for (int leafIdx = 0; leafIdx < PageHeap::PageMap::LEAF_LENGTH; leafIdx++)
  1039. {
  1040. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)rootLeaf->values[leafIdx];
  1041. if (span != NULL)
  1042. ReleasePendingSpanObjects(span);
  1043. }
  1044. }
  1045. #else
  1046. for (int pageIdx1 = 0; pageIdx1 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx1++)
  1047. {
  1048. PageHeap::PageMap::Node* node1 = Static::pageheap()->pagemap_.root_->ptrs[pageIdx1];
  1049. if (node1 == NULL)
  1050. continue;
  1051. for (int pageIdx2 = 0; pageIdx2 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx2++)
  1052. {
  1053. PageHeap::PageMap::Node* node2 = node1->ptrs[pageIdx2];
  1054. if (node2 == NULL)
  1055. continue;
  1056. for (int pageIdx3 = 0; pageIdx3 < PageHeap::PageMap::LEAF_LENGTH; pageIdx3++)
  1057. {
  1058. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)node2->ptrs[pageIdx3];
  1059. if (span != NULL)
  1060. ReleasePendingSpanObjects(span);
  1061. }
  1062. }
  1063. }
  1064. #endif
  1065. #ifdef BF_GC_VERIFY_SWEEP_IDS
  1066. for (int allocNum = 1; allocNum < maxAllocNum; allocNum++)
  1067. {
  1068. BF_LOGASSERT(allocIdSet.find(allocNum) != allocIdSet.end());
  1069. }
  1070. #endif
  1071. }
  1072. typedef struct _TEB {
  1073. PVOID Reserved1[11];
  1074. void* ThreadLocalStorage;
  1075. void* ProcessEnvironmentBlock;
  1076. PVOID Reserved2[399];
  1077. BYTE Reserved3[1952];
  1078. PVOID TlsSlots[64];
  1079. BYTE Reserved4[8];
  1080. PVOID Reserved5[26];
  1081. PVOID ReservedForOle;
  1082. PVOID Reserved6[4];
  1083. PVOID TlsExpansionSlots;
  1084. } TEB, *PTEB;
  1085. typedef LONG NTSTATUS;
  1086. typedef DWORD KPRIORITY;
  1087. typedef WORD UWORD;
  1088. typedef struct _CLIENT_ID
  1089. {
  1090. PVOID UniqueProcess;
  1091. PVOID UniqueThread;
  1092. } CLIENT_ID, *PCLIENT_ID;
  1093. typedef struct _THREAD_BASIC_INFORMATION
  1094. {
  1095. NTSTATUS ExitStatus;
  1096. PVOID TebBaseAddress;
  1097. CLIENT_ID ClientId;
  1098. KAFFINITY AffinityMask;
  1099. KPRIORITY Priority;
  1100. KPRIORITY BasePriority;
  1101. } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION;
  1102. enum THREADINFOCLASS
  1103. {
  1104. ThreadBasicInformation,
  1105. };
  1106. static _TEB* GetTEB(HANDLE hThread)
  1107. {
  1108. bool loadedManually = false;
  1109. HMODULE module = GetModuleHandleA("ntdll.dll");
  1110. if (!module)
  1111. {
  1112. module = LoadLibraryA("ntdll.dll");
  1113. loadedManually = true;
  1114. }
  1115. NTSTATUS(__stdcall *NtQueryInformationThread)(HANDLE ThreadHandle, THREADINFOCLASS ThreadInformationClass, PVOID ThreadInformation, ULONG ThreadInformationLength, PULONG ReturnLength);
  1116. NtQueryInformationThread = reinterpret_cast<decltype(NtQueryInformationThread)>(GetProcAddress(module, "NtQueryInformationThread"));
  1117. if (NtQueryInformationThread)
  1118. {
  1119. NT_TIB tib = { 0 };
  1120. THREAD_BASIC_INFORMATION tbi = { 0 };
  1121. NTSTATUS status = NtQueryInformationThread(hThread, ThreadBasicInformation, &tbi, sizeof(tbi), nullptr);
  1122. if (status >= 0)
  1123. {
  1124. _TEB* teb = (_TEB*)tbi.TebBaseAddress;
  1125. return teb;
  1126. }
  1127. }
  1128. if (loadedManually)
  1129. {
  1130. FreeLibrary(module);
  1131. }
  1132. return NULL;
  1133. }
  1134. static void** GetThreadLocalAddressMap(HANDLE hThread)
  1135. {
  1136. _TEB* teb = GetTEB(hThread);
  1137. if (teb == NULL)
  1138. return NULL;
  1139. return (void**)teb->ThreadLocalStorage;
  1140. }
  1141. void BFGC::AdjustStackPtr(intptr& addr, int& size)
  1142. {
  1143. int pageSize = 4096;
  1144. // There's a race condition where RSP can be adjusted into a guard page region before the
  1145. // guard page is actually removed. The guard page is a fire-once error so we can't just
  1146. // ignore it or else we rob that read of it's ability to expand (crash)
  1147. while (size > 0)
  1148. {
  1149. MEMORY_BASIC_INFORMATION memoryInfo;
  1150. int returnSize = ::VirtualQuery((void*)addr, &memoryInfo, sizeof(memoryInfo));
  1151. if ((returnSize > 0) && ((memoryInfo.Protect & (PAGE_GUARD | PAGE_NOACCESS)) == 0))
  1152. return;
  1153. addr += pageSize;
  1154. size -= pageSize;
  1155. }
  1156. }
  1157. bool BFGC::ScanThreads()
  1158. {
  1159. BP_ZONE("BFGC::ScanThreads");
  1160. mUsingThreadUnlocked = true;
  1161. BF_FULL_MEMORY_FENCE();
  1162. //BP_ZONE("ScanThreads");
  1163. bool didWork = false;
  1164. mStackScanIdx++;
  1165. mDoStackDeepMark = true;
  1166. int threadIdx = 0;
  1167. while (true)
  1168. {
  1169. ThreadInfo* thread = NULL;
  1170. ///
  1171. {
  1172. AutoCrit autoCrit(mCritSect);
  1173. for (auto& kv : mPendingThreads)
  1174. {
  1175. MarkFromGCThread(kv.mValue->mThread);
  1176. }
  1177. }
  1178. ///
  1179. {
  1180. AutoCrit autoCrit(mCritSect);
  1181. if (threadIdx >= mThreadList.size())
  1182. break;
  1183. thread = mThreadList[threadIdx++];
  1184. }
  1185. if (thread->mExcluded)
  1186. continue;
  1187. if (!thread->mRunning)
  1188. {
  1189. AutoCrit autoCrit(mCritSect);
  1190. BF_ASSERT(mThreadList[threadIdx - 1] == thread);
  1191. delete thread;
  1192. mThreadList.RemoveAt(threadIdx - 1);
  1193. continue;
  1194. }
  1195. BP_ZONE_F("ThreadCollect %d", thread->mThreadId);
  1196. //Beefy::DebugTimeGuard suspendTimeGuard(10, "ThreadSuspend");
  1197. DWORD result = 0;
  1198. //BFMark(thread);
  1199. //MarkObject(thread->mThread);
  1200. // If (thread->mLastGCScanIdx == mCurScanIdx), that means this is the second cycle of running through here,
  1201. // which could happen if we added another thread while scanning so we need another pass tSuspendThreadhrough to
  1202. // catch the new one
  1203. if (((mGCThread != NULL) && (thread->mThreadHandle == mGCThread)) ||
  1204. (!thread->mRunning) /*|| (thread->mLastGCScanIdx == mCurScanIdx)*/)
  1205. {
  1206. continue;
  1207. }
  1208. #ifdef BF_GC_LOG_ENABLED
  1209. // If we're writing the log from another thread then wait for it -- we'll deadlock if we pause that thread and then try to log
  1210. while (gGCLog.mWriting)
  1211. {
  1212. Sleep(20);
  1213. }
  1214. #endif
  1215. //printf("Processing Thread:%p Handle:%p\n", thread, thread->mThreadHandle);
  1216. //suspendTimeGuard.Start();
  1217. //DWORD lastError = GetLastError();
  1218. BF_LOGASSERT(result == 0);
  1219. didWork = true;
  1220. BFLOG2(GCLog::EVENT_SCAN_THREAD, (intptr)thread, (intptr)thread->mThreadId);
  1221. //
  1222. {
  1223. BP_ZONE("StackMarkableObjects");
  1224. for (auto obj : thread->mStackMarkableObjects)
  1225. {
  1226. MarkMembers(obj);
  1227. }
  1228. }
  1229. intptr regVals[128];
  1230. intptr stackPtr = 0;
  1231. BfpThreadResult threadResult;
  1232. int regValCount = 128;
  1233. ///
  1234. {
  1235. BP_ZONE("BfpThread_GetIntRegisters");
  1236. BfpThread_GetIntRegisters(thread->mThreadHandle, &stackPtr, regVals, &regValCount, &threadResult);
  1237. }
  1238. if (threadResult != BfpThreadResult_Ok)
  1239. {
  1240. mCollectFailed = true;
  1241. return false;
  1242. }
  1243. BF_ASSERT(threadResult == BfpThreadResult_Ok);
  1244. if (thread->mTEB != NULL)
  1245. {
  1246. void** threadLoadAddressMap = (void**)((_TEB*)thread->mTEB)->ThreadLocalStorage;
  1247. for (auto& tlsMember : mTLSMembers)
  1248. {
  1249. void* threadLoadAddress = threadLoadAddressMap[tlsMember.mTLSIndex];
  1250. typedef void(*MarkFunc)(void*);
  1251. MarkFunc markFunc = *(MarkFunc*)&tlsMember.mMarkFunc;
  1252. markFunc((uint8*)threadLoadAddress + tlsMember.mTLSOffset);
  1253. }
  1254. }
  1255. mQueueMarkObjects = true;
  1256. ConservativeScan(regVals, regValCount * sizeof(intptr));
  1257. intptr prevStackStart = thread->mStackStart;
  1258. thread->CalcStackStart();
  1259. thread->mLastStackPtr = stackPtr;
  1260. int length = thread->mStackStart - stackPtr;
  1261. AdjustStackPtr(stackPtr, length);
  1262. {
  1263. BP_ZONE("ConservativeScan stack");
  1264. ConservativeScan((void*)stackPtr, length);
  1265. }
  1266. mQueueMarkObjects = false;
  1267. if (mDoStackDeepMark)
  1268. {
  1269. HandlePendingGCData();
  1270. }
  1271. //suspendTimeGuard.Stop();
  1272. BF_LOGASSERT(result != -1);
  1273. if ((!mOrderedPendingGCData.IsEmpty()) || (!mOrderedPendingGCData.IsEmpty()))
  1274. {
  1275. BP_ZONE("HandlePendingGCData(Thread)");
  1276. HandlePendingGCData();
  1277. }
  1278. }
  1279. // This can be write barrier objects be from dead threads
  1280. HandlePendingGCData();
  1281. BF_FULL_MEMORY_FENCE();
  1282. mUsingThreadUnlocked = false;
  1283. return didWork;
  1284. }
  1285. int gAddedTypeCount = 0;
  1286. int gGCTypeCounts = 0;
  1287. int gGCAssemblyCount = 0;
  1288. static void GCObjFree(void* ptr)
  1289. {
  1290. Span* span = TCGetSpanAt(ptr);
  1291. if (span == NULL)
  1292. {
  1293. BF_DBG_FATAL("Bad");
  1294. tc_free(ptr);
  1295. return;
  1296. }
  1297. if (span->sizeclass == 0)
  1298. {
  1299. // Clear out all memory
  1300. intptr pageSize = (intptr)1 << kPageShift;
  1301. int spanSize = pageSize * span->length;
  1302. void* spanStart = (void*)((intptr)span->start << kPageShift);
  1303. memset(spanStart, 0, spanSize);
  1304. tc_free(ptr);
  1305. return;
  1306. }
  1307. int size = Static::sizemap()->class_to_size(span->sizeclass);
  1308. int dataOffset = (int)(sizeof(intptr) * 2);
  1309. memset((uint8*)ptr + dataOffset, 0, size - dataOffset);
  1310. // const PageID p = reinterpret_cast<uintptr_t>(ptr) >> kPageShift;
  1311. // size_t cl = Static::pageheap()->GetSizeClassIfCached(p);
  1312. // if (cl == 0)
  1313. // {
  1314. // tc_free(ptr);
  1315. // return;
  1316. // }
  1317. //
  1318. // Span* span = TCGetSpanAt(ptr);
  1319. if (span->freeingObjectsTail == NULL)
  1320. {
  1321. span->freeingObjectsTail = ptr;
  1322. *((intptr*)span->freeingObjectsTail) = 1;
  1323. }
  1324. else
  1325. {
  1326. // Increment pending size
  1327. (*((intptr*)span->freeingObjectsTail))++;
  1328. *(reinterpret_cast<void**>(ptr)) = span->freeingObjects;
  1329. }
  1330. span->freeingObjects = ptr;
  1331. }
  1332. void BFGC::DoCollect(bool doingFullGC)
  1333. {
  1334. BP_ZONE("Collect");
  1335. mThreadId = BfpThread_GetCurrentId();
  1336. mStage = 0;
  1337. gTargetFoundCount = 0;
  1338. gMarkTargetCount = 0;
  1339. gMarkTargetMutatorCount = 0;
  1340. mCurGCMarkCount = 0;
  1341. mCurMutatorMarkCount = 0;
  1342. mCurGCObjectQueuedCount = 0;
  1343. mCurMutatorObjectQueuedCount = 0;
  1344. mCurObjectDeleteCount = 0;
  1345. mCurFinalizersCalled = 0;
  1346. mCurSweepFoundCount = 0;
  1347. mCurSweepFoundPermanentCount = 0;
  1348. mCurFreedBytes = 0;
  1349. if (doingFullGC)
  1350. {
  1351. int nextMark = sCurMarkId + 1;
  1352. if (nextMark == 4)
  1353. nextMark = 1;
  1354. mCurMarkId = nextMark;
  1355. sCurMarkId = nextMark;
  1356. sAllocFlags = sCurMarkId;
  1357. }
  1358. mStage = 1;
  1359. BFLOG2(GCLog::EVENT_GC_START, sCurMarkId, BfpSystem_TickCount());
  1360. gGCTypeCounts = 0;
  1361. if (!mSkipMark)
  1362. {
  1363. BP_ZONE("MarkStatics");
  1364. MarkStatics();
  1365. RawMarkAll();
  1366. bool success = bf::System::GC::DoCallRootCallbacks();
  1367. if ((!success) && (!mHadRootError))
  1368. {
  1369. OutputDebugStringA("WARNING: GC leak detection disabled, a GC root callback disabled it\n");
  1370. mHadRootError = true;
  1371. }
  1372. }
  1373. if (!mSkipMark)
  1374. {
  1375. Beefy::AutoCrit autoCrit(mCritSect);
  1376. BP_ZONE("ExplicitRootsMark");
  1377. mQueueMarkObjects = true;
  1378. for (int i = 0; i < (int)mExplicitRoots.size(); i++)
  1379. MarkObject(mExplicitRoots[i]);
  1380. mQueueMarkObjects = false;
  1381. }
  1382. if ((doingFullGC) && (!mSkipMark))
  1383. {
  1384. //MarkObject(mGCThread);
  1385. BFMarkThreadPoolJobs();
  1386. BFMarkCOMObjects();
  1387. }
  1388. int threadIdx = 0;
  1389. // We need to turn roots black, otherwise the mutator could move a member
  1390. // of a gray root to the stack after the stack scan and we'd miss it
  1391. {
  1392. BP_ZONE("Collect - HandlePendingGCData(Roots)");
  1393. HandlePendingGCData();
  1394. }
  1395. mStage = 2;
  1396. mCurScanIdx++;
  1397. int passes = 0;
  1398. if (doingFullGC)
  1399. {
  1400. if (!mSkipMark)
  1401. {
  1402. ScanThreads();
  1403. HandlePendingGCData();
  1404. }
  1405. }
  1406. BF_ASSERT(mOrderedPendingGCData.IsEmpty());
  1407. }
  1408. void BFGC::FinishCollect()
  1409. {
  1410. //OutputDebugStrF("Collected %d objects\n", mFinalizeList.size());
  1411. if ((gBfRtDbgFlags & BfRtFlags_ObjectHasDebugFlags) == 0)
  1412. return;
  1413. mLastFreeCount = 0;
  1414. mStage = 3;
  1415. typedef std::unordered_set<bf::System::Object*> BfObjectSet;
  1416. {
  1417. // Handle any pending data from strong GCHandle references
  1418. HandlePendingGCData();
  1419. }
  1420. int finalizeDataCountFound = 0;
  1421. if (mDebugDumpState == DEBUGDUMPSTATE_WAITING_FOR_GC)
  1422. {
  1423. WriteDebugDumpState();
  1424. mDebugDumpState = DEBUGDUMPSTATE_NONE;
  1425. }
  1426. {
  1427. BP_ZONE("FreeingObjects");
  1428. void* lastPtr = NULL;
  1429. for (int i = 0; i < mFinalizeList.size(); i++)
  1430. {
  1431. bf::System::Object* obj = mFinalizeList[i];
  1432. if (obj == NULL)
  1433. continue;
  1434. BF_LOGASSERT((obj->mObjectFlags & (/*BF_OBJECTFLAG_FREED |*/ BF_OBJECTFLAG_ALLOCATED)) == BF_OBJECTFLAG_ALLOCATED);
  1435. //BF_LOGASSERT(obj > lastPtr);
  1436. lastPtr = obj;
  1437. }
  1438. {
  1439. BP_ZONE("ReleaseAtLeastNPages");
  1440. SpinLockHolder h(tcmalloc_obj::Static::pageheap_lock());
  1441. Static::pageheap()->ReleaseAtLeastNPages(256);
  1442. }
  1443. {
  1444. BP_ZONE("DecommitFromReleasedList");
  1445. Static::pageheap()->DecommitFromReleasedList(mForceDecommit);
  1446. mForceDecommit = false;
  1447. }
  1448. Dictionary<bf::System::Type*, int> sizeMap;
  1449. int objFreeSize = 0;
  1450. for (int i = 0; i < mFinalizeList.size(); i++)
  1451. {
  1452. bf::System::Object* obj = mFinalizeList[i];
  1453. if (obj == NULL)
  1454. continue;
  1455. // Removed from list already?
  1456. if ((obj->mObjectFlags & BF_OBJECTFLAG_MARK_ID_MASK) == mCurMarkId)
  1457. continue;
  1458. #ifdef BF_DEBUG
  1459. if ((obj->mObjectFlags & (/*BF_OBJECTFLAG_FREED |*/ BF_OBJECTFLAG_ALLOCATED)) != BF_OBJECTFLAG_ALLOCATED)
  1460. {
  1461. tcmalloc_obj::Span* span = TCGetSpanAt(obj);
  1462. BF_FATAL("Object corrupted");
  1463. }
  1464. #ifdef TARGET_TYPE
  1465. if (obj->mBFVData->mType == TARGET_TYPE)
  1466. {
  1467. printf("Finalizing target %p\n", obj);
  1468. }
  1469. #endif
  1470. #endif
  1471. BFLOG1(GCLog::EVENT_FREE, (intptr)obj);
  1472. // BYE!
  1473. #ifdef BF_NO_FREE_MEMORY
  1474. //obj->mObjectFlags |= BF_OBJECTFLAG_FREED;
  1475. #else
  1476. #ifdef BG_GC_TRACKPTRS
  1477. {
  1478. Beefy::AutoCrit autoCrit(gBFGC.mCritSect);
  1479. gTrackPtr.erase(gTrackPtr.find(obj));
  1480. }
  1481. #endif
  1482. int objSize = BFGetObjectSize(obj);
  1483. objFreeSize += objSize;
  1484. if (mDisplayFreedObjects)
  1485. {
  1486. // Temporarily remove object flags so GetType() won't fail
  1487. obj->mObjectFlags = BfObjectFlag_None;
  1488. bf::System::Type* type = obj->_GetType();
  1489. //auto pairVal = sizeMap.insert(std::make_pair(type, 0));
  1490. //int newSize = pairVal.first->second + objSize;
  1491. int* sizePtr = NULL;
  1492. sizeMap.TryAdd(type, NULL, &sizePtr);
  1493. *sizePtr += objSize;
  1494. //pairVal.first->second = newSize;
  1495. }
  1496. //obj->mObjectFlags = BfObjectFlag_None;
  1497. obj->mAllocCheckPtr = 0;
  1498. mLastFreeCount++;
  1499. #ifdef BF_GC_USE_OLD_FREE
  1500. tc_free(obj);
  1501. #else
  1502. GCObjFree(obj);
  1503. #endif
  1504. #ifdef BF_GC_PRINTSTATS
  1505. ::InterlockedIncrement((volatile uint32*) &gBFGC.mTotalFrees);
  1506. #endif
  1507. #endif
  1508. mCurObjectDeleteCount++;
  1509. }
  1510. if (!sizeMap.IsEmpty())
  1511. {
  1512. std::multimap<int, bf::System::Type*> orderedSizeMap;
  1513. int totalSize = 0;
  1514. for (auto& pair : sizeMap)
  1515. {
  1516. totalSize += pair.mValue;
  1517. orderedSizeMap.insert(std::make_pair(-pair.mValue, pair.mKey));
  1518. }
  1519. Beefy::String msg;
  1520. msg += Beefy::StrFormat("GC Live Count : %d\n", mCurLiveObjectCount);
  1521. msg += Beefy::StrFormat("GC Freed Count : %d\n", mLastFreeCount);
  1522. msg += Beefy::StrFormat("GC Freed Size : %dk\n", (int)(objFreeSize / 1024));
  1523. msg += "GC Objects\n";
  1524. for (auto& pair : orderedSizeMap)
  1525. {
  1526. bf::System::Type* typeName = pair.second;
  1527. msg += StrFormat(" %-37s : %dk\n", typeName->GetFullName().c_str(), (-pair.first + 1023) / 1024);
  1528. }
  1529. Beefy::OutputDebugStr(msg.c_str());
  1530. }
  1531. mBytesFreed += objFreeSize;
  1532. mBytesRequested -= objFreeSize;
  1533. mCurFreedBytes += objFreeSize;
  1534. }
  1535. #ifdef BF_GC_USE_OLD_FREE
  1536. {
  1537. BP_ZONE("TCScavenge");
  1538. tcmalloc_obj::ThreadCache::GetCacheWhichMustBePresent()->ForceScavenge();
  1539. }
  1540. #else
  1541. {
  1542. //Beefy::DebugTimeGuard suspendTimeGuard(10, "BFGC::ReleasePendingObjects");
  1543. ReleasePendingObjects();
  1544. }
  1545. #endif
  1546. mFinalizeList.Clear();
  1547. mStage = 4;
  1548. }
  1549. void BFGC::UpdateStats()
  1550. {
  1551. if (mStats == NULL)
  1552. return;
  1553. mStats->mHeapSize = TCMalloc_SystemTaken;
  1554. }
  1555. void BFGC::Run()
  1556. {
  1557. BfpThread_SetName(BfpThread_GetCurrent(), "BFGC", NULL);
  1558. uint32 lastGCTick = BFTickCount();
  1559. while (!mExiting)
  1560. {
  1561. UpdateStats();
  1562. float fullGCPeriod = mFullGCPeriod;
  1563. if ((fullGCPeriod != -1) && (mMaxPausePercentage > 0) && (!mCollectReports.IsEmpty()))
  1564. {
  1565. // When we are debugging, we can have a very long update when stepping through code,
  1566. // but otherwise try to pick an update period that keeps our pause time down
  1567. float maxExpandPeriod = BF_MAX(mFullGCPeriod, 2000);
  1568. auto& collectReport = mCollectReports.back();
  1569. fullGCPeriod = BF_MAX(fullGCPeriod, collectReport.mPausedMS * 100 / mMaxPausePercentage);
  1570. fullGCPeriod = BF_MIN(fullGCPeriod, maxExpandPeriod);
  1571. }
  1572. int waitPeriod = BF_MIN(fullGCPeriod, 100);
  1573. if (waitPeriod == 0)
  1574. waitPeriod = -1;
  1575. mCollectEvent.WaitFor(waitPeriod);
  1576. uint32 tickNow = BFTickCount();
  1577. if ((fullGCPeriod >= 0) && (tickNow - lastGCTick >= fullGCPeriod))
  1578. mCollectRequested = true;
  1579. if ((mFreeTrigger >= 0) && (mFreeSinceLastGC >= mFreeTrigger))
  1580. mCollectRequested = true;
  1581. if (!mCollectRequested)
  1582. continue;
  1583. lastGCTick = tickNow;
  1584. mCollectRequested = false;
  1585. mPerformingCollection = true;
  1586. BF_FULL_MEMORY_FENCE();
  1587. while (true)
  1588. {
  1589. mHadPendingGCDataOverflow = false;
  1590. mMaxPendingGCSize = 0;
  1591. PerformCollection();
  1592. if (!mHadPendingGCDataOverflow)
  1593. break;
  1594. mOrderedPendingGCData.Reserve(BF_MAX(mOrderedPendingGCData.mAllocSize + mOrderedPendingGCData.mAllocSize / 2, mMaxPendingGCSize + 256));
  1595. }
  1596. BF_FULL_MEMORY_FENCE();
  1597. mPerformingCollection = false;
  1598. BF_FULL_MEMORY_FENCE();
  1599. mCollectDoneEvent.Set(true);
  1600. }
  1601. mRunning = false;
  1602. }
  1603. void BFGC::RunStub(void* gc)
  1604. {
  1605. ((BFGC*)gc)->Run();
  1606. }
  1607. void BFGC::ThreadStarted(BfDbgInternalThread* thread)
  1608. {
  1609. Beefy::AutoCrit autoCrit(mCritSect);
  1610. //thread->mTCMallocObjThreadCache = tcmalloc_obj::ThreadCache::GetCache();
  1611. //mThreadList.push_back(thread);
  1612. BFLOG2(GCLog::EVENT_THREAD_STARTED, (intptr)thread, (intptr)BfpThread_GetCurrentId());
  1613. //printf("ThreadStarted: %p intern:%p TID:%d\n", thread->mThread, thread, ::GetCurrentThreadId());
  1614. }
  1615. void BFGC::ThreadStopped(BfDbgInternalThread* thread)
  1616. {
  1617. Beefy::AutoCrit autoCrit(mCritSect);
  1618. // Keep sync to avoid having the thread exit while the GC is trying to pause it,
  1619. // but do the actual cleanup from the GC's thread
  1620. //thread->mDone = true;
  1621. //printf("ThreadStopped: %p intern:%p TID:%d\n", thread->mThread, thread, ::GetCurrentThreadId());
  1622. }
  1623. void BFGC::ThreadStarted()
  1624. {
  1625. Beefy::AutoCrit autoCrit(mCritSect);
  1626. ThreadInfo* thread = new ThreadInfo();
  1627. thread->mRunning = true;
  1628. thread->mThreadHandle = BfpThread_GetCurrent();
  1629. thread->mThreadId = BfpThread_GetCurrentId();
  1630. thread->mTEB = GetTEB((HANDLE)thread->mThreadHandle);
  1631. thread->mThreadInfo = BfpThreadInfo_Create();
  1632. thread->CalcStackStart();
  1633. mThreadList.Add(thread);
  1634. mPendingThreads.Remove(thread->mThreadId);
  1635. ThreadInfo::sCurThreadInfo = thread;
  1636. }
  1637. void BFGC::ThreadStopped()
  1638. {
  1639. auto thread = ThreadInfo::sCurThreadInfo;
  1640. if (thread != NULL)
  1641. {
  1642. Beefy::AutoCrit autoCrit(mCritSect);
  1643. BF_ASSERT(thread->mStackMarkableObjects.IsEmpty());
  1644. if (!mUsingThreadUnlocked)
  1645. {
  1646. // Just delete it
  1647. mThreadList.Remove(thread);
  1648. delete thread;
  1649. }
  1650. else
  1651. {
  1652. thread->mRunning = false;
  1653. }
  1654. }
  1655. }
  1656. void BFGC::Init()
  1657. {
  1658. //ThreadStarted();
  1659. Start();
  1660. }
  1661. void BFGC::Start()
  1662. {
  1663. #ifndef BF_GC_DISABLED
  1664. mRunning = true;
  1665. #ifdef BF_DEBUG
  1666. // More stack space is needed in debug version
  1667. mGCThread = BfpThread_Create(RunStub, (void*)this, 256 * 1024, (BfpThreadCreateFlags)(BfpThreadCreateFlag_Suspended | BfpThreadCreateFlag_StackSizeReserve), &mThreadId);
  1668. #else
  1669. mGCThread = BfpThread_Create(RunStub, (void*)this, 64 * 1024, (BfpThreadCreateFlags)(BfpThreadCreateFlag_Suspended | BfpThreadCreateFlag_StackSizeReserve), &mThreadId);
  1670. #endif
  1671. BfpThread_Resume(mGCThread, NULL);
  1672. #endif
  1673. }
  1674. void BFGC::StopCollecting()
  1675. {
  1676. if (!mRunning)
  1677. return;
  1678. mExiting = true;
  1679. while (mRunning)
  1680. {
  1681. if (BfpThread_WaitFor(mGCThread, 0))
  1682. {
  1683. OutputDebugStr("BeefDbgRT not shut down gracefully!\n");
  1684. mGracelessShutdown = true;
  1685. mRunning = false;
  1686. break;
  1687. }
  1688. //BFRtLock bfLock(mEphemeronTombstone);
  1689. mWaitingForGC = true;
  1690. // Wait for current collection to finish
  1691. mCollectEvent.Set();
  1692. //Monitor::Monitor_wait(mEphemeronTombstone, 20);
  1693. mWaitingForGC = false;
  1694. }
  1695. }
  1696. void BFGC::AddStackMarkableObject(bf::System::Object* obj)
  1697. {
  1698. auto threadInfo = ThreadInfo::sCurThreadInfo;
  1699. Beefy::AutoCrit autoCrit(threadInfo->mCritSect);
  1700. threadInfo->mStackMarkableObjects.Add(obj);
  1701. }
  1702. void BFGC::RemoveStackMarkableObject(bf::System::Object* obj)
  1703. {
  1704. auto threadInfo = ThreadInfo::sCurThreadInfo;
  1705. Beefy::AutoCrit autoCrit(threadInfo->mCritSect);
  1706. int stackIdx = threadInfo->mStackMarkableObjects.LastIndexOf(obj);
  1707. BF_ASSERT(stackIdx != -1);
  1708. if (stackIdx != -1)
  1709. threadInfo->mStackMarkableObjects.RemoveAtFast(stackIdx);
  1710. }
  1711. void BFGC::AddPendingThread(BfInternalThread* internalThread)
  1712. {
  1713. if (internalThread->mThread == 0)
  1714. return;
  1715. Beefy::AutoCrit autoCrit(mCritSect);
  1716. mPendingThreads.TryAdd(internalThread->mThreadId, internalThread);
  1717. }
  1718. void BFGC::Shutdown()
  1719. {
  1720. if (mShutdown)
  1721. return;
  1722. mShutdown = true;
  1723. StopCollecting();
  1724. Beefy::AutoCrit autoCrit(mCritSect);
  1725. if (mGracelessShutdown)
  1726. return;
  1727. // Report any objects that aren't deleted
  1728. mSweepInfo.mShowAllAsLeaks = true;
  1729. Sweep();
  1730. ProcessSweepInfo();
  1731. RawShutdown();
  1732. TCMalloc_FreeAllocs();
  1733. mFinalizeList.Dispose();
  1734. mOrderedPendingGCData.Dispose();
  1735. for (auto thread : mThreadList)
  1736. thread->mStackMarkableObjects.Dispose();
  1737. }
  1738. void BFGC::InitDebugDump()
  1739. {
  1740. mDebugDumpState = DEBUGDUMPSTATE_WAITING_FOR_PREV;
  1741. mCollectEvent.Set();
  1742. while (mDebugDumpState < DEBUGDUMPSTATE_WAITING_FOR_MUTATOR)
  1743. {
  1744. //BFRtLock bfLock(mEphemeronTombstone);
  1745. //Monitor::Monitor_wait(mEphemeronTombstone, 20);
  1746. }
  1747. }
  1748. void BFGC::EndDebugDump()
  1749. {
  1750. mDebugDumpState = DEBUGDUMPSTATE_WAITING_FOR_GC;
  1751. }
  1752. intptr gFindAddrVal = 0;
  1753. void BFGC::DebugDumpLeaks()
  1754. {
  1755. CheckTcIntegrity();
  1756. BP_ZONE("DebugDump");
  1757. if (mExiting)
  1758. return;
  1759. mSkipMark = true;
  1760. Collect(false);
  1761. }
  1762. void BFGC::ObjReportHandleSpan(tcmalloc_obj::Span* span, int expectedStartPage, int& objectCount, intptr& freeSize, Beefy::Dictionary<bf::System::Type*, AllocInfo>& sizeMap)
  1763. {
  1764. if (span->location != tcmalloc_obj::Span::IN_USE)
  1765. return;
  1766. if (span->start != expectedStartPage)
  1767. {
  1768. return;
  1769. }
  1770. intptr pageSize = (intptr)1<<kPageShift;
  1771. intptr spanSize = pageSize * span->length;
  1772. void* spanStart = (void*)((intptr)span->start << kPageShift);
  1773. void* spanEnd = (void*)((intptr)spanStart + spanSize);
  1774. void* spanPtr = spanStart;
  1775. BF_LOGASSERT((spanStart >= tcmalloc_obj::PageHeap::sAddressStart) && (spanEnd <= tcmalloc_obj::PageHeap::sAddressEnd));
  1776. intptr elementSize = Static::sizemap()->ByteSizeForClass(span->sizeclass);
  1777. if (elementSize == 0)
  1778. elementSize = spanSize;
  1779. BF_LOGASSERT(elementSize >= sizeof(bf::System::Object));
  1780. while (spanPtr <= (uint8*)spanEnd - elementSize)
  1781. {
  1782. bf::System::Object* obj = (bf::System::Object*)spanPtr;
  1783. if (obj->mAllocCheckPtr != 0)
  1784. {
  1785. int objectFlags = obj->mObjectFlags;
  1786. if ((objectFlags & BF_OBJECTFLAG_DELETED) == 0)
  1787. {
  1788. bf::System::Type* type = obj->_GetType();
  1789. //auto pairVal = sizeMap.insert(std::make_pair(type, 0));
  1790. //int newSize = pairVal.first->second + elementSize;
  1791. //pairVal.first->second = newSize;
  1792. AllocInfo* sizePtr = NULL;
  1793. sizeMap.TryAdd(type, NULL, &sizePtr);
  1794. sizePtr->mObjCount++;
  1795. sizePtr->mObjSize += elementSize;
  1796. objectCount++;
  1797. }
  1798. }
  1799. else
  1800. freeSize += elementSize;
  1801. spanPtr = (void*)((intptr)spanPtr + elementSize);
  1802. }
  1803. }
  1804. void BFGC::ObjReportScan(int& objectCount, intptr& freeSize, Beefy::Dictionary<bf::System::Type*, AllocInfo>& sizeMap)
  1805. {
  1806. auto pageHeap = Static::pageheap();
  1807. if (pageHeap == NULL)
  1808. return;
  1809. #ifdef BF32
  1810. int checkPageId = (int)((uintptr)gFindAddrVal >> kPageShift);
  1811. int checkRootIdx = checkPageId >> PageHeap::PageMap::LEAF_BITS;
  1812. int checkLeafIdx = checkPageId & (PageHeap::PageMap::LEAF_LENGTH - 1);
  1813. for (int rootIdx = 0; rootIdx < PageHeap::PageMap::ROOT_LENGTH; rootIdx++)
  1814. {
  1815. PageHeap::PageMap::Leaf* rootLeaf = Static::pageheap()->pagemap_.root_[rootIdx];
  1816. if (rootLeaf == NULL)
  1817. continue;
  1818. for (int leafIdx = 0; leafIdx < PageHeap::PageMap::LEAF_LENGTH; leafIdx++)
  1819. {
  1820. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)rootLeaf->values[leafIdx];
  1821. if (span != NULL)
  1822. {
  1823. int expectedStartPage = (rootIdx * PageHeap::PageMap::LEAF_LENGTH) + leafIdx;
  1824. ObjReportHandleSpan(span, expectedStartPage, objectCount, freeSize, sizeMap);
  1825. // We may be tempted to advance by span->length here, BUT
  1826. // let us just scan all leafs becuause span data is
  1827. // sometimes invalid and a long invalid span can cause
  1828. // us to skip over an actual valid span
  1829. }
  1830. }
  1831. }
  1832. #else
  1833. for (int pageIdx1 = 0; pageIdx1 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx1++)
  1834. {
  1835. PageHeap::PageMap::Node* node1 = Static::pageheap()->pagemap_.root_->ptrs[pageIdx1];
  1836. if (node1 == NULL)
  1837. continue;
  1838. for (int pageIdx2 = 0; pageIdx2 < PageHeap::PageMap::INTERIOR_LENGTH; pageIdx2++)
  1839. {
  1840. PageHeap::PageMap::Node* node2 = node1->ptrs[pageIdx2];
  1841. if (node2 == NULL)
  1842. continue;
  1843. for (int pageIdx3 = 0; pageIdx3 < PageHeap::PageMap::LEAF_LENGTH; pageIdx3++)
  1844. {
  1845. tcmalloc_obj::Span* span = (tcmalloc_obj::Span*)node2->ptrs[pageIdx3];
  1846. if (span != NULL)
  1847. {
  1848. int expectedStartPage = ((pageIdx1 * PageHeap::PageMap::INTERIOR_LENGTH) + pageIdx2) * PageHeap::PageMap::LEAF_LENGTH + pageIdx3;
  1849. ObjReportHandleSpan(span, expectedStartPage, objectCount, freeSize, sizeMap);
  1850. // We may be tempted to advance by span->length here, BUT
  1851. // let us just scan all leafs because span data is
  1852. // sometimes invalid and a long invalid span can cause
  1853. // us to skip over an actual valid span
  1854. }
  1855. }
  1856. }
  1857. }
  1858. #endif
  1859. }
  1860. void BFGC::Report()
  1861. {
  1862. AutoCrit autoCrit(mCritSect);
  1863. CheckTcIntegrity();
  1864. BP_ZONE("Report");
  1865. Beefy::String msg;
  1866. int objectCount = 0;
  1867. #ifdef BF_GC_VERIFY_SWEEP_IDS
  1868. maxAllocNum = bf::System::Object::sCurAllocNum;
  1869. allocIdSet.clear();
  1870. #endif
  1871. int leafCheckCount = 0;
  1872. bool overflowed = false;
  1873. Dictionary<bf::System::Type*, AllocInfo> sizeMap;
  1874. intptr objFreeSize = 0;
  1875. ObjReportScan(objectCount, objFreeSize, sizeMap);
  1876. std::multimap<AllocInfo, bf::System::Type*> orderedSizeMap;
  1877. for (auto& pair : sizeMap)
  1878. {
  1879. orderedSizeMap.insert(std::make_pair(pair.mValue, pair.mKey));
  1880. }
  1881. msg += "Overall GC Summary\n";
  1882. //msg += Beefy::StrFormat(" TotalAllocs %d\n", mTotalAllocs);
  1883. //msg += Beefy::StrFormat(" TotalAllocs - TotalFrees %d\n", mTotalAllocs - mTotalFrees);
  1884. msg += Beefy::StrFormat(" System Memory Taken %dk\n", (int)(TCMalloc_SystemTaken / 1024));
  1885. //msg += Beefy::StrFormat(" BytesRequested %dk\n", (int)(mBytesRequested / 1024));
  1886. msg += Beefy::StrFormat(" Live Objects %d\n", objectCount);
  1887. msg += Beefy::StrFormat(" Last Object Freed Count %d\n", mLastFreeCount);
  1888. intptr objReportedCount = 0;
  1889. intptr rawReportedCount = 0;
  1890. intptr rawFreeSize = 0;
  1891. intptr objTotalSize = 0;
  1892. intptr rawTotalSize = 0;
  1893. gBFGC.RawReport(msg, rawFreeSize, orderedSizeMap);
  1894. for (auto& pair : orderedSizeMap)
  1895. {
  1896. objTotalSize += pair.first.mObjSize;
  1897. objReportedCount += pair.first.mObjCount;
  1898. rawTotalSize += pair.first.mRawSize;
  1899. rawReportedCount += pair.first.mRawCount;
  1900. }
  1901. msg += Beefy::StrFormat(" Obj Scanned Alloc Count %d\n", (int)(objReportedCount));
  1902. msg += Beefy::StrFormat(" Raw Scanned Alloc Count %d\n", (int)(rawReportedCount));
  1903. msg += Beefy::StrFormat(" Obj Used Memory %dk\n", (int)(objTotalSize / 1024));
  1904. msg += Beefy::StrFormat(" Raw Used Memory %dk\n", (int)(rawTotalSize / 1024));
  1905. msg += Beefy::StrFormat(" Obj Unusued Memory %dk\n", (int)(objFreeSize / 1024));
  1906. msg += Beefy::StrFormat(" Raw Unusued Memory %dk\n", (int)(rawFreeSize / 1024));
  1907. if (!mCollectReports.IsEmpty())
  1908. {
  1909. for (int reportIdx = 0; reportIdx < (int)mCollectReports.size(); reportIdx++)
  1910. {
  1911. auto& report = mCollectReports[reportIdx];
  1912. msg += Beefy::StrFormat(" Collection %d Total: %dms Paused: %dms CollectCount: %d", report.mCollectIdx, report.mTotalMS, report.mPausedMS, report.mCollectCount);
  1913. if (reportIdx > 0)
  1914. {
  1915. msg += Beefy::StrFormat(" SinceLast: %dms", report.mStartTick - mCollectReports[reportIdx - 1].mStartTick);
  1916. }
  1917. msg += "\n";
  1918. }
  1919. msg += Beefy::StrFormat(" Average Time Between Collections %dms\n", BFTickCount() / mCollectIdx);
  1920. }
  1921. msg += "Types Size Count\n";
  1922. for (auto& pair : orderedSizeMap)
  1923. {
  1924. bf::System::Type* type = pair.second;
  1925. Beefy::String typeName;
  1926. if (type == NULL)
  1927. typeName = "NULL";
  1928. else
  1929. typeName = type->GetFullName();
  1930. if (pair.first.mObjCount > 0)
  1931. msg += StrFormat("OBJ %-62s %7dk %7d\n", typeName.c_str(), (pair.first.mObjSize + 1023) / 1024, pair.first.mObjCount);
  1932. if (pair.first.mRawCount > 0)
  1933. msg += StrFormat("RAW %-62s %7dk %7d\n", typeName.c_str(), (pair.first.mRawSize + 1023) / 1024, pair.first.mRawCount);
  1934. }
  1935. Beefy::OutputDebugStr(msg.c_str());
  1936. BFGCLogWrite();
  1937. }
  1938. void BFGC::ReportTLSMember(int tlsIndex, void* ptr, void* markFunc)
  1939. {
  1940. if (mMainThreadTLSPtr == NULL)
  1941. {
  1942. _TEB* teb = NtCurrentTeb();
  1943. mMainThreadTLSPtr = teb->ThreadLocalStorage;
  1944. }
  1945. TLSMember tlsMember;
  1946. tlsMember.mTLSOffset = (uint8*)ptr - ((uint8**)mMainThreadTLSPtr)[tlsIndex];
  1947. tlsMember.mMarkFunc = markFunc;
  1948. tlsMember.mTLSIndex = tlsIndex;
  1949. mTLSMembers.Add(tlsMember);
  1950. }
  1951. void BFGC::SuspendThreads()
  1952. {
  1953. BP_ZONE("TriggerCollection - SuspendThreads");
  1954. auto curThreadId = GetCurrentThreadId();
  1955. for (auto thread : mThreadList)
  1956. {
  1957. if ((thread->mThreadId != curThreadId) && (!thread->mExcluded) && (thread->mRunning) && (thread->WantsSuspend()))
  1958. {
  1959. // We must lock this before suspending so we can access mStackMarkableObjects
  1960. // Otherwise we could deadlock
  1961. thread->mCritSect.Lock();
  1962. thread->mSuspended = true;
  1963. BfpThreadResult result;
  1964. BfpThread_Suspend(thread->mThreadHandle, &result);
  1965. ASSERT(result == BfpThreadResult_Ok);
  1966. }
  1967. }
  1968. }
  1969. void BFGC::ResumeThreads()
  1970. {
  1971. BP_ZONE("TriggerCollection - ResumeThreads");
  1972. auto curThreadId = GetCurrentThreadId();
  1973. for (auto thread : mThreadList)
  1974. {
  1975. if ((thread->mThreadId != curThreadId) && (thread->mSuspended) && (thread->mRunning) && (thread->WantsSuspend()))
  1976. {
  1977. // Previously locked in SuspendThreads
  1978. thread->mCritSect.Unlock();
  1979. thread->mSuspended = false;
  1980. BfpThread_Resume(thread->mThreadHandle, NULL);
  1981. }
  1982. }
  1983. }
  1984. void BFGC::PerformCollection()
  1985. {
  1986. BP_ZONE("TriggerCollection");
  1987. if (mCollectIdx == 0)
  1988. {
  1989. // 'Prime' register capture
  1990. intptr regVals[128];
  1991. intptr stackPtr = 0;
  1992. BfpThreadResult threadResult;
  1993. int regValCount = 128;
  1994. BfpThread_GetIntRegisters(BfpThread_GetCurrent(), &stackPtr, regVals, &regValCount, &threadResult);
  1995. }
  1996. int prevMarkId = mCurMarkId;
  1997. DWORD startTick = BFTickCount();
  1998. CollectReport collectReport;
  1999. collectReport.mCollectIdx = mCollectIdx;
  2000. collectReport.mStartTick = startTick;
  2001. #ifndef BF_MINGW
  2002. //_CrtCheckMemory();
  2003. #endif
  2004. #ifdef BF_GC_INCREMENTAL
  2005. mFullGCTriggered = true;
  2006. mForceDecommit |= forceDecommit;
  2007. gBFGC.mCollectEvent.Set();
  2008. #else
  2009. Beefy::AutoCrit autoCrit(mCritSect);
  2010. mAllocSinceLastGC = 0;
  2011. mCollectFailed = false;
  2012. // This was old "emergency" debugging code to make sure we weren't doing a malloc in the GC code,
  2013. // but it's a multi-threaded race condition
  2014. /*uint8* mallocAddr = (uint8*)&malloc;
  2015. DWORD oldProtect = 0;
  2016. BOOL worked = ::VirtualProtect(mallocAddr, 1, PAGE_EXECUTE_READWRITE, &oldProtect);
  2017. uint8 oldCode = *mallocAddr;
  2018. *mallocAddr = 0xCC;*/
  2019. mOrderedPendingGCData.Reserve(BF_GC_MAX_PENDING_OBJECT_COUNT);
  2020. uint32 suspendStartTick = BFTickCount();
  2021. SuspendThreads();
  2022. #ifndef BF_MINGW
  2023. //_CrtCheckMemory();
  2024. #endif
  2025. DoCollect(true);
  2026. #ifndef BF_MINGW
  2027. //_CrtCheckMemory();
  2028. #endif
  2029. //*mallocAddr = oldCode;
  2030. #ifdef BF_GC_EMPTYSCAN
  2031. {
  2032. mSweepInfo.mEmptyScan = true;
  2033. Sweep();
  2034. mSweepInfo.mEmptyScan = false;
  2035. }
  2036. #endif
  2037. mFreeSinceLastGC = 0;
  2038. BFLOG2(GCLog::EVENT_GC_UNFREEZE, sCurMarkId, BfpSystem_TickCount());
  2039. #ifndef BF_GC_DEBUGSWEEP
  2040. ResumeThreads();
  2041. #endif
  2042. collectReport.mPausedMS = BFTickCount() - suspendStartTick;
  2043. //BFGCLogWrite();
  2044. mFinalizeList.Clear();
  2045. Sweep();
  2046. #ifdef BF_GC_DEBUGSWEEP
  2047. ResumeThreads();
  2048. #endif
  2049. collectReport.mCollectCount = (int)mFinalizeList.size();
  2050. FinishCollect();
  2051. ReleasePendingObjects();
  2052. ProcessSweepInfo();
  2053. BFLOG2(GCLog::EVENT_GC_DONE, mCurGCMarkCount, mHadPendingGCDataOverflow ? 1 : 0);
  2054. collectReport.mTotalMS = BFTickCount() - startTick;
  2055. // while (mCollectReports.size() > 4)
  2056. // mCollectReports.RemoveAt(0);
  2057. while (mCollectReports.size() > 10)
  2058. mCollectReports.RemoveAt(0);
  2059. mCollectReports.Add(collectReport);
  2060. mCollectIdx++;
  2061. #endif
  2062. }
  2063. void BFGC::Collect(bool async)
  2064. {
  2065. mCollectRequested = true;
  2066. BF_FULL_MEMORY_FENCE();
  2067. if (async)
  2068. {
  2069. mCollectEvent.Set();
  2070. }
  2071. else
  2072. {
  2073. if (mPerformingCollection)
  2074. mCollectDoneEvent.WaitFor(0); // Wait for previous to finish
  2075. mCollectDoneEvent.Reset();
  2076. mCollectEvent.Set();
  2077. mCollectDoneEvent.WaitFor();
  2078. }
  2079. }
  2080. void BFGC::WriteDebugDumpState()
  2081. {
  2082. struct DebugInfo
  2083. {
  2084. bf::System::Type* mType;
  2085. int mCount;
  2086. int mSize;
  2087. int mAllocSize;
  2088. DebugInfo()
  2089. {
  2090. mType = NULL;
  2091. mCount = 0;
  2092. mSize = 0;
  2093. mAllocSize = 0;
  2094. }
  2095. };
  2096. std::vector<DebugInfo> debugInfoVector;
  2097. for (int i = 0; i < (int)mFinalizeList.size(); i++)
  2098. {
  2099. bf::System::Object* obj = (bf::System::Object*) mFinalizeList[i];
  2100. if ((bf::System::Type*)obj->GetTypeSafe() != NULL)
  2101. {
  2102. if ((uintptr)obj->GetTypeSafe() <= 1024U*1024U)
  2103. {
  2104. while ((int) debugInfoVector.size() <= 0)
  2105. debugInfoVector.push_back(DebugInfo());
  2106. DebugInfo* debugInfo = &debugInfoVector[0];
  2107. debugInfo->mType = NULL;
  2108. debugInfo->mCount++;
  2109. int objSize = BFGetObjectSize(obj);
  2110. debugInfo->mSize += objSize;
  2111. debugInfo->mAllocSize += objSize;
  2112. //debugInfo->mAllocSize += MallocExtension::instance()->GetEstimatedAllocatedSize(objSize);
  2113. }
  2114. else
  2115. {
  2116. //const bf::System::Type* bfTypeRootData = ((bf::System::Type*)obj->GetTypeSafe())->mTypeRootData;
  2117. bf::System::Type* bfType = obj->GetTypeSafe();
  2118. while ((int) debugInfoVector.size() <= bfType->mTypeId)
  2119. debugInfoVector.push_back(DebugInfo());
  2120. DebugInfo* debugInfo = &debugInfoVector[bfType->mTypeId];
  2121. debugInfo->mType = obj->GetTypeSafe();
  2122. debugInfo->mCount++;
  2123. int objSize = BFGetObjectSize(obj);
  2124. debugInfo->mSize += objSize;
  2125. debugInfo->mAllocSize += objSize;
  2126. //debugInfo->mAllocSize += MallocExtension::instance()->GetEstimatedAllocatedSize(objSize);
  2127. }
  2128. }
  2129. }
  2130. typedef std::multimap<int, DebugInfo*> DebugInfoMap;
  2131. DebugInfoMap debugInfoMap;
  2132. for (int i = 0; i < (int) debugInfoVector.size(); i++)
  2133. {
  2134. DebugInfo* debugInfo = &debugInfoVector[i];
  2135. if (debugInfo->mCount > 0)
  2136. debugInfoMap.insert(DebugInfoMap::value_type(-debugInfo->mSize, debugInfo));
  2137. }
  2138. Beefy::String dbgStr = "\n\nBeefyRT GC DebugDump:\n";
  2139. int countTotal = 0;
  2140. int sizeTotal = 0;
  2141. int allocSizeTotal = 0;
  2142. DebugInfoMap::iterator itr = debugInfoMap.begin();
  2143. while (itr != debugInfoMap.end())
  2144. {
  2145. DebugInfo* debugInfo = itr->second;
  2146. Beefy::String lineStr = StrFormat("%8d %8dk %8dk ", debugInfo->mCount, (debugInfo->mSize + 1023) / 1024, (debugInfo->mAllocSize + 1023) / 1024);
  2147. Beefy::String typeName;
  2148. if (debugInfo->mType != NULL)
  2149. typeName = debugInfo->mType->GetFullName();
  2150. else
  2151. typeName = "???";
  2152. lineStr += typeName;
  2153. dbgStr += lineStr += "\n";
  2154. countTotal += debugInfo->mCount;
  2155. sizeTotal += debugInfo->mSize;
  2156. allocSizeTotal += debugInfo->mAllocSize;
  2157. ++itr;
  2158. }
  2159. dbgStr += StrFormat("%8d %8dk %8dk TOTAL", countTotal, (sizeTotal + 1023)/1024, (allocSizeTotal + 1023)/1024);
  2160. OutputDebugStrF(dbgStr.c_str());
  2161. }
  2162. #ifdef BF_DEBUG
  2163. //#define NO_QUEUE_OBJECTS
  2164. #endif
  2165. #ifdef BF_GC_LOG_ENABLED
  2166. static bf::System::Object* gMarkingObject[8192];
  2167. #endif
  2168. void BFGC::MarkFromGCThread(bf::System::Object* obj)
  2169. {
  2170. if (obj == NULL)
  2171. return;
  2172. //BP_ZONE("MarkFromGCThread");
  2173. void* addr = obj;
  2174. if ((addr < tcmalloc_obj::PageHeap::sAddressStart) || (addr >= tcmalloc_obj::PageHeap::sAddressEnd))
  2175. return;
  2176. tcmalloc_obj::Span* span = TCGetSpanAt(obj);
  2177. if (span == NULL)
  2178. return;
  2179. if (span->location != tcmalloc_obj::Span::IN_USE)
  2180. return;
  2181. intptr pageSize = (intptr) 1 << kPageShift;
  2182. intptr spanSize = pageSize * span->length;
  2183. void* spanStart = (void*)((intptr)span->start << kPageShift);
  2184. void* spanEnd = (void*)((intptr)spanStart + spanSize);
  2185. if ((addr < spanStart) || (addr > (uint8*)spanEnd - sizeof(bf::System::Object)))
  2186. return;
  2187. // Is it already marked? Ignore.
  2188. if ((obj->mObjectFlags & BF_OBJECTFLAG_MARK_ID_MASK) == mCurMarkId)
  2189. return;
  2190. // Don't do any processing of non-allocated objects (like string literals), or append allocs
  2191. if ((obj->mObjectFlags & BF_OBJECTFLAG_ALLOCATED) == 0)
  2192. return;
  2193. if (obj->mAllocCheckPtr == 0) // It IS in the heap but not allocated
  2194. return;
  2195. bool curIsDeleted = false;
  2196. if (mMarkingDeleted)
  2197. {
  2198. if ((obj->mObjectFlags & BF_OBJECTFLAG_DELETED) == 0)
  2199. {
  2200. // Don't allow a deleted object to mark a non-deleted object-
  2201. // That should be handled as a LEAK if there aren't any non-deleted objects referencing it
  2202. return;
  2203. }
  2204. }
  2205. intptr elementSize = Static::sizemap()->ByteSizeForClass(span->sizeclass);
  2206. // Large alloc
  2207. if (elementSize == 0)
  2208. {
  2209. if (obj != (bf::System::Object*)spanStart)
  2210. return;
  2211. }
  2212. else
  2213. {
  2214. void* maskedAddr = addr;
  2215. maskedAddr = (uint8*)spanStart + (((uint8*)maskedAddr - (uint8*)spanStart) / elementSize * elementSize);
  2216. if (obj != (bf::System::Object*)maskedAddr)
  2217. return;
  2218. }
  2219. #ifndef BF_GC_DISABLED
  2220. BF_LOGASSERT(mThreadId == BfpThread_GetCurrentId());
  2221. BF_LOGASSERT(obj->mClassVData != 0);
  2222. #ifdef TARGET_TYPE
  2223. if (obj->mBFVData->mType == TARGET_TYPE)
  2224. {
  2225. gMarkTargetCount++;
  2226. printf("Marking target %p\n", obj);
  2227. }
  2228. #endif
  2229. #ifdef BF_GC_LOG_ENABLED
  2230. bf::System::Object* parentObj = NULL;
  2231. if (mMarkDepthCount > 0)
  2232. parentObj = gMarkingObject[mMarkDepthCount-1];
  2233. BFLOG3(GCLog::EVENT_MARK, (intptr)obj, obj->mObjectFlags, (intptr)parentObj);
  2234. #endif
  2235. obj->mObjectFlags = (BfObjectFlags)((obj->mObjectFlags & ~BF_OBJECTFLAG_MARK_ID_MASK) | mCurMarkId);
  2236. mCurGCMarkCount++;
  2237. mCurGCObjectQueuedCount++;
  2238. mCurPendingGCSize++;
  2239. bool allowQueue = true;
  2240. if (mOrderedPendingGCData.GetFreeCount() > 0)
  2241. {
  2242. mOrderedPendingGCData.Add(obj);
  2243. }
  2244. else
  2245. {
  2246. // No more room left -- we can't queue...
  2247. mHadPendingGCDataOverflow = true;
  2248. mCollectFailed = true;
  2249. }
  2250. #endif
  2251. }
  2252. void BFGC::SetAutoCollectPeriod(int periodMS)
  2253. {
  2254. mFullGCPeriod = periodMS;
  2255. mCollectEvent.Set();
  2256. }
  2257. void BFGC::SetCollectFreeThreshold(int freeBytes)
  2258. {
  2259. mFreeTrigger = freeBytes;
  2260. mCollectEvent.Set();
  2261. }
  2262. void BFGC::SetMaxPausePercentage(int maxPausePercentage)
  2263. {
  2264. mMaxPausePercentage = maxPausePercentage;
  2265. mCollectEvent.Set();
  2266. }
  2267. void BFGC::SetMaxRawDeferredObjectFreePercentage(intptr maxPercentage)
  2268. {
  2269. mMaxRawDeferredObjectFreePercentage = maxPercentage;
  2270. }
  2271. void BFGC::ExcludeThreadId(intptr threadId)
  2272. {
  2273. Beefy::AutoCrit autoCrit(mCritSect);
  2274. for (auto thread : mThreadList)
  2275. {
  2276. if (thread->mThreadId == threadId)
  2277. thread->mExcluded = true;
  2278. }
  2279. }
  2280. using namespace bf::System;
  2281. void GC::Run()
  2282. {
  2283. #ifdef BF_GC_INCREMENTAL
  2284. gBFGC.Run();
  2285. #endif
  2286. }
  2287. void GC::Init()
  2288. {
  2289. gBFGC.Init();
  2290. }
  2291. void GC::ReportTLSMember(intptr tlsIndex, void* ptr, void* markFunc)
  2292. {
  2293. gBFGC.ReportTLSMember((int)tlsIndex, ptr, markFunc);
  2294. }
  2295. void GC::StopCollecting()
  2296. {
  2297. gBFGC.StopCollecting();
  2298. }
  2299. void GC::AddStackMarkableObject(Object* obj)
  2300. {
  2301. gBFGC.AddStackMarkableObject(obj);
  2302. }
  2303. void GC::AddPendingThread(void* internalThreadInfo)
  2304. {
  2305. gBFGC.AddPendingThread((BfInternalThread*)internalThreadInfo);
  2306. }
  2307. void GC::RemoveStackMarkableObject(Object* obj)
  2308. {
  2309. gBFGC.RemoveStackMarkableObject(obj);
  2310. }
  2311. void GC::Shutdown()
  2312. {
  2313. gBFGC.Shutdown();
  2314. }
  2315. void GC::Collect(bool async)
  2316. {
  2317. gBFGC.Collect(async);
  2318. }
  2319. void GC::Report()
  2320. {
  2321. gBFGC.Report();
  2322. }
  2323. void GC::Mark(Object* obj)
  2324. {
  2325. gBFGC.MarkFromGCThread(obj);
  2326. }
  2327. void GC::Mark(void* ptr, intptr size)
  2328. {
  2329. gBFGC.ConservativeScan(ptr, (int)size);
  2330. }
  2331. void GC::DebugDumpLeaks()
  2332. {
  2333. gBFGC.DebugDumpLeaks();
  2334. }
  2335. void GC::SetAutoCollectPeriod(intptr periodMS)
  2336. {
  2337. gBFGC.SetAutoCollectPeriod((int)periodMS);
  2338. }
  2339. void GC::SetCollectFreeThreshold(intptr freeBytes)
  2340. {
  2341. gBFGC.SetCollectFreeThreshold((int)freeBytes);
  2342. }
  2343. BFRT_EXPORT void bf::System::GC::SetMaxPausePercentage(intptr maxPausePercentage)
  2344. {
  2345. gBFGC.SetMaxPausePercentage(maxPausePercentage);
  2346. }
  2347. BFRT_EXPORT void bf::System::GC::SetMaxRawDeferredObjectFreePercentage(intptr maxPercentage)
  2348. {
  2349. gBFGC.SetMaxRawDeferredObjectFreePercentage(maxPercentage);
  2350. }
  2351. BFRT_EXPORT void bf::System::GC::ExcludeThreadId(intptr threadId)
  2352. {
  2353. gBFGC.ExcludeThreadId(threadId);
  2354. }
  2355. #else // BF_GC_SUPPORTED
  2356. void* BfObjectAllocate(intptr size, bf::System::Type* type)
  2357. {
  2358. BF_FATAL("Not supported");
  2359. return NULL;
  2360. }
  2361. using namespace bf::System;
  2362. void GC::Run()
  2363. {
  2364. #ifdef BF_GC_INCREMENTAL
  2365. gBFGC.Run();
  2366. #endif
  2367. }
  2368. void GC::Init()
  2369. {
  2370. }
  2371. void GC::ReportTLSMember(intptr tlsIndex, void* ptr, void* markFunc)
  2372. {
  2373. }
  2374. void GC::Shutdown()
  2375. {
  2376. }
  2377. void GC::Collect(bool async)
  2378. {
  2379. }
  2380. void GC::Report()
  2381. {
  2382. }
  2383. /*void GC::Mark(Object* obj)
  2384. {
  2385. }*/
  2386. void GC::Mark(void* ptr, intptr size)
  2387. {
  2388. }
  2389. void GC::DebugDumpLeaks()
  2390. {
  2391. }
  2392. void GC::SetAutoCollectPeriod(intptr periodMS)
  2393. {
  2394. }
  2395. void GC::SetCollectFreeThreshold(intptr freeBytes)
  2396. {
  2397. }
  2398. #endif