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 // LordHavoc: enables our own low-level allocator (instead of malloc)
45 #define MEMCLUMPING_FREECLUMPS 0
48 // smallest unit we care about is this many bytes
50 // try to do 32MB clumps, but overhead eats into this
51 #define MEMWANTCLUMPSIZE (1<<27)
52 // give malloc padding so we can't waste most of a page at the end
53 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
54 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
55 #define MEMBITINTS (MEMBITS / 32)
57 typedef struct memclump_s
59 // contents of the clump
60 unsigned char block[MEMCLUMPSIZE];
61 // should always be MEMCLUMP_SENTINEL
62 unsigned int sentinel1;
63 // if a bit is on, it means that the MEMUNIT bytes it represents are
64 // allocated, otherwise free
65 unsigned int bits[MEMBITINTS];
66 // should always be MEMCLUMP_SENTINEL
67 unsigned int sentinel2;
68 // if this drops to 0, the clump is freed
70 // largest block of memory available (this is reset to an optimistic
71 // number when anything is freed, and updated when alloc fails the clump)
72 size_t largestavailable;
73 // next clump in the chain
74 struct memclump_s *chain;
79 static memclump_t masterclump;
81 static memclump_t *clumpchain = NULL;
85 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
86 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
87 cvar_t sys_memsize_physical = {CVAR_READONLY, "sys_memsize_physical", "", "physical memory size in MB (or empty if unknown)"};
88 cvar_t sys_memsize_virtual = {CVAR_READONLY, "sys_memsize_virtual", "", "virtual memory size in MB (or empty if unknown)"};
90 static mempool_t *poolchain = NULL;
92 void Mem_PrintStats(void);
93 void Mem_PrintList(size_t minallocationsize);
96 // some platforms have a malloc that returns NULL but succeeds later
97 // (Windows growing its swapfile for example)
98 static void *attempt_malloc(size_t size)
101 // try for half a second or so
102 unsigned int attempts = 500;
105 base = (void *)malloc(size);
115 static memclump_t *Clump_NewClump(void)
117 memclump_t **clumpchainpointer;
122 clump = &masterclump;
124 clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
130 if (developer_memorydebug.integer)
131 memset(clump, 0xEF, sizeof(*clump));
132 clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
133 memset(clump->bits, 0, sizeof(clump->bits));
134 clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
135 clump->blocksinuse = 0;
136 clump->largestavailable = 0;
139 // link clump into chain
140 for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
142 *clumpchainpointer = clump;
148 // low level clumping functions, all other memory functions use these
149 static void *Clump_AllocBlock(size_t size)
153 if (size <= MEMCLUMPSIZE)
157 unsigned int needbits;
158 unsigned int startbit;
160 unsigned int needints;
166 memclump_t **clumpchainpointer;
168 needbits = (size + MEMUNIT - 1) / MEMUNIT;
169 needints = (needbits+31)>>5;
170 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
172 clump = *clumpchainpointer;
175 clump = Clump_NewClump();
179 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
180 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
181 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
182 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
184 endbit = startbit + needbits;
186 // do as fast a search as possible, even if it means crude alignment
189 // large allocations are aligned to large boundaries
190 // furthermore, they are allocated downward from the top...
191 endindex = MEMBITINTS;
192 startindex = endindex - needints;
194 while (--index >= startindex)
199 startindex = endindex - needints;
204 startbit = startindex*32;
209 // search for a multi-bit gap in a single int
210 // (not dealing with the cases that cross two ints)
211 mask = (1<<needbits)-1;
212 endbit = 32-needbits;
214 for (index = 0;index < MEMBITINTS;index++)
216 value = array[index];
217 if (value != 0xFFFFFFFFu)
219 // there may be room in this one...
220 for (bit = 0;bit < endbit;bit++)
222 if (!(value & (mask<<bit)))
224 startbit = index*32+bit;
233 endbit = startbit + needbits;
234 // mark this range as used
236 for (bit = startbit;bit < endbit;bit++)
237 if (clump->bits[bit>>5] & (1<<(bit & 31)))
238 Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
239 for (bit = startbit;bit < endbit;bit++)
240 clump->bits[bit>>5] |= (1<<(bit & 31));
241 clump->blocksinuse += needbits;
242 base = clump->block + startbit * MEMUNIT;
243 if (developer_memorydebug.integer)
244 memset(base, 0xBF, needbits * MEMUNIT);
252 // too big, allocate it directly
257 base = (unsigned char *)attempt_malloc(size);
258 if (base && developer_memorydebug.integer)
259 memset(base, 0xAF, size);
263 static void Clump_FreeBlock(void *base, size_t size)
266 unsigned int needbits;
267 unsigned int startbit;
270 memclump_t **clumpchainpointer;
272 unsigned char *start = (unsigned char *)base;
273 for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
275 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
277 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
278 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
279 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
280 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
281 if (start + size > clump->block + MEMCLUMPSIZE)
282 Sys_Error("Clump_FreeBlock: block overrun\n");
283 // the block belongs to this clump, clear the range
284 needbits = (size + MEMUNIT - 1) / MEMUNIT;
285 startbit = (start - clump->block) / MEMUNIT;
286 endbit = startbit + needbits;
287 // first verify all bits are set, otherwise this may be misaligned or a double free
288 for (bit = startbit;bit < endbit;bit++)
289 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
290 Sys_Error("Clump_FreeBlock: double free\n");
291 for (bit = startbit;bit < endbit;bit++)
292 clump->bits[bit>>5] &= ~(1<<(bit & 31));
293 clump->blocksinuse -= needbits;
294 memset(base, 0xFF, needbits * MEMUNIT);
295 // if all has been freed, free the clump itself
296 if (clump->blocksinuse == 0)
298 *clumpchainpointer = clump->chain;
299 if (developer_memorydebug.integer)
300 memset(clump, 0xFF, sizeof(*clump));
308 // does not belong to any known chunk... assume it was a direct allocation
311 memset(base, 0xFF, size);
316 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
318 unsigned int sentinel1;
319 unsigned int sentinel2;
330 _Mem_Free(olddata, filename, fileline);
334 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
336 Thread_LockMutex(mem_mutex);
337 if (developer_memory.integer)
338 Con_DPrintf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
339 //if (developer.integer > 0 && developer_memorydebug.integer)
340 // _Mem_CheckSentinelsGlobal(filename, fileline);
341 pool->totalsize += size;
342 realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
343 pool->realsize += realsize;
344 base = (unsigned char *)Clump_AllocBlock(realsize);
349 Mem_PrintList(1<<30);
351 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
353 // calculate address that aligns the end of the memheader_t to the specified alignment
354 mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
355 mem->baseaddress = (void*)base;
356 mem->filename = filename;
357 mem->fileline = fileline;
361 // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
362 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
363 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
364 mem->sentinel = sentinel1;
365 memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
367 // append to head of list
368 mem->next = pool->chain;
372 mem->next->prev = mem;
375 Thread_UnlockMutex(mem_mutex);
377 // copy the shared portion in the case of a realloc, then memset the rest
382 oldmem = (memheader_t*)olddata - 1;
383 sharedsize = min(oldmem->size, size);
384 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
385 remainsize -= sharedsize;
386 _Mem_Free(olddata, filename, fileline);
388 memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
389 return (void *)((unsigned char *) mem + sizeof(memheader_t));
392 // only used by _Mem_Free and _Mem_FreePool
393 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
398 unsigned int sentinel1;
399 unsigned int sentinel2;
401 // check sentinels (detects buffer overruns, in a way that is hard to exploit)
402 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
403 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
404 if (mem->sentinel != sentinel1)
405 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
406 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
407 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
410 if (developer_memory.integer)
411 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));
412 // unlink memheader from doubly linked list
413 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
414 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
416 Thread_LockMutex(mem_mutex);
418 mem->prev->next = mem->next;
420 pool->chain = mem->next;
422 mem->next->prev = mem->prev;
423 // memheader has been unlinked, do the actual free now
425 realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
426 pool->totalsize -= size;
427 pool->realsize -= realsize;
428 Clump_FreeBlock(mem->baseaddress, realsize);
430 Thread_UnlockMutex(mem_mutex);
433 void _Mem_Free(void *data, const char *filename, int fileline)
437 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
441 if (developer_memorydebug.integer)
443 //_Mem_CheckSentinelsGlobal(filename, fileline);
444 if (!Mem_IsAllocated(NULL, data))
445 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
448 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
451 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
454 if (developer_memorydebug.integer)
455 _Mem_CheckSentinelsGlobal(filename, fileline);
456 pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
461 Mem_PrintList(1<<30);
463 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
465 memset(pool, 0, sizeof(mempool_t));
466 pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
467 pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
468 pool->filename = filename;
469 pool->fileline = fileline;
473 pool->realsize = sizeof(mempool_t);
474 strlcpy (pool->name, name, sizeof (pool->name));
475 pool->parent = parent;
476 pool->next = poolchain;
481 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
483 mempool_t *pool = *poolpointer;
484 mempool_t **chainaddress, *iter, *temp;
486 if (developer_memorydebug.integer)
487 _Mem_CheckSentinelsGlobal(filename, fileline);
490 // unlink pool from chain
491 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
492 if (*chainaddress != pool)
493 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
494 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
495 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
496 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
497 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
498 *chainaddress = pool->next;
500 // free memory owned by the pool
502 _Mem_FreeBlock(pool->chain, filename, fileline);
504 // free child pools, too
505 for(iter = poolchain; iter; temp = iter = iter->next)
506 if(iter->parent == pool)
507 _Mem_FreePool(&temp, filename, fileline);
509 // free the pool itself
510 Clump_FreeBlock(pool, sizeof(*pool));
516 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
518 mempool_t *chainaddress;
520 if (developer_memorydebug.integer)
522 //_Mem_CheckSentinelsGlobal(filename, fileline);
523 // check if this pool is in the poolchain
524 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
525 if (chainaddress == pool)
528 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
531 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
532 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
533 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
534 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
535 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
537 // free memory owned by the pool
539 _Mem_FreeBlock(pool->chain, filename, fileline);
541 // empty child pools, too
542 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
543 if(chainaddress->parent == pool)
544 _Mem_EmptyPool(chainaddress, filename, fileline);
548 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
551 unsigned int sentinel1;
552 unsigned int sentinel2;
555 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
557 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
558 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
559 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
560 if (mem->sentinel != sentinel1)
561 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
562 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
563 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
567 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
569 // this isn't really very useful
570 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
571 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
572 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
573 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
577 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
584 for (pool = poolchain;pool;pool = pool->next)
586 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
587 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
588 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
589 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
591 for (pool = poolchain;pool;pool = pool->next)
592 for (mem = pool->chain;mem;mem = mem->next)
593 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
595 for (pool = poolchain;pool;pool = pool->next)
596 for (clump = clumpchain;clump;clump = clump->chain)
597 _Mem_CheckClumpSentinels(clump, filename, fileline);
601 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
608 // search only one pool
609 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
610 for( header = pool->chain ; header ; header = header->next )
611 if( header == target )
617 for (pool = poolchain;pool;pool = pool->next)
618 if (Mem_IsAllocated(pool, data))
624 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
626 memset(l, 0, sizeof(*l));
627 l->mempool = mempool;
628 l->recordsize = recordsize;
629 l->numrecordsperarray = numrecordsperarray;
632 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
637 for (i = 0;i != l->numarrays;i++)
638 Mem_Free(l->arrays[i].data);
641 memset(l, 0, sizeof(*l));
644 // VorteX: hacked Mem_ExpandableArray_AllocRecord, it does allocate record at certain index
645 void *Mem_ExpandableArray_AllocRecordAtIndex(memexpandablearray_t *l, size_t index)
648 if (index >= l->numarrays)
650 if (l->numarrays == l->maxarrays)
652 memexpandablearray_array_t *oldarrays = l->arrays;
653 l->maxarrays = max(l->maxarrays * 2, 128);
654 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
657 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
661 l->arrays[index].numflaggedrecords = 0;
662 l->arrays[index].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
663 l->arrays[index].allocflags = l->arrays[index].data + l->recordsize * l->numrecordsperarray;
666 if (l->arrays[index].numflaggedrecords < l->numrecordsperarray)
668 for (j = 0;j < l->numrecordsperarray;j++)
670 if (!l->arrays[index].allocflags[j])
672 l->arrays[index].allocflags[j] = true;
673 l->arrays[index].numflaggedrecords++;
674 memset(l->arrays[index].data + l->recordsize * j, 0, l->recordsize);
675 return (void *)(l->arrays[index].data + l->recordsize * j);
682 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
687 if (i == l->numarrays)
689 if (l->numarrays == l->maxarrays)
691 memexpandablearray_array_t *oldarrays = l->arrays;
692 l->maxarrays = max(l->maxarrays * 2, 128);
693 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
696 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
700 l->arrays[i].numflaggedrecords = 0;
701 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
702 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
705 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
707 for (j = 0;j < l->numrecordsperarray;j++)
709 if (!l->arrays[i].allocflags[j])
711 l->arrays[i].allocflags[j] = true;
712 l->arrays[i].numflaggedrecords++;
713 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
714 return (void *)(l->arrays[i].data + l->recordsize * j);
721 /*****************************************************************************
723 * If this function was to change the size of the "expandable" array, you have
724 * to update r_shadow.c
725 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
726 * function to look at. (And also seems like the only one?) You might have to
727 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
730 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
733 unsigned char *p = (unsigned char *)record;
734 for (i = 0;i != l->numarrays;i++)
736 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
738 j = (p - l->arrays[i].data) / l->recordsize;
739 if (p != l->arrays[i].data + j * l->recordsize)
740 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
741 if (!l->arrays[i].allocflags[j])
742 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
743 l->arrays[i].allocflags[j] = false;
744 l->arrays[i].numflaggedrecords--;
750 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
752 size_t i, j, k, end = 0;
753 for (i = 0;i < l->numarrays;i++)
755 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
757 if (l->arrays[i].allocflags[j])
759 end = l->numrecordsperarray * i + j + 1;
767 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
770 i = index / l->numrecordsperarray;
771 j = index % l->numrecordsperarray;
772 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
774 return (void *)(l->arrays[i].data + j * l->recordsize);
778 // used for temporary memory allocations around the engine, not for longterm
779 // storage, if anything in this pool stays allocated during gameplay, it is
781 mempool_t *tempmempool;
783 mempool_t *zonemempool;
785 void Mem_PrintStats(void)
787 size_t count = 0, size = 0, realsize = 0;
790 Mem_CheckSentinelsGlobal();
791 for (pool = poolchain;pool;pool = pool->next)
794 size += pool->totalsize;
795 realsize += pool->realsize;
797 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
798 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
799 for (pool = poolchain;pool;pool = pool->next)
801 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
803 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);
804 for (mem = pool->chain;mem;mem = mem->next)
805 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
810 void Mem_PrintList(size_t minallocationsize)
814 Mem_CheckSentinelsGlobal();
815 Con_Print("memory pool list:\n"
817 for (pool = poolchain;pool;pool = pool->next)
819 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" : "");
820 pool->lastchecksize = pool->totalsize;
821 for (mem = pool->chain;mem;mem = mem->next)
822 if (mem->size >= minallocationsize)
823 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
827 static void MemList_f(void)
832 Mem_PrintList(1<<30);
836 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
840 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
845 static void MemStats_f(void)
847 Mem_CheckSentinelsGlobal();
848 R_TextureStats_Print(false, false, true);
849 GL_Mesh_ListVBOs(false);
854 char* Mem_strdup (mempool_t *pool, const char* s)
861 p = (char*)Mem_Alloc (pool, sz);
867 ========================
869 ========================
871 void Memory_Init (void)
873 static union {unsigned short s;unsigned char b[2];} u;
875 mem_bigendian = u.b[0] != 0;
877 sentinel_seed = rand();
879 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
880 zonemempool = Mem_AllocPool("Zone", 0, NULL);
882 if (Thread_HasThreads())
883 mem_mutex = Thread_CreateMutex();
886 void Memory_Shutdown (void)
888 // Mem_FreePool (&zonemempool);
889 // Mem_FreePool (&tempmempool);
892 Thread_DestroyMutex(mem_mutex);
896 void Memory_Init_Commands (void)
898 Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
899 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)");
900 Cvar_RegisterVariable (&developer_memory);
901 Cvar_RegisterVariable (&developer_memorydebug);
902 Cvar_RegisterVariable (&sys_memsize_physical);
903 Cvar_RegisterVariable (&sys_memsize_virtual);
908 MEMORYSTATUSEX status;
910 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
912 status.dwLength = sizeof(status);
913 if(GlobalMemoryStatusEx(&status))
915 Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
916 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
923 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
925 status.dwLength = sizeof(status);
926 GlobalMemoryStatus(&status);
927 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
928 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
934 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
937 // Linux, and BSD with linprocfs mounted
938 FILE *f = fopen("/proc/meminfo", "r");
941 static char buf[1024];
942 while(fgets(buf, sizeof(buf), f))
945 if(!COM_ParseToken_Console(&p))
947 if(!strcmp(com_token, "MemTotal:"))
949 if(!COM_ParseToken_Console(&p))
951 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
953 if(!strcmp(com_token, "SwapTotal:"))
955 if(!COM_ParseToken_Console(&p))
957 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));