forked from TheSuperHackers/GeneralsGameCode
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathGameMemory.cpp
More file actions
3591 lines (3157 loc) · 109 KB
/
Copy pathGameMemory.cpp
File metadata and controls
3591 lines (3157 loc) · 109 KB
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
/*
** Command & Conquer Generals(tm)
** Copyright 2025 Electronic Arts Inc.
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
////////////////////////////////////////////////////////////////////////////////
// //
// (c) 2001-2003 Electronic Arts Inc. //
// //
////////////////////////////////////////////////////////////////////////////////
// FILE: Memory.cpp
//-----------------------------------------------------------------------------
//
// Westwood Studios Pacific.
//
// Confidential Information
// Copyright (C) 2001 - All Rights Reserved
//
//-----------------------------------------------------------------------------
//
// Project: RTS3
//
// File name: Memory.cpp
//
// Created: Steven Johnson, August 2001
//
// Desc: Memory manager
//
// ----------------------------------------------------------------------------
#include "PreRTS.h" // This must go first in EVERY cpp file int the GameEngine
// SYSTEM INCLUDES
// USER INCLUDES
#include "Common/GameMemory.h"
#include "Common/CriticalSection.h"
#include "Common/Errors.h"
#include "Common/GlobalData.h"
#include "Common/PerfTimer.h"
#ifdef MEMORYPOOL_DEBUG
#include "GameClient/ClientRandomValue.h"
#endif
#ifdef MEMORYPOOL_STACKTRACE
#include "Common/StackDump.h"
#endif
#ifdef MEMORYPOOL_DEBUG
DECLARE_PERF_TIMER(MemoryPoolDebugging)
DECLARE_PERF_TIMER(MemoryPoolInitFilling)
#endif
// ----------------------------------------------------------------------------
// DEFINES
// ----------------------------------------------------------------------------
/**
define MPSB_DLINK to add a backlink to MemoryPoolSingleBlock; this makes it
faster to free raw DMA blocks.
@todo verify this speedup is enough to be worth the extra space
*/
#define MPSB_DLINK
#ifdef MEMORYPOOL_DEBUG
/**
if you define MEMORYPOOL_INTENSE_VERIFY, we do intensive verifications after
nearly every memory operation. this is OFF by default, since it slows down
things a lot, but is worth turning on for really obscure memory corruption issues.
*/
#ifndef MEMORYPOOL_INTENSE_VERIFY
#define NO_MEMORYPOOL_INTENSE_VERIFY
#endif
/**
if you define MEMORYPOOL_CHECK_BLOCK_OWNERSHIP, we do lots of calls to verify
that a block actually belongs to the pool it is called with. this is great
for debugging, but can be realllly slow, so is off by default.
*/
#ifndef MEMORYPOOL_CHECK_BLOCK_OWNERSHIP
#define NO_MEMORYPOOL_CHECK_BLOCK_OWNERSHIP
#endif
static const char* FREE_SINGLEBLOCK_TAG_STRING = "FREE_SINGLEBLOCK_TAG_STRING";
const Short SINGLEBLOCK_MAGIC_COOKIE = 12345;
const Int GARBAGE_FILL_VALUE = 0xdeadbeef;
// flags for m_debugFlags
enum
{
IGNORE_LEAKS = 0x0001
};
// in debug mode (but not internal), save stacktraces too
#if !defined(MEMORYPOOL_CHECKPOINTING) && defined(MEMORYPOOL_STACKTRACE) && defined(RTS_DEBUG)
#define MEMORYPOOL_SINGLEBLOCK_GETS_STACKTRACE
#endif
#define USE_FILLER_VALUE
const Int MAX_INIT_FILLER_COUNT = 8;
#ifdef USE_FILLER_VALUE
static UnsignedInt s_initFillerValue = 0xf00dcafe; // will be replaced, should never be this value at runtime
static void calcFillerValue(Int index)
{
s_initFillerValue = (index & 3) << 1;
s_initFillerValue |= 0x01;
s_initFillerValue |= (~(s_initFillerValue << 4)) & 0xf0;
s_initFillerValue |= (s_initFillerValue << 8);
s_initFillerValue |= (s_initFillerValue << 16);
//DEBUG_LOG(("Setting MemoryPool initFillerValue to %08x (index %d)",s_initFillerValue,index));
}
#endif
#endif
#ifdef MEMORYPOOL_BOUNDINGWALL
#define WALLCOUNT (2) // default setting of 8 requires 4*4*2==32 extra bytes PER BLOCK
#define WALLSIZE (WALLCOUNT * sizeof(Int))
#endif
#ifdef MEMORYPOOL_STACKTRACE
#define MEMORYPOOL_STACKTRACE_SIZE (20)
#define MEMORYPOOL_STACKTRACE_SKIP_SIZE (6)
#define MEMORYPOOL_STACKTRACE_SIZE_BYTES (MEMORYPOOL_STACKTRACE_SIZE * sizeof(void*))
#endif
// ----------------------------------------------------------------------------
// PRIVATE DATA
// ----------------------------------------------------------------------------
#ifdef MEMORYPOOL_BOUNDINGWALL
static Int theBoundingWallPattern = 0xbabeface;
#endif
#ifdef MEMORYPOOL_STACKTRACE
/** the max number levels to dump in the stacktrace. a variable rather than
constant so that you can fiddle with it in the debugger if desired, to
get shorter or longer dumps. (you can't go longer than MEMORYPOOL_STACKTRACE_SIZE
in any event. */
static Int theStackTraceDepth = 16;
#endif
#ifdef MEMORYPOOL_DEBUG
static Int theTotalSystemAllocationInBytes = 0;
static Int thePeakSystemAllocationInBytes = 0;
static Int theTotalLargeBlocks = 0;
static Int thePeakLargeBlocks = 0;
Int theTotalDMA = 0;
Int thePeakDMA = 0;
Int theWastedDMA = 0;
Int thePeakWastedDMA = 0;
#ifdef INTENSE_DMA_BOOKKEEPING
struct UsedNPeak
{
Int used, peak, waste, peakwaste;
UsedNPeak() : used(0), peak(0), waste(0), peakwaste(0) { }
};
typedef std::map< const char*, UsedNPeak, std::less<const char*> > UsedNPeakMap;
static UsedNPeakMap TheUsedNPeakMap;
static Int doingIntenseDMA = 0;
#endif
#endif
static Bool thePreMainInitFlag = false;
static Bool theMainInitFlag = false;
// ----------------------------------------------------------------------------
// PRIVATE PROTOTYPES
// ----------------------------------------------------------------------------
/// @todo srj -- make this work for 8
#define MEM_BOUND_ALIGNMENT 4
static Int roundUpMemBound(Int i);
static void *sysAllocate(Int numBytes);
static void *sysAllocateDoNotZero(Int numBytes);
static void sysFree(void* p);
static void memset32(void* ptr, Int value, Int bytesToFill);
#ifdef MEMORYPOOL_STACKTRACE
static void doStackDumpOutput(const char* m);
static void doStackDump(void **stacktrace, int size);
#endif
static void preMainInitMemoryManager();
// ----------------------------------------------------------------------------
// PRIVATE FUNCTIONS
// ----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/** round up to the nearest multiple of MEM_BOUND_ALIGNMENT */
static Int roundUpMemBound(Int i)
{
return (i + (MEM_BOUND_ALIGNMENT-1)) & ~(MEM_BOUND_ALIGNMENT-1);
}
//-----------------------------------------------------------------------------
/**
identical to sysAllocateDoNotZero, except that the memory block returned
is filled to all-zero-bytes.
*/
static void* sysAllocate(Int numBytes)
{
void* p = ::GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, numBytes);
if (!p)
throw ERROR_OUT_OF_MEMORY;
#ifdef MEMORYPOOL_DEBUG
{
USE_PERF_TIMER(MemoryPoolDebugging)
theTotalSystemAllocationInBytes += ::GlobalSize(p);
if (thePeakSystemAllocationInBytes < theTotalSystemAllocationInBytes)
thePeakSystemAllocationInBytes = theTotalSystemAllocationInBytes;
}
#endif
return p;
}
//-----------------------------------------------------------------------------
/**
this is the low-level allocator that we use to request memory from the OS.
all (repeat, all) memory allocations in this module should ultimately
go thru this routine (or sysAllocate).
note: throws ERROR_OUT_OF_MEMORY on failure; never returns null
*/
static void* sysAllocateDoNotZero(Int numBytes)
{
void* p = ::GlobalAlloc(GMEM_FIXED, numBytes);
if (!p)
throw ERROR_OUT_OF_MEMORY;
#ifdef MEMORYPOOL_DEBUG
{
USE_PERF_TIMER(MemoryPoolDebugging)
#ifdef USE_FILLER_VALUE
{
USE_PERF_TIMER(MemoryPoolInitFilling)
::memset32(p, s_initFillerValue, ::GlobalSize(p));
}
#endif
theTotalSystemAllocationInBytes += ::GlobalSize(p);
if (thePeakSystemAllocationInBytes < theTotalSystemAllocationInBytes)
thePeakSystemAllocationInBytes = theTotalSystemAllocationInBytes;
}
#endif
return p;
}
//-----------------------------------------------------------------------------
/**
the counterpart to sysAllocate / sysAllocateDoNotZero; used to free blocks
allocated by them. it is OK to pass null here (it will just be ignored).
*/
static void sysFree(void* p)
{
if (p)
{
#ifdef MEMORYPOOL_DEBUG
{
USE_PERF_TIMER(MemoryPoolDebugging)
::memset32(p, GARBAGE_FILL_VALUE, ::GlobalSize(p));
theTotalSystemAllocationInBytes -= ::GlobalSize(p);
}
#endif
::GlobalFree(p);
}
}
// ----------------------------------------------------------------------------
/**
fills memory with a 32-bit value (note: assumes the ptr is 4-byte-aligned)
*/
static void memset32(void* ptr, Int value, Int bytesToFill)
{
Int wordsToFill = bytesToFill>>2;
bytesToFill -= (wordsToFill<<2);
Int *p = (Int*)ptr;
for (++wordsToFill; --wordsToFill; )
*p++ = value;
Byte *b = (Byte *)p;
for (++bytesToFill; --bytesToFill; )
*b++ = (Byte)value;
}
#ifdef MEMORYPOOL_STACKTRACE
// ----------------------------------------------------------------------------
/**
This is just a convenience routine that dumps output from the StackDump module
to our normal debug log file, with a little massaging for formatting.
*/
static void doStackDumpOutput(const char* m)
{
const char *PREPEND = "STACKTRACE";
if (*m == 0)
{
DEBUG_LOG((m));
}
else
{
// Note - I am moving the prepend to the end, as this allows double clicking in the
// output window to open the file in VisualStudio. jba.
DEBUG_LOG(("%s, %s",m, PREPEND));
}
}
#endif
#ifdef MEMORYPOOL_STACKTRACE
// ----------------------------------------------------------------------------
/**
dump the given stacktrace to the debug log.
*/
static void doStackDump(void **stacktrace, int size)
{
::doStackDumpOutput("Allocation Stack Trace:");
::StackDumpFromAddresses(stacktrace, size, ::doStackDumpOutput);
}
#endif
// ----------------------------------------------------------------------------
// PRIVATE TYPES
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
#ifdef MEMORYPOOL_CHECKPOINTING
/**
This is a auxiliary record that we allocate in debug modes (actually, checkpoint modes)
to retain extra information about blocks; there is a one-to-one correspondence
between this record and a block allocation. The interesting bit about this record is that
we don't deallocate it when the corresponding block is freed; we retain it so we can
later provide information about what blocks were freed when, etc. Yes, this does chew
up a lot of memory! That's why it's debug-mode only; the presumption is that developers
machines have boatloads of RAM. (Note that we *do* free these when resetCheckpoints() is called.)
Note also that we directly allocate/free these with sysAllocate/sysFree, so ctors/dtors
are never executed, nor would virtual functions work -- I know, it's a little evil.
*/
class BlockCheckpointInfo
{
private:
BlockCheckpointInfo *m_next; ///< next checkpoint in this pool/dma
const char *m_debugLiteralTagString; ///< the tagstring for the block
Int m_allocCheckpoint; ///< when it was allocated
Int m_freeCheckpoint; ///< when it was freed (-1 if still in existence)
Int m_blockSize; ///< logical size of the block
#ifdef MEMORYPOOL_STACKTRACE
void* m_stacktrace[MEMORYPOOL_STACKTRACE_SIZE]; ///< stacktrace of when block was allocated
#endif
~BlockCheckpointInfo() {};
public:
BlockCheckpointInfo *getNext(); ///< return next checkpointinfo for this pool/dma
void debugSetFreepoint(Int f); ///< set the checkpoint at which the block was freed.
#ifdef MEMORYPOOL_STACKTRACE
void **getStacktraceInfo(); ///< return a ptr to the allocation stacktrace info.
#endif
static BlockCheckpointInfo *addToList(
BlockCheckpointInfo **pHead,
const char *debugLiteralTagString,
Int allocCheckpoint,
Int blockSize
);
static void freeList(BlockCheckpointInfo **pHead);
Bool shouldBeInReport(Int flags, Int startCheckpoint, Int endCheckpoint);
static void doBlockCheckpointReport( BlockCheckpointInfo *bi, const char *poolName,
Int flags, Int startCheckpoint, Int endCheckpoint );
};
#endif
// ----------------------------------------------------------------------------
/**
This is the fundamental allocation unit; when you allocate via (say) MemoryPool::allocateBlock,
this is what is being allocated for you. (Of course, you don't see the private fields.)
For the most part, we allocate big chunks of these in a monolithic Blob and subdivide
from there. (However, we occasionally allocate these individually, for large blocks.)
Note also that we directly allocate/free these with sysAllocate/sysFree, so ctors/dtors
are never executed, nor would virtual functions work -- I know, it's a little evil.
*/
class MemoryPoolSingleBlock
{
private:
MemoryPoolBlob *m_owningBlob; ///< will be NULL if the single block was allocated via sysAllocate()
MemoryPoolSingleBlock *m_nextBlock; ///< if m_owningBlob is nonnull, this points to next free (unallocated) block in the blob; if m_owningBlob is null, this points to the next used (allocated) raw block in the pool.
#ifdef MPSB_DLINK
MemoryPoolSingleBlock *m_prevBlock; ///< if m_owningBlob is nonnull, this points to prev free (unallocated) block in the blob; if m_owningBlob is null, this points to the prev used (allocated) raw block in the pool.
#endif
#ifdef MEMORYPOOL_CHECKPOINTING
BlockCheckpointInfo *m_checkpointInfo; ///< ptr to the checkpointinfo for this block
#endif
#ifdef MEMORYPOOL_BOUNDINGWALL
Int m_wallPattern; ///< unique seed value for the bounding-walls for this block
#endif
#ifdef MEMORYPOOL_DEBUG
const char *m_debugLiteralTagString; ///< ptr to the tagstring for this block.
Int m_logicalSize; ///< logical size of block (not including overhead, walls, etc.)
Int m_wastedSize; ///< if allocated via DMA, the "wasted" bytes
Short m_magicCookie; ///< magic value used to verify that the block is one of ours (as opposed to random pointer)
Short m_debugFlags; ///< misc flags
#ifdef MEMORYPOOL_SINGLEBLOCK_GETS_STACKTRACE
void* m_stacktrace[MEMORYPOOL_STACKTRACE_SIZE]; ///< stacktrace of when block was allocated (if not checkpointing)
#endif
#endif
private:
void* getUserDataNoDbg();
#ifdef MEMORYPOOL_BOUNDINGWALL
void debugFillInWalls();
#endif
public:
static Int calcRawBlockSize(Int logicalSize);
static MemoryPoolSingleBlock *rawAllocateSingleBlock(MemoryPoolSingleBlock **pRawListHead, Int logicalSize, MemoryPoolFactory *owningFactory DECLARE_LITERALSTRING_ARG2);
void removeBlockFromList(MemoryPoolSingleBlock **pHead);
void initBlock(Int logicalSize, MemoryPoolBlob *owningBlob, MemoryPoolFactory *owningFactory DECLARE_LITERALSTRING_ARG2);
void* getUserData();
static MemoryPoolSingleBlock *recoverBlockFromUserData(void* pUserData);
MemoryPoolBlob *getOwningBlob();
MemoryPoolSingleBlock *getNextFreeBlock();
void setNextFreeBlock(MemoryPoolSingleBlock *b);
MemoryPoolSingleBlock *getNextRawBlock();
void setNextRawBlock(MemoryPoolSingleBlock *b);
#ifdef MEMORYPOOL_DEBUG
void debugIgnoreLeaksForThisBlock();
const char *debugGetLiteralTagString();
Int debugGetLogicalSize();
Int debugGetWastedSize();
void debugSetWastedSize(Int waste);
void debugVerifyBlock();
void debugMarkBlockAsFree();
Bool debugCheckUnderrun();
Bool debugCheckOverrun();
Int debugSingleBlockReportLeak(const char* owner);
#endif // MEMORYPOOL_DEBUG
#ifdef MEMORYPOOL_CHECKPOINTING
BlockCheckpointInfo *debugGetCheckpointInfo();
void debugSetCheckpointInfo(BlockCheckpointInfo *bi);
void debugResetCheckpoint();
#endif
};
// ----------------------------------------------------------------------------
class MemoryPoolBlob
{
private:
MemoryPool *m_owningPool; ///< the pool that owns this blob
MemoryPoolBlob *m_nextBlob; ///< next blob in this pool
MemoryPoolBlob *m_prevBlob; ///< prev blob in this pool
MemoryPoolSingleBlock *m_firstFreeBlock; ///< ptr to first available block in this blob
Int m_usedBlocksInBlob; ///< total allocated blocks in this blob
Int m_totalBlocksInBlob; ///< total blocks in this blob (allocated + available)
char *m_blockData; ///< ptr to the blocks (really a MemoryPoolSingleBlock*)
public:
MemoryPoolBlob();
~MemoryPoolBlob();
void initBlob(MemoryPool *owningPool, Int allocationCount);
void addBlobToList(MemoryPoolBlob **ppHead, MemoryPoolBlob **ppTail);
void removeBlobFromList(MemoryPoolBlob **ppHead, MemoryPoolBlob **ppTail);
MemoryPoolBlob *getNextInList();
Bool hasAnyFreeBlocks();
MemoryPoolSingleBlock *allocateSingleBlock(DECLARE_LITERALSTRING_ARG1);
void freeSingleBlock(MemoryPoolSingleBlock *block);
MemoryPool *getOwningPool();
Int getFreeBlockCount();
Int getUsedBlockCount();
Int getTotalBlockCount();
#ifdef MEMORYPOOL_DEBUG
void debugMemoryVerifyBlob();
Int debugBlobReportLeaks(const char* owner);
Bool debugIsBlockInBlob(void *pBlock);
#endif
#ifdef MEMORYPOOL_CHECKPOINTING
void debugResetCheckpoints();
#endif
};
// ----------------------------------------------------------------------------
// PUBLIC DATA
// ----------------------------------------------------------------------------
MemoryPoolFactory *TheMemoryPoolFactory = NULL;
DynamicMemoryAllocator *TheDynamicMemoryAllocator = NULL;
// ----------------------------------------------------------------------------
// INLINES
// ----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifdef MEMORYPOOL_CHECKPOINTING
inline BlockCheckpointInfo *BlockCheckpointInfo::getNext() { return m_next; }
inline void BlockCheckpointInfo::debugSetFreepoint(Int f) { DEBUG_ASSERTCRASH(m_freeCheckpoint == -1, ("already have a freepoint")); m_freeCheckpoint = f; }
#ifdef MEMORYPOOL_STACKTRACE
inline void **BlockCheckpointInfo::getStacktraceInfo() { return m_stacktrace; }
#endif
#endif
// ----------------------------------------------------------------------------
/**
return a ptr to the user-data area of the block (ie, the part the enduser can deal with).
this call does NO debug verification and is for internal use of class MemoryPoolSingleBlock only.
*/
inline void* MemoryPoolSingleBlock::getUserDataNoDbg()
{
char* p = ((char*)this) + sizeof(MemoryPoolSingleBlock);
#ifdef MEMORYPOOL_BOUNDINGWALL
p += WALLSIZE;
#endif
return (void*)p;
}
/**
return a ptr to the user-data area of the block (ie, the part the enduser can deal with).
this call verifies that the block is valid in debug mode.
*/
inline void* MemoryPoolSingleBlock::getUserData()
{
// yes, verify the block in this case for plain debug mode (not intense-verify mode)
#ifdef MEMORYPOOL_DEBUG
debugVerifyBlock();
#endif
return getUserDataNoDbg();
}
/**
given a desired logical block size, calculate the physical size needed for each
MemoryPoolSingleBlock (including overhead, etc.)
*/
inline /*static*/ Int MemoryPoolSingleBlock::calcRawBlockSize(Int logicalSize)
{
Int s = ::roundUpMemBound(logicalSize) + sizeof(MemoryPoolSingleBlock);
#ifdef MEMORYPOOL_BOUNDINGWALL
s += WALLSIZE*2;
#endif
return s;
}
/**
accessor
*/
inline MemoryPoolBlob *MemoryPoolSingleBlock::getOwningBlob()
{
return m_owningBlob;
}
/**
return the next free block in this blob. this call assumes that the block
in question belongs to a blob, and will assert if not.
*/
inline MemoryPoolSingleBlock *MemoryPoolSingleBlock::getNextFreeBlock()
{
DEBUG_ASSERTCRASH(m_owningBlob != NULL, ("must be called on blob block"));
return m_nextBlock;
}
/**
set the next free block in this blob. this call assumes that both blocks
in question belongs to a blob, but will NOT assert if not, since it may be
called when the blocks are in an inconsistent state.
*/
inline void MemoryPoolSingleBlock::setNextFreeBlock(MemoryPoolSingleBlock *b)
{
//DEBUG_ASSERTCRASH(m_owningBlob != NULL && b->m_owningBlob != NULL, ("must be called on blob block"));
// don't check the 'b' block -- we need to call this before 'b' is fully initialized.
DEBUG_ASSERTCRASH(m_owningBlob != NULL, ("must be called on blob block"));
this->m_nextBlock = b;
#ifdef MPSB_DLINK
if (b) {
b->m_prevBlock = this;
}
#endif
}
/**
return the next raw block in this dma. this call assumes that the block
in question does NOT belong to a blob, and will assert if not.
*/
inline MemoryPoolSingleBlock *MemoryPoolSingleBlock::getNextRawBlock()
{
DEBUG_ASSERTCRASH(m_owningBlob == NULL, ("must be called on raw block"));
return m_nextBlock;
}
/**
set the next raw block in this dma. this call assumes that the blocks
in question do NOT belong to a blob, and will assert if not.
*/
inline void MemoryPoolSingleBlock::setNextRawBlock(MemoryPoolSingleBlock *b)
{
DEBUG_ASSERTCRASH(m_owningBlob == NULL && (!b || b->m_owningBlob == NULL), ("must be called on raw block"));
m_nextBlock = b;
#ifdef MPSB_DLINK
if (b)
b->m_prevBlock = this;
#endif
}
#ifdef MEMORYPOOL_DEBUG
inline void MemoryPoolSingleBlock::debugIgnoreLeaksForThisBlock()
{
//USE_PERF_TIMER(MemoryPoolDebugging) not worth it
m_debugFlags |= IGNORE_LEAKS;
}
/**
accessor
*/
inline const char *MemoryPoolSingleBlock::debugGetLiteralTagString()
{
//USE_PERF_TIMER(MemoryPoolDebugging) not worth it
return m_debugLiteralTagString;
}
#endif
#ifdef MEMORYPOOL_DEBUG
/**
accessor
*/
inline Int MemoryPoolSingleBlock::debugGetLogicalSize()
{
//USE_PERF_TIMER(MemoryPoolDebugging) not worth it
return m_logicalSize;
}
#endif
#ifdef MEMORYPOOL_DEBUG
/**
accessor
*/
inline Int MemoryPoolSingleBlock::debugGetWastedSize()
{
//USE_PERF_TIMER(MemoryPoolDebugging) not worth it
return m_wastedSize;
}
#endif
#ifdef MEMORYPOOL_DEBUG
inline void MemoryPoolSingleBlock::debugSetWastedSize(Int w)
{
//USE_PERF_TIMER(MemoryPoolDebugging) not worth it
m_wastedSize = w;
}
#endif
#ifdef MEMORYPOOL_CHECKPOINTING
/**
accessor
*/
inline BlockCheckpointInfo *MemoryPoolSingleBlock::debugGetCheckpointInfo()
{
return m_checkpointInfo;
}
#endif
#ifdef MEMORYPOOL_CHECKPOINTING
/**
set the checkpoint info for this block.
*/
inline void MemoryPoolSingleBlock::debugSetCheckpointInfo(BlockCheckpointInfo *bi)
{
DEBUG_ASSERTCRASH(m_checkpointInfo == NULL, ("should be null"));
m_checkpointInfo = bi;
}
#endif
#ifdef MEMORYPOOL_CHECKPOINTING
/**
sets the checkpointinfo to null, but does NOT free it... the checkpointinfo
is expected to be freed elsewhere.
*/
inline void MemoryPoolSingleBlock::debugResetCheckpoint()
{
m_checkpointInfo = NULL;
}
#endif
// ----------------------------------------------------------------------------
/// accessor
inline MemoryPoolBlob *MemoryPoolBlob::getNextInList() { return m_nextBlob; }
/// accessor
inline Bool MemoryPoolBlob::hasAnyFreeBlocks() { return m_firstFreeBlock != NULL; }
/// accessor
inline MemoryPool *MemoryPoolBlob::getOwningPool() { return m_owningPool; }
/// accessor
inline Int MemoryPoolBlob::getFreeBlockCount() { return getTotalBlockCount() - getUsedBlockCount(); }
/// accessor
inline Int MemoryPoolBlob::getUsedBlockCount() { return m_usedBlocksInBlob; }
/// accessor
inline Int MemoryPoolBlob::getTotalBlockCount() { return m_totalBlocksInBlob; }
//-----------------------------------------------------------------------------
// METHODS for BlockCheckpointInfo
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
#ifdef MEMORYPOOL_CHECKPOINTING
/// return true iff this checkpointinfo should be included in a checkpointreport with the given parameters.
Bool BlockCheckpointInfo::shouldBeInReport(Int flags, Int startCheckpoint, Int endCheckpoint)
{
Bool allocFlagsOK = false;
Bool freedFlagsOK = false;
if (m_allocCheckpoint < startCheckpoint && (flags & _REPORT_CP_ALLOCATED_BEFORE))
allocFlagsOK = true;
if (m_allocCheckpoint >= startCheckpoint && m_allocCheckpoint < endCheckpoint && (flags & _REPORT_CP_ALLOCATED_BETWEEN))
allocFlagsOK = true;
if (m_freeCheckpoint == -1)
{
// block still exists! process this only if we want 'em.
freedFlagsOK = (flags & _REPORT_CP_FREED_NEVER) ? true : false;
}
else
{
if (m_freeCheckpoint < startCheckpoint && (flags & _REPORT_CP_FREED_BEFORE))
freedFlagsOK = true;
if (m_freeCheckpoint >= startCheckpoint && m_freeCheckpoint < endCheckpoint && (flags & _REPORT_CP_FREED_BETWEEN))
freedFlagsOK = true;
}
// the block must match both the 'alloc' and 'free' criteria to get a report
return allocFlagsOK && freedFlagsOK;
}
#endif
//-----------------------------------------------------------------------------
#ifdef MEMORYPOOL_CHECKPOINTING
/// print a checkpointreport for the given checkpointinfo. if checkpointinfo is null, print column headers.
/*static*/ void BlockCheckpointInfo::doBlockCheckpointReport(BlockCheckpointInfo *bi,
const char *poolName, Int flags, Int startCheckpoint, Int endCheckpoint )
{
const char *PREPEND = "BLOCKINFO"; // allows grepping more easily
if (!bi)
{
DEBUG_LOG(("%s,%32s,%6s,%6s,%6s,%s",PREPEND,"POOLNAME","BLKSZ","ALLOC","FREED","BLOCKNAME"));
}
else
{
DEBUG_ASSERTCRASH(startCheckpoint >= 0 && startCheckpoint <= endCheckpoint, ("bad checkpoints"));
DEBUG_ASSERTCRASH((flags & _REPORT_CP_ALLOCATED_DONTCARE) != 0, ("bad flags: must set at least one alloc flag"));
DEBUG_ASSERTCRASH((flags & _REPORT_CP_FREED_DONTCARE) != 0, ("bad flags: must set at least one freed flag"));
if (bi->shouldBeInReport(flags, startCheckpoint, endCheckpoint))
{
DEBUG_LOG(("%s,%32s,%6d,%6d,%6d,%s",PREPEND,poolName,bi->m_blockSize,bi->m_allocCheckpoint,bi->m_freeCheckpoint,bi->m_debugLiteralTagString));
#ifdef MEMORYPOOL_STACKTRACE
if (flags & REPORT_CP_STACKTRACE)
{
::doStackDump(bi->m_stacktrace, min(MEMORYPOOL_STACKTRACE_SIZE, theStackTraceDepth ));
}
#endif
}
}
}
#endif
// ----------------------------------------------------------------------------
#ifdef MEMORYPOOL_CHECKPOINTING
/// free an entire list of checkpointinfos.
/*static*/ void BlockCheckpointInfo::freeList(BlockCheckpointInfo **pHead)
{
BlockCheckpointInfo *p = *pHead;
while (p)
{
BlockCheckpointInfo *n = p->m_next;
::sysFree((void *)p);
p = n;
}
*pHead = NULL;
}
#endif
// ----------------------------------------------------------------------------
#ifdef MEMORYPOOL_CHECKPOINTING
/**
allocate a new checkpointinfo with the given tag/checkpoint/size, add it to the
linked list, and return the checkpointinfo. (note that this will NOT throw an exception;
if there is not enough memory to allocate a new checkpointinfo, it will quietly return null.)
*/
/*static*/ BlockCheckpointInfo *BlockCheckpointInfo::addToList(
BlockCheckpointInfo **pHead,
const char *debugLiteralTagString,
Int allocCheckpoint,
Int blockSize
)
{
DEBUG_ASSERTCRASH(debugLiteralTagString != FREE_SINGLEBLOCK_TAG_STRING, ("bad tag string"));
BlockCheckpointInfo *freed = NULL;
try {
freed = (BlockCheckpointInfo *)::sysAllocate(sizeof(BlockCheckpointInfo));
} catch (...) {
freed = NULL;
}
if (freed)
{
DEBUG_ASSERTCRASH(debugLiteralTagString != NULL, ("null tagstrings are not allowed"));
freed->m_debugLiteralTagString = debugLiteralTagString;
freed->m_allocCheckpoint = allocCheckpoint;
freed->m_freeCheckpoint = -1;
freed->m_blockSize = blockSize;
freed->m_next = *pHead;
*pHead = freed;
}
return freed;
}
#endif
//-----------------------------------------------------------------------------
// METHODS for MemoryPoolSingleBlock
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
/**
fill in a block's fields. this is usually done only just after a block is allocated,
but might also be done at other points in debug mode.
*/
void MemoryPoolSingleBlock::initBlock(Int logicalSize, MemoryPoolBlob *owningBlob,
MemoryPoolFactory *owningFactory DECLARE_LITERALSTRING_ARG2)
{
// Note that while it is OK for owningBlob to be null, it is NEVER ok
// for owningFactory to be null.
DEBUG_ASSERTCRASH(owningFactory, ("null factory"));
#ifdef MEMORYPOOL_DEBUG
{
USE_PERF_TIMER(MemoryPoolDebugging)
m_magicCookie = SINGLEBLOCK_MAGIC_COOKIE;
m_debugFlags = 0;
if (!theMainInitFlag)
debugIgnoreLeaksForThisBlock();
DEBUG_ASSERTCRASH(debugLiteralTagString != NULL, ("null tagstrings are not allowed"));
m_debugLiteralTagString = debugLiteralTagString;
m_logicalSize = logicalSize;
m_wastedSize = 0;
#ifdef MEMORYPOOL_SINGLEBLOCK_GETS_STACKTRACE
if (theStackTraceDepth > 0 && (!TheGlobalData || TheGlobalData->m_checkForLeaks))
{
memset(m_stacktrace, 0, MEMORYPOOL_STACKTRACE_SIZE_BYTES);
::FillStackAddresses(m_stacktrace, min(MEMORYPOOL_STACKTRACE_SIZE, theStackTraceDepth), MEMORYPOOL_STACKTRACE_SKIP_SIZE);
}
else
{
m_stacktrace[0] = NULL;
}
#endif
}
#endif // MEMORYPOOL_DEBUG
#ifdef MEMORYPOOL_CHECKPOINTING
m_checkpointInfo = NULL;
#endif
m_nextBlock = NULL;
#ifdef MPSB_DLINK
m_prevBlock = NULL;
#endif
m_owningBlob = owningBlob; // could be NULL
#ifdef MEMORYPOOL_BOUNDINGWALL
m_wallPattern = theBoundingWallPattern++;
debugFillInWalls();
#endif
}
//-----------------------------------------------------------------------------
/**
given a 'public' ptr to a block (ie, the ptr returned by the MemoryPool::allocateBlock),
recover the ptr to the MemoryPoolSingleBlock, so we can access the hidden fields.
*/
/* static */ MemoryPoolSingleBlock *MemoryPoolSingleBlock::recoverBlockFromUserData(void* pUserData)
{
DEBUG_ASSERTCRASH(pUserData, ("null pUserData"));
if (!pUserData)
return NULL;
char* p = ((char*)pUserData) - sizeof(MemoryPoolSingleBlock);
#ifdef MEMORYPOOL_BOUNDINGWALL
p -= WALLSIZE;
#endif
MemoryPoolSingleBlock *block = (MemoryPoolSingleBlock *)p;
// yes, verify the block in this case for plain debug mode (not intense-verify mode)
#ifdef MEMORYPOOL_DEBUG
block->debugVerifyBlock();
#endif
return block;
}
//-----------------------------------------------------------------------------
/**
allocate and initialize a single block. this should only used by DynamicMemoryAllocator
when allocating an extraordinarily large block.
*/
/*static*/ MemoryPoolSingleBlock *MemoryPoolSingleBlock::rawAllocateSingleBlock(
MemoryPoolSingleBlock **pRawListHead,
Int logicalSize,
MemoryPoolFactory *owningFactory
DECLARE_LITERALSTRING_ARG2)
{
MemoryPoolSingleBlock *block = (MemoryPoolSingleBlock *)::sysAllocateDoNotZero(calcRawBlockSize(logicalSize));
block->initBlock(logicalSize, NULL, owningFactory PASS_LITERALSTRING_ARG2);
block->setNextRawBlock(*pRawListHead);
*pRawListHead = block;
return block;
}
//-----------------------------------------------------------------------------
/**
remove the block from the list, which is presumed to be a list of raw blocks.
generally, only the DynamicMemoryAllocator should call this.
*/
void MemoryPoolSingleBlock::removeBlockFromList(MemoryPoolSingleBlock **pHead)
{
DEBUG_ASSERTCRASH(this->m_owningBlob == NULL, ("this function should only be used on raw blocks"));
#ifdef MPSB_DLINK
DEBUG_ASSERTCRASH(this->m_nextBlock == NULL || this->m_nextBlock->m_owningBlob == NULL, ("this function should only be used on raw blocks"));
if (this->m_prevBlock)
{
DEBUG_ASSERTCRASH(this->m_prevBlock->m_owningBlob == NULL, ("this function should only be used on raw blocks"));
DEBUG_ASSERTCRASH(*pHead != this, ("bad linkage"));
this->m_prevBlock->m_nextBlock = this->m_nextBlock;
}
else
{
DEBUG_ASSERTCRASH(*pHead == this, ("bad linkage"));
*pHead = this->m_nextBlock;
}
if (this->m_nextBlock)
{
DEBUG_ASSERTCRASH(this->m_nextBlock->m_owningBlob == NULL, ("this function should only be used on raw blocks"));
this->m_nextBlock->m_prevBlock = this->m_prevBlock;
}
#else
// this isn't very efficient, and may need upgrading... but to do so
// would require adding a back link, so I'd rather do some testing
// first to see if it's really a speed issue in practice. (the only place
// this is used is when freeing 'raw' blocks allocated via the DMA).
MemoryPoolSingleBlock *prev = NULL;
for (MemoryPoolSingleBlock *cur = *pHead; cur; cur = cur->m_nextBlock)
{
DEBUG_ASSERTCRASH(cur->m_owningBlob == NULL, ("this function should only be used on raw blocks"));
if (cur == this)
{
if (prev)
{
prev->m_nextBlock = this->m_nextBlock;
}
else
{
*pHead = this->m_nextBlock;
}