Debian Codegraph @

libphobos/libdruntime/rt/lifetime.d

raw
1 /**
2 * This module contains all functions related to an object's lifetime:
3 * allocation, resizing, deallocation, and finalization.
4 *
5 * Copyright: Copyright Digital Mars 2000 - 2012.
6 * License: Distributed under the
7 * $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
8 * (See accompanying file LICENSE)
9 * Authors: Walter Bright, Sean Kelly, Steven Schveighoffer
10 * Source: $(DRUNTIMESRC rt/_lifetime.d)
11 */
12
13 module rt.lifetime;
14
15 import core.attribute : weak;
16 import core.checkedint : mulu;
17 import core.exception : onFinalizeError, onOutOfMemoryError, onUnicodeError;
18 import core.internal.gc.blockmeta : PAGESIZE;
19 import core.memory;
20 import core.stdc.stdlib : malloc;
21 import core.stdc.string : memcpy, memset;
22 static import rt.tlsgc;
23
24 debug (PRINTF) import core.stdc.stdio : printf;
25 debug (VALGRIND) import etc.valgrind.valgrind;
26
27 alias BlkAttr = GC.BlkAttr;
28
29 // for now, all GC array functions are not exposed via core.memory.
30 extern(C) {
31 void[] gc_getArrayUsed(void *ptr, bool atomic) nothrow;
32 bool gc_expandArrayUsed(void[] slice, size_t newUsed, bool atomic) nothrow;
33 size_t gc_reserveArrayCapacity(void[] slice, size_t request, bool atomic) nothrow;
34 bool gc_shrinkArrayUsed(void[] slice, size_t existingUsed, bool atomic) nothrow;
35 }
36
37 private
38 {
39 alias bool function(Object) CollectHandler;
40 __gshared CollectHandler collectHandler = null;
41
42 extern (C) void _d_monitordelete(Object h, bool det);
43
44 }
45
46 // Now-removed symbol, kept around for ABI
47 // Some programs are dynamically linked, so best to err on the side of keeping symbols around for a while (especially extern(C) ones)
48 // https://github.com/dlang/druntime/pull/3361
49 deprecated extern (C) void lifetime_init()
50 {
51 }
52
53 /**
54 Allocate memory using the garbage collector
55
56 DMD uses this to allocate closures:
57 ---
58 void f(byte[24] x)
59 {
60 return () => x; // `x` is on stack, must be moved to heap to keep it alive
61 }
62 ---
63
64 Params:
65 sz = number of bytes to allocate
66
67 Returns: pointer to `sz` bytes of free, uninitialized memory, managed by the GC.
68 */
69 extern (C) void* _d_allocmemory(size_t sz) @weak
70 {
71 return GC.malloc(sz);
72 }
73
74 /**
75 Create a new class instance.
76
77 Allocates memory and sets fields to their initial value, but does not call a constructor.
78
79 ---
80 new Object() // _d_newclass(typeid(Object))
81 ---
82 Params:
83 ci = `TypeInfo_Class` object, to provide instance size and initial bytes to copy
84
85 Returns: newly created object
86 */
87 extern (C) Object _d_newclass(const ClassInfo ci) @weak
88 {
89 void* p;
90 auto init = ci.initializer;
91
92 debug(PRINTF) printf("_d_newclass(ci = %p, %s)\n", ci, cast(char *)ci.name);
93 if (ci.m_flags & TypeInfo_Class.ClassFlags.isCOMclass)
94 { /* COM objects are not garbage collected, they are reference counted
95 * using AddRef() and Release(). They get free'd by C's free()
96 * function called by Release() when Release()'s reference count goes
97 * to zero.
98 */
99 p = malloc(init.length);
100 if (!p)
101 onOutOfMemoryError();
102 }
103 else
104 {
105 // TODO: should this be + 1 to avoid having pointers to the next block?
106 BlkAttr attr = BlkAttr.NONE;
107 // extern(C++) classes don't have a classinfo pointer in their vtable so the GC can't finalize them
108 if (ci.m_flags & TypeInfo_Class.ClassFlags.hasDtor
109 && !(ci.m_flags & TypeInfo_Class.ClassFlags.isCPPclass))
110 attr |= BlkAttr.FINALIZE;
111 if (ci.m_flags & TypeInfo_Class.ClassFlags.noPointers)
112 attr |= BlkAttr.NO_SCAN;
113 p = GC.malloc(init.length, attr, ci);
114 debug(PRINTF) printf(" p = %p\n", p);
115 }
116
117 debug(PRINTF)
118 {
119 printf("p = %p\n", p);
120 printf("ci = %p, ci.init.ptr = %p, len = %llu\n", ci, init.ptr, cast(ulong)init.length);
121 printf("vptr = %p\n", *cast(void**) init);
122 printf("vtbl[0] = %p\n", (*cast(void***) init)[0]);
123 printf("vtbl[1] = %p\n", (*cast(void***) init)[1]);
124 printf("init[0] = %x\n", (cast(uint*) init)[0]);
125 printf("init[1] = %x\n", (cast(uint*) init)[1]);
126 printf("init[2] = %x\n", (cast(uint*) init)[2]);
127 printf("init[3] = %x\n", (cast(uint*) init)[3]);
128 printf("init[4] = %x\n", (cast(uint*) init)[4]);
129 }
130
131 // initialize it
132 p[0 .. init.length] = cast(void[]) init[];
133
134 debug(PRINTF) printf("initialization done\n");
135 return cast(Object) p;
136 }
137
138
139 /**
140 *
141 */
142 extern (C) void _d_delinterface(void** p)
143 {
144 if (*p)
145 {
146 Interface* pi = **cast(Interface ***)*p;
147 Object o = cast(Object)(*p - pi.offset);
148
149 _d_delclass(&o);
150 *p = null;
151 }
152 }
153
154
155 // used for deletion
156 private extern (D) alias void function (Object) fp_t;
157
158
159 /**
160 *
161 */
162 extern (C) void _d_delclass(Object* p) @weak
163 {
164 if (*p)
165 {
166 debug(PRINTF) printf("_d_delclass(%p)\n", *p);
167
168 ClassInfo **pc = cast(ClassInfo **)*p;
169 if (*pc)
170 {
171 ClassInfo c = **pc;
172
173 rt_finalize(cast(void*) *p);
174
175 if (c.deallocator)
176 {
177 fp_t fp = cast(fp_t)c.deallocator;
178 (*fp)(*p); // call deallocator
179 *p = null;
180 return;
181 }
182 }
183 else
184 {
185 rt_finalize(cast(void*) *p);
186 }
187 GC.free(cast(void*) *p);
188 *p = null;
189 }
190 }
191
192 // strip const/immutable/shared/inout from type info
193 inout(TypeInfo) unqualify(return scope inout(TypeInfo) cti) pure nothrow @nogc
194 {
195 TypeInfo ti = cast() cti;
196 while (ti)
197 {
198 // avoid dynamic type casts
199 auto tti = typeid(ti);
200 if (tti is typeid(TypeInfo_Const))
201 ti = (cast(TypeInfo_Const)cast(void*)ti).base;
202 else if (tti is typeid(TypeInfo_Invariant))
203 ti = (cast(TypeInfo_Invariant)cast(void*)ti).base;
204 else if (tti is typeid(TypeInfo_Shared))
205 ti = (cast(TypeInfo_Shared)cast(void*)ti).base;
206 else if (tti is typeid(TypeInfo_Inout))
207 ti = (cast(TypeInfo_Inout)cast(void*)ti).base;
208 else
209 break;
210 }
211 return ti;
212 }
213
214 private uint __typeAttrs(const scope TypeInfo ti, void *copyAttrsFrom = null) pure nothrow
215 {
216 if (copyAttrsFrom)
217 {
218 // try to copy attrs from the given block
219 auto info = GC.query(copyAttrsFrom);
220 if (info.base)
221 return info.attr;
222 }
223 uint attrs = !(ti.flags & 1) ? BlkAttr.NO_SCAN : 0;
224 if (typeid(ti) is typeid(TypeInfo_Struct)) {
225 auto sti = cast(TypeInfo_Struct)cast(void*)ti;
226 if (sti.xdtor)
227 attrs |= BlkAttr.FINALIZE;
228 }
229 return attrs;
230 }
231
232 /**
233 Shrink the "allocated" length of an array to be the exact size of the array.
234
235 It doesn't matter what the current allocated length of the array is, the
236 user is telling the runtime that he knows what he is doing.
237
238 Params:
239 ti = `TypeInfo` of array type
240 arr = array to shrink. Its `.length` is element length, not byte length, despite `void` type
241 */
242 extern(C) void _d_arrayshrinkfit(const TypeInfo ti, void[] arr) nothrow
243 {
244 debug(PRINTF) printf("_d_arrayshrinkfit, elemsize = %zd, arr.ptr = %p arr.length = %zd\n", ti.next.tsize, arr.ptr, arr.length);
245 auto tinext = unqualify(ti.next);
246 auto size = tinext.tsize; // array element size
247 auto reqsize = arr.length * size;
248 auto isshared = typeid(ti) is typeid(TypeInfo_Shared);
249
250 auto curArr = gc_getArrayUsed(arr.ptr, isshared);
251 if (curArr.ptr is null)
252 // not a valid GC pointer
253 return;
254
255 // align the array.
256 auto offset = arr.ptr - curArr.ptr;
257 auto cursize = curArr.length - offset;
258 if (cursize <= reqsize)
259 // invalid situation, or no change.
260 return;
261
262 // if the type has a destructor, destroy elements we are about to remove.
263 if (typeid(tinext) is typeid(TypeInfo_Struct)) // avoid a complete dynamic type cast
264 {
265 auto sti = cast(TypeInfo_Struct)cast(void*)tinext;
266 if (sti.xdtor)
267 {
268 try
269 {
270 finalize_array(arr.ptr + reqsize, cursize - reqsize, sti);
271 }
272 catch (Exception e)
273 {
274 onFinalizeError(sti, e);
275 }
276 }
277 }
278
279 gc_shrinkArrayUsed(arr.ptr[0 .. reqsize], cursize, isshared);
280 }
281
282 package bool hasPostblit(in TypeInfo ti) nothrow pure
283 {
284 return (&ti.postblit).funcptr !is &TypeInfo.postblit;
285 }
286
287 void __doPostblit(void *ptr, size_t len, const TypeInfo ti)
288 {
289 if (!hasPostblit(ti))
290 return;
291
292 if (auto tis = cast(TypeInfo_Struct)ti)
293 {
294 // this is a struct, check the xpostblit member
295 auto pblit = tis.xpostblit;
296 if (!pblit)
297 // postblit not specified, no point in looping.
298 return;
299
300 // optimized for struct, call xpostblit directly for each element
301 immutable size = ti.tsize;
302 const eptr = ptr + len;
303 for (;ptr < eptr;ptr += size)
304 pblit(ptr);
305 }
306 else
307 {
308 // generic case, call the typeinfo's postblit function
309 immutable size = ti.tsize;
310 const eptr = ptr + len;
311 for (;ptr < eptr;ptr += size)
312 ti.postblit(ptr);
313 }
314 }
315
316
317 /**
318 Set the array capacity.
319
320 If the array capacity isn't currently large enough
321 to hold the requested capacity (in number of elements), then the array is
322 resized/reallocated to the appropriate size.
323
324 Pass in a requested capacity of 0 to get the current capacity.
325
326 Params:
327 ti = type info of element type
328 newcapacity = requested new capacity
329 p = pointer to array to set. Its `length` is left unchanged.
330
331 Returns: the number of elements that can actually be stored once the resizing is done
332 */
333 extern(C) size_t _d_arraysetcapacity(const TypeInfo ti, size_t newcapacity, void[]* p) @weak
334 in
335 {
336 assert(ti);
337 assert(!(*p).length || (*p).ptr);
338 }
339 do
340 {
341 auto isshared = typeid(ti) is typeid(TypeInfo_Shared);
342 auto tinext = unqualify(ti.next);
343 auto size = tinext.tsize;
344 version (D_InlineAsm_X86)
345 {
346 size_t reqsize = void;
347
348 asm
349 {
350 mov EAX, newcapacity;
351 mul EAX, size;
352 mov reqsize, EAX;
353 jnc Lcontinue;
354 }
355 }
356 else version (D_InlineAsm_X86_64)
357 {
358 size_t reqsize = void;
359
360 asm
361 {
362 mov RAX, newcapacity;
363 mul RAX, size;
364 mov reqsize, RAX;
365 jnc Lcontinue;
366 }
367 }
368 else
369 {
370 bool overflow = false;
371 size_t reqsize = mulu(size, newcapacity, overflow);
372 if (!overflow)
373 goto Lcontinue;
374 }
375 Loverflow:
376 onOutOfMemoryError();
377 assert(0);
378 Lcontinue:
379
380 // step 1, see if we can ensure the capacity is valid in-place
381 auto datasize = (*p).length * size;
382 auto curCapacity = gc_reserveArrayCapacity((*p).ptr[0 .. datasize], reqsize, isshared);
383 if (curCapacity != 0)
384 // in-place worked!
385 return curCapacity / size;
386
387 if (reqsize <= datasize)
388 // requested size is less than array size, the current array satisfies
389 // the request. But this is not an appendable GC array, so return 0.
390 return 0;
391
392 // step 2, if reserving in-place doesn't work, allocate a new array with at
393 // least the requested allocated size.
394 auto attrs = __typeAttrs(tinext, (*p).ptr) | BlkAttr.APPENDABLE;
395 auto ptr = GC.malloc(reqsize, attrs, tinext);
396 if (ptr is null)
397 goto Loverflow;
398
399 // copy the data over.
400 // note that malloc will have initialized the data we did not request to 0.
401 memcpy(ptr, (*p).ptr, datasize);
402
403 // handle postblit
404 __doPostblit(ptr, datasize, tinext);
405
406 if (!(attrs & BlkAttr.NO_SCAN))
407 {
408 // need to memset the newly requested data, except for the data that
409 // malloc returned that we didn't request.
410 void *endptr = ptr + reqsize;
411 void *begptr = ptr + datasize;
412
413 // sanity check
414 assert(endptr >= begptr);
415 memset(begptr, 0, endptr - begptr);
416 }
417
418 *p = ptr[0 .. (*p).length];
419
420 // set up the correct length. Note that we need to do this here, because
421 // the GC malloc will automatically set the used size to what we requested.
422 gc_shrinkArrayUsed(ptr[0 .. datasize], reqsize, isshared);
423
424 curCapacity = gc_reserveArrayCapacity(ptr[0 .. datasize], 0, isshared);
425 assert(curCapacity);
426 return curCapacity / size;
427 }
428
429 /**
430 Allocate an array with the garbage collector.
431
432 Has three variants:
433 - `_d_newarrayU` leave elements uninitialized
434 - `_d_newarrayT` initializes to 0 (e.g `new int[]`)
435 - `_d_newarrayiT` initializes based on initializer retrieved from TypeInfo (e.g `new float[]`)
436
437 Params:
438 ti = the type of the resulting array, (may also be the corresponding `array.ptr` type)
439 length = `.length` of resulting array
440 Returns: newly allocated array
441 */
442 extern (C) void[] _d_newarrayU(const scope TypeInfo ti, size_t length) pure nothrow @weak
443 {
444 auto tinext = unqualify(ti.next);
445 auto size = tinext.tsize;
446
447 debug(PRINTF) printf("_d_newarrayU(length = x%zx, size = %zd)\n", length, size);
448 if (length == 0 || size == 0)
449 return null;
450
451 version (D_InlineAsm_X86)
452 {
453 asm pure nothrow @nogc
454 {
455 mov EAX,size ;
456 mul EAX,length ;
457 mov size,EAX ;
458 jnc Lcontinue ;
459 }
460 }
461 else version (D_InlineAsm_X86_64)
462 {
463 asm pure nothrow @nogc
464 {
465 mov RAX,size ;
466 mul RAX,length ;
467 mov size,RAX ;
468 jnc Lcontinue ;
469 }
470 }
471 else
472 {
473 bool overflow = false;
474 size = mulu(size, length, overflow);
475 if (!overflow)
476 goto Lcontinue;
477 }
478 Loverflow:
479 onOutOfMemoryError();
480 assert(0);
481 Lcontinue:
482
483 auto ptr = GC.malloc(size, __typeAttrs(tinext) | BlkAttr.APPENDABLE, tinext);
484 if (!ptr)
485 goto Loverflow;
486 debug(PRINTF) printf(" p = %p\n", ptr);
487 return ptr[0 .. length];
488 }
489
490 /// ditto
491 extern (C) void[] _d_newarrayT(const TypeInfo ti, size_t length) pure nothrow @weak
492 {
493 void[] result = _d_newarrayU(ti, length);
494 auto tinext = unqualify(ti.next);
495 auto size = tinext.tsize;
496
497 memset(result.ptr, 0, size * length);
498 return result;
499 }
500
501 /// ditto
502 extern (C) void[] _d_newarrayiT(const TypeInfo ti, size_t length) pure nothrow @weak
503 {
504 import core.internal.traits : AliasSeq;
505
506 void[] result = _d_newarrayU(ti, length);
507 auto tinext = unqualify(ti.next);
508 auto size = tinext.tsize;
509
510 auto init = tinext.initializer();
511
512 switch (init.length)
513 {
514 foreach (T; AliasSeq!(ubyte, ushort, uint, ulong))
515 {
516 case T.sizeof:
517 if (tinext.talign % T.alignof == 0)
518 {
519 (cast(T*)result.ptr)[0 .. size * length / T.sizeof] = *cast(T*)init.ptr;
520 return result;
521 }
522 goto default;
523 }
524
525 default:
526 {
527 immutable sz = init.length;
528 for (size_t u = 0; u < size * length; u += sz)
529 memcpy(result.ptr + u, init.ptr, sz);
530 return result;
531 }
532 }
533 }
534
535 /**
536 Non-template version of $(REF _d_newitemT, core,lifetime) that does not perform
537 initialization. Needed for $(REF allocEntry, rt,aaA).
538
539 Params:
540 _ti = `TypeInfo` of item to allocate
541 Returns:
542 newly allocated item
543 */
544 extern (C) void* _d_newitemU(scope const TypeInfo _ti) pure nothrow @weak
545 {
546 auto ti = unqualify(_ti);
547 auto flags = __typeAttrs(ti);
548
549 return GC.malloc(ti.tsize, flags, ti);
550 }
551
552 /**
553 *
554 */
555 extern (C) void _d_delmemory(void* *p) @weak
556 {
557 if (*p)
558 {
559 GC.free(*p);
560 *p = null;
561 }
562 }
563
564
565 /**
566 *
567 */
568 extern (C) void _d_callinterfacefinalizer(void *p) @weak
569 {
570 if (p)
571 {
572 Interface *pi = **cast(Interface ***)p;
573 Object o = cast(Object)(p - pi.offset);
574 rt_finalize(cast(void*)o);
575 }
576 }
577
578
579 /**
580 *
581 */
582 extern (C) void _d_callfinalizer(void* p) @weak
583 {
584 rt_finalize( p );
585 }
586
587
588 /**
589 *
590 */
591 extern (C) void rt_setCollectHandler(CollectHandler h)
592 {
593 collectHandler = h;
594 }
595
596
597 /**
598 *
599 */
600 extern (C) CollectHandler rt_getCollectHandler()
601 {
602 return collectHandler;
603 }
604
605
606 /**
607 *
608 */
609 extern (C) int rt_hasFinalizerInSegment(void* p, size_t size, TypeInfo typeInfo, scope const(void)[] segment) nothrow
610 {
611 if (!p)
612 return false;
613
614 if (typeInfo !is null)
615 {
616 assert(typeid(typeInfo) is typeid(TypeInfo_Struct));
617
618 auto ti = cast(TypeInfo_Struct)cast(void*)typeInfo;
619 return cast(size_t)(cast(void*)ti.xdtor - segment.ptr) < segment.length;
620 }
621
622 // otherwise class
623 auto ppv = cast(void**) p;
624 if (!*ppv)
625 return false;
626
627 auto c = *cast(ClassInfo*)*ppv;
628 do
629 {
630 auto pf = c.destructor;
631 if (cast(size_t)(pf - segment.ptr) < segment.length) return true;
632 }
633 while ((c = c.base) !is null);
634
635 return false;
636 }
637
638 void finalize_array(void* p, size_t size, const TypeInfo_Struct si)
639 {
640 // Due to the fact that the delete operator calls destructors
641 // for arrays from the last element to the first, we maintain
642 // compatibility here by doing the same.
643 auto tsize = si.tsize;
644 for (auto curP = p + size - tsize; curP >= p; curP -= tsize)
645 {
646 // call destructor
647 si.destroy(curP);
648 }
649 }
650
651 // called by the GC
652 void finalize_struct(void* p, TypeInfo_Struct ti) nothrow
653 {
654 debug(PRINTF) printf("finalize_struct(p = %p)\n", p);
655
656 try
657 {
658 ti.destroy(p); // call destructor
659 }
660 catch (Exception e)
661 {
662 onFinalizeError(ti, e);
663 }
664 }
665
666 /**
667 *
668 */
669 extern (C) void rt_finalize2(void* p, bool det = true, bool resetMemory = true) nothrow
670 {
671 debug(PRINTF) printf("rt_finalize2(p = %p)\n", p);
672
673 auto ppv = cast(void**) p;
674 if (!p || !*ppv)
675 return;
676
677 auto pc = cast(ClassInfo*) *ppv;
678 try
679 {
680 if (det || collectHandler is null || collectHandler(cast(Object) p))
681 {
682 auto c = *pc;
683 do
684 {
685 if (c.destructor)
686 (cast(fp_t) c.destructor)(cast(Object) p); // call destructor
687 }
688 while ((c = c.base) !is null);
689 }
690
691 if (ppv[1]) // if monitor is not null
692 _d_monitordelete(cast(Object) p, det);
693
694 if (resetMemory)
695 {
696 auto w = (*pc).initializer;
697 p[0 .. w.length] = cast(void[]) w[];
698 }
699 }
700 catch (Exception e)
701 {
702 onFinalizeError(*pc, e);
703 }
704 finally
705 {
706 *ppv = null; // zero vptr even if `resetMemory` is false
707 }
708 }
709
710 /// Backwards compatibility
711 extern (C) void rt_finalize(void* p, bool det = true) nothrow
712 {
713 rt_finalize2(p, det, true);
714 }
715
716 extern (C) void rt_finalizeFromGC(void* p, size_t size, uint attr, TypeInfo typeInfo) nothrow
717 {
718 // to verify: reset memory necessary?
719 if (typeInfo is null) {
720 rt_finalize2(p, false, false); // class
721 return;
722 }
723
724 assert(typeid(typeInfo) is typeid(TypeInfo_Struct));
725
726 auto si = cast(TypeInfo_Struct)cast(void*)typeInfo;
727
728 try
729 {
730 if (attr & BlkAttr.APPENDABLE)
731 {
732 finalize_array(p, size, si);
733 }
734 else
735 finalize_struct(p, si); // struct
736 }
737 catch (Exception e)
738 {
739 onFinalizeError(si, e);
740 }
741 }
742
743
744 /**
745 Resize a dynamic array by setting the `.length` property
746
747 Newly created elements are initialized to their default value.
748
749 Has two variants:
750 - `_d_arraysetlengthT` for arrays with elements that initialize to 0
751 - `_d_arraysetlengthiT` for non-zero initializers retrieved from `TypeInfo`
752
753 ---
754 void main()
755 {
756 int[] a = [1, 2];
757 a.length = 3; // gets lowered to `_d_arraysetlengthT(typeid(int[]), 3, &a)`
758 }
759 ---
760
761 Params:
762 ti = `TypeInfo` of array
763 newlength = new value for the array's `.length`
764 p = pointer to array to update the `.length` of.
765 While it's cast to `void[]`, its `.length` is still treated as element length.
766 Returns: `*p` after being updated
767 */
768 extern (C) void[] _d_arraysetlengthT(const TypeInfo ti, size_t newlength, void[]* p) @weak
769 in
770 {
771 assert(ti);
772 assert(!(*p).length || (*p).ptr);
773 }
774 do
775 {
776 debug(PRINTF)
777 {
778 //printf("_d_arraysetlengthT(p = %p, sizeelem = %d, newlength = %d)\n", p, sizeelem, newlength);
779 if (p)
780 printf("\tp.ptr = %p, p.length = %zd\n", (*p).ptr, (*p).length);
781 }
782
783 if (newlength <= (*p).length)
784 {
785 *p = (*p)[0 .. newlength];
786 return *p;
787 }
788 auto tinext = unqualify(ti.next);
789 size_t sizeelem = tinext.tsize;
790
791 /* Calculate: newsize = newlength * sizeelem
792 */
793 bool overflow = false;
794 version (D_InlineAsm_X86)
795 {
796 size_t newsize = void;
797
798 asm pure nothrow @nogc
799 {
800 mov EAX, newlength;
801 mul EAX, sizeelem;
802 mov newsize, EAX;
803 setc overflow;
804 }
805 }
806 else version (D_InlineAsm_X86_64)
807 {
808 size_t newsize = void;
809
810 asm pure nothrow @nogc
811 {
812 mov RAX, newlength;
813 mul RAX, sizeelem;
814 mov newsize, RAX;
815 setc overflow;
816 }
817 }
818 else
819 {
820 const size_t newsize = mulu(sizeelem, newlength, overflow);
821 }
822 if (overflow)
823 {
824 onOutOfMemoryError();
825 assert(0);
826 }
827
828 debug(PRINTF) printf("newsize = %zx, newlength = %zx\n", newsize, newlength);
829
830 if (!(*p).ptr)
831 {
832 assert((*p).length == 0);
833 // pointer was null, need to allocate
834 auto ptr = GC.malloc(newsize, __typeAttrs(tinext) | BlkAttr.APPENDABLE, tinext);
835 if (ptr is null)
836 {
837 onOutOfMemoryError();
838 assert(0);
839 }
840 memset(ptr, 0, newsize);
841 *p = ptr[0 .. newlength];
842 return *p;
843 }
844
845 const size_t size = (*p).length * sizeelem;
846 const isshared = typeid(ti) is typeid(TypeInfo_Shared);
847
848 /* Attempt to extend past the end of the existing array.
849 * If not possible, allocate new space for entire array and copy.
850 */
851 void* newdata = (*p).ptr;
852 if (!gc_expandArrayUsed(newdata[0 .. size], newsize, isshared))
853 {
854 newdata = GC.malloc(newsize, __typeAttrs(tinext, (*p).ptr) | BlkAttr.APPENDABLE, tinext);
855 if (newdata is null)
856 {
857 onOutOfMemoryError();
858 assert(0);
859 }
860
861 newdata[0 .. size] = (*p).ptr[0 .. size];
862
863 // Do postblit processing, as we are making a copy.
864 __doPostblit(newdata, size, tinext);
865 }
866
867 // Zero the unused portion of the newly allocated space
868 memset(newdata + size, 0, newsize - size);
869
870 *p = newdata[0 .. newlength];
871 return *p;
872 }
873
874 /// ditto
875 extern (C) void[] _d_arraysetlengthiT(const TypeInfo ti, size_t newlength, void[]* p) @weak
876 in
877 {
878 assert(!(*p).length || (*p).ptr);
879 }
880 do
881 {
882 debug(PRINTF)
883 {
884 //printf("_d_arraysetlengthT(p = %p, sizeelem = %d, newlength = %d)\n", p, sizeelem, newlength);
885 if (p)
886 printf("\tp.ptr = %p, p.length = %zd\n", (*p).ptr, (*p).length);
887 }
888
889 if (newlength <= (*p).length)
890 {
891 *p = (*p)[0 .. newlength];
892 return *p;
893 }
894 auto tinext = unqualify(ti.next);
895 size_t sizeelem = tinext.tsize;
896
897 /* Calculate: newsize = newlength * sizeelem
898 */
899 bool overflow = false;
900 version (D_InlineAsm_X86)
901 {
902 size_t newsize = void;
903
904 asm pure nothrow @nogc
905 {
906 mov EAX, newlength;
907 mul EAX, sizeelem;
908 mov newsize, EAX;
909 setc overflow;
910 }
911 }
912 else version (D_InlineAsm_X86_64)
913 {
914 size_t newsize = void;
915
916 asm pure nothrow @nogc
917 {
918 mov RAX, newlength;
919 mul RAX, sizeelem;
920 mov newsize, RAX;
921 setc overflow;
922 }
923 }
924 else
925 {
926 const size_t newsize = mulu(sizeelem, newlength, overflow);
927 }
928 if (overflow)
929 {
930 onOutOfMemoryError();
931 assert(0);
932 }
933
934 debug(PRINTF) printf("newsize = %zx, newlength = %zx\n", newsize, newlength);
935
936 static void doInitialize(void *start, void *end, const void[] initializer)
937 {
938 if (initializer.length == 1)
939 {
940 memset(start, *(cast(ubyte*)initializer.ptr), end - start);
941 }
942 else
943 {
944 auto q = initializer.ptr;
945 immutable initsize = initializer.length;
946 for (; start < end; start += initsize)
947 {
948 memcpy(start, q, initsize);
949 }
950 }
951 }
952
953 if (!(*p).ptr)
954 {
955 assert((*p).length == 0);
956 // pointer was null, need to allocate
957 auto ptr = GC.malloc(newsize, __typeAttrs(tinext) | BlkAttr.APPENDABLE, tinext);
958 if (ptr is null)
959 {
960 onOutOfMemoryError();
961 assert(0);
962 }
963 doInitialize(ptr, ptr + newsize, tinext.initializer);
964 *p = ptr[0 .. newlength];
965 return *p;
966 }
967
968 const size_t size = (*p).length * sizeelem;
969 const isshared = typeid(ti) is typeid(TypeInfo_Shared);
970
971 /* Attempt to extend past the end of the existing array.
972 * If not possible, allocate new space for entire array and copy.
973 */
974 void* newdata = (*p).ptr;
975 if (!gc_expandArrayUsed(newdata[0 .. size], newsize, isshared))
976 {
977 newdata = GC.malloc(newsize, __typeAttrs(tinext, (*p).ptr) | BlkAttr.APPENDABLE, tinext);
978 if (newdata is null)
979 {
980 onOutOfMemoryError();
981 assert(0);
982 }
983
984 newdata[0 .. size] = (*p).ptr[0 .. size];
985
986 // Do postblit processing, as we are making a copy.
987 __doPostblit(newdata, size, tinext);
988 }
989
990 // Initialize the unused portion of the newly allocated space
991 doInitialize(newdata + size, newdata + newsize, tinext.initializer);
992 *p = newdata[0 .. newlength];
993 return *p;
994 }
995
996
997 /**
998 Given an array of length `size` that needs to be expanded to `newlength`,
999 compute a new capacity.
1000
1001 Better version by Dave Fladebo, enhanced by Steven Schveighoffer:
1002 This uses an inverse logorithmic algorithm to pre-allocate a bit more
1003 space for larger arrays.
1004 - The maximum "extra" space is about 80% of the requested space. This is for
1005 PAGE size and smaller.
1006 - As the arrays grow, the relative pre-allocated space shrinks.
1007 - Perhaps most importantly, overall memory usage and stress on the GC
1008 is decreased significantly for demanding environments.
1009 - The algorithm is tuned to avoid any division at runtime.
1010
1011 Params:
1012 newlength = new `.length`
1013 elemsize = size of the element in the new array
1014 Returns: new capacity for array
1015 */
1016 size_t newCapacity(size_t newlength, size_t elemsize)
1017 {
1018 size_t newcap = newlength * elemsize;
1019
1020 /*
1021 * Max growth factor numerator is 234, so allow for multiplying by 256.
1022 * But also, the resulting size cannot be more than 2x, so prevent
1023 * growing if 2x would fill up the address space (for 32-bit)
1024 */
1025 enum largestAllowed = (ulong.max >> 8) & (size_t.max >> 1);
1026 if (!newcap || (newcap & ~largestAllowed))
1027 return newcap;
1028
1029 /*
1030 * The calculation for "extra" space depends on the requested capacity.
1031 * We use an inverse logarithm of the new capacity to add an extra 15%
1032 * to 83% capacity. Note that normally we humans think in terms of
1033 * percent, but using 128 instead of 100 for the denominator means we
1034 * can avoid all division by simply bit-shifthing. Since there are only
1035 * 64 bits in a long, the bsr of a size_t is going to be 0 - 63. Using
1036 * a lookup table allows us to precalculate the multiplier based on the
1037 * inverse logarithm. The formula rougly is:
1038 *
1039 * newcap = request * (1.0 + min(0.83, 10.0 / (log(request) + 1)))
1040 */
1041 import core.bitop;
1042 static immutable multTable = (){
1043 assert(__ctfe);
1044 ulong[size_t.sizeof * 8] result;
1045 foreach (i; 0 .. result.length)
1046 {
1047 auto factor = 128 + 1280 / (i + 1);
1048 result[i] = factor > 234 ? 234 : factor;
1049 }
1050 return result;
1051 }();
1052
1053 auto mult = multTable[bsr(newcap)];
1054
1055 // if this were per cent, then the code would look like:
1056 // ((newlength * mult + 99) / 100) * elemsize
1057 newcap = cast(size_t)((newlength * mult + 127) >> 7) * elemsize;
1058 debug(PRINTF) printf("mult: %2.2f, alloc: %2.2f\n",mult/128.0,newcap / cast(double)elemsize);
1059 debug(PRINTF) printf("newcap = %zd, newlength = %zd, elemsize = %zd\n", newcap, newlength, elemsize);
1060 return newcap;
1061 }
1062
1063
1064 /**
1065 Extend an array by n elements.
1066
1067 Caller must initialize those elements.
1068
1069 Params:
1070 ti = type info of array type (not element type)
1071 px = array to append to, cast to `byte[]` while keeping the same `.length`. Will be updated.
1072 n = number of elements to append
1073 Returns: `px` after being appended to
1074 */
1075 extern (C)
1076 byte[] _d_arrayappendcTX(const TypeInfo ti, return scope ref byte[] px, size_t n) @weak
1077 {
1078 // This is a cut&paste job from _d_arrayappendT(). Should be refactored.
1079
1080 // Short circuit if no data is being appended.
1081 if (n == 0)
1082 return px;
1083
1084
1085 // only optimize array append where ti is not a shared type
1086 auto tinext = unqualify(ti.next);
1087 auto sizeelem = tinext.tsize; // array element size
1088 auto isshared = typeid(ti) is typeid(TypeInfo_Shared);
1089 auto length = px.length;
1090 auto newlength = length + n;
1091 auto newsize = newlength * sizeelem;
1092 auto size = length * sizeelem;
1093
1094 if (!gc_expandArrayUsed(px.ptr[0 .. size], newsize, isshared))
1095 {
1096 // could not set the size, we must reallocate.
1097 auto newcap = newCapacity(newlength, sizeelem);
1098 auto attrs = __typeAttrs(tinext, px.ptr) | BlkAttr.APPENDABLE;
1099 auto ptr = cast(byte*) GC.malloc(newcap, attrs, tinext);
1100 if (ptr is null)
1101 {
1102 onOutOfMemoryError();
1103 assert(0);
1104 }
1105
1106 if (newsize != newcap)
1107 {
1108 // For small blocks that are always fully scanned, if we allocated more
1109 // capacity than was requested, we are responsible for zeroing that
1110 // memory.
1111 // TODO: should let the GC figure this out, as this property may
1112 // not always hold.
1113 if (!(attrs & BlkAttr.NO_SCAN) && newcap < PAGESIZE)
1114 memset(ptr + newsize, 0, newcap - newsize);
1115
1116 gc_shrinkArrayUsed(ptr[0 .. newsize], newcap, isshared);
1117 }
1118
1119 memcpy(ptr, px.ptr, size);
1120
1121 // do potsblit processing.
1122 __doPostblit(ptr, size, tinext);
1123
1124 px = ptr[0 .. newlength];
1125 return px;
1126 }
1127
1128 // we were able to expand in place, just update the length
1129 px = px.ptr[0 .. newlength];
1130 return px;
1131 }
1132
1133
1134 /**
1135 Append `dchar` to `char[]`, converting UTF-32 to UTF-8
1136
1137 ---
1138 void main()
1139 {
1140 char[] s;
1141 s ~= 'α';
1142 }
1143 ---
1144
1145 Params:
1146 x = array to append to cast to `byte[]`. Will be modified.
1147 c = `dchar` to append
1148 Returns: updated `x` cast to `void[]`
1149 */
1150 extern (C) void[] _d_arrayappendcd(ref byte[] x, dchar c) @weak
1151 {
1152 // c could encode into from 1 to 4 characters
1153 char[4] buf = void;
1154 char[] appendthis; // passed to appendT
1155 if (c <= 0x7F)
1156 {
1157 buf.ptr[0] = cast(char)c;
1158 appendthis = buf[0..1];
1159 }
1160 else if (c <= 0x7FF)
1161 {
1162 buf.ptr[0] = cast(char)(0xC0 | (c >> 6));
1163 buf.ptr[1] = cast(char)(0x80 | (c & 0x3F));
1164 appendthis = buf[0..2];
1165 }
1166 else if (c <= 0xFFFF)
1167 {
1168 buf.ptr[0] = cast(char)(0xE0 | (c >> 12));
1169 buf.ptr[1] = cast(char)(0x80 | ((c >> 6) & 0x3F));
1170 buf.ptr[2] = cast(char)(0x80 | (c & 0x3F));
1171 appendthis = buf[0..3];
1172 }
1173 else if (c <= 0x10FFFF)
1174 {
1175 buf.ptr[0] = cast(char)(0xF0 | (c >> 18));
1176 buf.ptr[1] = cast(char)(0x80 | ((c >> 12) & 0x3F));
1177 buf.ptr[2] = cast(char)(0x80 | ((c >> 6) & 0x3F));
1178 buf.ptr[3] = cast(char)(0x80 | (c & 0x3F));
1179 appendthis = buf[0..4];
1180 }
1181 else
1182 {
1183 onUnicodeError("Invalid UTF-8 sequence", 0); // invalid utf character
1184 }
1185
1186 //
1187 // TODO: This always assumes the array type is shared, because we do not
1188 // get a typeinfo from the compiler. Assuming shared is the safest option.
1189 // Once the compiler is fixed, the proper typeinfo should be forwarded.
1190 //
1191
1192 // Hack because _d_arrayappendT takes `x` as a reference
1193 auto xx = cast(shared(char)[])x;
1194 object._d_arrayappendT(xx, cast(shared(char)[])appendthis);
1195 x = cast(byte[])xx;
1196 return x;
1197 }
1198
1199 unittest
1200 {
1201 import core.exception : UnicodeException;
1202
1203 /* Using inline try {} catch {} blocks fails to catch the UnicodeException
1204 * thrown.
1205 * https://issues.dlang.org/show_bug.cgi?id=16799
1206 */
1207 static void assertThrown(T : Throwable = Exception, E)(lazy E expr, string msg)
1208 {
1209 try
1210 expr;
1211 catch (T e) {
1212 assert(e.msg == msg);
1213 return;
1214 }
1215 }
1216
1217 static void f()
1218 {
1219 string ret;
1220 int i = -1;
1221 ret ~= i;
1222 }
1223
1224 assertThrown!UnicodeException(f(), "Invalid UTF-8 sequence");
1225 }
1226
1227
1228 /**
1229 Append `dchar` to `wchar[]`, converting UTF-32 to UTF-16
1230
1231 ---
1232 void main()
1233 {
1234 dchar x;
1235 wchar[] s;
1236 s ~= 'α';
1237 }
1238 ---
1239
1240 Params:
1241 x = array to append to cast to `byte[]`. Will be modified.
1242 c = `dchar` to append
1243
1244 Returns: updated `x` cast to `void[]`
1245 */
1246 extern (C) void[] _d_arrayappendwd(ref byte[] x, dchar c) @weak
1247 {
1248 // c could encode into from 1 to 2 w characters
1249 wchar[2] buf = void;
1250 wchar[] appendthis; // passed to appendT
1251 if (c <= 0xFFFF)
1252 {
1253 buf.ptr[0] = cast(wchar) c;
1254 appendthis = buf[0..1];
1255 }
1256 else
1257 {
1258 buf.ptr[0] = cast(wchar) ((((c - 0x10000) >> 10) & 0x3FF) + 0xD800);
1259 buf.ptr[1] = cast(wchar) (((c - 0x10000) & 0x3FF) + 0xDC00);
1260 appendthis = buf[0..2];
1261 }
1262
1263 //
1264 // TODO: This always assumes the array type is shared, because we do not
1265 // get a typeinfo from the compiler. Assuming shared is the safest option.
1266 // Once the compiler is fixed, the proper typeinfo should be forwarded.
1267 //
1268
1269 auto xx = (cast(shared(wchar)*)x.ptr)[0 .. x.length];
1270 object._d_arrayappendT(xx, cast(shared(wchar)[])appendthis);
1271 x = (cast(byte*)xx.ptr)[0 .. xx.length];
1272 return x;
1273 }
1274
1275 /**
1276 Allocate an array literal
1277
1278 Rely on the caller to do the initialization of the array.
1279
1280 ---
1281 int[] getArr()
1282 {
1283 return [10, 20];
1284 // auto res = cast(int*) _d_arrayliteralTX(typeid(int[]), 2);
1285 // res[0] = 10;
1286 // res[1] = 20;
1287 // return res[0..2];
1288 }
1289 ---
1290
1291 Params:
1292 ti = `TypeInfo` of resulting array type
1293 length = `.length` of array literal
1294
1295 Returns: pointer to allocated array
1296 */
1297 extern (C)
1298 void* _d_arrayliteralTX(const TypeInfo ti, size_t length) @weak
1299 {
1300 auto tinext = unqualify(ti.next);
1301 auto sizeelem = tinext.tsize; // array element size
1302 void* result;
1303
1304 debug(PRINTF) printf("_d_arrayliteralTX(sizeelem = %zd, length = %zd)\n", sizeelem, length);
1305 if (length == 0 || sizeelem == 0)
1306 return null;
1307 else
1308 {
1309 auto allocsize = length * sizeelem;
1310 return GC.malloc(allocsize, __typeAttrs(tinext) | BlkAttr.APPENDABLE, tinext);
1311 }
1312 }
1313
1314
1315 unittest
1316 {
1317 int[] a;
1318 int[] b;
1319 int i;
1320
1321 a = new int[3];
1322 a[0] = 1; a[1] = 2; a[2] = 3;
1323 b = a.dup;
1324 assert(b.length == 3);
1325 for (i = 0; i < 3; i++)
1326 assert(b[i] == i + 1);
1327
1328 // test slice appending
1329 b = a[0..1];
1330 b ~= 4;
1331 for (i = 0; i < 3; i++)
1332 assert(a[i] == i + 1);
1333
1334 // test reserving
1335 char[] arr = new char[4093];
1336 for (i = 0; i < arr.length; i++)
1337 arr[i] = cast(char)(i % 256);
1338
1339 // note that these two commands used to cause corruption, which may not be
1340 // detected.
1341 arr.reserve(4094);
1342 auto arr2 = arr ~ "123";
1343 assert(arr2[0..arr.length] == arr);
1344 assert(arr2[arr.length..$] == "123");
1345
1346 // test postblit on array concat, append, length, etc.
1347 static struct S
1348 {
1349 int x;
1350 int pad;
1351 this(this)
1352 {
1353 ++x;
1354 }
1355 }
1356 void testPostBlit(T)()
1357 {
1358 auto sarr = new T[1];
1359 debug(SENTINEL) {} else
1360 assert(sarr.capacity == 1);
1361
1362 // length extend
1363 auto sarr2 = sarr;
1364 assert(sarr[0].x == 0);
1365 sarr2.length += 1;
1366 assert(sarr2[0].x == 1);
1367 assert(sarr[0].x == 0);
1368
1369 // append
1370 T s;
1371 sarr2 = sarr;
1372 sarr2 ~= s;
1373 assert(sarr2[0].x == 1);
1374 assert(sarr2[1].x == 1);
1375 assert(sarr[0].x == 0);
1376 assert(s.x == 0);
1377
1378 // concat
1379 sarr2 = sarr ~ sarr;
1380 assert(sarr2[0].x == 1);
1381 assert(sarr2[1].x == 1);
1382 assert(sarr[0].x == 0);
1383
1384 // concat multiple (calls different method)
1385 sarr2 = sarr ~ sarr ~ sarr;
1386 assert(sarr2[0].x == 1);
1387 assert(sarr2[1].x == 1);
1388 assert(sarr2[2].x == 1);
1389 assert(sarr[0].x == 0);
1390
1391 // reserve capacity
1392 sarr2 = sarr;
1393 sarr2.reserve(2);
1394 assert(sarr2[0].x == 1);
1395 assert(sarr[0].x == 0);
1396 }
1397 testPostBlit!(S)();
1398 testPostBlit!(const(S))();
1399 }
1400
1401 unittest
1402 {
1403 // Bugzilla 3454 - Inconsistent flag setting in GC.realloc()
1404 static void test(size_t multiplier)
1405 {
1406 auto p = GC.malloc(8 * multiplier, 0);
1407 assert(GC.getAttr(p) == 0);
1408
1409 // no move, set attr
1410 p = GC.realloc(p, 8 * multiplier + 5, BlkAttr.NO_SCAN);
1411 assert(GC.getAttr(p) == BlkAttr.NO_SCAN);
1412
1413 // shrink, copy attr
1414 p = GC.realloc(p, 2 * multiplier, 0);
1415 assert(GC.getAttr(p) == BlkAttr.NO_SCAN);
1416
1417 // extend, copy attr
1418 p = GC.realloc(p, 8 * multiplier, 0);
1419 assert(GC.getAttr(p) == BlkAttr.NO_SCAN);
1420 }
1421 test(16);
1422 version (OnlyLowMemUnittests) {} else
1423 test(1024 * 1024);
1424 }
1425
1426 unittest
1427 {
1428 import core.exception;
1429 try
1430 {
1431 size_t x = size_t.max;
1432 byte[] big_buf = new byte[x];
1433 }
1434 catch (OutOfMemoryError)
1435 {
1436 }
1437 }
1438
1439 unittest
1440 {
1441 // https://issues.dlang.org/show_bug.cgi?id=13854
1442 auto arr = new ubyte[PAGESIZE]; // ensure page size
1443 auto info1 = GC.query(arr.ptr);
1444 assert(info1.base !is arr.ptr); // offset is required for page size or larger
1445
1446 auto arr2 = arr[0..1];
1447 assert(arr2.capacity == 0); // cannot append
1448 arr2 ~= 0; // add a byte
1449 assert(arr2.ptr !is arr.ptr); // reallocated
1450 auto info2 = GC.query(arr2.ptr);
1451 assert(info2.base is arr2.ptr); // no offset, the capacity is small.
1452
1453 // do the same via setting length
1454 arr2 = arr[0..1];
1455 assert(arr2.capacity == 0);
1456 arr2.length += 1;
1457 assert(arr2.ptr !is arr.ptr); // reallocated
1458 info2 = GC.query(arr2.ptr);
1459 assert(info2.base is arr2.ptr); // no offset, the capacity is small.
1460
1461 // do the same for char[] since we need a type with an initializer to test certain runtime functions
1462 auto carr = new char[PAGESIZE];
1463 info1 = GC.query(carr.ptr);
1464 assert(info1.base !is carr.ptr); // offset is required for page size or larger
1465
1466 auto carr2 = carr[0..1];
1467 assert(carr2.capacity == 0); // cannot append
1468 carr2 ~= 0; // add a byte
1469 assert(carr2.ptr !is carr.ptr); // reallocated
1470 info2 = GC.query(carr2.ptr);
1471 assert(info2.base is carr2.ptr); // no offset, the capacity is small.
1472
1473 // do the same via setting length
1474 carr2 = carr[0..1];
1475 assert(carr2.capacity == 0);
1476 carr2.length += 1;
1477 assert(carr2.ptr !is carr.ptr); // reallocated
1478 info2 = GC.query(carr2.ptr);
1479 assert(info2.base is carr2.ptr); // no offset, the capacity is small.
1480 }
1481
1482 unittest
1483 {
1484 // https://issues.dlang.org/show_bug.cgi?id=13878
1485 auto arr = new ubyte[1];
1486 auto info = GC.query(arr.ptr);
1487 assert(info.attr & BlkAttr.NO_SCAN); // should be NO_SCAN
1488 arr ~= 0; // ensure array is inserted into cache
1489 debug(SENTINEL) {} else
1490 assert(arr.ptr is info.base);
1491 GC.clrAttr(arr.ptr, BlkAttr.NO_SCAN); // remove the attribute
1492 auto arr2 = arr[0..1];
1493 assert(arr2.capacity == 0); // cannot append
1494 arr2 ~= 0;
1495 assert(arr2.ptr !is arr.ptr);
1496 info = GC.query(arr2.ptr);
1497 assert(!(info.attr & BlkAttr.NO_SCAN)); // ensure attribute sticks
1498
1499 // do the same via setting length
1500 arr = new ubyte[1];
1501 arr ~= 0; // ensure array is inserted into cache
1502 GC.clrAttr(arr.ptr, BlkAttr.NO_SCAN); // remove the attribute
1503 arr2 = arr[0..1];
1504 assert(arr2.capacity == 0);
1505 arr2.length += 1;
1506 assert(arr2.ptr !is arr.ptr); // reallocated
1507 info = GC.query(arr2.ptr);
1508 assert(!(info.attr & BlkAttr.NO_SCAN)); // ensure attribute sticks
1509
1510 // do the same for char[] since we need a type with an initializer to test certain runtime functions
1511 auto carr = new char[1];
1512 info = GC.query(carr.ptr);
1513 assert(info.attr & BlkAttr.NO_SCAN); // should be NO_SCAN
1514 carr ~= 0; // ensure array is inserted into cache
1515 debug(SENTINEL) {} else
1516 assert(carr.ptr is info.base);
1517 GC.clrAttr(carr.ptr, BlkAttr.NO_SCAN); // remove the attribute
1518 auto carr2 = carr[0..1];
1519 assert(carr2.capacity == 0); // cannot append
1520 carr2 ~= 0;
1521 assert(carr2.ptr !is carr.ptr);
1522 info = GC.query(carr2.ptr);
1523 assert(!(info.attr & BlkAttr.NO_SCAN)); // ensure attribute sticks
1524
1525 // do the same via setting length
1526 carr = new char[1];
1527 carr ~= 0; // ensure array is inserted into cache
1528 GC.clrAttr(carr.ptr, BlkAttr.NO_SCAN); // remove the attribute
1529 carr2 = carr[0..1];
1530 assert(carr2.capacity == 0);
1531 carr2.length += 1;
1532 assert(carr2.ptr !is carr.ptr); // reallocated
1533 info = GC.query(carr2.ptr);
1534 assert(!(info.attr & BlkAttr.NO_SCAN)); // ensure attribute sticks
1535 }
1536
1537 // test struct finalizers
1538 debug(SENTINEL) {} else
1539 deprecated unittest
1540 {
1541 __gshared int dtorCount;
1542 static struct S1
1543 {
1544 int x;
1545
1546 ~this()
1547 {
1548 dtorCount++;
1549 }
1550 }
1551
1552 dtorCount = 0;
1553 S1* s2 = new S1;
1554 GC.runFinalizers((cast(char*)(typeid(S1).xdtor))[0..1]);
1555 assert(dtorCount == 1);
1556 GC.free(s2);
1557
1558 dtorCount = 0;
1559 const(S1)* s3 = new const(S1);
1560 GC.runFinalizers((cast(char*)(typeid(S1).xdtor))[0..1]);
1561 assert(dtorCount == 1);
1562 GC.free(cast(void*)s3);
1563
1564 dtorCount = 0;
1565 shared(S1)* s4 = new shared(S1);
1566 GC.runFinalizers((cast(char*)(typeid(S1).xdtor))[0..1]);
1567 assert(dtorCount == 1);
1568 GC.free(cast(void*)s4);
1569
1570 dtorCount = 0;
1571 const(S1)[] carr1 = new const(S1)[5];
1572 auto blkinf1 = GC.query(carr1.ptr);
1573 GC.runFinalizers((cast(char*)(typeid(S1).xdtor))[0..1]);
1574 assert(dtorCount == 5);
1575 GC.free(blkinf1.base);
1576
1577 dtorCount = 0;
1578 S1[] arr2 = new S1[10];
1579 arr2.length = 6;
1580 arr2.assumeSafeAppend;
1581 assert(dtorCount == 4); // destructors run explicitely?
1582
1583 dtorCount = 0;
1584 auto blkinf = GC.query(arr2.ptr);
1585 GC.runFinalizers((cast(char*)(typeid(S1).xdtor))[0..1]);
1586 assert(dtorCount == 6);
1587 GC.free(blkinf.base);
1588
1589 // associative arrays
1590 S1[int] aa1;
1591 aa1[0] = S1(0);
1592 aa1[1] = S1(1);
1593 dtorCount = 0;
1594 aa1 = null;
1595 auto dtor1 = typeid(TypeInfo_AssociativeArray.Entry!(int, S1)).xdtor;
1596 GC.runFinalizers((cast(char*)dtor1)[0..1]);
1597 assert(dtorCount == 2);
1598
1599 int[S1] aa2;
1600 aa2[S1(0)] = 0;
1601 aa2[S1(1)] = 1;
1602 aa2[S1(2)] = 2;
1603 dtorCount = 0;
1604 aa2 = null;
1605 auto dtor2 = typeid(TypeInfo_AssociativeArray.Entry!(S1, int)).xdtor;
1606 GC.runFinalizers((cast(char*)dtor2)[0..1]);
1607 assert(dtorCount == 3);
1608
1609 S1[2][int] aa3;
1610 aa3[0] = [S1(0),S1(2)];
1611 aa3[1] = [S1(1),S1(3)];
1612 dtorCount = 0;
1613 aa3 = null;
1614 auto dtor3 = typeid(TypeInfo_AssociativeArray.Entry!(int, S1[2])).xdtor;
1615 GC.runFinalizers((cast(char*)dtor3)[0..1]);
1616 assert(dtorCount == 4);
1617 }
1618
1619 // test struct dtor handling not causing false pointers
1620 unittest
1621 {
1622 // for 64-bit, allocate a struct of size 40
1623 static struct S
1624 {
1625 size_t[4] data;
1626 S* ptr4;
1627 }
1628 auto p1 = new S;
1629 auto p2 = new S;
1630 p2.ptr4 = p1;
1631
1632 // a struct with a dtor with size 32, but the dtor will cause
1633 // allocation to be larger by a pointer
1634 static struct A
1635 {
1636 size_t[3] data;
1637 S* ptr3;
1638
1639 ~this() {}
1640 }
1641
1642 GC.free(p2);
1643 auto a = new A; // reuse same memory
1644 if (cast(void*)a is cast(void*)p2) // reusage not guaranteed
1645 {
1646 auto ptr = cast(S**)(a + 1);
1647 assert(*ptr != p1); // still same data as p2.ptr4?
1648 }
1649
1650 // small array
1651 static struct SArr
1652 {
1653 void*[10] data;
1654 }
1655 auto arr1 = new SArr;
1656 arr1.data[] = p1;
1657 GC.free(arr1);
1658
1659 // allocates 2*A.sizeof + (void*).sizeof (TypeInfo) + 1 (array length)
1660 auto arr2 = new A[2];
1661 if (cast(void*)arr1 is cast(void*)arr2.ptr) // reusage not guaranteed
1662 {
1663 auto ptr = cast(S**)(arr2.ptr + 2);
1664 assert(*ptr != p1); // still same data as p2.ptr4?
1665 }
1666
1667 // large array
1668 static struct LArr
1669 {
1670 void*[1023] data;
1671 }
1672 auto larr1 = new LArr;
1673 larr1.data[] = p1;
1674 GC.free(larr1);
1675
1676 auto larr2 = new S[255];
1677 import core.internal.gc.blockmeta : LARGEPREFIX;
1678 if (cast(void*)larr1 is cast(void*)larr2.ptr - LARGEPREFIX) // reusage not guaranteed
1679 {
1680 auto ptr = cast(S**)larr1;
1681 assert(ptr[0] != p1); // 16 bytes array header
1682 assert(ptr[1] != p1);
1683 version (D_LP64) {} else
1684 {
1685 assert(ptr[2] != p1);
1686 assert(ptr[3] != p1);
1687 }
1688 }
1689 }
1690
1691 // test class finalizers exception handling
1692 unittest
1693 {
1694 bool test(E)()
1695 {
1696 import core.exception;
1697 static class C1
1698 {
1699 E exc;
1700 this(E exc) { this.exc = exc; }
1701 ~this() { throw exc; }
1702 }
1703
1704 bool caught = false;
1705 C1 c = new C1(new E("test onFinalizeError"));
1706 try
1707 {
1708 GC.runFinalizers((cast(uint*)&C1.__dtor)[0..1]);
1709 }
1710 catch (FinalizeError err)
1711 {
1712 caught = true;
1713 }
1714 catch (E)
1715 {
1716 }
1717 GC.free(cast(void*)c);
1718 return caught;
1719 }
1720
1721 assert( test!Exception);
1722 import core.exception : InvalidMemoryOperationError;
1723 assert(!test!InvalidMemoryOperationError);
1724 }
1725
1726 // test bug 14126
1727 unittest
1728 {
1729 static struct S
1730 {
1731 S* thisptr;
1732 ~this() { assert(&this == thisptr); thisptr = null;}
1733 }
1734
1735 S[] test14126 = new S[2048]; // make sure we allocate at least a PAGE
1736 foreach (ref s; test14126)
1737 {
1738 s.thisptr = &s;
1739 }
1740 }