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 typedef struct mmap_data_s
115 static void *mmap_malloc(size_t size)
117 char vabuf[MAX_OSPATH + 1];
118 char *tmpdir = getenv("TEMP");
121 size += sizeof(mmap_data_t); // waste block
122 dpsnprintf(vabuf, sizeof(vabuf), "%s/darkplaces.XXXXXX", tmpdir ? tmpdir : "/tmp");
127 data = (unsigned char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_NORESERVE, fd, 0);
133 return (void *) (data + 1);
135 static void mmap_free(void *mem)
140 data = ((mmap_data_t *) mem) - 1;
141 munmap(data, data->len);
143 #define malloc mmap_malloc
144 #define free mmap_free
148 // some platforms have a malloc that returns NULL but succeeds later
149 // (Windows growing its swapfile for example)
150 static void *attempt_malloc(size_t size)
153 // try for half a second or so
154 unsigned int attempts = 500;
157 base = (void *)malloc(size);
167 static memclump_t *Clump_NewClump(void)
169 memclump_t **clumpchainpointer;
174 clump = &masterclump;
176 clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
182 if (developer_memorydebug.integer)
183 memset(clump, 0xEF, sizeof(*clump));
184 clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
185 memset(clump->bits, 0, sizeof(clump->bits));
186 clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
187 clump->blocksinuse = 0;
188 clump->largestavailable = 0;
191 // link clump into chain
192 for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
194 *clumpchainpointer = clump;
200 // low level clumping functions, all other memory functions use these
201 static void *Clump_AllocBlock(size_t size)
205 if (size <= MEMCLUMPSIZE)
209 unsigned int needbits;
210 unsigned int startbit;
212 unsigned int needints;
218 memclump_t **clumpchainpointer;
220 needbits = (size + MEMUNIT - 1) / MEMUNIT;
221 needints = (needbits+31)>>5;
222 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
224 clump = *clumpchainpointer;
227 clump = Clump_NewClump();
231 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
232 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
233 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
234 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
236 endbit = startbit + needbits;
238 // do as fast a search as possible, even if it means crude alignment
241 // large allocations are aligned to large boundaries
242 // furthermore, they are allocated downward from the top...
243 endindex = MEMBITINTS;
244 startindex = endindex - needints;
246 while (--index >= startindex)
251 startindex = endindex - needints;
256 startbit = startindex*32;
261 // search for a multi-bit gap in a single int
262 // (not dealing with the cases that cross two ints)
263 mask = (1<<needbits)-1;
264 endbit = 32-needbits;
266 for (index = 0;index < MEMBITINTS;index++)
268 value = array[index];
269 if (value != 0xFFFFFFFFu)
271 // there may be room in this one...
272 for (bit = 0;bit < endbit;bit++)
274 if (!(value & (mask<<bit)))
276 startbit = index*32+bit;
285 endbit = startbit + needbits;
286 // mark this range as used
288 for (bit = startbit;bit < endbit;bit++)
289 if (clump->bits[bit>>5] & (1<<(bit & 31)))
290 Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
291 for (bit = startbit;bit < endbit;bit++)
292 clump->bits[bit>>5] |= (1<<(bit & 31));
293 clump->blocksinuse += needbits;
294 base = clump->block + startbit * MEMUNIT;
295 if (developer_memorydebug.integer)
296 memset(base, 0xBF, needbits * MEMUNIT);
304 // too big, allocate it directly
309 base = (unsigned char *)attempt_malloc(size);
310 if (base && developer_memorydebug.integer)
311 memset(base, 0xAF, size);
315 static void Clump_FreeBlock(void *base, size_t size)
318 unsigned int needbits;
319 unsigned int startbit;
322 memclump_t **clumpchainpointer;
324 unsigned char *start = (unsigned char *)base;
325 for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
327 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
329 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
330 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
331 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
332 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
333 if (start + size > clump->block + MEMCLUMPSIZE)
334 Sys_Error("Clump_FreeBlock: block overrun\n");
335 // the block belongs to this clump, clear the range
336 needbits = (size + MEMUNIT - 1) / MEMUNIT;
337 startbit = (start - clump->block) / MEMUNIT;
338 endbit = startbit + needbits;
339 // first verify all bits are set, otherwise this may be misaligned or a double free
340 for (bit = startbit;bit < endbit;bit++)
341 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
342 Sys_Error("Clump_FreeBlock: double free\n");
343 for (bit = startbit;bit < endbit;bit++)
344 clump->bits[bit>>5] &= ~(1<<(bit & 31));
345 clump->blocksinuse -= needbits;
346 memset(base, 0xFF, needbits * MEMUNIT);
347 // if all has been freed, free the clump itself
348 if (clump->blocksinuse == 0)
350 *clumpchainpointer = clump->chain;
351 if (developer_memorydebug.integer)
352 memset(clump, 0xFF, sizeof(*clump));
360 // does not belong to any known chunk... assume it was a direct allocation
363 memset(base, 0xFF, size);
368 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
370 unsigned int sentinel1;
371 unsigned int sentinel2;
382 _Mem_Free(olddata, filename, fileline);
388 pool = ((memheader_t *)((unsigned char *) olddata - sizeof(memheader_t)))->pool;
390 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
393 Thread_LockMutex(mem_mutex);
394 if (developer_memory.integer || size >= developer_memoryreportlargerthanmb.value * 1048576)
395 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);
396 //if (developer.integer > 0 && developer_memorydebug.integer)
397 // _Mem_CheckSentinelsGlobal(filename, fileline);
398 pool->totalsize += size;
399 realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
400 pool->realsize += realsize;
401 base = (unsigned char *)Clump_AllocBlock(realsize);
406 Mem_PrintList(1<<30);
408 Sys_Error("Mem_Alloc: out of memory (alloc of size %f (%.3fMB) at %s:%i)", (double)realsize, (double)realsize / (1 << 20), filename, fileline);
410 // calculate address that aligns the end of the memheader_t to the specified alignment
411 mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
412 mem->baseaddress = (void*)base;
413 mem->filename = filename;
414 mem->fileline = fileline;
418 // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
419 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
420 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
421 mem->sentinel = sentinel1;
422 memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
424 // append to head of list
425 mem->next = pool->chain;
429 mem->next->prev = mem;
432 Thread_UnlockMutex(mem_mutex);
434 // copy the shared portion in the case of a realloc, then memset the rest
439 oldmem = (memheader_t*)olddata - 1;
440 sharedsize = min(oldmem->size, size);
441 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
442 remainsize -= sharedsize;
443 _Mem_Free(olddata, filename, fileline);
445 memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
446 return (void *)((unsigned char *) mem + sizeof(memheader_t));
449 // only used by _Mem_Free and _Mem_FreePool
450 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
455 unsigned int sentinel1;
456 unsigned int sentinel2;
458 // check sentinels (detects buffer overruns, in a way that is hard to exploit)
459 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
460 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
461 if (mem->sentinel != sentinel1)
462 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
463 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
464 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
467 if (developer_memory.integer)
468 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));
469 // unlink memheader from doubly linked list
470 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
471 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
473 Thread_LockMutex(mem_mutex);
475 mem->prev->next = mem->next;
477 pool->chain = mem->next;
479 mem->next->prev = mem->prev;
480 // memheader has been unlinked, do the actual free now
482 realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
483 pool->totalsize -= size;
484 pool->realsize -= realsize;
485 Clump_FreeBlock(mem->baseaddress, realsize);
487 Thread_UnlockMutex(mem_mutex);
490 void _Mem_Free(void *data, const char *filename, int fileline)
494 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
498 if (developer_memorydebug.integer)
500 //_Mem_CheckSentinelsGlobal(filename, fileline);
501 if (!Mem_IsAllocated(NULL, data))
502 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
505 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
508 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
511 if (developer_memorydebug.integer)
512 _Mem_CheckSentinelsGlobal(filename, fileline);
513 pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
518 Mem_PrintList(1<<30);
520 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
522 memset(pool, 0, sizeof(mempool_t));
523 pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
524 pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
525 pool->filename = filename;
526 pool->fileline = fileline;
530 pool->realsize = sizeof(mempool_t);
531 strlcpy (pool->name, name, sizeof (pool->name));
532 pool->parent = parent;
533 pool->next = poolchain;
538 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
540 mempool_t *pool = *poolpointer;
541 mempool_t **chainaddress, *iter, *temp;
543 if (developer_memorydebug.integer)
544 _Mem_CheckSentinelsGlobal(filename, fileline);
547 // unlink pool from chain
548 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
549 if (*chainaddress != pool)
550 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
551 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
552 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
553 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
554 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
555 *chainaddress = pool->next;
557 // free memory owned by the pool
559 _Mem_FreeBlock(pool->chain, filename, fileline);
561 // free child pools, too
562 for(iter = poolchain; iter; iter = temp) {
564 if(iter->parent == pool)
565 _Mem_FreePool(&temp, filename, fileline);
568 // free the pool itself
569 Clump_FreeBlock(pool, sizeof(*pool));
575 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
577 mempool_t *chainaddress;
579 if (developer_memorydebug.integer)
581 //_Mem_CheckSentinelsGlobal(filename, fileline);
582 // check if this pool is in the poolchain
583 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
584 if (chainaddress == pool)
587 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
590 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
591 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
592 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
593 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
594 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
596 // free memory owned by the pool
598 _Mem_FreeBlock(pool->chain, filename, fileline);
600 // empty child pools, too
601 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
602 if(chainaddress->parent == pool)
603 _Mem_EmptyPool(chainaddress, filename, fileline);
607 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
610 unsigned int sentinel1;
611 unsigned int sentinel2;
614 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
616 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
617 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
618 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
619 if (mem->sentinel != sentinel1)
620 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
621 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
622 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
626 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
628 // this isn't really very useful
629 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
630 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
631 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
632 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
636 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
643 for (pool = poolchain;pool;pool = pool->next)
645 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
646 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
647 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
648 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
650 for (pool = poolchain;pool;pool = pool->next)
651 for (mem = pool->chain;mem;mem = mem->next)
652 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
654 for (pool = poolchain;pool;pool = pool->next)
655 for (clump = clumpchain;clump;clump = clump->chain)
656 _Mem_CheckClumpSentinels(clump, filename, fileline);
660 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
667 // search only one pool
668 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
669 for( header = pool->chain ; header ; header = header->next )
670 if( header == target )
676 for (pool = poolchain;pool;pool = pool->next)
677 if (Mem_IsAllocated(pool, data))
683 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
685 memset(l, 0, sizeof(*l));
686 l->mempool = mempool;
687 l->recordsize = recordsize;
688 l->numrecordsperarray = numrecordsperarray;
691 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
696 for (i = 0;i != l->numarrays;i++)
697 Mem_Free(l->arrays[i].data);
700 memset(l, 0, sizeof(*l));
703 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
708 if (i == l->numarrays)
710 if (l->numarrays == l->maxarrays)
712 memexpandablearray_array_t *oldarrays = l->arrays;
713 l->maxarrays = max(l->maxarrays * 2, 128);
714 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
717 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
721 l->arrays[i].numflaggedrecords = 0;
722 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
723 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
726 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
728 for (j = 0;j < l->numrecordsperarray;j++)
730 if (!l->arrays[i].allocflags[j])
732 l->arrays[i].allocflags[j] = true;
733 l->arrays[i].numflaggedrecords++;
734 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
735 return (void *)(l->arrays[i].data + l->recordsize * j);
742 /*****************************************************************************
744 * If this function was to change the size of the "expandable" array, you have
745 * to update r_shadow.c
746 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
747 * function to look at. (And also seems like the only one?) You might have to
748 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
751 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
754 unsigned char *p = (unsigned char *)record;
755 for (i = 0;i != l->numarrays;i++)
757 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
759 j = (p - l->arrays[i].data) / l->recordsize;
760 if (p != l->arrays[i].data + j * l->recordsize)
761 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", (void *)p);
762 if (!l->arrays[i].allocflags[j])
763 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", (void *)p);
764 l->arrays[i].allocflags[j] = false;
765 l->arrays[i].numflaggedrecords--;
771 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
773 size_t i, j, k, end = 0;
774 for (i = 0;i < l->numarrays;i++)
776 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
778 if (l->arrays[i].allocflags[j])
780 end = l->numrecordsperarray * i + j + 1;
788 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
791 i = index / l->numrecordsperarray;
792 j = index % l->numrecordsperarray;
793 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
795 return (void *)(l->arrays[i].data + j * l->recordsize);
799 // used for temporary memory allocations around the engine, not for longterm
800 // storage, if anything in this pool stays allocated during gameplay, it is
802 mempool_t *tempmempool;
804 mempool_t *zonemempool;
806 void Mem_PrintStats(void)
808 size_t count = 0, size = 0, realsize = 0;
811 Mem_CheckSentinelsGlobal();
812 for (pool = poolchain;pool;pool = pool->next)
815 size += pool->totalsize;
816 realsize += pool->realsize;
818 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
819 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
820 for (pool = poolchain;pool;pool = pool->next)
822 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
824 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);
825 for (mem = pool->chain;mem;mem = mem->next)
826 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
831 void Mem_PrintList(size_t minallocationsize)
835 Mem_CheckSentinelsGlobal();
836 Con_Print("memory pool list:\n"
838 for (pool = poolchain;pool;pool = pool->next)
840 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" : "");
841 pool->lastchecksize = pool->totalsize;
842 for (mem = pool->chain;mem;mem = mem->next)
843 if (mem->size >= minallocationsize)
844 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
848 static void MemList_f(cmd_state_t *cmd)
850 switch(Cmd_Argc(cmd))
853 Mem_PrintList(1<<30);
857 Mem_PrintList(atoi(Cmd_Argv(cmd, 1)) * 1024);
861 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
866 static void MemStats_f(cmd_state_t *cmd)
868 Mem_CheckSentinelsGlobal();
869 R_TextureStats_Print(false, false, true);
870 GL_Mesh_ListVBOs(false);
875 char* Mem_strdup (mempool_t *pool, const char* s)
882 p = (char*)Mem_Alloc (pool, sz);
888 ========================
890 ========================
892 void Memory_Init (void)
894 static union {unsigned short s;unsigned char b[2];} u;
896 mem_bigendian = u.b[0] != 0;
898 sentinel_seed = rand();
900 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
901 zonemempool = Mem_AllocPool("Zone", 0, NULL);
903 if (Thread_HasThreads())
904 mem_mutex = Thread_CreateMutex();
907 void Memory_Shutdown (void)
909 // Mem_FreePool (&zonemempool);
910 // Mem_FreePool (&tempmempool);
913 Thread_DestroyMutex(mem_mutex);
917 void Memory_Init_Commands (void)
919 Cmd_AddCommand(CMD_SHARED, "memstats", MemStats_f, "prints memory system statistics");
920 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)");
922 Cvar_RegisterVariable (&developer_memory);
923 Cvar_RegisterVariable (&developer_memorydebug);
924 Cvar_RegisterVariable (&developer_memoryreportlargerthanmb);
925 Cvar_RegisterVariable (&sys_memsize_physical);
926 Cvar_RegisterVariable (&sys_memsize_virtual);
931 MEMORYSTATUSEX status;
933 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
935 status.dwLength = sizeof(status);
936 if(GlobalMemoryStatusEx(&status))
938 Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
939 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
946 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
948 status.dwLength = sizeof(status);
949 GlobalMemoryStatus(&status);
950 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
951 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
957 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
960 // Linux, and BSD with linprocfs mounted
961 FILE *f = fopen("/proc/meminfo", "r");
964 static char buf[1024];
965 while(fgets(buf, sizeof(buf), f))
968 if(!COM_ParseToken_Console(&p))
970 if(!strcmp(com_token, "MemTotal:"))
972 if(!COM_ParseToken_Console(&p))
974 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
976 if(!strcmp(com_token, "SwapTotal:"))
978 if(!COM_ParseToken_Console(&p))
980 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));