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