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