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