gc.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /* Copyright 1995-2003,2006,2008-2014,2016-2018
  2. Free Software Foundation, Inc.
  3. This file is part of Guile.
  4. Guile is free software: you can redistribute it and/or modify it
  5. under the terms of the GNU Lesser General Public License as published
  6. by the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. Guile is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  11. License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with Guile. If not, see
  14. <https://www.gnu.org/licenses/>. */
  15. /* #define DEBUGINFO */
  16. #ifdef HAVE_CONFIG_H
  17. # include <config.h>
  18. #endif
  19. #include <stdio.h>
  20. #include <errno.h>
  21. #include <string.h>
  22. #include <stdlib.h>
  23. #include <math.h>
  24. #include <unistd.h>
  25. #include "arrays.h"
  26. #include "async.h"
  27. #include "bdw-gc.h"
  28. #include "deprecation.h"
  29. #include "dynwind.h"
  30. #include "eval.h"
  31. #include "gen-scmconfig.h"
  32. #include "gsubr.h"
  33. #include "hashtab.h"
  34. #include "hooks.h"
  35. #include "list.h"
  36. #include "modules.h"
  37. #include "numbers.h"
  38. #include "pairs.h"
  39. #include "ports.h"
  40. #include "simpos.h"
  41. #include "smob.h"
  42. #include "stackchk.h"
  43. #include "stime.h"
  44. #include "strings.h"
  45. #include "struct.h"
  46. #include "symbols.h"
  47. #include "vectors.h"
  48. #ifdef GUILE_DEBUG_MALLOC
  49. #include "debug-malloc.h"
  50. #endif
  51. #include "gc.h"
  52. /* For GC_set_start_callback. */
  53. #include <gc/gc_mark.h>
  54. /* Size in bytes of the initial heap. This should be about the size of
  55. result of 'guile -c "(display (assq-ref (gc-stats)
  56. 'heap-total-allocated))"'. */
  57. #define DEFAULT_INITIAL_HEAP_SIZE (128 * 1024 * SIZEOF_UINTPTR_T)
  58. /* Set this to != 0 if every cell that is accessed shall be checked:
  59. */
  60. int scm_debug_cell_accesses_p = 0;
  61. int scm_expensive_debug_cell_accesses_p = 0;
  62. /* Set this to 0 if no additional gc's shall be performed, otherwise set it to
  63. * the number of cell accesses after which a gc shall be called.
  64. */
  65. int scm_debug_cells_gc_interval = 0;
  66. /* Hash table that keeps a reference to objects the user wants to protect from
  67. garbage collection. */
  68. static SCM scm_protects;
  69. static int needs_gc_after_nonlocal_exit = 0;
  70. /* Arrange to throw an exception on failed allocations. */
  71. static void*
  72. scm_oom_fn (size_t nbytes)
  73. {
  74. needs_gc_after_nonlocal_exit = 1;
  75. scm_report_out_of_memory ();
  76. return NULL;
  77. }
  78. /* Called within GC -- cannot allocate GC memory. */
  79. static void
  80. scm_gc_warn_proc (char *fmt, GC_word arg)
  81. {
  82. /* avoid scm_current_warning_port() b/c the GC lock is already taken
  83. and the fluid ref might require it */
  84. fprintf (stderr, fmt, arg);
  85. }
  86. void
  87. scm_gc_after_nonlocal_exit (void)
  88. {
  89. if (needs_gc_after_nonlocal_exit)
  90. {
  91. needs_gc_after_nonlocal_exit = 0;
  92. GC_gcollect_and_unmap ();
  93. }
  94. }
  95. /* Hooks. */
  96. scm_t_c_hook scm_before_gc_c_hook;
  97. scm_t_c_hook scm_before_mark_c_hook;
  98. scm_t_c_hook scm_before_sweep_c_hook;
  99. scm_t_c_hook scm_after_sweep_c_hook;
  100. scm_t_c_hook scm_after_gc_c_hook;
  101. static void
  102. run_before_gc_c_hook (void)
  103. {
  104. if (!SCM_I_CURRENT_THREAD)
  105. /* GC while a thread is spinning up; punt. */
  106. return;
  107. scm_c_hook_run (&scm_before_gc_c_hook, NULL);
  108. }
  109. /* GC Statistics Keeping
  110. */
  111. unsigned long scm_gc_ports_collected = 0;
  112. static long gc_time_taken = 0;
  113. static long gc_start_time = 0;
  114. static unsigned long free_space_divisor;
  115. static unsigned long minimum_free_space_divisor;
  116. static double target_free_space_divisor;
  117. static unsigned long protected_obj_count = 0;
  118. SCM_SYMBOL (sym_gc_time_taken, "gc-time-taken");
  119. SCM_SYMBOL (sym_heap_size, "heap-size");
  120. SCM_SYMBOL (sym_heap_free_size, "heap-free-size");
  121. SCM_SYMBOL (sym_heap_total_allocated, "heap-total-allocated");
  122. SCM_SYMBOL (sym_heap_allocated_since_gc, "heap-allocated-since-gc");
  123. SCM_SYMBOL (sym_protected_objects, "protected-objects");
  124. SCM_SYMBOL (sym_times, "gc-times");
  125. /* {Scheme Interface to GC}
  126. */
  127. extern int scm_gc_malloc_yield_percentage;
  128. SCM_DEFINE (scm_gc_stats, "gc-stats", 0, 0, 0,
  129. (),
  130. "Return an association list of statistics about Guile's current\n"
  131. "use of storage.\n")
  132. #define FUNC_NAME s_scm_gc_stats
  133. {
  134. SCM answer;
  135. GC_word heap_size, free_bytes, unmapped_bytes, bytes_since_gc, total_bytes;
  136. size_t gc_times;
  137. GC_get_heap_usage_safe (&heap_size, &free_bytes, &unmapped_bytes,
  138. &bytes_since_gc, &total_bytes);
  139. gc_times = GC_get_gc_no ();
  140. answer =
  141. scm_list_n (scm_cons (sym_gc_time_taken, scm_from_long (gc_time_taken)),
  142. scm_cons (sym_heap_size, scm_from_size_t (heap_size)),
  143. scm_cons (sym_heap_free_size, scm_from_size_t (free_bytes)),
  144. scm_cons (sym_heap_total_allocated,
  145. scm_from_size_t (total_bytes)),
  146. scm_cons (sym_heap_allocated_since_gc,
  147. scm_from_size_t (bytes_since_gc)),
  148. scm_cons (sym_protected_objects,
  149. scm_from_ulong (protected_obj_count)),
  150. scm_cons (sym_times, scm_from_size_t (gc_times)),
  151. SCM_UNDEFINED);
  152. return answer;
  153. }
  154. #undef FUNC_NAME
  155. SCM_DEFINE (scm_gc_dump, "gc-dump", 0, 0, 0,
  156. (void),
  157. "Dump information about the garbage collector's internal data "
  158. "structures and memory usage to the standard output.")
  159. #define FUNC_NAME s_scm_gc_dump
  160. {
  161. GC_dump ();
  162. return SCM_UNSPECIFIED;
  163. }
  164. #undef FUNC_NAME
  165. SCM_DEFINE (scm_object_address, "object-address", 1, 0, 0,
  166. (SCM obj),
  167. "Return an integer that for the lifetime of @var{obj} is uniquely\n"
  168. "returned by this function for @var{obj}")
  169. #define FUNC_NAME s_scm_object_address
  170. {
  171. return scm_from_ulong (SCM_UNPACK (obj));
  172. }
  173. #undef FUNC_NAME
  174. SCM_DEFINE (scm_gc_disable, "gc-disable", 0, 0, 0,
  175. (),
  176. "Disables the garbage collector. Nested calls are permitted. "
  177. "GC is re-enabled once @code{gc-enable} has been called the "
  178. "same number of times @code{gc-disable} was called.")
  179. #define FUNC_NAME s_scm_gc_disable
  180. {
  181. GC_disable ();
  182. return SCM_UNSPECIFIED;
  183. }
  184. #undef FUNC_NAME
  185. SCM_DEFINE (scm_gc_enable, "gc-enable", 0, 0, 0,
  186. (),
  187. "Enables the garbage collector.")
  188. #define FUNC_NAME s_scm_gc_enable
  189. {
  190. GC_enable ();
  191. return SCM_UNSPECIFIED;
  192. }
  193. #undef FUNC_NAME
  194. SCM_DEFINE (scm_gc, "gc", 0, 0, 0,
  195. (),
  196. "Scans all of SCM objects and reclaims for further use those that are\n"
  197. "no longer accessible.")
  198. #define FUNC_NAME s_scm_gc
  199. {
  200. scm_i_gc ("call");
  201. /* If you're calling scm_gc(), you probably want synchronous
  202. finalization. */
  203. GC_invoke_finalizers ();
  204. return SCM_UNSPECIFIED;
  205. }
  206. #undef FUNC_NAME
  207. void
  208. scm_i_gc (const char *what)
  209. {
  210. GC_gcollect ();
  211. }
  212. /* {GC Protection Helper Functions}
  213. */
  214. /*
  215. * If within a function you need to protect one or more scheme objects from
  216. * garbage collection, pass them as parameters to one of the
  217. * scm_remember_upto_here* functions below. These functions don't do
  218. * anything, but since the compiler does not know that they are actually
  219. * no-ops, it will generate code that calls these functions with the given
  220. * parameters. Therefore, you can be sure that the compiler will keep those
  221. * scheme values alive (on the stack or in a register) up to the point where
  222. * scm_remember_upto_here* is called. In other words, place the call to
  223. * scm_remember_upto_here* _behind_ the last code in your function, that
  224. * depends on the scheme object to exist.
  225. *
  226. * Example: We want to make sure that the string object str does not get
  227. * garbage collected during the execution of 'some_function' in the code
  228. * below, because otherwise the characters belonging to str would be freed and
  229. * 'some_function' might access freed memory. To make sure that the compiler
  230. * keeps str alive on the stack or in a register such that it is visible to
  231. * the conservative gc we add the call to scm_remember_upto_here_1 _after_ the
  232. * call to 'some_function'. Note that this would not be necessary if str was
  233. * used anyway after the call to 'some_function'.
  234. * char *chars = scm_i_string_chars (str);
  235. * some_function (chars);
  236. * scm_remember_upto_here_1 (str); // str will be alive up to this point.
  237. */
  238. /* Remove any macro versions of these while defining the functions.
  239. Functions are always included in the library, for upward binary
  240. compatibility and in case combinations of GCC and non-GCC are used. */
  241. #undef scm_remember_upto_here_1
  242. #undef scm_remember_upto_here_2
  243. void
  244. scm_remember_upto_here_1 (SCM obj SCM_UNUSED)
  245. {
  246. /* Empty. Protects a single object from garbage collection. */
  247. }
  248. void
  249. scm_remember_upto_here_2 (SCM obj1 SCM_UNUSED, SCM obj2 SCM_UNUSED)
  250. {
  251. /* Empty. Protects two objects from garbage collection. */
  252. }
  253. void
  254. scm_remember_upto_here (SCM obj SCM_UNUSED, ...)
  255. {
  256. /* Empty. Protects any number of objects from garbage collection. */
  257. }
  258. /*
  259. These crazy functions prevent garbage collection
  260. of arguments after the first argument by
  261. ensuring they remain live throughout the
  262. function because they are used in the last
  263. line of the code block.
  264. It'd be better to have a nice compiler hint to
  265. aid the conservative stack-scanning GC. --03/09/00 gjb */
  266. SCM
  267. scm_return_first (SCM elt, ...)
  268. {
  269. return elt;
  270. }
  271. int
  272. scm_return_first_int (int i, ...)
  273. {
  274. return i;
  275. }
  276. SCM
  277. scm_permanent_object (SCM obj)
  278. {
  279. return (scm_gc_protect_object (obj));
  280. }
  281. /* Protect OBJ from the garbage collector. OBJ will not be freed, even if all
  282. other references are dropped, until the object is unprotected by calling
  283. scm_gc_unprotect_object (OBJ). Calls to scm_gc_protect/unprotect_object nest,
  284. i. e. it is possible to protect the same object several times, but it is
  285. necessary to unprotect the object the same number of times to actually get
  286. the object unprotected. It is an error to unprotect an object more often
  287. than it has been protected before. The function scm_protect_object returns
  288. OBJ.
  289. */
  290. /* Implementation note: For every object X, there is a counter which
  291. scm_gc_protect_object (X) increments and scm_gc_unprotect_object (X) decrements.
  292. */
  293. static scm_i_pthread_mutex_t gc_protect_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  294. SCM
  295. scm_gc_protect_object (SCM obj)
  296. {
  297. SCM handle;
  298. scm_dynwind_begin (0);
  299. scm_i_dynwind_pthread_mutex_lock (&gc_protect_lock);
  300. handle = scm_hashq_create_handle_x (scm_protects, obj, scm_from_int (0));
  301. SCM_SETCDR (handle, scm_sum (SCM_CDR (handle), scm_from_int (1)));
  302. protected_obj_count ++;
  303. scm_dynwind_end ();
  304. return obj;
  305. }
  306. /* Remove any protection for OBJ established by a prior call to
  307. scm_protect_object. This function returns OBJ.
  308. See scm_protect_object for more information. */
  309. SCM
  310. scm_gc_unprotect_object (SCM obj)
  311. {
  312. SCM handle;
  313. scm_dynwind_begin (0);
  314. scm_i_dynwind_pthread_mutex_lock (&gc_protect_lock);
  315. handle = scm_hashq_get_handle (scm_protects, obj);
  316. if (scm_is_false (handle))
  317. {
  318. fprintf (stderr, "scm_unprotect_object called on unprotected object\n");
  319. abort ();
  320. }
  321. else
  322. {
  323. SCM count = scm_difference (SCM_CDR (handle), scm_from_int (1));
  324. if (scm_is_eq (count, scm_from_int (0)))
  325. scm_hashq_remove_x (scm_protects, obj);
  326. else
  327. SCM_SETCDR (handle, count);
  328. }
  329. protected_obj_count --;
  330. scm_dynwind_end ();
  331. return obj;
  332. }
  333. void
  334. scm_gc_register_root (SCM *p)
  335. {
  336. /* Nothing. */
  337. }
  338. void
  339. scm_gc_unregister_root (SCM *p)
  340. {
  341. /* Nothing. */
  342. }
  343. void
  344. scm_gc_register_roots (SCM *b, unsigned long n)
  345. {
  346. SCM *p = b;
  347. for (; p < b + n; ++p)
  348. scm_gc_register_root (p);
  349. }
  350. void
  351. scm_gc_unregister_roots (SCM *b, unsigned long n)
  352. {
  353. SCM *p = b;
  354. for (; p < b + n; ++p)
  355. scm_gc_unregister_root (p);
  356. }
  357. void
  358. scm_storage_prehistory ()
  359. {
  360. GC_set_all_interior_pointers (0);
  361. free_space_divisor = scm_getenv_int ("GC_FREE_SPACE_DIVISOR", 3);
  362. minimum_free_space_divisor = free_space_divisor;
  363. target_free_space_divisor = free_space_divisor;
  364. GC_set_free_space_divisor (free_space_divisor);
  365. GC_set_finalize_on_demand (1);
  366. #if (GC_VERSION_MAJOR == 7 && GC_VERSION_MINOR == 4 \
  367. && GC_VERSION_MICRO == 0)
  368. /* BDW-GC 7.4.0 has a bug making it loop indefinitely when using more
  369. than one marker thread: <https://github.com/ivmai/bdwgc/pull/30>.
  370. Work around it by asking for one marker thread. */
  371. setenv ("GC_MARKERS", "1", 1);
  372. #endif
  373. #if SCM_I_GSC_USE_NULL_THREADS
  374. /* If we have disabled threads in Guile, ensure that the GC doesn't
  375. spawn any marker threads. */
  376. setenv ("GC_MARKERS", "1", 1);
  377. #endif
  378. GC_INIT ();
  379. GC_expand_hp (DEFAULT_INITIAL_HEAP_SIZE);
  380. /* We only need to register a displacement for those types for which the
  381. higher bits of the type tag are used to store a pointer (that is, a
  382. pointer to an 8-octet aligned region). */
  383. GC_REGISTER_DISPLACEMENT (scm_tc3_cons);
  384. GC_REGISTER_DISPLACEMENT (scm_tc5_struct);
  385. /* GC_REGISTER_DISPLACEMENT (scm_tc3_unused); */
  386. /* Sanity check. */
  387. if (!GC_is_visible (&scm_protects))
  388. abort ();
  389. scm_c_hook_init (&scm_before_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
  390. scm_c_hook_init (&scm_before_mark_c_hook, 0, SCM_C_HOOK_NORMAL);
  391. scm_c_hook_init (&scm_before_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
  392. scm_c_hook_init (&scm_after_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
  393. scm_c_hook_init (&scm_after_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
  394. }
  395. void
  396. scm_init_gc_protect_object ()
  397. {
  398. scm_protects = scm_c_make_hash_table (31);
  399. #if 0
  400. /* We can't have a cleanup handler since we have no thread to run it
  401. in. */
  402. #ifdef HAVE_ATEXIT
  403. atexit (cleanup);
  404. #else
  405. #ifdef HAVE_ON_EXIT
  406. on_exit (cleanup, 0);
  407. #endif
  408. #endif
  409. #endif
  410. }
  411. SCM scm_after_gc_hook;
  412. static SCM after_gc_async_cell;
  413. /* The function after_gc_async_thunk causes the execution of the
  414. * after-gc-hook. It is run after the gc, as soon as the asynchronous
  415. * events are handled by the evaluator.
  416. */
  417. static SCM
  418. after_gc_async_thunk (void)
  419. {
  420. /* Fun, no? Hook-run *and* run-hook? */
  421. scm_c_hook_run (&scm_after_gc_c_hook, NULL);
  422. scm_c_run_hook (scm_after_gc_hook, SCM_EOL);
  423. return SCM_UNSPECIFIED;
  424. }
  425. /* The function queue_after_gc_hook is run by the scm_before_gc_c_hook
  426. * at the end of the garbage collection. The only purpose of this
  427. * function is to mark the after_gc_async (which will eventually lead to
  428. * the execution of the after_gc_async_thunk).
  429. */
  430. static void *
  431. queue_after_gc_hook (void * hook_data SCM_UNUSED,
  432. void *fn_data SCM_UNUSED,
  433. void *data SCM_UNUSED)
  434. {
  435. scm_thread *t = SCM_I_CURRENT_THREAD;
  436. if (scm_is_false (SCM_CDR (after_gc_async_cell)))
  437. {
  438. SCM_SETCDR (after_gc_async_cell, t->pending_asyncs);
  439. t->pending_asyncs = after_gc_async_cell;
  440. }
  441. return NULL;
  442. }
  443. static void *
  444. start_gc_timer (void * hook_data SCM_UNUSED,
  445. void *fn_data SCM_UNUSED,
  446. void *data SCM_UNUSED)
  447. {
  448. if (!gc_start_time)
  449. gc_start_time = scm_c_get_internal_run_time ();
  450. return NULL;
  451. }
  452. static void *
  453. accumulate_gc_timer (void * hook_data SCM_UNUSED,
  454. void *fn_data SCM_UNUSED,
  455. void *data SCM_UNUSED)
  456. {
  457. if (gc_start_time)
  458. {
  459. long now = scm_c_get_internal_run_time ();
  460. gc_time_taken += now - gc_start_time;
  461. gc_start_time = 0;
  462. }
  463. return NULL;
  464. }
  465. static size_t bytes_until_gc = DEFAULT_INITIAL_HEAP_SIZE;
  466. static scm_i_pthread_mutex_t bytes_until_gc_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  467. void
  468. scm_gc_register_allocation (size_t size)
  469. {
  470. scm_i_pthread_mutex_lock (&bytes_until_gc_lock);
  471. if (bytes_until_gc - size > bytes_until_gc)
  472. {
  473. bytes_until_gc = GC_get_heap_size ();
  474. scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
  475. GC_gcollect ();
  476. }
  477. else
  478. {
  479. bytes_until_gc -= size;
  480. scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
  481. }
  482. }
  483. void
  484. scm_init_gc ()
  485. {
  486. /* `GC_INIT ()' was invoked in `scm_storage_prehistory ()'. */
  487. scm_after_gc_hook = scm_make_hook (SCM_INUM0);
  488. scm_c_define ("after-gc-hook", scm_after_gc_hook);
  489. /* When the async is to run, the cdr of the gc_async pair gets set to
  490. the asyncs queue of the current thread. */
  491. after_gc_async_cell = scm_cons (scm_c_make_gsubr ("%after-gc-thunk", 0, 0, 0,
  492. after_gc_async_thunk),
  493. SCM_BOOL_F);
  494. scm_c_hook_add (&scm_before_gc_c_hook, queue_after_gc_hook, NULL, 0);
  495. scm_c_hook_add (&scm_before_gc_c_hook, start_gc_timer, NULL, 0);
  496. scm_c_hook_add (&scm_after_gc_c_hook, accumulate_gc_timer, NULL, 0);
  497. GC_set_oom_fn (scm_oom_fn);
  498. GC_set_warn_proc (scm_gc_warn_proc);
  499. GC_set_start_callback (run_before_gc_c_hook);
  500. #include "gc.x"
  501. }
  502. void
  503. scm_gc_sweep (void)
  504. #define FUNC_NAME "scm_gc_sweep"
  505. {
  506. /* FIXME */
  507. fprintf (stderr, "%s: doing nothing\n", FUNC_NAME);
  508. }
  509. #undef FUNC_NAME