alloc.c 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593
  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. if (GC_dont_gc) return;
  591. DISABLE_CANCEL(cancel_state);
  592. if (GC_incremental && GC_collection_in_progress()) {
  593. int i;
  594. int max_deficit = GC_rate * n;
  595. for (i = GC_deficit; i < max_deficit; i++) {
  596. if (GC_mark_some((ptr_t)0)) {
  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 {
  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. GC_collect_a_little_inner(1);
  641. result = (int)GC_collection_in_progress();
  642. UNLOCK();
  643. if (!result && GC_debugging_started) GC_print_all_smashed();
  644. return(result);
  645. }
  646. #ifndef NO_CLOCK
  647. /* Variables for world-stop average delay time statistic computation. */
  648. /* "divisor" is incremented every world-stop and halved when reached */
  649. /* its maximum (or upon "total_time" overflow). */
  650. static unsigned world_stopped_total_time = 0;
  651. static unsigned world_stopped_total_divisor = 0;
  652. # ifndef MAX_TOTAL_TIME_DIVISOR
  653. /* We shall not use big values here (so "outdated" delay time */
  654. /* values would have less impact on "average" delay time value than */
  655. /* newer ones). */
  656. # define MAX_TOTAL_TIME_DIVISOR 1000
  657. # endif
  658. #endif /* !NO_CLOCK */
  659. #ifdef USE_MUNMAP
  660. # define IF_USE_MUNMAP(x) x
  661. # define COMMA_IF_USE_MUNMAP(x) /* comma */, x
  662. #else
  663. # define IF_USE_MUNMAP(x) /* empty */
  664. # define COMMA_IF_USE_MUNMAP(x) /* empty */
  665. #endif
  666. /*
  667. * We stop the world and mark from all roots.
  668. * If stop_func() ever returns TRUE, we may fail and return FALSE.
  669. * Increment GC_gc_no if we succeed.
  670. */
  671. STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func)
  672. {
  673. unsigned i;
  674. # ifndef NO_CLOCK
  675. CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */
  676. # endif
  677. GC_ASSERT(I_HOLD_LOCK());
  678. # if !defined(REDIRECT_MALLOC) && defined(USE_WINALLOC)
  679. GC_add_current_malloc_heap();
  680. # endif
  681. # if defined(REGISTER_LIBRARIES_EARLY)
  682. GC_cond_register_dynamic_libraries();
  683. # endif
  684. # ifndef NO_CLOCK
  685. if (GC_PRINT_STATS_FLAG)
  686. GET_TIME(start_time);
  687. # endif
  688. # if !defined(GC_NO_FINALIZATION) && !defined(GC_TOGGLE_REFS_NOT_NEEDED)
  689. GC_process_togglerefs();
  690. # endif
  691. # ifdef THREADS
  692. if (GC_on_collection_event)
  693. GC_on_collection_event(GC_EVENT_PRE_STOP_WORLD);
  694. # endif
  695. STOP_WORLD();
  696. # ifdef THREADS
  697. if (GC_on_collection_event)
  698. GC_on_collection_event(GC_EVENT_POST_STOP_WORLD);
  699. # endif
  700. # ifdef THREAD_LOCAL_ALLOC
  701. GC_world_stopped = TRUE;
  702. # endif
  703. /* Output blank line for convenience here */
  704. GC_COND_LOG_PRINTF(
  705. "\n--> Marking for collection #%lu after %lu allocated bytes\n",
  706. (unsigned long)GC_gc_no + 1, (unsigned long) GC_bytes_allocd);
  707. # ifdef MAKE_BACK_GRAPH
  708. if (GC_print_back_height) {
  709. GC_build_back_graph();
  710. }
  711. # endif
  712. /* Mark from all roots. */
  713. if (GC_on_collection_event)
  714. GC_on_collection_event(GC_EVENT_MARK_START);
  715. /* Minimize junk left in my registers and on the stack */
  716. GC_clear_a_few_frames();
  717. GC_noop6(0,0,0,0,0,0);
  718. GC_initiate_gc();
  719. for (i = 0;;i++) {
  720. if ((*stop_func)()) {
  721. GC_COND_LOG_PRINTF("Abandoned stopped marking after"
  722. " %u iterations\n", i);
  723. GC_deficit = i; /* Give the mutator a chance. */
  724. # ifdef THREAD_LOCAL_ALLOC
  725. GC_world_stopped = FALSE;
  726. # endif
  727. # ifdef THREADS
  728. if (GC_on_collection_event)
  729. GC_on_collection_event(GC_EVENT_PRE_START_WORLD);
  730. # endif
  731. START_WORLD();
  732. # ifdef THREADS
  733. if (GC_on_collection_event)
  734. GC_on_collection_event(GC_EVENT_POST_START_WORLD);
  735. # endif
  736. /* TODO: Notify GC_EVENT_MARK_ABANDON */
  737. return(FALSE);
  738. }
  739. if (GC_mark_some(GC_approx_sp())) break;
  740. }
  741. GC_gc_no++;
  742. GC_DBGLOG_PRINTF("GC #%lu freed %ld bytes, heap %lu KiB"
  743. IF_USE_MUNMAP(" (+ %lu KiB unmapped)") "\n",
  744. (unsigned long)GC_gc_no, (long)GC_bytes_found,
  745. TO_KiB_UL(GC_heapsize - GC_unmapped_bytes) /*, */
  746. COMMA_IF_USE_MUNMAP(TO_KiB_UL(GC_unmapped_bytes)));
  747. /* Check all debugged objects for consistency */
  748. if (GC_debugging_started) {
  749. (*GC_check_heap)();
  750. }
  751. if (GC_on_collection_event)
  752. GC_on_collection_event(GC_EVENT_MARK_END);
  753. # ifdef THREAD_LOCAL_ALLOC
  754. GC_world_stopped = FALSE;
  755. # endif
  756. # ifdef THREADS
  757. if (GC_on_collection_event)
  758. GC_on_collection_event(GC_EVENT_PRE_START_WORLD);
  759. # endif
  760. START_WORLD();
  761. # ifdef THREADS
  762. if (GC_on_collection_event)
  763. GC_on_collection_event(GC_EVENT_POST_START_WORLD);
  764. # endif
  765. # ifndef NO_CLOCK
  766. if (GC_PRINT_STATS_FLAG) {
  767. unsigned long time_diff;
  768. unsigned total_time, divisor;
  769. CLOCK_TYPE current_time;
  770. GET_TIME(current_time);
  771. time_diff = MS_TIME_DIFF(current_time,start_time);
  772. /* Compute new world-stop delay total time */
  773. total_time = world_stopped_total_time;
  774. divisor = world_stopped_total_divisor;
  775. if ((int)total_time < 0 || divisor >= MAX_TOTAL_TIME_DIVISOR) {
  776. /* Halve values if overflow occurs */
  777. total_time >>= 1;
  778. divisor >>= 1;
  779. }
  780. total_time += time_diff < (((unsigned)-1) >> 1) ?
  781. (unsigned)time_diff : ((unsigned)-1) >> 1;
  782. /* Update old world_stopped_total_time and its divisor */
  783. world_stopped_total_time = total_time;
  784. world_stopped_total_divisor = ++divisor;
  785. GC_ASSERT(divisor != 0);
  786. GC_log_printf(
  787. "World-stopped marking took %lu msecs (%u in average)\n",
  788. time_diff, total_time / divisor);
  789. }
  790. # endif
  791. return(TRUE);
  792. }
  793. /* Set all mark bits for the free list whose first entry is q */
  794. GC_INNER void GC_set_fl_marks(ptr_t q)
  795. {
  796. if (q != NULL) {
  797. struct hblk *h = HBLKPTR(q);
  798. struct hblk *last_h = h;
  799. hdr *hhdr = HDR(h);
  800. IF_PER_OBJ(word sz = hhdr->hb_sz;)
  801. for (;;) {
  802. word bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz);
  803. if (!mark_bit_from_hdr(hhdr, bit_no)) {
  804. set_mark_bit_from_hdr(hhdr, bit_no);
  805. ++hhdr -> hb_n_marks;
  806. }
  807. q = (ptr_t)obj_link(q);
  808. if (q == NULL)
  809. break;
  810. h = HBLKPTR(q);
  811. if (h != last_h) {
  812. last_h = h;
  813. hhdr = HDR(h);
  814. IF_PER_OBJ(sz = hhdr->hb_sz;)
  815. }
  816. }
  817. }
  818. }
  819. #if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
  820. /* Check that all mark bits for the free list whose first entry is */
  821. /* (*pfreelist) are set. Check skipped if points to a special value. */
  822. void GC_check_fl_marks(void **pfreelist)
  823. {
  824. /* TODO: There is a data race with GC_FAST_MALLOC_GRANS (which does */
  825. /* not do atomic updates to the free-list). The race seems to be */
  826. /* harmless, and for now we just skip this check in case of TSan. */
  827. # if defined(AO_HAVE_load_acquire_read) && !defined(THREAD_SANITIZER)
  828. AO_t *list = (AO_t *)AO_load_acquire_read((AO_t *)pfreelist);
  829. /* Atomic operations are used because the world is running. */
  830. AO_t *prev;
  831. AO_t *p;
  832. if ((word)list <= HBLKSIZE) return;
  833. prev = (AO_t *)pfreelist;
  834. for (p = list; p != NULL;) {
  835. AO_t *next;
  836. if (!GC_is_marked(p)) {
  837. ABORT_ARG2("Unmarked local free list entry",
  838. ": object %p on list %p", (void *)p, (void *)list);
  839. }
  840. /* While traversing the free-list, it re-reads the pointer to */
  841. /* the current node before accepting its next pointer and */
  842. /* bails out if the latter has changed. That way, it won't */
  843. /* try to follow the pointer which might be been modified */
  844. /* after the object was returned to the client. It might */
  845. /* perform the mark-check on the just allocated object but */
  846. /* that should be harmless. */
  847. next = (AO_t *)AO_load_acquire_read(p);
  848. if (AO_load(prev) != (AO_t)p)
  849. break;
  850. prev = p;
  851. p = next;
  852. }
  853. # else
  854. /* FIXME: Not implemented (just skipped). */
  855. (void)pfreelist;
  856. # endif
  857. }
  858. #endif /* GC_ASSERTIONS && THREAD_LOCAL_ALLOC */
  859. /* Clear all mark bits for the free list whose first entry is q */
  860. /* Decrement GC_bytes_found by number of bytes on free list. */
  861. STATIC void GC_clear_fl_marks(ptr_t q)
  862. {
  863. struct hblk *h = HBLKPTR(q);
  864. struct hblk *last_h = h;
  865. hdr *hhdr = HDR(h);
  866. word sz = hhdr->hb_sz; /* Normally set only once. */
  867. for (;;) {
  868. word bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz);
  869. if (mark_bit_from_hdr(hhdr, bit_no)) {
  870. size_t n_marks = hhdr -> hb_n_marks;
  871. GC_ASSERT(n_marks != 0);
  872. clear_mark_bit_from_hdr(hhdr, bit_no);
  873. n_marks--;
  874. # ifdef PARALLEL_MARK
  875. /* Appr. count, don't decrement to zero! */
  876. if (0 != n_marks || !GC_parallel) {
  877. hhdr -> hb_n_marks = n_marks;
  878. }
  879. # else
  880. hhdr -> hb_n_marks = n_marks;
  881. # endif
  882. }
  883. GC_bytes_found -= sz;
  884. q = (ptr_t)obj_link(q);
  885. if (q == NULL)
  886. break;
  887. h = HBLKPTR(q);
  888. if (h != last_h) {
  889. last_h = h;
  890. hhdr = HDR(h);
  891. sz = hhdr->hb_sz;
  892. }
  893. }
  894. }
  895. #if defined(GC_ASSERTIONS) && defined(THREAD_LOCAL_ALLOC)
  896. void GC_check_tls(void);
  897. #endif
  898. GC_on_heap_resize_proc GC_on_heap_resize = 0;
  899. /* Used for logging only. */
  900. GC_INLINE int GC_compute_heap_usage_percent(void)
  901. {
  902. word used = GC_composite_in_use + GC_atomic_in_use;
  903. word heap_sz = GC_heapsize - GC_unmapped_bytes;
  904. return used >= heap_sz ? 0 : used < ((word)-1) / 100 ?
  905. (int)((used * 100) / heap_sz) : (int)(used / (heap_sz / 100));
  906. }
  907. /* Finish up a collection. Assumes mark bits are consistent, lock is */
  908. /* held, but the world is otherwise running. */
  909. STATIC void GC_finish_collection(void)
  910. {
  911. # ifndef NO_CLOCK
  912. CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */
  913. CLOCK_TYPE finalize_time = 0;
  914. # endif
  915. GC_ASSERT(I_HOLD_LOCK());
  916. # if defined(GC_ASSERTIONS) \
  917. && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
  918. /* Check that we marked some of our own data. */
  919. /* FIXME: Add more checks. */
  920. GC_check_tls();
  921. # endif
  922. # ifndef NO_CLOCK
  923. if (GC_print_stats)
  924. GET_TIME(start_time);
  925. # endif
  926. if (GC_on_collection_event)
  927. GC_on_collection_event(GC_EVENT_RECLAIM_START);
  928. # ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
  929. if (GC_bytes_found > 0)
  930. GC_reclaimed_bytes_before_gc += (word)GC_bytes_found;
  931. # endif
  932. GC_bytes_found = 0;
  933. # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
  934. if (GETENV("GC_PRINT_ADDRESS_MAP") != 0) {
  935. GC_print_address_map();
  936. }
  937. # endif
  938. COND_DUMP;
  939. if (GC_find_leak) {
  940. /* Mark all objects on the free list. All objects should be */
  941. /* marked when we're done. */
  942. word size; /* current object size */
  943. unsigned kind;
  944. ptr_t q;
  945. for (kind = 0; kind < GC_n_kinds; kind++) {
  946. for (size = 1; size <= MAXOBJGRANULES; size++) {
  947. q = (ptr_t)GC_obj_kinds[kind].ok_freelist[size];
  948. if (q != NULL)
  949. GC_set_fl_marks(q);
  950. }
  951. }
  952. GC_start_reclaim(TRUE);
  953. /* The above just checks; it doesn't really reclaim anything. */
  954. }
  955. # ifndef GC_NO_FINALIZATION
  956. GC_finalize();
  957. # endif
  958. # ifndef NO_CLOCK
  959. if (GC_print_stats)
  960. GET_TIME(finalize_time);
  961. # endif
  962. if (GC_print_back_height) {
  963. # ifdef MAKE_BACK_GRAPH
  964. GC_traverse_back_graph();
  965. # elif !defined(SMALL_CONFIG)
  966. GC_err_printf("Back height not available: "
  967. "Rebuild collector with -DMAKE_BACK_GRAPH\n");
  968. # endif
  969. }
  970. /* Clear free list mark bits, in case they got accidentally marked */
  971. /* (or GC_find_leak is set and they were intentionally marked). */
  972. /* Also subtract memory remaining from GC_bytes_found count. */
  973. /* Note that composite objects on free list are cleared. */
  974. /* Thus accidentally marking a free list is not a problem; only */
  975. /* objects on the list itself will be marked, and that's fixed here. */
  976. {
  977. word size; /* current object size */
  978. ptr_t q; /* pointer to current object */
  979. unsigned kind;
  980. for (kind = 0; kind < GC_n_kinds; kind++) {
  981. for (size = 1; size <= MAXOBJGRANULES; size++) {
  982. q = (ptr_t)GC_obj_kinds[kind].ok_freelist[size];
  983. if (q != NULL)
  984. GC_clear_fl_marks(q);
  985. }
  986. }
  987. }
  988. GC_VERBOSE_LOG_PRINTF("Bytes recovered before sweep - f.l. count = %ld\n",
  989. (long)GC_bytes_found);
  990. /* Reconstruct free lists to contain everything not marked */
  991. GC_start_reclaim(FALSE);
  992. GC_DBGLOG_PRINTF("In-use heap: %d%% (%lu KiB pointers + %lu KiB other)\n",
  993. GC_compute_heap_usage_percent(),
  994. TO_KiB_UL(GC_composite_in_use),
  995. TO_KiB_UL(GC_atomic_in_use));
  996. if (GC_is_full_gc) {
  997. GC_used_heap_size_after_full = USED_HEAP_SIZE;
  998. GC_need_full_gc = FALSE;
  999. } else {
  1000. GC_need_full_gc = USED_HEAP_SIZE - GC_used_heap_size_after_full
  1001. > min_bytes_allocd();
  1002. }
  1003. GC_VERBOSE_LOG_PRINTF("Immediately reclaimed %ld bytes, heapsize:"
  1004. " %lu bytes" IF_USE_MUNMAP(" (%lu unmapped)") "\n",
  1005. (long)GC_bytes_found,
  1006. (unsigned long)GC_heapsize /*, */
  1007. COMMA_IF_USE_MUNMAP((unsigned long)
  1008. GC_unmapped_bytes));
  1009. /* Reset or increment counters for next cycle */
  1010. GC_n_attempts = 0;
  1011. GC_is_full_gc = FALSE;
  1012. GC_bytes_allocd_before_gc += GC_bytes_allocd;
  1013. GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
  1014. GC_bytes_allocd = 0;
  1015. GC_bytes_dropped = 0;
  1016. GC_bytes_freed = 0;
  1017. GC_finalizer_bytes_freed = 0;
  1018. IF_USE_MUNMAP(GC_unmap_old());
  1019. if (GC_on_collection_event)
  1020. GC_on_collection_event(GC_EVENT_RECLAIM_END);
  1021. # ifndef NO_CLOCK
  1022. if (GC_print_stats) {
  1023. CLOCK_TYPE done_time;
  1024. GET_TIME(done_time);
  1025. # if !defined(SMALL_CONFIG) && !defined(GC_NO_FINALIZATION)
  1026. /* A convenient place to output finalization statistics. */
  1027. GC_print_finalization_stats();
  1028. # endif
  1029. GC_log_printf("Finalize plus initiate sweep took %lu + %lu msecs\n",
  1030. MS_TIME_DIFF(finalize_time,start_time),
  1031. MS_TIME_DIFF(done_time,finalize_time));
  1032. }
  1033. # elif !defined(SMALL_CONFIG) && !defined(GC_NO_FINALIZATION)
  1034. if (GC_print_stats)
  1035. GC_print_finalization_stats();
  1036. # endif
  1037. }
  1038. /* If stop_func == 0 then GC_default_stop_func is used instead. */
  1039. STATIC GC_bool GC_try_to_collect_general(GC_stop_func stop_func,
  1040. GC_bool force_unmap GC_ATTR_UNUSED)
  1041. {
  1042. GC_bool result;
  1043. IF_USE_MUNMAP(int old_unmap_threshold;)
  1044. IF_CANCEL(int cancel_state;)
  1045. DCL_LOCK_STATE;
  1046. if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
  1047. if (GC_debugging_started) GC_print_all_smashed();
  1048. GC_INVOKE_FINALIZERS();
  1049. LOCK();
  1050. DISABLE_CANCEL(cancel_state);
  1051. # ifdef USE_MUNMAP
  1052. old_unmap_threshold = GC_unmap_threshold;
  1053. if (force_unmap ||
  1054. (GC_force_unmap_on_gcollect && old_unmap_threshold > 0))
  1055. GC_unmap_threshold = 1; /* unmap as much as possible */
  1056. # endif
  1057. ENTER_GC();
  1058. /* Minimize junk left in my registers */
  1059. GC_noop6(0,0,0,0,0,0);
  1060. result = GC_try_to_collect_inner(stop_func != 0 ? stop_func :
  1061. GC_default_stop_func);
  1062. EXIT_GC();
  1063. IF_USE_MUNMAP(GC_unmap_threshold = old_unmap_threshold); /* restore */
  1064. RESTORE_CANCEL(cancel_state);
  1065. UNLOCK();
  1066. if (result) {
  1067. if (GC_debugging_started) GC_print_all_smashed();
  1068. GC_INVOKE_FINALIZERS();
  1069. }
  1070. return(result);
  1071. }
  1072. /* Externally callable routines to invoke full, stop-the-world collection. */
  1073. GC_API int GC_CALL GC_try_to_collect(GC_stop_func stop_func)
  1074. {
  1075. GC_ASSERT(NONNULL_ARG_NOT_NULL(stop_func));
  1076. return (int)GC_try_to_collect_general(stop_func, FALSE);
  1077. }
  1078. GC_API void GC_CALL GC_gcollect(void)
  1079. {
  1080. /* 0 is passed as stop_func to get GC_default_stop_func value */
  1081. /* while holding the allocation lock (to prevent data races). */
  1082. (void)GC_try_to_collect_general(0, FALSE);
  1083. if (GC_have_errors) GC_print_all_errors();
  1084. }
  1085. STATIC word GC_heapsize_at_forced_unmap = 0;
  1086. GC_API void GC_CALL GC_gcollect_and_unmap(void)
  1087. {
  1088. /* Record current heap size to make heap growth more conservative */
  1089. /* afterwards (as if the heap is growing from zero size again). */
  1090. GC_heapsize_at_forced_unmap = GC_heapsize;
  1091. /* Collect and force memory unmapping to OS. */
  1092. (void)GC_try_to_collect_general(GC_never_stop_func, TRUE);
  1093. }
  1094. GC_INNER word GC_n_heap_sects = 0;
  1095. /* Number of sections currently in heap. */
  1096. #ifdef USE_PROC_FOR_LIBRARIES
  1097. GC_INNER word GC_n_memory = 0;
  1098. /* Number of GET_MEM allocated memory sections. */
  1099. #endif
  1100. #ifdef USE_PROC_FOR_LIBRARIES
  1101. /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */
  1102. /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set. */
  1103. GC_INNER void GC_add_to_our_memory(ptr_t p, size_t bytes)
  1104. {
  1105. if (0 == p) return;
  1106. if (GC_n_memory >= MAX_HEAP_SECTS)
  1107. ABORT("Too many GC-allocated memory sections: Increase MAX_HEAP_SECTS");
  1108. GC_our_memory[GC_n_memory].hs_start = p;
  1109. GC_our_memory[GC_n_memory].hs_bytes = bytes;
  1110. GC_n_memory++;
  1111. }
  1112. #endif
  1113. /*
  1114. * Use the chunk of memory starting at p of size bytes as part of the heap.
  1115. * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
  1116. */
  1117. GC_INNER void GC_add_to_heap(struct hblk *p, size_t bytes)
  1118. {
  1119. hdr * phdr;
  1120. word endp;
  1121. if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
  1122. ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
  1123. }
  1124. while ((word)p <= HBLKSIZE) {
  1125. /* Can't handle memory near address zero. */
  1126. ++p;
  1127. bytes -= HBLKSIZE;
  1128. if (0 == bytes) return;
  1129. }
  1130. endp = (word)p + bytes;
  1131. if (endp <= (word)p) {
  1132. /* Address wrapped. */
  1133. bytes -= HBLKSIZE;
  1134. if (0 == bytes) return;
  1135. endp -= HBLKSIZE;
  1136. }
  1137. phdr = GC_install_header(p);
  1138. if (0 == phdr) {
  1139. /* This is extremely unlikely. Can't add it. This will */
  1140. /* almost certainly result in a 0 return from the allocator, */
  1141. /* which is entirely appropriate. */
  1142. return;
  1143. }
  1144. GC_ASSERT(endp > (word)p && endp == (word)p + bytes);
  1145. GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
  1146. GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
  1147. GC_n_heap_sects++;
  1148. phdr -> hb_sz = bytes;
  1149. phdr -> hb_flags = 0;
  1150. GC_freehblk(p);
  1151. GC_heapsize += bytes;
  1152. /* Normally the caller calculates a new GC_collect_at_heapsize,
  1153. * but this is also called directly from alloc_mark_stack, so
  1154. * adjust here. It will be recalculated when called from
  1155. * GC_expand_hp_inner.
  1156. */
  1157. GC_collect_at_heapsize += bytes;
  1158. if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
  1159. GC_collect_at_heapsize = (word)(-1);
  1160. if ((word)p <= (word)GC_least_plausible_heap_addr
  1161. || GC_least_plausible_heap_addr == 0) {
  1162. GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word));
  1163. /* Making it a little smaller than necessary prevents */
  1164. /* us from getting a false hit from the variable */
  1165. /* itself. There's some unintentional reflection */
  1166. /* here. */
  1167. }
  1168. if ((word)p + bytes >= (word)GC_greatest_plausible_heap_addr) {
  1169. GC_greatest_plausible_heap_addr = (void *)endp;
  1170. }
  1171. }
  1172. #if !defined(NO_DEBUGGING)
  1173. void GC_print_heap_sects(void)
  1174. {
  1175. unsigned i;
  1176. GC_printf("Total heap size: %lu" IF_USE_MUNMAP(" (%lu unmapped)") "\n",
  1177. (unsigned long)GC_heapsize /*, */
  1178. COMMA_IF_USE_MUNMAP((unsigned long)GC_unmapped_bytes));
  1179. for (i = 0; i < GC_n_heap_sects; i++) {
  1180. ptr_t start = GC_heap_sects[i].hs_start;
  1181. size_t len = GC_heap_sects[i].hs_bytes;
  1182. struct hblk *h;
  1183. unsigned nbl = 0;
  1184. for (h = (struct hblk *)start; (word)h < (word)(start + len); h++) {
  1185. if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
  1186. }
  1187. GC_printf("Section %d from %p to %p %u/%lu blacklisted\n",
  1188. i, (void *)start, (void *)&start[len],
  1189. nbl, (unsigned long)divHBLKSZ(len));
  1190. }
  1191. }
  1192. #endif
  1193. void * GC_least_plausible_heap_addr = (void *)ONES;
  1194. void * GC_greatest_plausible_heap_addr = 0;
  1195. GC_INLINE word GC_max(word x, word y)
  1196. {
  1197. return(x > y? x : y);
  1198. }
  1199. GC_INLINE word GC_min(word x, word y)
  1200. {
  1201. return(x < y? x : y);
  1202. }
  1203. STATIC word GC_max_heapsize = 0;
  1204. GC_API void GC_CALL GC_set_max_heap_size(GC_word n)
  1205. {
  1206. GC_max_heapsize = n;
  1207. }
  1208. GC_word GC_max_retries = 0;
  1209. /* This explicitly increases the size of the heap. It is used */
  1210. /* internally, but may also be invoked from GC_expand_hp by the user. */
  1211. /* The argument is in units of HBLKSIZE (tiny values are rounded up). */
  1212. /* Returns FALSE on failure. */
  1213. GC_INNER GC_bool GC_expand_hp_inner(word n)
  1214. {
  1215. size_t bytes;
  1216. struct hblk * space;
  1217. word expansion_slop; /* Number of bytes by which we expect the */
  1218. /* heap to expand soon. */
  1219. if (n < MINHINCR) n = MINHINCR;
  1220. bytes = ROUNDUP_PAGESIZE((size_t)n * HBLKSIZE);
  1221. if (GC_max_heapsize != 0
  1222. && (GC_max_heapsize < (word)bytes
  1223. || GC_heapsize > GC_max_heapsize - (word)bytes)) {
  1224. /* Exceeded self-imposed limit */
  1225. return(FALSE);
  1226. }
  1227. space = GET_MEM(bytes);
  1228. GC_add_to_our_memory((ptr_t)space, bytes);
  1229. if (space == 0) {
  1230. WARN("Failed to expand heap by %" WARN_PRIdPTR " bytes\n",
  1231. (word)bytes);
  1232. return(FALSE);
  1233. }
  1234. GC_INFOLOG_PRINTF("Grow heap to %lu KiB after %lu bytes allocated\n",
  1235. TO_KiB_UL(GC_heapsize + (word)bytes),
  1236. (unsigned long)GC_bytes_allocd);
  1237. /* Adjust heap limits generously for blacklisting to work better. */
  1238. /* GC_add_to_heap performs minimal adjustment needed for */
  1239. /* correctness. */
  1240. expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE;
  1241. if ((GC_last_heap_addr == 0 && !((word)space & SIGNB))
  1242. || (GC_last_heap_addr != 0
  1243. && (word)GC_last_heap_addr < (word)space)) {
  1244. /* Assume the heap is growing up */
  1245. word new_limit = (word)space + (word)bytes + expansion_slop;
  1246. if (new_limit > (word)space) {
  1247. GC_greatest_plausible_heap_addr =
  1248. (void *)GC_max((word)GC_greatest_plausible_heap_addr,
  1249. (word)new_limit);
  1250. }
  1251. } else {
  1252. /* Heap is growing down */
  1253. word new_limit = (word)space - expansion_slop;
  1254. if (new_limit < (word)space) {
  1255. GC_least_plausible_heap_addr =
  1256. (void *)GC_min((word)GC_least_plausible_heap_addr,
  1257. (word)space - expansion_slop);
  1258. }
  1259. }
  1260. GC_prev_heap_addr = GC_last_heap_addr;
  1261. GC_last_heap_addr = (ptr_t)space;
  1262. GC_add_to_heap(space, bytes);
  1263. /* Force GC before we are likely to allocate past expansion_slop */
  1264. GC_collect_at_heapsize =
  1265. GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
  1266. if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
  1267. GC_collect_at_heapsize = (word)(-1);
  1268. if (GC_on_heap_resize)
  1269. (*GC_on_heap_resize)(GC_heapsize);
  1270. return(TRUE);
  1271. }
  1272. /* Really returns a bool, but it's externally visible, so that's clumsy. */
  1273. /* Arguments is in bytes. Includes GC_init() call. */
  1274. GC_API int GC_CALL GC_expand_hp(size_t bytes)
  1275. {
  1276. int result;
  1277. DCL_LOCK_STATE;
  1278. if (!EXPECT(GC_is_initialized, TRUE)) GC_init();
  1279. LOCK();
  1280. result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
  1281. if (result) GC_requested_heapsize += bytes;
  1282. UNLOCK();
  1283. return(result);
  1284. }
  1285. word GC_fo_entries = 0; /* used also in extra/MacOS.c */
  1286. GC_INNER unsigned GC_fail_count = 0;
  1287. /* How many consecutive GC/expansion failures? */
  1288. /* Reset by GC_allochblk. */
  1289. static word last_fo_entries = 0;
  1290. static word last_bytes_finalized = 0;
  1291. #define GC_WORD_MAX (~(word)0)
  1292. /* Collect or expand heap in an attempt make the indicated number of */
  1293. /* free blocks available. Should be called until the blocks are */
  1294. /* available (setting retry value to TRUE unless this is the first call */
  1295. /* in a loop) or until it fails by returning FALSE. */
  1296. GC_INNER GC_bool GC_collect_or_expand(word needed_blocks,
  1297. GC_bool ignore_off_page,
  1298. GC_bool retry)
  1299. {
  1300. GC_bool gc_not_stopped = TRUE;
  1301. word blocks_to_get;
  1302. IF_CANCEL(int cancel_state;)
  1303. DISABLE_CANCEL(cancel_state);
  1304. if (!GC_incremental && !GC_dont_gc &&
  1305. ((GC_dont_expand && GC_bytes_allocd > 0)
  1306. || (GC_fo_entries > (last_fo_entries + 500)
  1307. && (last_bytes_finalized | GC_bytes_finalized) != 0)
  1308. || GC_should_collect())) {
  1309. /* Try to do a full collection using 'default' stop_func (unless */
  1310. /* nothing has been allocated since the latest collection or heap */
  1311. /* expansion is disabled). */
  1312. gc_not_stopped = GC_try_to_collect_inner(
  1313. GC_bytes_allocd > 0 && (!GC_dont_expand || !retry) ?
  1314. GC_default_stop_func : GC_never_stop_func);
  1315. if (gc_not_stopped == TRUE || !retry) {
  1316. /* Either the collection hasn't been aborted or this is the */
  1317. /* first attempt (in a loop). */
  1318. last_fo_entries = GC_fo_entries;
  1319. last_bytes_finalized = GC_bytes_finalized;
  1320. RESTORE_CANCEL(cancel_state);
  1321. return(TRUE);
  1322. }
  1323. }
  1324. blocks_to_get = (GC_heapsize - GC_heapsize_at_forced_unmap)
  1325. / (HBLKSIZE * GC_free_space_divisor)
  1326. + needed_blocks;
  1327. if (blocks_to_get > MAXHINCR) {
  1328. word slop;
  1329. /* Get the minimum required to make it likely that we can satisfy */
  1330. /* the current request in the presence of black-listing. */
  1331. /* This will probably be more than MAXHINCR. */
  1332. if (ignore_off_page) {
  1333. slop = 4;
  1334. } else {
  1335. slop = 2 * divHBLKSZ(BL_LIMIT);
  1336. if (slop > needed_blocks) slop = needed_blocks;
  1337. }
  1338. if (needed_blocks + slop > MAXHINCR) {
  1339. blocks_to_get = needed_blocks + slop;
  1340. } else {
  1341. blocks_to_get = MAXHINCR;
  1342. }
  1343. if (blocks_to_get > divHBLKSZ(GC_WORD_MAX))
  1344. blocks_to_get = divHBLKSZ(GC_WORD_MAX);
  1345. }
  1346. if (!GC_expand_hp_inner(blocks_to_get)
  1347. && (blocks_to_get == needed_blocks
  1348. || !GC_expand_hp_inner(needed_blocks))) {
  1349. if (gc_not_stopped == FALSE) {
  1350. /* Don't increment GC_fail_count here (and no warning). */
  1351. GC_gcollect_inner();
  1352. GC_ASSERT(GC_bytes_allocd == 0);
  1353. } else if (GC_fail_count++ < GC_max_retries) {
  1354. WARN("Out of Memory! Trying to continue...\n", 0);
  1355. GC_gcollect_inner();
  1356. } else {
  1357. # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
  1358. WARN("Out of Memory! Heap size: %" WARN_PRIdPTR " MiB."
  1359. " Returning NULL!\n", (GC_heapsize - GC_unmapped_bytes) >> 20);
  1360. # endif
  1361. RESTORE_CANCEL(cancel_state);
  1362. return(FALSE);
  1363. }
  1364. } else if (GC_fail_count) {
  1365. GC_COND_LOG_PRINTF("Memory available again...\n");
  1366. }
  1367. RESTORE_CANCEL(cancel_state);
  1368. return(TRUE);
  1369. }
  1370. /*
  1371. * Make sure the object free list for size gran (in granules) is not empty.
  1372. * Return a pointer to the first object on the free list.
  1373. * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
  1374. */
  1375. GC_INNER ptr_t GC_allocobj(size_t gran, int kind)
  1376. {
  1377. void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]);
  1378. GC_bool tried_minor = FALSE;
  1379. GC_bool retry = FALSE;
  1380. GC_ASSERT(I_HOLD_LOCK());
  1381. if (gran == 0) return(0);
  1382. while (*flh == 0) {
  1383. ENTER_GC();
  1384. /* Do our share of marking work */
  1385. if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
  1386. /* Sweep blocks for objects of this size */
  1387. GC_ASSERT(!GC_is_full_gc
  1388. || NULL == GC_obj_kinds[kind].ok_reclaim_list
  1389. || NULL == GC_obj_kinds[kind].ok_reclaim_list[gran]);
  1390. GC_continue_reclaim(gran, kind);
  1391. EXIT_GC();
  1392. if (*flh == 0) {
  1393. GC_new_hblk(gran, kind);
  1394. if (*flh == 0) {
  1395. ENTER_GC();
  1396. if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
  1397. && !tried_minor) {
  1398. GC_collect_a_little_inner(1);
  1399. tried_minor = TRUE;
  1400. } else {
  1401. if (!GC_collect_or_expand(1, FALSE, retry)) {
  1402. EXIT_GC();
  1403. return(0);
  1404. }
  1405. retry = TRUE;
  1406. }
  1407. EXIT_GC();
  1408. }
  1409. }
  1410. }
  1411. /* Successful allocation; reset failure count. */
  1412. GC_fail_count = 0;
  1413. return (ptr_t)(*flh);
  1414. }