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