This repository has been archived by the owner on Oct 12, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 424
/
lifetime.d
2836 lines (2506 loc) · 78.3 KB
/
lifetime.d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* This module contains all functions related to an object's lifetime:
* allocation, resizing, deallocation, and finalization.
*
* Copyright: Copyright Digital Mars 2000 - 2012.
* License: Distributed under the
* $(LINK2 http://www.boost.org/LICENSE_1_0.txt, Boost Software License 1.0).
* (See accompanying file LICENSE)
* Authors: Walter Bright, Sean Kelly, Steven Schveighoffer
* Source: $(DRUNTIMESRC rt/_lifetime.d)
*/
module rt.lifetime;
import core.memory;
debug(PRINTF) import core.stdc.stdio;
static import rt.tlsgc;
alias BlkInfo = GC.BlkInfo;
alias BlkAttr = GC.BlkAttr;
private
{
alias bool function(Object) CollectHandler;
__gshared CollectHandler collectHandler = null;
extern (C) void _d_monitordelete(Object h, bool det);
enum : size_t
{
PAGESIZE = 4096,
BIGLENGTHMASK = ~(PAGESIZE - 1),
SMALLPAD = 1,
MEDPAD = ushort.sizeof,
LARGEPREFIX = 16, // 16 bytes padding at the front of the array
LARGEPAD = LARGEPREFIX + 1,
MAXSMALLSIZE = 256-SMALLPAD,
MAXMEDSIZE = (PAGESIZE / 2) - MEDPAD
}
}
extern (C) void lifetime_init()
{
// this is run before static ctors, so it is safe to modify immutables
}
/**
*
*/
extern (C) void* _d_allocmemory(size_t sz)
{
return GC.malloc(sz);
}
/**
*
*/
extern (C) Object _d_newclass(const ClassInfo ci)
{
import core.stdc.stdlib;
import core.exception : onOutOfMemoryError;
void* p;
auto init = ci.initializer;
debug(PRINTF) printf("_d_newclass(ci = %p, %s)\n", ci, cast(char *)ci.name);
if (ci.m_flags & TypeInfo_Class.ClassFlags.isCOMclass)
{ /* COM objects are not garbage collected, they are reference counted
* using AddRef() and Release(). They get free'd by C's free()
* function called by Release() when Release()'s reference count goes
* to zero.
*/
p = malloc(init.length);
if (!p)
onOutOfMemoryError();
}
else
{
// TODO: should this be + 1 to avoid having pointers to the next block?
BlkAttr attr = BlkAttr.NONE;
// extern(C++) classes don't have a classinfo pointer in their vtable so the GC can't finalize them
if (ci.m_flags & TypeInfo_Class.ClassFlags.hasDtor
&& !(ci.m_flags & TypeInfo_Class.ClassFlags.isCPPclass))
attr |= BlkAttr.FINALIZE;
if (ci.m_flags & TypeInfo_Class.ClassFlags.noPointers)
attr |= BlkAttr.NO_SCAN;
p = GC.malloc(init.length, attr, ci);
debug(PRINTF) printf(" p = %p\n", p);
}
debug(PRINTF)
{
printf("p = %p\n", p);
printf("ci = %p, ci.init.ptr = %p, len = %llu\n", ci, init.ptr, cast(ulong)init.length);
printf("vptr = %p\n", *cast(void**) init);
printf("vtbl[0] = %p\n", (*cast(void***) init)[0]);
printf("vtbl[1] = %p\n", (*cast(void***) init)[1]);
printf("init[0] = %x\n", (cast(uint*) init)[0]);
printf("init[1] = %x\n", (cast(uint*) init)[1]);
printf("init[2] = %x\n", (cast(uint*) init)[2]);
printf("init[3] = %x\n", (cast(uint*) init)[3]);
printf("init[4] = %x\n", (cast(uint*) init)[4]);
}
// initialize it
p[0 .. init.length] = init[];
debug(PRINTF) printf("initialization done\n");
return cast(Object) p;
}
/**
*
*/
extern (C) void _d_delinterface(void** p)
{
if (*p)
{
Interface* pi = **cast(Interface ***)*p;
Object o = cast(Object)(*p - pi.offset);
_d_delclass(&o);
*p = null;
}
}
// used for deletion
private extern (D) alias void function (Object) fp_t;
/**
*
*/
extern (C) void _d_delclass(Object* p)
{
if (*p)
{
debug(PRINTF) printf("_d_delclass(%p)\n", *p);
ClassInfo **pc = cast(ClassInfo **)*p;
if (*pc)
{
ClassInfo c = **pc;
rt_finalize(cast(void*) *p);
if (c.deallocator)
{
fp_t fp = cast(fp_t)c.deallocator;
(*fp)(*p); // call deallocator
*p = null;
return;
}
}
else
{
rt_finalize(cast(void*) *p);
}
GC.free(cast(void*) *p);
*p = null;
}
}
/**
* This is called for a delete statement where the value
* being deleted is a pointer to a struct with a destructor
* but doesn't have an overloaded delete operator.
*/
extern (C) void _d_delstruct(void** p, TypeInfo_Struct inf)
{
if (*p)
{
debug(PRINTF) printf("_d_delstruct(%p, %p)\n", *p, cast(void*)inf);
inf.destroy(*p);
GC.free(*p);
*p = null;
}
}
// strip const/immutable/shared/inout from type info
inout(TypeInfo) unqualify(inout(TypeInfo) cti) pure nothrow @nogc
{
TypeInfo ti = cast() cti;
while (ti)
{
// avoid dynamic type casts
auto tti = typeid(ti);
if (tti is typeid(TypeInfo_Const))
ti = (cast(TypeInfo_Const)cast(void*)ti).base;
else if (tti is typeid(TypeInfo_Invariant))
ti = (cast(TypeInfo_Invariant)cast(void*)ti).base;
else if (tti is typeid(TypeInfo_Shared))
ti = (cast(TypeInfo_Shared)cast(void*)ti).base;
else if (tti is typeid(TypeInfo_Inout))
ti = (cast(TypeInfo_Inout)cast(void*)ti).base;
else
break;
}
return ti;
}
// size used to store the TypeInfo at the end of an allocation for structs that have a destructor
size_t structTypeInfoSize(const TypeInfo ti) pure nothrow @nogc
{
if (ti && typeid(ti) is typeid(TypeInfo_Struct)) // avoid a complete dynamic type cast
{
auto sti = cast(TypeInfo_Struct)cast(void*)ti;
if (sti.xdtor)
return size_t.sizeof;
}
return 0;
}
/** dummy class used to lock for shared array appending */
private class ArrayAllocLengthLock
{}
/**
Set the allocated length of the array block. This is called
any time an array is appended to or its length is set.
The allocated block looks like this for blocks < PAGESIZE:
|elem0|elem1|elem2|...|elemN-1|emptyspace|N*elemsize|
The size of the allocated length at the end depends on the block size:
a block of 16 to 256 bytes has an 8-bit length.
a block with 512 to pagesize/2 bytes has a 16-bit length.
For blocks >= pagesize, the length is a size_t and is at the beginning of the
block. The reason we have to do this is because the block can extend into
more pages, so we cannot trust the block length if it sits at the end of the
block, because it might have just been extended. If we can prove in the
future that the block is unshared, we may be able to change this, but I'm not
sure it's important.
In order to do put the length at the front, we have to provide 16 bytes
buffer space in case the block has to be aligned properly. In x86, certain
SSE instructions will only work if the data is 16-byte aligned. In addition,
we need the sentinel byte to prevent accidental pointers to the next block.
Because of the extra overhead, we only do this for page size and above, where
the overhead is minimal compared to the block size.
So for those blocks, it looks like:
|N*elemsize|padding|elem0|elem1|...|elemN-1|emptyspace|sentinelbyte|
where elem0 starts 16 bytes after the first byte.
*/
bool __setArrayAllocLength(ref BlkInfo info, size_t newlength, bool isshared, const TypeInfo tinext, size_t oldlength = ~0) pure nothrow
{
import core.atomic;
size_t typeInfoSize = structTypeInfoSize(tinext);
if (info.size <= 256)
{
import core.checkedint;
bool overflow;
auto newlength_padded = addu(newlength,
addu(SMALLPAD, typeInfoSize, overflow),
overflow);
if (newlength_padded > info.size || overflow)
// new size does not fit inside block
return false;
auto length = cast(ubyte *)(info.base + info.size - typeInfoSize - SMALLPAD);
if (oldlength != ~0)
{
if (isshared)
{
return cas(cast(shared)length, cast(ubyte)oldlength, cast(ubyte)newlength);
}
else
{
if (*length == cast(ubyte)oldlength)
*length = cast(ubyte)newlength;
else
return false;
}
}
else
{
// setting the initial length, no cas needed
*length = cast(ubyte)newlength;
}
if (typeInfoSize)
{
auto typeInfo = cast(TypeInfo*)(info.base + info.size - size_t.sizeof);
*typeInfo = cast() tinext;
}
}
else if (info.size < PAGESIZE)
{
if (newlength + MEDPAD + typeInfoSize > info.size)
// new size does not fit inside block
return false;
auto length = cast(ushort *)(info.base + info.size - typeInfoSize - MEDPAD);
if (oldlength != ~0)
{
if (isshared)
{
return cas(cast(shared)length, cast(ushort)oldlength, cast(ushort)newlength);
}
else
{
if (*length == oldlength)
*length = cast(ushort)newlength;
else
return false;
}
}
else
{
// setting the initial length, no cas needed
*length = cast(ushort)newlength;
}
if (typeInfoSize)
{
auto typeInfo = cast(TypeInfo*)(info.base + info.size - size_t.sizeof);
*typeInfo = cast() tinext;
}
}
else
{
if (newlength + LARGEPAD > info.size)
// new size does not fit inside block
return false;
auto length = cast(size_t *)(info.base);
if (oldlength != ~0)
{
if (isshared)
{
return cas(cast(shared)length, cast(size_t)oldlength, cast(size_t)newlength);
}
else
{
if (*length == oldlength)
*length = newlength;
else
return false;
}
}
else
{
// setting the initial length, no cas needed
*length = newlength;
}
if (typeInfoSize)
{
auto typeInfo = cast(TypeInfo*)(info.base + size_t.sizeof);
*typeInfo = cast()tinext;
}
}
return true; // resize succeeded
}
/**
get the allocation size of the array for the given block (without padding or type info)
*/
size_t __arrayAllocLength(ref BlkInfo info, const TypeInfo tinext) pure nothrow
{
if (info.size <= 256)
return *cast(ubyte *)(info.base + info.size - structTypeInfoSize(tinext) - SMALLPAD);
if (info.size < PAGESIZE)
return *cast(ushort *)(info.base + info.size - structTypeInfoSize(tinext) - MEDPAD);
return *cast(size_t *)(info.base);
}
/**
get the start of the array for the given block
*/
void *__arrayStart(return BlkInfo info) nothrow pure
{
return info.base + ((info.size & BIGLENGTHMASK) ? LARGEPREFIX : 0);
}
/**
get the padding required to allocate size bytes. Note that the padding is
NOT included in the passed in size. Therefore, do NOT call this function
with the size of an allocated block.
*/
size_t __arrayPad(size_t size, const TypeInfo tinext) nothrow pure @trusted
{
return size > MAXMEDSIZE ? LARGEPAD : ((size > MAXSMALLSIZE ? MEDPAD : SMALLPAD) + structTypeInfoSize(tinext));
}
/**
clear padding that might not be zeroed by the GC (it assumes it is within the
requested size from the start, but it is actually at the end of the allocated block)
*/
private void __arrayClearPad(ref BlkInfo info, size_t arrsize, size_t padsize) nothrow pure
{
import core.stdc.string;
if (padsize > MEDPAD && !(info.attr & BlkAttr.NO_SCAN) && info.base)
{
if (info.size < PAGESIZE)
memset(info.base + arrsize, 0, padsize);
else
memset(info.base, 0, LARGEPREFIX);
}
}
/**
allocate an array memory block by applying the proper padding and
assigning block attributes if not inherited from the existing block
*/
BlkInfo __arrayAlloc(size_t arrsize, const TypeInfo ti, const TypeInfo tinext) nothrow pure
{
import core.checkedint;
size_t typeInfoSize = structTypeInfoSize(tinext);
size_t padsize = arrsize > MAXMEDSIZE ? LARGEPAD : ((arrsize > MAXSMALLSIZE ? MEDPAD : SMALLPAD) + typeInfoSize);
bool overflow;
auto padded_size = addu(arrsize, padsize, overflow);
if (overflow)
return BlkInfo();
uint attr = (!(tinext.flags & 1) ? BlkAttr.NO_SCAN : 0) | BlkAttr.APPENDABLE;
if (typeInfoSize)
attr |= BlkAttr.STRUCTFINAL | BlkAttr.FINALIZE;
auto bi = GC.qalloc(padded_size, attr, tinext);
__arrayClearPad(bi, arrsize, padsize);
return bi;
}
BlkInfo __arrayAlloc(size_t arrsize, ref BlkInfo info, const TypeInfo ti, const TypeInfo tinext)
{
import core.checkedint;
if (!info.base)
return __arrayAlloc(arrsize, ti, tinext);
immutable padsize = __arrayPad(arrsize, tinext);
bool overflow;
auto padded_size = addu(arrsize, padsize, overflow);
if (overflow)
{
return BlkInfo();
}
auto bi = GC.qalloc(padded_size, info.attr, tinext);
__arrayClearPad(bi, arrsize, padsize);
return bi;
}
/**
cache for the lookup of the block info
*/
enum N_CACHE_BLOCKS=8;
// note this is TLS, so no need to sync.
BlkInfo *__blkcache_storage;
static if (N_CACHE_BLOCKS==1)
{
version=single_cache;
}
else
{
//version=simple_cache; // uncomment to test simple cache strategy
//version=random_cache; // uncomment to test random cache strategy
// ensure N_CACHE_BLOCKS is power of 2.
static assert(!((N_CACHE_BLOCKS - 1) & N_CACHE_BLOCKS));
version (random_cache)
{
int __nextRndNum = 0;
}
int __nextBlkIdx;
}
@property BlkInfo *__blkcache() nothrow
{
if (!__blkcache_storage)
{
import core.stdc.stdlib;
import core.stdc.string;
// allocate the block cache for the first time
immutable size = BlkInfo.sizeof * N_CACHE_BLOCKS;
__blkcache_storage = cast(BlkInfo *)malloc(size);
memset(__blkcache_storage, 0, size);
}
return __blkcache_storage;
}
// called when thread is exiting.
static ~this()
{
// free the blkcache
if (__blkcache_storage)
{
import core.stdc.stdlib;
free(__blkcache_storage);
__blkcache_storage = null;
}
}
// we expect this to be called with the lock in place
void processGCMarks(BlkInfo* cache, scope rt.tlsgc.IsMarkedDg isMarked) nothrow
{
// called after the mark routine to eliminate block cache data when it
// might be ready to sweep
debug(PRINTF) printf("processing GC Marks, %x\n", cache);
if (cache)
{
debug(PRINTF) foreach (i; 0 .. N_CACHE_BLOCKS)
{
printf("cache entry %d has base ptr %x\tsize %d\tflags %x\n", i, cache[i].base, cache[i].size, cache[i].attr);
}
auto cache_end = cache + N_CACHE_BLOCKS;
for (;cache < cache_end; ++cache)
{
if (cache.base != null && !isMarked(cache.base))
{
debug(PRINTF) printf("clearing cache entry at %x\n", cache.base);
cache.base = null; // clear that data.
}
}
}
}
unittest
{
// Bugzilla 10701 - segfault in GC
ubyte[] result; result.length = 4096;
GC.free(result.ptr);
GC.collect();
}
/**
Get the cached block info of an interior pointer. Returns null if the
interior pointer's block is not cached.
NOTE: The base ptr in this struct can be cleared asynchronously by the GC,
so any use of the returned BlkInfo should copy it and then check the
base ptr of the copy before actually using it.
TODO: Change this function so the caller doesn't have to be aware of this
issue. Either return by value and expect the caller to always check
the base ptr as an indication of whether the struct is valid, or set
the BlkInfo as a side-effect and return a bool to indicate success.
*/
BlkInfo *__getBlkInfo(void *interior) nothrow
{
BlkInfo *ptr = __blkcache;
version (single_cache)
{
if (ptr.base && ptr.base <= interior && (interior - ptr.base) < ptr.size)
return ptr;
return null; // not in cache.
}
else version (simple_cache)
{
foreach (i; 0..N_CACHE_BLOCKS)
{
if (ptr.base && ptr.base <= interior && (interior - ptr.base) < ptr.size)
return ptr;
ptr++;
}
}
else
{
// try to do a smart lookup, using __nextBlkIdx as the "head"
auto curi = ptr + __nextBlkIdx;
for (auto i = curi; i >= ptr; --i)
{
if (i.base && i.base <= interior && cast(size_t)(interior - i.base) < i.size)
return i;
}
for (auto i = ptr + N_CACHE_BLOCKS - 1; i > curi; --i)
{
if (i.base && i.base <= interior && cast(size_t)(interior - i.base) < i.size)
return i;
}
}
return null; // not in cache.
}
void __insertBlkInfoCache(BlkInfo bi, BlkInfo *curpos) nothrow
{
version (single_cache)
{
*__blkcache = bi;
}
else
{
version (simple_cache)
{
if (curpos)
*curpos = bi;
else
{
// note, this is a super-simple algorithm that does not care about
// most recently used. It simply uses a round-robin technique to
// cache block info. This means that the ordering of the cache
// doesn't mean anything. Certain patterns of allocation may
// render the cache near-useless.
__blkcache[__nextBlkIdx] = bi;
__nextBlkIdx = (__nextBlkIdx+1) & (N_CACHE_BLOCKS - 1);
}
}
else version (random_cache)
{
// strategy: if the block currently is in the cache, move the
// current block index to the a random element and evict that
// element.
auto cache = __blkcache;
if (!curpos)
{
__nextBlkIdx = (__nextRndNum = 1664525 * __nextRndNum + 1013904223) & (N_CACHE_BLOCKS - 1);
curpos = cache + __nextBlkIdx;
}
else
{
__nextBlkIdx = curpos - cache;
}
*curpos = bi;
}
else
{
//
// strategy: If the block currently is in the cache, swap it with
// the head element. Otherwise, move the head element up by one,
// and insert it there.
//
auto cache = __blkcache;
if (!curpos)
{
__nextBlkIdx = (__nextBlkIdx+1) & (N_CACHE_BLOCKS - 1);
curpos = cache + __nextBlkIdx;
}
else if (curpos !is cache + __nextBlkIdx)
{
*curpos = cache[__nextBlkIdx];
curpos = cache + __nextBlkIdx;
}
*curpos = bi;
}
}
}
/**
* Shrink the "allocated" length of an array to be the exact size of the array.
* It doesn't matter what the current allocated length of the array is, the
* user is telling the runtime that he knows what he is doing.
*/
extern(C) void _d_arrayshrinkfit(const TypeInfo ti, void[] arr) /+nothrow+/
{
// note, we do not care about shared. We are setting the length no matter
// what, so no lock is required.
debug(PRINTF) printf("_d_arrayshrinkfit, elemsize = %d, arr.ptr = x%x arr.length = %d\n", ti.next.tsize, arr.ptr, arr.length);
auto tinext = unqualify(ti.next);
auto size = tinext.tsize; // array element size
auto cursize = arr.length * size;
auto isshared = typeid(ti) is typeid(TypeInfo_Shared);
auto bic = isshared ? null : __getBlkInfo(arr.ptr);
auto info = bic ? *bic : GC.query(arr.ptr);
if (info.base && (info.attr & BlkAttr.APPENDABLE))
{
auto newsize = (arr.ptr - __arrayStart(info)) + cursize;
debug(PRINTF) printf("setting allocated size to %d\n", (arr.ptr - info.base) + cursize);
// destroy structs that become unused memory when array size is shrinked
if (typeid(tinext) is typeid(TypeInfo_Struct)) // avoid a complete dynamic type cast
{
auto sti = cast(TypeInfo_Struct)cast(void*)tinext;
if (sti.xdtor)
{
auto oldsize = __arrayAllocLength(info, tinext);
if (oldsize > cursize)
finalize_array(arr.ptr + cursize, oldsize - cursize, sti);
}
}
// Note: Since we "assume" the append is safe, it means it is not shared.
// Since it is not shared, we also know it won't throw (no lock).
if (!__setArrayAllocLength(info, newsize, false, tinext))
{
import core.exception : onInvalidMemoryOperationError;
onInvalidMemoryOperationError();
}
// cache the block if not already done.
if (!isshared && !bic)
__insertBlkInfoCache(info, null);
}
}
package bool hasPostblit(in TypeInfo ti)
{
return (&ti.postblit).funcptr !is &TypeInfo.postblit;
}
void __doPostblit(void *ptr, size_t len, const TypeInfo ti)
{
if (!hasPostblit(ti))
return;
if (auto tis = cast(TypeInfo_Struct)ti)
{
// this is a struct, check the xpostblit member
auto pblit = tis.xpostblit;
if (!pblit)
// postblit not specified, no point in looping.
return;
// optimized for struct, call xpostblit directly for each element
immutable size = ti.tsize;
const eptr = ptr + len;
for (;ptr < eptr;ptr += size)
pblit(ptr);
}
else
{
// generic case, call the typeinfo's postblit function
immutable size = ti.tsize;
const eptr = ptr + len;
for (;ptr < eptr;ptr += size)
ti.postblit(ptr);
}
}
/**
* set the array capacity. If the array capacity isn't currently large enough
* to hold the requested capacity (in number of elements), then the array is
* resized/reallocated to the appropriate size. Pass in a requested capacity
* of 0 to get the current capacity. Returns the number of elements that can
* actually be stored once the resizing is done.
*/
extern(C) size_t _d_arraysetcapacity(const TypeInfo ti, size_t newcapacity, void[]* p)
in
{
assert(ti);
assert(!(*p).length || (*p).ptr);
}
do
{
import core.stdc.string;
import core.exception : onOutOfMemoryError;
// step 1, get the block
auto isshared = typeid(ti) is typeid(TypeInfo_Shared);
auto bic = isshared ? null : __getBlkInfo((*p).ptr);
auto info = bic ? *bic : GC.query((*p).ptr);
auto tinext = unqualify(ti.next);
auto size = tinext.tsize;
version (D_InlineAsm_X86)
{
size_t reqsize = void;
asm
{
mov EAX, newcapacity;
mul EAX, size;
mov reqsize, EAX;
jnc Lcontinue;
}
}
else version (D_InlineAsm_X86_64)
{
size_t reqsize = void;
asm
{
mov RAX, newcapacity;
mul RAX, size;
mov reqsize, RAX;
jnc Lcontinue;
}
}
else
{
import core.checkedint : mulu;
bool overflow = false;
size_t reqsize = mulu(size, newcapacity, overflow);
if (!overflow)
goto Lcontinue;
}
Loverflow:
onOutOfMemoryError();
assert(0);
Lcontinue:
// step 2, get the actual "allocated" size. If the allocated size does not
// match what we expect, then we will need to reallocate anyways.
// TODO: this probably isn't correct for shared arrays
size_t curallocsize = void;
size_t curcapacity = void;
size_t offset = void;
size_t arraypad = void;
if (info.base && (info.attr & BlkAttr.APPENDABLE))
{
if (info.size <= 256)
{
arraypad = SMALLPAD + structTypeInfoSize(tinext);
curallocsize = *(cast(ubyte *)(info.base + info.size - arraypad));
}
else if (info.size < PAGESIZE)
{
arraypad = MEDPAD + structTypeInfoSize(tinext);
curallocsize = *(cast(ushort *)(info.base + info.size - arraypad));
}
else
{
curallocsize = *(cast(size_t *)(info.base));
arraypad = LARGEPAD;
}
offset = (*p).ptr - __arrayStart(info);
if (offset + (*p).length * size != curallocsize)
{
curcapacity = 0;
}
else
{
// figure out the current capacity of the block from the point
// of view of the array.
curcapacity = info.size - offset - arraypad;
}
}
else
{
curallocsize = curcapacity = offset = 0;
}
debug(PRINTF) printf("_d_arraysetcapacity, p = x%d,%d, newcapacity=%d, info.size=%d, reqsize=%d, curallocsize=%d, curcapacity=%d, offset=%d\n", (*p).ptr, (*p).length, newcapacity, info.size, reqsize, curallocsize, curcapacity, offset);
if (curcapacity >= reqsize)
{
// no problems, the current allocated size is large enough.
return curcapacity / size;
}
// step 3, try to extend the array in place.
if (info.size >= PAGESIZE && curcapacity != 0)
{
auto extendsize = reqsize + offset + LARGEPAD - info.size;
auto u = GC.extend(info.base, extendsize, extendsize);
if (u)
{
// extend worked, save the new current allocated size
if (bic)
bic.size = u; // update cache
curcapacity = u - offset - LARGEPAD;
return curcapacity / size;
}
}
// step 4, if extending doesn't work, allocate a new array with at least the requested allocated size.
auto datasize = (*p).length * size;
// copy attributes from original block, or from the typeinfo if the
// original block doesn't exist.
info = __arrayAlloc(reqsize, info, ti, tinext);
if (info.base is null)
goto Loverflow;
// copy the data over.
// note that malloc will have initialized the data we did not request to 0.
auto tgt = __arrayStart(info);
memcpy(tgt, (*p).ptr, datasize);
// handle postblit
__doPostblit(tgt, datasize, tinext);
if (!(info.attr & BlkAttr.NO_SCAN))
{
// need to memset the newly requested data, except for the data that
// malloc returned that we didn't request.
void *endptr = tgt + reqsize;
void *begptr = tgt + datasize;
// sanity check
assert(endptr >= begptr);
memset(begptr, 0, endptr - begptr);
}
// set up the correct length
__setArrayAllocLength(info, datasize, isshared, tinext);
if (!isshared)
__insertBlkInfoCache(info, bic);
*p = (cast(void*)tgt)[0 .. (*p).length];
// determine the padding. This has to be done manually because __arrayPad
// assumes you are not counting the pad size, and info.size does include
// the pad.
if (info.size <= 256)
arraypad = SMALLPAD + structTypeInfoSize(tinext);
else if (info.size < PAGESIZE)
arraypad = MEDPAD + structTypeInfoSize(tinext);
else
arraypad = LARGEPAD;
curcapacity = info.size - arraypad;
return curcapacity / size;
}
/**
* Allocate a new uninitialized array of length elements.
* ti is the type of the resulting array, or pointer to element.
*/
extern (C) void[] _d_newarrayU(const TypeInfo ti, size_t length) pure nothrow
{
import core.exception : onOutOfMemoryError;
auto tinext = unqualify(ti.next);
auto size = tinext.tsize;
debug(PRINTF) printf("_d_newarrayU(length = x%x, size = %d)\n", length, size);
if (length == 0 || size == 0)
return null;
version (D_InlineAsm_X86)
{
asm pure nothrow @nogc
{
mov EAX,size ;
mul EAX,length ;
mov size,EAX ;
jnc Lcontinue ;
}
}
else version (D_InlineAsm_X86_64)
{
asm pure nothrow @nogc
{
mov RAX,size ;
mul RAX,length ;
mov size,RAX ;
jnc Lcontinue ;
}
}
else
{
import core.checkedint : mulu;
bool overflow = false;
size = mulu(size, length, overflow);
if (!overflow)
goto Lcontinue;
}
Loverflow:
onOutOfMemoryError();
assert(0);
Lcontinue:
auto info = __arrayAlloc(size, ti, tinext);
if (!info.base)
goto Loverflow;
debug(PRINTF) printf(" p = %p\n", info.base);
// update the length of the array
auto arrstart = __arrayStart(info);
auto isshared = typeid(ti) is typeid(TypeInfo_Shared);
__setArrayAllocLength(info, size, isshared, tinext);
return arrstart[0..length];
}
/**
* Allocate a new array of length elements.
* ti is the type of the resulting array, or pointer to element.
* (For when the array is initialized to 0)
*/
extern (C) void[] _d_newarrayT(const TypeInfo ti, size_t length) pure nothrow
{
import core.stdc.string;
void[] result = _d_newarrayU(ti, length);
auto tinext = unqualify(ti.next);
auto size = tinext.tsize;
memset(result.ptr, 0, size * length);
return result;
}
/**
* For when the array has a non-zero initializer.
*/
extern (C) void[] _d_newarrayiT(const TypeInfo ti, size_t length) pure nothrow
{
import core.internal.traits : AliasSeq;