Debian Codegraph @

libphobos/libdruntime/core/memory.d

raw
1 /**
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.
6 *
7 * Using this module is not necessary in typical D code. It is mostly
8 * useful when doing low-level _memory management.
9 *
10 * Notes_to_users:
11 *
12 $(OL
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.
19 )
20
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:
27 $(OL
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
32 GC does know about.)
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,osthread)/$(REF thread_detachThis, core,thread,threadbase).)
35 )
36 )
37 )
38 *
39 * Notes_to_implementors:
40 * $(UL
41 * $(LI On POSIX systems, the signals `SIGRTMIN` and `SIGRTMIN + 1` 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).)
47 *
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.)
54 *
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.)
62 *
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.)
66 *
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.)
70 *
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.)
75 *
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.)
84 *
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.)
89 *
90 * $(LI Implementations are free to assume that GC pointers are only
91 * stored on word boundaries. Unaligned pointers may be ignored
92 * entirely.)
93 *
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.)
97 * )
98 *
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)
103 * Macros:
104 * WARN_UNINITIALIZED=$(RED Warning):
105 * $1 will be uninitialized, and may happen to hold pointers to GC memory.
106 * Consider zeroing out any uninitialized bytes which won't be immediately written to.
107 */
108
109 module core.memory;
110
111 version (ARM)
112 version = AnyARM;
113 else version (AArch64)
114 version = AnyARM;
115
116 version (iOS)
117 version = iOSDerived;
118 else version (TVOS)
119 version = iOSDerived;
120 else version (WatchOS)
121 version = iOSDerived;
122
123 private
124 {
125 extern (C) uint gc_getAttr( void* p ) pure nothrow;
126 extern (C) uint gc_setAttr( void* p, uint a ) pure nothrow;
127 extern (C) uint gc_clrAttr( void* p, uint a ) pure nothrow;
128
129 extern (C) void* gc_addrOf( void* p ) pure nothrow @nogc;
130 extern (C) size_t gc_sizeOf( void* p ) pure nothrow @nogc;
131
132 struct BlkInfo_
133 {
134 void* base;
135 size_t size;
136 uint attr;
137 }
138
139 extern (C) BlkInfo_ gc_query(return scope void* p) pure nothrow;
140 extern (C) GC.Stats gc_stats ( ) @safe nothrow @nogc;
141 extern (C) GC.ProfileStats gc_profileStats ( ) nothrow @nogc @safe;
142 }
143
144 version (CoreDoc)
145 {
146 /**
147 * The minimum size of a system page in bytes.
148 *
149 * This is a compile time, platform specific value. This value might not
150 * be accurate, since it might be possible to change this value. Whenever
151 * possible, please use $(LREF pageSize) instead, which is initialized
152 * during runtime.
153 *
154 * The minimum size is useful when the context requires a compile time known
155 * value, like the size of a static array: `ubyte[minimumPageSize] buffer`.
156 */
157 enum minimumPageSize : size_t;
158 }
159 else version (AnyARM)
160 {
161 version (iOSDerived)
162 enum size_t minimumPageSize = 16384;
163 else
164 enum size_t minimumPageSize = 4096;
165 }
166 else
167 enum size_t minimumPageSize = 4096;
168
169 ///
170 unittest
171 {
172 ubyte[minimumPageSize] buffer;
173 }
174
175 /**
176 * The size of a system page in bytes.
177 *
178 * This value is set at startup time of the application. It's safe to use
179 * early in the start process, like in shared module constructors and
180 * initialization of the D runtime itself.
181 */
182 immutable size_t pageSize;
183
184 ///
185 unittest
186 {
187 ubyte[] buffer = new ubyte[pageSize];
188 }
189
190 // The reason for this elaborated way of declaring a function is:
191 //
192 // * `pragma(crt_constructor)` is used to declare a constructor that is called by
193 // the C runtime, before C main. This allows the `pageSize` value to be used
194 // during initialization of the D runtime. This also avoids any issues with
195 // static module constructors and circular references.
196 //
197 // * `pragma(mangle)` is used because `pragma(crt_constructor)` requires a
198 // function with C linkage. To avoid any name conflict with other C symbols,
199 // standard D mangling is used.
200 //
201 // * The extra function declaration, without the body, is to be able to get the
202 // D mangling of the function without the need to hardcode the value.
203 //
204 // * The extern function declaration also has the side effect of making it
205 // impossible to manually call the function with standard syntax. This is to
206 // make it more difficult to call the function again, manually.
207 private void initialize();
208 pragma(crt_constructor)
209 pragma(mangle, initialize.mangleof)
210 private extern (C) void _initialize() @system
211 {
212 version (Posix)
213 {
214 import core.sys.posix.unistd : sysconf, _SC_PAGESIZE;
215
216 (cast() pageSize) = cast(size_t) sysconf(_SC_PAGESIZE);
217 }
218 else version (Windows)
219 {
220 import core.sys.windows.winbase : GetSystemInfo, SYSTEM_INFO;
221
222 SYSTEM_INFO si;
223 GetSystemInfo(&si);
224 (cast() pageSize) = cast(size_t) si.dwPageSize;
225 }
226 else
227 static assert(false, __FUNCTION__ ~ " is not implemented on this platform");
228 }
229
230 /**
231 * This struct encapsulates all garbage collection functionality for the D
232 * programming language.
233 */
234 struct GC
235 {
236 @disable this();
237
238 /**
239 * Aggregation of GC stats to be exposed via public API
240 */
241 static struct Stats
242 {
243 /// number of used bytes on the GC heap (might only get updated after a collection)
244 size_t usedSize;
245 /// number of free bytes on the GC heap (might only get updated after a collection)
246 size_t freeSize;
247 /// number of bytes allocated for current thread since program start
248 ulong allocatedInCurrentThread;
249 }
250
251 /**
252 * Aggregation of current profile information
253 */
254 static struct ProfileStats
255 {
256 import core.time : Duration;
257 /// total number of GC cycles
258 size_t numCollections;
259 /// total time spent doing GC
260 Duration totalCollectionTime;
261 /// total time threads were paused doing GC
262 Duration totalPauseTime;
263 /// largest time threads were paused during one GC cycle
264 Duration maxPauseTime;
265 /// largest time spent doing one GC cycle
266 Duration maxCollectionTime;
267 }
268
269 extern(C):
270
271 /**
272 * Enables automatic garbage collection behavior if collections have
273 * previously been suspended by a call to `GC.disable()`. This function is
274 * reentrant, and must be called once for every call to `GC.disable()` before
275 * automatic collections are enabled.
276 */
277 pragma(mangle, "gc_enable") static void enable() @safe nothrow pure;
278
279
280 /**
281 * Disables automatic garbage collections performed to minimize the
282 * process footprint. Collections may continue to occur in instances
283 * where the implementation deems necessary for correct program behavior,
284 * such as during an out of memory condition. This function is reentrant,
285 * but `GC.enable()` must be called once for each call to `GC.disable()`.
286 * Unlike the
287 * $(LINK2 https://dlang.org/spec/function.html#nogc-functions, `@nogc` attribute),
288 * `GC.disable()` halts
289 * collections across all threads, yet still allows GC allocations.
290 * Disabling collections eliminates GC pauses.
291 */
292 pragma(mangle, "gc_disable") static void disable() @safe nothrow pure;
293
294
295 /**
296 * Begins a full collection. While the meaning of this may change based
297 * on the garbage collector implementation, typical behavior is to scan
298 * all stack segments for roots, mark accessible memory blocks as alive,
299 * and then to reclaim free space. This action may need to suspend all
300 * running threads for at least part of the collection process.
301 */
302 pragma(mangle, "gc_collect") static void collect() @safe nothrow pure;
303
304 /**
305 * Indicates that the managed memory space be minimized by returning free
306 * physical memory to the operating system. The amount of free memory
307 * returned depends on the allocator design and on program behavior.
308 */
309 pragma(mangle, "gc_minimize") static void minimize() @safe nothrow pure;
310
311 extern(D):
312
313 /**
314 * Elements for a bit field representing memory block attributes. These
315 * are manipulated via the getAttr, setAttr, clrAttr functions.
316 */
317 enum BlkAttr : uint
318 {
319 NONE = 0b0000_0000, /// No attributes set.
320 FINALIZE = 0b0000_0001, /// Finalize the data in this block on collect.
321 NO_SCAN = 0b0000_0010, /// Do not scan through this block on collect.
322 NO_MOVE = 0b0000_0100, /// Do not move this memory block on collect.
323 /**
324 This block contains the info to allow appending.
325
326 This can be used to manually allocate arrays. Initial slice size is 0.
327
328 Note: The slice's usable size will not match the block size. Use
329 $(REF1 capacity, object) to retrieve actual usable capacity.
330
331 Example:
332 ----
333 // Allocate the underlying array.
334 int* pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE);
335 // Bind a slice. Check the slice has capacity information.
336 int[] slice = pToArray[0 .. 0];
337 assert(capacity(slice) > 0);
338 // Appending to the slice will not relocate it.
339 slice.length = 5;
340 slice ~= 1;
341 assert(slice.ptr == p);
342 ----
343 */
344 APPENDABLE = 0b0000_1000,
345
346 /**
347 This block is guaranteed to have a pointer to its base while it is
348 alive. Interior pointers can be safely ignored. This attribute is
349 useful for eliminating false pointers in very large data structures
350 and is only implemented for data structures at least a page in size.
351 */
352 NO_INTERIOR = 0b0001_0000,
353
354 STRUCTFINAL = 0b0010_0000, // the block has a finalizer for (an array of) structs
355 }
356
357
358 /**
359 * Contains aggregate information about a block of managed memory. The
360 * purpose of this struct is to support a more efficient query style in
361 * instances where detailed information is needed.
362 *
363 * base = A pointer to the base of the block in question.
364 * size = The size of the block, calculated from base.
365 * attr = Attribute bits set on the memory block.
366 */
367 alias BlkInfo = BlkInfo_;
368
369
370 /**
371 * Returns a bit field representing all block attributes set for the memory
372 * referenced by p. If p references memory not originally allocated by
373 * this garbage collector, points to the interior of a memory block, or if
374 * p is null, zero will be returned.
375 *
376 * Params:
377 * p = A pointer to the root of a valid memory block or to null.
378 *
379 * Returns:
380 * A bit field containing any bits set for the memory block referenced by
381 * p or zero on error.
382 */
383 static uint getAttr( const scope void* p ) nothrow
384 {
385 return gc_getAttr(cast(void*) p);
386 }
387
388
389 /// ditto
390 static uint getAttr(void* p) pure nothrow
391 {
392 return gc_getAttr( p );
393 }
394
395
396 /**
397 * Sets the specified bits for the memory references by p. If p references
398 * memory not originally allocated by this garbage collector, points to the
399 * interior of a memory block, or if p is null, no action will be
400 * performed.
401 *
402 * Params:
403 * p = A pointer to the root of a valid memory block or to null.
404 * a = A bit field containing any bits to set for this memory block.
405 *
406 * Returns:
407 * The result of a call to $(LREF getAttr) after the specified bits have been
408 * set.
409 */
410 static uint setAttr( const scope void* p, uint a ) nothrow
411 {
412 return gc_setAttr(cast(void*) p, a);
413 }
414
415
416 /// ditto
417 static uint setAttr(void* p, uint a) pure nothrow
418 {
419 return gc_setAttr( p, a );
420 }
421
422
423 /**
424 * Clears the specified bits for the memory references by p. If p
425 * references memory not originally allocated by this garbage collector,
426 * points to the interior of a memory block, or if p is null, no action
427 * will be performed.
428 *
429 * Params:
430 * p = A pointer to the root of a valid memory block or to null.
431 * a = A bit field containing any bits to clear for this memory block.
432 *
433 * Returns:
434 * The result of a call to $(LREF getAttr) after the specified bits have been
435 * cleared.
436 */
437 static uint clrAttr( const scope void* p, uint a ) nothrow
438 {
439 return gc_clrAttr(cast(void*) p, a);
440 }
441
442
443 /// ditto
444 static uint clrAttr(void* p, uint a) pure nothrow
445 {
446 return gc_clrAttr( p, a );
447 }
448
449 extern(C):
450
451 /**
452 * Requests an aligned block of managed memory from the garbage collector.
453 * This memory may be deleted at will with a call to free, or it may be
454 * discarded and cleaned up automatically during a collection run. If
455 * allocation fails, this function will call onOutOfMemory which is
456 * expected to throw an OutOfMemoryError.
457 *
458 * Params:
459 * sz = The desired allocation size in bytes.
460 * ba = A bitmask of the attributes to set on this block.
461 * ti = TypeInfo to describe the memory. The GC might use this information
462 * to improve scanning for pointers or to call finalizers.
463 *
464 * Returns:
465 * A reference to the allocated memory or null if insufficient memory
466 * is available.
467 *
468 * $(WARN_UNINITIALIZED Allocated memory)
469 *
470 * Throws:
471 * OutOfMemoryError on allocation failure.
472 */
473 version (D_ProfileGC)
474 pragma(mangle, "gc_mallocTrace") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null,
475 string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
476 else
477 pragma(mangle, "gc_malloc") static void* malloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow;
478
479 /**
480 * Requests an aligned block of managed memory from the garbage collector.
481 * This memory may be deleted at will with a call to $(LREF free), or it may be
482 * discarded and cleaned up automatically during a collection run. If
483 * allocation fails, this function will call onOutOfMemory which is
484 * expected to throw an OutOfMemoryError.
485 *
486 * Params:
487 * sz = The desired allocation size in bytes.
488 * ba = A bitmask of the attributes to set on this block.
489 * ti = TypeInfo to describe the memory. The GC might use this information
490 * to improve scanning for pointers or to call finalizers.
491 *
492 * Returns:
493 * Information regarding the allocated memory block or BlkInfo.init on
494 * error.
495 *
496 * $(WARN_UNINITIALIZED Allocated memory)
497 *
498 * Throws:
499 * OutOfMemoryError on allocation failure.
500 */
501 version (D_ProfileGC)
502 pragma(mangle, "gc_qallocTrace") static BlkInfo qalloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null,
503 string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
504 else
505 pragma(mangle, "gc_qalloc") static BlkInfo qalloc(size_t sz, uint ba = 0, const scope TypeInfo ti = null) pure nothrow;
506
507
508 /**
509 * Requests an aligned block of managed memory from the garbage collector,
510 * which is initialized with all bits set to zero. This memory may be
511 * deleted at will with a call to free, or it may be discarded and cleaned
512 * up automatically during a collection run. If allocation fails, this
513 * function will call onOutOfMemory which is expected to throw an
514 * OutOfMemoryError.
515 *
516 * Params:
517 * sz = The desired allocation size in bytes.
518 * ba = A bitmask of the attributes to set on this block.
519 * ti = TypeInfo to describe the memory. The GC might use this information
520 * to improve scanning for pointers or to call finalizers.
521 *
522 * Returns:
523 * A reference to the allocated memory or null if insufficient memory
524 * is available.
525 *
526 * Throws:
527 * OutOfMemoryError on allocation failure.
528 */
529 version (D_ProfileGC)
530 pragma(mangle, "gc_callocTrace") static void* calloc(size_t sz, uint ba = 0, const TypeInfo ti = null,
531 string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
532 else
533 pragma(mangle, "gc_calloc") static void* calloc(size_t sz, uint ba = 0, const TypeInfo ti = null) pure nothrow;
534
535
536 /**
537 * Extend, shrink or allocate a new block of memory keeping the contents of
538 * an existing block
539 *
540 * If `sz` is zero, the memory referenced by p will be deallocated as if
541 * by a call to `free`.
542 * If `p` is `null`, new memory will be allocated via `malloc`.
543 * If `p` is pointing to memory not allocated from the GC or to the interior
544 * of an allocated memory block, no operation is performed and null is returned.
545 *
546 * Otherwise, a new memory block of size `sz` will be allocated as if by a
547 * call to `malloc`, or the implementation may instead resize or shrink the memory
548 * block in place.
549 * The contents of the new memory block will be the same as the contents
550 * of the old memory block, up to the lesser of the new and old sizes.
551 *
552 * The caller guarantees that there are no other live pointers to the
553 * passed memory block, still it might not be freed immediately by `realloc`.
554 * The garbage collector can reclaim the memory block in a later
555 * collection if it is unused.
556 * If allocation fails, this function will throw an `OutOfMemoryError`.
557 *
558 * If `ba` is zero (the default) the attributes of the existing memory
559 * will be used for an allocation.
560 * If `ba` is not zero and no new memory is allocated, the bits in ba will
561 * replace those of the current memory block.
562 *
563 * Params:
564 * p = A pointer to the base of a valid memory block or to `null`.
565 * sz = The desired allocation size in bytes.
566 * ba = A bitmask of the BlkAttr attributes to set on this block.
567 * ti = TypeInfo to describe the memory. The GC might use this information
568 * to improve scanning for pointers or to call finalizers.
569 *
570 * Returns:
571 * A reference to the allocated memory on success or `null` if `sz` is
572 * zero or the pointer does not point to the base of an GC allocated
573 * memory block.
574 *
575 * $(WARN_UNINITIALIZED Any extra bytes past the initial size)
576 *
577 * Throws:
578 * `OutOfMemoryError` on allocation failure.
579 */
580 version (D_ProfileGC)
581 pragma(mangle, "gc_reallocTrace") static void* realloc(return scope void* p, size_t sz, uint ba = 0, const TypeInfo ti = null,
582 string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
583 else
584 pragma(mangle, "gc_realloc") static void* realloc(return scope void* p, size_t sz, uint ba = 0, const TypeInfo ti = null) pure nothrow;
585
586 // https://issues.dlang.org/show_bug.cgi?id=13111
587 ///
588 version (OnlyLowMemUnittests) {} else // Test needs a lot of RAM
589 unittest
590 {
591 enum size1 = 1 << 11 + 1; // page in large object pool
592 enum size2 = 1 << 22 + 1; // larger than large object pool size
593
594 auto data1 = cast(ubyte*)GC.calloc(size1);
595 auto data2 = cast(ubyte*)GC.realloc(data1, size2);
596
597 GC.BlkInfo info = GC.query(data2);
598 assert(info.size >= size2);
599 }
600
601
602 /**
603 * Requests that the managed memory block referenced by p be extended in
604 * place by at least mx bytes, with a desired extension of sz bytes. If an
605 * extension of the required size is not possible or if p references memory
606 * not originally allocated by this garbage collector, no action will be
607 * taken.
608 *
609 * Params:
610 * p = A pointer to the root of a valid memory block or to null.
611 * mx = The minimum extension size in bytes.
612 * sz = The desired extension size in bytes.
613 * ti = TypeInfo to describe the full memory block. The GC might use
614 * this information to improve scanning for pointers or to
615 * call finalizers.
616 *
617 * Returns:
618 * The size in bytes of the extended memory block referenced by p or zero
619 * if no extension occurred.
620 *
621 * $(WARN_UNINITIALIZED Any extension bytes)
622 *
623 * Note:
624 * Extend may also be used to extend slices (or memory blocks with
625 * $(LREF APPENDABLE) info). However, use the return value only
626 * as an indicator of success. $(REF1 capacity, object) should be used to
627 * retrieve actual usable slice capacity.
628 */
629 version (D_ProfileGC)
630 pragma(mangle, "gc_extendTrace") static size_t extend(void* p, size_t mx, size_t sz, const TypeInfo ti = null,
631 string file = __FILE__, int line = __LINE__, string func = __FUNCTION__) pure nothrow;
632 else
633 pragma(mangle, "gc_extend") static size_t extend(void* p, size_t mx, size_t sz, const TypeInfo ti = null) pure nothrow;
634
635 /// Standard extending
636 unittest
637 {
638 size_t size = 1000;
639 int* p = cast(int*)GC.malloc(size * int.sizeof, GC.BlkAttr.NO_SCAN);
640
641 //Try to extend the allocated data by 1000 elements, preferred 2000.
642 size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
643 if (u != 0)
644 size = u / int.sizeof;
645 }
646 /// slice extending
647 unittest
648 {
649 int[] slice = new int[](1000);
650 int* p = slice.ptr;
651
652 //Check we have access to capacity before attempting the extend
653 if (slice.capacity)
654 {
655 //Try to extend slice by 1000 elements, preferred 2000.
656 size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
657 if (u != 0)
658 {
659 slice.length = slice.capacity;
660 assert(slice.length >= 2000);
661 }
662 }
663 }
664
665
666 /**
667 * Requests that at least sz bytes of memory be obtained from the operating
668 * system and marked as free.
669 *
670 * Params:
671 * sz = The desired size in bytes.
672 *
673 * Returns:
674 * The actual number of bytes reserved or zero on error.
675 */
676 pragma(mangle, "gc_reserve") static size_t reserve(size_t sz) nothrow pure;
677
678
679 /**
680 * Deallocates the memory referenced by p. If p is null, no action occurs.
681 * If p references memory not originally allocated by this garbage
682 * collector, if p points to the interior of a memory block, or if this
683 * method is called from a finalizer, no action will be taken. The block
684 * will not be finalized regardless of whether the $(LREF FINALIZE) attribute is
685 * set. If finalization is desired, call $(REF1 destroy, object) prior to `GC.free`.
686 *
687 * Params:
688 * p = A pointer to the root of a valid memory block or to null.
689 */
690 pragma(mangle, "gc_free") static void free(void* p) pure nothrow @nogc;
691
692 extern(D):
693
694 /**
695 * Returns the base address of the memory block containing p. This value
696 * is useful to determine whether p is an interior pointer, and the result
697 * may be passed to routines such as sizeOf which may otherwise fail. If p
698 * references memory not originally allocated by this garbage collector, if
699 * p is null, or if the garbage collector does not support this operation,
700 * null will be returned.
701 *
702 * Params:
703 * p = A pointer to the root or the interior of a valid memory block or to
704 * null.
705 *
706 * Returns:
707 * The base address of the memory block referenced by p or null on error.
708 */
709 static inout(void)* addrOf( inout(void)* p ) nothrow @nogc pure @trusted
710 {
711 return cast(inout(void)*)gc_addrOf(cast(void*)p);
712 }
713
714 /// ditto
715 static void* addrOf(void* p) pure nothrow @nogc @trusted
716 {
717 return gc_addrOf(p);
718 }
719
720 /**
721 * Returns the true size of the memory block referenced by p. This value
722 * represents the maximum number of bytes for which a call to $(LREF realloc) may
723 * resize the existing block in place. If p references memory not
724 * originally allocated by this garbage collector, points to the interior
725 * of a memory block, or if p is null, zero will be returned.
726 *
727 * Params:
728 * p = A pointer to the root of a valid memory block or to null.
729 *
730 * Returns:
731 * The size in bytes of the memory block referenced by p or zero on error.
732 */
733 static size_t sizeOf( const scope void* p ) nothrow @nogc /* FIXME pure */
734 {
735 return gc_sizeOf(cast(void*)p);
736 }
737
738
739 /// ditto
740 static size_t sizeOf(void* p) pure nothrow @nogc
741 {
742 return gc_sizeOf( p );
743 }
744
745 // verify that the reallocation doesn't leave the size cache in a wrong state
746 unittest
747 {
748 auto data = cast(int*)realloc(null, 4096);
749 size_t size = GC.sizeOf(data);
750 assert(size >= 4096);
751 data = cast(int*)GC.realloc(data, 4100);
752 size = GC.sizeOf(data);
753 assert(size >= 4100);
754 }
755
756 /**
757 * Returns aggregate information about the memory block containing p. If p
758 * references memory not originally allocated by this garbage collector, if
759 * p is null, or if the garbage collector does not support this operation,
760 * BlkInfo.init will be returned. Typically, support for this operation
761 * is dependent on support for addrOf.
762 *
763 * Params:
764 * p = A pointer to the root or the interior of a valid memory block or to
765 * null.
766 *
767 * Returns:
768 * Information regarding the memory block referenced by p or BlkInfo.init
769 * on error.
770 */
771 static BlkInfo query(return scope const void* p) nothrow
772 {
773 return gc_query(cast(void*)p);
774 }
775
776
777 /// ditto
778 static BlkInfo query(return scope void* p) pure nothrow
779 {
780 return gc_query( p );
781 }
782
783 /**
784 * Returns runtime stats for currently active GC implementation
785 * See `core.memory.GC.Stats` for list of available metrics.
786 */
787 static Stats stats() @safe nothrow @nogc
788 {
789 return gc_stats();
790 }
791
792 /**
793 * Returns runtime profile stats for currently active GC implementation
794 * See `core.memory.GC.ProfileStats` for list of available metrics.
795 */
796 static ProfileStats profileStats() nothrow @nogc @safe
797 {
798 return gc_profileStats();
799 }
800
801 extern(C):
802
803 /**
804 * Adds an internal root pointing to the GC memory block referenced by p.
805 * As a result, the block referenced by p itself and any blocks accessible
806 * via it will be considered live until the root is removed again.
807 *
808 * If p is null, no operation is performed.
809 *
810 * Params:
811 * p = A pointer into a GC-managed memory block or null.
812 *
813 * Example:
814 * ---
815 * // Typical C-style callback mechanism; the passed function
816 * // is invoked with the user-supplied context pointer at a
817 * // later point.
818 * extern(C) void addCallback(void function(void*), void*);
819 *
820 * // Allocate an object on the GC heap (this would usually be
821 * // some application-specific context data).
822 * auto context = new Object;
823 *
824 * // Make sure that it is not collected even if it is no
825 * // longer referenced from D code (stack, GC heap, …).
826 * GC.addRoot(cast(void*)context);
827 *
828 * // Also ensure that a moving collector does not relocate
829 * // the object.
830 * GC.setAttr(cast(void*)context, GC.BlkAttr.NO_MOVE);
831 *
832 * // Now context can be safely passed to the C library.
833 * addCallback(&myHandler, cast(void*)context);
834 *
835 * extern(C) void myHandler(void* ctx)
836 * {
837 * // Assuming that the callback is invoked only once, the
838 * // added root can be removed again now to allow the GC
839 * // to collect it later.
840 * GC.removeRoot(ctx);
841 * GC.clrAttr(ctx, GC.BlkAttr.NO_MOVE);
842 *
843 * auto context = cast(Object)ctx;
844 * // Use context here…
845 * }
846 * ---
847 */
848 pragma(mangle, "gc_addRoot") static void addRoot(const void* p) nothrow @nogc pure;
849
850
851 /**
852 * Removes the memory block referenced by p from an internal list of roots
853 * to be scanned during a collection. If p is null or is not a value
854 * previously passed to addRoot() then no operation is performed.
855 *
856 * Params:
857 * p = A pointer into a GC-managed memory block or null.
858 */
859 pragma(mangle, "gc_removeRoot") static void removeRoot(const void* p) nothrow @nogc pure;
860
861
862 /**
863 * Adds $(D p[0 .. sz]) to the list of memory ranges to be scanned for
864 * pointers during a collection. If p is null, no operation is performed.
865 *
866 * Note that $(D p[0 .. sz]) is treated as an opaque range of memory assumed
867 * to be suitably managed by the caller. In particular, if p points into a
868 * GC-managed memory block, addRange does $(I not) mark this block as live.
869 *
870 * Params:
871 * p = A pointer to a valid memory address or to null.
872 * sz = The size in bytes of the block to add. If sz is zero then the
873 * no operation will occur. If p is null then sz must be zero.
874 * ti = TypeInfo to describe the memory. The GC might use this information
875 * to improve scanning for pointers or to call finalizers
876 *
877 * Example:
878 * ---
879 * // Allocate a piece of memory on the C heap.
880 * enum size = 1_000;
881 * auto rawMemory = core.stdc.stdlib.malloc(size);
882 *
883 * // Add it as a GC range.
884 * GC.addRange(rawMemory, size);
885 *
886 * // Now, pointers to GC-managed memory stored in
887 * // rawMemory will be recognized on collection.
888 * ---
889 */
890 pragma(mangle, "gc_addRange")
891 static void addRange(const void* p, size_t sz, const TypeInfo ti = null) @nogc nothrow pure;
892
893
894 /**
895 * Removes the memory range starting at p from an internal list of ranges
896 * to be scanned during a collection. If p is null or does not represent
897 * a value previously passed to addRange() then no operation is
898 * performed.
899 *
900 * Params:
901 * p = A pointer to a valid memory address or to null.
902 */
903 pragma(mangle, "gc_removeRange") static void removeRange(const void* p) nothrow @nogc pure;
904
905
906 /**
907 * Runs any finalizer that is located in address range of the
908 * given code segment. This is used before unloading shared
909 * libraries. All matching objects which have a finalizer in this
910 * code segment are assumed to be dead, using them while or after
911 * calling this method has undefined behavior.
912 *
913 * Params:
914 * segment = address range of a code segment.
915 */
916 pragma(mangle, "gc_runFinalizers") static void runFinalizers(const scope void[] segment);
917
918 /**
919 * Queries the GC whether the current thread is running object finalization
920 * as part of a GC collection, or an explicit call to runFinalizers.
921 *
922 * As some GC implementations (such as the current conservative one) don't
923 * support GC memory allocation during object finalization, this function
924 * can be used to guard against such programming errors.
925 *
926 * Returns:
927 * true if the current thread is in a finalizer, a destructor invoked by
928 * the GC.
929 */
930 pragma(mangle, "gc_inFinalizer") static bool inFinalizer() nothrow @nogc @safe;
931
932 ///
933 @safe nothrow @nogc unittest
934 {
935 // Only code called from a destructor is executed during finalization.
936 assert(!GC.inFinalizer);
937 }
938
939 ///
940 unittest
941 {
942 enum Outcome
943 {
944 notCalled,
945 calledManually,
946 calledFromDruntime
947 }
948
949 static class Resource
950 {
951 static Outcome outcome;
952
953 this()
954 {
955 outcome = Outcome.notCalled;
956 }
957
958 ~this()
959 {
960 if (GC.inFinalizer)
961 {
962 outcome = Outcome.calledFromDruntime;
963
964 import core.exception : InvalidMemoryOperationError;
965 try
966 {
967 /*
968 * Presently, allocating GC memory during finalization
969 * is forbidden and leads to
970 * `InvalidMemoryOperationError` being thrown.
971 *
972 * `GC.inFinalizer` can be used to guard against
973 * programming erros such as these and is also a more
974 * efficient way to verify whether a destructor was
975 * invoked by the GC.
976 */
977 cast(void) GC.malloc(1);
978 assert(false);
979 }
980 catch (InvalidMemoryOperationError e)
981 {
982 return;
983 }
984 assert(false);
985 }
986 else
987 outcome = Outcome.calledManually;
988 }
989 }
990
991 static void createGarbage()
992 {
993 auto r = new Resource;
994 r = null;
995 }
996
997 assert(Resource.outcome == Outcome.notCalled);
998 createGarbage();
999 GC.collect;
1000 assert(
1001 Resource.outcome == Outcome.notCalled ||
1002 Resource.outcome == Outcome.calledFromDruntime);
1003
1004 auto r = new Resource;
1005 GC.runFinalizers((cast(const void*)typeid(Resource).destructor)[0..1]);
1006 assert(Resource.outcome == Outcome.calledFromDruntime);
1007 Resource.outcome = Outcome.notCalled;
1008
1009 debug(MEMSTOMP) {} else
1010 {
1011 // assume Resource data is still available
1012 r.destroy;
1013 assert(Resource.outcome == Outcome.notCalled);
1014 }
1015
1016 r = new Resource;
1017 assert(Resource.outcome == Outcome.notCalled);
1018 r.destroy;
1019 assert(Resource.outcome == Outcome.calledManually);
1020 }
1021
1022 /**
1023 * Returns the number of bytes allocated for the current thread
1024 * since program start. It is the same as
1025 * GC.stats().allocatedInCurrentThread, but faster.
1026 */
1027 pragma(mangle, "gc_allocatedInCurrentThread") static ulong allocatedInCurrentThread() nothrow;
1028
1029 /// Using allocatedInCurrentThread
1030 nothrow unittest
1031 {
1032 ulong currentlyAllocated = GC.allocatedInCurrentThread();
1033 struct DataStruct
1034 {
1035 long l1;
1036 long l2;
1037 long l3;
1038 long l4;
1039 }
1040 DataStruct* unused = new DataStruct;
1041 assert(GC.allocatedInCurrentThread() == currentlyAllocated + 32);
1042 assert(GC.stats().allocatedInCurrentThread == currentlyAllocated + 32);
1043 }
1044 }
1045
1046 /**
1047 * Pure variants of C's memory allocation functions `malloc`, `calloc`, and
1048 * `realloc` and deallocation function `free`.
1049 *
1050 * UNIX 98 requires that errno be set to ENOMEM upon failure.
1051 * Purity is achieved by saving and restoring the value of `errno`, thus
1052 * behaving as if it were never changed.
1053 *
1054 * See_Also:
1055 * $(LINK2 https://dlang.org/spec/function.html#pure-functions, D's rules for purity),
1056 * which allow for memory allocation under specific circumstances.
1057 */
1058 void* pureMalloc()(size_t size) @trusted pure @nogc nothrow
1059 {
1060 const errnosave = fakePureErrno;
1061 void* ret = fakePureMalloc(size);
1062 fakePureErrno = errnosave;
1063 return ret;
1064 }
1065 /// ditto
1066 void* pureCalloc()(size_t nmemb, size_t size) @trusted pure @nogc nothrow
1067 {
1068 const errnosave = fakePureErrno;
1069 void* ret = fakePureCalloc(nmemb, size);
1070 fakePureErrno = errnosave;
1071 return ret;
1072 }
1073 /// ditto
1074 void* pureRealloc()(void* ptr, size_t size) @system pure @nogc nothrow
1075 {
1076 const errnosave = fakePureErrno;
1077 void* ret = fakePureRealloc(ptr, size);
1078 fakePureErrno = errnosave;
1079 return ret;
1080 }
1081
1082 /// ditto
1083 void pureFree()(void* ptr) @system pure @nogc nothrow
1084 {
1085 version (Posix)
1086 {
1087 // POSIX free doesn't set errno
1088 fakePureFree(ptr);
1089 }
1090 else
1091 {
1092 const errnosave = fakePureErrno;
1093 fakePureFree(ptr);
1094 fakePureErrno = errnosave;
1095 }
1096 }
1097
1098 ///
1099 @system pure nothrow @nogc unittest
1100 {
1101 ubyte[] fun(size_t n) pure
1102 {
1103 void* p = pureMalloc(n);
1104 p !is null || n == 0 || assert(0);
1105 scope(failure) p = pureRealloc(p, 0);
1106 p = pureRealloc(p, n *= 2);
1107 p !is null || n == 0 || assert(0);
1108 return cast(ubyte[]) p[0 .. n];
1109 }
1110
1111 auto buf = fun(100);
1112 assert(buf.length == 200);
1113 pureFree(buf.ptr);
1114 }
1115
1116 @system pure nothrow @nogc unittest
1117 {
1118 const int errno = fakePureErrno();
1119
1120 void* x = pureMalloc(10); // normal allocation
1121 assert(errno == fakePureErrno()); // errno shouldn't change
1122 assert(x !is null); // allocation should succeed
1123
1124 x = pureRealloc(x, 10); // normal reallocation
1125 assert(errno == fakePureErrno()); // errno shouldn't change
1126 assert(x !is null); // allocation should succeed
1127
1128 fakePureFree(x);
1129
1130 void* y = pureCalloc(10, 1); // normal zeroed allocation
1131 assert(errno == fakePureErrno()); // errno shouldn't change
1132 assert(y !is null); // allocation should succeed
1133
1134 fakePureFree(y);
1135
1136 // Workaround bug in glibc 2.26
1137 // See also: https://issues.dlang.org/show_bug.cgi?id=17956
1138 void* z = pureMalloc(size_t.max & ~255); // won't affect `errno`
1139 assert(errno == fakePureErrno()); // errno shouldn't change
1140 assert(z is null);
1141 }
1142
1143 // locally purified for internal use here only
1144
1145 static import core.stdc.errno;
1146 static if (__traits(getOverloads, core.stdc.errno, "errno").length == 1
1147 && __traits(getLinkage, core.stdc.errno.errno) == "C")
1148 {
1149 extern(C) pragma(mangle, __traits(identifier, core.stdc.errno.errno))
1150 private ref int fakePureErrno() @nogc nothrow pure @system;
1151 }
1152 else
1153 {
1154 extern(C) private @nogc nothrow pure @system
1155 {
1156 pragma(mangle, __traits(identifier, core.stdc.errno.getErrno))
1157 @property int fakePureErrno();
1158
1159 pragma(mangle, __traits(identifier, core.stdc.errno.setErrno))
1160 @property int fakePureErrno(int);
1161 }
1162 }
1163
1164 version (D_BetterC) {}
1165 else // TODO: remove this function after Phobos no longer needs it.
1166 extern (C) private @system @nogc nothrow
1167 {
1168 ref int fakePureErrnoImpl()
1169 {
1170 import core.stdc.errno : errno;
1171 return errno();
1172 }
1173 }
1174
1175 extern (C) private pure @system @nogc nothrow
1176 {
1177 pragma(mangle, "malloc") void* fakePureMalloc(size_t);
1178 pragma(mangle, "calloc") void* fakePureCalloc(size_t nmemb, size_t size);
1179 pragma(mangle, "realloc") void* fakePureRealloc(void* ptr, size_t size);
1180
1181 pragma(mangle, "free") void fakePureFree(void* ptr);
1182 }
1183
1184 /**
1185 Destroys and then deallocates an object.
1186
1187 In detail, `__delete(x)` returns with no effect if `x` is `null`. Otherwise, it
1188 performs the following actions in sequence:
1189 $(UL
1190 $(LI
1191 Calls the destructor `~this()` for the object referred to by `x`
1192 (if `x` is a class or interface reference) or
1193 for the object pointed to by `x` (if `x` is a pointer to a `struct`).
1194 Arrays of structs call the destructor, if defined, for each element in the array.
1195 If no destructor is defined, this step has no effect.
1196 )
1197 $(LI
1198 Frees the memory allocated for `x`. If `x` is a reference to a class
1199 or interface, the memory allocated for the underlying instance is freed. If `x` is
1200 a pointer, the memory allocated for the pointed-to object is freed. If `x` is a
1201 built-in array, the memory allocated for the array is freed.
1202 If `x` does not refer to memory previously allocated with `new` (or the lower-level
1203 equivalents in the GC API), the behavior is undefined.
1204 )
1205 $(LI
1206 Lastly, `x` is set to `null`. Any attempt to read or write the freed memory via
1207 other references will result in undefined behavior.
1208 )
1209 )
1210
1211 Note: Users should prefer $(REF1 destroy, object) to explicitly finalize objects,
1212 and only resort to $(LREF __delete) when $(REF1 destroy, object)
1213 wouldn't be a feasible option.
1214
1215 Params:
1216 x = aggregate object that should be destroyed
1217
1218 See_Also: $(REF1 destroy, object), $(LREF GC.free)
1219
1220 History:
1221
1222 The `delete` keyword allowed to free GC-allocated memory.
1223 As this is inherently not `@safe`, it has been deprecated.
1224 This function has been added to provide an easy transition from `delete`.
1225 It performs the same functionality as the former `delete` keyword.
1226 */
1227 void __delete(T)(ref T x) @system
1228 {
1229 static void _destructRecurse(S)(ref S s)
1230 if (is(S == struct))
1231 {
1232 static if (__traits(hasMember, S, "__xdtor") &&
1233 // Bugzilla 14746: Check that it's the exact member of S.
1234 __traits(isSame, S, __traits(parent, s.__xdtor)))
1235 s.__xdtor();
1236 }
1237
1238 // See also: https://github.com/dlang/dmd/blob/v2.078.0/src/dmd/e2ir.d#L3886
1239 static if (is(T == interface))
1240 {
1241 .object.destroy(x);
1242 }
1243 else static if (is(T == class))
1244 {
1245 .object.destroy(x);
1246 }
1247 else static if (is(T == U*, U))
1248 {
1249 static if (is(U == struct))
1250 {
1251 if (x)
1252 _destructRecurse(*x);
1253 }
1254 }
1255 else static if (is(T : E[], E))
1256 {
1257 static if (is(E == struct))
1258 {
1259 foreach_reverse (ref e; x)
1260 _destructRecurse(e);
1261 }
1262 }
1263 else
1264 {
1265 static assert(0, "It is not possible to delete: `" ~ T.stringof ~ "`");
1266 }
1267
1268 static if (is(T == interface) ||
1269 is(T == class) ||
1270 is(T == U2*, U2))
1271 {
1272 GC.free(GC.addrOf(cast(void*) x));
1273 x = null;
1274 }
1275 else static if (is(T : E2[], E2))
1276 {
1277 GC.free(GC.addrOf(cast(void*) x.ptr));
1278 x = null;
1279 }
1280 }
1281
1282 /// Deleting classes
1283 unittest
1284 {
1285 bool dtorCalled;
1286 class B
1287 {
1288 int test;
1289 ~this()
1290 {
1291 dtorCalled = true;
1292 }
1293 }
1294 B b = new B();
1295 B a = b;
1296 b.test = 10;
1297
1298 assert(GC.addrOf(cast(void*) b) != null);
1299 __delete(b);
1300 assert(b is null);
1301 assert(dtorCalled);
1302 assert(GC.addrOf(cast(void*) b) == null);
1303 // but be careful, a still points to it
1304 assert(a !is null);
1305 assert(GC.addrOf(cast(void*) a) == null); // but not a valid GC pointer
1306 }
1307
1308 /// Deleting interfaces
1309 unittest
1310 {
1311 bool dtorCalled;
1312 interface A
1313 {
1314 int quack();
1315 }
1316 class B : A
1317 {
1318 int a;
1319 int quack()
1320 {
1321 a++;
1322 return a;
1323 }
1324 ~this()
1325 {
1326 dtorCalled = true;
1327 }
1328 }
1329 A a = new B();
1330 a.quack();
1331
1332 assert(GC.addrOf(cast(void*) a) != null);
1333 __delete(a);
1334 assert(a is null);
1335 assert(dtorCalled);
1336 assert(GC.addrOf(cast(void*) a) == null);
1337 }
1338
1339 /// Deleting structs
1340 unittest
1341 {
1342 bool dtorCalled;
1343 struct A
1344 {
1345 string test;
1346 ~this()
1347 {
1348 dtorCalled = true;
1349 }
1350 }
1351 auto a = new A("foo");
1352
1353 assert(GC.addrOf(cast(void*) a) != null);
1354 __delete(a);
1355 assert(a is null);
1356 assert(dtorCalled);
1357 assert(GC.addrOf(cast(void*) a) == null);
1358
1359 // https://issues.dlang.org/show_bug.cgi?id=22779
1360 A *aptr;
1361 __delete(aptr);
1362 }
1363
1364 /// Deleting arrays
1365 unittest
1366 {
1367 int[] a = [1, 2, 3];
1368 auto b = a;
1369
1370 assert(GC.addrOf(b.ptr) != null);
1371 __delete(b);
1372 assert(b is null);
1373 assert(GC.addrOf(b.ptr) == null);
1374 // but be careful, a still points to it
1375 assert(a !is null);
1376 assert(GC.addrOf(a.ptr) == null); // but not a valid GC pointer
1377 }
1378
1379 /// Deleting arrays of structs
1380 unittest
1381 {
1382 int dtorCalled;
1383 struct A
1384 {
1385 int a;
1386 ~this()
1387 {
1388 assert(dtorCalled == a);
1389 dtorCalled++;
1390 }
1391 }
1392 auto arr = [A(1), A(2), A(3)];
1393 arr[0].a = 2;
1394 arr[1].a = 1;
1395 arr[2].a = 0;
1396
1397 assert(GC.addrOf(arr.ptr) != null);
1398 __delete(arr);
1399 assert(dtorCalled == 3);
1400 assert(GC.addrOf(arr.ptr) == null);
1401 }
1402
1403 // Deleting raw memory
1404 unittest
1405 {
1406 import core.memory : GC;
1407 auto a = GC.malloc(5);
1408 assert(GC.addrOf(cast(void*) a) != null);
1409 __delete(a);
1410 assert(a is null);
1411 assert(GC.addrOf(cast(void*) a) == null);
1412 }
1413
1414 // __delete returns with no effect if x is null
1415 unittest
1416 {
1417 Object x = null;
1418 __delete(x);
1419
1420 struct S { ~this() { } }
1421 class C { }
1422 interface I { }
1423
1424 int[] a; __delete(a);
1425 S[] as; __delete(as);
1426 C c; __delete(c);
1427 I i; __delete(i);
1428 C* pc = &c; __delete(*pc);
1429 I* pi = &i; __delete(*pi);
1430 int* pint; __delete(pint);
1431 S* ps; __delete(ps);
1432 }
1433
1434 // https://issues.dlang.org/show_bug.cgi?id=19092
1435 unittest
1436 {
1437 const(int)[] x = [1, 2, 3];
1438 assert(GC.addrOf(x.ptr) != null);
1439 __delete(x);
1440 assert(x is null);
1441 assert(GC.addrOf(x.ptr) == null);
1442
1443 immutable(int)[] y = [1, 2, 3];
1444 assert(GC.addrOf(y.ptr) != null);
1445 __delete(y);
1446 assert(y is null);
1447 assert(GC.addrOf(y.ptr) == null);
1448 }
1449
1450 // test realloc behaviour
1451 unittest
1452 {
1453 static void set(int* p, size_t size)
1454 {
1455 foreach (i; 0 .. size)
1456 *p++ = cast(int) i;
1457 }
1458 static void verify(int* p, size_t size)
1459 {
1460 foreach (i; 0 .. size)
1461 assert(*p++ == i);
1462 }
1463 static void test(size_t memsize)
1464 {
1465 int* p = cast(int*) GC.malloc(memsize * int.sizeof);
1466 assert(p);
1467 set(p, memsize);
1468 verify(p, memsize);
1469
1470 int* q = cast(int*) GC.realloc(p + 4, 2 * memsize * int.sizeof);
1471 assert(q == null);
1472
1473 q = cast(int*) GC.realloc(p + memsize / 2, 2 * memsize * int.sizeof);
1474 assert(q == null);
1475
1476 q = cast(int*) GC.realloc(p + memsize - 1, 2 * memsize * int.sizeof);
1477 assert(q == null);
1478
1479 int* r = cast(int*) GC.realloc(p, 5 * memsize * int.sizeof);
1480 verify(r, memsize);
1481 set(r, 5 * memsize);
1482
1483 int* s = cast(int*) GC.realloc(r, 2 * memsize * int.sizeof);
1484 verify(s, 2 * memsize);
1485
1486 assert(GC.realloc(s, 0) == null); // free
1487 assert(GC.addrOf(p) == null);
1488 }
1489
1490 test(16);
1491 test(200);
1492 test(800); // spans large and small pools
1493 test(1200);
1494 test(8000);
1495
1496 void* p = GC.malloc(100);
1497 assert(GC.realloc(&p, 50) == null); // non-GC pointer
1498 }
1499
1500 // test GC.profileStats
1501 unittest
1502 {
1503 auto stats = GC.profileStats();
1504 GC.collect();
1505 auto nstats = GC.profileStats();
1506 assert(nstats.numCollections > stats.numCollections);
1507 }
1508
1509 // in rt.lifetime:
1510 private extern (C) void* _d_newitemU(scope const TypeInfo _ti) @system pure nothrow;
1511
1512 /**
1513 Moves a value to a new GC allocation.
1514
1515 Params:
1516 value = Value to be moved. If the argument is an lvalue and a struct with a
1517 destructor or postblit, it will be reset to its `.init` value.
1518
1519 Returns:
1520 A pointer to the new GC-allocated value.
1521 */
1522 T* moveToGC(T)(auto ref T value)
1523 {
1524 static T* doIt(ref T value) @trusted
1525 {
1526 import core.lifetime : moveEmplace;
1527 auto mem = cast(T*) _d_newitemU(typeid(T)); // allocate but don't initialize
1528 moveEmplace(value, *mem);
1529 return mem;
1530 }
1531
1532 return doIt(value); // T dtor might be @system
1533 }
1534
1535 ///
1536 @safe pure nothrow unittest
1537 {
1538 struct S
1539 {
1540 int x;
1541 this(this) @disable;
1542 ~this() @safe pure nothrow @nogc {}
1543 }
1544
1545 S* p;
1546
1547 // rvalue
1548 p = moveToGC(S(123));
1549 assert(p.x == 123);
1550
1551 // lvalue
1552 auto lval = S(456);
1553 p = moveToGC(lval);
1554 assert(p.x == 456);
1555 assert(lval.x == 0);
1556 }
1557
1558 // @system dtor
1559 unittest
1560 {
1561 struct S
1562 {
1563 int x;
1564 ~this() @system {}
1565 }
1566
1567 // lvalue case is @safe, ref param isn't destructed
1568 static assert(__traits(compiles, (ref S lval) @safe { moveToGC(lval); }));
1569
1570 // rvalue case is @system, value param is destructed
1571 static assert(!__traits(compiles, () @safe { moveToGC(S(0)); }));
1572 }