Make guardians thread-safe.
[bpt/guile.git] / libguile / guardians.c
1 /* Copyright (C) 1998,1999,2000,2001, 2006, 2008, 2009, 2011,
2 * 2012, 2013 Free Software Foundation, Inc.
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public License
6 * as published by the Free Software Foundation; either version 3 of
7 * the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
17 * 02110-1301 USA
18 */
19
20 \f
21 /* This is an implementation of guardians as described in
22 * R. Kent Dybvig, Carl Bruggeman, and David Eby (1993) "Guardians in
23 * a Generation-Based Garbage Collector" ACM SIGPLAN Conference on
24 * Programming Language Design and Implementation, June 1993
25 * ftp://ftp.cs.indiana.edu/pub/scheme-repository/doc/pubs/guardians.ps.gz
26 *
27 * Original design: Mikael Djurfeldt
28 * Original implementation: Michael Livshin
29 * Hacked on since by: everybody
30 *
31 * By this point, the semantics are actually quite different from
32 * those described in the abovementioned paper. The semantic changes
33 * are there to improve safety and intuitiveness. The interface is
34 * still (mostly) the one described by the paper, however.
35 *
36 * Boiled down again: Marius Vollmer
37 *
38 * Now they should again behave like those described in the paper.
39 * Scheme guardians should be simple and friendly, not like the greedy
40 * monsters we had...
41 *
42 * Rewritten for the Boehm-Demers-Weiser GC by Ludovic Courtès.
43 */
44
45 /* Uncomment the following line to debug guardian finalization. */
46 /* #define DEBUG_GUARDIANS 1 */
47
48 #ifdef HAVE_CONFIG_H
49 # include <config.h>
50 #endif
51
52 #include "libguile/_scm.h"
53 #include "libguile/async.h"
54 #include "libguile/ports.h"
55 #include "libguile/print.h"
56 #include "libguile/smob.h"
57 #include "libguile/validate.h"
58 #include "libguile/root.h"
59 #include "libguile/hashtab.h"
60 #include "libguile/weaks.h"
61 #include "libguile/deprecation.h"
62 #include "libguile/eval.h"
63
64 #include "libguile/guardians.h"
65 #include "libguile/bdw-gc.h"
66
67
68
69
70 static scm_t_bits tc16_guardian;
71
72 typedef struct t_guardian
73 {
74 scm_i_pthread_mutex_t mutex;
75 unsigned long live;
76 SCM zombies;
77 struct t_guardian *next;
78 } t_guardian;
79
80 #define GUARDIAN_P(x) SCM_SMOB_PREDICATE(tc16_guardian, x)
81 #define GUARDIAN_DATA(x) ((t_guardian *) SCM_SMOB_DATA_1 (x))
82
83
84
85
86 static int
87 guardian_print (SCM guardian, SCM port, scm_print_state *pstate SCM_UNUSED)
88 {
89 t_guardian *g = GUARDIAN_DATA (guardian);
90
91 scm_puts ("#<guardian ", port);
92 scm_uintprint ((scm_t_bits) g, 16, port);
93
94 scm_puts (" (reachable: ", port);
95 scm_display (scm_from_uint (g->live), port);
96 scm_puts (" unreachable: ", port);
97 scm_display (scm_length (g->zombies), port);
98 scm_puts (")", port);
99
100 scm_puts (">", port);
101
102 return 1;
103 }
104
105 /* Handle finalization of OBJ which is guarded by the guardians listed in
106 GUARDIAN_LIST. */
107 static void
108 finalize_guarded (void *ptr, void *finalizer_data)
109 {
110 SCM cell_pool;
111 SCM obj, guardian_list, proxied_finalizer;
112
113 obj = PTR2SCM (ptr);
114 guardian_list = SCM_CDR (PTR2SCM (finalizer_data));
115 proxied_finalizer = SCM_CAR (PTR2SCM (finalizer_data));
116
117 #ifdef DEBUG_GUARDIANS
118 printf ("finalizing guarded %p (%u guardians)\n",
119 ptr, scm_to_uint (scm_length (guardian_list)));
120 #endif
121
122 /* Preallocate a bunch of cells so that we can make sure that no garbage
123 collection (and, thus, nested calls to `finalize_guarded ()') occurs
124 while executing the following loop. This is quite inefficient (call to
125 `scm_length ()') but that shouldn't be a problem in most cases. */
126 cell_pool = scm_make_list (scm_length (guardian_list), SCM_UNSPECIFIED);
127
128 /* Tell each guardian interested in OBJ that OBJ is no longer
129 reachable. */
130 for (;
131 !scm_is_null (guardian_list);
132 guardian_list = SCM_CDR (guardian_list))
133 {
134 SCM zombies;
135 t_guardian *g;
136
137 if (SCM_WEAK_PAIR_CAR_DELETED_P (guardian_list))
138 {
139 /* The guardian itself vanished in the meantime. */
140 #ifdef DEBUG_GUARDIANS
141 printf (" guardian for %p vanished\n", ptr);
142 #endif
143 continue;
144 }
145
146 g = GUARDIAN_DATA (SCM_CAR (guardian_list));
147
148 scm_i_pthread_mutex_lock_block_asyncs (&g->mutex);
149
150 if (g->live == 0)
151 abort ();
152
153 /* Get a fresh cell from CELL_POOL. */
154 zombies = cell_pool;
155 cell_pool = SCM_CDR (cell_pool);
156
157 /* Compute and update G's zombie list. */
158 SCM_SETCAR (zombies, obj);
159 SCM_SETCDR (zombies, g->zombies);
160 g->zombies = zombies;
161
162 g->live--;
163
164 scm_i_pthread_mutex_unlock_unblock_asyncs (&g->mutex);
165 }
166
167 if (scm_is_true (proxied_finalizer))
168 {
169 /* Re-register the finalizer that was in place before we installed this
170 one. */
171 GC_finalization_proc finalizer, prev_finalizer;
172 void *finalizer_data, *prev_finalizer_data;
173
174 finalizer = (GC_finalization_proc) SCM2PTR (SCM_CAR (proxied_finalizer));
175 finalizer_data = SCM2PTR (SCM_CDR (proxied_finalizer));
176
177 if (finalizer == NULL)
178 abort ();
179
180 GC_REGISTER_FINALIZER_NO_ORDER (ptr, finalizer, finalizer_data,
181 &prev_finalizer, &prev_finalizer_data);
182
183 #ifdef DEBUG_GUARDIANS
184 printf (" reinstalled proxied finalizer %p for %p\n", finalizer, ptr);
185 #endif
186 }
187
188 #ifdef DEBUG_GUARDIANS
189 printf ("end of finalize (%p)\n", ptr);
190 #endif
191 }
192
193 /* Add OBJ as a guarded object of GUARDIAN. */
194 static void
195 scm_i_guard (SCM guardian, SCM obj)
196 {
197 t_guardian *g = GUARDIAN_DATA (guardian);
198
199 if (SCM_NIMP (obj))
200 {
201 /* Register a finalizer and pass a pair as the ``client data''
202 argument. The pair contains in its car `#f' or a pair describing a
203 ``proxied'' finalizer (see below); its cdr contains a list of
204 guardians interested in OBJ.
205
206 A ``proxied'' finalizer is a finalizer that was registered for OBJ
207 before OBJ became guarded (e.g., a SMOB `free' function). We are
208 assuming here that finalizers are only used internally, either at
209 the very beginning of an object's lifetime (e.g., see `SCM_NEWSMOB')
210 or by this function. */
211 GC_finalization_proc prev_finalizer;
212 void *prev_data;
213 SCM guardians_for_obj, finalizer_data;
214
215 scm_i_pthread_mutex_lock_block_asyncs (&g->mutex);
216
217 g->live++;
218
219 /* Note: GUARDIANS_FOR_OBJ is a weak list so that a guardian can be
220 collected before the objects it guards (see `guardians.test'). */
221 guardians_for_obj = scm_weak_car_pair (guardian, SCM_EOL);
222 finalizer_data = scm_cons (SCM_BOOL_F, guardians_for_obj);
223
224 GC_REGISTER_FINALIZER_NO_ORDER (SCM2PTR (obj), finalize_guarded,
225 SCM2PTR (finalizer_data),
226 &prev_finalizer, &prev_data);
227
228 if (prev_finalizer == finalize_guarded)
229 {
230 /* OBJ is already guarded by another guardian: add GUARDIAN to its
231 list of guardians. */
232 SCM prev_guardian_list, prev_finalizer_data;
233
234 if (prev_data == NULL)
235 abort ();
236
237 prev_finalizer_data = PTR2SCM (prev_data);
238 if (!scm_is_pair (prev_finalizer_data))
239 abort ();
240
241 prev_guardian_list = SCM_CDR (prev_finalizer_data);
242 SCM_SETCDR (guardians_for_obj, prev_guardian_list);
243
244 /* Also copy information about proxied finalizers. */
245 SCM_SETCAR (finalizer_data, SCM_CAR (prev_finalizer_data));
246 }
247 else if (prev_finalizer != NULL)
248 {
249 /* There was already a finalizer registered for OBJ so we will
250 ``proxy'' it, i.e., record it so that we can re-register it once
251 `finalize_guarded ()' has finished. */
252 SCM proxied_finalizer;
253
254 proxied_finalizer = scm_cons (PTR2SCM (prev_finalizer),
255 PTR2SCM (prev_data));
256 SCM_SETCAR (finalizer_data, proxied_finalizer);
257 }
258
259 scm_i_pthread_mutex_unlock_unblock_asyncs (&g->mutex);
260 }
261 }
262
263 static SCM
264 scm_i_get_one_zombie (SCM guardian)
265 {
266 t_guardian *g = GUARDIAN_DATA (guardian);
267 SCM res = SCM_BOOL_F;
268
269 scm_i_pthread_mutex_lock_block_asyncs (&g->mutex);
270
271 if (!scm_is_null (g->zombies))
272 {
273 /* Note: We return zombies in reverse order. */
274 res = SCM_CAR (g->zombies);
275 g->zombies = SCM_CDR (g->zombies);
276 }
277
278 scm_i_pthread_mutex_unlock_unblock_asyncs (&g->mutex);
279
280 return res;
281 }
282
283 /* This is the Scheme entry point for each guardian: If OBJ is an
284 * object, it's added to the guardian's live list. If OBJ is unbound,
285 * the next available unreachable object (or #f if none) is returned.
286 *
287 * If the second optional argument THROW_P is true (the default), then
288 * an error is raised if GUARDIAN is greedy and OBJ is already greedily
289 * guarded. If THROW_P is false, #f is returned instead of raising the
290 * error, and #t is returned if everything is fine.
291 */
292 static SCM
293 guardian_apply (SCM guardian, SCM obj, SCM throw_p)
294 {
295 if (!SCM_UNBNDP (obj))
296 {
297 scm_i_guard (guardian, obj);
298 return SCM_UNSPECIFIED;
299 }
300 else
301 return scm_i_get_one_zombie (guardian);
302 }
303
304 SCM_DEFINE (scm_make_guardian, "make-guardian", 0, 0, 0,
305 (),
306 "Create a new guardian. A guardian protects a set of objects from\n"
307 "garbage collection, allowing a program to apply cleanup or other\n"
308 "actions.\n"
309 "\n"
310 "@code{make-guardian} returns a procedure representing the guardian.\n"
311 "Calling the guardian procedure with an argument adds the argument to\n"
312 "the guardian's set of protected objects. Calling the guardian\n"
313 "procedure without an argument returns one of the protected objects\n"
314 "which are ready for garbage collection, or @code{#f} if no such object\n"
315 "is available. Objects which are returned in this way are removed from\n"
316 "the guardian.\n"
317 "\n"
318 "You can put a single object into a guardian more than once and you can\n"
319 "put a single object into more than one guardian. The object will then\n"
320 "be returned multiple times by the guardian procedures.\n"
321 "\n"
322 "An object is eligible to be returned from a guardian when it is no\n"
323 "longer referenced from outside any guardian.\n"
324 "\n"
325 "There is no guarantee about the order in which objects are returned\n"
326 "from a guardian. If you want to impose an order on finalization\n"
327 "actions, for example, you can do that by keeping objects alive in some\n"
328 "global data structure until they are no longer needed for finalizing\n"
329 "other objects.\n"
330 "\n"
331 "Being an element in a weak vector, a key in a hash table with weak\n"
332 "keys, or a value in a hash table with weak value does not prevent an\n"
333 "object from being returned by a guardian. But as long as an object\n"
334 "can be returned from a guardian it will not be removed from such a\n"
335 "weak vector or hash table. In other words, a weak link does not\n"
336 "prevent an object from being considered collectable, but being inside\n"
337 "a guardian prevents a weak link from being broken.\n"
338 "\n"
339 "A key in a weak key hash table can be though of as having a strong\n"
340 "reference to its associated value as long as the key is accessible.\n"
341 "Consequently, when the key only accessible from within a guardian, the\n"
342 "reference from the key to the value is also considered to be coming\n"
343 "from within a guardian. Thus, if there is no other reference to the\n"
344 "value, it is eligible to be returned from a guardian.\n")
345 #define FUNC_NAME s_scm_make_guardian
346 {
347 t_guardian *g = scm_gc_malloc (sizeof (t_guardian), "guardian");
348 SCM z;
349
350 scm_i_pthread_mutex_init (&g->mutex, NULL);
351
352 /* A tconc starts out with one tail pair. */
353 g->live = 0;
354 g->zombies = SCM_EOL;
355
356 g->next = NULL;
357
358 SCM_NEWSMOB (z, tc16_guardian, g);
359
360 return z;
361 }
362 #undef FUNC_NAME
363
364 void
365 scm_init_guardians ()
366 {
367 /* We use unordered finalization `a la Java. */
368 #ifdef HAVE_GC_SET_JAVA_FINALIZATION
369 /* This function was added in 7.2alpha2 (June 2009). */
370 GC_set_java_finalization (1);
371 #else
372 /* This symbol is deprecated as of 7.3. */
373 GC_java_finalization = 1;
374 #endif
375
376 tc16_guardian = scm_make_smob_type ("guardian", 0);
377
378 scm_set_smob_print (tc16_guardian, guardian_print);
379 scm_set_smob_apply (tc16_guardian, guardian_apply, 0, 1, 0);
380
381 #include "libguile/guardians.x"
382 }
383
384 /*
385 Local Variables:
386 c-file-style: "gnu"
387 End:
388 */