-
Notifications
You must be signed in to change notification settings - Fork 5
/
mem.cpp
1703 lines (1420 loc) · 53.2 KB
/
mem.cpp
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
#include "mem.h"
#pragma warning(disable:6011)
#pragma warning(disable:28182)
#ifndef ATLAS_U16
#define ATLAS_U16
typedef unsigned short u16;
static_assert (sizeof(u16) == 2, "u16 should be defined as a 2 byte type");
#endif
#if _DEBUG
#define assert(cond, msg) Memory::Assert(cond, msg, __LINE__, __FILE__)
#else
#define assert(cond, msg) ;
#endif
#if _WASM32
namespace Memory {
Allocator* wasmGlobalAllocator = 0;
}
#define NotImplementedException() __builtin_trap()
#else
#define NotImplementedException() (*(char*)((void*)0) = '\0')
#endif
extern "C" void* __cdecl memset(void* _mem, i32 _value, Memory::ptr_type _size) {
return Memory::Set(_mem, (u8)_value, (u32)_size, "internal - memset");
}
namespace Memory {
namespace Debug {
u32 u32toa(u8* dest, u32 destSize, u32 num);
}
static void Assert(bool condition, const char* msg, u32 line, const char* file) {
#if _WASM32
if (condition == false) {
u32 wasmLen = 0;
for (const char* i = msg; msg != 0 && *i != '\0'; ++i, ++wasmLen);
//wasmConsoleLog(msg, wasmLen);
__builtin_trap();
}
#else
char* data = (char*)((void*)0);
if (condition == false) {
*data = '\0';
}
#endif
}
static inline u32 AllocatorPaddedSize() {
static_assert (sizeof(Memory::Allocator) % AllocatorAlignment == 0, "Memory::Allocator size needs to be 8 byte aligned for the allocation mask to start on this alignment without any padding");
return sizeof(Allocator);
}
static inline u8* AllocatorPageMask(Allocator* allocator) {
static_assert (sizeof(Memory::Allocator) % AllocatorAlignment == 0, "Memory::Allocator size needs to be 8 byte aligned for the allocation mask to start on this alignment without any padding");
return ((u8*)allocator) + sizeof(Allocator);
}
static inline u32 AllocatorPageMaskSize(Allocator* allocator) { // This is the number of u8's that make up the AllocatorPageMask array
const u32 allocatorNumberOfPages = allocator->size / allocator->pageSize; // 1 page = (probably) 4096 bytes, how many are needed
assert(allocator->size % allocator->pageSize == 0, "Allocator size should line up with page size");
// allocatorNumberOfPages is the number of bits that are required to track memory
// Pad out to sizeof(32) (if MaskTrackerSize is 32). This is because AllocatorPageMask will often be used as a u32 array
// and we want to make sure that enough space is reserved.
const u32 allocatorPageArraySize = allocatorNumberOfPages / TrackingUnitSize + (allocatorNumberOfPages % TrackingUnitSize ? 1 : 0);
return allocatorPageArraySize * (TrackingUnitSize / 8); // In bytes, not bits
}
static inline void RemoveFromList(Allocator* allocator, Allocation** list, Allocation* allocation) {
u32 allocationOffset = (u32)((u8*)allocation - (u8*)allocator);
u32 listOffset = (u32)((u8*)(*list) - (u8*)allocator);
Allocation* head = *list;
if (head == allocation) { // Removing head
if (head->nextOffset != 0) { // There is a next
Allocation* allocNext = 0;
if (allocation->nextOffset != 0) {
allocNext = (Allocation*)((u8*)allocator + allocation->nextOffset);
}
Allocation* headerNext = 0;
if (head->nextOffset != 0) {
headerNext = (Allocation*)((u8*)allocator + head->nextOffset);
}
assert(allocNext == headerNext, __LOCATION__);
assert(headerNext->prevOffset == allocationOffset, __LOCATION__);
headerNext->prevOffset = 0;
}
Allocation* next = 0;
if (head != 0 && head->nextOffset != 0) {
next = (Allocation*)((u8*)allocator + head->nextOffset);
}
*list = next;
}
else {
if (allocation->nextOffset != 0) {
Allocation* _next = (Allocation*)((u8*)allocator + allocation->nextOffset);
assert(_next->prevOffset == allocationOffset, __LOCATION__);
_next->prevOffset = allocation->prevOffset;
}
if (allocation->prevOffset != 0) {
Allocation* _prev = (Allocation*)((u8*)allocator + allocation->prevOffset);
assert(_prev->nextOffset == allocationOffset, __LOCATION__);
_prev->nextOffset = allocation->nextOffset;
}
}
allocation->prevOffset = 0;
allocation->nextOffset = 0;
}
static inline void AddtoList(Allocator* allocator, Allocation** list, Allocation* allocation) {
u32 allocationOffset = (u32)((u8*)allocation - (u8*)allocator);
u32 listOffset = (u32)((u8*)(*list) - (u8*)allocator);
Allocation* head = *list;
allocation->prevOffset = 0;
allocation->nextOffset = 0;
if (head != 0) {
allocation->nextOffset = listOffset;
head->prevOffset = allocationOffset;
}
*list = allocation;
}
// Returns 0 on error. Since the first page is always tracking overhead it's invalid for a range
static inline u32 FindRange(Allocator* allocator, u32 numPages, u32 searchStartBit) {
assert(allocator != 0, __LOCATION__);
assert(numPages != 0, __LOCATION__);
u32 * mask = (u32*)AllocatorPageMask(allocator);
u32 numBitsInMask = AllocatorPageMaskSize(allocator) * 8;
u32 numElementsInMask = AllocatorPageMaskSize(allocator) / (TrackingUnitSize / 8);
assert(allocator->size % allocator->pageSize == 0, "Memory::FindRange, the allocators size must be a multiple of Memory::PageSize, otherwise there would be a partial page at the end");
assert(mask != 0, __LOCATION__);
assert(numBitsInMask != 0, __LOCATION__);
u32 startBit = 0;
u32 numBits = 0;
for (u32 i = searchStartBit; i < numBitsInMask; ++i) {
u32 m = i / TrackingUnitSize;
u32 b = i % TrackingUnitSize;
assert(m < numElementsInMask, "indexing mask out of range");
bool set = mask[m] & (1 << b);
if (!set) {
if (startBit == 0) {
startBit = i;
numBits = 1;
}
else {
numBits++;
}
}
else {
startBit = 0;
numBits = 0;
}
if (numBits == numPages) {
break;
}
}
if (numBits != numPages || startBit == 0) {
startBit = 0;
numBits = 0;
for (u32 i = 0; i < searchStartBit; ++i) {
u32 m = i / TrackingUnitSize;
u32 b = i % TrackingUnitSize;
bool set = mask[m] & (1 << b);
if (!set) {
if (startBit == 0) {
startBit = i;
numBits = 1;
}
else {
numBits++;
}
}
else {
startBit = 0;
numBits = 0;
}
if (numBits == numPages) {
break;
}
}
}
allocator->scanBit = startBit + numPages;
assert(numBits == numPages, "Memory::FindRange Could not find enough memory to fufill request");
assert(startBit != 0, "Memory::FindRange Could not memory fufill request");
if (numBits != numPages || startBit == 0 || allocator->size % allocator->pageSize != 0) {
assert(false, __LOCATION__);
return 0;
}
return startBit;
}
static inline void SetRange(Allocator* allocator, u32 startBit, u32 bitCount) {
assert(allocator != 0, __LOCATION__);
assert(bitCount != 0, __LOCATION__);
u32* mask = (u32*)AllocatorPageMask(allocator);
assert(allocator->size % allocator->pageSize == 0, "Memory::FindRange, the allocators size must be a multiple of Memory::PageSize, otherwise there would be a partial page at the end");
assert(mask != 0, __LOCATION__);
#if _DEBUG
u32 numBitsInMask = AllocatorPageMaskSize(allocator) * 8;
assert(numBitsInMask != 0, __LOCATION__);
#endif
u32 numElementsInMask = AllocatorPageMaskSize(allocator) / (TrackingUnitSize / 8);
for (u32 i = startBit; i < startBit + bitCount; ++i) {
u32 m = i / TrackingUnitSize;
u32 b = i % TrackingUnitSize;
assert(m < numElementsInMask, "indexing mask out of range");
#if _DEBUG
assert(i < numBitsInMask, __LOCATION__);
bool set = mask[m] & (1 << b);
assert(!set, __LOCATION__);
#endif
mask[m] |= (1 << b);
}
assert(allocator->numPagesUsed <= numBitsInMask, "Memory::FindRange, over allocating");
assert(allocator->numPagesUsed + bitCount <= numBitsInMask, "Memory::FindRange, over allocating");
allocator->numPagesUsed += bitCount;
if (allocator->numPagesUsed > allocator->peekPagesUsed) {
allocator->peekPagesUsed = allocator->numPagesUsed;
}
}
static inline void ClearRange(Allocator* allocator, u32 startBit, u32 bitCount) {
assert(allocator != 0, __LOCATION__);
assert(bitCount != 0, __LOCATION__);
u32* mask = (u32*)AllocatorPageMask(allocator);
assert(allocator->size % allocator->pageSize == 0, "Memory::FindRange, the allocators size must be a multiple of Memory::PageSize, otherwise there would be a partial page at the end");
assert(mask != 0, __LOCATION__);
#if _DEBUG
u32 numBitsInMask = AllocatorPageMaskSize(allocator) * 8;
assert(numBitsInMask != 0, __LOCATION__);
#endif
u32 numElementsInMask = AllocatorPageMaskSize(allocator) / (TrackingUnitSize / 8);
for (u32 i = startBit; i < startBit + bitCount; ++i) {
u32 m = i / TrackingUnitSize;
u32 b = i % TrackingUnitSize;
assert(m < numElementsInMask, "indexing mask out of range");
#if _DEBUG
assert(i < numBitsInMask, __LOCATION__);
bool set = mask[m] & (1 << b);
assert(set, __LOCATION__);
#endif
mask[m] &= ~(1 << b);
}
assert(allocator->numPagesUsed != 0, __LOCATION__);
assert(allocator->numPagesUsed >= bitCount != 0, "underflow");
allocator->numPagesUsed -= bitCount;
}
#if MEM_USE_SUBALLOCATORS
// This function will chop the provided page into several blocks. Since the block size is constant, we
// know that headers will be laid out at a stride of blockSize. There is no additional tracking needed.
void* SubAllocate(u32 requestedBytes, u32 blockSize, Allocation** freeList, const char* location, Allocator* allocator) {
assert(blockSize < allocator->pageSize, "Block size must be less than page size");
// There is no blocks of the requested size available. Reserve 1 page, and carve it up into blocks.
bool grabNewPage = *freeList == 0;
if (*freeList == 0) {
// Find and reserve 1 free page
#if MEM_FIRST_FIT
const u32 page = FindRange(allocator, 1, 0);
#else
const u32 page = FindRange(allocator, 1, allocator->scanBit);
#endif
SetRange(allocator, page, 1);
// Zero out the pages memory
u8* mem = (u8*)allocator + allocator->pageSize * page;
Set(mem, 0, allocator->pageSize, __LOCATION__);
// Figure out how many blocks fit into this page
const u32 numBlocks = allocator->pageSize / blockSize;
assert(numBlocks > 0, __LOCATION__);
assert(numBlocks < 128, __LOCATION__);
// For each block in this page, initialize it's header and add it to the free list
for (u32 i = 0; i < numBlocks; ++i) {
Allocation* alloc = (Allocation*)mem;
mem += blockSize;
// Initialize the allocation header
alloc->prevOffset = 0;
alloc->nextOffset = 0;
alloc->size = 0;
alloc->alignment = 0;
#if MEM_TRACK_LOCATION
alloc->location = location;
#endif
AddtoList(allocator, freeList, alloc);
}
}
assert(*freeList != 0, "The free list literally can't be zero here...");
// At this point we know the free list has some number of blocks in it.
// Save a reference to the current header & advance the free list
// Advance the free list, we're going to be using this one.
Allocation* block = *freeList;
#if MEM_CLEAR_ON_ALLOC
Set((u8*)block + sizeof(Allocation), 0, blockSize - sizeof(Allocation), location);
#elif MEM_DEBUG_ON_ALLOC
{
const u8 stamp[] = "-MEMORY-";
u8* mem = (u8*)block + sizeof(Allocation);
u32 size = blockSize - sizeof(Allocation);
for (u32 i = requestedBytes; i < size; ++i) {
mem[i] = stamp[(i - requestedBytes) % 7];
}
}
#endif
if ((*freeList)->nextOffset != 0) { // Advance one
Allocation* _next = (Allocation*)((u8*)allocator + (*freeList)->nextOffset);
_next->prevOffset = 0;
*freeList = (Allocation*)((u8*)allocator + (*freeList)->nextOffset); // freeList = freeList.next
}
else {
*freeList = 0;
}
block->prevOffset = 0;
block->size = requestedBytes;
block->alignment = 0;
#if MEM_TRACK_LOCATION
block->location = location;
#endif
AddtoList(allocator, &allocator->active, block); // Sets block->next
if (allocator->allocateCallback != 0) {
u32 firstPage = ((u32)((u8*)block - (u8*)allocator)) / allocator->pageSize;
allocator->allocateCallback(allocator, block, requestedBytes, blockSize, firstPage, grabNewPage? 1 : 0);
}
// Memory always follows the header
return (u8*)block + sizeof(Allocation);
}
#endif
#if MEM_USE_SUBALLOCATORS
void SubRelease(void* memory, u32 blockSize, Allocation** freeList, const char* location, Allocator* allocator) {
// Find the allocation header and mark it as free. Early out on double free to avoid breaking.
Allocation* header = (Allocation*)((u8*)memory - sizeof(Allocation));
assert(header->size != 0, "Double Free!"); // Make sure it's not a double free
if (header->size == 0) {
assert(false, __LOCATION__);
return;
}
u32 oldSize = header->size;
header->size = 0;
// Now remove from the active list.
RemoveFromList(allocator, &allocator->active, header);
// Add memory back into the free list
AddtoList(allocator, freeList, header);
#if _DEBUG & MEM_TRACK_LOCATION
header->location = "SubRelease released this block";
#endif
// Find the first allocation inside the page
u32 startPage = (u32)((u8*)header - (u8*)allocator) / allocator->pageSize;
u8* mem =(u8*)allocator + startPage * allocator->pageSize;
// Each sub allocator page contains multiple blocks. check if all of the blocks
// belonging to a single page are free, if they are, release the page.
bool releasePage = true;
const u32 numAllocationsPerPage = allocator->pageSize / blockSize;
assert(numAllocationsPerPage >= 1, __LOCATION__);
for (u32 i = 0; i < numAllocationsPerPage; ++i) {
Allocation* alloc = (Allocation*)mem;
if (alloc->size > 0) {
releasePage = false;
break;
}
mem += blockSize;
}
// If appropriate, release entire page
if (releasePage) {
// Remove from free list
mem = (u8*)allocator + startPage * allocator->pageSize;
for (u32 i = 0; i < numAllocationsPerPage; ++i) {
Allocation* iter = (Allocation*)mem;
mem += blockSize;
assert(iter != 0, __LOCATION__);
RemoveFromList(allocator, freeList, iter);
}
// Clear the tracking bits
assert(startPage > 0, __LOCATION__);
ClearRange(allocator, startPage, 1);
}
if (allocator->releaseCallback != 0) {
allocator->releaseCallback(allocator, header, oldSize, blockSize, startPage, releasePage ? 1 : 0);
}
}
#endif
} // Namespace Memory
#if _WASM32
#define export __attribute__ (( visibility( "default" ) )) extern "C"
extern unsigned char __heap_base;
extern unsigned char __data_end;
// These are wasm shim functions
export int GameAllocator_wasmHeapSize(int memSize) {
void* heapPtr = &__heap_base;
Memory::ptr_type heapAddr = (Memory::ptr_type)heapPtr;
Memory::ptr_type maxAddr = (Memory::ptr_type)memSize;
Memory::ptr_type heapSize = maxAddr - heapAddr;
return (int)heapSize;
}
export Memory::Allocator* GameAllocator_wasmInitialize(int heapSize) {
void* memory = &__heap_base;
u32 size = (u32)heapSize; //GameAllocator_wasmHeapSize(totalMemorySize);
Memory::AlignAndTrim(&memory, &size);
Memory::Allocator* allocator = Memory::Initialize(memory, size);
Memory::wasmGlobalAllocator = allocator;
return allocator;
}
export void GameAllocator_wasmShutdown(Memory::Allocator* allocator) {
Memory::Shutdown(allocator);
}
export void* GameAllocator_wasmAllocate(Memory::Allocator* allocator, int bytes, int alignment) {
return Memory::wasmGlobalAllocator->Allocate(bytes, alignment, "GameAllocator_wasmAllocate");
}
export void GameAllocator_wasmRelease(Memory::Allocator* allocator, void* mem) {
Memory::wasmGlobalAllocator->Release(mem, "GameAllocator_wasmAllocate");
}
export void GameAllocator_wasmSet(void* mem, int val, int size) {
Memory::Set(mem, (u8)val, (u32)size, "GameAllocator_wasmAllocate");
}
export void GameAllocator_wasmCopy(void* dst, const void* src, int size) {
Memory::Copy(dst, src, (u32)size, "GameAllocator_wasmAllocate");
}
export int GameAllocator_wasmGetNumPages(Memory::Allocator* a) {
return a->size / a->pageSize;
}
export int GameAllocator_wasmGetNumPagesInUse(Memory::Allocator* a) {
return a->numPagesUsed;
}
export int GameAllocator_wasmGetPeekPagesUsed(Memory::Allocator* a) {
return a->peekPagesUsed;
}
export int GameAllocator_wasmGetRequestedBytes(Memory::Allocator* a) {
return a->requested;
}
export int GameAllocator_wasmGetServedBytes(Memory::Allocator* a) {
u32 maskSize = AllocatorPageMaskSize(a) / (sizeof(u32) / sizeof(u8)); // convert from u8 to u32
u32 metaDataSizeBytes = sizeof(Memory::Allocator) + (maskSize * sizeof(u32));
u32 numberOfMasksUsed = metaDataSizeBytes / a->pageSize;
if (metaDataSizeBytes % a->pageSize != 0) {
numberOfMasksUsed += 1;
}
metaDataSizeBytes = numberOfMasksUsed * a->pageSize; // This way, allocatable will start on a page boundary
// Account for meta data
metaDataSizeBytes += a->pageSize;
numberOfMasksUsed += 1;
u32 numPages = a->size / a->pageSize;
u32 usedPages = a->numPagesUsed;
u32 freePages = numPages - usedPages;
u32 overheadPages = metaDataSizeBytes / a->pageSize;
return (usedPages - overheadPages) * a->pageSize;
}
export int GameAllocator_wasmIsPageInUse(Memory::Allocator* a, int page) {
u32 m = page / Memory::TrackingUnitSize;
u32 b = page % Memory::TrackingUnitSize;
u32 * mask = (u32*)Memory::AllocatorPageMask(a);
bool set = mask[m] & (1 << b);
return set;
}
export int GameAllocator_wasmGetSize(Memory::Allocator* a) {
return a->size;
}
export int GameAllocator_wasmGetNumOverheadPages(Memory::Allocator* a) {
u32 maskSize = Memory::AllocatorPageMaskSize(a) / (sizeof(u32) / sizeof(u8)); // convert from u8 to u32
u32 metaDataSizeBytes = Memory::AllocatorPaddedSize() + (maskSize * sizeof(u32));
u32 numberOfMasksUsed = metaDataSizeBytes / a->pageSize;
if (metaDataSizeBytes % a->pageSize != 0) {
numberOfMasksUsed += 1;
}
metaDataSizeBytes = numberOfMasksUsed * a->pageSize; // This way, allocatable will start on a page boundary
// Account for meta data
metaDataSizeBytes += a->pageSize;
numberOfMasksUsed += 1;
u32 overheadPages = metaDataSizeBytes / a->pageSize;
return (int)overheadPages;
}
// Helper functions
export int GameAllocator_wasmStrLen(const char* str) {
if (str == 0) {
return 0;
}
const char *s = str;
while (*s) {
++s;
}
return (s - str);
}
extern "C" void GameAllocator_jsBuildMemState(const u8* msg, int len);
export void GameAllocator_wasmDumpState(Memory::Allocator* allocator) {
Memory::Debug::MemInfo(allocator, [](const u8* mem, u32 size, void* userdata) {
GameAllocator_jsBuildMemState(mem, (int)size);
}, 0);
}
export void* GameAllocator_wasmGetAllocationDebugName(Memory::Allocator* allocator, void* _m) {
const char* l = "mem_GetAllocationDebugName";
u8* debugPage = allocator->RequestDbgPage();
u32 debugSize = allocator->pageSize;
// Reset memory buffer
Memory::Set(debugPage, 0, debugSize, l);
u8* i_to_a_buff = debugPage; // Used to convert numbers to strings
const u32 i_to_a_buff_size = GameAllocator_wasmStrLen((const char*)"18446744073709551615") + 1; // u64 max
u8* mem = i_to_a_buff + i_to_a_buff_size;
u32 memSize = allocator->pageSize - i_to_a_buff_size;
u8* m = (u8*)_m - sizeof(Memory::Allocation);
Memory::Allocation* iter = (Memory::Allocation*)m;
Memory::Copy(mem, "Address: ", 9, l);
mem += 9; memSize -= 9;
u32 allocationOffset = (u32)((u8*)iter - (u8*)allocator);
i32 i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, allocationOffset);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
Memory::Copy(mem, ", size: ", 8, l);
mem += 8; memSize -= 8;
i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, iter->size);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
Memory::Copy(mem, ", padded: ", 10, l);
mem += 10; memSize -= 10;
u32 alignment = iter->alignment;
u32 allocationHeaderPadding = 0;
if (alignment != 0) { // Add padding to the header to compensate for alignment
allocationHeaderPadding = alignment - 1; // Somewhere in this range, we will be aligned
}
u32 realSize = iter->size + (u32)(sizeof(Memory::Allocation)) + allocationHeaderPadding;
i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, realSize);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
Memory::Copy(mem, ", alignment: ", 13, l);
mem += 13; memSize -= 13;
i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, iter->alignment);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
Memory::Copy(mem, ", first page: ", 14, l);
mem += 14; memSize -= 14;
i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, (allocationOffset) / allocator->pageSize);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
Memory::Copy(mem, ", prev: ", 8, l);
mem += 8; memSize -= 8;
i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, iter->prevOffset);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
Memory::Copy(mem, ", next: ", 8, l);
mem += 8; memSize -= 8;
i_len = Memory::Debug::u32toa(i_to_a_buff, i_to_a_buff_size, iter->nextOffset);
Memory::Copy(mem, i_to_a_buff, i_len, l);
mem += i_len;
memSize -= i_len;
u32 pathLen = 0;
#if MEM_TRACK_LOCATION
if (iter->location != 0) {
pathLen = GameAllocator_wasmStrLen((const char*)iter->location);
}
#endif
Memory::Copy(mem, ", location: ", 12, l);
mem += 12; memSize -= 12;
#if MEM_TRACK_LOCATION
if (iter->location == 0) {
#else
{
#endif
Memory::Copy(mem, "null", 4, l);
mem += 4; memSize -= 4;
}
#if MEM_TRACK_LOCATION
else {
Memory::Copy(mem, iter->location, pathLen, l);
mem += pathLen;
memSize -= pathLen;
}
#endif
*mem = '\0';
allocator->ReleaseDbgPage();
return debugPage + i_to_a_buff_size;
}
#endif
u32 Memory::AlignAndTrim(void** memory, u32* size, u32 alignment, u32 pageSize) {
#if ATLAS_64
u64 ptr = (u64)((const void*)(*memory));
#elif ATLAS_32
u32 ptr = (u32)((const void*)(*memory));
#else
#error Unknown Platform
#endif
u32 delta = 0;
if (alignment != 0) {
// Align to 8 byte boundary. This is so the mask array lines up on a u64
u32 alignmentDelta = alignment - (u32)(ptr % alignment);
assert(alignmentDelta <= (*size), __LOCATION__);
if (alignmentDelta > *size) { // In release mode, we want to fail on asserts
*memory = 0;
*size = 0;
return 0;
}
if (ptr % alignment != 0) {
u8* mem = (u8*)(*memory);
delta += alignmentDelta;
mem += alignmentDelta;
*size -= alignmentDelta;
*memory = mem;
}
}
// Trim to page size (4096) to make sure the provided memory can be chunked up perfectly
if ((*size) % pageSize != 0) {
u32 diff = (*size) % pageSize;
assert(*size >= diff, __LOCATION__);
if (*size < diff) { // In release mode, fail on assert
*memory = 0;
*size = 0;
return 0;
}
*size -= diff;
delta += diff;
}
return delta;
}
Memory::Allocator* Memory::Initialize(void* memory, u32 bytes, u32 pageSize) {
assert(pageSize % AllocatorAlignment == 0, "Memory::Initialize, Page boundaries are expected to be on 8 bytes");
// First, make sure that the memory being passed in is aligned well
#if ATLAS_64
u64 ptr = (u64)((const void*)memory);
#elif ATLAS_32
u32 ptr = (u32)((const void*)memory);
#else
#error Unknown platform
#endif
assert(ptr % AllocatorAlignment == 0, "Memory::Initialize, Memory being managed should be 8 byte aligned. Consider using Memory::AlignAndTrim");
assert(bytes % pageSize == 0, "Memory::Initialize, the size of the memory being managed must be aligned to Memory::PageSize");
assert(bytes / pageSize >= 10, "Memory::Initialize, minimum memory size is 10 pages, page size is Memory::PageSize");
// Set up the allocator
Allocator* allocator = (Allocator*)memory;
Set(memory, 0, sizeof(Allocator), "Memory::Initialize");
allocator->size = bytes;
allocator->pageSize = pageSize;
allocator->mask = 0;
// Set up the mask that will track our allocation data
u32* mask = (u32*)AllocatorPageMask(allocator);
u32 maskSize = AllocatorPageMaskSize(allocator) / (sizeof(u32) / sizeof(u8)); // convert from u8 to u32
Set(mask, 0, sizeof(u32) * maskSize, __LOCATION__);
// Find how many pages the meta data for the header + allocation mask will take up.
// Store the offset to first allocatable,
u32 metaDataSizeBytes = AllocatorPaddedSize() + (maskSize * sizeof(u32));
u32 numberOfMasksUsed = metaDataSizeBytes / pageSize;
if (metaDataSizeBytes % pageSize != 0) {
numberOfMasksUsed += 1;
}
metaDataSizeBytes = numberOfMasksUsed * pageSize; // This way, allocatable will start on a page boundary
// Add a debug page at the end
metaDataSizeBytes += pageSize;
numberOfMasksUsed += 1;
//allocator->offsetToAllocatable = metaDataSizeBytes;
allocator->scanBit = 0;
SetRange(allocator, 0, numberOfMasksUsed);
allocator->requested = 0;
if (ptr % AllocatorAlignment != 0 || bytes % pageSize != 0 || bytes / pageSize < 10) {
assert(false, __LOCATION__);
return 0;
}
return (Allocator*)memory;
}
void Memory::Shutdown(Allocator* allocator) {
assert(allocator != 0, "Memory::Shutdown called without it being initialized");
u32* mask = (u32*)AllocatorPageMask(allocator);
u32 maskSize = AllocatorPageMaskSize(allocator) / (sizeof(u32) / sizeof(u8)); // convert from u8 to u32
assert(allocator->size > 0, "Memory::Shutdown, trying to shut down an un-initialized allocator");
// Unset tracking bits
u32 metaDataSizeBytes = AllocatorPaddedSize() + (maskSize * sizeof(u32));
u32 numberOfMasksUsed = metaDataSizeBytes / allocator->pageSize;
if (metaDataSizeBytes % allocator->pageSize != 0) {
numberOfMasksUsed += 1;
}
metaDataSizeBytes = numberOfMasksUsed * allocator->pageSize;
// There is a debug between the memory bitmask and allocatable memory
metaDataSizeBytes += allocator->pageSize;
numberOfMasksUsed += 1;
ClearRange(allocator, 0, numberOfMasksUsed);
assert(allocator->requested == 0, "Memory::Shutdown, not all memory has been released");
assert(allocator->active == 0, "There are active allocations in Memory::Shutdown, leaking memory");
assert(allocator->free_64 == 0, "Free list is not empty in Memory::Shutdown, leaking memory");
assert(allocator->free_128 == 0, "Free list is not empty in Memory::Shutdown, leaking memory");
assert(allocator->free_256 == 0, "Free list is not empty in Memory::Shutdown, leaking memory");
assert(allocator->free_512 == 0, "Free list is not empty in Memory::Shutdown, leaking memory");
assert(allocator->free_1024 == 0, "Free list is not empty in Memory::Shutdown, leaking memory");
assert(allocator->free_2048 == 0, "Free list is not empty in Memory::Shutdown, leaking memory");
#if _DEBUG
// In debug mode only, we will scan the entire mask to make sure all memory has been free-d
for (u32 i = 0; i < maskSize; ++i) {
assert(mask[i] == 0, "Page tracking unit isn't empty in Memory::Shutdown, leaking memory.");
}
#endif
}
void Memory::Copy(void* dest, const void* source, u32 size, const char* location) {
#if ATLAS_64
u64 dst_ptr = (u64)((const void*)(dest));
u64 src_ptr = (u64)((const void*)(source));
u64 alignment = sizeof(u64);
#elif ATLAS_32
u32 dst_ptr = (u32)((const void*)(dest));
u32 src_ptr = (u32)((const void*)(source));
u32 alignment = sizeof(u32);
#else
#error Unknown Platform
#endif
if (dst_ptr % alignment != 0 || src_ptr % alignment != 0) {
// Memory is not aligned well, fall back on slow copy
u8* dst = (u8*)dest;
const u8* src = (const u8*)source;
for (u32 i = 0; i < size; ++i) {
dst[i] = src[i];
}
return;
}
#if ATLAS_64
u64 size_64 = size / sizeof(u64);
u64* dst_64 = (u64*)dest;
const u64* src_64 = (const u64*)source;
for (u32 i = 0; i < size_64; ++i) {
dst_64[i] = src_64[i];
}
#endif
#if ATLAS_64
u32 size_32 = (u32)((size - size_64 * sizeof(u64)) / sizeof(u32));
u32* dst_32 = (u32*)(dst_64 + size_64);
const u32* src_32 = (const u32*)(src_64 + size_64);
#else
u32 size_32 = size / sizeof(u32);
u32* dst_32 = (u32*)dest;
const u32* src_32 = (u32*)source;
#endif
for (u32 i = 0; i < size_32; ++i) {
dst_32[i] = src_32[i];
}
#if ATLAS_64
u32 size_16 = (u32)((size - size_64 * sizeof(u64) - size_32 * sizeof(u32)) / sizeof(u16));
#else
u32 size_16 = (size - size_32 * sizeof(u32)) / sizeof(u16);
#endif
u16* dst_16 = (u16*)(dst_32 + size_32);
const u16* src_16 = (const u16*)(src_32 + size_32);
for (u32 i = 0; i < size_16; ++i) {
dst_16[i] = src_16[i];
}
#if ATLAS_64
u32 size_8 = (u32)(size - size_64 * sizeof(u64) - size_32 * sizeof(u32) - size_16 * sizeof(u16));
#else
u32 size_8 = (size - size_32 * sizeof(u32) - size_16 * sizeof(u16));
#endif
u8* dst_8 = (u8*)(dst_16 + size_16);
const u8* src_8 = (const u8*)(src_16 + size_16);
for (u32 i = 0; i < size_8; ++i) {
dst_8[i] = src_8[i];
}
#if ATLAS_64
assert(size_64 * sizeof(u64) + size_32 * sizeof(u32) + size_16 * sizeof(u16) + size_8 == size, "Number of pages not adding up");
#elif ATLAS_32
assert(size_32 * sizeof(u32) + size_16 * sizeof(u16) + size_8 == size, "Number of pages not adding up");
#else
#error Unknown Platform
#endif
}
// MSVC generates a recursive memset with this implementation. The naive one works fine.
//#pragma optimize( "", off )
void* Memory::Set(void* memory, u8 value, u32 size, const char* location) {
if (memory == 0) {
return 0; // Can't set null!
}
#if ATLAS_64
u64 ptr = (u64)((const void*)(memory));
u64 alignment = sizeof(u64);
#elif ATLAS_32
u32 ptr = (u32)((const void*)(memory));
u32 alignment = sizeof(u32);
#else
#error Unknown Platform
#endif
if (size <= alignment) {
u8* mem = (u8*)memory;
/* MSCV was optimizing this loop into a recursive call?
for (u32 i = 0; i < size; ++i) {
mem[i] = value;
}*/
while ((alignment--) > 0) {
*mem = value;
}
return memory;
}
// Algin memory if needed
assert(alignment >= (ptr % alignment), __LOCATION__);
u32 alignDelta = (u32)(alignment - (ptr % alignment));
assert(alignDelta <= alignment, __LOCATION__);
assert(size >= alignDelta, __LOCATION__);
u8* mem = (u8*)(memory);
if (alignDelta != 0) {
if (alignDelta > size) {
alignDelta = size;
}
for (u32 iter = 0; iter < alignDelta; ++iter) {
mem[iter] = value;
}
mem += alignDelta;
size -= alignDelta;
}
#if ATLAS_64
u64 size_64 = size / sizeof(u64);
u64* ptr_64 = (u64*)mem;
u32 v32 = (((u32)value) << 8) | (((u32)value) << 16) | (((u32)value) << 24) | ((u32)value);
u64 val_64 = (((u64)v32) << 32) | ((u64)v32);
for (u32 i = 0; i < size_64; ++i) {
ptr_64[i] = val_64;
}
#endif
#if ATLAS_64
u32 size_32 = (u32)((size - size_64 * sizeof(u64)) / sizeof(u32));
u32* ptr_32 = (u32*)(ptr_64 + size_64);
#else
u32 size_32 = size / sizeof(u32);
u32* ptr_32 = (u32*)memory;
#endif
u32 val_32 = (((u32)value) << 8) | (((u32)value) << 16) | (((u32)value) << 24) | ((u32)value);
for (u32 i = 0; i < size_32; ++i) {
ptr_32[i] = val_32;
}
#if ATLAS_64
u32 size_16 = (u32)((size - size_64 * sizeof(u64) - size_32 * sizeof(u32)) / sizeof(u16));
#else
u32 size_16 = (size - size_32 * sizeof(u32)) / sizeof(u16);
#endif
u16* ptr_16 = (u16*)(ptr_32 + size_32);
u32 val_16 = (((u16)value) << 8) | ((u16)value);
for (u32 i = 0; i < size_16; ++i) {
ptr_16[i] = val_16;
}
#if ATLAS_64
u32 size_8 = (u32)((size - size_64 * sizeof(u64) - size_32 * sizeof(u32) - size_16 * sizeof(u16)) / sizeof(u8));
#else
u32 size_8 = (size - size_32 * sizeof(u32) - size_16 * sizeof(u16));
#endif
u8* ptr_8 = (u8*)(ptr_16 + size_16);
for (u32 i = 0; i < size_8; ++i) {
ptr_8[i] = value;
}
#if ATLAS_64
assert(size_64 * sizeof(u64) + size_32 * sizeof(u32) + size_16 * sizeof(u16) + size_8 == size, "Number of pages not adding up");
#elif ATLAS_32
assert(size_32 * sizeof(u32) + size_16 * sizeof(u16) + size_8 == size, "Number of pages not adding up");
#else
#error Unknown Platform
#endif
return memory;