]> de.git.xonotic.org Git - xonotic/darkplaces.git/blob - zone.c
optimized vm by using cached local variables instead of accessing prog->
[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; temp = iter = iter->next)
562                         if(iter->parent == pool)
563                                 _Mem_FreePool(&temp, filename, fileline);
564
565                 // free the pool itself
566                 Clump_FreeBlock(pool, sizeof(*pool));
567
568                 *poolpointer = NULL;
569         }
570 }
571
572 void _Mem_EmptyPool(mempool_t *pool, const char *filename, int fileline)
573 {
574         mempool_t *chainaddress;
575
576         if (developer_memorydebug.integer)
577         {
578                 //_Mem_CheckSentinelsGlobal(filename, fileline);
579                 // check if this pool is in the poolchain
580                 for (chainaddress = poolchain;chainaddress;chainaddress = chainaddress->next)
581                         if (chainaddress == pool)
582                                 break;
583                 if (!chainaddress)
584                         Sys_Error("Mem_EmptyPool: pool is already free (emptypool at %s:%i)", filename, fileline);
585         }
586         if (pool == NULL)
587                 Sys_Error("Mem_EmptyPool: pool == NULL (emptypool at %s:%i)", filename, fileline);
588         if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
589                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 1 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
590         if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
591                 Sys_Error("Mem_EmptyPool: trashed pool sentinel 2 (allocpool at %s:%i, emptypool at %s:%i)", pool->filename, pool->fileline, filename, fileline);
592
593         // free memory owned by the pool
594         while (pool->chain)
595                 _Mem_FreeBlock(pool->chain, filename, fileline);
596
597         // empty child pools, too
598         for(chainaddress = poolchain; chainaddress; chainaddress = chainaddress->next)
599                 if(chainaddress->parent == pool)
600                         _Mem_EmptyPool(chainaddress, filename, fileline);
601
602 }
603
604 void _Mem_CheckSentinels(void *data, const char *filename, int fileline)
605 {
606         memheader_t *mem;
607         unsigned int sentinel1;
608         unsigned int sentinel2;
609
610         if (data == NULL)
611                 Sys_Error("Mem_CheckSentinels: data == NULL (sentinel check at %s:%i)", filename, fileline);
612
613         mem = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
614         sentinel1 = MEMHEADER_SENTINEL_FOR_ADDRESS(&mem->sentinel);
615         sentinel2 = MEMHEADER_SENTINEL_FOR_ADDRESS((unsigned char *) mem + sizeof(memheader_t) + mem->size);
616         if (mem->sentinel != sentinel1)
617                 Sys_Error("Mem_Free: trashed head sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
618         if (memcmp((unsigned char *) mem + sizeof(memheader_t) + mem->size, &sentinel2, sizeof(sentinel2)))
619                 Sys_Error("Mem_Free: trashed tail sentinel (alloc at %s:%i, sentinel check at %s:%i)", mem->filename, mem->fileline, filename, fileline);
620 }
621
622 #if MEMCLUMPING
623 static void _Mem_CheckClumpSentinels(memclump_t *clump, const char *filename, int fileline)
624 {
625         // this isn't really very useful
626         if (clump->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel1))
627                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 1 (sentinel check at %s:%i)", filename, fileline);
628         if (clump->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&clump->sentinel2))
629                 Sys_Error("Mem_CheckClumpSentinels: trashed sentinel 2 (sentinel check at %s:%i)", filename, fileline);
630 }
631 #endif
632
633 void _Mem_CheckSentinelsGlobal(const char *filename, int fileline)
634 {
635         memheader_t *mem;
636 #if MEMCLUMPING
637         memclump_t *clump;
638 #endif
639         mempool_t *pool;
640         for (pool = poolchain;pool;pool = pool->next)
641         {
642                 if (pool->sentinel1 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel1))
643                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 1 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
644                 if (pool->sentinel2 != MEMHEADER_SENTINEL_FOR_ADDRESS(&pool->sentinel2))
645                         Sys_Error("Mem_CheckSentinelsGlobal: trashed pool sentinel 2 (allocpool at %s:%i, sentinel check at %s:%i)", pool->filename, pool->fileline, filename, fileline);
646         }
647         for (pool = poolchain;pool;pool = pool->next)
648                 for (mem = pool->chain;mem;mem = mem->next)
649                         _Mem_CheckSentinels((void *)((unsigned char *) mem + sizeof(memheader_t)), filename, fileline);
650 #if MEMCLUMPING
651         for (pool = poolchain;pool;pool = pool->next)
652                 for (clump = clumpchain;clump;clump = clump->chain)
653                         _Mem_CheckClumpSentinels(clump, filename, fileline);
654 #endif
655 }
656
657 qboolean Mem_IsAllocated(mempool_t *pool, void *data)
658 {
659         memheader_t *header;
660         memheader_t *target;
661
662         if (pool)
663         {
664                 // search only one pool
665                 target = (memheader_t *)((unsigned char *) data - sizeof(memheader_t));
666                 for( header = pool->chain ; header ; header = header->next )
667                         if( header == target )
668                                 return true;
669         }
670         else
671         {
672                 // search all pools
673                 for (pool = poolchain;pool;pool = pool->next)
674                         if (Mem_IsAllocated(pool, data))
675                                 return true;
676         }
677         return false;
678 }
679
680 void Mem_ExpandableArray_NewArray(memexpandablearray_t *l, mempool_t *mempool, size_t recordsize, int numrecordsperarray)
681 {
682         memset(l, 0, sizeof(*l));
683         l->mempool = mempool;
684         l->recordsize = recordsize;
685         l->numrecordsperarray = numrecordsperarray;
686 }
687
688 void Mem_ExpandableArray_FreeArray(memexpandablearray_t *l)
689 {
690         size_t i;
691         if (l->maxarrays)
692         {
693                 for (i = 0;i != l->numarrays;i++)
694                         Mem_Free(l->arrays[i].data);
695                 Mem_Free(l->arrays);
696         }
697         memset(l, 0, sizeof(*l));
698 }
699
700 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
701 {
702         size_t i, j;
703         for (i = 0;;i++)
704         {
705                 if (i == l->numarrays)
706                 {
707                         if (l->numarrays == l->maxarrays)
708                         {
709                                 memexpandablearray_array_t *oldarrays = l->arrays;
710                                 l->maxarrays = max(l->maxarrays * 2, 128);
711                                 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
712                                 if (oldarrays)
713                                 {
714                                         memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
715                                         Mem_Free(oldarrays);
716                                 }
717                         }
718                         l->arrays[i].numflaggedrecords = 0;
719                         l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
720                         l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
721                         l->numarrays++;
722                 }
723                 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
724                 {
725                         for (j = 0;j < l->numrecordsperarray;j++)
726                         {
727                                 if (!l->arrays[i].allocflags[j])
728                                 {
729                                         l->arrays[i].allocflags[j] = true;
730                                         l->arrays[i].numflaggedrecords++;
731                                         memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
732                                         return (void *)(l->arrays[i].data + l->recordsize * j);
733                                 }
734                         }
735                 }
736         }
737 }
738
739 /*****************************************************************************
740  * IF YOU EDIT THIS:
741  * If this function was to change the size of the "expandable" array, you have
742  * to update r_shadow.c
743  * Just do a search for "range =", R_ShadowClearWorldLights would be the first
744  * function to look at. (And also seems like the only one?) You  might have to
745  * move the  call to Mem_ExpandableArray_IndexRange  back into for(...) loop's
746  * condition
747  */
748 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
749 {
750         size_t i, j;
751         unsigned char *p = (unsigned char *)record;
752         for (i = 0;i != l->numarrays;i++)
753         {
754                 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
755                 {
756                         j = (p - l->arrays[i].data) / l->recordsize;
757                         if (p != l->arrays[i].data + j * l->recordsize)
758                                 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
759                         if (!l->arrays[i].allocflags[j])
760                                 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
761                         l->arrays[i].allocflags[j] = false;
762                         l->arrays[i].numflaggedrecords--;
763                         return;
764                 }
765         }
766 }
767
768 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
769 {
770         size_t i, j, k, end = 0;
771         for (i = 0;i < l->numarrays;i++)
772         {
773                 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
774                 {
775                         if (l->arrays[i].allocflags[j])
776                         {
777                                 end = l->numrecordsperarray * i + j + 1;
778                                 k++;
779                         }
780                 }
781         }
782         return end;
783 }
784
785 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
786 {
787         size_t i, j;
788         i = index / l->numrecordsperarray;
789         j = index % l->numrecordsperarray;
790         if (i >= l->numarrays || !l->arrays[i].allocflags[j])
791                 return NULL;
792         return (void *)(l->arrays[i].data + j * l->recordsize);
793 }
794
795
796 // used for temporary memory allocations around the engine, not for longterm
797 // storage, if anything in this pool stays allocated during gameplay, it is
798 // considered a leak
799 mempool_t *tempmempool;
800 // only for zone
801 mempool_t *zonemempool;
802
803 void Mem_PrintStats(void)
804 {
805         size_t count = 0, size = 0, realsize = 0;
806         mempool_t *pool;
807         memheader_t *mem;
808         Mem_CheckSentinelsGlobal();
809         for (pool = poolchain;pool;pool = pool->next)
810         {
811                 count++;
812                 size += pool->totalsize;
813                 realsize += pool->realsize;
814         }
815         Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
816         Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
817         for (pool = poolchain;pool;pool = pool->next)
818         {
819                 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
820                 {
821                         Con_Printf("Memory pool %p has sprung a leak totalling %lu bytes (%.3fMB)!  Listing contents...\n", (void *)pool, (unsigned long)pool->totalsize, pool->totalsize / 1048576.0);
822                         for (mem = pool->chain;mem;mem = mem->next)
823                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
824                 }
825         }
826 }
827
828 void Mem_PrintList(size_t minallocationsize)
829 {
830         mempool_t *pool;
831         memheader_t *mem;
832         Mem_CheckSentinelsGlobal();
833         Con_Print("memory pool list:\n"
834                    "size    name\n");
835         for (pool = poolchain;pool;pool = pool->next)
836         {
837                 Con_Printf("%10luk (%10luk actual) %s (%+li byte change) %s\n", (unsigned long) ((pool->totalsize + 1023) / 1024), (unsigned long)((pool->realsize + 1023) / 1024), pool->name, (long)(pool->totalsize - pool->lastchecksize), (pool->flags & POOLFLAG_TEMP) ? "TEMP" : "");
838                 pool->lastchecksize = pool->totalsize;
839                 for (mem = pool->chain;mem;mem = mem->next)
840                         if (mem->size >= minallocationsize)
841                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
842         }
843 }
844
845 static void MemList_f(void)
846 {
847         switch(Cmd_Argc())
848         {
849         case 1:
850                 Mem_PrintList(1<<30);
851                 Mem_PrintStats();
852                 break;
853         case 2:
854                 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
855                 Mem_PrintStats();
856                 break;
857         default:
858                 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
859                 break;
860         }
861 }
862
863 static void MemStats_f(void)
864 {
865         Mem_CheckSentinelsGlobal();
866         R_TextureStats_Print(false, false, true);
867         GL_Mesh_ListVBOs(false);
868         Mem_PrintStats();
869 }
870
871
872 char* Mem_strdup (mempool_t *pool, const char* s)
873 {
874         char* p;
875         size_t sz;
876         if (s == NULL)
877                 return NULL;
878         sz = strlen (s) + 1;
879         p = (char*)Mem_Alloc (pool, sz);
880         strlcpy (p, s, sz);
881         return p;
882 }
883
884 /*
885 ========================
886 Memory_Init
887 ========================
888 */
889 void Memory_Init (void)
890 {
891         static union {unsigned short s;unsigned char b[2];} u;
892         u.s = 0x100;
893         mem_bigendian = u.b[0] != 0;
894
895         sentinel_seed = rand();
896         poolchain = NULL;
897         tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
898         zonemempool = Mem_AllocPool("Zone", 0, NULL);
899
900         if (Thread_HasThreads())
901                 mem_mutex = Thread_CreateMutex();
902 }
903
904 void Memory_Shutdown (void)
905 {
906 //      Mem_FreePool (&zonemempool);
907 //      Mem_FreePool (&tempmempool);
908
909         if (mem_mutex)
910                 Thread_DestroyMutex(mem_mutex);
911         mem_mutex = NULL;
912 }
913
914 void Memory_Init_Commands (void)
915 {
916         Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
917         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)");
918         Cvar_RegisterVariable (&developer_memory);
919         Cvar_RegisterVariable (&developer_memorydebug);
920         Cvar_RegisterVariable (&sys_memsize_physical);
921         Cvar_RegisterVariable (&sys_memsize_virtual);
922
923 #if defined(WIN32)
924 #ifdef _WIN64
925         {
926                 MEMORYSTATUSEX status;
927                 // first guess
928                 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
929                 // then improve
930                 status.dwLength = sizeof(status);
931                 if(GlobalMemoryStatusEx(&status))
932                 {
933                         Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
934                         Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
935                 }
936         }
937 #else
938         {
939                 MEMORYSTATUS status;
940                 // first guess
941                 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
942                 // then improve
943                 status.dwLength = sizeof(status);
944                 GlobalMemoryStatus(&status);
945                 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
946                 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
947         }
948 #endif
949 #else
950         {
951                 // first guess
952                 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
953                 // then improve
954                 {
955                         // Linux, and BSD with linprocfs mounted
956                         FILE *f = fopen("/proc/meminfo", "r");
957                         if(f)
958                         {
959                                 static char buf[1024];
960                                 while(fgets(buf, sizeof(buf), f))
961                                 {
962                                         const char *p = buf;
963                                         if(!COM_ParseToken_Console(&p))
964                                                 continue;
965                                         if(!strcmp(com_token, "MemTotal:"))
966                                         {
967                                                 if(!COM_ParseToken_Console(&p))
968                                                         continue;
969                                                 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
970                                         }
971                                         if(!strcmp(com_token, "SwapTotal:"))
972                                         {
973                                                 if(!COM_ParseToken_Console(&p))
974                                                         continue;
975                                                 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));
976                                         }
977                                 }
978                                 fclose(f);
979                         }
980                 }
981         }
982 #endif
983 }
984