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)/$(REF thread_detachThis, core,thread).)
35 )
36 )
37 )
38 *
39 * Notes_to_implementors:
40 * $(UL
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).)
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 */
104
105 module core.memory;
106
107
108 private
109 {
110 extern (C) void gc_init();
111 extern (C) void gc_term();
112
113 extern (C) void gc_enable() nothrow;
114 extern (C) void gc_disable() nothrow;
115 extern (C) void gc_collect() nothrow;
116 extern (C) void gc_minimize() nothrow;
117
118 extern (C) uint gc_getAttr( void* p ) pure nothrow;
119 extern (C) uint gc_setAttr( void* p, uint a ) pure nothrow;
120 extern (C) uint gc_clrAttr( void* p, uint a ) pure nothrow;
121
122 extern (C) void* gc_malloc( size_t sz, uint ba = 0, const TypeInfo = null ) pure nothrow;
123 extern (C) void* gc_calloc( size_t sz, uint ba = 0, const TypeInfo = null ) pure nothrow;
124 extern (C) BlkInfo_ gc_qalloc( size_t sz, uint ba = 0, const TypeInfo = null ) pure nothrow;
125 extern (C) void* gc_realloc( void* p, size_t sz, uint ba = 0, const TypeInfo = null ) pure nothrow;
126 extern (C) size_t gc_extend( void* p, size_t mx, size_t sz, const TypeInfo = null ) pure nothrow;
127 extern (C) size_t gc_reserve( size_t sz ) nothrow;
128 extern (C) void gc_free( void* p ) pure nothrow;
129
130 extern (C) void* gc_addrOf( void* p ) pure nothrow;
131 extern (C) size_t gc_sizeOf( void* p ) pure nothrow;
132
133 struct BlkInfo_
134 {
135 void* base;
136 size_t size;
137 uint attr;
138 }
139
140 extern (C) BlkInfo_ gc_query( void* p ) pure nothrow;
141 extern (C) GC.Stats gc_stats ( ) nothrow @nogc;
142
143 extern (C) void gc_addRoot( in void* p ) nothrow @nogc;
144 extern (C) void gc_addRange( in void* p, size_t sz, const TypeInfo ti = null ) nothrow @nogc;
145
146 extern (C) void gc_removeRoot( in void* p ) nothrow @nogc;
147 extern (C) void gc_removeRange( in void* p ) nothrow @nogc;
148 extern (C) void gc_runFinalizers( in void[] segment );
149
150 package extern (C) bool gc_inFinalizer();
151 }
152
153
154 /**
155 * This struct encapsulates all garbage collection functionality for the D
156 * programming language.
157 */
158 struct GC
159 {
160 @disable this();
161
162 /**
163 * Aggregation of GC stats to be exposed via public API
164 */
165 static struct Stats
166 {
167 /// number of used bytes on the GC heap (might only get updated after a collection)
168 size_t usedSize;
169 /// number of free bytes on the GC heap (might only get updated after a collection)
170 size_t freeSize;
171 }
172
173 /**
174 * Enables automatic garbage collection behavior if collections have
175 * previously been suspended by a call to disable. This function is
176 * reentrant, and must be called once for every call to disable before
177 * automatic collections are enabled.
178 */
enableGC179 static void enable() nothrow /* FIXME pure */
180 {
181 gc_enable();
182 }
183
184
185 /**
186 * Disables automatic garbage collections performed to minimize the
187 * process footprint. Collections may continue to occur in instances
188 * where the implementation deems necessary for correct program behavior,
189 * such as during an out of memory condition. This function is reentrant,
190 * but enable must be called once for each call to disable.
191 */
disableGC192 static void disable() nothrow /* FIXME pure */
193 {
194 gc_disable();
195 }
196
197
198 /**
199 * Begins a full collection. While the meaning of this may change based
200 * on the garbage collector implementation, typical behavior is to scan
201 * all stack segments for roots, mark accessible memory blocks as alive,
202 * and then to reclaim free space. This action may need to suspend all
203 * running threads for at least part of the collection process.
204 */
collectGC205 static void collect() nothrow /* FIXME pure */
206 {
207 gc_collect();
208 }
209
210 /**
211 * Indicates that the managed memory space be minimized by returning free
212 * physical memory to the operating system. The amount of free memory
213 * returned depends on the allocator design and on program behavior.
214 */
minimizeGC215 static void minimize() nothrow /* FIXME pure */
216 {
217 gc_minimize();
218 }
219
220
221 /**
222 * Elements for a bit field representing memory block attributes. These
223 * are manipulated via the getAttr, setAttr, clrAttr functions.
224 */
225 enum BlkAttr : uint
226 {
227 NONE = 0b0000_0000, /// No attributes set.
228 FINALIZE = 0b0000_0001, /// Finalize the data in this block on collect.
229 NO_SCAN = 0b0000_0010, /// Do not scan through this block on collect.
230 NO_MOVE = 0b0000_0100, /// Do not move this memory block on collect.
231 /**
232 This block contains the info to allow appending.
233
234 This can be used to manually allocate arrays. Initial slice size is 0.
235
236 Note: The slice's usable size will not match the block size. Use
237 $(LREF capacity) to retrieve actual usable capacity.
238
239 Example:
240 ----
241 // Allocate the underlying array.
242 int* pToArray = cast(int*)GC.malloc(10 * int.sizeof, GC.BlkAttr.NO_SCAN | GC.BlkAttr.APPENDABLE);
243 // Bind a slice. Check the slice has capacity information.
244 int[] slice = pToArray[0 .. 0];
245 assert(capacity(slice) > 0);
246 // Appending to the slice will not relocate it.
247 slice.length = 5;
248 slice ~= 1;
249 assert(slice.ptr == p);
250 ----
251 */
252 APPENDABLE = 0b0000_1000,
253
254 /**
255 This block is guaranteed to have a pointer to its base while it is
256 alive. Interior pointers can be safely ignored. This attribute is
257 useful for eliminating false pointers in very large data structures
258 and is only implemented for data structures at least a page in size.
259 */
260 NO_INTERIOR = 0b0001_0000,
261
262 STRUCTFINAL = 0b0010_0000, // the block has a finalizer for (an array of) structs
263 }
264
265
266 /**
267 * Contains aggregate information about a block of managed memory. The
268 * purpose of this struct is to support a more efficient query style in
269 * instances where detailed information is needed.
270 *
271 * base = A pointer to the base of the block in question.
272 * size = The size of the block, calculated from base.
273 * attr = Attribute bits set on the memory block.
274 */
275 alias BlkInfo = BlkInfo_;
276
277
278 /**
279 * Returns a bit field representing all block attributes set for the memory
280 * referenced by p. If p references memory not originally allocated by
281 * this garbage collector, points to the interior of a memory block, or if
282 * p is null, zero will be returned.
283 *
284 * Params:
285 * p = A pointer to the root of a valid memory block or to null.
286 *
287 * Returns:
288 * A bit field containing any bits set for the memory block referenced by
289 * p or zero on error.
290 */
getAttrGC291 static uint getAttr( in void* p ) nothrow
292 {
293 return getAttr(cast()p);
294 }
295
296
297 /// ditto
getAttrGC298 static uint getAttr(void* p) pure nothrow
299 {
300 return gc_getAttr( p );
301 }
302
303
304 /**
305 * Sets the specified bits for the memory references by p. If p references
306 * memory not originally allocated by this garbage collector, points to the
307 * interior of a memory block, or if p is null, no action will be
308 * performed.
309 *
310 * Params:
311 * p = A pointer to the root of a valid memory block or to null.
312 * a = A bit field containing any bits to set for this memory block.
313 *
314 * Returns:
315 * The result of a call to getAttr after the specified bits have been
316 * set.
317 */
setAttrGC318 static uint setAttr( in void* p, uint a ) nothrow
319 {
320 return setAttr(cast()p, a);
321 }
322
323
324 /// ditto
setAttrGC325 static uint setAttr(void* p, uint a) pure nothrow
326 {
327 return gc_setAttr( p, a );
328 }
329
330
331 /**
332 * Clears the specified bits for the memory references by p. If p
333 * references memory not originally allocated by this garbage collector,
334 * points to the interior of a memory block, or if p is null, no action
335 * will be performed.
336 *
337 * Params:
338 * p = A pointer to the root of a valid memory block or to null.
339 * a = A bit field containing any bits to clear for this memory block.
340 *
341 * Returns:
342 * The result of a call to getAttr after the specified bits have been
343 * cleared.
344 */
clrAttrGC345 static uint clrAttr( in void* p, uint a ) nothrow
346 {
347 return clrAttr(cast()p, a);
348 }
349
350
351 /// ditto
clrAttrGC352 static uint clrAttr(void* p, uint a) pure nothrow
353 {
354 return gc_clrAttr( p, a );
355 }
356
357
358 /**
359 * Requests an aligned block of managed memory from the garbage collector.
360 * This memory may be deleted at will with a call to free, or it may be
361 * discarded and cleaned up automatically during a collection run. If
362 * allocation fails, this function will call onOutOfMemory which is
363 * expected to throw an OutOfMemoryError.
364 *
365 * Params:
366 * sz = The desired allocation size in bytes.
367 * ba = A bitmask of the attributes to set on this block.
368 * ti = TypeInfo to describe the memory. The GC might use this information
369 * to improve scanning for pointers or to call finalizers.
370 *
371 * Returns:
372 * A reference to the allocated memory or null if insufficient memory
373 * is available.
374 *
375 * Throws:
376 * OutOfMemoryError on allocation failure.
377 */
378 static void* malloc( size_t sz, uint ba = 0, const TypeInfo ti = null ) pure nothrow
379 {
380 return gc_malloc( sz, ba, ti );
381 }
382
383
384 /**
385 * Requests an aligned block of managed memory from the garbage collector.
386 * This memory may be deleted at will with a call to free, or it may be
387 * discarded and cleaned up automatically during a collection run. If
388 * allocation fails, this function will call onOutOfMemory which is
389 * expected to throw an OutOfMemoryError.
390 *
391 * Params:
392 * sz = The desired allocation size in bytes.
393 * ba = A bitmask of the attributes to set on this block.
394 * ti = TypeInfo to describe the memory. The GC might use this information
395 * to improve scanning for pointers or to call finalizers.
396 *
397 * Returns:
398 * Information regarding the allocated memory block or BlkInfo.init on
399 * error.
400 *
401 * Throws:
402 * OutOfMemoryError on allocation failure.
403 */
404 static BlkInfo qalloc( size_t sz, uint ba = 0, const TypeInfo ti = null ) pure nothrow
405 {
406 return gc_qalloc( sz, ba, ti );
407 }
408
409
410 /**
411 * Requests an aligned block of managed memory from the garbage collector,
412 * which is initialized with all bits set to zero. This memory may be
413 * deleted at will with a call to free, or it may be discarded and cleaned
414 * up automatically during a collection run. If allocation fails, this
415 * function will call onOutOfMemory which is expected to throw an
416 * OutOfMemoryError.
417 *
418 * Params:
419 * sz = The desired allocation size in bytes.
420 * ba = A bitmask of the attributes to set on this block.
421 * ti = TypeInfo to describe the memory. The GC might use this information
422 * to improve scanning for pointers or to call finalizers.
423 *
424 * Returns:
425 * A reference to the allocated memory or null if insufficient memory
426 * is available.
427 *
428 * Throws:
429 * OutOfMemoryError on allocation failure.
430 */
431 static void* calloc( size_t sz, uint ba = 0, const TypeInfo ti = null ) pure nothrow
432 {
433 return gc_calloc( sz, ba, ti );
434 }
435
436
437 /**
438 * If sz is zero, the memory referenced by p will be deallocated as if
439 * by a call to free. A new memory block of size sz will then be
440 * allocated as if by a call to malloc, or the implementation may instead
441 * resize the memory block in place. The contents of the new memory block
442 * will be the same as the contents of the old memory block, up to the
443 * lesser of the new and old sizes. Note that existing memory will only
444 * be freed by realloc if sz is equal to zero. The garbage collector is
445 * otherwise expected to later reclaim the memory block if it is unused.
446 * If allocation fails, this function will call onOutOfMemory which is
447 * expected to throw an OutOfMemoryError. If p references memory not
448 * originally allocated by this garbage collector, or if it points to the
449 * interior of a memory block, no action will be taken. If ba is zero
450 * (the default) and p references the head of a valid, known memory block
451 * then any bits set on the current block will be set on the new block if a
452 * reallocation is required. If ba is not zero and p references the head
453 * of a valid, known memory block then the bits in ba will replace those on
454 * the current memory block and will also be set on the new block if a
455 * reallocation is required.
456 *
457 * Params:
458 * p = A pointer to the root of a valid memory block or to null.
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 on success or null if sz is
466 * zero. On failure, the original value of p is returned.
467 *
468 * Throws:
469 * OutOfMemoryError on allocation failure.
470 */
471 static void* realloc( void* p, size_t sz, uint ba = 0, const TypeInfo ti = null ) pure nothrow
472 {
473 return gc_realloc( p, sz, ba, ti );
474 }
475
476 /// Issue 13111
477 unittest
478 {
479 enum size1 = 1 << 11 + 1; // page in large object pool
480 enum size2 = 1 << 22 + 1; // larger than large object pool size
481
482 auto data1 = cast(ubyte*)GC.calloc(size1);
483 auto data2 = cast(ubyte*)GC.realloc(data1, size2);
484
485 BlkInfo info = query(data2);
486 assert(info.size >= size2);
487 }
488
489
490 /**
491 * Requests that the managed memory block referenced by p be extended in
492 * place by at least mx bytes, with a desired extension of sz bytes. If an
493 * extension of the required size is not possible or if p references memory
494 * not originally allocated by this garbage collector, no action will be
495 * taken.
496 *
497 * Params:
498 * p = A pointer to the root of a valid memory block or to null.
499 * mx = The minimum extension size in bytes.
500 * sz = The desired extension size in bytes.
501 * ti = TypeInfo to describe the full memory block. The GC might use
502 * this information to improve scanning for pointers or to
503 * call finalizers.
504 *
505 * Returns:
506 * The size in bytes of the extended memory block referenced by p or zero
507 * if no extension occurred.
508 *
509 * Note:
510 * Extend may also be used to extend slices (or memory blocks with
511 * $(LREF APPENDABLE) info). However, use the return value only
512 * as an indicator of success. $(LREF capacity) should be used to
513 * retrieve actual usable slice capacity.
514 */
515 static size_t extend( void* p, size_t mx, size_t sz, const TypeInfo ti = null ) pure nothrow
516 {
517 return gc_extend( p, mx, sz, ti );
518 }
519 /// Standard extending
520 unittest
521 {
522 size_t size = 1000;
523 int* p = cast(int*)GC.malloc(size * int.sizeof, GC.BlkAttr.NO_SCAN);
524
525 //Try to extend the allocated data by 1000 elements, preferred 2000.
526 size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
527 if (u != 0)
528 size = u / int.sizeof;
529 }
530 /// slice extending
531 unittest
532 {
533 int[] slice = new int[](1000);
534 int* p = slice.ptr;
535
536 //Check we have access to capacity before attempting the extend
537 if (slice.capacity)
538 {
539 //Try to extend slice by 1000 elements, preferred 2000.
540 size_t u = GC.extend(p, 1000 * int.sizeof, 2000 * int.sizeof);
541 if (u != 0)
542 {
543 slice.length = slice.capacity;
544 assert(slice.length >= 2000);
545 }
546 }
547 }
548
549
550 /**
551 * Requests that at least sz bytes of memory be obtained from the operating
552 * system and marked as free.
553 *
554 * Params:
555 * sz = The desired size in bytes.
556 *
557 * Returns:
558 * The actual number of bytes reserved or zero on error.
559 */
reserveGC560 static size_t reserve( size_t sz ) nothrow /* FIXME pure */
561 {
562 return gc_reserve( sz );
563 }
564
565
566 /**
567 * Deallocates the memory referenced by p. If p is null, no action occurs.
568 * If p references memory not originally allocated by this garbage
569 * collector, if p points to the interior of a memory block, or if this
570 * method is called from a finalizer, no action will be taken. The block
571 * will not be finalized regardless of whether the FINALIZE attribute is
572 * set. If finalization is desired, use delete instead.
573 *
574 * Params:
575 * p = A pointer to the root of a valid memory block or to null.
576 */
freeGC577 static void free( void* p ) pure nothrow
578 {
579 gc_free( p );
580 }
581
582
583 /**
584 * Returns the base address of the memory block containing p. This value
585 * is useful to determine whether p is an interior pointer, and the result
586 * may be passed to routines such as sizeOf which may otherwise fail. If p
587 * references memory not originally allocated by this garbage collector, if
588 * p is null, or if the garbage collector does not support this operation,
589 * null will be returned.
590 *
591 * Params:
592 * p = A pointer to the root or the interior of a valid memory block or to
593 * null.
594 *
595 * Returns:
596 * The base address of the memory block referenced by p or null on error.
597 */
inoutGC598 static inout(void)* addrOf( inout(void)* p ) nothrow /* FIXME pure */
599 {
600 return cast(inout(void)*)gc_addrOf(cast(void*)p);
601 }
602
603
604 /// ditto
addrOfGC605 static void* addrOf(void* p) pure nothrow
606 {
607 return gc_addrOf(p);
608 }
609
610
611 /**
612 * Returns the true size of the memory block referenced by p. This value
613 * represents the maximum number of bytes for which a call to realloc may
614 * resize the existing block in place. If p references memory not
615 * originally allocated by this garbage collector, points to the interior
616 * of a memory block, or if p is null, zero will be returned.
617 *
618 * Params:
619 * p = A pointer to the root of a valid memory block or to null.
620 *
621 * Returns:
622 * The size in bytes of the memory block referenced by p or zero on error.
623 */
sizeOfGC624 static size_t sizeOf( in void* p ) nothrow
625 {
626 return gc_sizeOf(cast(void*)p);
627 }
628
629
630 /// ditto
sizeOfGC631 static size_t sizeOf(void* p) pure nothrow
632 {
633 return gc_sizeOf( p );
634 }
635
636 // verify that the reallocation doesn't leave the size cache in a wrong state
637 unittest
638 {
639 auto data = cast(int*)realloc(null, 4096);
640 size_t size = GC.sizeOf(data);
641 assert(size >= 4096);
642 data = cast(int*)GC.realloc(data, 4100);
643 size = GC.sizeOf(data);
644 assert(size >= 4100);
645 }
646
647 /**
648 * Returns aggregate information about the memory block containing p. If p
649 * references memory not originally allocated by this garbage collector, if
650 * p is null, or if the garbage collector does not support this operation,
651 * BlkInfo.init will be returned. Typically, support for this operation
652 * is dependent on support for addrOf.
653 *
654 * Params:
655 * p = A pointer to the root or the interior of a valid memory block or to
656 * null.
657 *
658 * Returns:
659 * Information regarding the memory block referenced by p or BlkInfo.init
660 * on error.
661 */
queryGC662 static BlkInfo query( in void* p ) nothrow
663 {
664 return gc_query(cast(void*)p);
665 }
666
667
668 /// ditto
queryGC669 static BlkInfo query(void* p) pure nothrow
670 {
671 return gc_query( p );
672 }
673
674 /**
675 * Returns runtime stats for currently active GC implementation
676 * See `core.memory.GC.Stats` for list of available metrics.
677 */
statsGC678 static Stats stats() nothrow
679 {
680 return gc_stats();
681 }
682
683 /**
684 * Adds an internal root pointing to the GC memory block referenced by p.
685 * As a result, the block referenced by p itself and any blocks accessible
686 * via it will be considered live until the root is removed again.
687 *
688 * If p is null, no operation is performed.
689 *
690 * Params:
691 * p = A pointer into a GC-managed memory block or null.
692 *
693 * Example:
694 * ---
695 * // Typical C-style callback mechanism; the passed function
696 * // is invoked with the user-supplied context pointer at a
697 * // later point.
698 * extern(C) void addCallback(void function(void*), void*);
699 *
700 * // Allocate an object on the GC heap (this would usually be
701 * // some application-specific context data).
702 * auto context = new Object;
703 *
704 * // Make sure that it is not collected even if it is no
705 * // longer referenced from D code (stack, GC heap, …).
706 * GC.addRoot(cast(void*)context);
707 *
708 * // Also ensure that a moving collector does not relocate
709 * // the object.
710 * GC.setAttr(cast(void*)context, GC.BlkAttr.NO_MOVE);
711 *
712 * // Now context can be safely passed to the C library.
713 * addCallback(&myHandler, cast(void*)context);
714 *
715 * extern(C) void myHandler(void* ctx)
716 * {
717 * // Assuming that the callback is invoked only once, the
718 * // added root can be removed again now to allow the GC
719 * // to collect it later.
720 * GC.removeRoot(ctx);
721 * GC.clrAttr(ctx, GC.BlkAttr.NO_MOVE);
722 *
723 * auto context = cast(Object)ctx;
724 * // Use context here…
725 * }
726 * ---
727 */
addRootGC728 static void addRoot( in void* p ) nothrow @nogc /* FIXME pure */
729 {
730 gc_addRoot( p );
731 }
732
733
734 /**
735 * Removes the memory block referenced by p from an internal list of roots
736 * to be scanned during a collection. If p is null or is not a value
737 * previously passed to addRoot() then no operation is performed.
738 *
739 * Params:
740 * p = A pointer into a GC-managed memory block or null.
741 */
removeRootGC742 static void removeRoot( in void* p ) nothrow @nogc /* FIXME pure */
743 {
744 gc_removeRoot( p );
745 }
746
747
748 /**
749 * Adds $(D p[0 .. sz]) to the list of memory ranges to be scanned for
750 * pointers during a collection. If p is null, no operation is performed.
751 *
752 * Note that $(D p[0 .. sz]) is treated as an opaque range of memory assumed
753 * to be suitably managed by the caller. In particular, if p points into a
754 * GC-managed memory block, addRange does $(I not) mark this block as live.
755 *
756 * Params:
757 * p = A pointer to a valid memory address or to null.
758 * sz = The size in bytes of the block to add. If sz is zero then the
759 * no operation will occur. If p is null then sz must be zero.
760 * ti = TypeInfo to describe the memory. The GC might use this information
761 * to improve scanning for pointers or to call finalizers
762 *
763 * Example:
764 * ---
765 * // Allocate a piece of memory on the C heap.
766 * enum size = 1_000;
767 * auto rawMemory = core.stdc.stdlib.malloc(size);
768 *
769 * // Add it as a GC range.
770 * GC.addRange(rawMemory, size);
771 *
772 * // Now, pointers to GC-managed memory stored in
773 * // rawMemory will be recognized on collection.
774 * ---
775 */
776 static void addRange( in void* p, size_t sz, const TypeInfo ti = null ) @nogc nothrow /* FIXME pure */
777 {
778 gc_addRange( p, sz, ti );
779 }
780
781
782 /**
783 * Removes the memory range starting at p from an internal list of ranges
784 * to be scanned during a collection. If p is null or does not represent
785 * a value previously passed to addRange() then no operation is
786 * performed.
787 *
788 * Params:
789 * p = A pointer to a valid memory address or to null.
790 */
removeRangeGC791 static void removeRange( in void* p ) nothrow @nogc /* FIXME pure */
792 {
793 gc_removeRange( p );
794 }
795
796
797 /**
798 * Runs any finalizer that is located in address range of the
799 * given code segment. This is used before unloading shared
800 * libraries. All matching objects which have a finalizer in this
801 * code segment are assumed to be dead, using them while or after
802 * calling this method has undefined behavior.
803 *
804 * Params:
805 * segment = address range of a code segment.
806 */
runFinalizersGC807 static void runFinalizers( in void[] segment )
808 {
809 gc_runFinalizers( segment );
810 }
811 }
812
813 /**
814 * Pure variants of C's memory allocation functions `malloc`, `calloc`, and
815 * `realloc` and deallocation function `free`.
816 *
817 * Purity is achieved by saving and restoring the value of `errno`, thus
818 * behaving as if it were never changed.
819 *
820 * See_Also:
821 * $(LINK2 https://dlang.org/spec/function.html#pure-functions, D's rules for purity),
822 * which allow for memory allocation under specific circumstances.
823 */
pureMalloc(size_t size)824 void* pureMalloc(size_t size) @trusted pure @nogc nothrow
825 {
826 const errno = fakePureGetErrno();
827 void* ret = fakePureMalloc(size);
828 if (!ret || errno != 0)
829 {
830 cast(void)fakePureSetErrno(errno);
831 }
832 return ret;
833 }
834 /// ditto
pureCalloc(size_t nmemb,size_t size)835 void* pureCalloc(size_t nmemb, size_t size) @trusted pure @nogc nothrow
836 {
837 const errno = fakePureGetErrno();
838 void* ret = fakePureCalloc(nmemb, size);
839 if (!ret || errno != 0)
840 {
841 cast(void)fakePureSetErrno(errno);
842 }
843 return ret;
844 }
845 /// ditto
pureRealloc(void * ptr,size_t size)846 void* pureRealloc(void* ptr, size_t size) @system pure @nogc nothrow
847 {
848 const errno = fakePureGetErrno();
849 void* ret = fakePureRealloc(ptr, size);
850 if (!ret || errno != 0)
851 {
852 cast(void)fakePureSetErrno(errno);
853 }
854 return ret;
855 }
856 /// ditto
pureFree(void * ptr)857 void pureFree(void* ptr) @system pure @nogc nothrow
858 {
859 const errno = fakePureGetErrno();
860 fakePureFree(ptr);
861 cast(void)fakePureSetErrno(errno);
862 }
863
864 ///
865 @system pure nothrow @nogc unittest
866 {
fun(size_t n)867 ubyte[] fun(size_t n) pure
868 {
869 void* p = pureMalloc(n);
870 p !is null || n == 0 || assert(0);
871 scope(failure) p = pureRealloc(p, 0);
872 p = pureRealloc(p, n *= 2);
873 p !is null || n == 0 || assert(0);
874 return cast(ubyte[]) p[0 .. n];
875 }
876
877 auto buf = fun(100);
878 assert(buf.length == 200);
879 pureFree(buf.ptr);
880 }
881
882 @system pure nothrow @nogc unittest
883 {
884 const int errno = fakePureGetErrno();
885
886 void* x = pureMalloc(10); // normal allocation
887 assert(errno == fakePureGetErrno()); // errno shouldn't change
888 assert(x !is null); // allocation should succeed
889
890 x = pureRealloc(x, 10); // normal reallocation
891 assert(errno == fakePureGetErrno()); // errno shouldn't change
892 assert(x !is null); // allocation should succeed
893
894 fakePureFree(x);
895
896 void* y = pureCalloc(10, 1); // normal zeroed allocation
897 assert(errno == fakePureGetErrno()); // errno shouldn't change
898 assert(y !is null); // allocation should succeed
899
900 fakePureFree(y);
901
902 // subtract 2 because snn.lib adds 2 unconditionally before passing
903 // the size to the Windows API
904 void* z = pureMalloc(size_t.max - 2); // won't affect `errno`
905 assert(errno == fakePureGetErrno()); // errno shouldn't change
906 assert(z is null);
907 }
908
909 // locally purified for internal use here only
910 extern (C) private pure @system @nogc nothrow
911 {
912 pragma(mangle, "getErrno") int fakePureGetErrno();
913 pragma(mangle, "setErrno") int fakePureSetErrno(int);
914
915 pragma(mangle, "malloc") void* fakePureMalloc(size_t);
916 pragma(mangle, "calloc") void* fakePureCalloc(size_t nmemb, size_t size);
917 pragma(mangle, "realloc") void* fakePureRealloc(void* ptr, size_t size);
918
919 pragma(mangle, "free") void fakePureFree(void* ptr);
920 }
921