2 Copyright (C) 1996-1997 Id Software, Inc.
4 This program is free software; you can redistribute it and/or
5 modify it under the terms of the GNU General Public License
6 as published by the Free Software Foundation; either version 2
7 of the License, or (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13 See the GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
37 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
38 unsigned int sentinel_seed;
40 qboolean mem_bigendian = false;
41 void *mem_mutex = NULL;
43 // divVerent: enables file backed malloc using mmap to conserve swap space (instead of malloc)
44 #ifndef FILE_BACKED_MALLOC
45 # define FILE_BACKED_MALLOC 0
48 // LordHavoc: enables our own low-level allocator (instead of malloc)
50 # define MEMCLUMPING 0
52 #ifndef MEMCLUMPING_FREECLUMPS
53 # define MEMCLUMPING_FREECLUMPS 0
57 // smallest unit we care about is this many bytes
59 // try to do 32MB clumps, but overhead eats into this
60 #ifndef MEMWANTCLUMPSIZE
61 # define MEMWANTCLUMPSIZE (1<<27)
63 // give malloc padding so we can't waste most of a page at the end
64 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
65 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
66 #define MEMBITINTS (MEMBITS / 32)
68 typedef struct memclump_s
70 // contents of the clump
71 unsigned char block[MEMCLUMPSIZE];
72 // should always be MEMCLUMP_SENTINEL
73 unsigned int sentinel1;
74 // if a bit is on, it means that the MEMUNIT bytes it represents are
75 // allocated, otherwise free
76 unsigned int bits[MEMBITINTS];
77 // should always be MEMCLUMP_SENTINEL
78 unsigned int sentinel2;
79 // if this drops to 0, the clump is freed
81 // largest block of memory available (this is reset to an optimistic
82 // number when anything is freed, and updated when alloc fails the clump)
83 size_t largestavailable;
84 // next clump in the chain
85 struct memclump_s *chain;
90 static memclump_t masterclump;
92 static memclump_t *clumpchain = NULL;
96 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
97 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
98 cvar_t sys_memsize_physical = {CVAR_READONLY, "sys_memsize_physical", "", "physical memory size in MB (or empty if unknown)"};
99 cvar_t sys_memsize_virtual = {CVAR_READONLY, "sys_memsize_virtual", "", "virtual memory size in MB (or empty if unknown)"};
101 static mempool_t *poolchain = NULL;
103 void Mem_PrintStats(void);
104 void Mem_PrintList(size_t minallocationsize);
106 #if FILE_BACKED_MALLOC
108 #include <sys/mman.h>
109 typedef struct mmap_data_s
114 static void *mmap_malloc(size_t size)
116 char vabuf[MAX_OSPATH + 1];
117 char *tmpdir = getenv("TEMP");
120 size += sizeof(mmap_data_t); // waste block
121 dpsnprintf(vabuf, sizeof(vabuf), "%s/darkplaces.XXXXXX", tmpdir ? tmpdir : "/tmp");
126 data = (unsigned char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, fd, 0);
132 return (void *) (data + 1);
134 static void mmap_free(void *mem)
139 data = ((mmap_data_t *) mem) - 1;
140 munmap(data, data->len);
142 #define malloc mmap_malloc
143 #define free mmap_free
147 // some platforms have a malloc that returns NULL but succeeds later
148 // (Windows growing its swapfile for example)
149 static void *attempt_malloc(size_t size)
152 // try for half a second or so
153 unsigned int attempts = 500;
156 base = (void *)malloc(size);
166 static memclump_t *Clump_NewClump(void)
168 memclump_t **clumpchainpointer;
173 clump = &masterclump;
175 clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
181 if (developer_memorydebug.integer)
182 memset(clump, 0xEF, sizeof(*clump));
183 clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
184 memset(clump->bits, 0, sizeof(clump->bits));
185 clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
186 clump->blocksinuse = 0;
187 clump->largestavailable = 0;
190 // link clump into chain
191 for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
193 *clumpchainpointer = clump;
199 // low level clumping functions, all other memory functions use these
200 static void *Clump_AllocBlock(size_t size)
204 if (size <= MEMCLUMPSIZE)
208 unsigned int needbits;
209 unsigned int startbit;
211 unsigned int needints;
217 memclump_t **clumpchainpointer;
219 needbits = (size + MEMUNIT - 1) / MEMUNIT;
220 needints = (needbits+31)>>5;
221 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
223 clump = *clumpchainpointer;
226 clump = Clump_NewClump();
230 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
231 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
232 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
233 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
235 endbit = startbit + needbits;
237 // do as fast a search as possible, even if it means crude alignment
240 // large allocations are aligned to large boundaries
241 // furthermore, they are allocated downward from the top...
242 endindex = MEMBITINTS;
243 startindex = endindex - needints;
245 while (--index >= startindex)
250 startindex = endindex - needints;
255 startbit = startindex*32;
260 // search for a multi-bit gap in a single int
261 // (not dealing with the cases that cross two ints)
262 mask = (1<<needbits)-1;
263 endbit = 32-needbits;
265 for (index = 0;index < MEMBITINTS;index++)
267 value = array[index];
268 if (value != 0xFFFFFFFFu)
270 // there may be room in this one...
271 for (bit = 0;bit < endbit;bit++)
273 if (!(value & (mask<<bit)))
275 startbit = index*32+bit;
284 endbit = startbit + needbits;
285 // mark this range as used
287 for (bit = startbit;bit < endbit;bit++)
288 if (clump->bits[bit>>5] & (1<<(bit & 31)))
289 Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
290 for (bit = startbit;bit < endbit;bit++)
291 clump->bits[bit>>5] |= (1<<(bit & 31));
292 clump->blocksinuse += needbits;
293 base = clump->block + startbit * MEMUNIT;
294 if (developer_memorydebug.integer)
295 memset(base, 0xBF, needbits * MEMUNIT);
303 // too big, allocate it directly
308 base = (unsigned char *)attempt_malloc(size);
309 if (base && developer_memorydebug.integer)
310 memset(base, 0xAF, size);
314 static void Clump_FreeBlock(void *base, size_t size)
317 unsigned int needbits;
318 unsigned int startbit;
321 memclump_t **clumpchainpointer;
323 unsigned char *start = (unsigned char *)base;
324 for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
326 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
328 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
329 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
330 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
331 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
332 if (start + size > clump->block + MEMCLUMPSIZE)
333 Sys_Error("Clump_FreeBlock: block overrun\n");
334 // the block belongs to this clump, clear the range
335 needbits = (size + MEMUNIT - 1) / MEMUNIT;
336 startbit = (start - clump->block) / MEMUNIT;
337 endbit = startbit + needbits;
338 // first verify all bits are set, otherwise this may be misaligned or a double free
339 for (bit = startbit;bit < endbit;bit++)
340 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
341 Sys_Error("Clump_FreeBlock: double free\n");
342 for (bit = startbit;bit < endbit;bit++)
343 clump->bits[bit>>5] &= ~(1<<(bit & 31));
344 clump->blocksinuse -= needbits;
345 memset(base, 0xFF, needbits * MEMUNIT);
346 // if all has been freed, free the clump itself
347 if (clump->blocksinuse == 0)
349 *clumpchainpointer = clump->chain;
350 if (developer_memorydebug.integer)
351 memset(clump, 0xFF, sizeof(*clump));
359 // does not belong to any known chunk... assume it was a direct allocation
362 memset(base, 0xFF, size);
367 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
369 unsigned int sentinel1;
370 unsigned int sentinel2;
381 _Mem_Free(olddata, filename, fileline);
387 pool = ((memheader_t *)((unsigned char *) olddata - sizeof(memheader_t)))->pool;
389 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
392 Thread_LockMutex(mem_mutex);
393 if (developer_memory.integer)
394 Con_DPrintf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
395 //if (developer.integer > 0 && developer_memorydebug.integer)
396 // _Mem_CheckSentinelsGlobal(filename, fileline);
397 pool->totalsize += size;
398 realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
399 pool->realsize += realsize;
400 base = (unsigned char *)Clump_AllocBlock(realsize);
405 Mem_PrintList(1<<30);
407 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
409 // calculate address that aligns the end of the memheader_t to the specified alignment
410 mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
411 mem->baseaddress = (void*)base;
412 mem->filename = filename;
413 mem->fileline = fileline;
417 // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
418 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
419 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
420 mem->sentinel = sentinel1;
421 memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
423 // append to head of list
424 mem->next = pool->chain;
428 mem->next->prev = mem;
431 Thread_UnlockMutex(mem_mutex);
433 // copy the shared portion in the case of a realloc, then memset the rest
438 oldmem = (memheader_t*)olddata - 1;
439 sharedsize = min(oldmem->size, size);
440 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
441 remainsize -= sharedsize;
442 _Mem_Free(olddata, filename, fileline);
444 memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
445 return (void *)((unsigned char *) mem + sizeof(memheader_t));
448 // only used by _Mem_Free and _Mem_FreePool
449 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
454 unsigned int sentinel1;
455 unsigned int sentinel2;
457 // check sentinels (detects buffer overruns, in a way that is hard to exploit)
458 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
459 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
460 if (mem->sentinel != sentinel1)
461 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
462 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
463 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
466 if (developer_memory.integer)
467 Con_DPrintf("Mem_Free: pool %s, alloc %s:%i, free %s:%i, size %i bytes\n", pool->name, mem->filename, mem->fileline, filename, fileline, (int)(mem->size));
468 // unlink memheader from doubly linked list
469 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
470 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
472 Thread_LockMutex(mem_mutex);
474 mem->prev->next = mem->next;
476 pool->chain = mem->next;
478 mem->next->prev = mem->prev;
479 // memheader has been unlinked, do the actual free now
481 realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
482 pool->totalsize -= size;
483 pool->realsize -= realsize;
484 Clump_FreeBlock(mem->baseaddress, realsize);
486 Thread_UnlockMutex(mem_mutex);
489 void _Mem_Free(void *data, const char *filename, int fileline)
493 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
497 if (developer_memorydebug.integer)
499 //_Mem_CheckSentinelsGlobal(filename, fileline);
500 if (!Mem_IsAllocated(NULL, data))
501 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
504 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
507 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
510 if (developer_memorydebug.integer)
511 _Mem_CheckSentinelsGlobal(filename, fileline);
512 pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
517 Mem_PrintList(1<<30);
519 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
521 memset(pool, 0, sizeof(mempool_t));
522 pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
523 pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
524 pool->filename = filename;
525 pool->fileline = fileline;
529 pool->realsize = sizeof(mempool_t);
530 strlcpy (pool->name, name, sizeof (pool->name));
531 pool->parent = parent;
532 pool->next = poolchain;
537 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
539 mempool_t *pool = *poolpointer;
540 mempool_t **chainaddress, *iter, *temp;
542 if (developer_memorydebug.integer)
543 _Mem_CheckSentinelsGlobal(filename, fileline);
546 // unlink pool from chain
547 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
548 if (*chainaddress != pool)
549 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
550 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
551 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
552 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
553 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
554 *chainaddress = pool->next;
556 // free memory owned by the pool
558 _Mem_FreeBlock(pool->chain, filename, fileline);
560 // free child pools, too
561 for(iter = poolchain; iter; iter = temp) {
563 if(iter->parent == pool)
564 _Mem_FreePool(&temp, filename, fileline);
567 // free the pool itself
568 Clump_FreeBlock(pool, sizeof(*pool));
574 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
576 mempool_t *chainaddress;
578 if (developer_memorydebug.integer)
580 //_Mem_CheckSentinelsGlobal(filename, fileline);
581 // check if this pool is in the poolchain
582 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
583 if (chainaddress == pool)
586 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
589 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
590 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
591 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
592 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
593 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
595 // free memory owned by the pool
597 _Mem_FreeBlock(pool->chain, filename, fileline);
599 // empty child pools, too
600 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
601 if(chainaddress->parent == pool)
602 _Mem_EmptyPool(chainaddress, filename, fileline);
606 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
609 unsigned int sentinel1;
610 unsigned int sentinel2;
613 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
615 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
616 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
617 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
618 if (mem->sentinel != sentinel1)
619 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
620 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
621 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
625 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
627 // this isn't really very useful
628 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
629 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
630 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
631 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
635 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
642 for (pool = poolchain;pool;pool = pool->next)
644 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
645 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
646 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
647 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
649 for (pool = poolchain;pool;pool = pool->next)
650 for (mem = pool->chain;mem;mem = mem->next)
651 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
653 for (pool = poolchain;pool;pool = pool->next)
654 for (clump = clumpchain;clump;clump = clump->chain)
655 _Mem_CheckClumpSentinels(clump, filename, fileline);
659 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
666 // search only one pool
667 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
668 for( header = pool->chain ; header ; header = header->next )
669 if( header == target )
675 for (pool = poolchain;pool;pool = pool->next)
676 if (Mem_IsAllocated(pool, data))
682 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
684 memset(l, 0, sizeof(*l));
685 l->mempool = mempool;
686 l->recordsize = recordsize;
687 l->numrecordsperarray = numrecordsperarray;
690 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
695 for (i = 0;i != l->numarrays;i++)
696 Mem_Free(l->arrays[i].data);
699 memset(l, 0, sizeof(*l));
702 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
707 if (i == l->numarrays)
709 if (l->numarrays == l->maxarrays)
711 memexpandablearray_array_t *oldarrays = l->arrays;
712 l->maxarrays = max(l->maxarrays * 2, 128);
713 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
716 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
720 l->arrays[i].numflaggedrecords = 0;
721 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
722 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
725 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
727 for (j = 0;j < l->numrecordsperarray;j++)
729 if (!l->arrays[i].allocflags[j])
731 l->arrays[i].allocflags[j] = true;
732 l->arrays[i].numflaggedrecords++;
733 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
734 return (void *)(l->arrays[i].data + l->recordsize * j);
741 /*****************************************************************************
743 * If this function was to change the size of the "expandable" array, you have
744 * to update r_shadow.c
745 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
746 * function to look at. (And also seems like the only one?) You might have to
747 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
750 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
753 unsigned char *p = (unsigned char *)record;
754 for (i = 0;i != l->numarrays;i++)
756 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
758 j = (p - l->arrays[i].data) / l->recordsize;
759 if (p != l->arrays[i].data + j * l->recordsize)
760 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
761 if (!l->arrays[i].allocflags[j])
762 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
763 l->arrays[i].allocflags[j] = false;
764 l->arrays[i].numflaggedrecords--;
770 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
772 size_t i, j, k, end = 0;
773 for (i = 0;i < l->numarrays;i++)
775 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
777 if (l->arrays[i].allocflags[j])
779 end = l->numrecordsperarray * i + j + 1;
787 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
790 i = index / l->numrecordsperarray;
791 j = index % l->numrecordsperarray;
792 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
794 return (void *)(l->arrays[i].data + j * l->recordsize);
798 // used for temporary memory allocations around the engine, not for longterm
799 // storage, if anything in this pool stays allocated during gameplay, it is
801 mempool_t *tempmempool;
803 mempool_t *zonemempool;
805 void Mem_PrintStats(void)
807 size_t count = 0, size = 0, realsize = 0;
810 Mem_CheckSentinelsGlobal();
811 for (pool = poolchain;pool;pool = pool->next)
814 size += pool->totalsize;
815 realsize += pool->realsize;
817 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
818 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
819 for (pool = poolchain;pool;pool = pool->next)
821 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
823 Con_Printf("Memory pool %p has sprung a leak totalling %lu bytes (%.3fMB)! Listing contents...\n", (void *)pool, (unsigned long)pool->totalsize, pool->totalsize / 1048576.0);
824 for (mem = pool->chain;mem;mem = mem->next)
825 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
830 void Mem_PrintList(size_t minallocationsize)
834 Mem_CheckSentinelsGlobal();
835 Con_Print("memory pool list:\n"
837 for (pool = poolchain;pool;pool = pool->next)
839 Con_Printf("%10luk (%10luk actual) %s (%+li byte change) %s\n", (unsigned long) ((pool->totalsize + 1023) / 1024), (unsigned long)((pool->realsize + 1023) / 1024), pool->name, (long)(pool->totalsize - pool->lastchecksize), (pool->flags & POOLFLAG_TEMP) ? "TEMP" : "");
840 pool->lastchecksize = pool->totalsize;
841 for (mem = pool->chain;mem;mem = mem->next)
842 if (mem->size >= minallocationsize)
843 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
847 static void MemList_f(void)
852 Mem_PrintList(1<<30);
856 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
860 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
865 static void MemStats_f(void)
867 Mem_CheckSentinelsGlobal();
868 R_TextureStats_Print(false, false, true);
869 GL_Mesh_ListVBOs(false);
874 char* Mem_strdup (mempool_t *pool, const char* s)
881 p = (char*)Mem_Alloc (pool, sz);
887 ========================
889 ========================
891 void Memory_Init (void)
893 static union {unsigned short s;unsigned char b[2];} u;
895 mem_bigendian = u.b[0] != 0;
897 sentinel_seed = rand();
899 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
900 zonemempool = Mem_AllocPool("Zone", 0, NULL);
902 if (Thread_HasThreads())
903 mem_mutex = Thread_CreateMutex();
906 void Memory_Shutdown (void)
908 // Mem_FreePool (&zonemempool);
909 // Mem_FreePool (&tempmempool);
912 Thread_DestroyMutex(mem_mutex);
916 void Memory_Init_Commands (void)
918 Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
919 Cmd_AddCommand ("memlist", MemList_f, "prints memory pool information (or if used as memlist 5 lists individual allocations of 5K or larger, 0 lists all allocations)");
920 Cvar_RegisterVariable (&developer_memory);
921 Cvar_RegisterVariable (&developer_memorydebug);
922 Cvar_RegisterVariable (&sys_memsize_physical);
923 Cvar_RegisterVariable (&sys_memsize_virtual);
928 MEMORYSTATUSEX status;
930 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
932 status.dwLength = sizeof(status);
933 if(GlobalMemoryStatusEx(&status))
935 Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
936 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
943 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
945 status.dwLength = sizeof(status);
946 GlobalMemoryStatus(&status);
947 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
948 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
954 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
957 // Linux, and BSD with linprocfs mounted
958 FILE *f = fopen("/proc/meminfo", "r");
961 static char buf[1024];
962 while(fgets(buf, sizeof(buf), f))
965 if(!COM_ParseToken_Console(&p))
967 if(!strcmp(com_token, "MemTotal:"))
969 if(!COM_ParseToken_Console(&p))
971 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
973 if(!strcmp(com_token, "SwapTotal:"))
975 if(!COM_ParseToken_Console(&p))
977 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));