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.
24 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
25 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
27 mempool_t *poolchain = NULL;
29 void *_Mem_Alloc(mempool_t *pool, size_t size, const char *filename, int fileline)
32 int i, j, k, needed, endbit, largest;
33 memclump_t *clump, **clumpchainpointer;
39 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
40 if (developer.integer && developer_memory.integer)
41 Con_Printf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
42 if (developer.integer && developer_memorydebug.integer)
43 _Mem_CheckSentinelsGlobal(filename, fileline);
44 pool->totalsize += size;
49 needed = (sizeof(memheader_t) + size + sizeof(int) + (MEMUNIT - 1)) / MEMUNIT;
50 endbit = MEMBITS - needed;
51 for (clumpchainpointer = &pool->clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
53 clump = *clumpchainpointer;
54 if (clump->sentinel1 != MEMCLUMP_SENTINEL)
55 Sys_Error("Mem_Alloc: trashed clump sentinel 1 (alloc at %s:%d)", filename, fileline);
56 if (clump->sentinel2 != MEMCLUMP_SENTINEL)
57 Sys_Error("Mem_Alloc: trashed clump sentinel 2 (alloc at %s:%d)", filename, fileline);
58 if (clump->largestavailable >= needed)
61 for (i = 0;i < endbit;i++)
63 if (clump->bits[i >> 5] & (1 << (i & 31)))
67 if (clump->bits[i >> 5] & (1 << (i & 31)))
74 // since clump falsely advertised enough space (nothing wrong
75 // with that), update largest count to avoid wasting time in
77 clump->largestavailable = largest;
80 pool->realsize += sizeof(memclump_t);
81 clump = malloc(sizeof(memclump_t));
83 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
84 memset(clump, 0, sizeof(memclump_t));
85 *clumpchainpointer = clump;
86 clump->sentinel1 = MEMCLUMP_SENTINEL;
87 clump->sentinel2 = MEMCLUMP_SENTINEL;
89 clump->blocksinuse = 0;
90 clump->largestavailable = MEMBITS - needed;
93 mem = (memheader_t *)((unsigned char *) clump->block + j * MEMUNIT);
95 clump->blocksinuse += needed;
96 for (i = j + needed;j < i;j++)
97 clump->bits[j >> 5] |= (1 << (j & 31));
101 // big allocations are not clumped
103 pool->realsize += sizeof(memheader_t) + size + sizeof(int);
104 mem = (memheader_t *)malloc(sizeof(memheader_t) + size + sizeof(int));
106 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
111 mem->filename = filename;
112 mem->fileline = fileline;
115 mem->sentinel1 = MEMHEADER_SENTINEL1;
116 // we have to use only a single byte for this sentinel, because it may not be aligned, and some platforms can't use unaligned accesses
117 *((unsigned char *) mem + sizeof(memheader_t) + mem->size) = MEMHEADER_SENTINEL2;
118 // append to head of list
119 mem->next = pool->chain;
123 mem->next->prev = mem;
124 memset((void *)((unsigned char *) mem + sizeof(memheader_t)), 0, mem->size);
125 return (void *)((unsigned char *) mem + sizeof(memheader_t));
128 // only used by _Mem_Free and _Mem_FreePool
129 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
132 int i, firstblock, endblock;
133 memclump_t *clump, **clumpchainpointer;
136 if (mem->sentinel1 != MEMHEADER_SENTINEL1)
137 Sys_Error("Mem_Free: trashed header sentinel 1 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
138 if (*((unsigned char *) mem + sizeof(memheader_t) + mem->size) != MEMHEADER_SENTINEL2)
139 Sys_Error("Mem_Free: trashed header sentinel 2 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
141 if (developer.integer && developer_memory.integer)
142 Con_Printf("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));
143 // unlink memheader from doubly linked list
144 if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
145 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
147 mem->prev->next = mem->next;
149 pool->chain = mem->next;
151 mem->next->prev = mem->prev;
152 // memheader has been unlinked, do the actual free now
153 pool->totalsize -= mem->size;
155 if ((clump = mem->clump))
157 if (clump->sentinel1 != MEMCLUMP_SENTINEL)
158 Sys_Error("Mem_Free: trashed clump sentinel 1 (free at %s:%i)", filename, fileline);
159 if (clump->sentinel2 != MEMCLUMP_SENTINEL)
160 Sys_Error("Mem_Free: trashed clump sentinel 2 (free at %s:%i)", filename, fileline);
161 firstblock = ((unsigned char *) mem - (unsigned char *) clump->block);
162 if (firstblock & (MEMUNIT - 1))
163 Sys_Error("Mem_Free: address not valid in clump (free at %s:%i)", filename, fileline);
164 firstblock /= MEMUNIT;
165 endblock = firstblock + ((sizeof(memheader_t) + mem->size + sizeof(int) + (MEMUNIT - 1)) / MEMUNIT);
166 clump->blocksinuse -= endblock - firstblock;
167 // could use &, but we know the bit is set
168 for (i = firstblock;i < endblock;i++)
169 clump->bits[i >> 5] -= (1 << (i & 31));
170 if (clump->blocksinuse <= 0)
173 for (clumpchainpointer = &pool->clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
175 if (*clumpchainpointer == clump)
177 *clumpchainpointer = clump->chain;
181 pool->realsize -= sizeof(memclump_t);
182 memset(clump, 0xBF, sizeof(memclump_t));
187 // clump still has some allocations
188 // force re-check of largest available space on next alloc
189 clump->largestavailable = MEMBITS - clump->blocksinuse;
195 pool->realsize -= sizeof(memheader_t) + mem->size + sizeof(int);
196 if (developer_memorydebug.integer)
197 memset(mem, 0xBF, sizeof(memheader_t) + mem->size + sizeof(int));
204 void _Mem_Free(void *data, const char *filename, int fileline)
208 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)", filename, fileline);
212 if (developer.integer && developer_memorydebug.integer)
214 _Mem_CheckSentinelsGlobal(filename, fileline);
215 if (!Mem_IsAllocated(NULL, data))
216 Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
219 _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
222 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
225 if (developer.integer && developer_memorydebug.integer)
226 _Mem_CheckSentinelsGlobal(filename, fileline);
227 pool = (mempool_t *)malloc(sizeof(mempool_t));
229 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
230 memset(pool, 0, sizeof(mempool_t));
231 pool->sentinel1 = MEMHEADER_SENTINEL1;
232 pool->sentinel2 = MEMHEADER_SENTINEL1;
233 pool->filename = filename;
234 pool->fileline = fileline;
238 pool->realsize = sizeof(mempool_t);
239 strlcpy (pool->name, name, sizeof (pool->name));
240 pool->parent = parent;
241 pool->next = poolchain;
246 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
248 mempool_t *pool = *poolpointer;
249 mempool_t **chainaddress, *iter, *temp;
251 if (developer.integer && developer_memorydebug.integer)
252 _Mem_CheckSentinelsGlobal(filename, fileline);
255 // unlink pool from chain
256 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
257 if (*chainaddress != pool)
258 Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
259 if (pool->sentinel1 != MEMHEADER_SENTINEL1)
260 Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
261 if (pool->sentinel2 != MEMHEADER_SENTINEL1)
262 Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
263 *chainaddress = pool->next;
265 // free memory owned by the pool
267 _Mem_FreeBlock(pool->chain, filename, fileline);
269 // free child pools, too
270 for(iter = poolchain; iter; temp = iter = iter->next)
271 if(iter->parent == pool)
272 _Mem_FreePool(&temp, filename, fileline);
274 // free the pool itself
275 memset(pool, 0xBF, sizeof(mempool_t));
282 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
284 mempool_t *chainaddress;
286 if (developer.integer && developer_memorydebug.integer)
288 _Mem_CheckSentinelsGlobal(filename, fileline);
289 // check if this pool is in the poolchain
290 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
291 if (chainaddress == pool)
294 Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
297 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
298 if (pool->sentinel1 != MEMHEADER_SENTINEL1)
299 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
300 if (pool->sentinel2 != MEMHEADER_SENTINEL1)
301 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
303 // free memory owned by the pool
305 _Mem_FreeBlock(pool->chain, filename, fileline);
307 // empty child pools, too
308 for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
309 if(chainaddress->parent == pool)
310 _Mem_EmptyPool(chainaddress, filename, fileline);
314 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
319 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
321 mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
322 if (mem->sentinel1 != MEMHEADER_SENTINEL1)
323 Sys_Error("Mem_CheckSentinels: trashed header sentinel 1 (block allocated at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
324 if (*((unsigned char *) mem + sizeof(memheader_t) + mem->size) != MEMHEADER_SENTINEL2)
325 Sys_Error("Mem_CheckSentinels: trashed header sentinel 2 (block allocated at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
329 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
331 // this isn't really very useful
332 if (clump->sentinel1 != MEMCLUMP_SENTINEL)
333 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
334 if (clump->sentinel2 != MEMCLUMP_SENTINEL)
335 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
339 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
346 for (pool = poolchain;pool;pool = pool->next)
348 if (pool->sentinel1 != MEMHEADER_SENTINEL1)
349 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
350 if (pool->sentinel2 != MEMHEADER_SENTINEL1)
351 Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
353 for (pool = poolchain;pool;pool = pool->next)
354 for (mem = pool->chain;mem;mem = mem->next)
355 _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
357 for (pool = poolchain;pool;pool = pool->next)
358 for (clump = pool->clumpchain;clump;clump = clump->chain)
359 _Mem_CheckClumpSentinels(clump, filename, fileline);
363 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
370 // search only one pool
371 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
372 for( header = pool->chain ; header ; header = header->next )
373 if( header == target )
379 for (pool = poolchain;pool;pool = pool->next)
380 if (Mem_IsAllocated(pool, data))
386 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
388 memset(l, 0, sizeof(*l));
389 l->mempool = mempool;
390 l->recordsize = recordsize;
391 l->numrecordsperarray = numrecordsperarray;
394 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
399 for (i = 0;i != l->numarrays;i++)
400 Mem_Free(l->arrays[i].data);
403 memset(l, 0, sizeof(*l));
406 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
411 if (i == l->numarrays)
413 if (l->numarrays == l->maxarrays)
415 memexpandablearray_array_t *oldarrays = l->arrays;
416 l->maxarrays = max(l->maxarrays * 2, 128);
417 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
420 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
424 l->arrays[i].numflaggedrecords = 0;
425 l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
426 l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
429 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
431 for (j = 0;j < l->numrecordsperarray;j++)
433 if (!l->arrays[i].allocflags[j])
435 l->arrays[i].allocflags[j] = true;
436 l->arrays[i].numflaggedrecords++;
437 memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
438 return (void *)(l->arrays[i].data + l->recordsize * j);
445 /*****************************************************************************
447 * If this function was to change the size of the "expandable" array, you have
448 * to update r_shadow.c
449 * Just do a search for "range =", R_ShadowClearWorldLights would be the first
450 * function to look at. (And also seems like the only one?) You might have to
451 * move the call to Mem_ExpandableArray_IndexRange back into for(...) loop's
454 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
457 unsigned char *p = (unsigned char *)record;
458 for (i = 0;i != l->numarrays;i++)
460 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
462 j = (p - l->arrays[i].data) / l->recordsize;
463 if (p != l->arrays[i].data + j * l->recordsize)
464 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
465 if (!l->arrays[i].allocflags[j])
466 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
467 l->arrays[i].allocflags[j] = false;
468 l->arrays[i].numflaggedrecords--;
474 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
476 size_t i, j, k, end = 0;
477 for (i = 0;i < l->numarrays;i++)
479 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
481 if (l->arrays[i].allocflags[j])
483 end = l->numrecordsperarray * i + j + 1;
491 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
494 i = index / l->numrecordsperarray;
495 j = index % l->numrecordsperarray;
496 if (i >= l->numarrays || !l->arrays[i].allocflags[j])
498 return (void *)(l->arrays[i].data + j * l->recordsize);
502 // used for temporary memory allocations around the engine, not for longterm
503 // storage, if anything in this pool stays allocated during gameplay, it is
505 mempool_t *tempmempool;
507 mempool_t *zonemempool;
509 void Mem_PrintStats(void)
511 size_t count = 0, size = 0, realsize = 0;
514 Mem_CheckSentinelsGlobal();
515 for (pool = poolchain;pool;pool = pool->next)
518 size += pool->totalsize;
519 realsize += pool->realsize;
521 Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
522 Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
523 for (pool = poolchain;pool;pool = pool->next)
525 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
527 Con_Printf("Memory pool %p has sprung a leak totalling %lu bytes (%.3fMB)! Listing contents...\n", pool, (unsigned long)pool->totalsize, pool->totalsize / 1048576.0);
528 for (mem = pool->chain;mem;mem = mem->next)
529 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
534 void Mem_PrintList(size_t minallocationsize)
538 Mem_CheckSentinelsGlobal();
539 Con_Print("memory pool list:\n"
541 for (pool = poolchain;pool;pool = pool->next)
543 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" : "");
544 pool->lastchecksize = pool->totalsize;
545 for (mem = pool->chain;mem;mem = mem->next)
546 if (mem->size >= minallocationsize)
547 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
556 Mem_PrintList(1<<30);
560 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
564 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
569 extern void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal);
570 void MemStats_f(void)
572 Mem_CheckSentinelsGlobal();
573 R_TextureStats_Print(false, false, true);
574 GL_Mesh_ListVBOs(false);
579 char* Mem_strdup (mempool_t *pool, const char* s)
582 size_t sz = strlen (s) + 1;
583 if (s == NULL) return NULL;
584 p = (char*)Mem_Alloc (pool, sz);
590 ========================
592 ========================
594 void Memory_Init (void)
597 tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
598 zonemempool = Mem_AllocPool("Zone", 0, NULL);
601 void Memory_Shutdown (void)
603 // Mem_FreePool (&zonemempool);
604 // Mem_FreePool (&tempmempool);
607 void Memory_Init_Commands (void)
609 Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
610 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)");
611 Cvar_RegisterVariable (&developer_memory);
612 Cvar_RegisterVariable (&developer_memorydebug);