PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/libgc/alloc.c

https://bitbucket.org/danipen/mono
C | 1137 lines | 815 code | 118 blank | 204 comment | 196 complexity | bcf25a7e8579db6af6e6e3994dccff2c MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0
  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 by Hewlett-Packard Company. All rights reserved.
  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. # include <sys/types.h>
  22. # endif
  23. /*
  24. * Separate free lists are maintained for different sized objects
  25. * up to MAXOBJSZ.
  26. * The call GC_allocobj(i,k) ensures that the freelist for
  27. * kind k objects of size i points to a non-empty
  28. * free list. It returns a pointer to the first entry on the free list.
  29. * In a single-threaded world, GC_allocobj may be called to allocate
  30. * an object of (small) size i as follows:
  31. *
  32. * opp = &(GC_objfreelist[i]);
  33. * if (*opp == 0) GC_allocobj(i, NORMAL);
  34. * ptr = *opp;
  35. * *opp = obj_link(ptr);
  36. *
  37. * Note that this is very fast if the free list is non-empty; it should
  38. * only involve the execution of 4 or 5 simple instructions.
  39. * All composite objects on freelists are cleared, except for
  40. * their first word.
  41. */
  42. /*
  43. * The allocator uses GC_allochblk to allocate large chunks of objects.
  44. * These chunks all start on addresses which are multiples of
  45. * HBLKSZ. Each allocated chunk has an associated header,
  46. * which can be located quickly based on the address of the chunk.
  47. * (See headers.c for details.)
  48. * This makes it possible to check quickly whether an
  49. * arbitrary address corresponds to an object administered by the
  50. * allocator.
  51. */
  52. word GC_non_gc_bytes = 0; /* Number of bytes not intended to be collected */
  53. word GC_gc_no = 0;
  54. #ifndef SMALL_CONFIG
  55. int GC_incremental = 0; /* By default, stop the world. */
  56. #endif
  57. int GC_parallel = FALSE; /* By default, parallel GC is off. */
  58. int GC_full_freq = 19; /* Every 20th collection is a full */
  59. /* collection, whether we need it */
  60. /* or not. */
  61. GC_bool GC_need_full_gc = FALSE;
  62. /* Need full GC do to heap growth. */
  63. #ifdef THREADS
  64. GC_bool GC_world_stopped = FALSE;
  65. # define IF_THREADS(x) x
  66. #else
  67. # define IF_THREADS(x)
  68. #endif
  69. word GC_used_heap_size_after_full = 0;
  70. char * GC_copyright[] =
  71. {"Copyright 1988,1989 Hans-J. Boehm and Alan J. Demers ",
  72. "Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved. ",
  73. "Copyright (c) 1996-1998 by Silicon Graphics. All rights reserved. ",
  74. "Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved. ",
  75. "THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY",
  76. " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.",
  77. "See source code for details." };
  78. # include "version.h"
  79. #if defined(SAVE_CALL_CHAIN) && \
  80. !(defined(REDIRECT_MALLOC) && defined(GC_HAVE_BUILTIN_BACKTRACE))
  81. # define SAVE_CALL_CHAIN_IN_GC
  82. /* This is only safe if the call chain save mechanism won't end up */
  83. /* calling GC_malloc. The GNU C library documentation suggests */
  84. /* that backtrace doesn't use malloc, but at least the initial */
  85. /* call in some versions does seem to invoke the dynamic linker, */
  86. /* which uses malloc. */
  87. #endif
  88. /* some more variables */
  89. extern signed_word GC_mem_found; /* Number of reclaimed longwords */
  90. /* after garbage collection */
  91. GC_bool GC_dont_expand = 0;
  92. word GC_free_space_divisor = 3;
  93. extern GC_bool GC_collection_in_progress();
  94. /* Collection is in progress, or was abandoned. */
  95. int GC_never_stop_func GC_PROTO((void)) { return(0); }
  96. unsigned long GC_time_limit = TIME_LIMIT;
  97. CLOCK_TYPE GC_start_time; /* Time at which we stopped world. */
  98. /* used only in GC_timeout_stop_func. */
  99. int GC_n_attempts = 0; /* Number of attempts at finishing */
  100. /* collection within GC_time_limit. */
  101. #if defined(SMALL_CONFIG) || defined(NO_CLOCK)
  102. # define GC_timeout_stop_func GC_never_stop_func
  103. #else
  104. int GC_timeout_stop_func GC_PROTO((void))
  105. {
  106. CLOCK_TYPE current_time;
  107. static unsigned count = 0;
  108. unsigned long time_diff;
  109. if ((count++ & 3) != 0) return(0);
  110. GET_TIME(current_time);
  111. time_diff = MS_TIME_DIFF(current_time,GC_start_time);
  112. if (time_diff >= GC_time_limit) {
  113. # ifdef CONDPRINT
  114. if (GC_print_stats) {
  115. GC_printf0("Abandoning stopped marking after ");
  116. GC_printf1("%lu msecs", (unsigned long)time_diff);
  117. GC_printf1("(attempt %ld)\n", (unsigned long) GC_n_attempts);
  118. }
  119. # endif
  120. return(1);
  121. }
  122. return(0);
  123. }
  124. #endif /* !SMALL_CONFIG */
  125. /* Return the minimum number of words that must be allocated between */
  126. /* collections to amortize the collection cost. */
  127. static word min_words_allocd()
  128. {
  129. # ifdef THREADS
  130. /* We punt, for now. */
  131. register signed_word stack_size = 10000;
  132. # else
  133. int dummy;
  134. register signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom;
  135. # endif
  136. word total_root_size; /* includes double stack size, */
  137. /* since the stack is expensive */
  138. /* to scan. */
  139. word scan_size; /* Estimate of memory to be scanned */
  140. /* during normal GC. */
  141. if (stack_size < 0) stack_size = -stack_size;
  142. total_root_size = 2 * stack_size + GC_root_size;
  143. scan_size = BYTES_TO_WORDS(GC_heapsize - GC_large_free_bytes
  144. + (GC_large_free_bytes >> 2)
  145. /* use a bit more of large empty heap */
  146. + total_root_size);
  147. if (TRUE_INCREMENTAL) {
  148. return scan_size / (2 * GC_free_space_divisor);
  149. } else {
  150. return scan_size / GC_free_space_divisor;
  151. }
  152. }
  153. /* Return the number of words allocated, adjusted for explicit storage */
  154. /* management, etc.. This number is used in deciding when to trigger */
  155. /* collections. */
  156. word GC_adj_words_allocd()
  157. {
  158. register signed_word result;
  159. register signed_word expl_managed =
  160. BYTES_TO_WORDS((long)GC_non_gc_bytes
  161. - (long)GC_non_gc_bytes_at_gc);
  162. /* Don't count what was explicitly freed, or newly allocated for */
  163. /* explicit management. Note that deallocating an explicitly */
  164. /* managed object should not alter result, assuming the client */
  165. /* is playing by the rules. */
  166. result = (signed_word)GC_words_allocd
  167. - (signed_word)GC_mem_freed
  168. + (signed_word)GC_finalizer_mem_freed - expl_managed;
  169. if (result > (signed_word)GC_words_allocd) {
  170. result = GC_words_allocd;
  171. /* probably client bug or unfortunate scheduling */
  172. }
  173. result += GC_words_finalized;
  174. /* We count objects enqueued for finalization as though they */
  175. /* had been reallocated this round. Finalization is user */
  176. /* visible progress. And if we don't count this, we have */
  177. /* stability problems for programs that finalize all objects. */
  178. if ((GC_words_wasted >> 3) < result)
  179. result += GC_words_wasted;
  180. /* This doesn't reflect useful work. But if there is lots of */
  181. /* new fragmentation, the same is probably true of the heap, */
  182. /* and the collection will be correspondingly cheaper. */
  183. if (result < (signed_word)(GC_words_allocd >> 3)) {
  184. /* Always count at least 1/8 of the allocations. We don't want */
  185. /* to collect too infrequently, since that would inhibit */
  186. /* coalescing of free storage blocks. */
  187. /* This also makes us partially robust against client bugs. */
  188. return(GC_words_allocd >> 3);
  189. } else {
  190. return(result);
  191. }
  192. }
  193. /* Clear up a few frames worth of garbage left at the top of the stack. */
  194. /* This is used to prevent us from accidentally treating garbade left */
  195. /* on the stack by other parts of the collector as roots. This */
  196. /* differs from the code in misc.c, which actually tries to keep the */
  197. /* stack clear of long-lived, client-generated garbage. */
  198. void GC_clear_a_few_frames()
  199. {
  200. # define NWORDS 64
  201. word frames[NWORDS];
  202. /* Some compilers will warn that frames was set but never used. */
  203. /* That's the whole idea ... */
  204. register int i;
  205. for (i = 0; i < NWORDS; i++) frames[i] = 0;
  206. }
  207. /* Heap size at which we need a collection to avoid expanding past */
  208. /* limits used by blacklisting. */
  209. static word GC_collect_at_heapsize = (word)(-1);
  210. /* Have we allocated enough to amortize a collection? */
  211. GC_bool GC_should_collect()
  212. {
  213. return(GC_adj_words_allocd() >= min_words_allocd()
  214. || GC_heapsize >= GC_collect_at_heapsize);
  215. }
  216. void GC_notify_full_gc()
  217. {
  218. if (GC_start_call_back != (void (*) GC_PROTO((void)))0) {
  219. (*GC_start_call_back)();
  220. }
  221. }
  222. GC_bool GC_is_full_gc = FALSE;
  223. /*
  224. * Initiate a garbage collection if appropriate.
  225. * Choose judiciously
  226. * between partial, full, and stop-world collections.
  227. * Assumes lock held, signals disabled.
  228. */
  229. void GC_maybe_gc()
  230. {
  231. static int n_partial_gcs = 0;
  232. if (GC_should_collect()) {
  233. if (!GC_incremental) {
  234. GC_gcollect_inner();
  235. n_partial_gcs = 0;
  236. return;
  237. } else {
  238. # ifdef PARALLEL_MARK
  239. GC_wait_for_reclaim();
  240. # endif
  241. if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) {
  242. # ifdef CONDPRINT
  243. if (GC_print_stats) {
  244. GC_printf2(
  245. "***>Full mark for collection %lu after %ld allocd bytes\n",
  246. (unsigned long) GC_gc_no+1,
  247. (long)WORDS_TO_BYTES(GC_words_allocd));
  248. }
  249. # endif
  250. GC_promote_black_lists();
  251. (void)GC_reclaim_all((GC_stop_func)0, TRUE);
  252. GC_clear_marks();
  253. n_partial_gcs = 0;
  254. GC_notify_full_gc();
  255. GC_is_full_gc = TRUE;
  256. } else {
  257. n_partial_gcs++;
  258. }
  259. }
  260. /* We try to mark with the world stopped. */
  261. /* If we run out of time, this turns into */
  262. /* incremental marking. */
  263. # ifndef NO_CLOCK
  264. if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); }
  265. # endif
  266. if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED?
  267. GC_never_stop_func : GC_timeout_stop_func)) {
  268. # ifdef SAVE_CALL_CHAIN_IN_GC
  269. GC_save_callers(GC_last_stack);
  270. # endif
  271. GC_finish_collection();
  272. } else {
  273. if (!GC_is_full_gc) {
  274. /* Count this as the first attempt */
  275. GC_n_attempts++;
  276. }
  277. }
  278. }
  279. }
  280. /*
  281. * Stop the world garbage collection. Assumes lock held, signals disabled.
  282. * If stop_func is not GC_never_stop_func, then abort if stop_func returns TRUE.
  283. * Return TRUE if we successfully completed the collection.
  284. */
  285. GC_bool GC_try_to_collect_inner(stop_func)
  286. GC_stop_func stop_func;
  287. {
  288. # ifdef CONDPRINT
  289. CLOCK_TYPE start_time, current_time;
  290. # endif
  291. if (GC_dont_gc) return FALSE;
  292. if (GC_notify_event)
  293. GC_notify_event (GC_EVENT_START);
  294. if (GC_incremental && GC_collection_in_progress()) {
  295. # ifdef CONDPRINT
  296. if (GC_print_stats) {
  297. GC_printf0(
  298. "GC_try_to_collect_inner: finishing collection in progress\n");
  299. }
  300. # endif /* CONDPRINT */
  301. /* Just finish collection already in progress. */
  302. while(GC_collection_in_progress()) {
  303. if (stop_func()) return(FALSE);
  304. GC_collect_a_little_inner(1);
  305. }
  306. }
  307. if (stop_func == GC_never_stop_func) GC_notify_full_gc();
  308. # ifdef CONDPRINT
  309. if (GC_print_stats) {
  310. if (GC_print_stats) GET_TIME(start_time);
  311. GC_printf2(
  312. "Initiating full world-stop collection %lu after %ld allocd bytes\n",
  313. (unsigned long) GC_gc_no+1,
  314. (long)WORDS_TO_BYTES(GC_words_allocd));
  315. }
  316. # endif
  317. GC_promote_black_lists();
  318. /* Make sure all blocks have been reclaimed, so sweep routines */
  319. /* don't see cleared mark bits. */
  320. /* If we're guaranteed to finish, then this is unnecessary. */
  321. /* In the find_leak case, we have to finish to guarantee that */
  322. /* previously unmarked objects are not reported as leaks. */
  323. # ifdef PARALLEL_MARK
  324. GC_wait_for_reclaim();
  325. # endif
  326. if ((GC_find_leak || stop_func != GC_never_stop_func)
  327. && !GC_reclaim_all(stop_func, FALSE)) {
  328. /* Aborted. So far everything is still consistent. */
  329. return(FALSE);
  330. }
  331. GC_invalidate_mark_state(); /* Flush mark stack. */
  332. GC_clear_marks();
  333. # ifdef SAVE_CALL_CHAIN_IN_GC
  334. GC_save_callers(GC_last_stack);
  335. # endif
  336. GC_is_full_gc = TRUE;
  337. if (!GC_stopped_mark(stop_func)) {
  338. if (!GC_incremental) {
  339. /* We're partially done and have no way to complete or use */
  340. /* current work. Reestablish invariants as cheaply as */
  341. /* possible. */
  342. GC_invalidate_mark_state();
  343. GC_unpromote_black_lists();
  344. } /* else we claim the world is already still consistent. We'll */
  345. /* finish incrementally. */
  346. return(FALSE);
  347. }
  348. GC_finish_collection();
  349. # if defined(CONDPRINT)
  350. if (GC_print_stats) {
  351. GET_TIME(current_time);
  352. GC_printf1("Complete collection took %lu msecs\n",
  353. MS_TIME_DIFF(current_time,start_time));
  354. }
  355. # endif
  356. if (GC_notify_event)
  357. GC_notify_event (GC_EVENT_END);
  358. return(TRUE);
  359. }
  360. /*
  361. * Perform n units of garbage collection work. A unit is intended to touch
  362. * roughly GC_RATE pages. Every once in a while, we do more than that.
  363. * This needa to be a fairly large number with our current incremental
  364. * GC strategy, since otherwise we allocate too much during GC, and the
  365. * cleanup gets expensive.
  366. */
  367. # define GC_RATE 10
  368. # define MAX_PRIOR_ATTEMPTS 1
  369. /* Maximum number of prior attempts at world stop marking */
  370. /* A value of 1 means that we finish the second time, no matter */
  371. /* how long it takes. Doesn't count the initial root scan */
  372. /* for a full GC. */
  373. int GC_deficit = 0; /* The number of extra calls to GC_mark_some */
  374. /* that we have made. */
  375. void GC_collect_a_little_inner(n)
  376. int n;
  377. {
  378. register int i;
  379. if (GC_dont_gc) return;
  380. if (GC_incremental && GC_collection_in_progress()) {
  381. for (i = GC_deficit; i < GC_RATE*n; i++) {
  382. if (GC_mark_some((ptr_t)0)) {
  383. /* Need to finish a collection */
  384. # ifdef SAVE_CALL_CHAIN_IN_GC
  385. GC_save_callers(GC_last_stack);
  386. # endif
  387. # ifdef PARALLEL_MARK
  388. GC_wait_for_reclaim();
  389. # endif
  390. if (GC_n_attempts < MAX_PRIOR_ATTEMPTS
  391. && GC_time_limit != GC_TIME_UNLIMITED) {
  392. GET_TIME(GC_start_time);
  393. if (!GC_stopped_mark(GC_timeout_stop_func)) {
  394. GC_n_attempts++;
  395. break;
  396. }
  397. } else {
  398. (void)GC_stopped_mark(GC_never_stop_func);
  399. }
  400. GC_finish_collection();
  401. break;
  402. }
  403. }
  404. if (GC_deficit > 0) GC_deficit -= GC_RATE*n;
  405. if (GC_deficit < 0) GC_deficit = 0;
  406. } else {
  407. GC_maybe_gc();
  408. }
  409. }
  410. int GC_collect_a_little GC_PROTO(())
  411. {
  412. int result;
  413. DCL_LOCK_STATE;
  414. DISABLE_SIGNALS();
  415. LOCK();
  416. GC_collect_a_little_inner(1);
  417. result = (int)GC_collection_in_progress();
  418. UNLOCK();
  419. ENABLE_SIGNALS();
  420. if (!result && GC_debugging_started) GC_print_all_smashed();
  421. return(result);
  422. }
  423. /*
  424. * Assumes lock is held, signals are disabled.
  425. * We stop the world.
  426. * If stop_func() ever returns TRUE, we may fail and return FALSE.
  427. * Increment GC_gc_no if we succeed.
  428. */
  429. GC_bool GC_stopped_mark(stop_func)
  430. GC_stop_func stop_func;
  431. {
  432. register int i;
  433. int dummy;
  434. # if defined(PRINTTIMES) || defined(CONDPRINT)
  435. CLOCK_TYPE start_time, current_time;
  436. # endif
  437. # ifdef PRINTTIMES
  438. GET_TIME(start_time);
  439. # endif
  440. # if defined(CONDPRINT) && !defined(PRINTTIMES)
  441. if (GC_print_stats) GET_TIME(start_time);
  442. # endif
  443. # if defined(REGISTER_LIBRARIES_EARLY)
  444. GC_cond_register_dynamic_libraries();
  445. # endif
  446. STOP_WORLD();
  447. IF_THREADS(GC_world_stopped = TRUE);
  448. if (GC_notify_event)
  449. GC_notify_event (GC_EVENT_MARK_START);
  450. # ifdef CONDPRINT
  451. if (GC_print_stats) {
  452. GC_printf1("--> Marking for collection %lu ",
  453. (unsigned long) GC_gc_no + 1);
  454. GC_printf2("after %lu allocd bytes + %lu wasted bytes\n",
  455. (unsigned long) WORDS_TO_BYTES(GC_words_allocd),
  456. (unsigned long) WORDS_TO_BYTES(GC_words_wasted));
  457. }
  458. # endif
  459. # ifdef MAKE_BACK_GRAPH
  460. if (GC_print_back_height) {
  461. GC_build_back_graph();
  462. }
  463. # endif
  464. /* Mark from all roots. */
  465. /* Minimize junk left in my registers and on the stack */
  466. GC_clear_a_few_frames();
  467. GC_noop(0,0,0,0,0,0);
  468. GC_initiate_gc();
  469. for(i = 0;;i++) {
  470. if ((*stop_func)()) {
  471. # ifdef CONDPRINT
  472. if (GC_print_stats) {
  473. GC_printf0("Abandoned stopped marking after ");
  474. GC_printf1("%lu iterations\n",
  475. (unsigned long)i);
  476. }
  477. # endif
  478. GC_deficit = i; /* Give the mutator a chance. */
  479. IF_THREADS(GC_world_stopped = FALSE);
  480. START_WORLD();
  481. return(FALSE);
  482. }
  483. if (GC_mark_some((ptr_t)(&dummy))) break;
  484. }
  485. GC_gc_no++;
  486. # ifdef PRINTSTATS
  487. GC_printf2("Collection %lu reclaimed %ld bytes",
  488. (unsigned long) GC_gc_no - 1,
  489. (long)WORDS_TO_BYTES(GC_mem_found));
  490. # else
  491. # ifdef CONDPRINT
  492. if (GC_print_stats) {
  493. GC_printf1("Collection %lu finished", (unsigned long) GC_gc_no - 1);
  494. }
  495. # endif
  496. # endif /* !PRINTSTATS */
  497. # ifdef CONDPRINT
  498. if (GC_print_stats) {
  499. GC_printf1(" ---> heapsize = %lu bytes\n",
  500. (unsigned long) GC_heapsize);
  501. /* Printf arguments may be pushed in funny places. Clear the */
  502. /* space. */
  503. GC_printf0("");
  504. }
  505. # endif /* CONDPRINT */
  506. /* Check all debugged objects for consistency */
  507. if (GC_debugging_started) {
  508. (*GC_check_heap)();
  509. }
  510. if (GC_notify_event)
  511. GC_notify_event (GC_EVENT_MARK_END);
  512. IF_THREADS(GC_world_stopped = FALSE);
  513. START_WORLD();
  514. # ifdef PRINTTIMES
  515. GET_TIME(current_time);
  516. GC_printf1("World-stopped marking took %lu msecs\n",
  517. MS_TIME_DIFF(current_time,start_time));
  518. # else
  519. # ifdef CONDPRINT
  520. if (GC_print_stats) {
  521. GET_TIME(current_time);
  522. GC_printf1("World-stopped marking took %lu msecs\n",
  523. MS_TIME_DIFF(current_time,start_time));
  524. }
  525. # endif
  526. # endif
  527. return(TRUE);
  528. }
  529. /* Set all mark bits for the free list whose first entry is q */
  530. #ifdef __STDC__
  531. void GC_set_fl_marks(ptr_t q)
  532. #else
  533. void GC_set_fl_marks(q)
  534. ptr_t q;
  535. #endif
  536. {
  537. ptr_t p;
  538. struct hblk * h, * last_h = 0;
  539. hdr *hhdr;
  540. int word_no;
  541. for (p = q; p != 0; p = obj_link(p)){
  542. h = HBLKPTR(p);
  543. if (h != last_h) {
  544. last_h = h;
  545. hhdr = HDR(h);
  546. }
  547. word_no = (((word *)p) - ((word *)h));
  548. set_mark_bit_from_hdr(hhdr, word_no);
  549. }
  550. }
  551. /* Clear all mark bits for the free list whose first entry is q */
  552. /* Decrement GC_mem_found by number of words on free list. */
  553. #ifdef __STDC__
  554. void GC_clear_fl_marks(ptr_t q)
  555. #else
  556. void GC_clear_fl_marks(q)
  557. ptr_t q;
  558. #endif
  559. {
  560. ptr_t p;
  561. struct hblk * h, * last_h = 0;
  562. hdr *hhdr;
  563. int word_no;
  564. for (p = q; p != 0; p = obj_link(p)){
  565. h = HBLKPTR(p);
  566. if (h != last_h) {
  567. last_h = h;
  568. hhdr = HDR(h);
  569. }
  570. word_no = (((word *)p) - ((word *)h));
  571. clear_mark_bit_from_hdr(hhdr, word_no);
  572. # ifdef GATHERSTATS
  573. GC_mem_found -= hhdr -> hb_sz;
  574. # endif
  575. }
  576. }
  577. void (*GC_notify_event) GC_PROTO((GCEventType e));
  578. void (*GC_on_heap_resize) GC_PROTO((size_t new_size));
  579. /* Finish up a collection. Assumes lock is held, signals are disabled, */
  580. /* but the world is otherwise running. */
  581. void GC_finish_collection()
  582. {
  583. # ifdef PRINTTIMES
  584. CLOCK_TYPE start_time;
  585. CLOCK_TYPE finalize_time;
  586. CLOCK_TYPE done_time;
  587. GET_TIME(start_time);
  588. finalize_time = start_time;
  589. # endif
  590. if (GC_notify_event)
  591. GC_notify_event (GC_EVENT_RECLAIM_START);
  592. # ifdef GATHERSTATS
  593. GC_mem_found = 0;
  594. # endif
  595. # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG)
  596. if (getenv("GC_PRINT_ADDRESS_MAP") != 0) {
  597. GC_print_address_map();
  598. }
  599. # endif
  600. COND_DUMP;
  601. if (GC_find_leak) {
  602. /* Mark all objects on the free list. All objects should be */
  603. /* marked when we're done. */
  604. {
  605. register word size; /* current object size */
  606. int kind;
  607. ptr_t q;
  608. for (kind = 0; kind < GC_n_kinds; kind++) {
  609. for (size = 1; size <= MAXOBJSZ; size++) {
  610. q = GC_obj_kinds[kind].ok_freelist[size];
  611. if (q != 0) GC_set_fl_marks(q);
  612. }
  613. }
  614. }
  615. GC_start_reclaim(TRUE);
  616. /* The above just checks; it doesn't really reclaim anything. */
  617. }
  618. GC_finalize();
  619. # ifdef STUBBORN_ALLOC
  620. GC_clean_changing_list();
  621. # endif
  622. # ifdef PRINTTIMES
  623. GET_TIME(finalize_time);
  624. # endif
  625. if (GC_print_back_height) {
  626. # ifdef MAKE_BACK_GRAPH
  627. GC_traverse_back_graph();
  628. # else
  629. # ifndef SMALL_CONFIG
  630. GC_err_printf0("Back height not available: "
  631. "Rebuild collector with -DMAKE_BACK_GRAPH\n");
  632. # endif
  633. # endif
  634. }
  635. /* Clear free list mark bits, in case they got accidentally marked */
  636. /* (or GC_find_leak is set and they were intentionally marked). */
  637. /* Also subtract memory remaining from GC_mem_found count. */
  638. /* Note that composite objects on free list are cleared. */
  639. /* Thus accidentally marking a free list is not a problem; only */
  640. /* objects on the list itself will be marked, and that's fixed here. */
  641. {
  642. register word size; /* current object size */
  643. register ptr_t q; /* pointer to current object */
  644. int kind;
  645. for (kind = 0; kind < GC_n_kinds; kind++) {
  646. for (size = 1; size <= MAXOBJSZ; size++) {
  647. q = GC_obj_kinds[kind].ok_freelist[size];
  648. if (q != 0) GC_clear_fl_marks(q);
  649. }
  650. }
  651. }
  652. # ifdef PRINTSTATS
  653. GC_printf1("Bytes recovered before sweep - f.l. count = %ld\n",
  654. (long)WORDS_TO_BYTES(GC_mem_found));
  655. # endif
  656. /* Reconstruct free lists to contain everything not marked */
  657. GC_start_reclaim(FALSE);
  658. if (GC_is_full_gc) {
  659. GC_used_heap_size_after_full = USED_HEAP_SIZE;
  660. GC_need_full_gc = FALSE;
  661. } else {
  662. GC_need_full_gc =
  663. BYTES_TO_WORDS(USED_HEAP_SIZE - GC_used_heap_size_after_full)
  664. > min_words_allocd();
  665. }
  666. # ifdef PRINTSTATS
  667. GC_printf2(
  668. "Immediately reclaimed %ld bytes in heap of size %lu bytes",
  669. (long)WORDS_TO_BYTES(GC_mem_found),
  670. (unsigned long)GC_heapsize);
  671. # ifdef USE_MUNMAP
  672. GC_printf1("(%lu unmapped)", GC_unmapped_bytes);
  673. # endif
  674. GC_printf2(
  675. "\n%lu (atomic) + %lu (composite) collectable bytes in use\n",
  676. (unsigned long)WORDS_TO_BYTES(GC_atomic_in_use),
  677. (unsigned long)WORDS_TO_BYTES(GC_composite_in_use));
  678. # endif
  679. GC_n_attempts = 0;
  680. GC_is_full_gc = FALSE;
  681. /* Reset or increment counters for next cycle */
  682. GC_words_allocd_before_gc += GC_words_allocd;
  683. GC_non_gc_bytes_at_gc = GC_non_gc_bytes;
  684. GC_words_allocd = 0;
  685. GC_words_wasted = 0;
  686. GC_mem_freed = 0;
  687. GC_finalizer_mem_freed = 0;
  688. # ifdef USE_MUNMAP
  689. GC_unmap_old();
  690. # endif
  691. if (GC_notify_event)
  692. GC_notify_event (GC_EVENT_RECLAIM_END);
  693. # ifdef PRINTTIMES
  694. GET_TIME(done_time);
  695. GC_printf2("Finalize + initiate sweep took %lu + %lu msecs\n",
  696. MS_TIME_DIFF(finalize_time,start_time),
  697. MS_TIME_DIFF(done_time,finalize_time));
  698. # endif
  699. }
  700. /* Externally callable routine to invoke full, stop-world collection */
  701. # if defined(__STDC__) || defined(__cplusplus)
  702. int GC_try_to_collect(GC_stop_func stop_func)
  703. # else
  704. int GC_try_to_collect(stop_func)
  705. GC_stop_func stop_func;
  706. # endif
  707. {
  708. int result;
  709. DCL_LOCK_STATE;
  710. if (GC_debugging_started) GC_print_all_smashed();
  711. GC_INVOKE_FINALIZERS();
  712. DISABLE_SIGNALS();
  713. LOCK();
  714. ENTER_GC();
  715. if (!GC_is_initialized) GC_init_inner();
  716. /* Minimize junk left in my registers */
  717. GC_noop(0,0,0,0,0,0);
  718. result = (int)GC_try_to_collect_inner(stop_func);
  719. EXIT_GC();
  720. UNLOCK();
  721. ENABLE_SIGNALS();
  722. if(result) {
  723. if (GC_debugging_started) GC_print_all_smashed();
  724. GC_INVOKE_FINALIZERS();
  725. }
  726. return(result);
  727. }
  728. void GC_gcollect GC_PROTO(())
  729. {
  730. (void)GC_try_to_collect(GC_never_stop_func);
  731. if (GC_have_errors) GC_print_all_errors();
  732. }
  733. word GC_n_heap_sects = 0; /* Number of sections currently in heap. */
  734. /*
  735. * Use the chunk of memory starting at p of size bytes as part of the heap.
  736. * Assumes p is HBLKSIZE aligned, and bytes is a multiple of HBLKSIZE.
  737. */
  738. void GC_add_to_heap(p, bytes)
  739. struct hblk *p;
  740. word bytes;
  741. {
  742. word words;
  743. hdr * phdr;
  744. if (GC_n_heap_sects >= MAX_HEAP_SECTS) {
  745. ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS");
  746. }
  747. phdr = GC_install_header(p);
  748. if (0 == phdr) {
  749. /* This is extremely unlikely. Can't add it. This will */
  750. /* almost certainly result in a 0 return from the allocator, */
  751. /* which is entirely appropriate. */
  752. return;
  753. }
  754. GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p;
  755. GC_heap_sects[GC_n_heap_sects].hs_bytes = bytes;
  756. GC_n_heap_sects++;
  757. words = BYTES_TO_WORDS(bytes);
  758. phdr -> hb_sz = words;
  759. phdr -> hb_map = (unsigned char *)1; /* A value != GC_invalid_map */
  760. phdr -> hb_flags = 0;
  761. GC_freehblk(p);
  762. GC_heapsize += bytes;
  763. if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr
  764. || GC_least_plausible_heap_addr == 0) {
  765. GC_least_plausible_heap_addr = (GC_PTR)((ptr_t)p - sizeof(word));
  766. /* Making it a little smaller than necessary prevents */
  767. /* us from getting a false hit from the variable */
  768. /* itself. There's some unintentional reflection */
  769. /* here. */
  770. }
  771. if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) {
  772. GC_greatest_plausible_heap_addr = (GC_PTR)((ptr_t)p + bytes);
  773. }
  774. }
  775. # if !defined(NO_DEBUGGING)
  776. void GC_print_heap_sects()
  777. {
  778. register unsigned i;
  779. GC_printf1("Total heap size: %lu\n", (unsigned long) GC_heapsize);
  780. for (i = 0; i < GC_n_heap_sects; i++) {
  781. unsigned long start = (unsigned long) GC_heap_sects[i].hs_start;
  782. unsigned long len = (unsigned long) GC_heap_sects[i].hs_bytes;
  783. struct hblk *h;
  784. unsigned nbl = 0;
  785. GC_printf3("Section %ld from 0x%lx to 0x%lx ", (unsigned long)i,
  786. start, (unsigned long)(start + len));
  787. for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) {
  788. if (GC_is_black_listed(h, HBLKSIZE)) nbl++;
  789. }
  790. GC_printf2("%lu/%lu blacklisted\n", (unsigned long)nbl,
  791. (unsigned long)(len/HBLKSIZE));
  792. }
  793. }
  794. # endif
  795. GC_PTR GC_least_plausible_heap_addr = (GC_PTR)ONES;
  796. GC_PTR GC_greatest_plausible_heap_addr = 0;
  797. ptr_t GC_max(x,y)
  798. ptr_t x, y;
  799. {
  800. return(x > y? x : y);
  801. }
  802. ptr_t GC_min(x,y)
  803. ptr_t x, y;
  804. {
  805. return(x < y? x : y);
  806. }
  807. # if defined(__STDC__) || defined(__cplusplus)
  808. void GC_set_max_heap_size(GC_word n)
  809. # else
  810. void GC_set_max_heap_size(n)
  811. GC_word n;
  812. # endif
  813. {
  814. GC_max_heapsize = n;
  815. }
  816. GC_word GC_max_retries = 0;
  817. /*
  818. * this explicitly increases the size of the heap. It is used
  819. * internally, but may also be invoked from GC_expand_hp by the user.
  820. * The argument is in units of HBLKSIZE.
  821. * Tiny values of n are rounded up.
  822. * Returns FALSE on failure.
  823. */
  824. GC_bool GC_expand_hp_inner(n)
  825. word n;
  826. {
  827. word bytes;
  828. struct hblk * space;
  829. word expansion_slop; /* Number of bytes by which we expect the */
  830. /* heap to expand soon. */
  831. if (n < MINHINCR) n = MINHINCR;
  832. bytes = n * HBLKSIZE;
  833. /* Make sure bytes is a multiple of GC_page_size */
  834. {
  835. word mask = GC_page_size - 1;
  836. bytes += mask;
  837. bytes &= ~mask;
  838. }
  839. if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) {
  840. /* Exceeded self-imposed limit */
  841. return(FALSE);
  842. }
  843. space = GET_MEM(bytes);
  844. if( space == 0 ) {
  845. # ifdef CONDPRINT
  846. if (GC_print_stats) {
  847. GC_printf1("Failed to expand heap by %ld bytes\n",
  848. (unsigned long)bytes);
  849. }
  850. # endif
  851. return(FALSE);
  852. }
  853. # ifdef CONDPRINT
  854. if (GC_print_stats) {
  855. GC_printf2("Increasing heap size by %lu after %lu allocated bytes\n",
  856. (unsigned long)bytes,
  857. (unsigned long)WORDS_TO_BYTES(GC_words_allocd));
  858. # ifdef UNDEFINED
  859. GC_printf1("Root size = %lu\n", GC_root_size);
  860. GC_print_block_list(); GC_print_hblkfreelist();
  861. GC_printf0("\n");
  862. # endif
  863. }
  864. # endif
  865. expansion_slop = WORDS_TO_BYTES(min_words_allocd()) + 4*MAXHINCR*HBLKSIZE;
  866. if (GC_last_heap_addr == 0 && !((word)space & SIGNB)
  867. || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) {
  868. /* Assume the heap is growing up */
  869. GC_greatest_plausible_heap_addr =
  870. (GC_PTR)GC_max((ptr_t)GC_greatest_plausible_heap_addr,
  871. (ptr_t)space + bytes + expansion_slop);
  872. } else {
  873. /* Heap is growing down */
  874. GC_least_plausible_heap_addr =
  875. (GC_PTR)GC_min((ptr_t)GC_least_plausible_heap_addr,
  876. (ptr_t)space - expansion_slop);
  877. }
  878. # if defined(LARGE_CONFIG)
  879. if (((ptr_t)GC_greatest_plausible_heap_addr <= (ptr_t)space + bytes
  880. || (ptr_t)GC_least_plausible_heap_addr >= (ptr_t)space)
  881. && GC_heapsize > 0) {
  882. /* GC_add_to_heap will fix this, but ... */
  883. WARN("Too close to address space limit: blacklisting ineffective\n", 0);
  884. }
  885. # endif
  886. GC_prev_heap_addr = GC_last_heap_addr;
  887. GC_last_heap_addr = (ptr_t)space;
  888. GC_add_to_heap(space, bytes);
  889. /* Force GC before we are likely to allocate past expansion_slop */
  890. GC_collect_at_heapsize =
  891. GC_heapsize + expansion_slop - 2*MAXHINCR*HBLKSIZE;
  892. # if defined(LARGE_CONFIG)
  893. if (GC_collect_at_heapsize < GC_heapsize /* wrapped */)
  894. GC_collect_at_heapsize = (word)(-1);
  895. # endif
  896. if (GC_on_heap_resize)
  897. GC_on_heap_resize (GC_heapsize);
  898. return(TRUE);
  899. }
  900. /* Really returns a bool, but it's externally visible, so that's clumsy. */
  901. /* Arguments is in bytes. */
  902. # if defined(__STDC__) || defined(__cplusplus)
  903. int GC_expand_hp(size_t bytes)
  904. # else
  905. int GC_expand_hp(bytes)
  906. size_t bytes;
  907. # endif
  908. {
  909. int result;
  910. DCL_LOCK_STATE;
  911. DISABLE_SIGNALS();
  912. LOCK();
  913. if (!GC_is_initialized) GC_init_inner();
  914. result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes));
  915. if (result) GC_requested_heapsize += bytes;
  916. UNLOCK();
  917. ENABLE_SIGNALS();
  918. return(result);
  919. }
  920. unsigned GC_fail_count = 0;
  921. /* How many consecutive GC/expansion failures? */
  922. /* Reset by GC_allochblk. */
  923. static word last_fo_entries = 0;
  924. static word last_words_finalized = 0;
  925. GC_bool GC_collect_or_expand(needed_blocks, ignore_off_page)
  926. word needed_blocks;
  927. GC_bool ignore_off_page;
  928. {
  929. if (!GC_incremental && !GC_dont_gc &&
  930. ((GC_dont_expand && GC_words_allocd > 0)
  931. || (GC_fo_entries > (last_fo_entries + 500) && (last_words_finalized || GC_words_finalized))
  932. || GC_should_collect())) {
  933. GC_gcollect_inner();
  934. last_fo_entries = GC_fo_entries;
  935. last_words_finalized = GC_words_finalized;
  936. } else {
  937. word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor)
  938. + needed_blocks;
  939. if (blocks_to_get > MAXHINCR) {
  940. word slop;
  941. /* Get the minimum required to make it likely that we */
  942. /* can satisfy the current request in the presence of black- */
  943. /* listing. This will probably be more than MAXHINCR. */
  944. if (ignore_off_page) {
  945. slop = 4;
  946. } else {
  947. slop = 2*divHBLKSZ(BL_LIMIT);
  948. if (slop > needed_blocks) slop = needed_blocks;
  949. }
  950. if (needed_blocks + slop > MAXHINCR) {
  951. blocks_to_get = needed_blocks + slop;
  952. } else {
  953. blocks_to_get = MAXHINCR;
  954. }
  955. }
  956. if (!GC_expand_hp_inner(blocks_to_get)
  957. && !GC_expand_hp_inner(needed_blocks)) {
  958. if (GC_fail_count++ < GC_max_retries) {
  959. WARN("Out of Memory! Trying to continue ...\n", 0);
  960. GC_gcollect_inner();
  961. } else {
  962. # if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC)
  963. WARN("Out of Memory! Returning NIL!\n", 0);
  964. # endif
  965. return(FALSE);
  966. }
  967. } else {
  968. # ifdef CONDPRINT
  969. if (GC_fail_count && GC_print_stats) {
  970. GC_printf0("Memory available again ...\n");
  971. }
  972. # endif
  973. }
  974. }
  975. return(TRUE);
  976. }
  977. /*
  978. * Make sure the object free list for sz is not empty.
  979. * Return a pointer to the first object on the free list.
  980. * The object MUST BE REMOVED FROM THE FREE LIST BY THE CALLER.
  981. * Assumes we hold the allocator lock and signals are disabled.
  982. *
  983. */
  984. ptr_t GC_allocobj(sz, kind)
  985. word sz;
  986. int kind;
  987. {
  988. ptr_t * flh = &(GC_obj_kinds[kind].ok_freelist[sz]);
  989. GC_bool tried_minor = FALSE;
  990. if (sz == 0) return(0);
  991. while (*flh == 0) {
  992. ENTER_GC();
  993. /* Do our share of marking work */
  994. if(TRUE_INCREMENTAL) GC_collect_a_little_inner(1);
  995. /* Sweep blocks for objects of this size */
  996. GC_continue_reclaim(sz, kind);
  997. EXIT_GC();
  998. if (*flh == 0) {
  999. GC_new_hblk(sz, kind);
  1000. }
  1001. if (*flh == 0) {
  1002. ENTER_GC();
  1003. if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED
  1004. && ! tried_minor ) {
  1005. GC_collect_a_little_inner(1);
  1006. tried_minor = TRUE;
  1007. } else {
  1008. if (!GC_collect_or_expand((word)1,FALSE)) {
  1009. EXIT_GC();
  1010. return(0);
  1011. }
  1012. }
  1013. EXIT_GC();
  1014. }
  1015. }
  1016. /* Successful allocation; reset failure count. */
  1017. GC_fail_count = 0;
  1018. return(*flh);
  1019. }