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