/** * This module provides an interface to the garbage collector used by * applications written in the D programming language. It allows the * garbage collector in the runtime to be swapped without affecting * binary compatibility of applications. * * Using this module is not necessary in typical D code. It is mostly * useful when doing low-level _memory management. * * Notes_to_users: * $(OL $(LI The GC is a conservative mark-and-sweep collector. It only runs a collection cycle when an allocation is requested of it, never otherwise. Hence, if the program is not doing allocations, there will be no GC collection pauses. The pauses occur because all threads the GC knows about are halted so the threads' stacks and registers can be scanned for references to GC allocated data. ) $(LI The GC does not know about threads that were created by directly calling the OS/C runtime thread creation APIs and D threads that were detached from the D runtime after creation. Such threads will not be paused for a GC collection, and the GC might not detect references to GC allocated data held by them. This can cause memory corruption. There are several ways to resolve this issue: $(OL $(LI Do not hold references to GC allocated data in such threads.) $(LI Register/unregister such data with calls to $(LREF addRoot)/$(LREF removeRoot) and $(LREF addRange)/$(LREF removeRange).) $(LI Maintain another reference to that same data in another thread that the GC does know about.) $(LI Disable GC collection cycles while that thread is active with $(LREF disable)/$(LREF enable).) $(LI Register the thread with the GC using $(REF thread_attachThis, core,thread,osthread)/$(REF thread_detachThis, core,thread,threadbase).) ) ) ) * * Notes_to_implementors: * $(UL * $(LI On POSIX systems, the signals `SIGRTMIN` and `SIGRTMIN + 1` are reserved * by this module for use in the garbage collector implementation. * Typically, they will be used to stop and resume other threads * when performing a collection, but an implementation may choose * not to use this mechanism (or not stop the world at all, in the * case of concurrent garbage collectors).) * * $(LI Registers, the stack, and any other _memory locations added through * the $(D GC.$(LREF addRange)) function are always scanned conservatively. * This means that even if a variable is e.g. of type $(D float), * it will still be scanned for possible GC pointers. And, if the * word-interpreted representation of the variable matches a GC-managed * _memory block's address, that _memory block is considered live.) * * $(LI Implementations are free to scan the non-root heap in a precise * manner, so that fields of types like $(D float) will not be considered * relevant when scanning the heap. Thus, casting a GC pointer to an * integral type (e.g. $(D size_t)) and storing it in a field of that * type inside the GC heap may mean that it will not be recognized * if the _memory block was allocated with precise type info or with * the $(D GC.BlkAttr.$(LREF NO_SCAN)) attribute.) * * $(LI Destructors will always be executed while other threads are * active; that is, an implementation that stops the world must not * execute destructors until the world has been resumed.) * * $(LI A destructor of an object must not access object references * within the object. This means that an implementation is free to * optimize based on this rule.) * * $(LI An implementation is free to perform heap compaction and copying * so long as no valid GC pointers are invalidated in the process. * However, _memory allocated with $(D GC.BlkAttr.$(LREF NO_MOVE)) must * not be moved/copied.) * * $(LI Implementations must support interior pointers. That is, if the * only reference to a GC-managed _memory block points into the * middle of the block rather than the beginning (for example), the * GC must consider the _memory block live. The exception to this * rule is when a _memory block is allocated with the * $(D GC.BlkAttr.$(LREF NO_INTERIOR)) attribute; it is the user's * responsibility to make sure such _memory blocks have a proper pointer * to them when they should be considered live.) * * $(LI It is acceptable for an implementation to store bit flags into * pointer values and GC-managed _memory blocks, so long as such a * trick is not visible to the application. In practice, this means * that only a stop-the-world collector can do this.) * * $(LI Implementations are free to assume that GC pointers are only * stored on word boundaries. Unaligned pointers may be ignored * entirely.) * * $(LI Implementations are free to run collections at any point. It is, * however, recommendable to only do so when an allocation attempt * happens and there is insufficient _memory available.) * ) * * Copyright: Copyright Sean Kelly 2005 - 2015. * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) * Authors: Sean Kelly, Alex Rønne Petersen * Source: $(DRUNTIMESRC core/_memory.d) * Macros: * WARN_UNINITIALIZED=$(RED Warning): * $1 will be uninitialized, and may happen to hold pointers to GC memory. * Consider zeroing out any uninitialized bytes which won't be immediately written to. */ module core.memory; version (ARM) version = AnyARM;else version (AArch64) version = AnyARM; version (iOS) version = iOSDerived;else version (TVOS) version = iOSDerived;else version (WatchOS) version = iOSDerived; private{ extern (C) uint gc_getAttr( void* p ) pure nothrow; extern (C) uint gc_setAttr( void* p, uint a ) pure nothrow; extern (C) uint gc_clrAttr( void* p, uint a ) pure nothrow; extern (C) void* gc_addrOf( void* p ) pure nothrow @nogc; extern (C) size_t gc_sizeOf( void* p ) pure nothrow @nogc; struct BlkInfo_ { void* base; size_t size; uint attr; } extern (C) BlkInfo_ gc_query(return scope void* p) pure nothrow; extern (C) GC.Stats gc_stats ( ) @safe nothrow @nogc; extern (C) GC.ProfileStats gc_profileStats ( ) nothrow @nogc @safe;} version (CoreDdoc){ /** * The minimum size of a system page in bytes. * * This is a compile time, platform specific value. This value might not * be accurate, since it might be possible to change this value. Whenever * possible, please use $(LREF pageSize) instead, which is initialized * during runtime. * * The minimum size is useful when the context requires a compile time known * value, like the size of a static array: `ubyte[minimumPageSize] buffer`. */ enum minimumPageSize : size_t;}else version (AnyARM){ version (iOSDerived) enum size_t minimumPageSize = 16384; else enum size_t minimumPageSize = 4096;}else enum size_t minimumPageSize = 4096; ///unittest{ ubyte[minimumPageSize] buffer;} /** * The size of a system page in bytes. * * This value is set at startup time of the application. It's safe to use * early in the start process, like in shared module constructors and * initialization of the D runtime itself. */immutable size_t pageSize; ///unittest{ ubyte[] buffer = new ubyte[pageSize];} // The reason for this elaborated way of declaring a function is://// * `pragma(crt_constructor)` is used to declare a constructor that is called by// the C runtime, before C main. This allows the `pageSize` value to be used// during initialization of the D runtime. This also avoids any issues with// static module constructors and circular references.//// * `pragma(mangle)` is used because `pragma(crt_constructor)` requires a// function with C linkage. To avoid any name conflict with other C symbols,// standard D mangling is used.//// * The extra function declaration, without the body, is to be able to get the// D mangling of the function without the need to hardcode the value.//// * The extern function declaration also has the side effect of making it// impossible to manually call the function with standard syntax. This is to// make it more difficult to call the function again, manually.private void initialize();pragma(crt_constructor)pragma(mangle, initialize.mangleof)private extern (C) void _initialize() @system{ version (Posix) { import core.sys.posix.unistd : sysconf, _SC_PAGESIZE; (cast() pageSize) = cast(size_t) sysconf(_SC_PAGESIZE); } else version (Windows) { import core.sys.windows.winbase : GetSystemInfo, SYSTEM_INFO; SYSTEM_INFO si; GetSystemInfo(&si); (cast() pageSize) = cast(size_t) si.dwPageSize; } else static assert(false, __FUNCTION__ ~ " is not implemented on this platform");} /** * This struct encapsulates all garbage collection functionality for the D * programming language. */struct GC{ @disable this(); /** * Aggregation of GC stats to be exposed via public API */ static struct Stats { /// number of used bytes on the GC heap (might only get updated after a collection) size_t usedSize; /// number of free bytes on the GC heap (might only get updated after a collection) size_t freeSize; /// number of bytes allocated for current thread since program start ulong allocatedInCurrentThread; } /** * Aggregation of current profile information */ static struct ProfileStats { import core.time : Duration; /// total number of GC cycles size_t numCollections; /// total time spent doing GC Duration totalCollectionTime; /// total time threads were paused doing GC Duration totalPauseTime; /// largest time threads were paused during one GC cycle Duration maxPauseTime; /// largest time spent doing one GC cycle Duration maxCollectionTime; } extern(C): /** * Enables automatic garbage collection behavior if collections have * previously been suspended by a call to `GC.disable()`. This function is * reentrant, and must be called once for every call to `GC.disable()` before * automatic collections are enabled. */ pragma(mangle, "gc_enable") static void enable() @safe nothrow pure; /** * Disables automatic garbage collections performed to minimize the * process footprint. Collections may continue to occur in instances * where the implementation deems necessary for correct program behavior, * such as during an out of memory condition. This function is reentrant, * but `GC.enable()` must be called once for each call to `GC.disable()`. * Unlike the * $(LINK2 https://dlang.org/spec/function.html#nogc-functions, `@nogc` attribute), * `GC.disable()` halts * collections across all threads, yet still allows GC allocations. * Disabling collections eliminates GC pauses. */ pragma(mangle, "gc_disable") static void disable() @safe nothrow pure; /** * Begins a full collection. While the meaning of this may change based * on the garbage collector implementation, typical behavior is to scan * all stack segments for roots, mark accessible memory blocks as alive, * and then to reclaim free space. This action may need to suspend all * running threads for at least part of the collection process. */ pragma(mangle, "gc_collect") static void collect() @safe nothrow pure; /** * Indicates that the managed memory space be minimized by returning free * physical memory to the operating system. The amount of free memory * returned depends on the allocator design and on program behavior. */ pragma(mangle, "gc_minimize") static void minimize() @safe nothrow pure; extern(D): /** * Elements for a bit field representing memory block attributes. These * are manipulated via the getAttr, setAttr, clrAttr functions. */ enum BlkAttr : uint { NONE = 0b0000_0000, /// No attributes set. FINALIZE = 0b0000_0001, /// Finalize the data in this block on collect. NO_SCAN = 0b0000_0010, /// Do not scan through this block on collect. NO_MOVE = 0b0000_0100, /// Do not move this memory block on collect. /** This block contains the info to allow appending. This can be used to manually allocate arrays. Initial slice size is 0. Note: The slice's usable size will not match the block size. Use $(REF1 capacity, object) to retrieve actual usable capacity. Example: ---- // Allocate the underlying array. int* pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE); // Bind a slice. Check the slice has capacity information. int[] slice = pToArray[0 .. 0]; assert(capacity(slice) > 0); // Appending to the slice will not relocate it. slice.length = 5; slice ~= 1; assert(slice.ptr == p); ---- */ APPENDABLE = 0b0000_1000, /** This block is guaranteed to have a pointer to its base while it is alive. Interior pointers can be safely ignored. This attribute is useful for eliminating false pointers in very large data structures and is only implemented for data structures at least a page in size. */ NO_INTERIOR = 0b0001_0000, STRUCTFINAL = 0b0010_0000, // the block has a finalizer for (an array of) structs } /** * Contains aggregate information about a block of managed memory. The * purpose of this struct is to support a more efficient query style in * instances where detailed information is needed. * * base = A pointer to the base of the block in question. * size = The size of the block, calculated from base. * attr = Attribute bits set on the memory block. */ alias BlkInfo = BlkInfo_; /** * Returns a bit field representing all block attributes set for the memory * referenced by p. If p references memory not originally allocated by * this garbage collector, points to the interior of a memory block, or if * p is null, zero will be returned. * * Params: * p = A pointer to the root of a valid memory block or to null. * * Returns: * A bit field containing any bits set for the memory block referenced by * p or zero on error. */ static uint getAttr( const scope void* p ) nothrow { return gc_getAttr(cast(void*) p); } /// ditto static uint getAttr(void* p) pure nothrow { return gc_getAttr( p ); } /** * Sets the specified bits for the memory references by p. If p references * memory not originally allocated by this garbage collector, points to the * interior of a memory block, or if p is null, no action will be * performed. * * Params: * p = A pointer to the root of a valid memory block or to null. * a = A bit field containing any bits to set for this memory block. * * Returns: * The result of a call to $(LREF getAttr) after the specified bits have been * set. */ static uint setAttr( const scope void* p, uint a ) nothrow { return gc_setAttr(cast(void*) p, a); } /// ditto static uint setAttr(void* p, uint a) pure nothrow { return gc_setAttr( p, a ); } /** * Clears the specified bits for the memory references by p. If p * references memory not originally allocated by this garbage collector, * points to the interior of a memory block, or if p is null, no action * will be performed. * * Params: * p = A pointer to the root of a valid memory block or to null. * a = A bit field containing any bits to clear for this memory block. * * Returns: * The result of a call to $(LREF getAttr) after the specified bits have been * cleared. */ static uint clrAttr( const scope void* p, uint a ) nothrow { return gc_clrAttr(cast(void*) p, a); } /// ditto static uint clrAttr(void* p, uint a) pure nothrow { return gc_clrAttr( p, a ); } extern(C): /** * Requests an aligned block of managed memory from the garbage collector. * This memory may be deleted at will with a call to free, or it may be * discarded and cleaned up automatically during a collection run. If * allocation fails, this function will call onOutOfMemory which is * expected to throw an OutOfMemoryError. * * Params: * sz = The desired allocation size in bytes. * ba = A bitmask of the attributes to set on this block. * ti = TypeInfo to describe the memory. The GC might use this information * to improve scanning for pointers or to call finalizers. * * Returns: * A reference to the allocated memory or null if insufficient memory * is available. * * $(WARN_UNINITIALIZED Allocated memory) * * Throws: * OutOfMemoryError on allocation failure. */ version (D_ProfileGC) pragma(mangle, "gc_mallocTrace") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null, string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow; else pragma(mangle, "gc_malloc") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow; /** * Requests an aligned block of managed memory from the garbage collector. * This memory may be deleted at will with a call to $(LREF free), or it may be * discarded and cleaned up automatically during a collection run. If * allocation fails, this function will call onOutOfMemory which is * expected to throw an OutOfMemoryError. * * Params: * sz = The desired allocation size in bytes. * ba = A bitmask of the attributes to set on this block. * ti = TypeInfo to describe the memory. The GC might use this information * to improve scanning for pointers or to call finalizers. * * Returns: * Information regarding the allocated memory block or BlkInfo.init on * error. * * $(WARN_UNINITIALIZED Allocated memory) * * Throws: * OutOfMemoryError on allocation failure. */Lines 1–500 of 1572. Load more
/** * This module provides an interface to the garbage collector used by * applications written in the D programming language. It allows the * garbage collector in the runtime to be swapped without affecting * binary compatibility of applications. * * Using this module is not necessary in typical D code. It is mostly * useful when doing low-level _memory management. * * Notes_to_users: * $(OL $(LI The GC is a conservative mark-and-sweep collector. It only runs a collection cycle when an allocation is requested of it, never otherwise. Hence, if the program is not doing allocations, there will be no GC collection pauses. The pauses occur because all threads the GC knows about are halted so the threads' stacks and registers can be scanned for references to GC allocated data. ) $(LI The GC does not know about threads that were created by directly calling the OS/C runtime thread creation APIs and D threads that were detached from the D runtime after creation. Such threads will not be paused for a GC collection, and the GC might not detect references to GC allocated data held by them. This can cause memory corruption. There are several ways to resolve this issue: $(OL $(LI Do not hold references to GC allocated data in such threads.) $(LI Register/unregister such data with calls to $(LREF addRoot)/$(LREF removeRoot) and $(LREF addRange)/$(LREF removeRange).) $(LI Maintain another reference to that same data in another thread that the GC does know about.) $(LI Disable GC collection cycles while that thread is active with $(LREF disable)/$(LREF enable).) $(LI Register the thread with the GC using $(REF thread_attachThis, core,thread,osthread)/$(REF thread_detachThis, core,thread,threadbase).) ) ) ) * * Notes_to_implementors: * $(UL * $(LI On POSIX systems, the signals `SIGRTMIN` and `SIGRTMIN + 1` are reserved * by this module for use in the garbage collector implementation. * Typically, they will be used to stop and resume other threads * when performing a collection, but an implementation may choose * not to use this mechanism (or not stop the world at all, in the * case of concurrent garbage collectors).) * * $(LI Registers, the stack, and any other _memory locations added through * the $(D GC.$(LREF addRange)) function are always scanned conservatively. * This means that even if a variable is e.g. of type $(D float), * it will still be scanned for possible GC pointers. And, if the * word-interpreted representation of the variable matches a GC-managed * _memory block's address, that _memory block is considered live.) * * $(LI Implementations are free to scan the non-root heap in a precise * manner, so that fields of types like $(D float) will not be considered * relevant when scanning the heap. Thus, casting a GC pointer to an * integral type (e.g. $(D size_t)) and storing it in a field of that * type inside the GC heap may mean that it will not be recognized * if the _memory block was allocated with precise type info or with * the $(D GC.BlkAttr.$(LREF NO_SCAN)) attribute.) * * $(LI Destructors will always be executed while other threads are * active; that is, an implementation that stops the world must not * execute destructors until the world has been resumed.) * * $(LI A destructor of an object must not access object references * within the object. This means that an implementation is free to * optimize based on this rule.) * * $(LI An implementation is free to perform heap compaction and copying * so long as no valid GC pointers are invalidated in the process. * However, _memory allocated with $(D GC.BlkAttr.$(LREF NO_MOVE)) must * not be moved/copied.) * * $(LI Implementations must support interior pointers. That is, if the * only reference to a GC-managed _memory block points into the * middle of the block rather than the beginning (for example), the * GC must consider the _memory block live. The exception to this * rule is when a _memory block is allocated with the * $(D GC.BlkAttr.$(LREF NO_INTERIOR)) attribute; it is the user's * responsibility to make sure such _memory blocks have a proper pointer * to them when they should be considered live.) * * $(LI It is acceptable for an implementation to store bit flags into * pointer values and GC-managed _memory blocks, so long as such a * trick is not visible to the application. In practice, this means * that only a stop-the-world collector can do this.) * * $(LI Implementations are free to assume that GC pointers are only * stored on word boundaries. Unaligned pointers may be ignored * entirely.) * * $(LI Implementations are free to run collections at any point. It is, * however, recommendable to only do so when an allocation attempt * happens and there is insufficient _memory available.) * ) * * Copyright: Copyright Sean Kelly 2005 - 2015. * License: $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost License 1.0) * Authors: Sean Kelly, Alex Rønne Petersen * Source: $(DRUNTIMESRC core/_memory.d) * Macros: * WARN_UNINITIALIZED=$(RED Warning): * $1 will be uninitialized, and may happen to hold pointers to GC memory. * Consider zeroing out any uninitialized bytes which won't be immediately written to. */ module core.memory; version (ARM) version = AnyARM; else version (AArch64) version = AnyARM; version (iOS) version = iOSDerived; else version (TVOS) version = iOSDerived; else version (WatchOS) version = iOSDerived; private { extern (C) uint gc_getAttr( void* p ) pure nothrow; extern (C) uint gc_setAttr( void* p, uint a ) pure nothrow; extern (C) uint gc_clrAttr( void* p, uint a ) pure nothrow; extern (C) void* gc_addrOf( void* p ) pure nothrow @nogc; extern (C) size_t gc_sizeOf( void* p ) pure nothrow @nogc; struct BlkInfo_ { void* base; size_t size; uint attr; } extern (C) BlkInfo_ gc_query(return scope void* p) pure nothrow; extern (C) GC.Stats gc_stats ( ) @safe nothrow @nogc; extern (C) GC.ProfileStats gc_profileStats ( ) nothrow @nogc @safe; } version (CoreDdoc) { /** * The minimum size of a system page in bytes. * * This is a compile time, platform specific value. This value might not * be accurate, since it might be possible to change this value. Whenever * possible, please use $(LREF pageSize) instead, which is initialized * during runtime. * * The minimum size is useful when the context requires a compile time known * value, like the size of a static array: `ubyte[minimumPageSize] buffer`. */ enum minimumPageSize : size_t; } else version (AnyARM) { version (iOSDerived) enum size_t minimumPageSize = 16384; else enum size_t minimumPageSize = 4096; } else enum size_t minimumPageSize = 4096; /// unittest { ubyte[minimumPageSize] buffer; } /** * The size of a system page in bytes. * * This value is set at startup time of the application. It's safe to use * early in the start process, like in shared module constructors and * initialization of the D runtime itself. */ immutable size_t pageSize; /// unittest { ubyte[] buffer = new ubyte[pageSize]; } // The reason for this elaborated way of declaring a function is: // // * `pragma(crt_constructor)` is used to declare a constructor that is called by // the C runtime, before C main. This allows the `pageSize` value to be used // during initialization of the D runtime. This also avoids any issues with // static module constructors and circular references. // // * `pragma(mangle)` is used because `pragma(crt_constructor)` requires a // function with C linkage. To avoid any name conflict with other C symbols, // standard D mangling is used. // // * The extra function declaration, without the body, is to be able to get the // D mangling of the function without the need to hardcode the value. // // * The extern function declaration also has the side effect of making it // impossible to manually call the function with standard syntax. This is to // make it more difficult to call the function again, manually. private void initialize(); pragma(crt_constructor) pragma(mangle, initialize.mangleof) private extern (C) void _initialize() @system { version (Posix) { import core.sys.posix.unistd : sysconf, _SC_PAGESIZE; (cast() pageSize) = cast(size_t) sysconf(_SC_PAGESIZE); } else version (Windows) { import core.sys.windows.winbase : GetSystemInfo, SYSTEM_INFO; SYSTEM_INFO si; GetSystemInfo(&si); (cast() pageSize) = cast(size_t) si.dwPageSize; } else static assert(false, __FUNCTION__ ~ " is not implemented on this platform"); } /** * This struct encapsulates all garbage collection functionality for the D * programming language. */ struct GC { @disable this(); /** * Aggregation of GC stats to be exposed via public API */ static struct Stats { /// number of used bytes on the GC heap (might only get updated after a collection) size_t usedSize; /// number of free bytes on the GC heap (might only get updated after a collection) size_t freeSize; /// number of bytes allocated for current thread since program start ulong allocatedInCurrentThread; } /** * Aggregation of current profile information */ static struct ProfileStats { import core.time : Duration; /// total number of GC cycles size_t numCollections; /// total time spent doing GC Duration totalCollectionTime; /// total time threads were paused doing GC Duration totalPauseTime; /// largest time threads were paused during one GC cycle Duration maxPauseTime; /// largest time spent doing one GC cycle Duration maxCollectionTime; } extern(C): /** * Enables automatic garbage collection behavior if collections have * previously been suspended by a call to `GC.disable()`. This function is * reentrant, and must be called once for every call to `GC.disable()` before * automatic collections are enabled. */ pragma(mangle, "gc_enable") static void enable() @safe nothrow pure; /** * Disables automatic garbage collections performed to minimize the * process footprint. Collections may continue to occur in instances * where the implementation deems necessary for correct program behavior, * such as during an out of memory condition. This function is reentrant, * but `GC.enable()` must be called once for each call to `GC.disable()`. * Unlike the * $(LINK2 https://dlang.org/spec/function.html#nogc-functions, `@nogc` attribute), * `GC.disable()` halts * collections across all threads, yet still allows GC allocations. * Disabling collections eliminates GC pauses. */ pragma(mangle, "gc_disable") static void disable() @safe nothrow pure; /** * Begins a full collection. While the meaning of this may change based * on the garbage collector implementation, typical behavior is to scan * all stack segments for roots, mark accessible memory blocks as alive, * and then to reclaim free space. This action may need to suspend all * running threads for at least part of the collection process. */ pragma(mangle, "gc_collect") static void collect() @safe nothrow pure; /** * Indicates that the managed memory space be minimized by returning free * physical memory to the operating system. The amount of free memory * returned depends on the allocator design and on program behavior. */ pragma(mangle, "gc_minimize") static void minimize() @safe nothrow pure; extern(D): /** * Elements for a bit field representing memory block attributes. These * are manipulated via the getAttr, setAttr, clrAttr functions. */ enum BlkAttr : uint { NONE = 0b0000_0000, /// No attributes set. FINALIZE = 0b0000_0001, /// Finalize the data in this block on collect. NO_SCAN = 0b0000_0010, /// Do not scan through this block on collect. NO_MOVE = 0b0000_0100, /// Do not move this memory block on collect. /** This block contains the info to allow appending. This can be used to manually allocate arrays. Initial slice size is 0. Note: The slice's usable size will not match the block size. Use $(REF1 capacity, object) to retrieve actual usable capacity. Example: ---- // Allocate the underlying array. int* pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE); // Bind a slice. Check the slice has capacity information. int[] slice = pToArray[0 .. 0]; assert(capacity(slice) > 0); // Appending to the slice will not relocate it. slice.length = 5; slice ~= 1; assert(slice.ptr == p); ---- */ APPENDABLE = 0b0000_1000, /** This block is guaranteed to have a pointer to its base while it is alive. Interior pointers can be safely ignored. This attribute is useful for eliminating false pointers in very large data structures and is only implemented for data structures at least a page in size. */ NO_INTERIOR = 0b0001_0000, STRUCTFINAL = 0b0010_0000, // the block has a finalizer for (an array of) structs } /** * Contains aggregate information about a block of managed memory. The * purpose of this struct is to support a more efficient query style in * instances where detailed information is needed. * * base = A pointer to the base of the block in question. * size = The size of the block, calculated from base. * attr = Attribute bits set on the memory block. */ alias BlkInfo = BlkInfo_; /** * Returns a bit field representing all block attributes set for the memory * referenced by p. If p references memory not originally allocated by * this garbage collector, points to the interior of a memory block, or if * p is null, zero will be returned. * * Params: * p = A pointer to the root of a valid memory block or to null. * * Returns: * A bit field containing any bits set for the memory block referenced by * p or zero on error. */ static uint getAttr( const scope void* p ) nothrow { return gc_getAttr(cast(void*) p); } /// ditto static uint getAttr(void* p) pure nothrow { return gc_getAttr( p ); } /** * Sets the specified bits for the memory references by p. If p references * memory not originally allocated by this garbage collector, points to the * interior of a memory block, or if p is null, no action will be * performed. * * Params: * p = A pointer to the root of a valid memory block or to null. * a = A bit field containing any bits to set for this memory block. * * Returns: * The result of a call to $(LREF getAttr) after the specified bits have been * set. */ static uint setAttr( const scope void* p, uint a ) nothrow { return gc_setAttr(cast(void*) p, a); } /// ditto static uint setAttr(void* p, uint a) pure nothrow { return gc_setAttr( p, a ); } /** * Clears the specified bits for the memory references by p. If p * references memory not originally allocated by this garbage collector, * points to the interior of a memory block, or if p is null, no action * will be performed. * * Params: * p = A pointer to the root of a valid memory block or to null. * a = A bit field containing any bits to clear for this memory block. * * Returns: * The result of a call to $(LREF getAttr) after the specified bits have been * cleared. */ static uint clrAttr( const scope void* p, uint a ) nothrow { return gc_clrAttr(cast(void*) p, a); } /// ditto static uint clrAttr(void* p, uint a) pure nothrow { return gc_clrAttr( p, a ); } extern(C): /** * Requests an aligned block of managed memory from the garbage collector. * This memory may be deleted at will with a call to free, or it may be * discarded and cleaned up automatically during a collection run. If * allocation fails, this function will call onOutOfMemory which is * expected to throw an OutOfMemoryError. * * Params: * sz = The desired allocation size in bytes. * ba = A bitmask of the attributes to set on this block. * ti = TypeInfo to describe the memory. The GC might use this information * to improve scanning for pointers or to call finalizers. * * Returns: * A reference to the allocated memory or null if insufficient memory * is available. * * $(WARN_UNINITIALIZED Allocated memory) * * Throws: * OutOfMemoryError on allocation failure. */ version (D_ProfileGC) pragma(mangle, "gc_mallocTrace") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null, string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow; else pragma(mangle, "gc_malloc") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow; /** * Requests an aligned block of managed memory from the garbage collector. * This memory may be deleted at will with a call to $(LREF free), or it may be * discarded and cleaned up automatically during a collection run. If * allocation fails, this function will call onOutOfMemory which is * expected to throw an OutOfMemoryError. * * Params: * sz = The desired allocation size in bytes. * ba = A bitmask of the attributes to set on this block. * ti = TypeInfo to describe the memory. The GC might use this information * to improve scanning for pointers or to call finalizers. * * Returns: * Information regarding the allocated memory block or BlkInfo.init on * error. * * $(WARN_UNINITIALIZED Allocated memory) * * Throws: * OutOfMemoryError on allocation failure. */