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