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.
22 #include "darkplaces.h"
31 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
32 unsigned int sentinel_seed;
34 qbool mem_bigendian = false;
35 void *mem_mutex = NULL;
37 // divVerent: enables file backed malloc using mmap to conserve swap space (instead of malloc)
38 #ifndef FILE_BACKED_MALLOC
39 # define FILE_BACKED_MALLOC 0
42 // LadyHavoc: enables our own low-level allocator (instead of malloc)
44 # define MEMCLUMPING 0
46 #ifndef MEMCLUMPING_FREECLUMPS
47 # define MEMCLUMPING_FREECLUMPS 0
51 // smallest unit we care about is this many bytes
53 // try to do 32MB clumps, but overhead eats into this
54 #ifndef MEMWANTCLUMPSIZE
55 # define MEMWANTCLUMPSIZE (1<<27)
57 // give malloc padding so we can't waste most of a page at the end
58 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
59 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
60 #define MEMBITINTS (MEMBITS / 32)
62 typedef struct memclump_s
64 // contents of the clump
65 unsigned char block[MEMCLUMPSIZE];
66 // should always be MEMCLUMP_SENTINEL
67 unsigned int sentinel1;
68 // if a bit is on, it means that the MEMUNIT bytes it represents are
69 // allocated, otherwise free
70 unsigned int bits[MEMBITINTS];
71 // should always be MEMCLUMP_SENTINEL
72 unsigned int sentinel2;
73 // if this drops to 0, the clump is freed
75 // largest block of memory available (this is reset to an optimistic
76 // number when anything is freed, and updated when alloc fails the clump)
77 size_t largestavailable;
78 // next clump in the chain
79 struct memclump_s *chain;
84 static memclump_t masterclump;
86 static memclump_t *clumpchain = NULL;
90 cvar_t developer_memory = {CF_CLIENT | CF_SERVER, "developer_memory", "0", "prints debugging information about memory allocations"};
91 cvar_t developer_memorydebug = {CF_CLIENT | CF_SERVER, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
92 cvar_t developer_memoryreportlargerthanmb = {CF_CLIENT | CF_SERVER, "developer_memorylargerthanmb", "16", "prints debugging information about memory allocations over this size"};
93 cvar_t sys_memsize_physical = {CF_CLIENT | CF_SERVER | CF_READONLY, "sys_memsize_physical", "", "physical memory size in MB (or empty if unknown)"};
94 cvar_t sys_memsize_virtual = {CF_CLIENT | CF_SERVER | CF_READONLY, "sys_memsize_virtual", "", "virtual memory size in MB (or empty if unknown)"};
96 static mempool_t *poolchain = NULL;
98 void Mem_PrintStats(void);
99 void Mem_PrintList(size_t minallocationsize);
101 #if FILE_BACKED_MALLOC
103 #include <sys/mman.h>
104 #ifndef MAP_NORESERVE
105 #define MAP_NORESERVE 0
107 typedef struct mmap_data_s
112 static void *mmap_malloc(size_t size)
114 char vabuf[MAX_OSPATH + 1];
115 char *tmpdir = getenv("TEMP");
118 size += sizeof(mmap_data_t); // waste block
119 dpsnprintf(vabuf, sizeof(vabuf), "%s/darkplaces.XXXXXX", tmpdir ? tmpdir : "/tmp");
124 data = (unsigned char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, fd, 0);
127 if(!data || data == (void *)-1)
130 return (void *) (data + 1);
132 static void mmap_free(void *mem)
137 data = ((mmap_data_t *) mem) - 1;
138 munmap(data, data->len);
140 #define malloc mmap_malloc
141 #define free mmap_free
145 // some platforms have a malloc that returns NULL but succeeds later
146 // (Windows growing its swapfile for example)
147 static void *attempt_malloc(size_t size)
150 // try for half a second or so
151 unsigned int attempts = 500;
154 base = (void *)malloc(size);
164 static memclump_t *Clump_NewClump(void)
166 memclump_t **clumpchainpointer;
171 clump = &masterclump;
173 clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
179 if (developer_memorydebug.integer)
180 memset(clump, 0xEF, sizeof(*clump));
181 clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
182 memset(clump->bits, 0, sizeof(clump->bits));
183 clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
184 clump->blocksinuse = 0;
185 clump->largestavailable = 0;
188 // link clump into chain
189 for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
191 *clumpchainpointer = clump;
197 // low level clumping functions, all other memory functions use these
198 static void *Clump_AllocBlock(size_t size)
202 if (size <= MEMCLUMPSIZE)
206 unsigned int needbits;
207 unsigned int startbit;
209 unsigned int needints;
215 memclump_t **clumpchainpointer;
217 needbits = (size + MEMUNIT - 1) / MEMUNIT;
218 needints = (needbits+31)>>5;
219 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
221 clump = *clumpchainpointer;
224 clump = Clump_NewClump();
228 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
229 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
230 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
231 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
233 endbit = startbit + needbits;
235 // do as fast a search as possible, even if it means crude alignment
238 // large allocations are aligned to large boundaries
239 // furthermore, they are allocated downward from the top...
240 endindex = MEMBITINTS;
241 startindex = endindex - needints;
243 while (--index >= startindex)
248 startindex = endindex - needints;
253 startbit = startindex*32;
258 // search for a multi-bit gap in a single int
259 // (not dealing with the cases that cross two ints)
260 mask = (1<<needbits)-1;
261 endbit = 32-needbits;
263 for (index = 0;index < MEMBITINTS;index++)
265 value = array[index];
266 if (value != 0xFFFFFFFFu)
268 // there may be room in this one...
269 for (bit = 0;bit < endbit;bit++)
271 if (!(value & (mask<<bit)))
273 startbit = index*32+bit;
282 endbit = startbit + needbits;
283 // mark this range as used
285 for (bit = startbit;bit < endbit;bit++)
286 if (clump->bits[bit>>5] & (1<<(bit & 31)))
287 Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
288 for (bit = startbit;bit < endbit;bit++)
289 clump->bits[bit>>5] |= (1<<(bit & 31));
290 clump->blocksinuse += needbits;
291 base = clump->block + startbit * MEMUNIT;
292 if (developer_memorydebug.integer)
293 memset(base, 0xBF, needbits * MEMUNIT);
301 // too big, allocate it directly
306 base = (unsigned char *)attempt_malloc(size);
307 if (base && developer_memorydebug.integer)
308 memset(base, 0xAF, size);
312 static void Clump_FreeBlock(void *base, size_t size)
315 unsigned int needbits;
316 unsigned int startbit;
319 memclump_t **clumpchainpointer;
321 unsigned char *start = (unsigned char *)base;
322 for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
324 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
326 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
327 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
328 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
329 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
330 if (start + size > clump->block + MEMCLUMPSIZE)
331 Sys_Error("Clump_FreeBlock: block overrun\n");
332 // the block belongs to this clump, clear the range
333 needbits = (size + MEMUNIT - 1) / MEMUNIT;
334 startbit = (start - clump->block) / MEMUNIT;
335 endbit = startbit + needbits;
336 // first verify all bits are set, otherwise this may be misaligned or a double free
337 for (bit = startbit;bit < endbit;bit++)
338 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
339 Sys_Error("Clump_FreeBlock: double free\n");
340 for (bit = startbit;bit < endbit;bit++)
341 clump->bits[bit>>5] &= ~(1<<(bit & 31));
342 clump->blocksinuse -= needbits;
343 memset(base, 0xFF, needbits * MEMUNIT);
344 // if all has been freed, free the clump itself
345 if (clump->blocksinuse == 0)
347 *clumpchainpointer = clump->chain;
348 if (developer_memorydebug.integer)
349 memset(clump, 0xFF, sizeof(*clump));
357 // does not belong to any known chunk... assume it was a direct allocation
360 memset(base, 0xFF, size);
365 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
367 unsigned int sentinel1;
368 unsigned int sentinel2;
379 _Mem_Free(olddata, filename, fileline);
385 pool = ((memheader_t *)((unsigned char *) olddata - sizeof(memheader_t)))->pool;
387 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
390 Thread_LockMutex(mem_mutex);
391 if (developer_memory.integer || size >= developer_memoryreportlargerthanmb.value * 1048576)
392 Con_DPrintf("Mem_Alloc: pool %s, file %s:%i, size %f bytes (%f MB)\n", pool->name, filename, fileline, (double)size, (double)size / 1048576.0f);
393 //if (developer.integer > 0 && developer_memorydebug.integer)
394 // _Mem_CheckSentinelsGlobal(filename, fileline);
395 pool->totalsize += size;
396 realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
397 pool->realsize += realsize;
398 base = (unsigned char *)Clump_AllocBlock(realsize);
403 Mem_PrintList(1<<30);
405 Sys_Error("Mem_Alloc: out of memory (alloc of size %f (%.3fMB) at %s:%i)", (double)realsize, (double)realsize / (1 << 20), filename, fileline);
407 // calculate address that aligns the end of the memheader_t to the specified alignment
408 mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
409 mem->baseaddress = (void*)base;
410 mem->filename = filename;
411 mem->fileline = fileline;
415 // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
416 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
417 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
418 mem->sentinel = sentinel1;
419 memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
421 // append to head of list
422 mem->next = pool->chain;
426 mem->next->prev = mem;
429 Thread_UnlockMutex(mem_mutex);
431 // copy the shared portion in the case of a realloc, then memset the rest
436 oldmem = (memheader_t*)olddata - 1;
437 sharedsize = min(oldmem->size, size);
438 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
439 remainsize -= sharedsize;
440 _Mem_Free(olddata, filename, fileline);
442 memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
443 return (void *)((unsigned char *) mem + sizeof(memheader_t));
446 // only used by _Mem_Free and _Mem_FreePool
447 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
452 unsigned int sentinel1;
453 unsigned int sentinel2;
455 // check sentinels (detects buffer overruns, in a way that is hard to exploit)
456 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
457 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
458 if (mem->sentinel != sentinel1)
459 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
460 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
461 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
464 if (developer_memory.integer)
465 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));
466 // unlink memheader from doubly linked list
467 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
468 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
470 Thread_LockMutex(mem_mutex);
472 mem->prev->next = mem->next;
474 pool->chain = mem->next;
476 mem->next->prev = mem->prev;
477 // memheader has been unlinked, do the actual free now
479 realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
480 pool->totalsize -= size;
481 pool->realsize -= realsize;
482 Clump_FreeBlock(mem->baseaddress, realsize);
484 Thread_UnlockMutex(mem_mutex);
487 void _Mem_Free(void *data, const char *filename, int fileline)
491 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
495 if (developer_memorydebug.integer)
497 //_Mem_CheckSentinelsGlobal(filename, fileline);
498 if (!Mem_IsAllocated(NULL, data))
499 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
502 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
505 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
508 if (developer_memorydebug.integer)
509 _Mem_CheckSentinelsGlobal(filename, fileline);
510 pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
515 Mem_PrintList(1<<30);
517 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
519 memset(pool, 0, sizeof(mempool_t));
520 pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
521 pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
522 pool->filename = filename;
523 pool->fileline = fileline;
527 pool->realsize = sizeof(mempool_t);
528 strlcpy (pool->name, name, sizeof (pool->name));
529 pool->parent = parent;
530 pool->next = poolchain;
535 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
537 mempool_t *pool = *poolpointer;
538 mempool_t **chainaddress, *iter, *temp;
540 if (developer_memorydebug.integer)
541 _Mem_CheckSentinelsGlobal(filename, fileline);
544 // unlink pool from chain
545 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
546 if (*chainaddress != pool)
547 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
548 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
549 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
550 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
551 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
552 *chainaddress = pool->next;
554 // free memory owned by the pool
556 _Mem_FreeBlock(pool->chain, filename, fileline);
558 // free child pools, too
559 for(iter = poolchain; iter; iter = temp) {
561 if(iter->parent == pool)
562 _Mem_FreePool(&temp, filename, fileline);
565 // free the pool itself
566 Clump_FreeBlock(pool, sizeof(*pool));
572 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
574 mempool_t *chainaddress;
576 if (developer_memorydebug.integer)
578 //_Mem_CheckSentinelsGlobal(filename, fileline);
579 // check if this pool is in the poolchain
580 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
581 if (chainaddress == pool)
584 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
587 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
588 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
589 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
590 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
591 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
593 // free memory owned by the pool
595 _Mem_FreeBlock(pool->chain, filename, fileline);
597 // empty child pools, too
598 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
599 if(chainaddress->parent == pool)
600 _Mem_EmptyPool(chainaddress, filename, fileline);
604 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
607 unsigned int sentinel1;
608 unsigned int sentinel2;
611 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
613 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
614 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
615 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
616 if (mem->sentinel != sentinel1)
617 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
618 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
619 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
623 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
625 // this isn't really very useful
626 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
627 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
628 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
629 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
633 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
640 for (pool = poolchain;pool;pool = pool->next)
642 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
643 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
644 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
645 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
647 for (pool = poolchain;pool;pool = pool->next)
648 for (mem = pool->chain;mem;mem = mem->next)
649 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
651 for (pool = poolchain;pool;pool = pool->next)
652 for (clump = clumpchain;clump;clump = clump->chain)
653 _Mem_CheckClumpSentinels(clump, filename, fileline);
657 qbool Mem_IsAllocated(mempool_t *pool, void *data)
664 // search only one pool
665 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
666 for( header = pool->chain ; header ; header = header->next )
667 if( header == target )
673 for (pool = poolchain;pool;pool = pool->next)
674 if (Mem_IsAllocated(pool, data))
680 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
682 memset(l, 0, sizeof(*l));
683 l->mempool = mempool;
684 l->recordsize = recordsize;
685 l->numrecordsperarray = numrecordsperarray;
688 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
693 for (i = 0;i != l->numarrays;i++)
694 Mem_Free(l->arrays[i].data);
697 memset(l, 0, sizeof(*l));
700 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
705 if (i == l->numarrays)
707 if (l->numarrays == l->maxarrays)
709 memexpandablearray_array_t *oldarrays = l->arrays;
710 l->maxarrays = max(l->maxarrays * 2, 128);
711 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
714 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
718 l->arrays[i].numflaggedrecords = 0;
719 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
720 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
723 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
725 for (j = 0;j < l->numrecordsperarray;j++)
727 if (!l->arrays[i].allocflags[j])
729 l->arrays[i].allocflags[j] = true;
730 l->arrays[i].numflaggedrecords++;
731 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
732 return (void *)(l->arrays[i].data + l->recordsize * j);
739 /*****************************************************************************
741 * If this function was to change the size of the "expandable" array, you have
742 * to update r_shadow.c
743 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
744 * function to look at. (And also seems like the only one?) You might have to
745 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
748 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
751 unsigned char *p = (unsigned char *)record;
752 for (i = 0;i != l->numarrays;i++)
754 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
756 j = (p - l->arrays[i].data) / l->recordsize;
757 if (p != l->arrays[i].data + j * l->recordsize)
758 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", (void *)p);
759 if (!l->arrays[i].allocflags[j])
760 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", (void *)p);
761 l->arrays[i].allocflags[j] = false;
762 l->arrays[i].numflaggedrecords--;
768 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
770 size_t i, j, k, end = 0;
771 for (i = 0;i < l->numarrays;i++)
773 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
775 if (l->arrays[i].allocflags[j])
777 end = l->numrecordsperarray * i + j + 1;
785 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
788 i = index / l->numrecordsperarray;
789 j = index % l->numrecordsperarray;
790 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
792 return (void *)(l->arrays[i].data + j * l->recordsize);
796 // used for temporary memory allocations around the engine, not for longterm
797 // storage, if anything in this pool stays allocated during gameplay, it is
799 mempool_t *tempmempool;
801 mempool_t *zonemempool;
803 void Mem_PrintStats(void)
805 size_t count = 0, size = 0, realsize = 0;
808 Mem_CheckSentinelsGlobal();
809 for (pool = poolchain;pool;pool = pool->next)
812 size += pool->totalsize;
813 realsize += pool->realsize;
815 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
816 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
817 for (pool = poolchain;pool;pool = pool->next)
819 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
821 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);
822 for (mem = pool->chain;mem;mem = mem->next)
823 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
828 void Mem_PrintList(size_t minallocationsize)
832 Mem_CheckSentinelsGlobal();
833 Con_Print("memory pool list:\n"
835 for (pool = poolchain;pool;pool = pool->next)
837 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" : "");
838 pool->lastchecksize = pool->totalsize;
839 for (mem = pool->chain;mem;mem = mem->next)
840 if (mem->size >= minallocationsize)
841 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
845 static void MemList_f(cmd_state_t *cmd)
847 switch(Cmd_Argc(cmd))
850 Mem_PrintList(1<<30);
854 Mem_PrintList(atoi(Cmd_Argv(cmd, 1)) * 1024);
858 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
863 static void MemStats_f(cmd_state_t *cmd)
865 Mem_CheckSentinelsGlobal();
870 char* Mem_strdup (mempool_t *pool, const char* s)
877 p = (char*)Mem_Alloc (pool, sz);
883 ========================
885 ========================
887 void Memory_Init (void)
889 static union {unsigned short s;unsigned char b[2];} u;
891 mem_bigendian = u.b[0] != 0;
893 sentinel_seed = rand();
895 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
896 zonemempool = Mem_AllocPool("Zone", 0, NULL);
898 if (Thread_HasThreads())
899 mem_mutex = Thread_CreateMutex();
902 void Memory_Shutdown (void)
904 // Mem_FreePool (&zonemempool);
905 // Mem_FreePool (&tempmempool);
908 Thread_DestroyMutex(mem_mutex);
912 void Memory_Init_Commands (void)
914 Cmd_AddCommand(CF_SHARED, "memstats", MemStats_f, "prints memory system statistics");
915 Cmd_AddCommand(CF_SHARED, "memlist", MemList_f, "prints memory pool information (or if used as memlist 5 lists individual allocations of 5K or larger, 0 lists all allocations)");
917 Cvar_RegisterVariable (&developer_memory);
918 Cvar_RegisterVariable (&developer_memorydebug);
919 Cvar_RegisterVariable (&developer_memoryreportlargerthanmb);
920 Cvar_RegisterVariable (&sys_memsize_physical);
921 Cvar_RegisterVariable (&sys_memsize_virtual);
926 MEMORYSTATUSEX status;
928 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
930 status.dwLength = sizeof(status);
931 if(GlobalMemoryStatusEx(&status))
933 Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
934 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
941 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
943 status.dwLength = sizeof(status);
944 GlobalMemoryStatus(&status);
945 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
946 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
952 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
955 // Linux, and BSD with linprocfs mounted
956 FILE *f = fopen("/proc/meminfo", "r");
959 static char buf[1024];
960 while(fgets(buf, sizeof(buf), f))
963 if(!COM_ParseToken_Console(&p))
965 if(!strcmp(com_token, "MemTotal:"))
967 if(!COM_ParseToken_Console(&p))
969 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
971 if(!strcmp(com_token, "SwapTotal:"))
973 if(!COM_ParseToken_Console(&p))
975 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));