forked from gildor2/UEViewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemory.cpp
More file actions
499 lines (411 loc) · 10.7 KB
/
Copy pathMemory.cpp
File metadata and controls
499 lines (411 loc) · 10.7 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
#include "Core.h"
#include "Parallel.h"
#if DEBUG_MEMORY
#define MAX_STACK_TRACE 16
#define MAX_ALLOCATION_POINTS 8192
#endif // DEBUG_MEMORY
//#define TRACY_DEBUG_MALLOC 1
#if PROFILE
int GNumAllocs = 0;
#endif
size_t GTotalAllocationSize = 0;
int GTotalAllocationCount = 0;
#define BLOCK_MAGIC 0xAE
#define UNINIT_BLOCK 0xCC
#define FREE_BLOCK 0xFE
#define MAX_ALLOCATION_SIZE (513<<20) // upper limit for single allocation is 513+1 Mb
#if DEBUG_MEMORY
#if THREADING
static CMutex GMallocMutex;
#endif
struct CStackTrace
{
int hash;
address_t stack[MAX_STACK_TRACE];
CStackTrace()
{
memset(this, 0, sizeof(*this));
}
void UpdateHash()
{
int h = 0;
for (int i = 0; i < MAX_STACK_TRACE; i++)
{
h += stack[i];
h ^= 0x56789ABC;
}
hash = h;
}
bool operator==(const CStackTrace& other) const
{
if (hash != other.hash) return false;
if (memcmp(stack, other.stack, sizeof(stack)) != 0) return false;
return true;
}
void Dump() const
{
appDumpStackTrace(stack, MAX_STACK_TRACE);
}
};
static CStackTrace GAllocationPoints[MAX_ALLOCATION_POINTS];
static int GNumAllocationPoints = 0;
#endif // DEBUG_MEMORY
struct CBlockHeader
{
byte magic;
byte offset;
byte align;
int blockSize;
#if DEBUG_MEMORY
CBlockHeader* prev;
CBlockHeader* next;
CStackTrace* stack;
static CBlockHeader* first;
inline void Link()
{
if (first) first->prev = this;
next = first;
prev = NULL;
first = this;
}
inline void Unlink()
{
if (first == this) first = next;
if (prev) prev->next = next;
if (next) next->prev = prev;
}
#endif // DEBUG_MEMORY
};
#if DEBUG_MEMORY
CBlockHeader* CBlockHeader::first = NULL;
#endif
/*-----------------------------------------------------------------------------
Primary allocation functions
-----------------------------------------------------------------------------*/
#if DEBUG_MEMORY
#define RESERVE_MEMORY_SIZE (16<<20)
static void* ReservedMemory = NULL;
#endif
inline void OutOfMemory(int size)
{
#if DEBUG_MEMORY
static bool recurse = false;
if (recurse) return;
recurse = true;
// Release reserved memory
if (ReservedMemory)
free(ReservedMemory);
// Log allocations
appOpenLogFile("memory.log");
appDumpMemoryAllocations();
#endif
// Crash ...
appErrorNoLog("Out of memory: failed to allocate %d bytes", size);
}
void* appMalloc(int size, int alignment, bool noInit)
{
guard(appMalloc);
PROFILE_LABEL(noInit ? "NoInit" : "Zero");
#if DEBUG_MEMORY
// Reserve some amount of memory for possibility to log memory when crashed
if (!ReservedMemory) ReservedMemory = malloc(RESERVE_MEMORY_SIZE);
#endif
if (size < 0 || size >= MAX_ALLOCATION_SIZE)
appError("Memory: bad allocation size %d bytes", size);
assert(alignment > 1 && alignment <= 256 && ((alignment & (alignment - 1)) == 0));
// Allocate memory
void* block = malloc(size + sizeof(CBlockHeader) + (alignment - 1));
if (!block)
OutOfMemory(size);
// Initialize the allocated block
void* ptr = Align(OffsetPointer(block, sizeof(CBlockHeader)), alignment);
if (size > 0 && !noInit)
memset(ptr, 0, size);
#if DEBUG_MEMORY
else if (size > 0)
memset(ptr, UNINIT_BLOCK, size);
#endif
// Prepare block header
CBlockHeader *hdr = (CBlockHeader*)ptr - 1;
byte offset = (byte*)ptr - (byte*)block;
hdr->magic = BLOCK_MAGIC;
hdr->offset = offset - 1;
hdr->align = alignment - 1;
hdr->blockSize = size;
#if DEBUG_MEMORY
// Setup debug stuff
#if THREADING
bool bLocked = false;
if (CThread::NumThreads)
{
GMallocMutex.Lock();
bLocked = true;
}
#endif
hdr->Link();
// Collect a call stack
CStackTrace stack;
appCaptureStackTrace(stack.stack, MAX_STACK_TRACE, 2);
stack.UpdateHash();
// Find similar call stack
CStackTrace* found = NULL;
for (int i = 0; i < GNumAllocationPoints; i++)
{
if (stack == GAllocationPoints[i])
{
found = &GAllocationPoints[i];
break;
}
}
if (!found)
{
assert(GNumAllocationPoints < MAX_ALLOCATION_POINTS);
found = &GAllocationPoints[GNumAllocationPoints++];
*found = stack;
}
hdr->stack = found;
#if THREADING
if (bLocked)
{
GMallocMutex.Unlock();
}
#endif
#endif // DEBUG_MEMORY
#if TRACY_DEBUG_MALLOC
PROFILE_ALLOC(ptr, size);
#endif
// statistics
InterlockedAdd(>otalAllocationSize, size);
InterlockedIncrement(>otalAllocationCount);
#if PROFILE
InterlockedIncrement(&GNumAllocs);
#endif
return ptr;
unguardf("size=%d (total=%d Mbytes)", size, (int)(GTotalAllocationSize >> 20));
}
void* appRealloc(void* ptr, int newSize)
{
guard(appRealloc);
// special case
if (!ptr) return appMallocNoInit(newSize);
CBlockHeader* hdr = (CBlockHeader*)ptr - 1;
assert(hdr->magic == BLOCK_MAGIC);
int oldSize = hdr->blockSize;
if (oldSize == newSize) return ptr; // size not changed
// Allocate new memory block and copy contents
int alignment = hdr->align + 1;
void* newData = appMallocNoInit(newSize, alignment);
memcpy(newData, ptr, min(newSize, oldSize));
// Release old memory block
hdr->magic--; // modify to any value
int offset = hdr->offset + 1;
void* block = OffsetPointer(ptr, -offset);
#if DEBUG_MEMORY
#if THREADING
if (CThread::NumThreads)
{
GMallocMutex.Lock();
hdr->Unlink();
GMallocMutex.Unlock();
}
else
{
hdr->Unlink();
}
#else
hdr->Unlink();
#endif
memset(ptr, FREE_BLOCK, oldSize);
#endif
free(block);
#if TRACY_DEBUG_MALLOC
PROFILE_FREE(ptr);
PROFILE_ALLOC(newData, newSize);
#endif
// statistics: we're allocating a new block with appMalloc, which counts statistics
// for this allocation, so only eliminate statistics from old memory block here
InterlockedAdd(>otalAllocationSize, -oldSize);
InterlockedDecrement(>otalAllocationCount);
#if PROFILE
InterlockedIncrement(&GNumAllocs);
#endif
return newData;
unguard;
}
void appFree(void* ptr)
{
guard(appFree);
assert(ptr);
CBlockHeader* hdr = (CBlockHeader*)ptr - 1;
assert(hdr->magic == BLOCK_MAGIC);
hdr->magic--; // modify to any value
int offset = hdr->offset + 1;
void* block = OffsetPointer(ptr, -offset);
#if DEBUG_MEMORY
#if THREADING
if (CThread::NumThreads)
{
GMallocMutex.Lock();
hdr->Unlink();
GMallocMutex.Unlock();
}
else
{
hdr->Unlink();
}
#else
hdr->Unlink();
#endif
memset(ptr, FREE_BLOCK, hdr->blockSize);
#endif
#if TRACY_DEBUG_MALLOC
PROFILE_FREE(ptr);
#endif
// statistics
InterlockedAdd(>otalAllocationSize, -hdr->blockSize);
InterlockedDecrement(>otalAllocationCount);
free(block);
unguard;
}
/*-----------------------------------------------------------------------------
CMemoryChain
-----------------------------------------------------------------------------*/
void* CMemoryChain::operator new(size_t size, int dataSize)
{
guard(CMemoryChain::new);
int alloc = Align(size + dataSize, MEM_CHUNK_SIZE);
CMemoryChain *chain = (CMemoryChain *) appMalloc(alloc); //!! allocate
if (!chain)
appError("Failed to allocate %d bytes", alloc);
chain->size = alloc;
chain->next = NULL;
chain->data = (byte*) OffsetPointer(chain, size);
chain->end = (byte*) OffsetPointer(chain, alloc);
memset(chain->data, 0, chain->end - chain->data);
return chain;
unguard;
}
void CMemoryChain::operator delete(void *ptr)
{
guard(CMemoryChain::delete);
CMemoryChain *curr, *next;
for (curr = (CMemoryChain *)ptr; curr; curr = next)
{
// free memory block
next = curr->next;
free(curr); //!! deallocate
}
unguard;
}
void *CMemoryChain::Alloc(size_t size, int alignment)
{
PROFILE_IF(false)
guard(CMemoryChain::Alloc);
if (!size) return NULL;
// sequence of blocks (with using "next" field): 1(==this)->5(last)->4->3->2->NULL
CMemoryChain *b = (next) ? next : this; // block for allocation
byte* start = Align(b->data, alignment); // start of new allocation
// check block free space
if (start + size > b->end)
{
PROFILE_IF(true);
guard(NewMemoryChain);
//?? may be, search in other blocks ...
// allocate in the new block
b = new (size + alignment - 1) CMemoryChain;
// insert new block immediately after 1st block (==this)
b->next = next;
next = b;
start = Align(b->data, alignment);
unguard;
}
// update pointer to a free space
b->data = start + size;
return start;
unguard;
}
int CMemoryChain::GetSize() const
{
int n = 0;
for (const CMemoryChain *c = this; c; c = c->next)
n += c->size;
return n;
}
/*-----------------------------------------------------------------------------
Debugging information
-----------------------------------------------------------------------------*/
#if DEBUG_MEMORY
struct CAllocInfo
{
int totalBlocks;
unsigned totalBytes;
const CStackTrace* stack;
};
static int CompareAllocInfo(const CAllocInfo* p1, const CAllocInfo* p2)
{
// Can't safely compare unsigned values with 'a - b', especially when a = max_uint and b = 0
if (p2->totalBytes > p1->totalBytes)
return 1;
else if (p2->totalBytes < p1->totalBytes)
return -1;
return p2->totalBlocks - p1->totalBlocks;
}
void appDumpMemoryAllocations()
{
appPrintf(
"Memory information:\n"
FORMAT_SIZE("u")" bytes allocated in %d blocks from %d points\n\n", GTotalAllocationSize, GTotalAllocationCount, GNumAllocationPoints
);
// collect statistics
CAllocInfo allocations[MAX_ALLOCATION_POINTS];
memset(allocations, 0, sizeof(allocations));
int numAllocations = 0;
for (const CBlockHeader* hdr = CBlockHeader::first; hdr; hdr = hdr->next)
{
const CStackTrace* stack = hdr->stack;
CAllocInfo* info = NULL;
for (int i = 0; i < numAllocations; i++)
if (allocations[i].stack == stack)
{
info = &allocations[i];
break;
}
if (!info)
{
assert(numAllocations < MAX_ALLOCATION_POINTS);
info = &allocations[numAllocations++];
info->stack = stack;
}
info->totalBytes += hdr->blockSize;
info->totalBlocks++;
}
// sort by allocation size
QSort(allocations, numAllocations, CompareAllocInfo);
// dump statistics
for (int i = 0; i < numAllocations; i++)
{
const CAllocInfo* info = &allocations[i];
appPrintf("%d blocks %u bytes\n", info->totalBlocks, info->totalBytes);
info->stack->Dump();
appPrintf("\n");
}
}
#endif // DEBUG_MEMORY
#ifdef __APPLE__
void* operator new(size_t size)
{
return appMalloc(size);
}
void* operator new[](size_t size)
{
return appMalloc(size);
}
void operator delete(void* ptr)
{
appFree(ptr);
}
void operator delete[](void* ptr)
{
appFree(ptr);
}
#endif // __APPLE__