]> icculus.org git repositories - divverent/darkplaces.git/blob - zone.c
added R_FrameData_Alloc and Store functions (a per-frame heap allocator
[divverent/darkplaces.git] / zone.c
1 /*
2 Copyright (C) 1996-1997 Id Software, Inc.
3
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.
8
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.
12
13 See the GNU General Public License for more details.
14
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.
18
19 */
20 // Z_zone.c
21
22 #include "quakedef.h"
23
24 #ifdef WIN32
25 #include <windows.h>
26 #else
27 #include <unistd.h>
28 #endif
29
30 #ifdef _MSC_VER
31 #include <vadefs.h>
32 #else
33 #include <stdint.h>
34 #endif
35 #define MEMHEADER_SENTINEL_FOR_ADDRESS(p) ((sentinel_seed ^ (unsigned int) (uintptr_t) (p)) + sentinel_seed)
36 unsigned int sentinel_seed;
37
38 // LordHavoc: enables our own low-level allocator (instead of malloc)
39 #define MEMCLUMPING 0
40 #define MEMCLUMPING_FREECLUMPS 0
41
42 #if MEMCLUMPING
43 // smallest unit we care about is this many bytes
44 #define MEMUNIT 128
45 // try to do 32MB clumps, but overhead eats into this
46 #define MEMWANTCLUMPSIZE (1<<29)
47 // give malloc padding so we can't waste most of a page at the end
48 #define MEMCLUMPSIZE (MEMWANTCLUMPSIZE - MEMWANTCLUMPSIZE/MEMUNIT/32 - 128)
49 #define MEMBITS (MEMCLUMPSIZE / MEMUNIT)
50 #define MEMBITINTS (MEMBITS / 32)
51
52 typedef struct memclump_s
53 {
54         // contents of the clump
55         unsigned char block[MEMCLUMPSIZE];
56         // should always be MEMCLUMP_SENTINEL
57         unsigned int sentinel1;
58         // if a bit is on, it means that the MEMUNIT bytes it represents are
59         // allocated, otherwise free
60         unsigned int bits[MEMBITINTS];
61         // should always be MEMCLUMP_SENTINEL
62         unsigned int sentinel2;
63         // if this drops to 0, the clump is freed
64         size_t blocksinuse;
65         // largest block of memory available (this is reset to an optimistic
66         // number when anything is freed, and updated when alloc fails the clump)
67         size_t largestavailable;
68         // next clump in the chain
69         struct memclump_s *chain;
70 }
71 memclump_t;
72
73 #if MEMCLUMPING == 2
74 static memclump_t masterclump;
75 #endif
76 static memclump_t *clumpchain = NULL;
77 #endif
78
79
80 cvar_t developer_memory = {0, "developer_memory", "0", "prints debugging information about memory allocations"};
81 cvar_t developer_memorydebug = {0, "developer_memorydebug", "0", "enables memory corruption checks (very slow)"};
82
83 static mempool_t *poolchain = NULL;
84
85 #if MEMCLUMPING != 2
86 // some platforms have a malloc that returns NULL but succeeds later
87 // (Windows growing its swapfile for example)
88 static void *attempt_malloc(size_t size)
89 {
90         void *base;
91         // try for half a second or so
92         unsigned int attempts = 500;
93         while (attempts--)
94         {
95                 base = (void *)malloc(size);
96                 if (base)
97                         return base;
98                 Sys_Sleep(1000);
99         }
100         return NULL;
101 }
102 #endif
103
104 #if MEMCLUMPING
105 static memclump_t *Clump_NewClump(void)
106 {
107         memclump_t **clumpchainpointer;
108         memclump_t *clump;
109 #if MEMCLUMPING == 2
110         if (clumpchain)
111                 return NULL;
112         clump = &masterclump;
113 #else
114         clump = (memclump_t*)attempt_malloc(sizeof(memclump_t));
115         if (!clump)
116                 return NULL;
117 #endif
118
119         // initialize clump
120         if (developer_memorydebug.integer)
121                 memset(clump, 0xEF, sizeof(*clump));
122         clump->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1);
123         memset(clump->bits, 0, sizeof(clump->bits));
124         clump->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2);
125         clump->blocksinuse = 0;
126         clump->largestavailable = 0;
127         clump->chain = NULL;
128
129         // link clump into chain
130         for (clumpchainpointer = &clumpchain;*clumpchainpointer;clumpchainpointer = &(*clumpchainpointer)->chain)
131                 ;
132         *clumpchainpointer = clump;
133
134         return clump;
135 }
136 #endif
137
138 // low level clumping functions, all other memory functions use these
139 static void *Clump_AllocBlock(size_t size)
140 {
141         unsigned char *base;
142 #if MEMCLUMPING
143         if (size <= MEMCLUMPSIZE)
144         {
145                 int index;
146                 unsigned int bit;
147                 unsigned int needbits;
148                 unsigned int startbit;
149                 unsigned int endbit;
150                 unsigned int needints;
151                 int startindex;
152                 int endindex;
153                 unsigned int value;
154                 unsigned int mask;
155                 unsigned int *array;
156                 memclump_t **clumpchainpointer;
157                 memclump_t *clump;
158                 needbits = (size + MEMUNIT - 1) / MEMUNIT;
159                 needints = (needbits+31)>>5;
160                 for (clumpchainpointer = &clumpchain;;clumpchainpointer = &(*clumpchainpointer)->chain)
161                 {
162                         clump = *clumpchainpointer;
163                         if (!clump)
164                         {
165                                 clump = Clump_NewClump();
166                                 if (!clump)
167                                         return NULL;
168                         }
169                         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
170                                 Sys_Error("Clump_AllocBlock: trashed sentinel1\n");
171                         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
172                                 Sys_Error("Clump_AllocBlock: trashed sentinel2\n");
173                         startbit = 0;
174                         endbit = startbit + needbits;
175                         array = clump->bits;
176                         // do as fast a search as possible, even if it means crude alignment
177                         if (needbits >= 32)
178                         {
179                                 // large allocations are aligned to large boundaries
180                                 // furthermore, they are allocated downward from the top...
181                                 endindex = MEMBITINTS;
182                                 startindex = endindex - needints;
183                                 index = endindex;
184                                 while (--index >= startindex)
185                                 {
186                                         if (array[index])
187                                         {
188                                                 endindex = index;
189                                                 startindex = endindex - needints;
190                                                 if (startindex < 0)
191                                                         goto nofreeblock;
192                                         }
193                                 }
194                                 startbit = startindex*32;
195                                 goto foundblock;
196                         }
197                         else
198                         {
199                                 // search for a multi-bit gap in a single int
200                                 // (not dealing with the cases that cross two ints)
201                                 mask = (1<<needbits)-1;
202                                 endbit = 32-needbits;
203                                 bit = endbit;
204                                 for (index = 0;index < MEMBITINTS;index++)
205                                 {
206                                         value = array[index];
207                                         if (value != 0xFFFFFFFFu)
208                                         {
209                                                 // there may be room in this one...
210                                                 for (bit = 0;bit < endbit;bit++)
211                                                 {
212                                                         if (!(value & (mask<<bit)))
213                                                         {
214                                                                 startbit = index*32+bit;
215                                                                 goto foundblock;
216                                                         }
217                                                 }
218                                         }
219                                 }
220                                 goto nofreeblock;
221                         }
222 foundblock:
223                         endbit = startbit + needbits;
224                         // mark this range as used
225                         // TODO: optimize
226                         for (bit = startbit;bit < endbit;bit++)
227                                 if (clump->bits[bit>>5] & (1<<(bit & 31)))
228                                         Sys_Error("Clump_AllocBlock: internal error (%i needbits)\n", needbits);
229                         for (bit = startbit;bit < endbit;bit++)
230                                 clump->bits[bit>>5] |= (1<<(bit & 31));
231                         clump->blocksinuse += needbits;
232                         base = clump->block + startbit * MEMUNIT;
233                         if (developer_memorydebug.integer)
234                                 memset(base, 0xBF, needbits * MEMUNIT);
235                         return base;
236 nofreeblock:
237                         ;
238                 }
239                 // never reached
240                 return NULL;
241         }
242         // too big, allocate it directly
243 #endif
244 #if MEMCLUMPING == 2
245         return NULL;
246 #else
247         base = (unsigned char *)attempt_malloc(size);
248         if (base && developer_memorydebug.integer)
249                 memset(base, 0xAF, size);
250         return base;
251 #endif
252 }
253 static void Clump_FreeBlock(void *base, size_t size)
254 {
255 #if MEMCLUMPING
256         unsigned int needbits;
257         unsigned int startbit;
258         unsigned int endbit;
259         unsigned int bit;
260         memclump_t **clumpchainpointer;
261         memclump_t *clump;
262         unsigned char *start = (unsigned char *)base;
263         for (clumpchainpointer = &clumpchain;(clump = *clumpchainpointer);clumpchainpointer = &(*clumpchainpointer)->chain)
264         {
265                 if (start >= clump->block && start < clump->block + MEMCLUMPSIZE)
266                 {
267                         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
268                                 Sys_Error("Clump_FreeBlock: trashed sentinel1\n");
269                         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
270                                 Sys_Error("Clump_FreeBlock: trashed sentinel2\n");
271                         if (start + size > clump->block + MEMCLUMPSIZE)
272                                 Sys_Error("Clump_FreeBlock: block overrun\n");
273                         // the block belongs to this clump, clear the range
274                         needbits = (size + MEMUNIT - 1) / MEMUNIT;
275                         startbit = (start - clump->block) / MEMUNIT;
276                         endbit = startbit + needbits;
277                         // first verify all bits are set, otherwise this may be misaligned or a double free
278                         for (bit = startbit;bit < endbit;bit++)
279                                 if ((clump->bits[bit>>5] & (1<<(bit & 31))) == 0)
280                                         Sys_Error("Clump_FreeBlock: double free\n");
281                         for (bit = startbit;bit < endbit;bit++)
282                                 clump->bits[bit>>5] &= ~(1<<(bit & 31));
283                         clump->blocksinuse -= needbits;
284                         memset(base, 0xFF, needbits * MEMUNIT);
285                         // if all has been freed, free the clump itself
286                         if (clump->blocksinuse == 0)
287                         {
288                                 *clumpchainpointer = clump->chain;
289                                 if (developer_memorydebug.integer)
290                                         memset(clump, 0xFF, sizeof(*clump));
291 #if MEMCLUMPING != 2
292                                 free(clump);
293 #endif
294                         }
295                         return;
296                 }
297         }
298         // does not belong to any known chunk...  assume it was a direct allocation
299 #endif
300 #if MEMCLUMPING != 2
301         memset(base, 0xFF, size);
302         free(base);
303 #endif
304 }
305
306 void *_Mem_Alloc(mempool_t *pool, void *olddata, size_t size, size_t alignment, const char *filename, int fileline)
307 {
308         unsigned int sentinel1;
309         unsigned int sentinel2;
310         size_t realsize;
311         size_t sharedsize;
312         size_t remainsize;
313         memheader_t *mem;
314         memheader_t *oldmem;
315         unsigned char *base;
316
317         if (size <= 0)
318         {
319                 if (olddata)
320                         _Mem_Free(olddata, filename, fileline);
321                 return NULL;
322         }
323         if (pool == NULL)
324                 Sys_Error("Mem_Alloc: pool == NULL (alloc at %s:%i)", filename, fileline);
325         if (developer.integer && developer_memory.integer)
326                 Con_Printf("Mem_Alloc: pool %s, file %s:%i, size %i bytes\n", pool->name, filename, fileline, (int)size);
327         //if (developer.integer && developer_memorydebug.integer)
328         //      _Mem_CheckSentinelsGlobal(filename, fileline);
329         pool->totalsize += size;
330         realsize = alignment + sizeof(memheader_t) + size + sizeof(sentinel2);
331         pool->realsize += realsize;
332         base = (unsigned char *)Clump_AllocBlock(realsize);
333         if (base== NULL)
334                 Sys_Error("Mem_Alloc: out of memory (alloc at %s:%i)", filename, fileline);
335         // calculate address that aligns the end of the memheader_t to the specified alignment
336         mem = (memheader_t*)((((size_t)base + sizeof(memheader_t) + (alignment-1)) & ~(alignment-1)) - sizeof(memheader_t));
337         mem->baseaddress = (void*)base;
338         mem->filename = filename;
339         mem->fileline = fileline;
340         mem->size = size;
341         mem->pool = pool;
342
343         // calculate sentinels (detects buffer overruns, in a way that is hard to exploit)
344         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
345         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
346         mem->sentinel = sentinel1;
347         memcpy((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2));
348
349         // append to head of list
350         mem->next = pool->chain;
351         mem->prev = NULL;
352         pool->chain = mem;
353         if (mem->next)
354                 mem->next->prev = mem;
355
356         // copy the shared portion in the case of a realloc, then memset the rest
357         sharedsize = 0;
358         remainsize = size;
359         if (olddata)
360         {
361                 oldmem = (memheader_t*)olddata - 1;
362                 sharedsize = min(oldmem->size, size);
363                 memcpy((void *)((unsigned char *) mem + sizeof(memheader_t)), olddata, sharedsize);
364                 remainsize -= sharedsize;
365                 _Mem_Free(olddata, filename, fileline);
366         }
367         memset((void *)((unsigned char *) mem + sizeof(memheader_t) + sharedsize), 0, remainsize);
368         return (void *)((unsigned char *) mem + sizeof(memheader_t));
369 }
370
371 // only used by _Mem_Free and _Mem_FreePool
372 static void _Mem_FreeBlock(memheader_t *mem, const char *filename, int fileline)
373 {
374         mempool_t *pool;
375         size_t size;
376         size_t realsize;
377         unsigned int sentinel1;
378         unsigned int sentinel2;
379
380         // check sentinels (detects buffer overruns, in a way that is hard to exploit)
381         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
382         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
383         if (mem->sentinel != sentinel1)
384                 Sys_Error("Mem_Free: trashed header sentinel 1 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
385         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
386                 Sys_Error("Mem_Free: trashed header sentinel 2 (alloc at %s:%i, free at %s:%i)", mem->filename, mem->fileline, filename, fileline);
387
388         pool = mem->pool;
389         if (developer.integer && developer_memory.integer)
390                 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));
391         // unlink memheader from doubly linked list
392         if ((mem->prev ? mem->prev->next != mem : pool->chain != mem) || (mem->next && mem->next->prev != mem))
393                 Sys_Error("Mem_Free: not allocated or double freed (free at %s:%i)", filename, fileline);
394         if (mem->prev)
395                 mem->prev->next = mem->next;
396         else
397                 pool->chain = mem->next;
398         if (mem->next)
399                 mem->next->prev = mem->prev;
400         // memheader has been unlinked, do the actual free now
401         size = mem->size;
402         realsize = sizeof(memheader_t) + size + sizeof(sentinel2);
403         pool->totalsize -= size;
404         pool->realsize -= realsize;
405         Clump_FreeBlock(mem->baseaddress, realsize);
406 }
407
408 void _Mem_Free(void *data, const char *filename, int fileline)
409 {
410         if (data == NULL)
411         {
412                 Con_DPrintf("Mem_Free: data == NULL (called at %s:%i)\n", filename, fileline);
413                 return;
414         }
415
416         if (developer.integer && developer_memorydebug.integer)
417         {
418                 //_Mem_CheckSentinelsGlobal(filename, fileline);
419                 if (!Mem_IsAllocated(NULL, data))
420                         Sys_Error("Mem_Free: data is not allocated (called at %s:%i)", filename, fileline);
421         }
422
423         _Mem_FreeBlock((memheader_t *)((unsigned char *) data - sizeof(memheader_t)), filename, fileline);
424 }
425
426 mempool_t *_Mem_AllocPool(const char *name, int flags, mempool_t *parent, const char *filename, int fileline)
427 {
428         mempool_t *pool;
429         //if (developer.integer && developer_memorydebug.integer)
430         //      _Mem_CheckSentinelsGlobal(filename, fileline);
431         pool = (mempool_t *)Clump_AllocBlock(sizeof(mempool_t));
432         if (pool == NULL)
433                 Sys_Error("Mem_AllocPool: out of memory (allocpool at %s:%i)", filename, fileline);
434         memset(pool, 0, sizeof(mempool_t));
435         pool->sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1);
436         pool->sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2);
437         pool->filename = filename;
438         pool->fileline = fileline;
439         pool->flags = flags;
440         pool->chain = NULL;
441         pool->totalsize = 0;
442         pool->realsize = sizeof(mempool_t);
443         strlcpy (pool->name, name, sizeof (pool->name));
444         pool->parent = parent;
445         pool->next = poolchain;
446         poolchain = pool;
447         return pool;
448 }
449
450 void _Mem_FreePool(mempool_t **poolpointer, const char *filename, int fileline)
451 {
452         mempool_t *pool = *poolpointer;
453         mempool_t **chainaddress, *iter, *temp;
454
455         //if (developer.integer && developer_memorydebug.integer)
456         //      _Mem_CheckSentinelsGlobal(filename, fileline);
457         if (pool)
458         {
459                 // unlink pool from chain
460                 for (chainaddress = &poolchain;*chainaddress && *chainaddress != pool;chainaddress = &((*chainaddress)->next));
461                 if (*chainaddress != pool)
462                         Sys_Error("Mem_FreePool: pool already free (freepool at %s:%i)", filename, fileline);
463                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
464                         Sys_Error("Mem_FreePool: trashed pool sentinel 1 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
465                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
466                         Sys_Error("Mem_FreePool: trashed pool sentinel 2 (allocpool at %s:%i, freepool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
467                 *chainaddress = pool->next;
468
469                 // free memory owned by the pool
470                 while (pool->chain)
471                         _Mem_FreeBlock(pool->chain, filename, fileline);
472
473                 // free child pools, too
474                 for(iter = poolchain; iter; temp = iter = iter->next)
475                         if(iter->parent == pool)
476                                 _Mem_FreePool(&temp, filename, fileline);
477
478                 // free the pool itself
479                 Clump_FreeBlock(pool, sizeof(*pool));
480
481                 *poolpointer = NULL;
482         }
483 }
484
485 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
486 {
487         mempool_t *chainaddress;
488
489         if (developer.integer && developer_memorydebug.integer)
490         {
491                 //_Mem_CheckSentinelsGlobal(filename, fileline);
492                 // check if this pool is in the poolchain
493                 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
494                         if (chainaddress == pool)
495                                 break;
496                 if (!chainaddress)
497                         Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
498         }
499         if (pool == NULL)
500                 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
501         if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
502                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
503         if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
504                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
505
506         // free memory owned by the pool
507         while (pool->chain)
508                 _Mem_FreeBlock(pool->chain, filename, fileline);
509
510         // empty child pools, too
511         for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
512                 if(chainaddress->parent == pool)
513                         _Mem_EmptyPool(chainaddress, filename, fileline);
514
515 }
516
517 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
518 {
519         memheader_t *mem;
520         unsigned int sentinel1;
521         unsigned int sentinel2;
522
523         if (data == NULL)
524                 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
525
526         mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
527         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
528         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
529         if (mem->sentinel != sentinel1)
530                 Sys_Error("Mem_Free: trashed header sentinel 1 (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
531         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
532                 Sys_Error("Mem_Free: trashed header sentinel 2 (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
533 }
534
535 #if MEMCLUMPING
536 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
537 {
538         // this isn't really very useful
539         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
540                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
541         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
542                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
543 }
544 #endif
545
546 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
547 {
548         memheader_t *mem;
549 #if MEMCLUMPING
550         memclump_t *clump;
551 #endif
552         mempool_t *pool;
553         for (pool = poolchain;pool;pool = pool->next)
554         {
555                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
556                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
557                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
558                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
559         }
560         for (pool = poolchain;pool;pool = pool->next)
561                 for (mem = pool->chain;mem;mem = mem->next)
562                         _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
563 #if MEMCLUMPING
564         for (pool = poolchain;pool;pool = pool->next)
565                 for (clump = clumpchain;clump;clump = clump->chain)
566                         _Mem_CheckClumpSentinels(clump, filename, fileline);
567 #endif
568 }
569
570 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
571 {
572         memheader_t *header;
573         memheader_t *target;
574
575         if (pool)
576         {
577                 // search only one pool
578                 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
579                 for( header = pool->chain ; header ; header = header->next )
580                         if( header == target )
581                                 return true;
582         }
583         else
584         {
585                 // search all pools
586                 for (pool = poolchain;pool;pool = pool->next)
587                         if (Mem_IsAllocated(pool, data))
588                                 return true;
589         }
590         return false;
591 }
592
593 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
594 {
595         memset(l, 0, sizeof(*l));
596         l->mempool = mempool;
597         l->recordsize = recordsize;
598         l->numrecordsperarray = numrecordsperarray;
599 }
600
601 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
602 {
603         size_t i;
604         if (l->maxarrays)
605         {
606                 for (i = 0;i != l->numarrays;i++)
607                         Mem_Free(l->arrays[i].data);
608                 Mem_Free(l->arrays);
609         }
610         memset(l, 0, sizeof(*l));
611 }
612
613 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
614 {
615         size_t i, j;
616         for (i = 0;;i++)
617         {
618                 if (i == l->numarrays)
619                 {
620                         if (l->numarrays == l->maxarrays)
621                         {
622                                 memexpandablearray_array_t *oldarrays = l->arrays;
623                                 l->maxarrays = max(l->maxarrays * 2, 128);
624                                 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
625                                 if (oldarrays)
626                                 {
627                                         memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
628                                         Mem_Free(oldarrays);
629                                 }
630                         }
631                         l->arrays[i].numflaggedrecords = 0;
632                         l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
633                         l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
634                         l->numarrays++;
635                 }
636                 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
637                 {
638                         for (j = 0;j < l->numrecordsperarray;j++)
639                         {
640                                 if (!l->arrays[i].allocflags[j])
641                                 {
642                                         l->arrays[i].allocflags[j] = true;
643                                         l->arrays[i].numflaggedrecords++;
644                                         memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
645                                         return (void *)(l->arrays[i].data + l->recordsize * j);
646                                 }
647                         }
648                 }
649         }
650 }
651
652 /*****************************************************************************
653  * IF YOU EDIT THIS:
654  * If this function was to change the size of the "expandable" array, you have
655  * to update r_shadow.c
656  * Just do a search for "range =", R_ShadowClearWorldLights would be the first
657  * function to look at. (And also seems like the only one?) You  might have to
658  * move the  call to Mem_ExpandableArray_IndexRange  back into for(...) loop's
659  * condition
660  */
661 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
662 {
663         size_t i, j;
664         unsigned char *p = (unsigned char *)record;
665         for (i = 0;i != l->numarrays;i++)
666         {
667                 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
668                 {
669                         j = (p - l->arrays[i].data) / l->recordsize;
670                         if (p != l->arrays[i].data + j * l->recordsize)
671                                 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
672                         if (!l->arrays[i].allocflags[j])
673                                 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
674                         l->arrays[i].allocflags[j] = false;
675                         l->arrays[i].numflaggedrecords--;
676                         return;
677                 }
678         }
679 }
680
681 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
682 {
683         size_t i, j, k, end = 0;
684         for (i = 0;i < l->numarrays;i++)
685         {
686                 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
687                 {
688                         if (l->arrays[i].allocflags[j])
689                         {
690                                 end = l->numrecordsperarray * i + j + 1;
691                                 k++;
692                         }
693                 }
694         }
695         return end;
696 }
697
698 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
699 {
700         size_t i, j;
701         i = index / l->numrecordsperarray;
702         j = index % l->numrecordsperarray;
703         if (i >= l->numarrays || !l->arrays[i].allocflags[j])
704                 return NULL;
705         return (void *)(l->arrays[i].data + j * l->recordsize);
706 }
707
708
709 // used for temporary memory allocations around the engine, not for longterm
710 // storage, if anything in this pool stays allocated during gameplay, it is
711 // considered a leak
712 mempool_t *tempmempool;
713 // only for zone
714 mempool_t *zonemempool;
715
716 void Mem_PrintStats(void)
717 {
718         size_t count = 0, size = 0, realsize = 0;
719         mempool_t *pool;
720         memheader_t *mem;
721         Mem_CheckSentinelsGlobal();
722         for (pool = poolchain;pool;pool = pool->next)
723         {
724                 count++;
725                 size += pool->totalsize;
726                 realsize += pool->realsize;
727         }
728         Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
729         Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
730         for (pool = poolchain;pool;pool = pool->next)
731         {
732                 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
733                 {
734                         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);
735                         for (mem = pool->chain;mem;mem = mem->next)
736                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
737                 }
738         }
739 }
740
741 void Mem_PrintList(size_t minallocationsize)
742 {
743         mempool_t *pool;
744         memheader_t *mem;
745         Mem_CheckSentinelsGlobal();
746         Con_Print("memory pool list:\n"
747                    "size    name\n");
748         for (pool = poolchain;pool;pool = pool->next)
749         {
750                 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" : "");
751                 pool->lastchecksize = pool->totalsize;
752                 for (mem = pool->chain;mem;mem = mem->next)
753                         if (mem->size >= minallocationsize)
754                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
755         }
756 }
757
758 void MemList_f(void)
759 {
760         switch(Cmd_Argc())
761         {
762         case 1:
763                 Mem_PrintList(1<<30);
764                 Mem_PrintStats();
765                 break;
766         case 2:
767                 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
768                 Mem_PrintStats();
769                 break;
770         default:
771                 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
772                 break;
773         }
774 }
775
776 extern void R_TextureStats_Print(qboolean printeach, qboolean printpool, qboolean printtotal);
777 void MemStats_f(void)
778 {
779         Mem_CheckSentinelsGlobal();
780         R_TextureStats_Print(false, false, true);
781         GL_Mesh_ListVBOs(false);
782         Mem_PrintStats();
783 }
784
785
786 char* Mem_strdup (mempool_t *pool, const char* s)
787 {
788         char* p;
789         size_t sz = strlen (s) + 1;
790         if (s == NULL) return NULL;
791         p = (char*)Mem_Alloc (pool, sz);
792         strlcpy (p, s, sz);
793         return p;
794 }
795
796 /*
797 ========================
798 Memory_Init
799 ========================
800 */
801 void Memory_Init (void)
802 {
803         sentinel_seed = rand();
804         poolchain = NULL;
805         tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
806         zonemempool = Mem_AllocPool("Zone", 0, NULL);
807 }
808
809 void Memory_Shutdown (void)
810 {
811 //      Mem_FreePool (&zonemempool);
812 //      Mem_FreePool (&tempmempool);
813 }
814
815 void Memory_Init_Commands (void)
816 {
817         Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
818         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)");
819         Cvar_RegisterVariable (&developer_memory);
820         Cvar_RegisterVariable (&developer_memorydebug);
821 }
822