alloc.c 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600
  1. /*
  2. * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
  3. * Copyright (c) 1991-1996 by Xerox Corporation. All rights reserved.
  4. * Copyright (c) 1998 by Silicon Graphics. All rights reserved.
  5. * Copyright (c) 1999-2004 Hewlett-Packard Development Company, L.P.
  6. *
  7. * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
  8. * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
  9. *
  10. * Permission is hereby granted to use or copy this program
  11. * for any purpose, provided the above notices are retained on all copies.
  12. * Permission to modify the code and to distribute modified code is granted,
  13. * provided the above notices are retained, and a notice that the code was
  14. * modified is included with the above copyright notice.
  15. *
  16. */
  17. #include "private/gc_priv.h"
  18. #include <stdio.h>
  19. #if !defined(MACOS) && !defined(MSWINCE)
  20. # include <signal.h>
  21. # if !defined(GC_NO_TYPES) && !defined(SN_TARGET_PSP2) \
  22. && !defined(__CC_ARM)
  23. # include <sys/types.h>
  24. # endif
  25. #endif
  26. #if VERIFY_UNITY_DEFINES
  27. #if ! (ALL_INTERIOR_POINTERS \
  28. && GC_GCJ_SUPPORT \
  29. && JAVA_FINALIZATION \
  30. && NO_EXECUTE_PERMISSION \
  31. && GC_VERSION_MAJOR == 7 \
  32. && GC_VERSION_MINOR == 7 \
  33. && GC_VERSION_MICRO == 0 \
  34. && GC_NO_THREADS_DISCOVERY \
  35. && IGNORE_DYNAMIC_LOADING \
  36. && GC_DONT_REGISTER_MAIN_STATIC_DATA \
  37. && GC_THREADS \
  38. && USE_MMAP \
  39. && USE_MUNMAP)
  40. #error Unity Defines Incorrect
  41. #endif
  42. #endif
  43. /*
  44. * Separate free lists are maintained for different sized objects
  45. * up to MAXOBJBYTES.
  46. * The call GC_allocobj(i,k) ensures that the freelist for
  47. * kind k objects of size i points to a non-empty
  48. * free list. It returns a pointer to the first entry on the free list.
  49. * In a single-threaded world, GC_allocobj may be called to allocate
  50. * an object of small size lb (and NORMAL kind) as follows
  51. * (GC_generic_malloc_inner is a wrapper over GC_allocobj which also
  52. * fills in GC_size_map if needed):
  53. *
  54. * lg = GC_size_map[lb];
  55. * op = GC_objfreelist[lg];
  56. * if (NULL == op) {
  57. * op = GC_generic_malloc_inner(lb, NORMAL);
  58. * } else {
  59. * GC_objfreelist[lg] = obj_link(op);
  60. * GC_bytes_allocd += GRANULES_TO_BYTES((word)lg);
  61. * }
  62. *
  63. * Note that this is very fast if the free list is non-empty; it should
  64. * only involve the execution of 4 or 5 simple instructions.
  65. * All composite objects on freelists are cleared, except for
  66. * their first word.
  67. */
  68. /*
  69. * The allocator uses GC_allochblk to allocate large chunks of objects.
  70. * These chunks all start on addresses which are multiples of
  71. * HBLKSZ. Each allocated chunk has an associated header,
  72. * which can be located quickly based on the address of the chunk.
  73. * (See headers.c for details.)
  74. * This makes it possible to check quickly whether an
  75. * arbitrary address corresponds to an object administered by the
  76. * allocator.
  77. */
  78. word GC_non_gc_bytes = 0; /* Number of bytes not intended to be collected */
  79. word GC_gc_no = 0;
  80. #ifndef NO_CLOCK
  81. static unsigned long full_gc_total_time = 0; /* in msecs, may wrap */
  82. static GC_bool measure_performance = FALSE;
  83. /* Do performance measurements if set to true (e.g., */
  84. /* accumulation of the total time of full collections). */
  85. GC_API void GC_CALL GC_start_performance_measurement(void)
  86. {
  87. measure_performance = TRUE;
  88. }
  89. GC_API unsigned long GC_CALL GC_get_full_gc_total_time(void)
  90. {
  91. return full_gc_total_time;
  92. }
  93. #endif /* !NO_CLOCK */
  94. #ifndef GC_DISABLE_INCREMENTAL
  95. GC_INNER GC_bool GC_incremental = FALSE; /* By default, stop the world. */
  96. #endif
  97. GC_API int GC_CALL GC_is_incremental_mode(void)
  98. {
  99. return (int)GC_incremental;
  100. }
  101. #ifdef THREADS
  102. int GC_parallel = FALSE; /* By default, parallel GC is off. */
  103. #endif
  104. #if defined(GC_FULL_FREQ) && !defined(CPPCHECK)
  105. int GC_full_freq = GC_FULL_FREQ;
  106. #else
  107. int GC_full_freq = 19; /* Every 20th collection is a full */
  108. /* collection, whether we need it */
  109. /* or not. */
  110. #endif
  111. STATIC GC_bool GC_need_full_gc = FALSE;
  112. /* Need full GC do to heap growth. */
  113. #ifdef THREAD_LOCAL_ALLOC
  114. GC_INNER GC_bool GC_world_stopped = FALSE;
  115. #endif
  116. STATIC word GC_used_heap_size_after_full = 0;
  117. /* GC_copyright symbol is externally visible. */
  118. EXTERN_C_BEGIN
  119. extern const char * const GC_copyright[];
  120. EXTERN_C_END
  121. const char * const GC_copyright[] =
  122. {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
  123. "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
  124. "Copyright (c) 1996-1998 by Silicon Graphics. All rights reserved. ",
  125. "Copyright (c) 1999-2009 by Hewlett-Packard Company. All rights reserved. ",
  126. "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
  127. " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
  128. "See source code for details." };
  129. /* Version macros are now defined in gc_version.h, which is included by */
  130. /* gc.h, which is included by gc_priv.h. */
  131. #ifndef GC_NO_VERSION_VAR
  132. EXTERN_C_BEGIN
  133. extern const unsigned GC_version;
  134. EXTERN_C_END
  135. const unsigned GC_version = ((GC_VERSION_MAJOR << 16) |
  136. (GC_VERSION_MINOR << 8) | GC_VERSION_MICRO);
  137. #endif
  138. GC_API unsigned GC_CALL GC_get_version(void)
  139. {
  140. return (GC_VERSION_MAJOR << 16) | (GC_VERSION_MINOR << 8) |
  141. GC_VERSION_MICRO;
  142. }
  143. /* some more variables */
  144. #ifdef GC_DONT_EXPAND
  145. int GC_dont_expand = TRUE;
  146. #else
  147. int GC_dont_expand = FALSE;
  148. #endif
  149. #if defined(GC_FREE_SPACE_DIVISOR) && !defined(CPPCHECK)
  150. word GC_free_space_divisor = GC_FREE_SPACE_DIVISOR; /* must be > 0 */
  151. #else
  152. word GC_free_space_divisor = 3;
  153. #endif
  154. GC_INNER int GC_CALLBACK GC_never_stop_func(void)
  155. {
  156. return(0);
  157. }
  158. #if defined(GC_TIME_LIMIT) && !defined(CPPCHECK)
  159. unsigned long long GC_time_limit = GC_TIME_LIMIT * 1000000;
  160. /* We try to keep pause times from exceeding */
  161. /* this by much. In milliseconds. */
  162. #else
  163. unsigned long long GC_time_limit = 50000000;
  164. #endif
  165. #ifndef NO_CLOCK
  166. STATIC CLOCK_TYPE GC_start_time = 0;
  167. /* Time at which we stopped world. */
  168. /* used only in GC_timeout_stop_func. */
  169. #endif
  170. STATIC int GC_n_attempts = 0; /* Number of attempts at finishing */
  171. /* collection within GC_time_limit. */
  172. STATIC GC_stop_func GC_default_stop_func = GC_never_stop_func;
  173. /* accessed holding the lock. */
  174. GC_API void GC_CALL GC_set_stop_func(GC_stop_func stop_func)
  175. {
  176. DCL_LOCK_STATE;
  177. GC_ASSERT(NONNULL_ARG_NOT_NULL(stop_func));
  178. LOCK();
  179. GC_default_stop_func = stop_func;
  180. UNLOCK();
  181. }
  182. GC_API GC_stop_func GC_CALL GC_get_stop_func(void)
  183. {
  184. GC_stop_func stop_func;
  185. DCL_LOCK_STATE;
  186. LOCK();
  187. stop_func = GC_default_stop_func;
  188. UNLOCK();
  189. return stop_func;
  190. }
  191. #if defined(GC_DISABLE_INCREMENTAL) || defined(NO_CLOCK)
  192. # define GC_timeout_stop_func GC_default_stop_func
  193. #else
  194. STATIC int GC_CALLBACK GC_timeout_stop_func (void)
  195. {
  196. CLOCK_TYPE current_time;
  197. static unsigned count = 0;
  198. unsigned long long time_diff;
  199. if ((*GC_default_stop_func)())
  200. return(1);
  201. if ((count++ & 3) != 0) return(0);
  202. GET_TIME(current_time);
  203. time_diff = NS_TIME_DIFF(current_time,GC_start_time);
  204. if (time_diff >= GC_time_limit) {
  205. GC_COND_LOG_PRINTF(
  206. "Abandoning stopped marking after %llu nanoseconds (attempt %d)\n",
  207. time_diff, GC_n_attempts);
  208. return(1);
  209. }
  210. return(0);
  211. }
  212. #endif /* !GC_DISABLE_INCREMENTAL */
  213. #ifdef THREADS
  214. GC_INNER word GC_total_stacksize = 0; /* updated on every push_all_stacks */
  215. #endif
  216. static size_t min_bytes_allocd_minimum = 1;
  217. /* The lowest value returned by min_bytes_allocd(). */
  218. GC_API void GC_CALL GC_set_min_bytes_allocd(size_t value)
  219. {
  220. GC_ASSERT(value > 0);
  221. min_bytes_allocd_minimum = value;
  222. }
  223. GC_API size_t GC_CALL GC_get_min_bytes_allocd(void)
  224. {
  225. return min_bytes_allocd_minimum;
  226. }
  227. /* Return the minimum number of bytes that must be allocated between */
  228. /* collections to amortize the collection cost. Should be non-zero. */
  229. static word min_bytes_allocd(void)
  230. {
  231. word result;
  232. word stack_size;
  233. word total_root_size; /* includes double stack size, */
  234. /* since the stack is expensive */
  235. /* to scan. */
  236. word scan_size; /* Estimate of memory to be scanned */
  237. /* during normal GC. */
  238. # ifdef THREADS
  239. if (GC_need_to_lock) {
  240. /* We are multi-threaded... */
  241. stack_size = GC_total_stacksize;
  242. /* For now, we just use the value computed during the latest GC. */
  243. # ifdef DEBUG_THREADS
  244. GC_log_printf("Total stacks size: %lu\n",
  245. (unsigned long)stack_size);
  246. # endif
  247. } else
  248. # endif
  249. /* else*/ {
  250. # ifdef STACK_NOT_SCANNED
  251. stack_size = 0;
  252. # elif defined(STACK_GROWS_UP)
  253. stack_size = GC_approx_sp() - GC_stackbottom;
  254. # else
  255. stack_size = GC_stackbottom - GC_approx_sp();
  256. # endif
  257. }
  258. total_root_size = 2 * stack_size + GC_root_size;
  259. scan_size = 2 * GC_composite_in_use + GC_atomic_in_use / 4
  260. + total_root_size;
  261. result = scan_size / GC_free_space_divisor;
  262. if (GC_incremental) {
  263. result /= 2;
  264. }
  265. return result > min_bytes_allocd_minimum
  266. ? result : min_bytes_allocd_minimum;
  267. }
  268. STATIC word GC_non_gc_bytes_at_gc = 0;
  269. /* Number of explicitly managed bytes of storage */
  270. /* at last collection. */
  271. /* Return the number of bytes allocated, adjusted for explicit storage */
  272. /* management, etc.. This number is used in deciding when to trigger */
  273. /* collections. */
  274. STATIC word GC_adj_bytes_allocd(void)
  275. {
  276. signed_word result;
  277. signed_word expl_managed = (signed_word)GC_non_gc_bytes
  278. - (signed_word)GC_non_gc_bytes_at_gc;
  279. /* Don't count what was explicitly freed, or newly allocated for */
  280. /* explicit management. Note that deallocating an explicitly */
  281. /* managed object should not alter result, assuming the client */
  282. /* is playing by the rules. */
  283. result = (signed_word)GC_bytes_allocd
  284. + (signed_word)GC_bytes_dropped
  285. - (signed_word)GC_bytes_freed
  286. + (signed_word)GC_finalizer_bytes_freed
  287. - expl_managed;
  288. if (result > (signed_word)GC_bytes_allocd) {
  289. result = GC_bytes_allocd;
  290. /* probably client bug or unfortunate scheduling */
  291. }
  292. result += GC_bytes_finalized;
  293. /* We count objects enqueued for finalization as though they */
  294. /* had been reallocated this round. Finalization is user */
  295. /* visible progress. And if we don't count this, we have */
  296. /* stability problems for programs that finalize all objects. */
  297. if (result < (signed_word)(GC_bytes_allocd >> 3)) {
  298. /* Always count at least 1/8 of the allocations. We don't want */
  299. /* to collect too infrequently, since that would inhibit */
  300. /* coalescing of free storage blocks. */
  301. /* This also makes us partially robust against client bugs. */
  302. return(GC_bytes_allocd >> 3);
  303. } else {
  304. return(result);
  305. }
  306. }
  307. /* Clear up a few frames worth of garbage left at the top of the stack. */
  308. /* This is used to prevent us from accidentally treating garbage left */
  309. /* on the stack by other parts of the collector as roots. This */
  310. /* differs from the code in misc.c, which actually tries to keep the */
  311. /* stack clear of long-lived, client-generated garbage. */
  312. STATIC void GC_clear_a_few_frames(void)
  313. {
  314. # ifndef CLEAR_NWORDS
  315. # define CLEAR_NWORDS 64
  316. # endif
  317. volatile word frames[CLEAR_NWORDS];
  318. BZERO((word *)frames, CLEAR_NWORDS * sizeof(word));
  319. }
  320. /* Heap size at which we need a collection to avoid expanding past */
  321. /* limits used by blacklisting. */
  322. STATIC word GC_collect_at_heapsize = (word)(-1);
  323. STATIC GC_bool GC_should_start_incremental_collection = FALSE;
  324. STATIC GC_bool GC_disable_automatic_collection = FALSE;
  325. GC_API void GC_set_disable_automatic_collection(GC_bool disable)
  326. {
  327. GC_disable_automatic_collection = disable;
  328. }
  329. GC_API void GC_start_incremental_collection()
  330. {
  331. if (GC_incremental)
  332. {
  333. GC_should_start_incremental_collection = TRUE;
  334. GC_collect_a_little();
  335. }
  336. }
  337. /* Have we allocated enough to amortize a collection? */
  338. GC_INNER GC_bool GC_should_collect(void)
  339. {
  340. static word last_min_bytes_allocd;
  341. static word last_gc_no;
  342. if (last_gc_no != GC_gc_no) {
  343. last_gc_no = GC_gc_no;
  344. last_min_bytes_allocd = min_bytes_allocd();
  345. }
  346. if (GC_should_start_incremental_collection)
  347. {
  348. GC_should_start_incremental_collection = FALSE;
  349. return TRUE;
  350. }
  351. if (GC_disable_automatic_collection)
  352. return FALSE;
  353. return(GC_adj_bytes_allocd() >= last_min_bytes_allocd
  354. || GC_heapsize >= GC_collect_at_heapsize);
  355. }
  356. /* STATIC */ GC_start_callback_proc GC_start_call_back = 0;
  357. /* Called at start of full collections. */
  358. /* Not called if 0. Called with the allocation */
  359. /* lock held. Not used by GC itself. */
  360. GC_API void GC_CALL GC_set_start_callback(GC_start_callback_proc fn)
  361. {
  362. DCL_LOCK_STATE;
  363. LOCK();
  364. GC_start_call_back = fn;
  365. UNLOCK();
  366. }
  367. GC_API GC_start_callback_proc GC_CALL GC_get_start_callback(void)
  368. {
  369. GC_start_callback_proc fn;
  370. DCL_LOCK_STATE;
  371. LOCK();
  372. fn = GC_start_call_back;
  373. UNLOCK();
  374. return fn;
  375. }
  376. GC_INLINE void GC_notify_full_gc(void)
  377. {
  378. if (GC_start_call_back != 0) {
  379. (*GC_start_call_back)();
  380. }
  381. }
  382. STATIC GC_bool GC_is_full_gc = FALSE;
  383. STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func);
  384. STATIC void GC_finish_collection(void);
  385. /*
  386. * Initiate a garbage collection if appropriate.
  387. * Choose judiciously
  388. * between partial, full, and stop-world collections.
  389. */
  390. STATIC void GC_maybe_gc(void)
  391. {
  392. GC_ASSERT(I_HOLD_LOCK());
  393. ASSERT_CANCEL_DISABLED();
  394. if (GC_should_collect()) {
  395. static int n_partial_gcs = 0;
  396. if (!GC_incremental) {
  397. /* FIXME: If possible, GC_default_stop_func should be used here */
  398. GC_try_to_collect_inner(GC_never_stop_func);
  399. n_partial_gcs = 0;
  400. return;
  401. } else {
  402. # ifdef PARALLEL_MARK
  403. if (GC_parallel)
  404. GC_wait_for_reclaim();
  405. # endif
  406. if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
  407. GC_COND_LOG_PRINTF(
  408. "***>Full mark for collection #%lu after %lu allocd bytes\n",
  409. (unsigned long)GC_gc_no + 1, (unsigned long)GC_bytes_allocd);
  410. GC_promote_black_lists();
  411. (void)GC_reclaim_all((GC_stop_func)0, TRUE);
  412. GC_notify_full_gc();
  413. GC_clear_marks();
  414. n_partial_gcs = 0;
  415. GC_is_full_gc = TRUE;
  416. } else {
  417. n_partial_gcs++;
  418. }
  419. }
  420. /* We try to mark with the world stopped. */
  421. /* If we run out of time, this turns into */
  422. /* incremental marking. */
  423. # ifndef NO_CLOCK
  424. if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
  425. # endif
  426. /* FIXME: If possible, GC_default_stop_func should be */
  427. /* used instead of GC_never_stop_func here. */
  428. if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
  429. GC_never_stop_func : GC_timeout_stop_func)) {
  430. # ifdef SAVE_CALL_CHAIN
  431. GC_save_callers(GC_last_stack);
  432. # endif
  433. GC_finish_collection();
  434. } else {
  435. if (!GC_is_full_gc) {
  436. /* Count this as the first attempt */
  437. GC_n_attempts++;
  438. }
  439. }
  440. }
  441. }
  442. STATIC GC_on_collection_event_proc GC_on_collection_event = 0;
  443. GC_API void GC_CALL GC_set_on_collection_event(GC_on_collection_event_proc fn)
  444. {
  445. /* fn may be 0 (means no event notifier). */
  446. DCL_LOCK_STATE;
  447. LOCK();
  448. GC_on_collection_event = fn;
  449. UNLOCK();
  450. }
  451. GC_API GC_on_collection_event_proc GC_CALL GC_get_on_collection_event(void)
  452. {
  453. GC_on_collection_event_proc fn;
  454. DCL_LOCK_STATE;
  455. LOCK();
  456. fn = GC_on_collection_event;
  457. UNLOCK();
  458. return fn;
  459. }
  460. /* Stop the world garbage collection. If stop_func is not */
  461. /* GC_never_stop_func then abort if stop_func returns TRUE. */
  462. /* Return TRUE if we successfully completed the collection. */
  463. GC_INNER GC_bool GC_try_to_collect_inner(GC_stop_func stop_func)
  464. {
  465. # ifndef NO_CLOCK
  466. CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */
  467. GC_bool start_time_valid;
  468. # endif
  469. ASSERT_CANCEL_DISABLED();
  470. GC_ASSERT(I_HOLD_LOCK());
  471. if (GC_dont_gc || (*stop_func)()) return FALSE;
  472. if (GC_on_collection_event)
  473. GC_on_collection_event(GC_EVENT_START);
  474. if (GC_incremental && GC_collection_in_progress()) {
  475. GC_COND_LOG_PRINTF(
  476. "GC_try_to_collect_inner: finishing collection in progress\n");
  477. /* Just finish collection already in progress. */
  478. while(GC_collection_in_progress()) {
  479. if ((*stop_func)()) {
  480. /* TODO: Notify GC_EVENT_ABANDON */
  481. return(FALSE);
  482. }
  483. GC_collect_a_little_inner(1);
  484. }
  485. }
  486. GC_notify_full_gc();
  487. # ifndef NO_CLOCK
  488. start_time_valid = FALSE;
  489. if ((GC_print_stats | (int)measure_performance) != 0) {
  490. if (GC_print_stats)
  491. GC_log_printf("Initiating full world-stop collection!\n");
  492. start_time_valid = TRUE;
  493. GET_TIME(start_time);
  494. }
  495. # endif
  496. GC_promote_black_lists();
  497. /* Make sure all blocks have been reclaimed, so sweep routines */
  498. /* don't see cleared mark bits. */
  499. /* If we're guaranteed to finish, then this is unnecessary. */
  500. /* In the find_leak case, we have to finish to guarantee that */
  501. /* previously unmarked objects are not reported as leaks. */
  502. # ifdef PARALLEL_MARK
  503. if (GC_parallel)
  504. GC_wait_for_reclaim();
  505. # endif
  506. if ((GC_find_leak || stop_func != GC_never_stop_func)
  507. && !GC_reclaim_all(stop_func, FALSE)) {
  508. /* Aborted. So far everything is still consistent. */
  509. /* TODO: Notify GC_EVENT_ABANDON */
  510. return(FALSE);
  511. }
  512. GC_invalidate_mark_state(); /* Flush mark stack. */
  513. GC_clear_marks();
  514. # ifdef SAVE_CALL_CHAIN
  515. GC_save_callers(GC_last_stack);
  516. # endif
  517. GC_is_full_gc = TRUE;
  518. if (!GC_stopped_mark(stop_func)) {
  519. if (!GC_incremental) {
  520. /* We're partially done and have no way to complete or use */
  521. /* current work. Reestablish invariants as cheaply as */
  522. /* possible. */
  523. GC_invalidate_mark_state();
  524. GC_unpromote_black_lists();
  525. } /* else we claim the world is already still consistent. We'll */
  526. /* finish incrementally. */
  527. /* TODO: Notify GC_EVENT_ABANDON */
  528. return(FALSE);
  529. }
  530. GC_finish_collection();
  531. # ifndef NO_CLOCK
  532. if (start_time_valid) {
  533. CLOCK_TYPE current_time;
  534. unsigned long time_diff;
  535. GET_TIME(current_time);
  536. time_diff = MS_TIME_DIFF(current_time, start_time);
  537. if (measure_performance)
  538. full_gc_total_time += time_diff; /* may wrap */
  539. if (GC_print_stats)
  540. GC_log_printf("Complete collection took %lu msecs\n", time_diff);
  541. }
  542. # endif
  543. if (GC_on_collection_event)
  544. GC_on_collection_event(GC_EVENT_END);
  545. return(TRUE);
  546. }
  547. /*
  548. * Perform n units of garbage collection work. A unit is intended to touch
  549. * roughly GC_rate pages. Every once in a while, we do more than that.
  550. * This needs to be a fairly large number with our current incremental
  551. * GC strategy, since otherwise we allocate too much during GC, and the
  552. * cleanup gets expensive.
  553. */
  554. #ifndef GC_RATE
  555. # define GC_RATE 10
  556. #endif
  557. #ifndef MAX_PRIOR_ATTEMPTS
  558. # define MAX_PRIOR_ATTEMPTS 1
  559. #endif
  560. /* Maximum number of prior attempts at world stop marking */
  561. /* A value of 1 means that we finish the second time, no matter */
  562. /* how long it takes. Doesn't count the initial root scan */
  563. /* for a full GC. */
  564. STATIC int GC_deficit = 0;/* The number of extra calls to GC_mark_some */
  565. /* that we have made. */
  566. STATIC int GC_rate = GC_RATE;
  567. GC_API void GC_CALL GC_set_rate(int value)
  568. {
  569. GC_ASSERT(value > 0);
  570. GC_rate = value;
  571. }
  572. GC_API int GC_CALL GC_get_rate(void)
  573. {
  574. return GC_rate;
  575. }
  576. static int max_prior_attempts = MAX_PRIOR_ATTEMPTS;
  577. GC_API void GC_CALL GC_set_max_prior_attempts(int value)
  578. {
  579. GC_ASSERT(value >= 0);
  580. max_prior_attempts = value;
  581. }
  582. GC_API int GC_CALL GC_get_max_prior_attempts(void)
  583. {
  584. return max_prior_attempts;
  585. }
  586. GC_INNER void GC_collect_a_little_inner(int n)
  587. {
  588. IF_CANCEL(int cancel_state;)
  589. GC_ASSERT(I_HOLD_LOCK());
  590. DISABLE_CANCEL(cancel_state);
  591. if (GC_incremental && GC_collection_in_progress()) {
  592. int i;
  593. int max_deficit = GC_rate * n;
  594. for (i = GC_deficit; i < max_deficit; i++) {
  595. if (GC_mark_some((ptr_t)0)) {
  596. if (GC_dont_gc) break;
  597. /* Need to finish a collection */
  598. # ifdef SAVE_CALL_CHAIN
  599. GC_save_callers(GC_last_stack);
  600. # endif
  601. # ifdef PARALLEL_MARK
  602. if (GC_parallel)
  603. GC_wait_for_reclaim();
  604. # endif
  605. if (GC_n_attempts < max_prior_attempts
  606. && GC_time_limit != GC_TIME_UNLIMITED) {
  607. # ifndef NO_CLOCK
  608. GET_TIME(GC_start_time);
  609. # endif
  610. if (!GC_stopped_mark(GC_timeout_stop_func)) {
  611. GC_n_attempts++;
  612. break;
  613. }
  614. } else {
  615. /* FIXME: If possible, GC_default_stop_func should be */
  616. /* used here. */
  617. (void)GC_stopped_mark(GC_never_stop_func);
  618. }
  619. GC_finish_collection();
  620. break;
  621. }
  622. }
  623. if (GC_deficit > 0) {
  624. GC_deficit -= max_deficit;
  625. if (GC_deficit < 0)
  626. GC_deficit = 0;
  627. }
  628. } else if (!GC_dont_gc) {
  629. GC_maybe_gc();
  630. }
  631. RESTORE_CANCEL(cancel_state);
  632. }
  633. GC_INNER void (*GC_check_heap)(void) = 0;
  634. GC_INNER void (*GC_print_all_smashed)(void) = 0;
  635. GC_API int GC_CALL GC_collect_a_little(void)
  636. {
  637. int result;
  638. DCL_LOCK_STATE;
  639. LOCK();
  640. if (!GC_dont_gc) {
  641. GC_collect_a_little_inner(1);
  642. }
  643. result = (int)GC_collection_in_progress();
  644. UNLOCK();
  645. if (!result && GC_debugging_started) GC_print_all_smashed();
  646. return(result);
  647. }
  648. #ifndef NO_CLOCK
  649. /* Variables for world-stop average delay time statistic computation. */
  650. /* "divisor" is incremented every world-stop and halved when reached */
  651. /* its maximum (or upon "total_time" overflow). */
  652. static unsigned world_stopped_total_time = 0;
  653. static unsigned world_stopped_total_divisor = 0;
  654. # ifndef MAX_TOTAL_TIME_DIVISOR
  655. /* We shall not use big values here (so "outdated" delay time */
  656. /* values would have less impact on "average" delay time value than */
  657. /* newer ones). */
  658. # define MAX_TOTAL_TIME_DIVISOR 1000
  659. # endif
  660. #endif /* !NO_CLOCK */
  661. #ifdef USE_MUNMAP
  662. # define IF_USE_MUNMAP(x) x
  663. # define COMMA_IF_USE_MUNMAP(x) /* comma */, x
  664. #else
  665. # define IF_USE_MUNMAP(x) /* empty */
  666. # define COMMA_IF_USE_MUNMAP(x) /* empty */
  667. #endif
  668. /*
  669. * We stop the world and mark from all roots.
  670. * If stop_func() ever returns TRUE, we may fail and return FALSE.
  671. * Increment GC_gc_no if we succeed.
  672. */
  673. STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func)
  674. {
  675. unsigned i;
  676. # ifndef NO_CLOCK
  677. CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */
  678. # endif
  679. GC_ASSERT(I_HOLD_LOCK());
  680. # if !defined(REDIRECT_MALLOC) && defined(USE_WINALLOC)
  681. GC_add_current_malloc_heap();
  682. # endif
  683. # if defined(REGISTER_LIBRARIES_EARLY)
  684. GC_cond_register_dynamic_libraries();
  685. # endif
  686. # ifndef NO_CLOCK
  687. if (GC_PRINT_STATS_FLAG)
  688. GET_TIME(start_time);
  689. # endif
  690. # if !defined(GC_NO_FINALIZATION) && !defined(GC_TOGGLE_REFS_NOT_NEEDED)
  691. GC_process_togglerefs();
  692. # endif
  693. # ifdef THREADS
  694. if (GC_on_collection_event)
  695. GC_on_collection_event(GC_EVENT_PRE_STOP_WORLD);
  696. # endif
  697. STOP_WORLD();
  698. # ifdef THREADS
  699. if (GC_on_collection_event)
  700. GC_on_collection_event(GC_EVENT_POST_STOP_WORLD);
  701. # endif
  702. # ifdef THREAD_LOCAL_ALLOC
  703. GC_world_stopped = TRUE;
  704. # endif
  705. /* Output blank line for convenience here */
  706. GC_COND_LOG_PRINTF(
  707. "\n--> Marking for collection #%lu after %lu allocated bytes\n",
  708. (unsigned long)GC_gc_no + 1, (unsigned long) GC_bytes_allocd);
  709. # ifdef MAKE_BACK_GRAPH
  710. if (GC_print_back_height) {
  711. GC_build_back_graph();
  712. }
  713. # endif
  714. /* Mark from all roots. */
  715. if (GC_on_collection_event)
  716. GC_on_collection_event(GC_EVENT_MARK_START);
  717. /* Minimize junk left in my registers and on the stack */
  718. GC_clear_a_few_frames();
  719. GC_noop6(0,0,0,0,0,0);
  720. GC_initiate_gc();
  721. for (i = 0;;i++) {
  722. if ((*stop_func)()) {
  723. GC_COND_LOG_PRINTF("Abandoned stopped marking after"
  724. " %u iterations\n", i);
  725. GC_deficit = i; /* Give the mutator a chance. */
  726. # ifdef THREAD_LOCAL_ALLOC
  727. GC_world_stopped = FALSE;
  728. # endif
  729. # ifdef THREADS
  730. if (GC_on_collection_event)
  731. GC_on_collection_event(GC_EVENT_PRE_START_WORLD);
  732. # endif
  733. START_WORLD();
  734. # ifdef THREADS
  735. if (GC_on_collection_event)
  736. GC_on_collection_event(GC_EVENT_POST_START_WORLD);
  737. # endif
  738. /* TODO: Notify GC_EVENT_MARK_ABANDON */
  739. return(FALSE);
  740. }
  741. if (GC_mark_some(GC_approx_sp())) break;
  742. }
  743. GC_gc_no++;
  744. GC_DBGLOG_PRINTF("GC #%lu freed %ld bytes, heap %lu KiB"
  745. IF_USE_MUNMAP(" (+ %lu KiB unmapped)") "\n",
  746. (unsigned long)GC_gc_no, (long)GC_bytes_found,
  747. TO_KiB_UL(GC_heapsize - GC_unmapped_bytes) /*, */
  748. COMMA_IF_USE_MUNMAP(TO_KiB_UL(GC_unmapped_bytes)));
  749. /* Check all debugged objects for consistency */
  750. if (GC_debugging_started) {
  751. (*GC_check_heap)();
  752. }
  753. if (GC_on_collection_event)
  754. GC_on_collection_event(GC_EVENT_MARK_END);
  755. # ifdef THREAD_LOCAL_ALLOC
  756. GC_world_stopped = FALSE;
  757. # endif
  758. # ifdef THREADS
  759. if (GC_on_collection_event)
  760. GC_on_collection_event(GC_EVENT_PRE_START_WORLD);
  761. # endif
  762. START_WORLD();
  763. # ifdef THREADS
  764. if (GC_on_collection_event)
  765. GC_on_collection_event(GC_EVENT_POST_START_WORLD);
  766. # endif
  767. # ifndef NO_CLOCK
  768. if (GC_PRINT_STATS_FLAG) {
  769. unsigned long time_diff;
  770. unsigned total_time, divisor;
  771. CLOCK_TYPE current_time;
  772. GET_TIME(current_time);
  773. time_diff = MS_TIME_DIFF(current_time,start_time);
  774. /* Compute new world-stop delay total time */
  775. total_time = world_stopped_total_time;
  776. divisor = world_stopped_total_divisor;
  777. if ((int)total_time < 0 || divisor >= MAX_TOTAL_TIME_DIVISOR) {
  778. /* Halve values if overflow occurs */
  779. total_time >>= 1;
  780. divisor >>= 1;
  781. }
  782. total_time += time_diff < (((unsigned)-1) >> 1) ?
  783. (unsigned)time_diff : ((unsigned)-1) >> 1;
  784. /* Update old world_stopped_total_time and its divisor */
  785. world_stopped_total_time = total_time;
  786. world_stopped_total_divisor = ++divisor;
  787. GC_ASSERT(divisor != 0);
  788. GC_log_printf(
  789. "World-stopped marking took %lu msecs (%u in average)\n",
  790. time_diff, total_time / divisor);
  791. }
  792. # endif
  793. return(TRUE);
  794. }
  795. /* Set all mark bits for the free list whose first entry is q */
  796. GC_INNER void GC_set_fl_marks(ptr_t q)
  797. {
  798. if (q != NULL) {
  799. struct hblk *h = HBLKPTR(q);
  800. struct hblk *last_h = h;
  801. hdr *hhdr = HDR(h);
  802. IF_PER_OBJ(word sz = hhdr->hb_sz;)
  803. for (;;) {
  804. word bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz);
  805. if (!mark_bit_from_hdr(hhdr, bit_no)) {
  806. set_mark_bit_from_hdr(hhdr, bit_no);
  807. ++hhdr -> hb_n_marks;
  808. }
  809. q = (ptr_t)obj_link(q);
  810. if (q == NULL)
  811. break;
  812. h = HBLKPTR(q);
  813. if (h != last_h) {
  814. last_h = h;
  815. hhdr = HDR(h);
  816. IF_PER_OBJ(sz = hhdr->hb_sz;)
  817. }
  818. }
  819. }
  820. }
  821. #if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
  822. /* Check that all mark bits for the free list whose first entry is */
  823. /* (*pfreelist) are set. Check skipped if points to a special value. */
  824. void GC_check_fl_marks(void **pfreelist)
  825. {
  826. /* TODO: There is a data race with GC_FAST_MALLOC_GRANS (which does */
  827. /* not do atomic updates to the free-list). The race seems to be */
  828. /* harmless, and for now we just skip this check in case of TSan. */
  829. # if defined(AO_HAVE_load_acquire_read) && !defined(THREAD_SANITIZER)
  830. AO_t *list = (AO_t *)AO_load_acquire_read((AO_t *)pfreelist);
  831. /* Atomic operations are used because the world is running. */
  832. AO_t *prev;
  833. AO_t *p;
  834. if ((word)list <= HBLKSIZE) return;
  835. prev = (AO_t *)pfreelist;
  836. for (p = list; p != NULL;) {
  837. AO_t *next;
  838. if (!GC_is_marked(p)) {
  839. ABORT_ARG2("Unmarked local free list entry",
  840. ": object %p on list %p", (void *)p, (void *)list);
  841. }
  842. /* While traversing the free-list, it re-reads the pointer to */
  843. /* the current node before accepting its next pointer and */
  844. /* bails out if the latter has changed. That way, it won't */
  845. /* try to follow the pointer which might be been modified */
  846. /* after the object was returned to the client. It might */
  847. /* perform the mark-check on the just allocated object but */
  848. /* that should be harmless. */
  849. next = (AO_t *)AO_load_acquire_read(p);
  850. if (AO_load(prev) != (AO_t)p)
  851. break;
  852. prev = p;
  853. p = next;
  854. }
  855. # else
  856. /* FIXME: Not implemented (just skipped). */
  857. (void)pfreelist;
  858. # endif
  859. }
  860. #endif /* GC_ASSERTIONS && THREAD_LOCAL_ALLOC */
  861. /* Clear all mark bits for the free list whose first entry is q */
  862. /* Decrement GC_bytes_found by number of bytes on free list. */
  863. STATIC void GC_clear_fl_marks(ptr_t q)
  864. {
  865. struct hblk *h = HBLKPTR(q);
  866. struct hblk *last_h = h;
  867. hdr *hhdr = HDR(h);
  868. word sz = hhdr->hb_sz; /* Normally set only once. */
  869. for (;;) {
  870. word bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz);
  871. if (mark_bit_from_hdr(hhdr, bit_no)) {
  872. size_t n_marks = hhdr -> hb_n_marks;
  873. GC_ASSERT(n_marks != 0);
  874. clear_mark_bit_from_hdr(hhdr, bit_no);
  875. n_marks--;
  876. # ifdef PARALLEL_MARK
  877. /* Appr. count, don't decrement to zero! */
  878. if (0 != n_marks || !GC_parallel) {
  879. hhdr -> hb_n_marks = n_marks;
  880. }
  881. # else
  882. hhdr -> hb_n_marks = n_marks;
  883. # endif
  884. }
  885. GC_bytes_found -= sz;
  886. q = (ptr_t)obj_link(q);
  887. if (q == NULL)
  888. break;
  889. h = HBLKPTR(q);
  890. if (h != last_h) {
  891. last_h = h;
  892. hhdr = HDR(h);
  893. sz = hhdr->hb_sz;
  894. }
  895. }
  896. }
  897. #if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
  898. void GC_check_tls(void);
  899. #endif
  900. GC_on_heap_resize_proc GC_on_heap_resize = 0;
  901. /* Used for logging only. */
  902. GC_INLINE int GC_compute_heap_usage_percent(void)
  903. {
  904. word used = GC_composite_in_use + GC_atomic_in_use;
  905. word heap_sz = GC_heapsize - GC_unmapped_bytes;
  906. return used >= heap_sz ? 0 : used < ((word)-1) / 100 ?
  907. (int)((used * 100) / heap_sz) : (int)(used / (heap_sz / 100));
  908. }
  909. /* Finish up a collection. Assumes mark bits are consistent, lock is */
  910. /* held, but the world is otherwise running. */
  911. STATIC void GC_finish_collection(void)
  912. {
  913. # ifndef NO_CLOCK
  914. CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */
  915. CLOCK_TYPE finalize_time = 0;
  916. # endif
  917. GC_ASSERT(I_HOLD_LOCK());
  918. # if defined(GC_ASSERTIONS) \
  919. && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
  920. /* Check that we marked some of our own data. */
  921. /* FIXME: Add more checks. */
  922. GC_check_tls();
  923. # endif
  924. # ifndef NO_CLOCK
  925. if (GC_print_stats)
  926. GET_TIME(start_time);
  927. # endif
  928. if (GC_on_collection_event)
  929. GC_on_collection_event(GC_EVENT_RECLAIM_START);
  930. # ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
  931. if (GC_bytes_found > 0)
  932. GC_reclaimed_bytes_before_gc += (word)GC_bytes_found;
  933. # endif
  934. GC_bytes_found = 0;
  935. # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
  936. if (GETENV("GC_PRINT_ADDRESS_MAP") != 0) {
  937. GC_print_address_map();
  938. }
  939. # endif
  940. COND_DUMP;
  941. if (GC_find_leak) {
  942. /* Mark all objects on the free list. All objects should be */
  943. /* marked when we're done. */
  944. word size; /* current object size */
  945. unsigned kind;
  946. ptr_t q;
  947. for (kind = 0; kind < GC_n_kinds; kind++) {
  948. for (size = 1; size <= MAXOBJGRANULES; size++) {
  949. q = (ptr_t)GC_obj_kinds[kind].ok_freelist[size];
  950. if (q != NULL)
  951. GC_set_fl_marks(q);
  952. }
  953. }
  954. GC_start_reclaim(TRUE);
  955. /* The above just checks; it doesn't really reclaim anything. */
  956. }
  957. # ifndef GC_NO_FINALIZATION
  958. GC_finalize();
  959. # endif
  960. # ifndef NO_CLOCK
  961. if (GC_print_stats)
  962. GET_TIME(finalize_time);
  963. # endif
  964. if (GC_print_back_height) {
  965. # ifdef MAKE_BACK_GRAPH
  966. GC_traverse_back_graph();
  967. # elif !defined(SMALL_CONFIG)
  968. GC_err_printf("Back height not available: "
  969. "Rebuild collector with -DMAKE_BACK_GRAPH\n");
  970. # endif
  971. }
  972. /* Clear free list mark bits, in case they got accidentally marked */
  973. /* (or GC_find_leak is set and they were intentionally marked). */
  974. /* Also subtract memory remaining from GC_bytes_found count. */
  975. /* Note that composite objects on free list are cleared. */
  976. /* Thus accidentally marking a free list is not a problem; only */
  977. /* objects on the list itself will be marked, and that's fixed here. */
  978. {
  979. word size; /* current object size */
  980. ptr_t q; /* pointer to current object */
  981. unsigned kind;
  982. for (kind = 0; kind < GC_n_kinds; kind++) {
  983. for (size = 1; size <= MAXOBJGRANULES; size++) {
  984. q = (ptr_t)GC_obj_kinds[kind].ok_freelist[size];
  985. if (q != NULL)
  986. GC_clear_fl_marks(q);
  987. }
  988. }
  989. }
  990. GC_VERBOSE_LOG_PRINTF("Bytes recovered before sweep - f.l. count = %ld\n",
  991. (long)GC_bytes_found);
  992. /* Reconstruct free lists to contain everything not marked */
  993. GC_start_reclaim(FALSE);
  994. GC_DBGLOG_PRINTF("In-use heap: %d%% (%lu KiB pointers + %lu KiB other)\n",
  995. GC_compute_heap_usage_percent(),
  996. TO_KiB_UL(GC_composite_in_use),
  997. TO_KiB_UL(GC_atomic_in_use));
  998. if (GC_is_full_gc) {
  999. GC_used_heap_size_after_full = USED_HEAP_SIZE;
  1000. GC_need_full_gc = FALSE;
  1001. } else {
  1002. GC_need_full_gc = USED_HEAP_SIZE - GC_used_heap_size_after_full
  1003. > min_bytes_allocd();
  1004. }
  1005. GC_VERBOSE_LOG_PRINTF("Immediately reclaimed %ld bytes, heapsize:"
  1006. " %lu bytes" IF_USE_MUNMAP(" (%lu unmapped)") "\n",
  1007. (long)GC_bytes_found,
  1008. (unsigned long)GC_heapsize /*, */
  1009. COMMA_IF_USE_MUNMAP((unsigned long)
  1010. GC_unmapped_bytes));
  1011. /* Reset or increment counters for next cycle */
  1012. GC_n_attempts = 0;
  1013. GC_is_full_gc = FALSE;
  1014. GC_bytes_allocd_before_gc += GC_bytes_allocd;
  1015. GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
  1016. GC_bytes_allocd = 0;
  1017. GC_bytes_dropped = 0;
  1018. GC_bytes_freed = 0;
  1019. GC_finalizer_bytes_freed = 0;
  1020. IF_USE_MUNMAP(GC_unmap_old());
  1021. if (GC_on_collection_event)
  1022. GC_on_collection_event(GC_EVENT_RECLAIM_END);
  1023. # ifndef NO_CLOCK
  1024. if (GC_print_stats) {
  1025. CLOCK_TYPE done_time;
  1026. GET_TIME(done_time);
  1027. # if !defined(SMALL_CONFIG) && !defined(GC_NO_FINALIZATION)
  1028. /* A convenient place to output finalization statistics. */
  1029. GC_print_finalization_stats();
  1030. # endif
  1031. GC_log_printf("Finalize plus initiate sweep took %lu + %lu msecs\n",
  1032. MS_TIME_DIFF(finalize_time,start_time),
  1033. MS_TIME_DIFF(done_time,finalize_time));
  1034. }
  1035. # elif !defined(SMALL_CONFIG) && !defined(GC_NO_FINALIZATION)
  1036. if (GC_print_stats)
  1037. GC_print_finalization_stats();
  1038. # endif
  1039. }
  1040. /* If stop_func == 0 then GC_default_stop_func is used instead. */
  1041. STATIC GC_bool GC_try_to_collect_general(GC_stop_func stop_func,
  1042. GC_bool force_unmap GC_ATTR_UNUSED)
  1043. {
  1044. GC_bool result;
  1045. IF_USE_MUNMAP(int old_unmap_threshold;)
  1046. IF_CANCEL(int cancel_state;)
  1047. DCL_LOCK_STATE;
  1048. if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
  1049. if (GC_debugging_started) GC_print_all_smashed();
  1050. GC_INVOKE_FINALIZERS();
  1051. LOCK();
  1052. DISABLE_CANCEL(cancel_state);
  1053. # ifdef USE_MUNMAP
  1054. old_unmap_threshold = GC_unmap_threshold;
  1055. if (force_unmap ||
  1056. (GC_force_unmap_on_gcollect && old_unmap_threshold > 0))
  1057. GC_unmap_threshold = 1; /* unmap as much as possible */
  1058. # endif
  1059. ENTER_GC();
  1060. /* Minimize junk left in my registers */
  1061. GC_noop6(0,0,0,0,0,0);
  1062. result = GC_try_to_collect_inner(stop_func != 0 ? stop_func :
  1063. GC_default_stop_func);
  1064. EXIT_GC();
  1065. IF_USE_MUNMAP(GC_unmap_threshold = old_unmap_threshold); /* restore */
  1066. RESTORE_CANCEL(cancel_state);
  1067. UNLOCK();
  1068. if (result) {
  1069. if (GC_debugging_started) GC_print_all_smashed();
  1070. GC_INVOKE_FINALIZERS();
  1071. }
  1072. return(result);
  1073. }
  1074. /* Externally callable routines to invoke full, stop-the-world collection. */
  1075. GC_API int GC_CALL GC_try_to_collect(GC_stop_func stop_func)
  1076. {
  1077. GC_ASSERT(NONNULL_ARG_NOT_NULL(stop_func));
  1078. return (int)GC_try_to_collect_general(stop_func, FALSE);
  1079. }
  1080. GC_API void GC_CALL GC_gcollect(void)
  1081. {
  1082. /* 0 is passed as stop_func to get GC_default_stop_func value */
  1083. /* while holding the allocation lock (to prevent data races). */
  1084. (void)GC_try_to_collect_general(0, FALSE);
  1085. if (GC_have_errors) GC_print_all_errors();
  1086. }
  1087. STATIC word GC_heapsize_at_forced_unmap = 0;
  1088. GC_API void GC_CALL GC_gcollect_and_unmap(void)
  1089. {
  1090. /* Record current heap size to make heap growth more conservative */
  1091. /* afterwards (as if the heap is growing from zero size again). */
  1092. GC_heapsize_at_forced_unmap = GC_heapsize;
  1093. /* Collect and force memory unmapping to OS. */
  1094. (void)GC_try_to_collect_general(GC_never_stop_func, TRUE);
  1095. }
  1096. GC_INNER word GC_n_heap_sects = 0;
  1097. /* Number of sections currently in heap. */
  1098. #ifdef USE_PROC_FOR_LIBRARIES
  1099. GC_INNER word GC_n_memory = 0;
  1100. /* Number of GET_MEM allocated memory sections. */
  1101. #endif
  1102. #ifdef USE_PROC_FOR_LIBRARIES
  1103. /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */
  1104. /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set. */
  1105. GC_INNER void GC_add_to_our_memory(ptr_t p, size_t bytes)
  1106. {
  1107. if (0 == p) return;
  1108. if (GC_n_memory >= MAX_HEAP_SECTS)
  1109. ABORT("Too many GC-allocated memory sections: Increase MAX_HEAP_SECTS");
  1110. GC_our_memory[GC_n_memory].hs_start = p;
  1111. GC_our_memory[GC_n_memory].hs_bytes = bytes;
  1112. GC_n_memory++;
  1113. }
  1114. #endif
  1115. /*
  1116. * Use the chunk of memory starting at p of size bytes as part of the heap.
  1117. * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
  1118. */
  1119. GC_INNER void GC_add_to_heap(struct hblk *p, size_t bytes)
  1120. {
  1121. hdr * phdr;
  1122. word endp;
  1123. if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
  1124. ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
  1125. }
  1126. while ((word)p <= HBLKSIZE) {
  1127. /* Can't handle memory near address zero. */
  1128. ++p;
  1129. bytes -= HBLKSIZE;
  1130. if (0 == bytes) return;
  1131. }
  1132. endp = (word)p + bytes;
  1133. if (endp <= (word)p) {
  1134. /* Address wrapped. */
  1135. bytes -= HBLKSIZE;
  1136. if (0 == bytes) return;
  1137. endp -= HBLKSIZE;
  1138. }
  1139. phdr = GC_install_header(p);
  1140. if (0 == phdr) {
  1141. /* This is extremely unlikely. Can't add it. This will */
  1142. /* almost certainly result in a 0 return from the allocator, */
  1143. /* which is entirely appropriate. */
  1144. return;
  1145. }
  1146. GC_ASSERT(endp > (word)p && endp == (word)p + bytes);
  1147. GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
  1148. GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
  1149. GC_n_heap_sects++;
  1150. phdr -> hb_sz = bytes;
  1151. phdr -> hb_flags = 0;
  1152. GC_freehblk(p);
  1153. GC_heapsize += bytes;
  1154. /* Normally the caller calculates a new GC_collect_at_heapsize,
  1155. * but this is also called directly from alloc_mark_stack, so
  1156. * adjust here. It will be recalculated when called from
  1157. * GC_expand_hp_inner.
  1158. */
  1159. GC_collect_at_heapsize += bytes;
  1160. if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
  1161. GC_collect_at_heapsize = (word)(-1);
  1162. if ((word)p <= (word)GC_least_plausible_heap_addr
  1163. || GC_least_plausible_heap_addr == 0) {
  1164. GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
  1165. /* Making it a little smaller than necessary prevents */
  1166. /* us from getting a false hit from the variable */
  1167. /* itself. There's some unintentional reflection */
  1168. /* here. */
  1169. }
  1170. if ((word)p + bytes >= (word)GC_greatest_plausible_heap_addr) {
  1171. GC_greatest_plausible_heap_addr = (void *)endp;
  1172. }
  1173. }
  1174. #if !defined(NO_DEBUGGING)
  1175. void GC_print_heap_sects(void)
  1176. {
  1177. unsigned i;
  1178. GC_printf("Total heap size: %lu" IF_USE_MUNMAP(" (%lu unmapped)") "\n",
  1179. (unsigned long)GC_heapsize /*, */
  1180. COMMA_IF_USE_MUNMAP((unsigned long)GC_unmapped_bytes));
  1181. for (i = 0; i < GC_n_heap_sects; i++) {
  1182. ptr_t start = GC_heap_sects[i].hs_start;
  1183. size_t len = GC_heap_sects[i].hs_bytes;
  1184. struct hblk *h;
  1185. unsigned nbl = 0;
  1186. for (h = (struct hblk *)start; (word)h < (word)(start + len); h++) {
  1187. if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
  1188. }
  1189. GC_printf("Section %d from %p to %p %u/%lu blacklisted\n",
  1190. i, (void *)start, (void *)&start[len],
  1191. nbl, (unsigned long)divHBLKSZ(len));
  1192. }
  1193. }
  1194. #endif
  1195. void * GC_least_plausible_heap_addr = (void *)ONES;
  1196. void * GC_greatest_plausible_heap_addr = 0;
  1197. GC_INLINE word GC_max(word x, word y)
  1198. {
  1199. return(x > y? x : y);
  1200. }
  1201. GC_INLINE word GC_min(word x, word y)
  1202. {
  1203. return(x < y? x : y);
  1204. }
  1205. STATIC word GC_max_heapsize = 0;
  1206. GC_API void GC_CALL GC_set_max_heap_size(GC_word n)
  1207. {
  1208. GC_max_heapsize = n;
  1209. }
  1210. GC_word GC_max_retries = 0;
  1211. /* This explicitly increases the size of the heap. It is used */
  1212. /* internally, but may also be invoked from GC_expand_hp by the user. */
  1213. /* The argument is in units of HBLKSIZE (tiny values are rounded up). */
  1214. /* Returns FALSE on failure. */
  1215. GC_INNER GC_bool GC_expand_hp_inner(word n)
  1216. {
  1217. size_t bytes;
  1218. struct hblk * space;
  1219. word expansion_slop; /* Number of bytes by which we expect the */
  1220. /* heap to expand soon. */
  1221. if (n < MINHINCR) n = MINHINCR;
  1222. bytes = ROUNDUP_PAGESIZE((size_t)n * HBLKSIZE);
  1223. if (GC_max_heapsize != 0
  1224. && (GC_max_heapsize < (word)bytes
  1225. || GC_heapsize > GC_max_heapsize - (word)bytes)) {
  1226. /* Exceeded self-imposed limit */
  1227. return(FALSE);
  1228. }
  1229. space = GET_MEM(bytes);
  1230. GC_add_to_our_memory((ptr_t)space, bytes);
  1231. if (space == 0) {
  1232. WARN("Failed to expand heap by %" WARN_PRIdPTR " bytes\n",
  1233. (word)bytes);
  1234. return(FALSE);
  1235. }
  1236. GC_INFOLOG_PRINTF("Grow heap to %lu KiB after %lu bytes allocated\n",
  1237. TO_KiB_UL(GC_heapsize + (word)bytes),
  1238. (unsigned long)GC_bytes_allocd);
  1239. /* Adjust heap limits generously for blacklisting to work better. */
  1240. /* GC_add_to_heap performs minimal adjustment needed for */
  1241. /* correctness. */
  1242. expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE;
  1243. if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
  1244. || (GC_last_heap_addr != 0
  1245. && (word)GC_last_heap_addr < (word)space)) {
  1246. /* Assume the heap is growing up */
  1247. word new_limit = (word)space + (word)bytes + expansion_slop;
  1248. if (new_limit > (word)space) {
  1249. GC_greatest_plausible_heap_addr =
  1250. (void *)GC_max((word)GC_greatest_plausible_heap_addr,
  1251. (word)new_limit);
  1252. }
  1253. } else {
  1254. /* Heap is growing down */
  1255. word new_limit = (word)space - expansion_slop;
  1256. if (new_limit < (word)space) {
  1257. GC_least_plausible_heap_addr =
  1258. (void *)GC_min((word)GC_least_plausible_heap_addr,
  1259. (word)space - expansion_slop);
  1260. }
  1261. }
  1262. GC_prev_heap_addr = GC_last_heap_addr;
  1263. GC_last_heap_addr = (ptr_t)space;
  1264. GC_add_to_heap(space, bytes);
  1265. /* Force GC before we are likely to allocate past expansion_slop */
  1266. GC_collect_at_heapsize =
  1267. GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
  1268. if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
  1269. GC_collect_at_heapsize = (word)(-1);
  1270. if (GC_on_heap_resize)
  1271. (*GC_on_heap_resize)(GC_heapsize);
  1272. return(TRUE);
  1273. }
  1274. /* Really returns a bool, but it's externally visible, so that's clumsy. */
  1275. /* Arguments is in bytes. Includes GC_init() call. */
  1276. GC_API int GC_CALL GC_expand_hp(size_t bytes)
  1277. {
  1278. int result;
  1279. DCL_LOCK_STATE;
  1280. if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
  1281. LOCK();
  1282. result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
  1283. if (result) GC_requested_heapsize += bytes;
  1284. UNLOCK();
  1285. return(result);
  1286. }
  1287. word GC_fo_entries = 0; /* used also in extra/MacOS.c */
  1288. GC_INNER unsigned GC_fail_count = 0;
  1289. /* How many consecutive GC/expansion failures? */
  1290. /* Reset by GC_allochblk. */
  1291. static word last_fo_entries = 0;
  1292. static word last_bytes_finalized = 0;
  1293. #define GC_WORD_MAX (~(word)0)
  1294. /* Collect or expand heap in an attempt make the indicated number of */
  1295. /* free blocks available. Should be called until the blocks are */
  1296. /* available (setting retry value to TRUE unless this is the first call */
  1297. /* in a loop) or until it fails by returning FALSE. */
  1298. GC_INNER GC_bool GC_collect_or_expand(word needed_blocks,
  1299. GC_bool ignore_off_page,
  1300. GC_bool retry)
  1301. {
  1302. GC_bool gc_not_stopped = TRUE;
  1303. word blocks_to_get;
  1304. IF_CANCEL(int cancel_state;)
  1305. DISABLE_CANCEL(cancel_state);
  1306. if (!GC_incremental && !GC_dont_gc &&
  1307. ((GC_dont_expand && GC_bytes_allocd > 0)
  1308. || (GC_fo_entries > (last_fo_entries + 500)
  1309. && (last_bytes_finalized | GC_bytes_finalized) != 0)
  1310. || GC_should_collect())) {
  1311. /* Try to do a full collection using 'default' stop_func (unless */
  1312. /* nothing has been allocated since the latest collection or heap */
  1313. /* expansion is disabled). */
  1314. gc_not_stopped = GC_try_to_collect_inner(
  1315. GC_bytes_allocd > 0 && (!GC_dont_expand || !retry) ?
  1316. GC_default_stop_func : GC_never_stop_func);
  1317. if (gc_not_stopped == TRUE || !retry) {
  1318. /* Either the collection hasn't been aborted or this is the */
  1319. /* first attempt (in a loop). */
  1320. last_fo_entries = GC_fo_entries;
  1321. last_bytes_finalized = GC_bytes_finalized;
  1322. RESTORE_CANCEL(cancel_state);
  1323. return(TRUE);
  1324. }
  1325. }
  1326. blocks_to_get = (GC_heapsize - GC_heapsize_at_forced_unmap)
  1327. / (HBLKSIZE * GC_free_space_divisor)
  1328. + needed_blocks;
  1329. if (blocks_to_get > MAXHINCR) {
  1330. word slop;
  1331. /* Get the minimum required to make it likely that we can satisfy */
  1332. /* the current request in the presence of black-listing. */
  1333. /* This will probably be more than MAXHINCR. */
  1334. if (ignore_off_page) {
  1335. slop = 4;
  1336. } else {
  1337. slop = 2 * divHBLKSZ(BL_LIMIT);
  1338. if (slop > needed_blocks) slop = needed_blocks;
  1339. }
  1340. if (needed_blocks + slop > MAXHINCR) {
  1341. blocks_to_get = needed_blocks + slop;
  1342. } else {
  1343. blocks_to_get = MAXHINCR;
  1344. }
  1345. if (blocks_to_get > divHBLKSZ(GC_WORD_MAX))
  1346. blocks_to_get = divHBLKSZ(GC_WORD_MAX);
  1347. }
  1348. if (!GC_expand_hp_inner(blocks_to_get)
  1349. && (blocks_to_get == needed_blocks
  1350. || !GC_expand_hp_inner(needed_blocks))) {
  1351. if (gc_not_stopped == FALSE) {
  1352. /* Don't increment GC_fail_count here (and no warning). */
  1353. GC_gcollect_inner();
  1354. GC_ASSERT(GC_bytes_allocd == 0);
  1355. } else if (GC_fail_count++ < GC_max_retries) {
  1356. WARN("Out of Memory! Trying to continue...\n", 0);
  1357. GC_gcollect_inner();
  1358. } else {
  1359. # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
  1360. WARN("Out of Memory! Heap size: %" WARN_PRIdPTR " MiB."
  1361. " Returning NULL!\n", (GC_heapsize - GC_unmapped_bytes) >> 20);
  1362. # endif
  1363. RESTORE_CANCEL(cancel_state);
  1364. return(FALSE);
  1365. }
  1366. } else if (GC_fail_count) {
  1367. GC_COND_LOG_PRINTF("Memory available again...\n");
  1368. }
  1369. RESTORE_CANCEL(cancel_state);
  1370. return(TRUE);
  1371. }
  1372. /*
  1373. * Make sure the object free list for size gran (in granules) is not empty.
  1374. * Return a pointer to the first object on the free list.
  1375. * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
  1376. */
  1377. GC_INNER ptr_t GC_allocobj(size_t gran, int kind)
  1378. {
  1379. void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
  1380. GC_bool tried_minor = FALSE;
  1381. GC_bool retry = FALSE;
  1382. GC_ASSERT(I_HOLD_LOCK());
  1383. if (gran == 0) return(0);
  1384. while (*flh == 0) {
  1385. ENTER_GC();
  1386. # ifndef GC_DISABLE_INCREMENTAL
  1387. if (GC_incremental && GC_time_limit != GC_TIME_UNLIMITED
  1388. && !GC_dont_gc) {
  1389. /* True incremental mode, not just generational. */
  1390. /* Do our share of marking work. */
  1391. GC_collect_a_little_inner(1);
  1392. }
  1393. # endif
  1394. /* Sweep blocks for objects of this size */
  1395. GC_ASSERT(!GC_is_full_gc
  1396. || NULL == GC_obj_kinds[kind].ok_reclaim_list
  1397. || NULL == GC_obj_kinds[kind].ok_reclaim_list[gran]);
  1398. GC_continue_reclaim(gran, kind);
  1399. EXIT_GC();
  1400. if (*flh == 0) {
  1401. GC_new_hblk(gran, kind);
  1402. if (*flh == 0) {
  1403. ENTER_GC();
  1404. if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
  1405. && !tried_minor && !GC_dont_gc) {
  1406. GC_collect_a_little_inner(1);
  1407. tried_minor = TRUE;
  1408. } else {
  1409. if (!GC_collect_or_expand(1, FALSE, retry)) {
  1410. EXIT_GC();
  1411. return(0);
  1412. }
  1413. retry = TRUE;
  1414. }
  1415. EXIT_GC();
  1416. }
  1417. }
  1418. }
  1419. /* Successful allocation; reset failure count. */
  1420. GC_fail_count = 0;
  1421. return (ptr_t)(*flh);
  1422. }