Initialize cell contents with a pattern to detect corruption
[software/dgc/naive.git] / gc / gc.d
1 /**
2  * Naive Garbage Collector implementation.
3  *
4  * This module implements a Naive Garbage Collector. The idea behind this
5  * implementation is to document all the bookkeeping and considerations that
6  * have to be taken in order to implement a garbage collector for D.
7  *
8  * The garbage collector algorithm itself is extremely simple to make it
9  * easier to focus on the specifics of D. A completely naive mark and sweep
10  * algorithm is used, with a recursive mark phase. The code is extremely
11  * inefficient in order to keep it clean, and easy to read and understand.
12  *
13  * The implementation is split in several modules to ease the reading even
14  * more. All architecture/compiler specific code is done in the arch module,
15  * in order to avoid confusing version statements all over the places. The
16  * cell module has all the code related to the memory cells header. dynarray
17  * is another support module which holds the implementation of a simple
18  * dynamic array used to store root pointers and ranges. The list module holds
19  * a simple singly linked list (of cells) implementation to store the live and
20  * free lists. Finally, the iface module is the one with the C interface to
21  * comply with the Tango/Druntime GC specification.
22  *
23  * Copyright: Public Domain
24  * License:   Public Domain
25  * Authors:   Leandro Lucarella <llucax@gmail.com>
26  */
27
28 module gc.gc;
29
30 private:
31
32 // Internal imports
33 import gc.cell: Cell, BlkAttr, op_apply_ptr_range;
34 import gc.list: List;
35 import gc.dynarray: DynArray;
36 import gc.arch: push_registers, pop_registers;
37
38 // Standard imports
39 import cstring = tango.stdc.string;
40 import cstdlib = tango.stdc.stdlib;
41
42 // Debug imports
43
44 /*
45  * These are external functions coming from the D/Tango runtime. It's pretty
46  * intuitive what they do based on their names, for more details please
47  * refer to the functions documentation.
48  */
49 alias void delegate(void*, void*) mark_function;
50 extern (C) void onOutOfMemoryError();
51 extern (C) void rt_finalize(void* p, bool det=true);
52 extern (C) void rt_scanStaticData(mark_function mark);
53 extern (C) void thread_init();
54 extern (C) bool thread_needLock();
55 extern (C) void thread_suspendAll();
56 extern (C) void thread_resumeAll();
57 extern (C) void thread_scanAll(mark_function mark, void* stack_top=null);
58
59 /**
60  * A range of memory that should be scanned for pointers.
61  *
62  * This object is iterable, yielding a pointer (void*) for each iteration.
63  */
64 struct RootRange
65 {
66
67     /// Beginning of the memory range
68     void* from;
69
70     /// End of the memory range
71     void* to;
72
73     /// Iterate over a memory range applying dg to its elements
74     int opApply(int delegate(ref void*) dg)
75     {
76         return op_apply_ptr_range(this.from, this.to, dg);
77     }
78
79 }
80
81
82 package:
83
84
85 /**
86  * Information on a block of memory.
87  *
88  * This is part of the GC specification, it's used for the query() method.
89  *
90  * Standards: Tango/Druntime specs
91  */
92 struct BlkInfo
93 {
94
95     /// Base address of the block
96     void* base;
97
98     /// Size of the block (this is the total capacity, not the requested size)
99     size_t size;
100
101     /**
102      * Memory block attributes
103      *
104      * See_Also: cell.BlkAttr for possible values
105      */
106     uint attr;
107
108 }
109
110
111 /**
112  * GC implementation.
113  *
114  * This object contains the whole GC implementation. This is instantiated in
115  * the iface module as a global variable to provide the GC services.
116  *
117  * This implementation is designed to be extremely simple. The algorithm
118  * implemented is the most basic stop-the-world mark-sweep known.
119  *
120  * Memory is organized in cells. Each cell has a header where all the
121  * bookkeeping information is stored (like the mark bit, cell attributes,
122  * capacity, etc.), and the memory allocated for the requested memory itself.
123  *
124  * Two lists of cells are kept: free list and live list.
125  *
126  * The free list store cells known not to be referenced by the program. The
127  * live list stores cells that were referenced by the program at the end of
128  * the last collection (and just allocated cells).
129  *
130  * The root set is composed by several elements:
131  *
132  * $(UL
133  *      $(LI Static data)
134  *      $(LI Threads stack)
135  *      $(LI Registers)
136  *      $(LI Root pointers)
137  *      $(LI Root ranges)
138  * )
139  *
140  * Root pointers and ranges are user-defined.
141  *
142  * See_Also:
143  *
144  *  $(UL
145  *      $(LI cell.Cell for the cell header layout)
146  *      $(LI collect() for the main collection algorithm)
147  *      $(LI )
148  * )
149  *
150  */
151 struct GC
152 {
153
154 private:
155
156     /// List of free cells.
157     List free_list;
158
159     /// List of live cells.
160     List live_list;
161
162     /// Single root pointers.
163     DynArray!(void*) root_pointers;
164
165     /// Root ranges.
166     DynArray!(RootRange) root_ranges;
167
168     /**
169      * "Flag" to indicate when the GC is disabled.
170      *
171      * This is a number because calls to enable() and disable() can be
172      * recursive. The number of calls to enable() should match the number of
173      * calls to disable(), though, if you want the GC to be effectively
174      * enabled again.
175      */
176     uint disabled = 0;
177
178     /**
179      * Remove the mark bit to all the live cells.
180      *
181      * This is done before starting the mark phase.
182      *
183      * See_Also:
184      *
185      *  $(UL
186      *      $(LI collect() for the main collect algorithm)
187      *      $(LI mark_all() for details on the marking phase)
188      *  )
189      */
190     void unmark()
191     {
192         foreach (cell; this.live_list)
193             cell.marked = false;
194     }
195
196     /**
197      * Mark all live data (pausing all threads)
198      *
199      * This methods start marking following all the known roots:
200      *
201      *  $(UL
202      *      $(LI Static data)
203      *      $(LI Threads stack)
204      *      $(LI Registers)
205      *      $(LI Root pointers)
206      *      $(LI Root ranges)
207      *  )
208      *
209      * Note that the registers are pushed into the stack to get scanned.
210      *
211      * This is the complete mark phase. The algorithm roughly does:
212      *
213      *  $(OL
214      *      $(LI Push registers into the stack)
215      *      $(LI Pause all threads (but the current one, of course))
216      *      $(LI Scan the static data)
217      *      $(LI Scan all threads stack)
218      *      $(LI Scan the root pointers and ranges)
219      *      $(LI Resume all threads)
220      *      $(LI Pop the registers from the stack)
221      *  )
222      *
223      *
224      * See_Also:
225      *
226      *  $(UL
227      *      $(LI collect() for the main collect algorithm)
228      *      $(LI mark() for details on the marking algorithm)
229      *      $(LI sweep() for details on the sweep phase)
230      *  )
231      */
232     void mark_all()
233     {
234         void* stack_top;
235         mixin (push_registers("stack_top"));
236         thread_suspendAll();
237         rt_scanStaticData(&mark_range);
238         thread_scanAll(&mark_range, stack_top);
239         foreach (ptr; this.root_pointers) {
240             this.mark(ptr);
241         }
242         foreach (range; this.root_ranges) {
243             this.mark_range(range.from, range.to);
244         }
245         thread_resumeAll();
246         mixin (pop_registers("stack_top"));
247     }
248
249     /**
250      * Wrapper for mark() over a range, needed by some runtime functions.
251      *
252      * This function is used as a delegate to be passed to rt_scanStaticData()
253      * and thread_scanAll(), because they expect a function taking 2 pointers.
254      *
255      * This extremely inefficient on purpose. The goal of this implementation
256      * is simplicity, nor performance.
257      *
258      * See_Also:
259      *  $(UL
260      *      $(LI mark() for details on the marking algorithm)
261      *  )
262      */
263     void mark_range(void* from, void* to)
264     {
265         foreach (ptr; RootRange(from, to))
266             mark(ptr);
267     }
268
269     /**
270      * Mark all cells accessible from a pointer.
271      *
272      * This is the mark algorithm itself. It's recursive and dumb as a log. No
273      * care is taken in regards to stack overflows. This is the first example
274      * in text books.
275      *
276      * Marking is done with all threads stopped.
277      *
278      * See_Also:
279      *  $(UL
280      *      $(LI collect() for the main collect algorithm)
281      *      $(LI mark_all() for details on the marking phase)
282      *      $(LI sweep() for details on the sweep phase)
283      *  )
284      */
285     void mark(void* ptr)
286     {
287         Cell* cell = Cell.from_ptr(this.addrOf(ptr));
288         if (cell is null)
289             return;
290         if (!cell.marked) {
291             cell.marked = true;
292             if (cell.has_pointers) {
293                 foreach (ptr; *cell)
294                     mark(ptr);
295             }
296         }
297     }
298
299     /**
300      * Move unreferenced live objects to the free list (calling finalizers).
301      *
302      * This is the sweep phase. It's very simple, it just searches the live
303      * list and move unmarked cells to the free list. This function is in
304      * charge of calling finalizers too, through the rt_finalize() runtime
305      * function.
306      *
307      * Sweeping is done concurrently with the mutator threads.
308      *
309      * See_Also:
310      *  $(UL
311      *      $(LI collect() for the main collect algorithm)
312      *      $(LI mark_all() for details on the marking phase)
313      *  )
314      */
315     void sweep()
316     {
317         foreach (cell; this.live_list) {
318             if (!cell.marked) {
319                 this.live_list.unlink(cell);
320                 if (cell.has_finalizer)
321                     rt_finalize(cell.ptr, false);
322                 // Set the pattern to detect corruption
323                 cstring.memset(cell.ptr, 0xca, cell.capacity);
324                 this.free_list.link(cell);
325             }
326         }
327     }
328
329
330 public:
331
332     /**
333      * Initialize the GC.
334      *
335      * This initializes the thread library too, as requested by the
336      * Tango/Druntime specs.
337      */
338     void init()
339     {
340         this.disabled = 0;
341         thread_init();
342     }
343
344     /**
345      * Terminate the GC.
346      *
347      * Finalization of unreferenced cells is not mandatory by the specs.
348      * This implementation guarantees that all finalizers are called, at least
349      * at program exit (i.e. at GC termination).
350      *
351      * The specs says that "objects referenced from the data segment never get
352      * collected by the GC". While this is true for this implementation,
353      * finalizers are called for objects referenced from the data segment at
354      * program exit.
355      *
356      * There could be some problems with this, in very strange situations. For
357      * a more complete discussion about the topic please take a look at the
358      * bug 2858: http://d.puremagic.com/issues/show_bug.cgi?id=2858
359      */
360     void term()
361     {
362         foreach (cell; this.live_list)
363             if (cell.has_finalizer)
364                 rt_finalize(cell.ptr, false);
365         // Let the OS free the memory on exit.
366     }
367
368     /**
369      * Enable the GC.
370      *
371      * When the GC is enabled, a collection is triggered when malloc() can't
372      * find room in the free list to fulfill the requested size.
373      *
374      * enable() and disable() can be called recursively. The number of calls
375      * to enable() should match the number of calls to disable(), though, if
376      * you want the GC to be effectively enabled again.
377      *
378      * See_Also: disable()
379      */
380     void enable()
381     {
382         assert (this.disabled > 0);
383         this.disabled--;
384     }
385
386     /**
387      * Disable the GC.
388      *
389      * See_Also: enable()
390      */
391     void disable()
392     {
393         this.disabled++;
394         assert (this.disabled > 0);
395     }
396
397     /**
398      * Run a GC collection in order to find unreferenced objects.
399      *
400      * This is the simplest stop-the-world mark-sweep algorithm ever. It first
401      * removes the mark bit from all the live cells, then it marks the cells
402      * that are reachable through the root set (static data, stack, registers
403      * and custom root), and finally sweeps the live list looking for unmarked
404      * cells to free.
405      *
406      * The world is stopped only for the mark phase.
407      *
408      * See_Also:
409      *  $(UL
410      *      $(LI mark_all() for details on the marking phase)
411      *      $(LI sweep() for details on the sweep phase)
412      *  )
413      */
414     void collect()
415     {
416         this.unmark();
417         this.mark_all();
418         this.sweep();
419     }
420
421     /**
422      * Minimize free space usage.
423      *
424      * This method returns to the OS memory that is not longer used by
425      * the program. Usually calling this method manually is not
426      * necessary, because unused cells are recycled for future
427      * allocations. But if there is some small part of the program that
428      * requires a lot of memory and it's known that it won't be used
429      * further, calling this can reduce the memory footprint of the program
430      * considerably (at the expense of some performance lost in future
431      * allocations).
432      *
433      * This implementation just return to the OS all the cells in the free
434      * list.
435      */
436     void minimize()
437     {
438         foreach (cell; this.free_list) {
439             this.free_list.unlink(cell);
440             Cell.free(cell);
441         }
442     }
443
444     /**
445      * Get attributes associated to the cell pointed by ptr.
446      *
447      * Attributes is a bitmap that can have these values:
448      *
449      *  $(UL
450      *      $(LI 1: The object stored in the cell has to be finalized)
451      *      $(LI 2: The cell should not be scanned for pointers)
452      *      $(LI 4: The cell should not be moved during a collection
453      *           (unimplemented))
454      *  )
455      *
456      * See_Also: cell.BlkAttr, setAttr(), clrAttr()
457      */
458     uint getAttr(void* ptr)
459     {
460         auto cell = this.live_list.find(ptr);
461         if (cell !is null)
462             return cell.attr;
463         return 0;
464     }
465
466     /**
467      * Set the attributes of the cell pointed by ptr.
468      *
469      * All bits present in attr are set, other bits are untouched. The old
470      * attributes are returned.
471      *
472      * See_Also: cell.BlkAttr, getAttr(), clrAttr()
473      */
474     uint setAttr(void* ptr, uint attr)
475     {
476         auto cell = this.live_list.find(ptr);
477         if (cell !is null) {
478             auto old = cell.attr;
479             cell.attr |= attr;
480             return cell.attr;
481         }
482         return 0;
483     }
484
485     /**
486      * Clear the attributes of the cell pointed by ptr.
487      *
488      * All bits present in attr are cleared, other bits are untouched. The old
489      * attributes are returned.
490      *
491      * See_Also: cell.BlkAttr, getAttr(), setAttr()
492      */
493     uint clrAttr(void* ptr, uint attr)
494     {
495         auto cell = this.live_list.find(ptr);
496         if (cell !is null) {
497             auto old = cell.attr;
498             cell.attr &= ~attr;
499             return cell.attr;
500         }
501         return 0;
502     }
503
504     /**
505      * Allocate memory.
506      *
507      * This is the main allocator of the GC. The algorithm is really
508      * simple. It does a first-fit search in the free list, if no free cell is
509      * found with enough room, it runs a collection and retry (unless the GC
510      * is disabled). If there is no room still, it uses C malloc to allocate
511      * a new cell. If all that fails, then onOutOfMemoryError() runtime
512      * function is called to handle the error.
513      *
514      * attr are the attributes to associate to the new cell (see getAttr() for
515      * details).
516      */
517     void* malloc(size_t size, uint attr=0)
518     {
519         if (size == 0)
520             return null;
521
522         // Find a free cell in the free list with enough space
523         auto cell = this.free_list.pop(size);
524         if (cell !is null)
525             goto reuse;
526
527         // No room in the free list found, if the GC is enabled, trigger
528         // a collection and try again
529         if (!this.disabled) {
530             this.collect();
531             cell = this.free_list.pop(size);
532             if (cell !is null)
533                 goto reuse;
534         }
535
536         // No luck still, allocate a new cell
537         cell = Cell.alloc(size, attr);
538         if (cell !is null)
539             goto link;
540
541         // No memory
542         onOutOfMemoryError();
543
544         return null;
545
546     reuse:
547         // Check the pattern to detect corruption
548         for (size_t i = 0; i < cell.capacity; ++i)
549             if ((cast(ubyte*) cell.ptr)[i] != 0xca)
550                 cstdlib.abort();
551         cell.size = size;
552         cell.attr = cast(BlkAttr) attr;
553
554     link:
555         this.live_list.link(cell);
556
557         return cell.ptr;
558     }
559
560     /**
561      * Allocate memory (set memory to zero).
562      *
563      * Same as malloc() but set the allocated memory cell to zero.
564      */
565     void* calloc(size_t size, uint attr=0)
566     {
567         if (size == 0)
568             return null;
569
570         void* ptr = this.malloc(size, attr);
571
572         if (ptr !is null) // in case onOutOfMemoryError didn't throw
573             cstring.memset(ptr, 0, size);
574
575         return ptr;
576     }
577
578     /**
579      * Reallocate memory.
580      *
581      * This implementation is very simple, if size less or equals than the
582      * cells capacity, the cell's size is changed and the same address is
583      * returned. Otherwise a new cell is allocated using malloc() (this can
584      * trigger a collection), the contents are moved and the old cell is freed.
585      *
586      * attr has the same meaning as in malloc().
587      */
588     void* realloc(void* ptr, size_t size, uint attr=0)
589     {
590
591         // Undercover malloc()
592         if (ptr is null)
593             return this.malloc(size, attr);
594
595         // Undercover free()
596         if (size == 0) {
597             this.free(ptr);
598             return null;
599         }
600
601         auto cell = this.live_list.find(ptr);
602         assert (cell !is null);
603
604         // We have enough capacity already, just change the size
605         if (cell.capacity >= size) {
606             cell.size = size;
607             return cell.ptr;
608         }
609
610         // We need to move the cell because of the lack of capacity, find
611         // a free cell with the requested capacity (at least)
612         ptr = this.malloc(size, attr);
613         if (ptr is null) // in case onOutOfMemoryError didn't throw
614             return null;
615         Cell* new_cell = Cell.from_ptr(ptr);
616         assert (new_cell !is null);
617
618         // Move cell attributes and contents
619         new_cell.attr = cell.attr;
620         cstring.memcpy(new_cell.ptr, cell.ptr, cell.size);
621
622         // Free the old cell
623         this.free(cell);
624
625         return new_cell.ptr;
626     }
627
628     /**
629      * Attempt to in-place enlarge a memory block pointed to by ptr.
630      *
631      * The memory should be enlarged to at least min_size beyond its current
632      * capacity, up to a maximum of max_size. This does not attempt to move
633      * the memory block (like realloc() does).
634      *
635      * Returns:
636      *  0 if could not extend ptr, total size of entire memory block if
637      *  successful.
638      */
639     size_t extend(void* ptr, size_t min_size, size_t max_size)
640     {
641         assert (min_size <= max_size);
642         // There is no possible extension of the capacity for this
643         // implementation.
644         return 0;
645     }
646
647     /**
648      * Reserve memory to anticipate memory allocations.
649      *
650      * This implementation is really dumb, a single cell is allocated with
651      * size bytes. If 2 malloc()s follow a call to reserve(size), requesting
652      * size/2 bytes each, one allocation will still be done (and half the
653      * memory of the first malloc will be wasted =). Since this is a trivial
654      * implementation, we don't care about this.
655      *
656      * The actual number of bytes reserved are returned, or 0 on error.
657      */
658     size_t reserve(size_t size)
659     {
660         assert (size > 0);
661         auto cell = Cell.alloc(size);
662         if (cell is null)
663             return 0;
664         // Set the pattern to detect corruption
665         cstring.memset(cell.ptr, 0xca, cell.capacity);
666         this.free_list.link(cell);
667         return cell.capacity;
668     }
669
670     /**
671      * Free unused memory.
672      *
673      * This method tells the GC that a cell is not longer used. The GC doesn't
674      * perform any connectivity check, if the cell was referenced by others,
675      * nasty things will happen (much like C/C++).
676      *
677      * Note that finalizers are not called by this method. Finalizers are
678      * called by the runtime when the delete operator is used, and the delete
679      * operator calls this method through the runtime.
680      */
681     void free(void* ptr)
682     {
683         if (ptr is null)
684             return;
685
686         auto cell = this.live_list.pop(ptr);
687         assert (cell !is null);
688
689         this.free_list.link(cell);
690     }
691
692     /**
693      * Get the base address of an interior pointer into the GC heap.
694      *
695      * If ptr is not pointing into the GC heap null is returned.
696      */
697     void* addrOf(void* ptr)
698     {
699         if (ptr is null)
700             return null;
701
702         bool in_range(Cell* cell)
703         {
704             return ptr >= cell.ptr && ptr < (cell.ptr + cell.size);
705         }
706
707         auto cell = this.live_list.find(&in_range);
708         if (cell !is null)
709             return cell.ptr;
710
711         return null;
712     }
713
714     /**
715      * Return the real size (capacity) for the cell pointed to by ptr.
716      *
717      * ptr should be the base address of a heap allocated object, interior
718      * pointers are not supported (use addrOf() if you have an interior
719      * pointer). If this is not true, this method returns 0.
720      *
721      * realloc(ptr, sizeOf(ptr), attr) is guaranteed not to allocate/move
722      * memory.
723      */
724     size_t sizeOf(void* ptr)
725     {
726         auto cell = this.live_list.find(ptr);
727         if (cell !is null)
728             return cell.capacity;
729         return 0;
730     }
731
732     /**
733      * Get information about the cell pointed to by ptr.
734      *
735      * ptr should be the base address of a heap allocated object, interior
736      * pointers are not supported (use addrOf() if you have an interior
737      * pointer). If this is not true, this method returns BlkInfo.init.
738      *
739      * See BlkInfo for the information provided by this method.
740      */
741     BlkInfo query(void* ptr)
742     {
743         BlkInfo blk_info;
744
745         auto cell = this.live_list.find(ptr);
746         if (cell !is null) {
747             blk_info.base = cell.ptr;
748             blk_info.size = cell.capacity;
749             blk_info.attr = cell.attr;
750         }
751
752         return blk_info;
753     }
754
755     /**
756      * Add a root pointer to the root set.
757      *
758      * This method can be used to register new root to the GC heap. This is
759      * only needed when the user has custom memory that has pointers into the
760      * GC heap (for example for interfacing with C programs, which allocates
761      * memory using malloc() directly).
762      *
763      * See_Also: removeRoot(), addRange(), removeRange()
764      */
765     void addRoot(void* ptr)
766     {
767         this.root_pointers.append(ptr);
768     }
769
770     /**
771      * Add a root range to the root set.
772      *
773      * This method can be used to register new root range (a memory chunk
774      * that should be scanned for pointers into the GC heap). This is
775      * only needed when the user has custom memory that has pointers into the
776      * GC heap (for example for interfacing with C programs, which allocates
777      * memory using malloc() directly).
778      *
779      * Pointers will be scanned assuming they are aligned.
780      *
781      * See_Also: removeRange(), addRoot(), removeRoot()
782      */
783     void addRange(void* ptr, size_t size)
784     {
785         this.root_ranges.append(RootRange(ptr, ptr + size));
786     }
787
788     /**
789      * Remove a root pointer from the root set.
790      *
791      * ptr has to be previously registered using addRoot(), otherwise the
792      * results are undefined.
793      *
794      * See_Also: addRoot(), addRange(), removeRange()
795      */
796     void removeRoot(void* ptr)
797     {
798         this.root_pointers.remove(ptr);
799     }
800
801     /**
802      * Remove a root range from the root set.
803      *
804      * ptr has to be previously registered using addRange(), otherwise the
805      * results are undefined.
806      *
807      * See_Also: addRange(), addRoot(), removeRoot()
808      */
809     void removeRange(void* ptr)
810     {
811         this.root_ranges.remove_if((ref RootRange range) {
812                     return range.from is ptr;
813                 });
814     }
815
816 } // struct GC
817
818 // vim: set et sw=4 sts=4 :