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.
36 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
37 unsigned int sentinel_seed;
39 qboolean mem_bigendian = false;
41 // LordHavoc: enables our own low-level allocator (instead of malloc)
43 #define MEMCLUMPING_FREECLUMPS 0
46 // smallest unit we care about is this many bytes
48 // try to do 32MB clumps, but overhead eats into this
49 #define MEMWANTCLUMPSIZE (1<<27)
50 // give malloc padding so we can't waste most of a page at the end
51 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
52 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
53 #define MEMBITINTS (MEMBITS / 32)
55 typedef struct memclump_s
57 // contents of the clump
58 unsigned char block[MEMCLUMPSIZE];
59 // should always be MEMCLUMP_SENTINEL
60 unsigned int sentinel1;
61 // if a bit is on, it means that the MEMUNIT bytes it represents are
62 // allocated, otherwise free
63 unsigned int bits[MEMBITINTS];
64 // should always be MEMCLUMP_SENTINEL
65 unsigned int sentinel2;
66 // if this drops to 0, the clump is freed
68 // largest block of memory available (this is reset to an optimistic
69 // number when anything is freed, and updated when alloc fails the clump)
70 size_t largestavailable;
71 // next clump in the chain
72 struct memclump_s *chain;
77 static memclump_t masterclump;
79 static memclump_t *clumpchain = NULL;
83 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
84 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
85 cvar_t sys_memsize_physical = {CVAR_READONLY, "sys_memsize_physical", "", "physical memory size in MB (or empty if unknown)"};
86 cvar_t sys_memsize_virtual = {CVAR_READONLY, "sys_memsize_virtual", "", "virtual memory size in MB (or empty if unknown)"};
88 static mempool_t *poolchain = NULL;
90 void Mem_PrintStats(void);
91 void Mem_PrintList(size_t minallocationsize);
94 // some platforms have a malloc that returns NULL but succeeds later
95 // (Windows growing its swapfile for example)
96 static void *attempt_malloc(size_t size)
99 // try for half a second or so
100 unsigned int attempts = 500;
103 base = (void *)malloc(size);
113 static memclump_t *Clump_NewClump(void)
115 memclump_t **clumpchainpointer;
120 clump = &masterclump;
122 clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
128 if (developer_memorydebug.integer)
129 memset(clump, 0xEF, sizeof(*clump));
130 clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
131 memset(clump->bits, 0, sizeof(clump->bits));
132 clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
133 clump->blocksinuse = 0;
134 clump->largestavailable = 0;
137 // link clump into chain
138 for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
140 *clumpchainpointer = clump;
146 // low level clumping functions, all other memory functions use these
147 static void *Clump_AllocBlock(size_t size)
151 if (size <= MEMCLUMPSIZE)
155 unsigned int needbits;
156 unsigned int startbit;
158 unsigned int needints;
164 memclump_t **clumpchainpointer;
166 needbits = (size + MEMUNIT - 1) / MEMUNIT;
167 needints = (needbits+31)>>5;
168 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
170 clump = *clumpchainpointer;
173 clump = Clump_NewClump();
177 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
178 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
179 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
180 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
182 endbit = startbit + needbits;
184 // do as fast a search as possible, even if it means crude alignment
187 // large allocations are aligned to large boundaries
188 // furthermore, they are allocated downward from the top...
189 endindex = MEMBITINTS;
190 startindex = endindex - needints;
192 while (--index >= startindex)
197 startindex = endindex - needints;
202 startbit = startindex*32;
207 // search for a multi-bit gap in a single int
208 // (not dealing with the cases that cross two ints)
209 mask = (1<<needbits)-1;
210 endbit = 32-needbits;
212 for (index = 0;index < MEMBITINTS;index++)
214 value = array[index];
215 if (value != 0xFFFFFFFFu)
217 // there may be room in this one...
218 for (bit = 0;bit < endbit;bit++)
220 if (!(value & (mask<<bit)))
222 startbit = index*32+bit;
231 endbit = startbit + needbits;
232 // mark this range as used
234 for (bit = startbit;bit < endbit;bit++)
235 if (clump->bits[bit>>5] & (1<<(bit & 31)))
236 Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
237 for (bit = startbit;bit < endbit;bit++)
238 clump->bits[bit>>5] |= (1<<(bit & 31));
239 clump->blocksinuse += needbits;
240 base = clump->block + startbit * MEMUNIT;
241 if (developer_memorydebug.integer)
242 memset(base, 0xBF, needbits * MEMUNIT);
250 // too big, allocate it directly
255 base = (unsigned char *)attempt_malloc(size);
256 if (base && developer_memorydebug.integer)
257 memset(base, 0xAF, size);
261 static void Clump_FreeBlock(void *base, size_t size)
264 unsigned int needbits;
265 unsigned int startbit;
268 memclump_t **clumpchainpointer;
270 unsigned char *start = (unsigned char *)base;
271 for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
273 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
275 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
276 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
277 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
278 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
279 if (start + size > clump->block + MEMCLUMPSIZE)
280 Sys_Error("Clump_FreeBlock: block overrun\n");
281 // the block belongs to this clump, clear the range
282 needbits = (size + MEMUNIT - 1) / MEMUNIT;
283 startbit = (start - clump->block) / MEMUNIT;
284 endbit = startbit + needbits;
285 // first verify all bits are set, otherwise this may be misaligned or a double free
286 for (bit = startbit;bit < endbit;bit++)
287 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
288 Sys_Error("Clump_FreeBlock: double free\n");
289 for (bit = startbit;bit < endbit;bit++)
290 clump->bits[bit>>5] &= ~(1<<(bit & 31));
291 clump->blocksinuse -= needbits;
292 memset(base, 0xFF, needbits * MEMUNIT);
293 // if all has been freed, free the clump itself
294 if (clump->blocksinuse == 0)
296 *clumpchainpointer = clump->chain;
297 if (developer_memorydebug.integer)
298 memset(clump, 0xFF, sizeof(*clump));
306 // does not belong to any known chunk... assume it was a direct allocation
309 memset(base, 0xFF, size);
314 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
316 unsigned int sentinel1;
317 unsigned int sentinel2;
328 _Mem_Free(olddata, filename, fileline);
332 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
333 if (developer_memory.integer)
334 Con_DPrintf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
335 //if (developer.integer > 0 && developer_memorydebug.integer)
336 // _Mem_CheckSentinelsGlobal(filename, fileline);
337 pool->totalsize += size;
338 realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
339 pool->realsize += realsize;
340 base = (unsigned char *)Clump_AllocBlock(realsize);
345 Mem_PrintList(1<<30);
347 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
349 // calculate address that aligns the end of the memheader_t to the specified alignment
350 mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
351 mem->baseaddress = (void*)base;
352 mem->filename = filename;
353 mem->fileline = fileline;
357 // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
358 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
359 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
360 mem->sentinel = sentinel1;
361 memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
363 // append to head of list
364 mem->next = pool->chain;
368 mem->next->prev = mem;
370 // copy the shared portion in the case of a realloc, then memset the rest
375 oldmem = (memheader_t*)olddata - 1;
376 sharedsize = min(oldmem->size, size);
377 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
378 remainsize -= sharedsize;
379 _Mem_Free(olddata, filename, fileline);
381 memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
382 return (void *)((unsigned char *) mem + sizeof(memheader_t));
385 // only used by _Mem_Free and _Mem_FreePool
386 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
391 unsigned int sentinel1;
392 unsigned int sentinel2;
394 // check sentinels (detects buffer overruns, in a way that is hard to exploit)
395 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
396 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
397 if (mem->sentinel != sentinel1)
398 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
399 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
400 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
403 if (developer_memory.integer)
404 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));
405 // unlink memheader from doubly linked list
406 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
407 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
409 mem->prev->next = mem->next;
411 pool->chain = mem->next;
413 mem->next->prev = mem->prev;
414 // memheader has been unlinked, do the actual free now
416 realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
417 pool->totalsize -= size;
418 pool->realsize -= realsize;
419 Clump_FreeBlock(mem->baseaddress, realsize);
422 void _Mem_Free(void *data, const char *filename, int fileline)
426 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
430 if (developer_memorydebug.integer)
432 //_Mem_CheckSentinelsGlobal(filename, fileline);
433 if (!Mem_IsAllocated(NULL, data))
434 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
437 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
440 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
443 if (developer_memorydebug.integer)
444 _Mem_CheckSentinelsGlobal(filename, fileline);
445 pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
450 Mem_PrintList(1<<30);
452 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
454 memset(pool, 0, sizeof(mempool_t));
455 pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
456 pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
457 pool->filename = filename;
458 pool->fileline = fileline;
462 pool->realsize = sizeof(mempool_t);
463 strlcpy (pool->name, name, sizeof (pool->name));
464 pool->parent = parent;
465 pool->next = poolchain;
470 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
472 mempool_t *pool = *poolpointer;
473 mempool_t **chainaddress, *iter, *temp;
475 if (developer_memorydebug.integer)
476 _Mem_CheckSentinelsGlobal(filename, fileline);
479 // unlink pool from chain
480 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
481 if (*chainaddress != pool)
482 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
483 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
484 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
485 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
486 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
487 *chainaddress = pool->next;
489 // free memory owned by the pool
491 _Mem_FreeBlock(pool->chain, filename, fileline);
493 // free child pools, too
494 for(iter = poolchain; iter; temp = iter = iter->next)
495 if(iter->parent == pool)
496 _Mem_FreePool(&temp, filename, fileline);
498 // free the pool itself
499 Clump_FreeBlock(pool, sizeof(*pool));
505 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
507 mempool_t *chainaddress;
509 if (developer_memorydebug.integer)
511 //_Mem_CheckSentinelsGlobal(filename, fileline);
512 // check if this pool is in the poolchain
513 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
514 if (chainaddress == pool)
517 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
520 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
521 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
522 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
523 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
524 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
526 // free memory owned by the pool
528 _Mem_FreeBlock(pool->chain, filename, fileline);
530 // empty child pools, too
531 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
532 if(chainaddress->parent == pool)
533 _Mem_EmptyPool(chainaddress, filename, fileline);
537 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
540 unsigned int sentinel1;
541 unsigned int sentinel2;
544 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
546 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
547 sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
548 sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
549 if (mem->sentinel != sentinel1)
550 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
551 if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
552 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
556 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
558 // this isn't really very useful
559 if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
560 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
561 if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
562 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
566 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
573 for (pool = poolchain;pool;pool = pool->next)
575 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
576 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
577 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
578 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
580 for (pool = poolchain;pool;pool = pool->next)
581 for (mem = pool->chain;mem;mem = mem->next)
582 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
584 for (pool = poolchain;pool;pool = pool->next)
585 for (clump = clumpchain;clump;clump = clump->chain)
586 _Mem_CheckClumpSentinels(clump, filename, fileline);
590 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
597 // search only one pool
598 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
599 for( header = pool->chain ; header ; header = header->next )
600 if( header == target )
606 for (pool = poolchain;pool;pool = pool->next)
607 if (Mem_IsAllocated(pool, data))
613 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
615 memset(l, 0, sizeof(*l));
616 l->mempool = mempool;
617 l->recordsize = recordsize;
618 l->numrecordsperarray = numrecordsperarray;
621 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
626 for (i = 0;i != l->numarrays;i++)
627 Mem_Free(l->arrays[i].data);
630 memset(l, 0, sizeof(*l));
633 // VorteX: hacked Mem_ExpandableArray_AllocRecord, it does allocate record at certain index
634 void *Mem_ExpandableArray_AllocRecordAtIndex(memexpandablearray_t *l, size_t index)
637 if (index == l->numarrays)
639 if (l->numarrays == l->maxarrays)
641 memexpandablearray_array_t *oldarrays = l->arrays;
642 l->maxarrays = max(l->maxarrays * 2, 128);
643 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
646 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
650 l->arrays[index].numflaggedrecords = 0;
651 l->arrays[index].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
652 l->arrays[index].allocflags = l->arrays[index].data + l->recordsize * l->numrecordsperarray;
655 if (l->arrays[index].numflaggedrecords < l->numrecordsperarray)
657 for (j = 0;j < l->numrecordsperarray;j++)
659 if (!l->arrays[index].allocflags[j])
661 l->arrays[index].allocflags[j] = true;
662 l->arrays[index].numflaggedrecords++;
663 memset(l->arrays[index].data + l->recordsize * j, 0, l->recordsize);
664 return (void *)(l->arrays[index].data + l->recordsize * j);
671 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
676 if (i == l->numarrays)
678 if (l->numarrays == l->maxarrays)
680 memexpandablearray_array_t *oldarrays = l->arrays;
681 l->maxarrays = max(l->maxarrays * 2, 128);
682 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
685 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
689 l->arrays[i].numflaggedrecords = 0;
690 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
691 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
694 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
696 for (j = 0;j < l->numrecordsperarray;j++)
698 if (!l->arrays[i].allocflags[j])
700 l->arrays[i].allocflags[j] = true;
701 l->arrays[i].numflaggedrecords++;
702 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
703 return (void *)(l->arrays[i].data + l->recordsize * j);
710 /*****************************************************************************
712 * If this function was to change the size of the "expandable" array, you have
713 * to update r_shadow.c
714 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
715 * function to look at. (And also seems like the only one?) You might have to
716 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
719 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
722 unsigned char *p = (unsigned char *)record;
723 for (i = 0;i != l->numarrays;i++)
725 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
727 j = (p - l->arrays[i].data) / l->recordsize;
728 if (p != l->arrays[i].data + j * l->recordsize)
729 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
730 if (!l->arrays[i].allocflags[j])
731 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
732 l->arrays[i].allocflags[j] = false;
733 l->arrays[i].numflaggedrecords--;
739 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
741 size_t i, j, k, end = 0;
742 for (i = 0;i < l->numarrays;i++)
744 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
746 if (l->arrays[i].allocflags[j])
748 end = l->numrecordsperarray * i + j + 1;
756 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
759 i = index / l->numrecordsperarray;
760 j = index % l->numrecordsperarray;
761 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
763 return (void *)(l->arrays[i].data + j * l->recordsize);
767 // used for temporary memory allocations around the engine, not for longterm
768 // storage, if anything in this pool stays allocated during gameplay, it is
770 mempool_t *tempmempool;
772 mempool_t *zonemempool;
774 void Mem_PrintStats(void)
776 size_t count = 0, size = 0, realsize = 0;
779 Mem_CheckSentinelsGlobal();
780 for (pool = poolchain;pool;pool = pool->next)
783 size += pool->totalsize;
784 realsize += pool->realsize;
786 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
787 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
788 for (pool = poolchain;pool;pool = pool->next)
790 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
792 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);
793 for (mem = pool->chain;mem;mem = mem->next)
794 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
799 void Mem_PrintList(size_t minallocationsize)
803 Mem_CheckSentinelsGlobal();
804 Con_Print("memory pool list:\n"
806 for (pool = poolchain;pool;pool = pool->next)
808 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" : "");
809 pool->lastchecksize = pool->totalsize;
810 for (mem = pool->chain;mem;mem = mem->next)
811 if (mem->size >= minallocationsize)
812 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
821 Mem_PrintList(1<<30);
825 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
829 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
834 extern void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal);
835 void MemStats_f(void)
837 Mem_CheckSentinelsGlobal();
838 R_TextureStats_Print(false, false, true);
839 GL_Mesh_ListVBOs(false);
844 char* Mem_strdup (mempool_t *pool, const char* s)
847 size_t sz = strlen (s) + 1;
848 if (s == NULL) return NULL;
849 p = (char*)Mem_Alloc (pool, sz);
855 ========================
857 ========================
859 void Memory_Init (void)
861 static union {unsigned short s;unsigned char b[2];} u;
863 mem_bigendian = u.b[0];
865 sentinel_seed = rand();
867 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
868 zonemempool = Mem_AllocPool("Zone", 0, NULL);
871 void Memory_Shutdown (void)
873 // Mem_FreePool (&zonemempool);
874 // Mem_FreePool (&tempmempool);
877 void Memory_Init_Commands (void)
879 Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
880 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)");
881 Cvar_RegisterVariable (&developer_memory);
882 Cvar_RegisterVariable (&developer_memorydebug);
883 Cvar_RegisterVariable (&sys_memsize_physical);
884 Cvar_RegisterVariable (&sys_memsize_virtual);
889 MEMORYSTATUSEX status;
891 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
893 status.dwLength = sizeof(status);
894 if(GlobalMemoryStatusEx(&status))
896 Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
897 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
904 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
906 status.dwLength = sizeof(status);
907 GlobalMemoryStatus(&status);
908 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
909 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
915 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
918 // Linux, and BSD with linprocfs mounted
919 FILE *f = fopen("/proc/meminfo", "r");
922 static char buf[1024];
923 while(fgets(buf, sizeof(buf), f))
926 if(!COM_ParseToken_Console(&p))
928 if(!strcmp(com_token, "MemTotal:"))
930 if(!COM_ParseToken_Console(&p))
932 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
934 if(!strcmp(com_token, "SwapTotal:"))
936 if(!COM_ParseToken_Console(&p))
938 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));