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