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