misc.c 79 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582
  1. /*
  2. * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
  3. * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
  4. * Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved.
  5. *
  6. * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
  7. * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
  8. *
  9. * Permission is hereby granted to use or copy this program
  10. * for any purpose, provided the above notices are retained on all copies.
  11. * Permission to modify the code and to distribute modified code is granted,
  12. * provided the above notices are retained, and a notice that the code was
  13. * modified is included with the above copyright notice.
  14. */
  15. #include "private/gc_pmark.h"
  16. #include "private/gc_priv.h"
  17. #include <stdio.h>
  18. #include <limits.h>
  19. #include <stdarg.h>
  20. #ifndef MSWINCE
  21. # include <signal.h>
  22. #endif
  23. #ifdef GC_SOLARIS_THREADS
  24. # include <sys/syscall.h>
  25. #endif
  26. #if defined(MSWIN32) || defined(MSWINCE) \
  27. || (defined(CYGWIN32) && defined(GC_READ_ENV_FILE))
  28. # ifndef WIN32_LEAN_AND_MEAN
  29. # define WIN32_LEAN_AND_MEAN 1
  30. # endif
  31. # define NOSERVICE
  32. # include <windows.h>
  33. #ifdef MSWINRT
  34. # include <windows.storage.h>
  35. // This API is defined in roapi.h, but we cannot include it here since it does not compile in C -_-
  36. DECLSPEC_IMPORT HRESULT WINAPI RoGetActivationFactory(HSTRING activatableClassId, REFIID iid, void** factory);
  37. #endif
  38. #endif
  39. #if defined(UNIX_LIKE) || defined(CYGWIN32) || defined(SYMBIAN)
  40. # include <fcntl.h>
  41. # include <sys/types.h>
  42. # include <sys/stat.h>
  43. #endif
  44. #ifdef NONSTOP
  45. # include <floss.h>
  46. #endif
  47. #ifdef THREADS
  48. # ifdef PCR
  49. # include "il/PCR_IL.h"
  50. GC_INNER PCR_Th_ML GC_allocate_ml;
  51. # elif defined(SN_TARGET_PSP2)
  52. GC_INNER WapiMutex GC_allocate_ml_PSP2 = { 0, NULL };
  53. # elif defined(GC_PTHREAD_MUTEX) || defined(SN_TARGET_PS3)
  54. # include <pthread.h>
  55. GC_INNER pthread_mutex_t GC_allocate_ml;
  56. # endif
  57. /* For other platforms with threads, the lock and possibly */
  58. /* GC_lock_holder variables are defined in the thread support code. */
  59. #endif /* THREADS */
  60. #ifdef DYNAMIC_LOADING
  61. /* We need to register the main data segment. Returns TRUE unless */
  62. /* this is done implicitly as part of dynamic library registration. */
  63. # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data()
  64. #elif defined(GC_DONT_REGISTER_MAIN_STATIC_DATA)
  65. # define GC_REGISTER_MAIN_STATIC_DATA() FALSE
  66. #else
  67. /* Don't unnecessarily call GC_register_main_static_data() in case */
  68. /* dyn_load.c isn't linked in. */
  69. # define GC_REGISTER_MAIN_STATIC_DATA() TRUE
  70. #endif
  71. #ifdef NEED_CANCEL_DISABLE_COUNT
  72. __thread unsigned char GC_cancel_disable_count = 0;
  73. #endif
  74. GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */;
  75. GC_INNER GC_bool GC_debugging_started = FALSE;
  76. /* defined here so we don't have to load dbg_mlc.o */
  77. ptr_t GC_stackbottom = 0;
  78. #ifdef IA64
  79. ptr_t GC_register_stackbottom = 0;
  80. #endif
  81. int GC_dont_gc = FALSE;
  82. int GC_dont_precollect = FALSE;
  83. GC_bool GC_quiet = 0; /* used also in pcr_interface.c */
  84. #if !defined(NO_CLOCK) || !defined(SMALL_CONFIG)
  85. int GC_print_stats = 0;
  86. #endif
  87. #ifdef GC_PRINT_BACK_HEIGHT
  88. GC_INNER GC_bool GC_print_back_height = TRUE;
  89. #else
  90. GC_INNER GC_bool GC_print_back_height = FALSE;
  91. #endif
  92. #ifndef NO_DEBUGGING
  93. # ifdef GC_DUMP_REGULARLY
  94. GC_INNER GC_bool GC_dump_regularly = TRUE;
  95. /* Generate regular debugging dumps. */
  96. # else
  97. GC_INNER GC_bool GC_dump_regularly = FALSE;
  98. # endif
  99. # ifndef NO_CLOCK
  100. STATIC CLOCK_TYPE GC_init_time;
  101. /* The time that the GC was initialized at. */
  102. # endif
  103. #endif /* !NO_DEBUGGING */
  104. #ifdef KEEP_BACK_PTRS
  105. GC_INNER long GC_backtraces = 0;
  106. /* Number of random backtraces to generate for each GC. */
  107. #endif
  108. #ifdef FIND_LEAK
  109. int GC_find_leak = 1;
  110. #else
  111. int GC_find_leak = 0;
  112. #endif
  113. #ifndef SHORT_DBG_HDRS
  114. # ifdef GC_FINDLEAK_DELAY_FREE
  115. GC_INNER GC_bool GC_findleak_delay_free = TRUE;
  116. # else
  117. GC_INNER GC_bool GC_findleak_delay_free = FALSE;
  118. # endif
  119. #endif /* !SHORT_DBG_HDRS */
  120. #ifdef ALL_INTERIOR_POINTERS
  121. int GC_all_interior_pointers = 1;
  122. #else
  123. int GC_all_interior_pointers = 0;
  124. #endif
  125. #ifdef FINALIZE_ON_DEMAND
  126. int GC_finalize_on_demand = 1;
  127. #else
  128. int GC_finalize_on_demand = 0;
  129. #endif
  130. #ifdef JAVA_FINALIZATION
  131. int GC_java_finalization = 1;
  132. #else
  133. int GC_java_finalization = 0;
  134. #endif
  135. /* All accesses to it should be synchronized to avoid data races. */
  136. GC_finalizer_notifier_proc GC_finalizer_notifier =
  137. (GC_finalizer_notifier_proc)0;
  138. #ifdef GC_FORCE_UNMAP_ON_GCOLLECT
  139. /* Has no effect unless USE_MUNMAP. */
  140. /* Has no effect on implicitly-initiated garbage collections. */
  141. GC_INNER GC_bool GC_force_unmap_on_gcollect = TRUE;
  142. #else
  143. GC_INNER GC_bool GC_force_unmap_on_gcollect = FALSE;
  144. #endif
  145. #ifndef GC_LARGE_ALLOC_WARN_INTERVAL
  146. # define GC_LARGE_ALLOC_WARN_INTERVAL 5
  147. #endif
  148. GC_INNER long GC_large_alloc_warn_interval = GC_LARGE_ALLOC_WARN_INTERVAL;
  149. /* Interval between unsuppressed warnings. */
  150. STATIC void * GC_CALLBACK GC_default_oom_fn(
  151. size_t bytes_requested GC_ATTR_UNUSED)
  152. {
  153. return(0);
  154. }
  155. /* All accesses to it should be synchronized to avoid data races. */
  156. GC_oom_func GC_oom_fn = GC_default_oom_fn;
  157. #ifdef CAN_HANDLE_FORK
  158. # ifdef HANDLE_FORK
  159. GC_INNER int GC_handle_fork = 1;
  160. /* The value is examined by GC_thr_init. */
  161. # else
  162. GC_INNER int GC_handle_fork = FALSE;
  163. # endif
  164. #elif !defined(HAVE_NO_FORK)
  165. /* Same as above but with GC_CALL calling conventions. */
  166. GC_API void GC_CALL GC_atfork_prepare(void)
  167. {
  168. # ifdef THREADS
  169. ABORT("fork() handling unsupported");
  170. # endif
  171. }
  172. GC_API void GC_CALL GC_atfork_parent(void)
  173. {
  174. /* empty */
  175. }
  176. GC_API void GC_CALL GC_atfork_child(void)
  177. {
  178. /* empty */
  179. }
  180. #endif /* !CAN_HANDLE_FORK && !HAVE_NO_FORK */
  181. /* Overrides the default automatic handle-fork mode. Has effect only */
  182. /* if called before GC_INIT. */
  183. GC_API void GC_CALL GC_set_handle_fork(int value GC_ATTR_UNUSED)
  184. {
  185. # ifdef CAN_HANDLE_FORK
  186. if (!GC_is_initialized)
  187. GC_handle_fork = value >= -1 ? value : 1;
  188. /* Map all negative values except for -1 to a positive one. */
  189. # elif defined(THREADS) || (defined(DARWIN) && defined(MPROTECT_VDB))
  190. if (!GC_is_initialized && value) {
  191. # ifndef SMALL_CONFIG
  192. GC_init(); /* just to initialize GC_stderr */
  193. # endif
  194. ABORT("fork() handling unsupported");
  195. }
  196. # else
  197. /* No at-fork handler is needed in the single-threaded mode. */
  198. # endif
  199. }
  200. /* Set things up so that GC_size_map[i] >= granules(i), */
  201. /* but not too much bigger */
  202. /* and so that size_map contains relatively few distinct entries */
  203. /* This was originally stolen from Russ Atkinson's Cedar */
  204. /* quantization algorithm (but we precompute it). */
  205. STATIC void GC_init_size_map(void)
  206. {
  207. size_t i;
  208. /* Map size 0 to something bigger. */
  209. /* This avoids problems at lower levels. */
  210. GC_size_map[0] = 1;
  211. for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) {
  212. GC_size_map[i] = ROUNDED_UP_GRANULES(i);
  213. # ifndef _MSC_VER
  214. GC_ASSERT(GC_size_map[i] < TINY_FREELISTS);
  215. /* Seems to tickle bug in VC++ 2008 for AMD64 */
  216. # endif
  217. }
  218. /* We leave the rest of the array to be filled in on demand. */
  219. }
  220. /*
  221. * The following is a gross hack to deal with a problem that can occur
  222. * on machines that are sloppy about stack frame sizes, notably SPARC.
  223. * Bogus pointers may be written to the stack and not cleared for
  224. * a LONG time, because they always fall into holes in stack frames
  225. * that are not written. We partially address this by clearing
  226. * sections of the stack whenever we get control.
  227. */
  228. #ifndef SMALL_CLEAR_SIZE
  229. # define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */
  230. #endif
  231. #if defined(ALWAYS_SMALL_CLEAR_STACK) || defined(STACK_NOT_SCANNED)
  232. GC_API void * GC_CALL GC_clear_stack(void *arg)
  233. {
  234. # ifndef STACK_NOT_SCANNED
  235. word volatile dummy[SMALL_CLEAR_SIZE];
  236. BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
  237. # endif
  238. return arg;
  239. }
  240. #else
  241. # ifdef THREADS
  242. # define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */
  243. # else
  244. STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */
  245. STATIC ptr_t GC_min_sp = NULL;
  246. /* Coolest stack pointer value from which */
  247. /* we've already cleared the stack. */
  248. STATIC ptr_t GC_high_water = NULL;
  249. /* "hottest" stack pointer value we have seen */
  250. /* recently. Degrades over time. */
  251. STATIC word GC_bytes_allocd_at_reset = 0;
  252. # define DEGRADE_RATE 50
  253. # endif
  254. # if defined(ASM_CLEAR_CODE)
  255. void *GC_clear_stack_inner(void *, ptr_t);
  256. # else
  257. /* Clear the stack up to about limit. Return arg. This function */
  258. /* is not static because it could also be erroneously defined in .S */
  259. /* file, so this error would be caught by the linker. */
  260. void *GC_clear_stack_inner(void *arg,
  261. # if defined(__APPLE_CC__) && !GC_CLANG_PREREQ(6, 0)
  262. volatile /* to workaround some bug */
  263. # endif
  264. ptr_t limit)
  265. {
  266. # define CLEAR_SIZE 213 /* granularity */
  267. volatile word dummy[CLEAR_SIZE];
  268. BZERO((/* no volatile */ void *)dummy, sizeof(dummy));
  269. if ((word)GC_approx_sp() COOLER_THAN (word)limit) {
  270. (void)GC_clear_stack_inner(arg, limit);
  271. }
  272. /* Make sure the recursive call is not a tail call, and the bzero */
  273. /* call is not recognized as dead code. */
  274. GC_noop1((word)dummy);
  275. return(arg);
  276. }
  277. # endif /* !ASM_CLEAR_CODE */
  278. # ifdef THREADS
  279. /* Used to occasionally clear a bigger chunk. */
  280. /* TODO: Should be more random than it is ... */
  281. GC_ATTR_NO_SANITIZE_THREAD
  282. static unsigned next_random_no(void)
  283. {
  284. static unsigned random_no = 0;
  285. return ++random_no % 13;
  286. }
  287. # endif /* THREADS */
  288. /* Clear some of the inaccessible part of the stack. Returns its */
  289. /* argument, so it can be used in a tail call position, hence clearing */
  290. /* another frame. */
  291. GC_API void * GC_CALL GC_clear_stack(void *arg)
  292. {
  293. ptr_t sp = GC_approx_sp(); /* Hotter than actual sp */
  294. # ifdef THREADS
  295. word volatile dummy[SMALL_CLEAR_SIZE];
  296. # endif
  297. # define SLOP 400
  298. /* Extra bytes we clear every time. This clears our own */
  299. /* activation record, and should cause more frequent */
  300. /* clearing near the cold end of the stack, a good thing. */
  301. # define GC_SLOP 4000
  302. /* We make GC_high_water this much hotter than we really saw */
  303. /* it, to cover for GC noise etc. above our current frame. */
  304. # define CLEAR_THRESHOLD 100000
  305. /* We restart the clearing process after this many bytes of */
  306. /* allocation. Otherwise very heavily recursive programs */
  307. /* with sparse stacks may result in heaps that grow almost */
  308. /* without bounds. As the heap gets larger, collection */
  309. /* frequency decreases, thus clearing frequency would decrease, */
  310. /* thus more junk remains accessible, thus the heap gets */
  311. /* larger ... */
  312. # ifdef THREADS
  313. if (next_random_no() == 0) {
  314. ptr_t limit = sp;
  315. MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word));
  316. limit = (ptr_t)((word)limit & ~0xf);
  317. /* Make it sufficiently aligned for assembly */
  318. /* implementations of GC_clear_stack_inner. */
  319. return GC_clear_stack_inner(arg, limit);
  320. }
  321. BZERO((void *)dummy, SMALL_CLEAR_SIZE*sizeof(word));
  322. # else
  323. if (GC_gc_no > GC_stack_last_cleared) {
  324. /* Start things over, so we clear the entire stack again */
  325. if (GC_stack_last_cleared == 0)
  326. GC_high_water = (ptr_t)GC_stackbottom;
  327. GC_min_sp = GC_high_water;
  328. GC_stack_last_cleared = GC_gc_no;
  329. GC_bytes_allocd_at_reset = GC_bytes_allocd;
  330. }
  331. /* Adjust GC_high_water */
  332. MAKE_COOLER(GC_high_water, WORDS_TO_BYTES(DEGRADE_RATE) + GC_SLOP);
  333. if ((word)sp HOTTER_THAN (word)GC_high_water) {
  334. GC_high_water = sp;
  335. }
  336. MAKE_HOTTER(GC_high_water, GC_SLOP);
  337. {
  338. ptr_t limit = GC_min_sp;
  339. MAKE_HOTTER(limit, SLOP);
  340. if ((word)sp COOLER_THAN (word)limit) {
  341. limit = (ptr_t)((word)limit & ~0xf);
  342. /* Make it sufficiently aligned for assembly */
  343. /* implementations of GC_clear_stack_inner. */
  344. GC_min_sp = sp;
  345. return GC_clear_stack_inner(arg, limit);
  346. }
  347. }
  348. if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) {
  349. /* Restart clearing process, but limit how much clearing we do. */
  350. GC_min_sp = sp;
  351. MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4);
  352. if ((word)GC_min_sp HOTTER_THAN (word)GC_high_water)
  353. GC_min_sp = GC_high_water;
  354. GC_bytes_allocd_at_reset = GC_bytes_allocd;
  355. }
  356. # endif
  357. return arg;
  358. }
  359. #endif /* !ALWAYS_SMALL_CLEAR_STACK && !STACK_NOT_SCANNED */
  360. /* Return a pointer to the base address of p, given a pointer to a */
  361. /* an address within an object. Return 0 o.w. */
  362. GC_API void * GC_CALL GC_base(void * p)
  363. {
  364. ptr_t r;
  365. struct hblk *h;
  366. bottom_index *bi;
  367. hdr *candidate_hdr;
  368. r = (ptr_t)p;
  369. if (!EXPECT(GC_is_initialized, TRUE)) return 0;
  370. h = HBLKPTR(r);
  371. GET_BI(r, bi);
  372. candidate_hdr = HDR_FROM_BI(bi, r);
  373. if (candidate_hdr == 0) return(0);
  374. /* If it's a pointer to the middle of a large object, move it */
  375. /* to the beginning. */
  376. while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) {
  377. h = FORWARDED_ADDR(h,candidate_hdr);
  378. r = (ptr_t)h;
  379. candidate_hdr = HDR(h);
  380. }
  381. if (HBLK_IS_FREE(candidate_hdr)) return(0);
  382. /* Make sure r points to the beginning of the object */
  383. r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1));
  384. {
  385. size_t offset = HBLKDISPL(r);
  386. word sz = candidate_hdr -> hb_sz;
  387. size_t obj_displ = offset % sz;
  388. ptr_t limit;
  389. r -= obj_displ;
  390. limit = r + sz;
  391. if ((word)limit > (word)(h + 1) && sz <= HBLKSIZE) {
  392. return(0);
  393. }
  394. if ((word)p >= (word)limit) return(0);
  395. }
  396. return((void *)r);
  397. }
  398. /* Return TRUE if and only if p points to somewhere in GC heap. */
  399. GC_API int GC_CALL GC_is_heap_ptr(const void *p)
  400. {
  401. bottom_index *bi;
  402. GC_ASSERT(GC_is_initialized);
  403. GET_BI(p, bi);
  404. return HDR_FROM_BI(bi, p) != 0;
  405. }
  406. /* Return the size of an object, given a pointer to its base. */
  407. /* (For small objects this also happens to work from interior pointers, */
  408. /* but that shouldn't be relied upon.) */
  409. GC_API size_t GC_CALL GC_size(const void * p)
  410. {
  411. hdr * hhdr = HDR(p);
  412. return (size_t)hhdr->hb_sz;
  413. }
  414. /* These getters remain unsynchronized for compatibility (since some */
  415. /* clients could call some of them from a GC callback holding the */
  416. /* allocator lock). */
  417. GC_API size_t GC_CALL GC_get_heap_size(void)
  418. {
  419. /* ignore the memory space returned to OS (i.e. count only the */
  420. /* space owned by the garbage collector) */
  421. return (size_t)(GC_heapsize - GC_unmapped_bytes);
  422. }
  423. GC_API size_t GC_CALL GC_get_free_bytes(void)
  424. {
  425. /* ignore the memory space returned to OS */
  426. return (size_t)(GC_large_free_bytes - GC_unmapped_bytes);
  427. }
  428. GC_API size_t GC_CALL GC_get_unmapped_bytes(void)
  429. {
  430. return (size_t)GC_unmapped_bytes;
  431. }
  432. GC_API size_t GC_CALL GC_get_bytes_since_gc(void)
  433. {
  434. return (size_t)GC_bytes_allocd;
  435. }
  436. GC_API size_t GC_CALL GC_get_total_bytes(void)
  437. {
  438. return (size_t)(GC_bytes_allocd + GC_bytes_allocd_before_gc);
  439. }
  440. #ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
  441. GC_API size_t GC_CALL GC_get_size_map_at(int i)
  442. {
  443. if ((unsigned)i > MAXOBJBYTES)
  444. return GC_SIZE_MAX;
  445. return GRANULES_TO_BYTES(GC_size_map[i]);
  446. }
  447. /* Return the heap usage information. This is a thread-safe (atomic) */
  448. /* alternative for the five above getters. NULL pointer is allowed for */
  449. /* any argument. Returned (filled in) values are of word type. */
  450. GC_API void GC_CALL GC_get_heap_usage_safe(GC_word *pheap_size,
  451. GC_word *pfree_bytes, GC_word *punmapped_bytes,
  452. GC_word *pbytes_since_gc, GC_word *ptotal_bytes)
  453. {
  454. DCL_LOCK_STATE;
  455. LOCK();
  456. if (pheap_size != NULL)
  457. *pheap_size = GC_heapsize - GC_unmapped_bytes;
  458. if (pfree_bytes != NULL)
  459. *pfree_bytes = GC_large_free_bytes - GC_unmapped_bytes;
  460. if (punmapped_bytes != NULL)
  461. *punmapped_bytes = GC_unmapped_bytes;
  462. if (pbytes_since_gc != NULL)
  463. *pbytes_since_gc = GC_bytes_allocd;
  464. if (ptotal_bytes != NULL)
  465. *ptotal_bytes = GC_bytes_allocd + GC_bytes_allocd_before_gc;
  466. UNLOCK();
  467. }
  468. GC_INNER word GC_reclaimed_bytes_before_gc = 0;
  469. /* Fill in GC statistics provided the destination is of enough size. */
  470. static void fill_prof_stats(struct GC_prof_stats_s *pstats)
  471. {
  472. pstats->heapsize_full = GC_heapsize;
  473. pstats->free_bytes_full = GC_large_free_bytes;
  474. pstats->unmapped_bytes = GC_unmapped_bytes;
  475. pstats->bytes_allocd_since_gc = GC_bytes_allocd;
  476. pstats->allocd_bytes_before_gc = GC_bytes_allocd_before_gc;
  477. pstats->non_gc_bytes = GC_non_gc_bytes;
  478. pstats->gc_no = GC_gc_no; /* could be -1 */
  479. # ifdef PARALLEL_MARK
  480. pstats->markers_m1 = (word)GC_markers_m1;
  481. # else
  482. pstats->markers_m1 = 0; /* one marker */
  483. # endif
  484. pstats->bytes_reclaimed_since_gc = GC_bytes_found > 0 ?
  485. (word)GC_bytes_found : 0;
  486. pstats->reclaimed_bytes_before_gc = GC_reclaimed_bytes_before_gc;
  487. pstats->expl_freed_bytes_since_gc = GC_bytes_freed; /* since gc-7.7 */
  488. }
  489. # include <string.h> /* for memset() */
  490. GC_API size_t GC_CALL GC_get_prof_stats(struct GC_prof_stats_s *pstats,
  491. size_t stats_sz)
  492. {
  493. struct GC_prof_stats_s stats;
  494. DCL_LOCK_STATE;
  495. LOCK();
  496. fill_prof_stats(stats_sz >= sizeof(stats) ? pstats : &stats);
  497. UNLOCK();
  498. if (stats_sz == sizeof(stats)) {
  499. return sizeof(stats);
  500. } else if (stats_sz > sizeof(stats)) {
  501. /* Fill in the remaining part with -1. */
  502. memset((char *)pstats + sizeof(stats), 0xff, stats_sz - sizeof(stats));
  503. return sizeof(stats);
  504. } else {
  505. if (EXPECT(stats_sz > 0, TRUE))
  506. BCOPY(&stats, pstats, stats_sz);
  507. return stats_sz;
  508. }
  509. }
  510. # ifdef THREADS
  511. /* The _unsafe version assumes the caller holds the allocation lock. */
  512. GC_API size_t GC_CALL GC_get_prof_stats_unsafe(
  513. struct GC_prof_stats_s *pstats,
  514. size_t stats_sz)
  515. {
  516. struct GC_prof_stats_s stats;
  517. if (stats_sz >= sizeof(stats)) {
  518. fill_prof_stats(pstats);
  519. if (stats_sz > sizeof(stats))
  520. memset((char *)pstats + sizeof(stats), 0xff,
  521. stats_sz - sizeof(stats));
  522. return sizeof(stats);
  523. } else {
  524. if (EXPECT(stats_sz > 0, TRUE)) {
  525. fill_prof_stats(&stats);
  526. BCOPY(&stats, pstats, stats_sz);
  527. }
  528. return stats_sz;
  529. }
  530. }
  531. # endif /* THREADS */
  532. #endif /* !GC_GET_HEAP_USAGE_NOT_NEEDED */
  533. #if defined(GC_DARWIN_THREADS) || defined(GC_OPENBSD_UTHREADS) \
  534. || defined(GC_WIN32_THREADS) || (defined(NACL) && defined(THREADS))
  535. /* GC does not use signals to suspend and restart threads. */
  536. GC_API void GC_CALL GC_set_suspend_signal(int sig GC_ATTR_UNUSED)
  537. {
  538. /* empty */
  539. }
  540. GC_API void GC_CALL GC_set_thr_restart_signal(int sig GC_ATTR_UNUSED)
  541. {
  542. /* empty */
  543. }
  544. GC_API int GC_CALL GC_get_suspend_signal(void)
  545. {
  546. return -1;
  547. }
  548. GC_API int GC_CALL GC_get_thr_restart_signal(void)
  549. {
  550. return -1;
  551. }
  552. #endif /* GC_DARWIN_THREADS || GC_WIN32_THREADS || ... */
  553. #if !defined(_MAX_PATH) && (defined(MSWIN32) || defined(MSWINCE) \
  554. || defined(CYGWIN32))
  555. # define _MAX_PATH MAX_PATH
  556. #endif
  557. #ifdef GC_READ_ENV_FILE
  558. /* This works for Win32/WinCE for now. Really useful only for WinCE. */
  559. STATIC char *GC_envfile_content = NULL;
  560. /* The content of the GC "env" file with CR and */
  561. /* LF replaced to '\0'. NULL if the file is */
  562. /* missing or empty. Otherwise, always ends */
  563. /* with '\0'. */
  564. STATIC unsigned GC_envfile_length = 0;
  565. /* Length of GC_envfile_content (if non-NULL). */
  566. # ifndef GC_ENVFILE_MAXLEN
  567. # define GC_ENVFILE_MAXLEN 0x4000
  568. # endif
  569. # define GC_ENV_FILE_EXT ".gc.env"
  570. /* The routine initializes GC_envfile_content from the GC "env" file. */
  571. STATIC void GC_envfile_init(void)
  572. {
  573. # if defined(MSWIN32) || defined(MSWINCE) || defined(CYGWIN32)
  574. HANDLE hFile;
  575. char *content;
  576. unsigned ofs;
  577. unsigned len;
  578. DWORD nBytesRead;
  579. TCHAR path[_MAX_PATH + 0x10]; /* buffer for path + ext */
  580. len = (unsigned)GetModuleFileName(NULL /* hModule */, path,
  581. _MAX_PATH + 1);
  582. /* If GetModuleFileName() has failed then len is 0. */
  583. if (len > 4 && path[len - 4] == (TCHAR)'.') {
  584. len -= 4; /* strip executable file extension */
  585. }
  586. BCOPY(TEXT(GC_ENV_FILE_EXT), &path[len], sizeof(TEXT(GC_ENV_FILE_EXT)));
  587. hFile = CreateFile(path, GENERIC_READ,
  588. FILE_SHARE_READ | FILE_SHARE_WRITE,
  589. NULL /* lpSecurityAttributes */, OPEN_EXISTING,
  590. FILE_ATTRIBUTE_NORMAL, NULL /* hTemplateFile */);
  591. if (hFile == INVALID_HANDLE_VALUE)
  592. return; /* the file is absent or the operation is failed */
  593. len = (unsigned)GetFileSize(hFile, NULL);
  594. if (len <= 1 || len >= GC_ENVFILE_MAXLEN) {
  595. CloseHandle(hFile);
  596. return; /* invalid file length - ignoring the file content */
  597. }
  598. /* At this execution point, GC_setpagesize() and GC_init_win32() */
  599. /* must already be called (for GET_MEM() to work correctly). */
  600. content = (char *)GET_MEM(ROUNDUP_PAGESIZE_IF_MMAP((size_t)len + 1));
  601. if (content == NULL) {
  602. CloseHandle(hFile);
  603. return; /* allocation failure */
  604. }
  605. ofs = 0;
  606. nBytesRead = (DWORD)-1L;
  607. /* Last ReadFile() call should clear nBytesRead on success. */
  608. while (ReadFile(hFile, content + ofs, len - ofs + 1, &nBytesRead,
  609. NULL /* lpOverlapped */) && nBytesRead != 0) {
  610. if ((ofs += nBytesRead) > len)
  611. break;
  612. }
  613. CloseHandle(hFile);
  614. if (ofs != len || nBytesRead != 0)
  615. return; /* read operation is failed - ignoring the file content */
  616. content[ofs] = '\0';
  617. while (ofs-- > 0) {
  618. if (content[ofs] == '\r' || content[ofs] == '\n')
  619. content[ofs] = '\0';
  620. }
  621. GC_ASSERT(NULL == GC_envfile_content);
  622. GC_envfile_length = len + 1;
  623. GC_envfile_content = content;
  624. # endif
  625. }
  626. /* This routine scans GC_envfile_content for the specified */
  627. /* environment variable (and returns its value if found). */
  628. GC_INNER char * GC_envfile_getenv(const char *name)
  629. {
  630. char *p;
  631. char *end_of_content;
  632. unsigned namelen;
  633. # ifndef NO_GETENV
  634. p = getenv(name); /* try the standard getenv() first */
  635. if (p != NULL)
  636. return *p != '\0' ? p : NULL;
  637. # endif
  638. p = GC_envfile_content;
  639. if (p == NULL)
  640. return NULL; /* "env" file is absent (or empty) */
  641. namelen = strlen(name);
  642. if (namelen == 0) /* a sanity check */
  643. return NULL;
  644. for (end_of_content = p + GC_envfile_length;
  645. p != end_of_content; p += strlen(p) + 1) {
  646. if (strncmp(p, name, namelen) == 0 && *(p += namelen) == '=') {
  647. p++; /* the match is found; skip '=' */
  648. return *p != '\0' ? p : NULL;
  649. }
  650. /* If not matching then skip to the next line. */
  651. }
  652. return NULL; /* no match found */
  653. }
  654. #endif /* GC_READ_ENV_FILE */
  655. GC_INNER GC_bool GC_is_initialized = FALSE;
  656. GC_API int GC_CALL GC_is_init_called(void)
  657. {
  658. return GC_is_initialized;
  659. }
  660. #if (defined(MSWIN32) || defined(MSWINCE) || defined(MSWIN_XBOX1)) \
  661. && defined(THREADS)
  662. GC_INNER CRITICAL_SECTION GC_write_cs;
  663. #endif
  664. #ifndef DONT_USE_ATEXIT
  665. # if !defined(PCR) && !defined(SMALL_CONFIG)
  666. /* A dedicated variable to avoid a garbage collection on abort. */
  667. /* GC_find_leak cannot be used for this purpose as otherwise */
  668. /* TSan finds a data race (between GC_default_on_abort and, e.g., */
  669. /* GC_finish_collection). */
  670. static GC_bool skip_gc_atexit = FALSE;
  671. # else
  672. # define skip_gc_atexit FALSE
  673. # endif
  674. STATIC void GC_exit_check(void)
  675. {
  676. if (GC_find_leak && !skip_gc_atexit) {
  677. GC_gcollect();
  678. }
  679. }
  680. #endif
  681. #if defined(UNIX_LIKE) && !defined(NO_DEBUGGING)
  682. static void looping_handler(int sig)
  683. {
  684. GC_err_printf("Caught signal %d: looping in handler\n", sig);
  685. for (;;) {
  686. /* empty */
  687. }
  688. }
  689. static GC_bool installed_looping_handler = FALSE;
  690. static void maybe_install_looping_handler(void)
  691. {
  692. /* Install looping handler before the write fault handler, so we */
  693. /* handle write faults correctly. */
  694. if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) {
  695. GC_set_and_save_fault_handler(looping_handler);
  696. installed_looping_handler = TRUE;
  697. }
  698. }
  699. #else /* !UNIX_LIKE */
  700. # define maybe_install_looping_handler()
  701. #endif
  702. #define GC_DEFAULT_STDOUT_FD 1
  703. #define GC_DEFAULT_STDERR_FD 2
  704. #if !defined(OS2) && !defined(MACOS) && !defined(GC_ANDROID_LOG) \
  705. && !defined(NN_PLATFORM_CTR) && !defined(NINTENDO_SWITCH) \
  706. && !defined(MSWIN32) && !defined(MSWINCE)
  707. STATIC int GC_stdout = GC_DEFAULT_STDOUT_FD;
  708. STATIC int GC_stderr = GC_DEFAULT_STDERR_FD;
  709. STATIC int GC_log = GC_DEFAULT_STDERR_FD;
  710. GC_API void GC_CALL GC_set_log_fd(int fd)
  711. {
  712. GC_log = fd;
  713. }
  714. #endif
  715. #if defined(MSWIN32) && !defined(MSWINRT_FLAVOR) && !defined(MSWIN_XBOX1) \
  716. && !defined(SMALL_CONFIG)
  717. STATIC void GC_win32_MessageBoxA(const char *msg, const char *caption,
  718. unsigned flags)
  719. {
  720. # ifndef DONT_USE_USER32_DLL
  721. /* Use static binding to "user32.dll". */
  722. (void)MessageBoxA(NULL, msg, caption, flags);
  723. # else
  724. /* This simplifies linking - resolve "MessageBoxA" at run-time. */
  725. HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll"));
  726. if (hU32) {
  727. FARPROC pfn = GetProcAddress(hU32, "MessageBoxA");
  728. if (pfn)
  729. (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)(
  730. NULL /* hWnd */, msg, caption, flags);
  731. (void)FreeLibrary(hU32);
  732. }
  733. # endif
  734. }
  735. #endif /* MSWIN32 */
  736. #if defined(THREADS) && defined(UNIX_LIKE) && !defined(NO_GETCONTEXT)
  737. static void callee_saves_pushed_dummy_fn(ptr_t data GC_ATTR_UNUSED,
  738. void * context GC_ATTR_UNUSED) {}
  739. #endif
  740. STATIC word GC_parse_mem_size_arg(const char *str)
  741. {
  742. word result = 0; /* bad value */
  743. if (*str != '\0') {
  744. char *endptr;
  745. char ch;
  746. result = (word)STRTOULL(str, &endptr, 10);
  747. ch = *endptr;
  748. if (ch != '\0') {
  749. if (*(endptr + 1) != '\0')
  750. return 0;
  751. /* Allow k, M or G suffix. */
  752. switch (ch) {
  753. case 'K':
  754. case 'k':
  755. result <<= 10;
  756. break;
  757. case 'M':
  758. case 'm':
  759. result <<= 20;
  760. break;
  761. case 'G':
  762. case 'g':
  763. result <<= 30;
  764. break;
  765. default:
  766. result = 0;
  767. }
  768. }
  769. }
  770. return result;
  771. }
  772. #define GC_LOG_STD_NAME "gc.log"
  773. GC_API void GC_CALL GC_init(void)
  774. {
  775. /* LOCK(); -- no longer does anything this early. */
  776. word initial_heap_sz;
  777. IF_CANCEL(int cancel_state;)
  778. # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
  779. DCL_LOCK_STATE;
  780. # endif
  781. if (EXPECT(GC_is_initialized, TRUE)) return;
  782. # ifdef REDIRECT_MALLOC
  783. {
  784. static GC_bool init_started = FALSE;
  785. if (init_started)
  786. ABORT("Redirected malloc() called during GC init");
  787. init_started = TRUE;
  788. }
  789. # endif
  790. # if defined(GC_INITIAL_HEAP_SIZE) && !defined(CPPCHECK)
  791. initial_heap_sz = GC_INITIAL_HEAP_SIZE;
  792. # else
  793. initial_heap_sz = MINHINCR * HBLKSIZE;
  794. # endif
  795. DISABLE_CANCEL(cancel_state);
  796. /* Note that although we are nominally called with the */
  797. /* allocation lock held, the allocation lock is now */
  798. /* only really acquired once a second thread is forked.*/
  799. /* And the initialization code needs to run before */
  800. /* then. Thus we really don't hold any locks, and can */
  801. /* in fact safely initialize them here. */
  802. # ifdef THREADS
  803. # ifndef GC_ALWAYS_MULTITHREADED
  804. GC_ASSERT(!GC_need_to_lock);
  805. # endif
  806. # ifdef SN_TARGET_PS3
  807. {
  808. pthread_mutexattr_t mattr;
  809. if (0 != pthread_mutexattr_init(&mattr)) {
  810. ABORT("pthread_mutexattr_init failed");
  811. }
  812. if (0 != pthread_mutex_init(&GC_allocate_ml, &mattr)) {
  813. ABORT("pthread_mutex_init failed");
  814. }
  815. (void)pthread_mutexattr_destroy(&mattr);
  816. }
  817. # endif
  818. # endif /* THREADS */
  819. # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
  820. # ifndef SPIN_COUNT
  821. # define SPIN_COUNT 4000
  822. # endif
  823. # ifdef MSWINRT_FLAVOR
  824. InitializeCriticalSectionAndSpinCount(&GC_allocate_ml, SPIN_COUNT);
  825. # else
  826. {
  827. # ifndef MSWINCE
  828. # ifndef MSWINRT
  829. BOOL (WINAPI *pfn)(LPCRITICAL_SECTION, DWORD) = 0;
  830. HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll"));
  831. if (hK32)
  832. pfn = (BOOL (WINAPI *)(LPCRITICAL_SECTION, DWORD))
  833. GetProcAddress(hK32,
  834. "InitializeCriticalSectionAndSpinCount");
  835. if (pfn) {
  836. pfn(&GC_allocate_ml, SPIN_COUNT);
  837. } else
  838. # else
  839. InitializeCriticalSectionAndSpinCount(&GC_allocate_ml, 4000);
  840. # endif
  841. # endif /* !MSWINCE */
  842. # ifndef MSWINRT
  843. /* else */ InitializeCriticalSection(&GC_allocate_ml);
  844. # endif
  845. }
  846. # endif
  847. # endif /* GC_WIN32_THREADS */
  848. # if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS)
  849. InitializeCriticalSection(&GC_write_cs);
  850. # endif
  851. GC_setpagesize();
  852. # ifdef MSWIN32
  853. GC_init_win32();
  854. # endif
  855. # ifdef GC_READ_ENV_FILE
  856. GC_envfile_init();
  857. # endif
  858. # if !defined(NO_CLOCK) || !defined(SMALL_CONFIG)
  859. # ifdef GC_PRINT_VERBOSE_STATS
  860. /* This is useful for debugging and profiling on platforms with */
  861. /* missing getenv() (like WinCE). */
  862. GC_print_stats = VERBOSE;
  863. # else
  864. if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) {
  865. GC_print_stats = VERBOSE;
  866. } else if (0 != GETENV("GC_PRINT_STATS")) {
  867. GC_print_stats = 1;
  868. }
  869. # endif
  870. # endif
  871. # if ((defined(UNIX_LIKE) && !defined(GC_ANDROID_LOG)) \
  872. || defined(CYGWIN32) || defined(SYMBIAN)) && !defined(SMALL_CONFIG)
  873. {
  874. char * file_name = TRUSTED_STRING(GETENV("GC_LOG_FILE"));
  875. # ifdef GC_LOG_TO_FILE_ALWAYS
  876. if (NULL == file_name)
  877. file_name = GC_LOG_STD_NAME;
  878. # else
  879. if (0 != file_name)
  880. # endif
  881. {
  882. int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666);
  883. if (log_d < 0) {
  884. GC_err_printf("Failed to open %s as log file\n", file_name);
  885. } else {
  886. char *str;
  887. GC_log = log_d;
  888. str = GETENV("GC_ONLY_LOG_TO_FILE");
  889. # ifdef GC_ONLY_LOG_TO_FILE
  890. /* The similar environment variable set to "0" */
  891. /* overrides the effect of the macro defined. */
  892. if (str != NULL && *str == '0' && *(str + 1) == '\0')
  893. # else
  894. /* Otherwise setting the environment variable */
  895. /* to anything other than "0" will prevent from */
  896. /* redirecting stdout/err to the log file. */
  897. if (str == NULL || (*str == '0' && *(str + 1) == '\0'))
  898. # endif
  899. {
  900. GC_stdout = log_d;
  901. GC_stderr = log_d;
  902. }
  903. }
  904. }
  905. }
  906. # endif
  907. # if !defined(NO_DEBUGGING) && !defined(GC_DUMP_REGULARLY)
  908. if (0 != GETENV("GC_DUMP_REGULARLY")) {
  909. GC_dump_regularly = TRUE;
  910. }
  911. # endif
  912. # ifdef KEEP_BACK_PTRS
  913. {
  914. char * backtraces_string = GETENV("GC_BACKTRACES");
  915. if (0 != backtraces_string) {
  916. GC_backtraces = atol(backtraces_string);
  917. if (backtraces_string[0] == '\0') GC_backtraces = 1;
  918. }
  919. }
  920. # endif
  921. if (0 != GETENV("GC_FIND_LEAK")) {
  922. GC_find_leak = 1;
  923. }
  924. # ifndef SHORT_DBG_HDRS
  925. if (0 != GETENV("GC_FINDLEAK_DELAY_FREE")) {
  926. GC_findleak_delay_free = TRUE;
  927. }
  928. # endif
  929. if (0 != GETENV("GC_ALL_INTERIOR_POINTERS")) {
  930. GC_all_interior_pointers = 1;
  931. }
  932. if (0 != GETENV("GC_DONT_GC")) {
  933. GC_dont_gc = 1;
  934. }
  935. if (0 != GETENV("GC_PRINT_BACK_HEIGHT")) {
  936. GC_print_back_height = TRUE;
  937. }
  938. if (0 != GETENV("GC_NO_BLACKLIST_WARNING")) {
  939. GC_large_alloc_warn_interval = LONG_MAX;
  940. }
  941. {
  942. char * addr_string = GETENV("GC_TRACE");
  943. if (0 != addr_string) {
  944. # ifndef ENABLE_TRACE
  945. WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0);
  946. # else
  947. word addr = (word)STRTOULL(addr_string, NULL, 16);
  948. if (addr < 0x1000)
  949. WARN("Unlikely trace address: %p\n", (void *)addr);
  950. GC_trace_addr = (ptr_t)addr;
  951. # endif
  952. }
  953. }
  954. # ifdef GC_COLLECT_AT_MALLOC
  955. {
  956. char * string = GETENV("GC_COLLECT_AT_MALLOC");
  957. if (0 != string) {
  958. size_t min_lb = (size_t)STRTOULL(string, NULL, 10);
  959. if (min_lb > 0)
  960. GC_dbg_collect_at_malloc_min_lb = min_lb;
  961. }
  962. }
  963. # endif
  964. # ifndef GC_DISABLE_INCREMENTAL
  965. {
  966. char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET");
  967. if (0 != time_limit_string) {
  968. long time_limit = atol(time_limit_string);
  969. if (time_limit < 5) {
  970. WARN("GC_PAUSE_TIME_TARGET environment variable value too small "
  971. "or bad syntax: Ignoring\n", 0);
  972. } else {
  973. GC_time_limit = time_limit * 1000000;
  974. }
  975. }
  976. }
  977. # endif
  978. # ifndef SMALL_CONFIG
  979. {
  980. char * full_freq_string = GETENV("GC_FULL_FREQUENCY");
  981. if (full_freq_string != NULL) {
  982. int full_freq = atoi(full_freq_string);
  983. if (full_freq > 0)
  984. GC_full_freq = full_freq;
  985. }
  986. }
  987. # endif
  988. {
  989. char * interval_string = GETENV("GC_LARGE_ALLOC_WARN_INTERVAL");
  990. if (0 != interval_string) {
  991. long interval = atol(interval_string);
  992. if (interval <= 0) {
  993. WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has "
  994. "bad value: Ignoring\n", 0);
  995. } else {
  996. GC_large_alloc_warn_interval = interval;
  997. }
  998. }
  999. }
  1000. {
  1001. char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR");
  1002. if (space_divisor_string != NULL) {
  1003. int space_divisor = atoi(space_divisor_string);
  1004. if (space_divisor > 0)
  1005. GC_free_space_divisor = (word)space_divisor;
  1006. }
  1007. }
  1008. # ifdef USE_MUNMAP
  1009. {
  1010. char * string = GETENV("GC_UNMAP_THRESHOLD");
  1011. if (string != NULL) {
  1012. if (*string == '0' && *(string + 1) == '\0') {
  1013. /* "0" is used to disable unmapping. */
  1014. GC_unmap_threshold = 0;
  1015. } else {
  1016. int unmap_threshold = atoi(string);
  1017. if (unmap_threshold > 0)
  1018. GC_unmap_threshold = unmap_threshold;
  1019. }
  1020. }
  1021. }
  1022. {
  1023. char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT");
  1024. if (string != NULL) {
  1025. if (*string == '0' && *(string + 1) == '\0') {
  1026. /* "0" is used to turn off the mode. */
  1027. GC_force_unmap_on_gcollect = FALSE;
  1028. } else {
  1029. GC_force_unmap_on_gcollect = TRUE;
  1030. }
  1031. }
  1032. }
  1033. {
  1034. char * string = GETENV("GC_USE_ENTIRE_HEAP");
  1035. if (string != NULL) {
  1036. if (*string == '0' && *(string + 1) == '\0') {
  1037. /* "0" is used to turn off the mode. */
  1038. GC_use_entire_heap = FALSE;
  1039. } else {
  1040. GC_use_entire_heap = TRUE;
  1041. }
  1042. }
  1043. }
  1044. # endif
  1045. # if !defined(NO_DEBUGGING) && !defined(NO_CLOCK)
  1046. GET_TIME(GC_init_time);
  1047. # endif
  1048. maybe_install_looping_handler();
  1049. # if ALIGNMENT > GC_DS_TAGS
  1050. /* Adjust normal object descriptor for extra allocation. */
  1051. if (EXTRA_BYTES != 0)
  1052. GC_obj_kinds[NORMAL].ok_descriptor = (word)(-ALIGNMENT) | GC_DS_LENGTH;
  1053. # endif
  1054. GC_exclude_static_roots_inner(beginGC_arrays, endGC_arrays);
  1055. GC_exclude_static_roots_inner(beginGC_obj_kinds, endGC_obj_kinds);
  1056. # ifdef SEPARATE_GLOBALS
  1057. GC_exclude_static_roots_inner(beginGC_objfreelist, endGC_objfreelist);
  1058. GC_exclude_static_roots_inner(beginGC_aobjfreelist, endGC_aobjfreelist);
  1059. # endif
  1060. # if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS)
  1061. WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0);
  1062. /* If thread stacks are cached, they tend to be scanned in */
  1063. /* entirety as part of the root set. This wil grow them to */
  1064. /* maximum size, and is generally not desirable. */
  1065. # endif
  1066. # if defined(SEARCH_FOR_DATA_START)
  1067. GC_init_linux_data_start();
  1068. # endif
  1069. # if defined(NETBSD) && defined(__ELF__)
  1070. GC_init_netbsd_elf();
  1071. # endif
  1072. # if !defined(THREADS) || defined(GC_PTHREADS) \
  1073. || defined(NN_PLATFORM_CTR) || defined(NINTENDO_SWITCH) \
  1074. || defined(GC_WIN32_THREADS) || defined(GC_SOLARIS_THREADS)
  1075. if (GC_stackbottom == 0) {
  1076. GC_stackbottom = GC_get_main_stack_base();
  1077. # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
  1078. GC_register_stackbottom = GC_get_register_stack_base();
  1079. # endif
  1080. } else {
  1081. # if (defined(LINUX) || defined(HPUX)) && defined(IA64)
  1082. if (GC_register_stackbottom == 0) {
  1083. WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0);
  1084. /* The following may fail, since we may rely on */
  1085. /* alignment properties that may not hold with a user set */
  1086. /* GC_stackbottom. */
  1087. GC_register_stackbottom = GC_get_register_stack_base();
  1088. }
  1089. # endif
  1090. }
  1091. # endif
  1092. # if !defined(CPPCHECK)
  1093. GC_STATIC_ASSERT(sizeof(ptr_t) == sizeof(word));
  1094. GC_STATIC_ASSERT(sizeof(signed_word) == sizeof(word));
  1095. # if !defined(_AUX_SOURCE) || defined(__GNUC__)
  1096. GC_STATIC_ASSERT((word)(-1) > (word)0);
  1097. /* word should be unsigned */
  1098. # endif
  1099. /* We no longer check for ((void*)(-1) > NULL) since all pointers */
  1100. /* are explicitly cast to word in every less/greater comparison. */
  1101. GC_STATIC_ASSERT((signed_word)(-1) < (signed_word)0);
  1102. # endif
  1103. GC_STATIC_ASSERT(sizeof (struct hblk) == HBLKSIZE);
  1104. # ifndef THREADS
  1105. GC_ASSERT(!((word)GC_stackbottom HOTTER_THAN (word)GC_approx_sp()));
  1106. # endif
  1107. # ifndef GC_DISABLE_INCREMENTAL
  1108. if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) {
  1109. /* For GWW_VDB on Win32, this needs to happen before any */
  1110. /* heap memory is allocated. */
  1111. GC_incremental = GC_dirty_init();
  1112. GC_ASSERT(GC_bytes_allocd == 0);
  1113. }
  1114. # endif
  1115. /* Add initial guess of root sets. Do this first, since sbrk(0) */
  1116. /* might be used. */
  1117. if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments();
  1118. GC_init_headers();
  1119. GC_bl_init();
  1120. GC_mark_init();
  1121. {
  1122. char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE");
  1123. if (sz_str != NULL) {
  1124. initial_heap_sz = GC_parse_mem_size_arg(sz_str);
  1125. if (initial_heap_sz <= MINHINCR * HBLKSIZE) {
  1126. WARN("Bad initial heap size %s - ignoring it.\n", sz_str);
  1127. }
  1128. }
  1129. }
  1130. {
  1131. char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE");
  1132. if (sz_str != NULL) {
  1133. word max_heap_sz = GC_parse_mem_size_arg(sz_str);
  1134. if (max_heap_sz < initial_heap_sz) {
  1135. WARN("Bad maximum heap size %s - ignoring it.\n", sz_str);
  1136. }
  1137. if (0 == GC_max_retries) GC_max_retries = 2;
  1138. GC_set_max_heap_size(max_heap_sz);
  1139. }
  1140. }
  1141. if (!GC_expand_hp_inner(divHBLKSZ(initial_heap_sz))) {
  1142. GC_err_printf("Can't start up: not enough memory\n");
  1143. EXIT();
  1144. } else {
  1145. GC_requested_heapsize += initial_heap_sz;
  1146. }
  1147. if (GC_all_interior_pointers)
  1148. GC_initialize_offsets();
  1149. GC_register_displacement_inner(0L);
  1150. # if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC)
  1151. if (!GC_all_interior_pointers) {
  1152. /* TLS ABI uses pointer-sized offsets for dtv. */
  1153. GC_register_displacement_inner(sizeof(void *));
  1154. }
  1155. # endif
  1156. GC_init_size_map();
  1157. # ifdef PCR
  1158. if (PCR_IL_Lock(PCR_Bool_false, PCR_allSigsBlocked, PCR_waitForever)
  1159. != PCR_ERes_okay) {
  1160. ABORT("Can't lock load state");
  1161. } else if (PCR_IL_Unlock() != PCR_ERes_okay) {
  1162. ABORT("Can't unlock load state");
  1163. }
  1164. PCR_IL_Unlock();
  1165. GC_pcr_install();
  1166. # endif
  1167. GC_is_initialized = TRUE;
  1168. # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
  1169. LOCK(); /* just to set GC_lock_holder */
  1170. # endif
  1171. # if defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)
  1172. GC_thr_init();
  1173. # ifdef PARALLEL_MARK
  1174. /* Actually start helper threads. */
  1175. # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
  1176. UNLOCK();
  1177. # endif
  1178. GC_start_mark_threads_inner();
  1179. # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
  1180. LOCK();
  1181. # endif
  1182. # endif
  1183. # endif
  1184. COND_DUMP;
  1185. /* Get black list set up and/or incremental GC started */
  1186. if (!GC_dont_precollect || GC_incremental) {
  1187. GC_gcollect_inner();
  1188. }
  1189. # if defined(GC_ASSERTIONS) && defined(GC_ALWAYS_MULTITHREADED)
  1190. UNLOCK();
  1191. # endif
  1192. # if defined(THREADS) && defined(UNIX_LIKE) && !defined(NO_GETCONTEXT)
  1193. /* Ensure getcontext_works is set to avoid potential data race. */
  1194. if (GC_dont_gc || GC_dont_precollect)
  1195. GC_with_callee_saves_pushed(callee_saves_pushed_dummy_fn, NULL);
  1196. # endif
  1197. # ifndef DONT_USE_ATEXIT
  1198. if (GC_find_leak) {
  1199. /* This is to give us at least one chance to detect leaks. */
  1200. /* This may report some very benign leaks, but ... */
  1201. atexit(GC_exit_check);
  1202. }
  1203. # endif
  1204. /* The rest of this again assumes we don't really hold */
  1205. /* the allocation lock. */
  1206. # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC) \
  1207. || (defined(GC_ALWAYS_MULTITHREADED) && defined(GC_WIN32_THREADS) \
  1208. && !defined(GC_NO_THREADS_DISCOVERY))
  1209. /* Make sure marker threads are started and thread local */
  1210. /* allocation is initialized, in case we didn't get */
  1211. /* called from GC_init_parallel. */
  1212. GC_init_parallel();
  1213. # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
  1214. # if defined(DYNAMIC_LOADING) && defined(DARWIN)
  1215. /* This must be called WITHOUT the allocation lock held */
  1216. /* and before any threads are created. */
  1217. GC_init_dyld();
  1218. # endif
  1219. RESTORE_CANCEL(cancel_state);
  1220. }
  1221. GC_API void GC_CALL GC_enable_incremental(void)
  1222. {
  1223. # if !defined(GC_DISABLE_INCREMENTAL) && !defined(KEEP_BACK_PTRS)
  1224. DCL_LOCK_STATE;
  1225. /* If we are keeping back pointers, the GC itself dirties all */
  1226. /* pages on which objects have been marked, making */
  1227. /* incremental GC pointless. */
  1228. if (!GC_find_leak && 0 == GETENV("GC_DISABLE_INCREMENTAL")) {
  1229. LOCK();
  1230. if (!GC_incremental) {
  1231. GC_setpagesize();
  1232. /* if (GC_no_win32_dlls) goto out; Should be win32S test? */
  1233. maybe_install_looping_handler(); /* Before write fault handler! */
  1234. if (!GC_is_initialized) {
  1235. UNLOCK();
  1236. GC_incremental = TRUE; /* indicate intention to turn it on */
  1237. GC_init();
  1238. LOCK();
  1239. } else {
  1240. GC_incremental = GC_dirty_init();
  1241. }
  1242. if (GC_incremental && !GC_dont_gc) {
  1243. /* Can't easily do it if GC_dont_gc. */
  1244. IF_CANCEL(int cancel_state;)
  1245. DISABLE_CANCEL(cancel_state);
  1246. if (GC_bytes_allocd > 0) {
  1247. /* There may be unmarked reachable objects. */
  1248. GC_gcollect_inner();
  1249. }
  1250. /* else we're OK in assuming everything's */
  1251. /* clean since nothing can point to an */
  1252. /* unmarked object. */
  1253. GC_read_dirty(FALSE);
  1254. RESTORE_CANCEL(cancel_state);
  1255. }
  1256. }
  1257. UNLOCK();
  1258. return;
  1259. }
  1260. # endif
  1261. GC_init();
  1262. }
  1263. #if defined(THREADS)
  1264. GC_API void GC_CALL GC_start_mark_threads(void)
  1265. {
  1266. # if defined(PARALLEL_MARK) && defined(CAN_HANDLE_FORK) \
  1267. && !defined(THREAD_SANITIZER)
  1268. /* TSan does not support threads creation in the child process. */
  1269. IF_CANCEL(int cancel_state;)
  1270. DISABLE_CANCEL(cancel_state);
  1271. GC_start_mark_threads_inner();
  1272. RESTORE_CANCEL(cancel_state);
  1273. # else
  1274. /* No action since parallel markers are disabled (or no POSIX fork). */
  1275. GC_ASSERT(I_DONT_HOLD_LOCK());
  1276. # endif
  1277. }
  1278. #endif
  1279. extern void GC_reset_default_push_other_roots(void);
  1280. GC_API void GC_CALL GC_deinit(void)
  1281. {
  1282. if (GC_is_initialized) {
  1283. /* Prevent duplicate resource close. */
  1284. GC_is_initialized = FALSE;
  1285. # if defined(THREADS) && (defined(MSWIN32) || defined(MSWINCE))
  1286. DeleteCriticalSection(&GC_write_cs);
  1287. DeleteCriticalSection(&GC_allocate_ml);
  1288. # endif
  1289. GC_clear_exclusion_table();
  1290. memset(&GC_arrays, 0, sizeof(GC_arrays));
  1291. GC_clear_freelist();
  1292. GC_clear_bottom_indices();
  1293. GC_clear_finalizable_object_table();
  1294. GC_reset_mark_statics();
  1295. GC_reset_default_push_other_roots();
  1296. }
  1297. }
  1298. #if defined(MSWIN32) || defined(MSWINCE)
  1299. # if defined(_MSC_VER) && defined(_DEBUG) && !defined(MSWINCE)
  1300. # include <crtdbg.h>
  1301. # endif
  1302. STATIC HANDLE GC_log = 0;
  1303. # ifdef THREADS
  1304. # if defined(PARALLEL_MARK) && !defined(GC_ALWAYS_MULTITHREADED)
  1305. # define IF_NEED_TO_LOCK(x) if (GC_parallel || GC_need_to_lock) x
  1306. # else
  1307. # define IF_NEED_TO_LOCK(x) if (GC_need_to_lock) x
  1308. # endif
  1309. # else
  1310. # define IF_NEED_TO_LOCK(x)
  1311. # endif /* !THREADS */
  1312. # ifdef MSWINRT_FLAVOR
  1313. # include <windows.storage.h>
  1314. /* This API is defined in roapi.h, but we cannot include it here */
  1315. /* since it does not compile in C. */
  1316. DECLSPEC_IMPORT HRESULT WINAPI RoGetActivationFactory(
  1317. HSTRING activatableClassId,
  1318. REFIID iid, void** factory);
  1319. static GC_bool getWinRTLogPath(wchar_t* buf, size_t bufLen)
  1320. {
  1321. static const GUID kIID_IApplicationDataStatics = {
  1322. 0x5612147B, 0xE843, 0x45E3,
  1323. 0x94, 0xD8, 0x06, 0x16, 0x9E, 0x3C, 0x8E, 0x17
  1324. };
  1325. static const GUID kIID_IStorageItem = {
  1326. 0x4207A996, 0xCA2F, 0x42F7,
  1327. 0xBD, 0xE8, 0x8B, 0x10, 0x45, 0x7A, 0x7F, 0x30
  1328. };
  1329. GC_bool result = FALSE;
  1330. HSTRING_HEADER appDataClassNameHeader;
  1331. HSTRING appDataClassName;
  1332. __x_ABI_CWindows_CStorage_CIApplicationDataStatics* appDataStatics = 0;
  1333. GC_ASSERT(bufLen > 0);
  1334. if (SUCCEEDED(WindowsCreateStringReference(
  1335. RuntimeClass_Windows_Storage_ApplicationData,
  1336. (sizeof(RuntimeClass_Windows_Storage_ApplicationData)-1)
  1337. / sizeof(wchar_t),
  1338. &appDataClassNameHeader, &appDataClassName))
  1339. && SUCCEEDED(RoGetActivationFactory(appDataClassName,
  1340. &kIID_IApplicationDataStatics,
  1341. &appDataStatics))) {
  1342. __x_ABI_CWindows_CStorage_CIApplicationData* appData = NULL;
  1343. __x_ABI_CWindows_CStorage_CIStorageFolder* tempFolder = NULL;
  1344. __x_ABI_CWindows_CStorage_CIStorageItem* tempFolderItem = NULL;
  1345. HSTRING tempPath = NULL;
  1346. if (SUCCEEDED(appDataStatics->lpVtbl->get_Current(appDataStatics,
  1347. &appData))
  1348. && SUCCEEDED(appData->lpVtbl->get_TemporaryFolder(appData,
  1349. &tempFolder))
  1350. && SUCCEEDED(tempFolder->lpVtbl->QueryInterface(tempFolder,
  1351. &kIID_IStorageItem,
  1352. &tempFolderItem))
  1353. && SUCCEEDED(tempFolderItem->lpVtbl->get_Path(tempFolderItem,
  1354. &tempPath))) {
  1355. UINT32 tempPathLen;
  1356. const wchar_t* tempPathBuf =
  1357. WindowsGetStringRawBuffer(tempPath, &tempPathLen);
  1358. buf[0] = '\0';
  1359. if (wcsncat_s(buf, bufLen, tempPathBuf, tempPathLen) == 0
  1360. && wcscat_s(buf, bufLen, L"\\") == 0
  1361. && wcscat_s(buf, bufLen, TEXT(GC_LOG_STD_NAME)) == 0)
  1362. result = TRUE;
  1363. WindowsDeleteString(tempPath);
  1364. }
  1365. if (tempFolderItem != NULL)
  1366. tempFolderItem->lpVtbl->Release(tempFolderItem);
  1367. if (tempFolder != NULL)
  1368. tempFolder->lpVtbl->Release(tempFolder);
  1369. if (appData != NULL)
  1370. appData->lpVtbl->Release(appData);
  1371. appDataStatics->lpVtbl->Release(appDataStatics);
  1372. }
  1373. return result;
  1374. }
  1375. # endif /* MSWINRT_FLAVOR */
  1376. STATIC HANDLE GC_CreateLogFile(void)
  1377. {
  1378. HANDLE hFile;
  1379. # ifdef MSWINRT_FLAVOR
  1380. TCHAR pathBuf[_MAX_PATH + 0x10]; /* buffer for path + ext */
  1381. hFile = INVALID_HANDLE_VALUE;
  1382. if (getWinRTLogPath(pathBuf, _MAX_PATH + 1)) {
  1383. CREATEFILE2_EXTENDED_PARAMETERS extParams;
  1384. BZERO(&extParams, sizeof(extParams));
  1385. extParams.dwSize = sizeof(extParams);
  1386. extParams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
  1387. extParams.dwFileFlags = GC_print_stats == VERBOSE ? 0
  1388. : FILE_FLAG_WRITE_THROUGH;
  1389. hFile = CreateFile2(pathBuf, GENERIC_WRITE, FILE_SHARE_READ,
  1390. CREATE_ALWAYS, &extParams);
  1391. }
  1392. # else
  1393. TCHAR *logPath;
  1394. BOOL appendToFile = FALSE;
  1395. # if !defined(NO_GETENV_WIN32) || !defined(OLD_WIN32_LOG_FILE)
  1396. TCHAR pathBuf[_MAX_PATH + 0x10]; /* buffer for path + ext */
  1397. logPath = pathBuf;
  1398. # endif
  1399. # ifndef MSWINRT
  1400. /* Use GetEnvironmentVariable instead of GETENV() for unicode support. */
  1401. # ifndef NO_GETENV_WIN32
  1402. if (GetEnvironmentVariable(TEXT("GC_LOG_FILE"), pathBuf,
  1403. _MAX_PATH + 1) - 1U < (DWORD)_MAX_PATH) {
  1404. appendToFile = TRUE;
  1405. } else
  1406. # endif
  1407. /* else */ {
  1408. /* Env var not found or its value too long. */
  1409. # ifdef OLD_WIN32_LOG_FILE
  1410. logPath = TEXT(GC_LOG_STD_NAME);
  1411. # else
  1412. int len = (int)GetModuleFileName(NULL /* hModule */, pathBuf,
  1413. _MAX_PATH + 1);
  1414. /* If GetModuleFileName() has failed then len is 0. */
  1415. if (len > 4 && pathBuf[len - 4] == (TCHAR)'.') {
  1416. len -= 4; /* strip executable file extension */
  1417. }
  1418. BCOPY(TEXT(".") TEXT(GC_LOG_STD_NAME), &pathBuf[len],
  1419. sizeof(TEXT(".") TEXT(GC_LOG_STD_NAME)));
  1420. # endif
  1421. }
  1422. # endif
  1423. # ifndef MSWINRT
  1424. hFile = CreateFile(logPath, GENERIC_WRITE, FILE_SHARE_READ,
  1425. NULL /* lpSecurityAttributes */,
  1426. appendToFile ? OPEN_ALWAYS : CREATE_ALWAYS,
  1427. GC_print_stats == VERBOSE ? FILE_ATTRIBUTE_NORMAL :
  1428. /* immediately flush writes unless very verbose */
  1429. FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
  1430. NULL /* hTemplateFile */);
  1431. # else
  1432. {
  1433. if (GetWinRTLogPath(pathBuf, MAX_PATH + 1))
  1434. {
  1435. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  1436. ZeroMemory(&extendedParameters, sizeof(extendedParameters));
  1437. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  1438. extendedParameters.dwFileFlags = GC_print_stats == VERBOSE
  1439. ? 0
  1440. : /* immediately flush writes unless very verbose */ FILE_FLAG_WRITE_THROUGH;
  1441. extendedParameters.dwFileAttributes = FILE_ATTRIBUTE_NORMAL;
  1442. hFile = CreateFile2(logPath, GENERIC_WRITE, FILE_SHARE_READ,
  1443. appendToFile ? OPEN_ALWAYS : CREATE_ALWAYS,
  1444. &extendedParameters);
  1445. }
  1446. else
  1447. {
  1448. hFile = INVALID_HANDLE_VALUE;
  1449. }
  1450. }
  1451. # endif
  1452. # ifndef NO_GETENV_WIN32
  1453. if (appendToFile && hFile != INVALID_HANDLE_VALUE) {
  1454. LONG posHigh = 0;
  1455. (void)SetFilePointer(hFile, 0, &posHigh, FILE_END);
  1456. /* Seek to file end (ignoring any error) */
  1457. }
  1458. # endif
  1459. # endif
  1460. return hFile;
  1461. }
  1462. STATIC int GC_write(const char *buf, size_t len)
  1463. {
  1464. BOOL res;
  1465. DWORD written;
  1466. # if defined(THREADS) && defined(GC_ASSERTIONS)
  1467. static GC_bool inside_write = FALSE;
  1468. /* to prevent infinite recursion at abort. */
  1469. if (inside_write)
  1470. return -1;
  1471. # endif
  1472. if (len == 0)
  1473. return 0;
  1474. IF_NEED_TO_LOCK(EnterCriticalSection(&GC_write_cs));
  1475. # if defined(THREADS) && defined(GC_ASSERTIONS)
  1476. if (GC_write_disabled) {
  1477. inside_write = TRUE;
  1478. ABORT("Assertion failure: GC_write called with write_disabled");
  1479. }
  1480. # endif
  1481. if (GC_log == 0) {
  1482. GC_log = GC_CreateLogFile();
  1483. }
  1484. if (GC_log == INVALID_HANDLE_VALUE) {
  1485. IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
  1486. # ifdef NO_DEBUGGING
  1487. /* Ignore open log failure (e.g., it might be caused by */
  1488. /* read-only folder of the client application). */
  1489. return 0;
  1490. # else
  1491. return -1;
  1492. # endif
  1493. }
  1494. res = WriteFile(GC_log, buf, (DWORD)len, &written, NULL);
  1495. # if defined(_MSC_VER) && defined(_DEBUG) && !defined(NO_CRT)
  1496. # ifdef MSWINCE
  1497. /* There is no CrtDbgReport() in WinCE */
  1498. {
  1499. WCHAR wbuf[1024];
  1500. /* Always use Unicode variant of OutputDebugString() */
  1501. wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */,
  1502. buf, len, wbuf,
  1503. sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0;
  1504. OutputDebugStringW(wbuf);
  1505. }
  1506. # else
  1507. _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf);
  1508. # endif
  1509. # endif
  1510. IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs));
  1511. return res ? (int)written : -1;
  1512. }
  1513. /* FIXME: This is pretty ugly ... */
  1514. # define WRITE(f, buf, len) GC_write(buf, len)
  1515. #elif defined(OS2) || defined(MACOS)
  1516. STATIC FILE * GC_stdout = NULL;
  1517. STATIC FILE * GC_stderr = NULL;
  1518. STATIC FILE * GC_log = NULL;
  1519. /* Initialize GC_log (and the friends) passed to GC_write(). */
  1520. STATIC void GC_set_files(void)
  1521. {
  1522. if (GC_stdout == NULL) {
  1523. GC_stdout = stdout;
  1524. }
  1525. if (GC_stderr == NULL) {
  1526. GC_stderr = stderr;
  1527. }
  1528. if (GC_log == NULL) {
  1529. GC_log = stderr;
  1530. }
  1531. }
  1532. GC_INLINE int GC_write(FILE *f, const char *buf, size_t len)
  1533. {
  1534. int res = fwrite(buf, 1, len, f);
  1535. fflush(f);
  1536. return res;
  1537. }
  1538. # define WRITE(f, buf, len) (GC_set_files(), GC_write(f, buf, len))
  1539. #elif defined(GC_ANDROID_LOG)
  1540. # include <android/log.h>
  1541. # ifndef GC_ANDROID_LOG_TAG
  1542. # define GC_ANDROID_LOG_TAG "BDWGC"
  1543. # endif
  1544. # define GC_stdout ANDROID_LOG_DEBUG
  1545. # define GC_stderr ANDROID_LOG_ERROR
  1546. # define GC_log GC_stdout
  1547. # define WRITE(level, buf, unused_len) \
  1548. __android_log_write(level, GC_ANDROID_LOG_TAG, buf)
  1549. # elif defined(NN_PLATFORM_CTR)
  1550. int n3ds_log_write(const char* text, int length);
  1551. # define WRITE(level, buf, len) n3ds_log_write(buf, len)
  1552. # elif defined(NINTENDO_SWITCH)
  1553. int switch_log_write(const char* text, int length);
  1554. # define WRITE(level, buf, len) switch_log_write(buf, len)
  1555. #else
  1556. # if !defined(AMIGA) && !defined(MSWIN_XBOX1) && !defined(GC_NO_TYPES) \
  1557. && !defined(SN_TARGET_PSP2) && !defined(__CC_ARM)
  1558. # include <unistd.h>
  1559. # endif
  1560. STATIC int GC_write(int fd, const char *buf, size_t len)
  1561. {
  1562. # if defined(ECOS) || defined(PLATFORM_WRITE) || defined(SN_TARGET_PSP2) \
  1563. || defined(NOSYS)
  1564. # ifdef ECOS
  1565. /* FIXME: This seems to be defined nowhere at present. */
  1566. /* _Jv_diag_write(buf, len); */
  1567. # else
  1568. /* No writing. */
  1569. # endif
  1570. return len;
  1571. # else
  1572. int bytes_written = 0;
  1573. IF_CANCEL(int cancel_state;)
  1574. DISABLE_CANCEL(cancel_state);
  1575. while ((size_t)bytes_written < len) {
  1576. # ifdef GC_SOLARIS_THREADS
  1577. int result = syscall(SYS_write, fd, buf + bytes_written,
  1578. len - bytes_written);
  1579. # else
  1580. int result = write(fd, buf + bytes_written, len - bytes_written);
  1581. # endif
  1582. if (-1 == result) {
  1583. RESTORE_CANCEL(cancel_state);
  1584. return(result);
  1585. }
  1586. bytes_written += result;
  1587. }
  1588. RESTORE_CANCEL(cancel_state);
  1589. return(bytes_written);
  1590. # endif
  1591. }
  1592. # define WRITE(f, buf, len) GC_write(f, buf, len)
  1593. #endif /* !MSWIN32 && !OS2 && !MACOS && !GC_ANDROID_LOG */
  1594. #define BUFSZ 1024
  1595. #if !defined(NO_CRT)
  1596. #if defined(DJGPP) || defined(__STRICT_ANSI__)
  1597. /* vsnprintf is missing in DJGPP (v2.0.3) */
  1598. # define GC_VSNPRINTF(buf, bufsz, format, args) vsprintf(buf, format, args)
  1599. #elif defined(_MSC_VER)
  1600. # ifdef MSWINCE
  1601. /* _vsnprintf is deprecated in WinCE */
  1602. # define GC_VSNPRINTF StringCchVPrintfA
  1603. # else
  1604. # define GC_VSNPRINTF _vsnprintf
  1605. # endif
  1606. #else
  1607. # define GC_VSNPRINTF vsnprintf
  1608. #endif
  1609. #endif
  1610. /* A version of printf that is unlikely to call malloc, and is thus safer */
  1611. /* to call from the collector in case malloc has been bound to GC_malloc. */
  1612. /* Floating point arguments and formats should be avoided, since FP */
  1613. /* conversion is more likely to allocate memory. */
  1614. /* Assumes that no more than BUFSZ-1 characters are written at once. */
  1615. #if defined(GC_VSNPRINTF)
  1616. #define GC_PRINTF_FILLBUF(buf, format) \
  1617. do { \
  1618. va_list args; \
  1619. va_start(args, format); \
  1620. (buf)[sizeof(buf) - 1] = 0x15; /* guard */ \
  1621. (void)GC_VSNPRINTF(buf, sizeof(buf) - 1, format, args); \
  1622. va_end(args); \
  1623. if ((buf)[sizeof(buf) - 1] != 0x15) \
  1624. ABORT("GC_printf clobbered stack"); \
  1625. } while (0)
  1626. #else
  1627. #define GC_PRINTF_FILLBUF(buf, format) \
  1628. do { \
  1629. } while (0)
  1630. #endif
  1631. void GC_printf(const char *format, ...)
  1632. {
  1633. if (!GC_quiet) {
  1634. char buf[BUFSZ + 1];
  1635. GC_PRINTF_FILLBUF(buf, format);
  1636. # ifdef NACL
  1637. (void)WRITE(GC_stdout, buf, strlen(buf));
  1638. /* Ignore errors silently. */
  1639. # else
  1640. if (WRITE(GC_stdout, buf, strlen(buf)) < 0)
  1641. ABORT("write to stdout failed");
  1642. # endif
  1643. }
  1644. }
  1645. void GC_err_printf(const char *format, ...)
  1646. {
  1647. char buf[BUFSZ + 1];
  1648. GC_PRINTF_FILLBUF(buf, format);
  1649. GC_err_puts(buf);
  1650. }
  1651. void GC_log_printf(const char *format, ...)
  1652. {
  1653. char buf[BUFSZ + 1];
  1654. GC_PRINTF_FILLBUF(buf, format);
  1655. # ifdef NACL
  1656. (void)WRITE(GC_log, buf, strlen(buf));
  1657. # else
  1658. if (WRITE(GC_log, buf, strlen(buf)) < 0)
  1659. ABORT("write to GC log failed");
  1660. # endif
  1661. }
  1662. #ifndef GC_ANDROID_LOG
  1663. # define GC_warn_printf GC_err_printf
  1664. #else
  1665. GC_INNER void GC_info_log_printf(const char *format, ...)
  1666. {
  1667. char buf[BUFSZ + 1];
  1668. GC_PRINTF_FILLBUF(buf, format);
  1669. (void)WRITE(ANDROID_LOG_INFO, buf, 0 /* unused */);
  1670. }
  1671. GC_INNER void GC_verbose_log_printf(const char *format, ...)
  1672. {
  1673. char buf[BUFSZ + 1];
  1674. GC_PRINTF_FILLBUF(buf, format);
  1675. (void)WRITE(ANDROID_LOG_VERBOSE, buf, 0); /* ignore write errors */
  1676. }
  1677. STATIC void GC_warn_printf(const char *format, ...)
  1678. {
  1679. char buf[BUFSZ + 1];
  1680. GC_PRINTF_FILLBUF(buf, format);
  1681. (void)WRITE(ANDROID_LOG_WARN, buf, 0);
  1682. }
  1683. #endif /* GC_ANDROID_LOG */
  1684. void GC_err_puts(const char *s)
  1685. {
  1686. (void)WRITE(GC_stderr, s, strlen(s)); /* ignore errors */
  1687. }
  1688. STATIC void GC_CALLBACK GC_default_warn_proc(char *msg, GC_word arg)
  1689. {
  1690. /* TODO: Add assertion on arg comply with msg (format). */
  1691. GC_warn_printf(msg, arg);
  1692. }
  1693. GC_INNER GC_warn_proc GC_current_warn_proc = GC_default_warn_proc;
  1694. /* This is recommended for production code (release). */
  1695. GC_API void GC_CALLBACK GC_ignore_warn_proc(char *msg, GC_word arg)
  1696. {
  1697. if (GC_print_stats) {
  1698. /* Don't ignore warnings if stats printing is on. */
  1699. GC_default_warn_proc(msg, arg);
  1700. }
  1701. }
  1702. GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc p)
  1703. {
  1704. DCL_LOCK_STATE;
  1705. GC_ASSERT(NONNULL_ARG_NOT_NULL(p));
  1706. # ifdef GC_WIN32_THREADS
  1707. # ifdef CYGWIN32
  1708. /* Need explicit GC_INIT call */
  1709. GC_ASSERT(GC_is_initialized);
  1710. # else
  1711. if (!GC_is_initialized) GC_init();
  1712. # endif
  1713. # endif
  1714. LOCK();
  1715. GC_current_warn_proc = p;
  1716. UNLOCK();
  1717. }
  1718. GC_API GC_warn_proc GC_CALL GC_get_warn_proc(void)
  1719. {
  1720. GC_warn_proc result;
  1721. DCL_LOCK_STATE;
  1722. LOCK();
  1723. result = GC_current_warn_proc;
  1724. UNLOCK();
  1725. return(result);
  1726. }
  1727. #if !defined(PCR) && !defined(SMALL_CONFIG)
  1728. /* Print (or display) a message before abnormal exit (including */
  1729. /* abort). Invoked from ABORT(msg) macro (there msg is non-NULL) */
  1730. /* and from EXIT() macro (msg is NULL in that case). */
  1731. STATIC void GC_CALLBACK GC_default_on_abort(const char *msg)
  1732. {
  1733. # ifndef DONT_USE_ATEXIT
  1734. skip_gc_atexit = TRUE; /* disable at-exit GC_gcollect() */
  1735. # endif
  1736. if (msg != NULL) {
  1737. # if defined(MSWIN32) && !defined(MSWINRT_FLAVOR) && !defined(_XBOX_ONE)
  1738. GC_win32_MessageBoxA(msg, "Fatal error in GC", MB_ICONERROR | MB_OK);
  1739. /* Also duplicate msg to GC log file. */
  1740. # endif
  1741. # ifndef GC_ANDROID_LOG
  1742. /* Avoid calling GC_err_printf() here, as GC_on_abort() could be */
  1743. /* called from it. Note 1: this is not an atomic output. */
  1744. /* Note 2: possible write errors are ignored. */
  1745. # if defined(THREADS) && defined(GC_ASSERTIONS) \
  1746. && (defined(MSWIN32) || defined(MSWINCE))
  1747. if (!GC_write_disabled)
  1748. # endif
  1749. {
  1750. if (WRITE(GC_stderr, msg, strlen(msg)) >= 0)
  1751. (void)WRITE(GC_stderr, "\n", 1);
  1752. }
  1753. # else
  1754. __android_log_assert("*" /* cond */, GC_ANDROID_LOG_TAG, "%s\n", msg);
  1755. # endif
  1756. }
  1757. # if !defined(NO_DEBUGGING) && !defined(GC_ANDROID_LOG)
  1758. if (GETENV("GC_LOOP_ON_ABORT") != NULL) {
  1759. /* In many cases it's easier to debug a running process. */
  1760. /* It's arguably nicer to sleep, but that makes it harder */
  1761. /* to look at the thread if the debugger doesn't know much */
  1762. /* about threads. */
  1763. for(;;) {
  1764. /* Empty */
  1765. }
  1766. }
  1767. # endif
  1768. }
  1769. GC_abort_func GC_on_abort = GC_default_on_abort;
  1770. GC_API void GC_CALL GC_set_abort_func(GC_abort_func fn)
  1771. {
  1772. DCL_LOCK_STATE;
  1773. GC_ASSERT(NONNULL_ARG_NOT_NULL(fn));
  1774. LOCK();
  1775. GC_on_abort = fn;
  1776. UNLOCK();
  1777. }
  1778. GC_API GC_abort_func GC_CALL GC_get_abort_func(void)
  1779. {
  1780. GC_abort_func fn;
  1781. DCL_LOCK_STATE;
  1782. LOCK();
  1783. fn = GC_on_abort;
  1784. UNLOCK();
  1785. return fn;
  1786. }
  1787. #endif /* !SMALL_CONFIG */
  1788. GC_API void GC_CALL GC_enable(void)
  1789. {
  1790. DCL_LOCK_STATE;
  1791. LOCK();
  1792. GC_ASSERT(GC_dont_gc != 0); /* ensure no counter underflow */
  1793. GC_dont_gc--;
  1794. UNLOCK();
  1795. }
  1796. GC_API void GC_CALL GC_disable(void)
  1797. {
  1798. DCL_LOCK_STATE;
  1799. LOCK();
  1800. GC_dont_gc++;
  1801. UNLOCK();
  1802. }
  1803. GC_API int GC_CALL GC_is_disabled(void)
  1804. {
  1805. return GC_dont_gc != 0;
  1806. }
  1807. /* Helper procedures for new kind creation. */
  1808. GC_API void ** GC_CALL GC_new_free_list_inner(void)
  1809. {
  1810. void *result;
  1811. GC_ASSERT(I_HOLD_LOCK());
  1812. result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1) * sizeof(ptr_t), PTRFREE);
  1813. if (NULL == result) ABORT("Failed to allocate freelist for new kind");
  1814. BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t));
  1815. return (void **)result;
  1816. }
  1817. GC_API void ** GC_CALL GC_new_free_list(void)
  1818. {
  1819. void ** result;
  1820. DCL_LOCK_STATE;
  1821. LOCK();
  1822. result = GC_new_free_list_inner();
  1823. UNLOCK();
  1824. return result;
  1825. }
  1826. GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr,
  1827. int adjust, int clear)
  1828. {
  1829. unsigned result = GC_n_kinds;
  1830. GC_ASSERT(adjust == FALSE || adjust == TRUE);
  1831. /* If an object is not needed to be cleared (when moved to the */
  1832. /* free list) then its descriptor should be zero to denote */
  1833. /* a pointer-free object (and, as a consequence, the size of the */
  1834. /* object should not be added to the descriptor template). */
  1835. GC_ASSERT(clear == TRUE
  1836. || (descr == 0 && adjust == FALSE && clear == FALSE));
  1837. if (result < MAXOBJKINDS) {
  1838. GC_n_kinds++;
  1839. GC_obj_kinds[result].ok_freelist = fl;
  1840. GC_obj_kinds[result].ok_reclaim_list = 0;
  1841. GC_obj_kinds[result].ok_descriptor = descr;
  1842. GC_obj_kinds[result].ok_relocate_descr = adjust;
  1843. GC_obj_kinds[result].ok_init = (GC_bool)clear;
  1844. # ifdef ENABLE_DISCLAIM
  1845. GC_obj_kinds[result].ok_mark_unconditionally = FALSE;
  1846. GC_obj_kinds[result].ok_disclaim_proc = 0;
  1847. # endif
  1848. } else {
  1849. ABORT("Too many kinds");
  1850. }
  1851. return result;
  1852. }
  1853. GC_API unsigned GC_CALL GC_new_kind(void **fl, GC_word descr, int adjust,
  1854. int clear)
  1855. {
  1856. unsigned result;
  1857. DCL_LOCK_STATE;
  1858. LOCK();
  1859. result = GC_new_kind_inner(fl, descr, adjust, clear);
  1860. UNLOCK();
  1861. return result;
  1862. }
  1863. GC_API unsigned GC_CALL GC_new_proc_inner(GC_mark_proc proc)
  1864. {
  1865. unsigned result = GC_n_mark_procs;
  1866. if (result < MAX_MARK_PROCS) {
  1867. GC_n_mark_procs++;
  1868. GC_mark_procs[result] = proc;
  1869. } else {
  1870. ABORT("Too many mark procedures");
  1871. }
  1872. return result;
  1873. }
  1874. GC_API unsigned GC_CALL GC_new_proc(GC_mark_proc proc)
  1875. {
  1876. unsigned result;
  1877. DCL_LOCK_STATE;
  1878. LOCK();
  1879. result = GC_new_proc_inner(proc);
  1880. UNLOCK();
  1881. return result;
  1882. }
  1883. GC_API void * GC_CALL GC_call_with_alloc_lock(GC_fn_type fn, void *client_data)
  1884. {
  1885. void * result;
  1886. DCL_LOCK_STATE;
  1887. # ifdef THREADS
  1888. LOCK();
  1889. # endif
  1890. result = (*fn)(client_data);
  1891. # ifdef THREADS
  1892. UNLOCK();
  1893. # endif
  1894. return(result);
  1895. }
  1896. GC_API void * GC_CALL GC_call_with_stack_base(GC_stack_base_func fn, void *arg)
  1897. {
  1898. struct GC_stack_base base;
  1899. void *result;
  1900. base.mem_base = (void *)&base;
  1901. # ifdef IA64
  1902. base.reg_base = (void *)GC_save_regs_in_stack();
  1903. /* Unnecessarily flushes register stack, */
  1904. /* but that probably doesn't hurt. */
  1905. # endif
  1906. result = fn(&base, arg);
  1907. /* Strongly discourage the compiler from treating the above */
  1908. /* as a tail call. */
  1909. GC_noop1((word)(&base));
  1910. return result;
  1911. }
  1912. #ifndef THREADS
  1913. GC_INNER ptr_t GC_blocked_sp = NULL;
  1914. /* NULL value means we are not inside GC_do_blocking() call. */
  1915. # ifdef IA64
  1916. STATIC ptr_t GC_blocked_register_sp = NULL;
  1917. # endif
  1918. GC_INNER struct GC_traced_stack_sect_s *GC_traced_stack_sect = NULL;
  1919. /* This is nearly the same as in win32_threads.c */
  1920. GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn,
  1921. void * client_data)
  1922. {
  1923. struct GC_traced_stack_sect_s stacksect;
  1924. GC_ASSERT(GC_is_initialized);
  1925. /* Adjust our stack base value (this could happen if */
  1926. /* GC_get_main_stack_base() is unimplemented or broken for */
  1927. /* the platform). */
  1928. if ((word)GC_stackbottom HOTTER_THAN (word)(&stacksect))
  1929. GC_stackbottom = (ptr_t)(&stacksect);
  1930. if (GC_blocked_sp == NULL) {
  1931. /* We are not inside GC_do_blocking() - do nothing more. */
  1932. client_data = fn(client_data);
  1933. /* Prevent treating the above as a tail call. */
  1934. GC_noop1((word)(&stacksect));
  1935. return client_data; /* result */
  1936. }
  1937. /* Setup new "stack section". */
  1938. stacksect.saved_stack_ptr = GC_blocked_sp;
  1939. # ifdef IA64
  1940. /* This is the same as in GC_call_with_stack_base(). */
  1941. stacksect.backing_store_end = GC_save_regs_in_stack();
  1942. /* Unnecessarily flushes register stack, */
  1943. /* but that probably doesn't hurt. */
  1944. stacksect.saved_backing_store_ptr = GC_blocked_register_sp;
  1945. # endif
  1946. stacksect.prev = GC_traced_stack_sect;
  1947. GC_blocked_sp = NULL;
  1948. GC_traced_stack_sect = &stacksect;
  1949. client_data = fn(client_data);
  1950. GC_ASSERT(GC_blocked_sp == NULL);
  1951. GC_ASSERT(GC_traced_stack_sect == &stacksect);
  1952. # if defined(CPPCHECK)
  1953. GC_noop1((word)GC_traced_stack_sect - (word)GC_blocked_sp);
  1954. # endif
  1955. /* Restore original "stack section". */
  1956. GC_traced_stack_sect = stacksect.prev;
  1957. # ifdef IA64
  1958. GC_blocked_register_sp = stacksect.saved_backing_store_ptr;
  1959. # endif
  1960. GC_blocked_sp = stacksect.saved_stack_ptr;
  1961. return client_data; /* result */
  1962. }
  1963. /* This is nearly the same as in win32_threads.c */
  1964. STATIC void GC_do_blocking_inner(ptr_t data, void * context GC_ATTR_UNUSED)
  1965. {
  1966. struct blocking_data * d = (struct blocking_data *) data;
  1967. GC_ASSERT(GC_is_initialized);
  1968. GC_ASSERT(GC_blocked_sp == NULL);
  1969. # ifdef SPARC
  1970. GC_blocked_sp = GC_save_regs_in_stack();
  1971. # else
  1972. GC_blocked_sp = (ptr_t) &d; /* save approx. sp */
  1973. # endif
  1974. # ifdef IA64
  1975. GC_blocked_register_sp = GC_save_regs_in_stack();
  1976. # endif
  1977. d -> client_data = (d -> fn)(d -> client_data);
  1978. # ifdef SPARC
  1979. GC_ASSERT(GC_blocked_sp != NULL);
  1980. # else
  1981. GC_ASSERT(GC_blocked_sp == (ptr_t)(&d));
  1982. # endif
  1983. # if defined(CPPCHECK)
  1984. GC_noop1((word)GC_blocked_sp);
  1985. # endif
  1986. GC_blocked_sp = NULL;
  1987. }
  1988. #endif /* !THREADS */
  1989. /* Wrapper for functions that are likely to block (or, at least, do not */
  1990. /* allocate garbage collected memory and/or manipulate pointers to the */
  1991. /* garbage collected heap) for an appreciable length of time. */
  1992. /* In the single threaded case, GC_do_blocking() (together */
  1993. /* with GC_call_with_gc_active()) might be used to make stack scanning */
  1994. /* more precise (i.e. scan only stack frames of functions that allocate */
  1995. /* garbage collected memory and/or manipulate pointers to the garbage */
  1996. /* collected heap). */
  1997. GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data)
  1998. {
  1999. struct blocking_data my_data;
  2000. my_data.fn = fn;
  2001. my_data.client_data = client_data;
  2002. GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
  2003. return my_data.client_data; /* result */
  2004. }
  2005. #if !defined(NO_DEBUGGING)
  2006. GC_API void GC_CALL GC_dump(void)
  2007. {
  2008. DCL_LOCK_STATE;
  2009. LOCK();
  2010. GC_dump_named(NULL);
  2011. UNLOCK();
  2012. }
  2013. GC_API void GC_CALL GC_dump_named(const char *name)
  2014. {
  2015. # ifndef NO_CLOCK
  2016. CLOCK_TYPE current_time;
  2017. GET_TIME(current_time);
  2018. # endif
  2019. if (name != NULL) {
  2020. GC_printf("***GC Dump %s\n", name);
  2021. } else {
  2022. GC_printf("***GC Dump collection #%lu\n", (unsigned long)GC_gc_no);
  2023. }
  2024. # ifndef NO_CLOCK
  2025. /* Note that the time is wrapped in ~49 days if sizeof(long)==4. */
  2026. GC_printf("Time since GC init: %lu msecs\n",
  2027. MS_TIME_DIFF(current_time, GC_init_time));
  2028. # endif
  2029. GC_printf("\n***Static roots:\n");
  2030. GC_print_static_roots();
  2031. GC_printf("\n***Heap sections:\n");
  2032. GC_print_heap_sects();
  2033. GC_printf("\n***Free blocks:\n");
  2034. GC_print_hblkfreelist();
  2035. GC_printf("\n***Blocks in use:\n");
  2036. GC_print_block_list();
  2037. }
  2038. #endif /* !NO_DEBUGGING */
  2039. static void block_add_size(struct hblk *h, word pbytes)
  2040. {
  2041. hdr *hhdr = HDR(h);
  2042. *(word *)pbytes += (WORDS_TO_BYTES(hhdr->hb_sz) + (HBLKSIZE - 1))
  2043. & ~(word)(HBLKSIZE - 1);
  2044. }
  2045. GC_API size_t GC_CALL GC_get_memory_use(void)
  2046. {
  2047. word bytes = 0;
  2048. DCL_LOCK_STATE;
  2049. LOCK();
  2050. GC_apply_to_all_blocks(block_add_size, (word)(&bytes));
  2051. UNLOCK();
  2052. return (size_t)bytes;
  2053. }
  2054. /* Getter functions for the public Read-only variables. */
  2055. /* GC_get_gc_no() is unsynchronized and should be typically called */
  2056. /* inside the context of GC_call_with_alloc_lock() to prevent data */
  2057. /* races (on multiprocessors). */
  2058. GC_API GC_word GC_CALL GC_get_gc_no(void)
  2059. {
  2060. return GC_gc_no;
  2061. }
  2062. #ifdef THREADS
  2063. GC_API int GC_CALL GC_get_parallel(void)
  2064. {
  2065. /* GC_parallel is initialized at start-up. */
  2066. return GC_parallel;
  2067. }
  2068. GC_INNER GC_on_thread_event_proc GC_on_thread_event = 0;
  2069. GC_API void GC_CALL GC_set_on_thread_event(GC_on_thread_event_proc fn)
  2070. {
  2071. /* fn may be 0 (means no event notifier). */
  2072. DCL_LOCK_STATE;
  2073. LOCK();
  2074. GC_on_thread_event = fn;
  2075. UNLOCK();
  2076. }
  2077. GC_API GC_on_thread_event_proc GC_CALL GC_get_on_thread_event(void)
  2078. {
  2079. GC_on_thread_event_proc fn;
  2080. DCL_LOCK_STATE;
  2081. LOCK();
  2082. fn = GC_on_thread_event;
  2083. UNLOCK();
  2084. return fn;
  2085. }
  2086. #endif /* THREADS */
  2087. /* Setter and getter functions for the public R/W function variables. */
  2088. /* These functions are synchronized (like GC_set_warn_proc() and */
  2089. /* GC_get_warn_proc()). */
  2090. GC_API void GC_CALL GC_set_oom_fn(GC_oom_func fn)
  2091. {
  2092. GC_ASSERT(NONNULL_ARG_NOT_NULL(fn));
  2093. DCL_LOCK_STATE;
  2094. LOCK();
  2095. GC_oom_fn = fn;
  2096. UNLOCK();
  2097. }
  2098. GC_API GC_oom_func GC_CALL GC_get_oom_fn(void)
  2099. {
  2100. GC_oom_func fn;
  2101. DCL_LOCK_STATE;
  2102. LOCK();
  2103. fn = GC_oom_fn;
  2104. UNLOCK();
  2105. return fn;
  2106. }
  2107. GC_API void GC_CALL GC_set_on_heap_resize(GC_on_heap_resize_proc fn)
  2108. {
  2109. /* fn may be 0 (means no event notifier). */
  2110. DCL_LOCK_STATE;
  2111. LOCK();
  2112. GC_on_heap_resize = fn;
  2113. UNLOCK();
  2114. }
  2115. GC_API GC_on_heap_resize_proc GC_CALL GC_get_on_heap_resize(void)
  2116. {
  2117. GC_on_heap_resize_proc fn;
  2118. DCL_LOCK_STATE;
  2119. LOCK();
  2120. fn = GC_on_heap_resize;
  2121. UNLOCK();
  2122. return fn;
  2123. }
  2124. GC_API void GC_CALL GC_set_finalizer_notifier(GC_finalizer_notifier_proc fn)
  2125. {
  2126. /* fn may be 0 (means no finalizer notifier). */
  2127. DCL_LOCK_STATE;
  2128. LOCK();
  2129. GC_finalizer_notifier = fn;
  2130. UNLOCK();
  2131. }
  2132. GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void)
  2133. {
  2134. GC_finalizer_notifier_proc fn;
  2135. DCL_LOCK_STATE;
  2136. LOCK();
  2137. fn = GC_finalizer_notifier;
  2138. UNLOCK();
  2139. return fn;
  2140. }
  2141. /* Setter and getter functions for the public numeric R/W variables. */
  2142. /* It is safe to call these functions even before GC_INIT(). */
  2143. /* These functions are unsynchronized and should be typically called */
  2144. /* inside the context of GC_call_with_alloc_lock() (if called after */
  2145. /* GC_INIT()) to prevent data races (unless it is guaranteed the */
  2146. /* collector is not multi-threaded at that execution point). */
  2147. GC_API void GC_CALL GC_set_find_leak(int value)
  2148. {
  2149. /* value is of boolean type. */
  2150. GC_find_leak = value;
  2151. }
  2152. GC_API int GC_CALL GC_get_find_leak(void)
  2153. {
  2154. return GC_find_leak;
  2155. }
  2156. GC_API void GC_CALL GC_set_all_interior_pointers(int value)
  2157. {
  2158. DCL_LOCK_STATE;
  2159. GC_all_interior_pointers = value ? 1 : 0;
  2160. if (GC_is_initialized) {
  2161. /* It is not recommended to change GC_all_interior_pointers value */
  2162. /* after GC is initialized but it seems GC could work correctly */
  2163. /* even after switching the mode. */
  2164. LOCK();
  2165. GC_initialize_offsets(); /* NOTE: this resets manual offsets as well */
  2166. if (!GC_all_interior_pointers)
  2167. GC_bl_init_no_interiors();
  2168. UNLOCK();
  2169. }
  2170. }
  2171. GC_API int GC_CALL GC_get_all_interior_pointers(void)
  2172. {
  2173. return GC_all_interior_pointers;
  2174. }
  2175. GC_API void GC_CALL GC_set_finalize_on_demand(int value)
  2176. {
  2177. GC_ASSERT(value != -1);
  2178. /* value is of boolean type. */
  2179. GC_finalize_on_demand = value;
  2180. }
  2181. GC_API int GC_CALL GC_get_finalize_on_demand(void)
  2182. {
  2183. return GC_finalize_on_demand;
  2184. }
  2185. GC_API void GC_CALL GC_set_java_finalization(int value)
  2186. {
  2187. GC_ASSERT(value != -1);
  2188. /* value is of boolean type. */
  2189. GC_java_finalization = value;
  2190. }
  2191. GC_API int GC_CALL GC_get_java_finalization(void)
  2192. {
  2193. return GC_java_finalization;
  2194. }
  2195. GC_API void GC_CALL GC_set_dont_expand(int value)
  2196. {
  2197. GC_ASSERT(value != -1);
  2198. /* value is of boolean type. */
  2199. GC_dont_expand = value;
  2200. }
  2201. GC_API int GC_CALL GC_get_dont_expand(void)
  2202. {
  2203. return GC_dont_expand;
  2204. }
  2205. GC_API void GC_CALL GC_set_no_dls(int value)
  2206. {
  2207. GC_ASSERT(value != -1);
  2208. /* value is of boolean type. */
  2209. GC_no_dls = value;
  2210. }
  2211. GC_API int GC_CALL GC_get_no_dls(void)
  2212. {
  2213. return GC_no_dls;
  2214. }
  2215. GC_API void GC_CALL GC_set_non_gc_bytes(GC_word value)
  2216. {
  2217. GC_non_gc_bytes = value;
  2218. }
  2219. GC_API GC_word GC_CALL GC_get_non_gc_bytes(void)
  2220. {
  2221. return GC_non_gc_bytes;
  2222. }
  2223. GC_API void GC_CALL GC_set_free_space_divisor(GC_word value)
  2224. {
  2225. GC_ASSERT(value > 0);
  2226. GC_free_space_divisor = value;
  2227. }
  2228. GC_API GC_word GC_CALL GC_get_free_space_divisor(void)
  2229. {
  2230. return GC_free_space_divisor;
  2231. }
  2232. GC_API void GC_CALL GC_set_max_retries(GC_word value)
  2233. {
  2234. GC_ASSERT(value != ~(word)0);
  2235. GC_max_retries = value;
  2236. }
  2237. GC_API GC_word GC_CALL GC_get_max_retries(void)
  2238. {
  2239. return GC_max_retries;
  2240. }
  2241. GC_API void GC_CALL GC_set_dont_precollect(int value)
  2242. {
  2243. GC_ASSERT(value != -1);
  2244. /* value is of boolean type. */
  2245. GC_dont_precollect = value;
  2246. }
  2247. GC_API int GC_CALL GC_get_dont_precollect(void)
  2248. {
  2249. return GC_dont_precollect;
  2250. }
  2251. GC_API void GC_CALL GC_set_full_freq(int value)
  2252. {
  2253. GC_ASSERT(value >= 0);
  2254. GC_full_freq = value;
  2255. }
  2256. GC_API int GC_CALL GC_get_full_freq(void)
  2257. {
  2258. return GC_full_freq;
  2259. }
  2260. GC_API void GC_CALL GC_set_time_limit(unsigned long value)
  2261. {
  2262. GC_ASSERT(value != (unsigned long)-1L);
  2263. GC_time_limit = value * 1000000;
  2264. }
  2265. GC_API unsigned long GC_CALL GC_get_time_limit(void)
  2266. {
  2267. return (unsigned long)(GC_time_limit / 1000000);
  2268. }
  2269. GC_API void GC_CALL GC_set_time_limit_ns(unsigned long long value)
  2270. {
  2271. GC_ASSERT(value != (unsigned long long)-1L);
  2272. GC_time_limit = value;
  2273. }
  2274. GC_API unsigned long long GC_CALL GC_get_time_limit_ns(void)
  2275. {
  2276. return GC_time_limit;
  2277. }
  2278. GC_API void GC_CALL GC_set_force_unmap_on_gcollect(int value)
  2279. {
  2280. GC_force_unmap_on_gcollect = (GC_bool)value;
  2281. }
  2282. GC_API int GC_CALL GC_get_force_unmap_on_gcollect(void)
  2283. {
  2284. return (int)GC_force_unmap_on_gcollect;
  2285. }
  2286. /* Unity specific APIs */
  2287. GC_API void GC_CALL GC_stop_world_external()
  2288. {
  2289. LOCK();
  2290. STOP_WORLD();
  2291. }
  2292. GC_API void GC_CALL GC_start_world_external()
  2293. {
  2294. START_WORLD();
  2295. UNLOCK();
  2296. }
  2297. /* Disable incremental GC. Only tested with MANUAL_VDB mode. Might */
  2298. /* require extra teardown work when using other VDB configs.*/
  2299. GC_API void GC_CALL GC_disable_incremental(void)
  2300. {
  2301. LOCK();
  2302. GC_gcollect_inner();
  2303. #ifndef GC_DISABLE_INCREMENTAL
  2304. GC_incremental = FALSE;
  2305. #endif
  2306. UNLOCK();
  2307. }