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