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 // LadyHavoc: 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 = {CVAR_CLIENT | CVAR_SERVER, "developer_memory", "0", "prints debugging information about memory allocations"};
97 cvar_t developer_memorydebug = {CVAR_CLIENT | CVAR_SERVER, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
98 cvar_t developer_memoryreportlargerthanmb = {CVAR_CLIENT | CVAR_SERVER, "developer_memorylargerthanmb", "16", "prints debugging information about memory allocations over this size"};
99 cvar_t sys_memsize_physical = {CVAR_CLIENT | CVAR_SERVER | CVAR_READONLY, "sys_memsize_physical", "", "physical memory size in MB (or empty if unknown)"};
100 cvar_t sys_memsize_virtual = {CVAR_CLIENT | CVAR_SERVER | CVAR_READONLY, "sys_memsize_virtual", "", "virtual memory size in MB (or empty if unknown)"};
102 static mempool_t *poolchain = NULL;
104 void Mem_PrintStats(void);
105 void Mem_PrintList(size_t minallocationsize);
107 #if FILE_BACKED_MALLOC
109 #include <sys/mman.h>
110 #ifndef MAP_NORESERVE
111 #define MAP_NORESERVE 0
113 typedef struct mmap_data_s
118 static void *mmap_malloc(size_t size)
120 char vabuf[MAX_OSPATH + 1];
121 char *tmpdir = getenv("TEMP");
124 size += sizeof(mmap_data_t); // waste block
125 dpsnprintf(vabuf, sizeof(vabuf), "%s/darkplaces.XXXXXX", tmpdir ? tmpdir : "/tmp");
130 data = (unsigned char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, fd, 0);
133 if(!data || data == (void *)-1)
136 return (void *) (data + 1);
138 static void mmap_free(void *mem)
143 data = ((mmap_data_t *) mem) - 1;
144 munmap(data, data->len);
146 #define malloc mmap_malloc
147 #define free mmap_free
151 // some platforms have a malloc that returns NULL but succeeds later
152 // (Windows growing its swapfile for example)
153 static void *attempt_malloc(size_t size)
156 // try for half a second or so
157 unsigned int attempts = 500;
160 base = (void *)malloc(size);
170 static memclump_t *Clump_NewClump(void)
172 memclump_t **clumpchainpointer;
177 clump = &masterclump;
179 clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
185 if (developer_memorydebug.integer)
186 memset(clump, 0xEF, sizeof(*clump));
187 clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
188 memset(clump->bits, 0, sizeof(clump->bits));
189 clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
190 clump->blocksinuse = 0;
191 clump->largestavailable = 0;
194 // link clump into chain
195 for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
197 *clumpchainpointer = clump;
203 // low level clumping functions, all other memory functions use these
204 static void *Clump_AllocBlock(size_t size)
208 if (size <= MEMCLUMPSIZE)
212 unsigned int needbits;
213 unsigned int startbit;
215 unsigned int needints;
221 memclump_t **clumpchainpointer;
223 needbits = (size + MEMUNIT - 1) / MEMUNIT;
224 needints = (needbits+31)>>5;
225 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
227 clump = *clumpchainpointer;
230 clump = Clump_NewClump();
234 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
235 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
236 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
237 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
239 endbit = startbit + needbits;
241 // do as fast a search as possible, even if it means crude alignment
244 // large allocations are aligned to large boundaries
245 // furthermore, they are allocated downward from the top...
246 endindex = MEMBITINTS;
247 startindex = endindex - needints;
249 while (--index >= startindex)
254 startindex = endindex - needints;
259 startbit = startindex*32;
264 // search for a multi-bit gap in a single int
265 // (not dealing with the cases that cross two ints)
266 mask = (1<<needbits)-1;
267 endbit = 32-needbits;
269 for (index = 0;index < MEMBITINTS;index++)
271 value = array[index];
272 if (value != 0xFFFFFFFFu)
274 // there may be room in this one...
275 for (bit = 0;bit < endbit;bit++)
277 if (!(value & (mask<<bit)))
279 startbit = index*32+bit;
288 endbit = startbit + needbits;
289 // mark this range as used
291 for (bit = startbit;bit < endbit;bit++)
292 if (clump->bits[bit>>5] & (1<<(bit & 31)))
293 Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
294 for (bit = startbit;bit < endbit;bit++)
295 clump->bits[bit>>5] |= (1<<(bit & 31));
296 clump->blocksinuse += needbits;
297 base = clump->block + startbit * MEMUNIT;
298 if (developer_memorydebug.integer)
299 memset(base, 0xBF, needbits * MEMUNIT);
307 // too big, allocate it directly
312 base = (unsigned char *)attempt_malloc(size);
313 if (base && developer_memorydebug.integer)
314 memset(base, 0xAF, size);
318 static void Clump_FreeBlock(void *base, size_t size)
321 unsigned int needbits;
322 unsigned int startbit;
325 memclump_t **clumpchainpointer;
327 unsigned char *start = (unsigned char *)base;
328 for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
330 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
332 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
333 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
334 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
335 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
336 if (start + size > clump->block + MEMCLUMPSIZE)
337 Sys_Error("Clump_FreeBlock: block overrun\n");
338 // the block belongs to this clump, clear the range
339 needbits = (size + MEMUNIT - 1) / MEMUNIT;
340 startbit = (start - clump->block) / MEMUNIT;
341 endbit = startbit + needbits;
342 // first verify all bits are set, otherwise this may be misaligned or a double free
343 for (bit = startbit;bit < endbit;bit++)
344 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
345 Sys_Error("Clump_FreeBlock: double free\n");
346 for (bit = startbit;bit < endbit;bit++)
347 clump->bits[bit>>5] &= ~(1<<(bit & 31));
348 clump->blocksinuse -= needbits;
349 memset(base, 0xFF, needbits * MEMUNIT);
350 // if all has been freed, free the clump itself
351 if (clump->blocksinuse == 0)
353 *clumpchainpointer = clump->chain;
354 if (developer_memorydebug.integer)
355 memset(clump, 0xFF, sizeof(*clump));
363 // does not belong to any known chunk... assume it was a direct allocation
366 memset(base, 0xFF, size);
371 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
373 unsigned int sentinel1;
374 unsigned int sentinel2;
385 _Mem_Free(olddata, filename, fileline);
391 pool = ((memheader_t *)((unsigned char *) olddata - sizeof(memheader_t)))->pool;
393 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
396 Thread_LockMutex(mem_mutex);
397 if (developer_memory.integer || size >= developer_memoryreportlargerthanmb.value * 1048576)
398 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);
399 //if (developer.integer > 0 && developer_memorydebug.integer)
400 // _Mem_CheckSentinelsGlobal(filename, fileline);
401 pool->totalsize += size;
402 realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
403 pool->realsize += realsize;
404 base = (unsigned char *)Clump_AllocBlock(realsize);
409 Mem_PrintList(1<<30);
411 Sys_Error("Mem_Alloc: out of memory (alloc of size %f (%.3fMB) at %s:%i)", (double)realsize, (double)realsize / (1 << 20), filename, fileline);
413 // calculate address that aligns the end of the memheader_t to the specified alignment
414 mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
415 mem->baseaddress = (void*)base;
416 mem->filename = filename;
417 mem->fileline = fileline;
421 // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
422 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
423 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
424 mem->sentinel = sentinel1;
425 memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
427 // append to head of list
428 mem->next = pool->chain;
432 mem->next->prev = mem;
435 Thread_UnlockMutex(mem_mutex);
437 // copy the shared portion in the case of a realloc, then memset the rest
442 oldmem = (memheader_t*)olddata - 1;
443 sharedsize = min(oldmem->size, size);
444 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
445 remainsize -= sharedsize;
446 _Mem_Free(olddata, filename, fileline);
448 memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
449 return (void *)((unsigned char *) mem + sizeof(memheader_t));
452 // only used by _Mem_Free and _Mem_FreePool
453 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
458 unsigned int sentinel1;
459 unsigned int sentinel2;
461 // check sentinels (detects buffer overruns, in a way that is hard to exploit)
462 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
463 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
464 if (mem->sentinel != sentinel1)
465 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
466 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
467 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
470 if (developer_memory.integer)
471 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));
472 // unlink memheader from doubly linked list
473 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
474 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
476 Thread_LockMutex(mem_mutex);
478 mem->prev->next = mem->next;
480 pool->chain = mem->next;
482 mem->next->prev = mem->prev;
483 // memheader has been unlinked, do the actual free now
485 realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
486 pool->totalsize -= size;
487 pool->realsize -= realsize;
488 Clump_FreeBlock(mem->baseaddress, realsize);
490 Thread_UnlockMutex(mem_mutex);
493 void _Mem_Free(void *data, const char *filename, int fileline)
497 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
501 if (developer_memorydebug.integer)
503 //_Mem_CheckSentinelsGlobal(filename, fileline);
504 if (!Mem_IsAllocated(NULL, data))
505 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
508 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
511 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
514 if (developer_memorydebug.integer)
515 _Mem_CheckSentinelsGlobal(filename, fileline);
516 pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
521 Mem_PrintList(1<<30);
523 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
525 memset(pool, 0, sizeof(mempool_t));
526 pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
527 pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
528 pool->filename = filename;
529 pool->fileline = fileline;
533 pool->realsize = sizeof(mempool_t);
534 strlcpy (pool->name, name, sizeof (pool->name));
535 pool->parent = parent;
536 pool->next = poolchain;
541 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
543 mempool_t *pool = *poolpointer;
544 mempool_t **chainaddress, *iter, *temp;
546 if (developer_memorydebug.integer)
547 _Mem_CheckSentinelsGlobal(filename, fileline);
550 // unlink pool from chain
551 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
552 if (*chainaddress != pool)
553 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
554 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
555 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
556 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
557 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
558 *chainaddress = pool->next;
560 // free memory owned by the pool
562 _Mem_FreeBlock(pool->chain, filename, fileline);
564 // free child pools, too
565 for(iter = poolchain; iter; iter = temp) {
567 if(iter->parent == pool)
568 _Mem_FreePool(&temp, filename, fileline);
571 // free the pool itself
572 Clump_FreeBlock(pool, sizeof(*pool));
578 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
580 mempool_t *chainaddress;
582 if (developer_memorydebug.integer)
584 //_Mem_CheckSentinelsGlobal(filename, fileline);
585 // check if this pool is in the poolchain
586 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
587 if (chainaddress == pool)
590 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
593 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
594 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
595 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
596 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
597 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
599 // free memory owned by the pool
601 _Mem_FreeBlock(pool->chain, filename, fileline);
603 // empty child pools, too
604 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
605 if(chainaddress->parent == pool)
606 _Mem_EmptyPool(chainaddress, filename, fileline);
610 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
613 unsigned int sentinel1;
614 unsigned int sentinel2;
617 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
619 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
620 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
621 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
622 if (mem->sentinel != sentinel1)
623 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
624 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
625 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
629 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
631 // this isn't really very useful
632 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
633 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
634 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
635 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
639 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
646 for (pool = poolchain;pool;pool = pool->next)
648 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
649 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
650 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
651 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
653 for (pool = poolchain;pool;pool = pool->next)
654 for (mem = pool->chain;mem;mem = mem->next)
655 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
657 for (pool = poolchain;pool;pool = pool->next)
658 for (clump = clumpchain;clump;clump = clump->chain)
659 _Mem_CheckClumpSentinels(clump, filename, fileline);
663 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
670 // search only one pool
671 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
672 for( header = pool->chain ; header ; header = header->next )
673 if( header == target )
679 for (pool = poolchain;pool;pool = pool->next)
680 if (Mem_IsAllocated(pool, data))
686 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
688 memset(l, 0, sizeof(*l));
689 l->mempool = mempool;
690 l->recordsize = recordsize;
691 l->numrecordsperarray = numrecordsperarray;
694 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
699 for (i = 0;i != l->numarrays;i++)
700 Mem_Free(l->arrays[i].data);
703 memset(l, 0, sizeof(*l));
706 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
711 if (i == l->numarrays)
713 if (l->numarrays == l->maxarrays)
715 memexpandablearray_array_t *oldarrays = l->arrays;
716 l->maxarrays = max(l->maxarrays * 2, 128);
717 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
720 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
724 l->arrays[i].numflaggedrecords = 0;
725 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
726 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
729 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
731 for (j = 0;j < l->numrecordsperarray;j++)
733 if (!l->arrays[i].allocflags[j])
735 l->arrays[i].allocflags[j] = true;
736 l->arrays[i].numflaggedrecords++;
737 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
738 return (void *)(l->arrays[i].data + l->recordsize * j);
745 /*****************************************************************************
747 * If this function was to change the size of the "expandable" array, you have
748 * to update r_shadow.c
749 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
750 * function to look at. (And also seems like the only one?) You might have to
751 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
754 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
757 unsigned char *p = (unsigned char *)record;
758 for (i = 0;i != l->numarrays;i++)
760 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
762 j = (p - l->arrays[i].data) / l->recordsize;
763 if (p != l->arrays[i].data + j * l->recordsize)
764 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", (void *)p);
765 if (!l->arrays[i].allocflags[j])
766 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", (void *)p);
767 l->arrays[i].allocflags[j] = false;
768 l->arrays[i].numflaggedrecords--;
774 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
776 size_t i, j, k, end = 0;
777 for (i = 0;i < l->numarrays;i++)
779 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
781 if (l->arrays[i].allocflags[j])
783 end = l->numrecordsperarray * i + j + 1;
791 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
794 i = index / l->numrecordsperarray;
795 j = index % l->numrecordsperarray;
796 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
798 return (void *)(l->arrays[i].data + j * l->recordsize);
802 // used for temporary memory allocations around the engine, not for longterm
803 // storage, if anything in this pool stays allocated during gameplay, it is
805 mempool_t *tempmempool;
807 mempool_t *zonemempool;
809 void Mem_PrintStats(void)
811 size_t count = 0, size = 0, realsize = 0;
814 Mem_CheckSentinelsGlobal();
815 for (pool = poolchain;pool;pool = pool->next)
818 size += pool->totalsize;
819 realsize += pool->realsize;
821 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
822 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
823 for (pool = poolchain;pool;pool = pool->next)
825 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
827 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);
828 for (mem = pool->chain;mem;mem = mem->next)
829 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
834 void Mem_PrintList(size_t minallocationsize)
838 Mem_CheckSentinelsGlobal();
839 Con_Print("memory pool list:\n"
841 for (pool = poolchain;pool;pool = pool->next)
843 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" : "");
844 pool->lastchecksize = pool->totalsize;
845 for (mem = pool->chain;mem;mem = mem->next)
846 if (mem->size >= minallocationsize)
847 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
851 static void MemList_f(cmd_state_t *cmd)
853 switch(Cmd_Argc(cmd))
856 Mem_PrintList(1<<30);
860 Mem_PrintList(atoi(Cmd_Argv(cmd, 1)) * 1024);
864 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
869 static void MemStats_f(cmd_state_t *cmd)
871 Mem_CheckSentinelsGlobal();
872 R_TextureStats_Print(false, false, true);
873 GL_Mesh_ListVBOs(false);
878 char* Mem_strdup (mempool_t *pool, const char* s)
885 p = (char*)Mem_Alloc (pool, sz);
891 ========================
893 ========================
895 void Memory_Init (void)
897 static union {unsigned short s;unsigned char b[2];} u;
899 mem_bigendian = u.b[0] != 0;
901 sentinel_seed = rand();
903 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
904 zonemempool = Mem_AllocPool("Zone", 0, NULL);
906 if (Thread_HasThreads())
907 mem_mutex = Thread_CreateMutex();
910 void Memory_Shutdown (void)
912 // Mem_FreePool (&zonemempool);
913 // Mem_FreePool (&tempmempool);
916 Thread_DestroyMutex(mem_mutex);
920 void Memory_Init_Commands (void)
922 Cmd_AddCommand(CMD_SHARED, "memstats", MemStats_f, "prints memory system statistics");
923 Cmd_AddCommand(CMD_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)");
925 Cvar_RegisterVariable (&developer_memory);
926 Cvar_RegisterVariable (&developer_memorydebug);
927 Cvar_RegisterVariable (&developer_memoryreportlargerthanmb);
928 Cvar_RegisterVariable (&sys_memsize_physical);
929 Cvar_RegisterVariable (&sys_memsize_virtual);
934 MEMORYSTATUSEX status;
936 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
938 status.dwLength = sizeof(status);
939 if(GlobalMemoryStatusEx(&status))
941 Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
942 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
949 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
951 status.dwLength = sizeof(status);
952 GlobalMemoryStatus(&status);
953 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
954 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
960 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
963 // Linux, and BSD with linprocfs mounted
964 FILE *f = fopen("/proc/meminfo", "r");
967 static char buf[1024];
968 while(fgets(buf, sizeof(buf), f))
971 if(!COM_ParseToken_Console(&p))
973 if(!strcmp(com_token, "MemTotal:"))
975 if(!COM_ParseToken_Console(&p))
977 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
979 if(!strcmp(com_token, "SwapTotal:"))
981 if(!COM_ParseToken_Console(&p))
983 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));