2 * This module provides an interface to the garbage collector used by
3 * applications written in the D programming language. It allows the
4 * garbage collector in the runtime to be swapped without affecting
5 * binary compatibility of applications.
7 * Using this module is not necessary in typical D code. It is mostly
8 * useful when doing low-level _memory management.
13 $(LI The GC is a conservative mark-and-sweep collector. It only runs a
14 collection cycle when an allocation is requested of it, never
15 otherwise. Hence, if the program is not doing allocations,
16 there will be no GC collection pauses. The pauses occur because
17 all threads the GC knows about are halted so the threads' stacks
18 and registers can be scanned for references to GC allocated data.
21 $(LI The GC does not know about threads that were created by directly calling
22 the OS/C runtime thread creation APIs and D threads that were detached
23 from the D runtime after creation.
24 Such threads will not be paused for a GC collection, and the GC might not detect
25 references to GC allocated data held by them. This can cause memory corruption.
26 There are several ways to resolve this issue:
28 $(LI Do not hold references to GC allocated data in such threads.)
29 $(LI Register/unregister such data with calls to $(LREF addRoot)/$(LREF removeRoot) and
30 $(LREF addRange)/$(LREF removeRange).)
31 $(LI Maintain another reference to that same data in another thread that the
33 $(LI Disable GC collection cycles while that thread is active with $(LREF disable)/$(LREF enable).)
34 $(LI Register the thread with the GC using $(REF thread_attachThis, core,thread)/$(REF thread_detachThis, core,thread).)
39 * Notes_to_implementors:
41 * $(LI On POSIX systems, the signals SIGUSR1 and SIGUSR2 are reserved
42 * by this module for use in the garbage collector implementation.
43 * Typically, they will be used to stop and resume other threads
44 * when performing a collection, but an implementation may choose
45 * not to use this mechanism (or not stop the world at all, in the
46 * case of concurrent garbage collectors).)
48 * $(LI Registers, the stack, and any other _memory locations added through
49 * the $(D GC.$(LREF addRange)) function are always scanned conservatively.
50 * This means that even if a variable is e.g. of type $(D float),
51 * it will still be scanned for possible GC pointers. And, if the
52 * word-interpreted representation of the variable matches a GC-managed
53 * _memory block's address, that _memory block is considered live.)
55 * $(LI Implementations are free to scan the non-root heap in a precise
56 * manner, so that fields of types like $(D float) will not be considered
57 * relevant when scanning the heap. Thus, casting a GC pointer to an
58 * integral type (e.g. $(D size_t)) and storing it in a field of that
59 * type inside the GC heap may mean that it will not be recognized
60 * if the _memory block was allocated with precise type info or with
61 * the $(D GC.BlkAttr.$(LREF NO_SCAN)) attribute.)
63 * $(LI Destructors will always be executed while other threads are
64 * active; that is, an implementation that stops the world must not
65 * execute destructors until the world has been resumed.)
67 * $(LI A destructor of an object must not access object references
68 * within the object. This means that an implementation is free to
69 * optimize based on this rule.)
71 * $(LI An implementation is free to perform heap compaction and copying
72 * so long as no valid GC pointers are invalidated in the process.
73 * However, _memory allocated with $(D GC.BlkAttr.$(LREF NO_MOVE)) must
74 * not be moved/copied.)
76 * $(LI Implementations must support interior pointers. That is, if the
77 * only reference to a GC-managed _memory block points into the
78 * middle of the block rather than the beginning (for example), the
79 * GC must consider the _memory block live. The exception to this
80 * rule is when a _memory block is allocated with the
81 * $(D GC.BlkAttr.$(LREF NO_INTERIOR)) attribute; it is the user's
82 * responsibility to make sure such _memory blocks have a proper pointer
83 * to them when they should be considered live.)
85 * $(LI It is acceptable for an implementation to store bit flags into
86 * pointer values and GC-managed _memory blocks, so long as such a
87 * trick is not visible to the application. In practice, this means
88 * that only a stop-the-world collector can do this.)
90 * $(LI Implementations are free to assume that GC pointers are only
91 * stored on word boundaries. Unaligned pointers may be ignored
94 * $(LI Implementations are free to run collections at any point. It is,
95 * however, recommendable to only do so when an allocation attempt
96 * happens and there is insufficient _memory available.)
99 * Copyright: Copyright Sean Kelly 2005 - 2015.
100 * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
101 * Authors: Sean Kelly, Alex Rønne Petersen
102 * Source: $(DRUNTIMESRC core/_memory.d)
109 else version (AArch64)
113 version = iOSDerived;
115 version = iOSDerived;
116 else version (WatchOS)
117 version = iOSDerived;
121 extern (C) uint gc_getAttr( void* p ) pure nothrow;
122 extern (C) uint gc_setAttr( void* p, uint a ) pure nothrow;
123 extern (C) uint gc_clrAttr( void* p, uint a ) pure nothrow;
125 extern (C) void* gc_addrOf( void* p ) pure nothrow @nogc;
126 extern (C) size_t gc_sizeOf( void* p ) pure nothrow @nogc;
135 extern (C) BlkInfo_ gc_query(return scope void* p) pure nothrow;
136 extern (C) GC.Stats gc_stats ( ) nothrow @nogc;
137 extern (C) GC.ProfileStats gc_profileStats ( ) nothrow @nogc @safe;
143 * The minimum size of a system page in bytes.
145 * This is a compile time, platform specific value. This value might not
146 * be accurate, since it might be possible to change this value. Whenever
147 * possible, please use $(LREF pageSize) instead, which is initialized
150 * The minimum size is useful when the context requires a compile time known
151 * value, like the size of a static array: `ubyte[minimumPageSize] buffer`.
153 enum minimumPageSize : size_t;
155 else version (AnyARM)
158 enum size_t minimumPageSize = 16384;
160 enum size_t minimumPageSize = 4096;
163 enum size_t minimumPageSize = 4096;
168 ubyte[minimumPageSize] buffer;
172 * The size of a system page in bytes.
174 * This value is set at startup time of the application. It's safe to use
175 * early in the start process, like in shared module constructors and
176 * initialization of the D runtime itself.
178 immutable size_t pageSize;
183 ubyte[] buffer = new ubyte[pageSize];
186 // The reason for this elaborated way of declaring a function is:
188 // * `pragma(crt_constructor)` is used to declare a constructor that is called by
189 // the C runtime, before C main. This allows the `pageSize` value to be used
190 // during initialization of the D runtime. This also avoids any issues with
191 // static module constructors and circular references.
193 // * `pragma(mangle)` is used because `pragma(crt_constructor)` requires a
194 // function with C linkage. To avoid any name conflict with other C symbols,
195 // standard D mangling is used.
197 // * The extra function declaration, without the body, is to be able to get the
198 // D mangling of the function without the need to hardcode the value.
200 // * The extern function declaration also has the side effect of making it
201 // impossible to manually call the function with standard syntax. This is to
202 // make it more difficult to call the function again, manually.
203 private void initialize();
204 pragma(crt_constructor)
205 pragma(mangle, `_D` ~ initialize.mangleof)
206 private extern (C) void initialize() @system
210 import core.sys.posix.unistd : sysconf, _SC_PAGESIZE;
212 (cast() pageSize) = cast(size_t) sysconf(_SC_PAGESIZE);
214 else version (Windows)
216 import core.sys.windows.winbase : GetSystemInfo, SYSTEM_INFO;
220 (cast() pageSize) = cast(size_t) si.dwPageSize;
223 static assert(false, __FUNCTION__ ~ " is not implemented on this platform");
227 * This struct encapsulates all garbage collection functionality for the D
228 * programming language.
235 * Aggregation of GC stats to be exposed via public API
239 /// number of used bytes on the GC heap (might only get updated after a collection)
241 /// number of free bytes on the GC heap (might only get updated after a collection)
243 /// number of bytes allocated for current thread since program start
244 ulong allocatedInCurrentThread;
248 * Aggregation of current profile information
250 static struct ProfileStats
252 import core.time : Duration;
253 /// total number of GC cycles
254 size_t numCollections;
255 /// total time spent doing GC
256 Duration totalCollectionTime;
257 /// total time threads were paused doing GC
258 Duration totalPauseTime;
259 /// largest time threads were paused during one GC cycle
260 Duration maxPauseTime;
261 /// largest time spent doing one GC cycle
262 Duration maxCollectionTime;
268 * Enables automatic garbage collection behavior if collections have
269 * previously been suspended by a call to disable. This function is
270 * reentrant, and must be called once for every call to disable before
271 * automatic collections are enabled.
273 pragma(mangle, "gc_enable") static void enable() nothrow; /* FIXME pure */
277 * Disables automatic garbage collections performed to minimize the
278 * process footprint. Collections may continue to occur in instances
279 * where the implementation deems necessary for correct program behavior,
280 * such as during an out of memory condition. This function is reentrant,
281 * but enable must be called once for each call to disable.
283 pragma(mangle, "gc_disable") static void disable() nothrow; /* FIXME pure */
287 * Begins a full collection. While the meaning of this may change based
288 * on the garbage collector implementation, typical behavior is to scan
289 * all stack segments for roots, mark accessible memory blocks as alive,
290 * and then to reclaim free space. This action may need to suspend all
291 * running threads for at least part of the collection process.
293 pragma(mangle, "gc_collect") static void collect() nothrow; /* FIXME pure */
296 * Indicates that the managed memory space be minimized by returning free
297 * physical memory to the operating system. The amount of free memory
298 * returned depends on the allocator design and on program behavior.
300 pragma(mangle, "gc_minimize") static void minimize() nothrow; /* FIXME pure */
305 * Elements for a bit field representing memory block attributes. These
306 * are manipulated via the getAttr, setAttr, clrAttr functions.
310 NONE = 0b0000_0000, /// No attributes set.
311 FINALIZE = 0b0000_0001, /// Finalize the data in this block on collect.
312 NO_SCAN = 0b0000_0010, /// Do not scan through this block on collect.
313 NO_MOVE = 0b0000_0100, /// Do not move this memory block on collect.
315 This block contains the info to allow appending.
317 This can be used to manually allocate arrays. Initial slice size is 0.
319 Note: The slice's usable size will not match the block size. Use
320 $(LREF capacity) to retrieve actual usable capacity.
324 // Allocate the underlying array.
325 int* pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE);
326 // Bind a slice. Check the slice has capacity information.
327 int[] slice = pToArray[0 .. 0];
328 assert(capacity(slice) > 0);
329 // Appending to the slice will not relocate it.
332 assert(slice.ptr == p);
335 APPENDABLE = 0b0000_1000,
338 This block is guaranteed to have a pointer to its base while it is
339 alive. Interior pointers can be safely ignored. This attribute is
340 useful for eliminating false pointers in very large data structures
341 and is only implemented for data structures at least a page in size.
343 NO_INTERIOR = 0b0001_0000,
345 STRUCTFINAL = 0b0010_0000, // the block has a finalizer for (an array of) structs
350 * Contains aggregate information about a block of managed memory. The
351 * purpose of this struct is to support a more efficient query style in
352 * instances where detailed information is needed.
354 * base = A pointer to the base of the block in question.
355 * size = The size of the block, calculated from base.
356 * attr = Attribute bits set on the memory block.
358 alias BlkInfo = BlkInfo_;
362 * Returns a bit field representing all block attributes set for the memory
363 * referenced by p. If p references memory not originally allocated by
364 * this garbage collector, points to the interior of a memory block, or if
365 * p is null, zero will be returned.
368 * p = A pointer to the root of a valid memory block or to null.
371 * A bit field containing any bits set for the memory block referenced by
372 * p or zero on error.
374 static uint getAttr( const scope void* p ) nothrow
376 return gc_getAttr(cast(void*) p);
381 static uint getAttr(void* p) pure nothrow
383 return gc_getAttr( p );
388 * Sets the specified bits for the memory references by p. If p references
389 * memory not originally allocated by this garbage collector, points to the
390 * interior of a memory block, or if p is null, no action will be
394 * p = A pointer to the root of a valid memory block or to null.
395 * a = A bit field containing any bits to set for this memory block.
398 * The result of a call to getAttr after the specified bits have been
401 static uint setAttr( const scope void* p, uint a ) nothrow
403 return gc_setAttr(cast(void*) p, a);
408 static uint setAttr(void* p, uint a) pure nothrow
410 return gc_setAttr( p, a );
415 * Clears the specified bits for the memory references by p. If p
416 * references memory not originally allocated by this garbage collector,
417 * points to the interior of a memory block, or if p is null, no action
421 * p = A pointer to the root of a valid memory block or to null.
422 * a = A bit field containing any bits to clear for this memory block.
425 * The result of a call to getAttr after the specified bits have been
428 static uint clrAttr( const scope void* p, uint a ) nothrow
430 return gc_clrAttr(cast(void*) p, a);
435 static uint clrAttr(void* p, uint a) pure nothrow
437 return gc_clrAttr( p, a );
443 * Requests an aligned block of managed memory from the garbage collector.
444 * This memory may be deleted at will with a call to free, or it may be
445 * discarded and cleaned up automatically during a collection run. If
446 * allocation fails, this function will call onOutOfMemory which is
447 * expected to throw an OutOfMemoryError.
450 * sz = The desired allocation size in bytes.
451 * ba = A bitmask of the attributes to set on this block.
452 * ti = TypeInfo to describe the memory. The GC might use this information
453 * to improve scanning for pointers or to call finalizers.
456 * A reference to the allocated memory or null if insufficient memory
460 * OutOfMemoryError on allocation failure.
462 pragma(mangle, "gc_malloc") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow;
466 * Requests an aligned block of managed memory from the garbage collector.
467 * This memory may be deleted at will with a call to free, or it may be
468 * discarded and cleaned up automatically during a collection run. If
469 * allocation fails, this function will call onOutOfMemory which is
470 * expected to throw an OutOfMemoryError.
473 * sz = The desired allocation size in bytes.
474 * ba = A bitmask of the attributes to set on this block.
475 * ti = TypeInfo to describe the memory. The GC might use this information
476 * to improve scanning for pointers or to call finalizers.
479 * Information regarding the allocated memory block or BlkInfo.init on
483 * OutOfMemoryError on allocation failure.
485 pragma(mangle, "gc_qalloc") static BlkInfo qalloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow;
489 * Requests an aligned block of managed memory from the garbage collector,
490 * which is initialized with all bits set to zero. This memory may be
491 * deleted at will with a call to free, or it may be discarded and cleaned
492 * up automatically during a collection run. If allocation fails, this
493 * function will call onOutOfMemory which is expected to throw an
497 * sz = The desired allocation size in bytes.
498 * ba = A bitmask of the attributes to set on this block.
499 * ti = TypeInfo to describe the memory. The GC might use this information
500 * to improve scanning for pointers or to call finalizers.
503 * A reference to the allocated memory or null if insufficient memory
507 * OutOfMemoryError on allocation failure.
509 pragma(mangle, "gc_calloc") static void* calloc(size_t sz, uint ba = 0, const TypeInfo ti = null) pure nothrow;
513 * Extend, shrink or allocate a new block of memory keeping the contents of
516 * If `sz` is zero, the memory referenced by p will be deallocated as if
517 * by a call to `free`.
518 * If `p` is `null`, new memory will be allocated via `malloc`.
519 * If `p` is pointing to memory not allocated from the GC or to the interior
520 * of an allocated memory block, no operation is performed and null is returned.
522 * Otherwise, a new memory block of size `sz` will be allocated as if by a
523 * call to `malloc`, or the implementation may instead resize or shrink the memory
525 * The contents of the new memory block will be the same as the contents
526 * of the old memory block, up to the lesser of the new and old sizes.
528 * The caller guarantees that there are no other live pointers to the
529 * passed memory block, still it might not be freed immediately by `realloc`.
530 * The garbage collector can reclaim the memory block in a later
531 * collection if it is unused.
532 * If allocation fails, this function will throw an `OutOfMemoryError`.
534 * If `ba` is zero (the default) the attributes of the existing memory
535 * will be used for an allocation.
536 * If `ba` is not zero and no new memory is allocated, the bits in ba will
537 * replace those of the current memory block.
540 * p = A pointer to the base of a valid memory block or to `null`.
541 * sz = The desired allocation size in bytes.
542 * ba = A bitmask of the BlkAttr attributes to set on this block.
543 * ti = TypeInfo to describe the memory. The GC might use this information
544 * to improve scanning for pointers or to call finalizers.
547 * A reference to the allocated memory on success or `null` if `sz` is
548 * zero or the pointer does not point to the base of an GC allocated
552 * `OutOfMemoryError` on allocation failure.
554 pragma(mangle, "gc_realloc") static void* realloc(return void* p, size_t sz, uint ba = 0, const TypeInfo ti = null) pure nothrow;
556 // https://issues.dlang.org/show_bug.cgi?id=13111
560 enum size1 = 1 << 11 + 1; // page in large object pool
561 enum size2 = 1 << 22 + 1; // larger than large object pool size
563 auto data1 = cast(ubyte*)GC.calloc(size1);
564 auto data2 = cast(ubyte*)GC.realloc(data1, size2);
566 GC.BlkInfo info = GC.query(data2);
567 assert(info.size >= size2);
572 * Requests that the managed memory block referenced by p be extended in
573 * place by at least mx bytes, with a desired extension of sz bytes. If an
574 * extension of the required size is not possible or if p references memory
575 * not originally allocated by this garbage collector, no action will be
579 * p = A pointer to the root of a valid memory block or to null.
580 * mx = The minimum extension size in bytes.
581 * sz = The desired extension size in bytes.
582 * ti = TypeInfo to describe the full memory block. The GC might use
583 * this information to improve scanning for pointers or to
587 * The size in bytes of the extended memory block referenced by p or zero
588 * if no extension occurred.
591 * Extend may also be used to extend slices (or memory blocks with
592 * $(LREF APPENDABLE) info). However, use the return value only
593 * as an indicator of success. $(LREF capacity) should be used to
594 * retrieve actual usable slice capacity.
596 pragma(mangle, "gc_extend") static size_t extend(void* p, size_t mx, size_t sz, const TypeInfo ti = null) pure nothrow;
597 /// Standard extending
601 int* p = cast(int*)GC.malloc(size * int.sizeof, GC.BlkAttr.NO_SCAN);
603 //Try to extend the allocated data by 1000 elements, preferred 2000.
604 size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
606 size = u / int.sizeof;
611 int[] slice = new int[](1000);
614 //Check we have access to capacity before attempting the extend
617 //Try to extend slice by 1000 elements, preferred 2000.
618 size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
621 slice.length = slice.capacity;
622 assert(slice.length >= 2000);
629 * Requests that at least sz bytes of memory be obtained from the operating
630 * system and marked as free.
633 * sz = The desired size in bytes.
636 * The actual number of bytes reserved or zero on error.
638 pragma(mangle, "gc_reserve") static size_t reserve(size_t sz) nothrow; /* FIXME pure */
642 * Deallocates the memory referenced by p. If p is null, no action occurs.
643 * If p references memory not originally allocated by this garbage
644 * collector, if p points to the interior of a memory block, or if this
645 * method is called from a finalizer, no action will be taken. The block
646 * will not be finalized regardless of whether the FINALIZE attribute is
647 * set. If finalization is desired, call $(REF1 destroy, object) prior to `GC.free`.
650 * p = A pointer to the root of a valid memory block or to null.
652 pragma(mangle, "gc_free") static void free(void* p) pure nothrow @nogc;
657 * Returns the base address of the memory block containing p. This value
658 * is useful to determine whether p is an interior pointer, and the result
659 * may be passed to routines such as sizeOf which may otherwise fail. If p
660 * references memory not originally allocated by this garbage collector, if
661 * p is null, or if the garbage collector does not support this operation,
662 * null will be returned.
665 * p = A pointer to the root or the interior of a valid memory block or to
669 * The base address of the memory block referenced by p or null on error.
671 static inout(void)* addrOf( inout(void)* p ) nothrow @nogc pure @trusted
673 return cast(inout(void)*)gc_addrOf(cast(void*)p);
677 static void* addrOf(void* p) pure nothrow @nogc @trusted
683 * Returns the true size of the memory block referenced by p. This value
684 * represents the maximum number of bytes for which a call to realloc may
685 * resize the existing block in place. If p references memory not
686 * originally allocated by this garbage collector, points to the interior
687 * of a memory block, or if p is null, zero will be returned.
690 * p = A pointer to the root of a valid memory block or to null.
693 * The size in bytes of the memory block referenced by p or zero on error.
695 static size_t sizeOf( const scope void* p ) nothrow @nogc /* FIXME pure */
697 return gc_sizeOf(cast(void*)p);
702 static size_t sizeOf(void* p) pure nothrow @nogc
704 return gc_sizeOf( p );
707 // verify that the reallocation doesn't leave the size cache in a wrong state
710 auto data = cast(int*)realloc(null, 4096);
711 size_t size = GC.sizeOf(data);
712 assert(size >= 4096);
713 data = cast(int*)GC.realloc(data, 4100);
714 size = GC.sizeOf(data);
715 assert(size >= 4100);
719 * Returns aggregate information about the memory block containing p. If p
720 * references memory not originally allocated by this garbage collector, if
721 * p is null, or if the garbage collector does not support this operation,
722 * BlkInfo.init will be returned. Typically, support for this operation
723 * is dependent on support for addrOf.
726 * p = A pointer to the root or the interior of a valid memory block or to
730 * Information regarding the memory block referenced by p or BlkInfo.init
733 static BlkInfo query(return scope const void* p) nothrow
735 return gc_query(cast(void*)p);
740 static BlkInfo query(return scope void* p) pure nothrow
742 return gc_query( p );
746 * Returns runtime stats for currently active GC implementation
747 * See `core.memory.GC.Stats` for list of available metrics.
749 static Stats stats() nothrow
755 * Returns runtime profile stats for currently active GC implementation
756 * See `core.memory.GC.ProfileStats` for list of available metrics.
758 static ProfileStats profileStats() nothrow @nogc @safe
760 return gc_profileStats();
766 * Adds an internal root pointing to the GC memory block referenced by p.
767 * As a result, the block referenced by p itself and any blocks accessible
768 * via it will be considered live until the root is removed again.
770 * If p is null, no operation is performed.
773 * p = A pointer into a GC-managed memory block or null.
777 * // Typical C-style callback mechanism; the passed function
778 * // is invoked with the user-supplied context pointer at a
780 * extern(C) void addCallback(void function(void*), void*);
782 * // Allocate an object on the GC heap (this would usually be
783 * // some application-specific context data).
784 * auto context = new Object;
786 * // Make sure that it is not collected even if it is no
787 * // longer referenced from D code (stack, GC heap, …).
788 * GC.addRoot(cast(void*)context);
790 * // Also ensure that a moving collector does not relocate
792 * GC.setAttr(cast(void*)context, GC.BlkAttr.NO_MOVE);
794 * // Now context can be safely passed to the C library.
795 * addCallback(&myHandler, cast(void*)context);
797 * extern(C) void myHandler(void* ctx)
799 * // Assuming that the callback is invoked only once, the
800 * // added root can be removed again now to allow the GC
801 * // to collect it later.
802 * GC.removeRoot(ctx);
803 * GC.clrAttr(ctx, GC.BlkAttr.NO_MOVE);
805 * auto context = cast(Object)ctx;
806 * // Use context here…
810 pragma(mangle, "gc_addRoot") static void addRoot(const void* p) nothrow @nogc; /* FIXME pure */
814 * Removes the memory block referenced by p from an internal list of roots
815 * to be scanned during a collection. If p is null or is not a value
816 * previously passed to addRoot() then no operation is performed.
819 * p = A pointer into a GC-managed memory block or null.
821 pragma(mangle, "gc_removeRoot") static void removeRoot(const void* p) nothrow @nogc; /* FIXME pure */
825 * Adds $(D p[0 .. sz]) to the list of memory ranges to be scanned for
826 * pointers during a collection. If p is null, no operation is performed.
828 * Note that $(D p[0 .. sz]) is treated as an opaque range of memory assumed
829 * to be suitably managed by the caller. In particular, if p points into a
830 * GC-managed memory block, addRange does $(I not) mark this block as live.
833 * p = A pointer to a valid memory address or to null.
834 * sz = The size in bytes of the block to add. If sz is zero then the
835 * no operation will occur. If p is null then sz must be zero.
836 * ti = TypeInfo to describe the memory. The GC might use this information
837 * to improve scanning for pointers or to call finalizers
841 * // Allocate a piece of memory on the C heap.
843 * auto rawMemory = core.stdc.stdlib.malloc(size);
845 * // Add it as a GC range.
846 * GC.addRange(rawMemory, size);
848 * // Now, pointers to GC-managed memory stored in
849 * // rawMemory will be recognized on collection.
852 pragma(mangle, "gc_addRange") static void addRange(const void* p, size_t sz, const TypeInfo ti = null) @nogc nothrow; /* FIXME pure */
856 * Removes the memory range starting at p from an internal list of ranges
857 * to be scanned during a collection. If p is null or does not represent
858 * a value previously passed to addRange() then no operation is
862 * p = A pointer to a valid memory address or to null.
864 pragma(mangle, "gc_removeRange") static void removeRange(const void* p) nothrow @nogc; /* FIXME pure */
868 * Runs any finalizer that is located in address range of the
869 * given code segment. This is used before unloading shared
870 * libraries. All matching objects which have a finalizer in this
871 * code segment are assumed to be dead, using them while or after
872 * calling this method has undefined behavior.
875 * segment = address range of a code segment.
877 pragma(mangle, "gc_runFinalizers") static void runFinalizers(const scope void[] segment);
880 * Queries the GC whether the current thread is running object finalization
881 * as part of a GC collection, or an explicit call to runFinalizers.
883 * As some GC implementations (such as the current conservative one) don't
884 * support GC memory allocation during object finalization, this function
885 * can be used to guard against such programming errors.
888 * true if the current thread is in a finalizer, a destructor invoked by
891 pragma(mangle, "gc_inFinalizer") static bool inFinalizer() nothrow @nogc @safe;
894 @safe nothrow @nogc unittest
896 // Only code called from a destructor is executed during finalization.
897 assert(!GC.inFinalizer);
910 static class Resource
912 static Outcome outcome;
916 outcome = Outcome.notCalled;
923 outcome = Outcome.calledFromDruntime;
925 import core.exception : InvalidMemoryOperationError;
929 * Presently, allocating GC memory during finalization
930 * is forbidden and leads to
931 * `InvalidMemoryOperationError` being thrown.
933 * `GC.inFinalizer` can be used to guard against
934 * programming erros such as these and is also a more
935 * efficient way to verify whether a destructor was
938 cast(void) GC.malloc(1);
941 catch (InvalidMemoryOperationError e)
948 outcome = Outcome.calledManually;
952 static void createGarbage()
954 auto r = new Resource;
958 assert(Resource.outcome == Outcome.notCalled);
962 Resource.outcome == Outcome.notCalled ||
963 Resource.outcome == Outcome.calledFromDruntime);
965 auto r = new Resource;
966 GC.runFinalizers((cast(const void*)typeid(Resource).destructor)[0..1]);
967 assert(Resource.outcome == Outcome.calledFromDruntime);
968 Resource.outcome = Outcome.notCalled;
970 debug(MEMSTOMP) {} else
972 // assume Resource data is still available
974 assert(Resource.outcome == Outcome.notCalled);
978 assert(Resource.outcome == Outcome.notCalled);
980 assert(Resource.outcome == Outcome.calledManually);
984 * Returns the number of bytes allocated for the current thread
985 * since program start. It is the same as
986 * GC.stats().allocatedInCurrentThread, but faster.
988 pragma(mangle, "gc_allocatedInCurrentThread") static ulong allocatedInCurrentThread() nothrow;
990 /// Using allocatedInCurrentThread
993 ulong currentlyAllocated = GC.allocatedInCurrentThread();
1001 DataStruct* unused = new DataStruct;
1002 assert(GC.allocatedInCurrentThread() == currentlyAllocated + 32);
1003 assert(GC.stats().allocatedInCurrentThread == currentlyAllocated + 32);
1008 * Pure variants of C's memory allocation functions `malloc`, `calloc`, and
1009 * `realloc` and deallocation function `free`.
1011 * UNIX 98 requires that errno be set to ENOMEM upon failure.
1012 * Purity is achieved by saving and restoring the value of `errno`, thus
1013 * behaving as if it were never changed.
1016 * $(LINK2 https://dlang.org/spec/function.html#pure-functions, D's rules for purity),
1017 * which allow for memory allocation under specific circumstances.
1019 void* pureMalloc()(size_t size) @trusted pure @nogc nothrow
1021 const errnosave = fakePureErrno;
1022 void* ret = fakePureMalloc(size);
1023 fakePureErrno = errnosave;
1027 void* pureCalloc()(size_t nmemb, size_t size) @trusted pure @nogc nothrow
1029 const errnosave = fakePureErrno;
1030 void* ret = fakePureCalloc(nmemb, size);
1031 fakePureErrno = errnosave;
1035 void* pureRealloc()(void* ptr, size_t size) @system pure @nogc nothrow
1037 const errnosave = fakePureErrno;
1038 void* ret = fakePureRealloc(ptr, size);
1039 fakePureErrno = errnosave;
1044 void pureFree()(void* ptr) @system pure @nogc nothrow
1048 // POSIX free doesn't set errno
1053 const errnosave = fakePureErrno;
1055 fakePureErrno = errnosave;
1060 @system pure nothrow @nogc unittest
1062 ubyte[] fun(size_t n) pure
1064 void* p = pureMalloc(n);
1065 p !is null || n == 0 || assert(0);
1066 scope(failure) p = pureRealloc(p, 0);
1067 p = pureRealloc(p, n *= 2);
1068 p !is null || n == 0 || assert(0);
1069 return cast(ubyte[]) p[0 .. n];
1072 auto buf = fun(100);
1073 assert(buf.length == 200);
1077 @system pure nothrow @nogc unittest
1079 const int errno = fakePureErrno();
1081 void* x = pureMalloc(10); // normal allocation
1082 assert(errno == fakePureErrno()); // errno shouldn't change
1083 assert(x !is null); // allocation should succeed
1085 x = pureRealloc(x, 10); // normal reallocation
1086 assert(errno == fakePureErrno()); // errno shouldn't change
1087 assert(x !is null); // allocation should succeed
1091 void* y = pureCalloc(10, 1); // normal zeroed allocation
1092 assert(errno == fakePureErrno()); // errno shouldn't change
1093 assert(y !is null); // allocation should succeed
1097 // Workaround bug in glibc 2.26
1098 // See also: https://issues.dlang.org/show_bug.cgi?id=17956
1099 void* z = pureMalloc(size_t.max & ~255); // won't affect `errno`
1100 assert(errno == fakePureErrno()); // errno shouldn't change
1104 // locally purified for internal use here only
1106 static import core.stdc.errno;
1107 static if (__traits(getOverloads, core.stdc.errno, "errno").length == 1
1108 && __traits(getLinkage, core.stdc.errno.errno) == "C")
1110 extern(C) pragma(mangle, __traits(identifier, core.stdc.errno.errno))
1111 private ref int fakePureErrno() @nogc nothrow pure @system;
1115 extern(C) private @nogc nothrow pure @system
1117 pragma(mangle, __traits(identifier, core.stdc.errno.getErrno))
1118 @property int fakePureErrno();
1120 pragma(mangle, __traits(identifier, core.stdc.errno.setErrno))
1121 @property int fakePureErrno(int);
1125 version (D_BetterC) {}
1126 else // TODO: remove this function after Phobos no longer needs it.
1127 extern (C) private @system @nogc nothrow
1129 ref int fakePureErrnoImpl()
1131 import core.stdc.errno;
1136 extern (C) private pure @system @nogc nothrow
1138 pragma(mangle, "malloc") void* fakePureMalloc(size_t);
1139 pragma(mangle, "calloc") void* fakePureCalloc(size_t nmemb, size_t size);
1140 pragma(mangle, "realloc") void* fakePureRealloc(void* ptr, size_t size);
1142 pragma(mangle, "free") void fakePureFree(void* ptr);
1146 Destroys and then deallocates an object.
1148 In detail, `__delete(x)` returns with no effect if `x` is `null`. Otherwise, it
1149 performs the following actions in sequence:
1152 Calls the destructor `~this()` for the object referred to by `x`
1153 (if `x` is a class or interface reference) or
1154 for the object pointed to by `x` (if `x` is a pointer to a `struct`).
1155 Arrays of structs call the destructor, if defined, for each element in the array.
1156 If no destructor is defined, this step has no effect.
1159 Frees the memory allocated for `x`. If `x` is a reference to a class
1160 or interface, the memory allocated for the underlying instance is freed. If `x` is
1161 a pointer, the memory allocated for the pointed-to object is freed. If `x` is a
1162 built-in array, the memory allocated for the array is freed.
1163 If `x` does not refer to memory previously allocated with `new` (or the lower-level
1164 equivalents in the GC API), the behavior is undefined.
1167 Lastly, `x` is set to `null`. Any attempt to read or write the freed memory via
1168 other references will result in undefined behavior.
1172 Note: Users should prefer $(REF1 destroy, object) to explicitly finalize objects,
1173 and only resort to $(REF __delete, core,memory) when $(REF destroy, object)
1174 wouldn't be a feasible option.
1177 x = aggregate object that should be destroyed
1179 See_Also: $(REF1 destroy, object), $(REF free, core,GC)
1183 The `delete` keyword allowed to free GC-allocated memory.
1184 As this is inherently not `@safe`, it has been deprecated.
1185 This function has been added to provide an easy transition from `delete`.
1186 It performs the same functionality as the former `delete` keyword.
1188 void __delete(T)(ref T x) @system
1190 static void _destructRecurse(S)(ref S s)
1191 if (is(S == struct))
1193 static if (__traits(hasMember, S, "__xdtor") &&
1194 // Bugzilla 14746: Check that it's the exact member of S.
1195 __traits(isSame, S, __traits(parent, s.__xdtor)))
1199 // See also: https://github.com/dlang/dmd/blob/v2.078.0/src/dmd/e2ir.d#L3886
1200 static if (is(T == interface))
1204 else static if (is(T == class))
1208 else static if (is(T == U*, U))
1210 static if (is(U == struct))
1211 _destructRecurse(*x);
1213 else static if (is(T : E[], E))
1215 static if (is(E == struct))
1217 foreach_reverse (ref e; x)
1218 _destructRecurse(e);
1223 static assert(0, "It is not possible to delete: `" ~ T.stringof ~ "`");
1226 static if (is(T == interface) ||
1230 GC.free(GC.addrOf(cast(void*) x));
1233 else static if (is(T : E2[], E2))
1235 GC.free(GC.addrOf(cast(void*) x.ptr));
1240 /// Deleting classes
1256 assert(GC.addrOf(cast(void*) b) != null);
1260 assert(GC.addrOf(cast(void*) b) == null);
1261 // but be careful, a still points to it
1263 assert(GC.addrOf(cast(void*) a) == null); // but not a valid GC pointer
1266 /// Deleting interfaces
1290 assert(GC.addrOf(cast(void*) a) != null);
1294 assert(GC.addrOf(cast(void*) a) == null);
1297 /// Deleting structs
1309 auto a = new A("foo");
1311 assert(GC.addrOf(cast(void*) a) != null);
1315 assert(GC.addrOf(cast(void*) a) == null);
1321 int[] a = [1, 2, 3];
1324 assert(GC.addrOf(b.ptr) != null);
1327 assert(GC.addrOf(b.ptr) == null);
1328 // but be careful, a still points to it
1330 assert(GC.addrOf(a.ptr) == null); // but not a valid GC pointer
1333 /// Deleting arrays of structs
1342 assert(dtorCalled == a);
1346 auto arr = [A(1), A(2), A(3)];
1351 assert(GC.addrOf(arr.ptr) != null);
1353 assert(dtorCalled == 3);
1354 assert(GC.addrOf(arr.ptr) == null);
1357 // Deleting raw memory
1360 import core.memory : GC;
1361 auto a = GC.malloc(5);
1362 assert(GC.addrOf(cast(void*) a) != null);
1365 assert(GC.addrOf(cast(void*) a) == null);
1368 // __delete returns with no effect if x is null
1374 struct S { ~this() { } }
1378 int[] a; __delete(a);
1379 S[] as; __delete(as);
1382 C* pc = &c; __delete(*pc);
1383 I* pi = &i; __delete(*pi);
1384 int* pint; __delete(pint);
1385 S* ps; __delete(ps);
1388 // https://issues.dlang.org/show_bug.cgi?id=19092
1391 const(int)[] x = [1, 2, 3];
1392 assert(GC.addrOf(x.ptr) != null);
1395 assert(GC.addrOf(x.ptr) == null);
1397 immutable(int)[] y = [1, 2, 3];
1398 assert(GC.addrOf(y.ptr) != null);
1401 assert(GC.addrOf(y.ptr) == null);
1404 // test realloc behaviour
1407 static void set(int* p, size_t size)
1409 foreach (i; 0 .. size)
1412 static void verify(int* p, size_t size)
1414 foreach (i; 0 .. size)
1417 static void test(size_t memsize)
1419 int* p = cast(int*) GC.malloc(memsize * int.sizeof);
1424 int* q = cast(int*) GC.realloc(p + 4, 2 * memsize * int.sizeof);
1427 q = cast(int*) GC.realloc(p + memsize / 2, 2 * memsize * int.sizeof);
1430 q = cast(int*) GC.realloc(p + memsize - 1, 2 * memsize * int.sizeof);
1433 int* r = cast(int*) GC.realloc(p, 5 * memsize * int.sizeof);
1435 set(r, 5 * memsize);
1437 int* s = cast(int*) GC.realloc(r, 2 * memsize * int.sizeof);
1438 verify(s, 2 * memsize);
1440 assert(GC.realloc(s, 0) == null); // free
1441 assert(GC.addrOf(p) == null);
1446 test(800); // spans large and small pools
1450 void* p = GC.malloc(100);
1451 assert(GC.realloc(&p, 50) == null); // non-GC pointer
1454 // test GC.profileStats
1457 auto stats = GC.profileStats();
1459 auto nstats = GC.profileStats();
1460 assert(nstats.numCollections > stats.numCollections);
1464 private extern (C) void* _d_newitemU(scope const TypeInfo _ti) @system pure nothrow;
1467 Moves a value to a new GC allocation.
1470 value = Value to be moved. If the argument is an lvalue and a struct with a
1471 destructor or postblit, it will be reset to its `.init` value.
1474 A pointer to the new GC-allocated value.
1476 T* moveToGC(T)(auto ref T value)
1478 static T* doIt(ref T value) @trusted
1480 import core.lifetime : moveEmplace;
1481 auto mem = cast(T*) _d_newitemU(typeid(T)); // allocate but don't initialize
1482 moveEmplace(value, *mem);
1486 return doIt(value); // T dtor might be @system
1490 @safe pure nothrow unittest
1495 this(this) @disable;
1496 ~this() @safe pure nothrow @nogc {}
1502 p = moveToGC(S(123));
1509 assert(lval.x == 0);
1521 // lvalue case is @safe, ref param isn't destructed
1522 static assert(__traits(compiles, (ref S lval) @safe { moveToGC(lval); }));
1524 // rvalue case is @system, value param is destructed
1525 static assert(!__traits(compiles, () @safe { moveToGC(S(0)); }));