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