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