Merge branch 'bt/elisp'
[bpt/guile.git] / doc / ref / api-memory.texi
1 @c -*-texinfo-*-
2 @c This is part of the GNU Guile Reference Manual.
3 @c Copyright (C) 1996, 1997, 2000, 2001, 2002, 2003, 2004, 2009, 2010, 2012
4 @c Free Software Foundation, Inc.
5 @c See the file guile.texi for copying conditions.
6
7 @node Memory Management
8 @section Memory Management and Garbage Collection
9
10 Guile uses a @emph{garbage collector} to manage most of its objects.
11 While the garbage collector is designed to be mostly invisible, you
12 sometimes need to interact with it explicitly.
13
14 See @ref{Garbage Collection} for a general discussion of how garbage
15 collection relates to using Guile from C.
16
17 @menu
18 * Garbage Collection Functions::
19 * Memory Blocks::
20 * Weak References::
21 * Guardians::
22 @end menu
23
24
25 @node Garbage Collection Functions
26 @subsection Function related to Garbage Collection
27
28 @deffn {Scheme Procedure} gc
29 @deffnx {C Function} scm_gc ()
30 Scans all of SCM objects and reclaims for further use those that are
31 no longer accessible. You normally don't need to call this function
32 explicitly. It is called automatically when appropriate.
33 @end deffn
34
35 @deftypefn {C Function} SCM scm_gc_protect_object (SCM @var{obj})
36 Protects @var{obj} from being freed by the garbage collector, when it
37 otherwise might be. When you are done with the object, call
38 @code{scm_gc_unprotect_object} on the object. Calls to
39 @code{scm_gc_protect}/@code{scm_gc_unprotect_object} can be nested, and
40 the object remains protected until it has been unprotected as many times
41 as it was protected. It is an error to unprotect an object more times
42 than it has been protected. Returns the SCM object it was passed.
43
44 Note that storing @var{obj} in a C global variable has the same
45 effect@footnote{In Guile up to version 1.8, C global variables were not
46 scanned by the garbage collector; hence, @code{scm_gc_protect_object}
47 was the only way in C to prevent a Scheme object from being freed.}.
48 @end deftypefn
49
50 @deftypefn {C Function} SCM scm_gc_unprotect_object (SCM @var{obj})
51
52 Unprotects an object from the garbage collector which was protected by
53 @code{scm_gc_unprotect_object}. Returns the SCM object it was passed.
54 @end deftypefn
55
56 @deftypefn {C Function} SCM scm_permanent_object (SCM @var{obj})
57
58 Similar to @code{scm_gc_protect_object} in that it causes the
59 collector to always mark the object, except that it should not be
60 nested (only call @code{scm_permanent_object} on an object once), and
61 it has no corresponding unpermanent function. Once an object is
62 declared permanent, it will never be freed. Returns the SCM object it
63 was passed.
64 @end deftypefn
65
66 @c NOTE: The varargs scm_remember_upto_here is deliberately not
67 @c documented, because we don't think it can be implemented as a nice
68 @c inline compiler directive or asm block. New _3, _4 or whatever
69 @c forms could certainly be added though, if needed.
70
71 @deftypefn {C Macro} void scm_remember_upto_here_1 (SCM obj)
72 @deftypefnx {C Macro} void scm_remember_upto_here_2 (SCM obj1, SCM obj2)
73 Create a reference to the given object or objects, so they're certain
74 to be present on the stack or in a register and hence will not be
75 freed by the garbage collector before this point.
76
77 Note that these functions can only be applied to ordinary C local
78 variables (ie.@: ``automatics''). Objects held in global or static
79 variables or some malloced block or the like cannot be protected with
80 this mechanism.
81 @end deftypefn
82
83 @deffn {Scheme Procedure} gc-stats
84 @deffnx {C Function} scm_gc_stats ()
85 Return an association list of statistics about Guile's current
86 use of storage.
87 @end deffn
88
89 @deffn {Scheme Procedure} gc-live-object-stats
90 @deffnx {C Function} scm_gc_live_object_stats ()
91 Return an alist of statistics of the current live objects.
92 @end deffn
93
94 @deftypefun void scm_gc_mark (SCM @var{x})
95 Mark the object @var{x}, and recurse on any objects @var{x} refers to.
96 If @var{x}'s mark bit is already set, return immediately. This function
97 must only be called during the mark-phase of garbage collection,
98 typically from a smob @emph{mark} function.
99 @end deftypefun
100
101
102 @node Memory Blocks
103 @subsection Memory Blocks
104
105 @cindex automatically-managed memory
106 @cindex GC-managed memory
107 @cindex conservative garbage collection
108
109 In C programs, dynamic management of memory blocks is normally done
110 with the functions malloc, realloc, and free. Guile has additional
111 functions for dynamic memory allocation that are integrated into the
112 garbage collector and the error reporting system.
113
114 Memory blocks that are associated with Scheme objects (for example a
115 smob) should be allocated with @code{scm_gc_malloc} or
116 @code{scm_gc_malloc_pointerless}. These two functions will either
117 return a valid pointer or signal an error. Memory blocks allocated this
118 way can be freed with @code{scm_gc_free}; however, this is not strictly
119 needed: memory allocated with @code{scm_gc_malloc} or
120 @code{scm_gc_malloc_pointerless} is automatically reclaimed when the
121 garbage collector no longer sees any live reference to it@footnote{In
122 Guile up to version 1.8, memory allocated with @code{scm_gc_malloc}
123 @emph{had} to be freed with @code{scm_gc_free}.}.
124
125 Memory allocated with @code{scm_gc_malloc} is scanned for live pointers.
126 This means that if @code{scm_gc_malloc}-allocated memory contains a
127 pointer to some other part of the memory, the garbage collector notices
128 it and prevents it from being reclaimed@footnote{In Guile up to 1.8,
129 memory allocated with @code{scm_gc_malloc} was @emph{not} scanned.
130 Consequently, the GC had to be told explicitly about pointers to live
131 objects contained in the memory block, e.g., @i{via} SMOB mark functions
132 (@pxref{Smobs, @code{scm_set_smob_mark}})}. Conversely, memory
133 allocated with @code{scm_gc_malloc_pointerless} is assumed to be
134 ``pointer-less'' and is not scanned.
135
136 For memory that is not associated with a Scheme object, you can use
137 @code{scm_malloc} instead of @code{malloc}. Like
138 @code{scm_gc_malloc}, it will either return a valid pointer or signal
139 an error. However, it will not assume that the new memory block can
140 be freed by a garbage collection. The memory must be explicitly freed
141 with @code{free}.
142
143 There is also @code{scm_gc_realloc} and @code{scm_realloc}, to be used
144 in place of @code{realloc} when appropriate, and @code{scm_gc_calloc}
145 and @code{scm_calloc}, to be used in place of @code{calloc} when
146 appropriate.
147
148 The function @code{scm_dynwind_free} can be useful when memory should be
149 freed with libc's @code{free} when leaving a dynwind context,
150 @xref{Dynamic Wind}.
151
152 @deftypefn {C Function} {void *} scm_malloc (size_t @var{size})
153 @deftypefnx {C Function} {void *} scm_calloc (size_t @var{size})
154 Allocate @var{size} bytes of memory and return a pointer to it. When
155 @var{size} is 0, return @code{NULL}. When not enough memory is
156 available, signal an error. This function runs the GC to free up some
157 memory when it deems it appropriate.
158
159 The memory is allocated by the libc @code{malloc} function and can be
160 freed with @code{free}. There is no @code{scm_free} function to go
161 with @code{scm_malloc} to make it easier to pass memory back and forth
162 between different modules.
163
164 The function @code{scm_calloc} is similar to @code{scm_malloc}, but
165 initializes the block of memory to zero as well.
166
167 These functions will (indirectly) call
168 @code{scm_gc_register_allocation}.
169 @end deftypefn
170
171 @deftypefn {C Function} {void *} scm_realloc (void *@var{mem}, size_t @var{new_size})
172 Change the size of the memory block at @var{mem} to @var{new_size} and
173 return its new location. When @var{new_size} is 0, this is the same
174 as calling @code{free} on @var{mem} and @code{NULL} is returned. When
175 @var{mem} is @code{NULL}, this function behaves like @code{scm_malloc}
176 and allocates a new block of size @var{new_size}.
177
178 When not enough memory is available, signal an error. This function
179 runs the GC to free up some memory when it deems it appropriate.
180
181 This function will call @code{scm_gc_register_allocation}.
182 @end deftypefn
183
184
185
186
187 @deftypefn {C Function} {void *} scm_gc_malloc (size_t @var{size}, const char *@var{what})
188 @deftypefnx {C Function} {void *} scm_gc_malloc_pointerless (size_t @var{size}, const char *@var{what})
189 @deftypefnx {C Function} {void *} scm_gc_realloc (void *@var{mem}, size_t @var{old_size}, size_t @var{new_size}, const char *@var{what});
190 @deftypefnx {C Function} {void *} scm_gc_calloc (size_t @var{size}, const char *@var{what})
191 Allocate @var{size} bytes of automatically-managed memory. The memory
192 is automatically freed when no longer referenced from any live memory
193 block.
194
195 Memory allocated with @code{scm_gc_malloc} or @code{scm_gc_calloc} is
196 scanned for pointers. Memory allocated by
197 @code{scm_gc_malloc_pointerless} is not scanned.
198
199 The @code{scm_gc_realloc} call preserves the ``pointerlessness'' of the
200 memory area pointed to by @var{mem}. Note that you need to pass the old
201 size of a reallocated memory block as well. See below for a motivation.
202 @end deftypefn
203
204
205 @deftypefn {C Function} void scm_gc_free (void *@var{mem}, size_t @var{size}, const char *@var{what})
206 Explicitly free the memory block pointed to by @var{mem}, which was
207 previously allocated by one of the above @code{scm_gc} functions.
208
209 Note that you need to explicitly pass the @var{size} parameter. This
210 is done since it should normally be easy to provide this parameter
211 (for memory that is associated with GC controlled objects) and help keep
212 the memory management overhead very low. However, in Guile 2.x,
213 @var{size} is always ignored.
214 @end deftypefn
215
216
217 @deftypefn {C Function} void scm_gc_register_allocation (size_t @var{size})
218 Informs the garbage collector that @var{size} bytes have been allocated,
219 which the collector would otherwise not have known about.
220
221 In general, Scheme will decide to collect garbage only after some amount
222 of memory has been allocated. Calling this function will make the
223 Scheme garbage collector know about more allocation, and thus run more
224 often (as appropriate).
225
226 It is especially important to call this function when large unmanaged
227 allocations, like images, may be freed by small Scheme allocations, like
228 SMOBs.
229 @end deftypefn
230
231
232 @deftypefn {C Function} void scm_dynwind_free (void *mem)
233 Equivalent to @code{scm_dynwind_unwind_handler (free, @var{mem},
234 SCM_F_WIND_EXPLICITLY)}. That is, the memory block at @var{mem} will be
235 freed (using @code{free} from the C library) when the current dynwind is
236 left.
237 @end deftypefn
238
239 @deffn {Scheme Procedure} malloc-stats
240 Return an alist ((@var{what} . @var{n}) ...) describing number
241 of malloced objects.
242 @var{what} is the second argument to @code{scm_gc_malloc},
243 @var{n} is the number of objects of that type currently
244 allocated.
245
246 This function is only available if the @code{GUILE_DEBUG_MALLOC}
247 preprocessor macro was defined when Guile was compiled.
248 @end deffn
249
250
251 @subsubsection Upgrading from scm_must_malloc et al.
252
253 Version 1.6 of Guile and earlier did not have the functions from the
254 previous section. In their place, it had the functions
255 @code{scm_must_malloc}, @code{scm_must_realloc} and
256 @code{scm_must_free}. This section explains why we want you to stop
257 using them, and how to do this.
258
259 @findex scm_must_malloc
260 @findex scm_must_realloc
261 @findex scm_must_calloc
262 @findex scm_must_free
263 The functions @code{scm_must_malloc} and @code{scm_must_realloc}
264 behaved like @code{scm_gc_malloc} and @code{scm_gc_realloc} do now,
265 respectively. They would inform the GC about the newly allocated
266 memory via the internal equivalent of
267 @code{scm_gc_register_allocation}. However,
268 @code{scm_must_free} did not unregister the memory it was about to
269 free. The usual way to unregister memory was to return its size from
270 a smob free function.
271
272 This disconnectedness of the actual freeing of memory and reporting
273 this to the GC proved to be bad in practice. It was easy to make
274 mistakes and report the wrong size because allocating and freeing was
275 not done with symmetric code, and because it is cumbersome to compute
276 the total size of nested data structures that were freed with multiple
277 calls to @code{scm_must_free}. Additionally, there was no equivalent
278 to @code{scm_malloc}, and it was tempting to just use
279 @code{scm_must_malloc} and never to tell the GC that the memory has
280 been freed.
281
282 The effect was that the internal statistics kept by the GC drifted out
283 of sync with reality and could even overflow in long running programs.
284 When this happened, the result was a dramatic increase in (senseless)
285 GC activity which would effectively stop the program dead.
286
287 @findex scm_done_malloc
288 @findex scm_done_free
289 The functions @code{scm_done_malloc} and @code{scm_done_free} were
290 introduced to help restore balance to the force, but existing bugs did
291 not magically disappear, of course.
292
293 Therefore we decided to force everybody to review their code by
294 deprecating the existing functions and introducing new ones in their
295 place that are hopefully easier to use correctly.
296
297 For every use of @code{scm_must_malloc} you need to decide whether to
298 use @code{scm_malloc} or @code{scm_gc_malloc} in its place. When the
299 memory block is not part of a smob or some other Scheme object whose
300 lifetime is ultimately managed by the garbage collector, use
301 @code{scm_malloc} and @code{free}. When it is part of a smob, use
302 @code{scm_gc_malloc} and change the smob free function to use
303 @code{scm_gc_free} instead of @code{scm_must_free} or @code{free} and
304 make it return zero.
305
306 The important thing is to always pair @code{scm_malloc} with
307 @code{free}; and to always pair @code{scm_gc_malloc} with
308 @code{scm_gc_free}.
309
310 The same reasoning applies to @code{scm_must_realloc} and
311 @code{scm_realloc} versus @code{scm_gc_realloc}.
312
313
314 @node Weak References
315 @subsection Weak References
316
317 [FIXME: This chapter is based on Mikael Djurfeldt's answer to a
318 question by Michael Livshin. Any mistakes are not theirs, of course. ]
319
320 Weak references let you attach bookkeeping information to data so that
321 the additional information automatically disappears when the original
322 data is no longer in use and gets garbage collected. In a weak key hash,
323 the hash entry for that key disappears as soon as the key is no longer
324 referenced from anywhere else. For weak value hashes, the same happens
325 as soon as the value is no longer in use. Entries in a doubly weak hash
326 disappear when either the key or the value are not used anywhere else
327 anymore.
328
329 Object properties offer the same kind of functionality as weak key
330 hashes in many situations. (@pxref{Object Properties})
331
332 Here's an example (a little bit strained perhaps, but one of the
333 examples is actually used in Guile):
334
335 Assume that you're implementing a debugging system where you want to
336 associate information about filename and position of source code
337 expressions with the expressions themselves.
338
339 Hashtables can be used for that, but if you use ordinary hash tables
340 it will be impossible for the scheme interpreter to "forget" old
341 source when, for example, a file is reloaded.
342
343 To implement the mapping from source code expressions to positional
344 information it is necessary to use weak-key tables since we don't want
345 the expressions to be remembered just because they are in our table.
346
347 To implement a mapping from source file line numbers to source code
348 expressions you would use a weak-value table.
349
350 To implement a mapping from source code expressions to the procedures
351 they constitute a doubly-weak table has to be used.
352
353 @menu
354 * Weak hash tables::
355 * Weak vectors::
356 @end menu
357
358
359 @node Weak hash tables
360 @subsubsection Weak hash tables
361
362 @deffn {Scheme Procedure} make-weak-key-hash-table size
363 @deffnx {Scheme Procedure} make-weak-value-hash-table size
364 @deffnx {Scheme Procedure} make-doubly-weak-hash-table size
365 @deffnx {C Function} scm_make_weak_key_hash_table (size)
366 @deffnx {C Function} scm_make_weak_value_hash_table (size)
367 @deffnx {C Function} scm_make_doubly_weak_hash_table (size)
368 Return a weak hash table with @var{size} buckets. As with any
369 hash table, choosing a good size for the table requires some
370 caution.
371
372 You can modify weak hash tables in exactly the same way you
373 would modify regular hash tables. (@pxref{Hash Tables})
374 @end deffn
375
376 @deffn {Scheme Procedure} weak-key-hash-table? obj
377 @deffnx {Scheme Procedure} weak-value-hash-table? obj
378 @deffnx {Scheme Procedure} doubly-weak-hash-table? obj
379 @deffnx {C Function} scm_weak_key_hash_table_p (obj)
380 @deffnx {C Function} scm_weak_value_hash_table_p (obj)
381 @deffnx {C Function} scm_doubly_weak_hash_table_p (obj)
382 Return @code{#t} if @var{obj} is the specified weak hash
383 table. Note that a doubly weak hash table is neither a weak key
384 nor a weak value hash table.
385 @end deffn
386
387 @node Weak vectors
388 @subsubsection Weak vectors
389
390 Weak vectors are mainly useful in Guile's implementation of weak hash
391 tables.
392
393 @deffn {Scheme Procedure} make-weak-vector size [fill]
394 @deffnx {C Function} scm_make_weak_vector (size, fill)
395 Return a weak vector with @var{size} elements. If the optional
396 argument @var{fill} is given, all entries in the vector will be
397 set to @var{fill}. The default value for @var{fill} is the
398 empty list.
399 @end deffn
400
401 @deffn {Scheme Procedure} weak-vector elem @dots{}
402 @deffnx {Scheme Procedure} list->weak-vector l
403 @deffnx {C Function} scm_weak_vector (l)
404 Construct a weak vector from a list: @code{weak-vector} uses
405 the list of its arguments while @code{list->weak-vector} uses
406 its only argument @var{l} (a list) to construct a weak vector
407 the same way @code{list->vector} would.
408 @end deffn
409
410 @deffn {Scheme Procedure} weak-vector? obj
411 @deffnx {C Function} scm_weak_vector_p (obj)
412 Return @code{#t} if @var{obj} is a weak vector. Note that all
413 weak hashes are also weak vectors.
414 @end deffn
415
416
417 @node Guardians
418 @subsection Guardians
419
420 Guardians provide a way to be notified about objects that would
421 otherwise be collected as garbage. Guarding them prevents the objects
422 from being collected and cleanup actions can be performed on them, for
423 example.
424
425 See R. Kent Dybvig, Carl Bruggeman, and David Eby (1993) "Guardians in
426 a Generation-Based Garbage Collector". ACM SIGPLAN Conference on
427 Programming Language Design and Implementation, June 1993.
428
429 @deffn {Scheme Procedure} make-guardian
430 @deffnx {C Function} scm_make_guardian ()
431 Create a new guardian. A guardian protects a set of objects from
432 garbage collection, allowing a program to apply cleanup or other
433 actions.
434
435 @code{make-guardian} returns a procedure representing the guardian.
436 Calling the guardian procedure with an argument adds the argument to
437 the guardian's set of protected objects. Calling the guardian
438 procedure without an argument returns one of the protected objects
439 which are ready for garbage collection, or @code{#f} if no such object
440 is available. Objects which are returned in this way are removed from
441 the guardian.
442
443 You can put a single object into a guardian more than once and you can
444 put a single object into more than one guardian. The object will then
445 be returned multiple times by the guardian procedures.
446
447 An object is eligible to be returned from a guardian when it is no
448 longer referenced from outside any guardian.
449
450 There is no guarantee about the order in which objects are returned
451 from a guardian. If you want to impose an order on finalization
452 actions, for example, you can do that by keeping objects alive in some
453 global data structure until they are no longer needed for finalizing
454 other objects.
455
456 Being an element in a weak vector, a key in a hash table with weak
457 keys, or a value in a hash table with weak values does not prevent an
458 object from being returned by a guardian. But as long as an object
459 can be returned from a guardian it will not be removed from such a
460 weak vector or hash table. In other words, a weak link does not
461 prevent an object from being considered collectable, but being inside
462 a guardian prevents a weak link from being broken.
463
464 A key in a weak key hash table can be thought of as having a strong
465 reference to its associated value as long as the key is accessible.
466 Consequently, when the key is only accessible from within a guardian,
467 the reference from the key to the value is also considered to be
468 coming from within a guardian. Thus, if there is no other reference
469 to the value, it is eligible to be returned from a guardian.
470 @end deffn
471
472
473 @c Local Variables:
474 @c TeX-master: "guile.texi"
475 @c End: