]> de.git.xonotic.org Git - voretournament/voretournament.git/blob - misc/source/darkplaces-src/zone.c
Update the prebuilt engines to latest version of darkplaces. Also put Linux rebrand...
[voretournament/voretournament.git] / misc / source / darkplaces-src / 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 // VorteX: hacked Mem_ExpandableArray_AllocRecord, it does allocate record at certain index
701 void *Mem_ExpandableArray_AllocRecordAtIndex(memexpandablearray_t *l, size_t index)
702 {
703         size_t j;
704         if (index >= l->numarrays)
705         {
706                 if (l->numarrays == l->maxarrays)
707                 {
708                         memexpandablearray_array_t *oldarrays = l->arrays;
709                         l->maxarrays = max(l->maxarrays * 2, 128);
710                         l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
711                         if (oldarrays)
712                         {
713                                 memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
714                                 Mem_Free(oldarrays);
715                         }
716                 }
717                 l->arrays[index].numflaggedrecords = 0;
718                 l->arrays[index].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
719                 l->arrays[index].allocflags = l->arrays[index].data + l->recordsize * l->numrecordsperarray;
720                 l->numarrays++;
721         }
722         if (l->arrays[index].numflaggedrecords < l->numrecordsperarray)
723         {
724                 for (j = 0;j < l->numrecordsperarray;j++)
725                 {
726                         if (!l->arrays[index].allocflags[j])
727                         {
728                                 l->arrays[index].allocflags[j] = true;
729                                 l->arrays[index].numflaggedrecords++;
730                                 memset(l->arrays[index].data + l->recordsize * j, 0, l->recordsize);
731                                 return (void *)(l->arrays[index].data + l->recordsize * j);
732                         }
733                 }
734         }
735         return NULL;
736 }
737
738 void *Mem_ExpandableArray_AllocRecord(memexpandablearray_t *l)
739 {
740         size_t i, j;
741         for (i = 0;;i++)
742         {
743                 if (i == l->numarrays)
744                 {
745                         if (l->numarrays == l->maxarrays)
746                         {
747                                 memexpandablearray_array_t *oldarrays = l->arrays;
748                                 l->maxarrays = max(l->maxarrays * 2, 128);
749                                 l->arrays = (memexpandablearray_array_t*) Mem_Alloc(l->mempool, l->maxarrays * sizeof(*l->arrays));
750                                 if (oldarrays)
751                                 {
752                                         memcpy(l->arrays, oldarrays, l->numarrays * sizeof(*l->arrays));
753                                         Mem_Free(oldarrays);
754                                 }
755                         }
756                         l->arrays[i].numflaggedrecords = 0;
757                         l->arrays[i].data = (unsigned char *) Mem_Alloc(l->mempool, (l->recordsize + 1) * l->numrecordsperarray);
758                         l->arrays[i].allocflags = l->arrays[i].data + l->recordsize * l->numrecordsperarray;
759                         l->numarrays++;
760                 }
761                 if (l->arrays[i].numflaggedrecords < l->numrecordsperarray)
762                 {
763                         for (j = 0;j < l->numrecordsperarray;j++)
764                         {
765                                 if (!l->arrays[i].allocflags[j])
766                                 {
767                                         l->arrays[i].allocflags[j] = true;
768                                         l->arrays[i].numflaggedrecords++;
769                                         memset(l->arrays[i].data + l->recordsize * j, 0, l->recordsize);
770                                         return (void *)(l->arrays[i].data + l->recordsize * j);
771                                 }
772                         }
773                 }
774         }
775 }
776
777 /*****************************************************************************
778  * IF YOU EDIT THIS:
779  * If this function was to change the size of the "expandable" array, you have
780  * to update r_shadow.c
781  * Just do a search for "range =", R_ShadowClearWorldLights would be the first
782  * function to look at. (And also seems like the only one?) You  might have to
783  * move the  call to Mem_ExpandableArray_IndexRange  back into for(...) loop's
784  * condition
785  */
786 void Mem_ExpandableArray_FreeRecord(memexpandablearray_t *l, void *record) // const!
787 {
788         size_t i, j;
789         unsigned char *p = (unsigned char *)record;
790         for (i = 0;i != l->numarrays;i++)
791         {
792                 if (p >= l->arrays[i].data && p < (l->arrays[i].data + l->recordsize * l->numrecordsperarray))
793                 {
794                         j = (p - l->arrays[i].data) / l->recordsize;
795                         if (p != l->arrays[i].data + j * l->recordsize)
796                                 Sys_Error("Mem_ExpandableArray_FreeRecord: no such record %p\n", p);
797                         if (!l->arrays[i].allocflags[j])
798                                 Sys_Error("Mem_ExpandableArray_FreeRecord: record %p is already free!\n", p);
799                         l->arrays[i].allocflags[j] = false;
800                         l->arrays[i].numflaggedrecords--;
801                         return;
802                 }
803         }
804 }
805
806 size_t Mem_ExpandableArray_IndexRange(const memexpandablearray_t *l)
807 {
808         size_t i, j, k, end = 0;
809         for (i = 0;i < l->numarrays;i++)
810         {
811                 for (j = 0, k = 0;k < l->arrays[i].numflaggedrecords;j++)
812                 {
813                         if (l->arrays[i].allocflags[j])
814                         {
815                                 end = l->numrecordsperarray * i + j + 1;
816                                 k++;
817                         }
818                 }
819         }
820         return end;
821 }
822
823 void *Mem_ExpandableArray_RecordAtIndex(const memexpandablearray_t *l, size_t index)
824 {
825         size_t i, j;
826         i = index / l->numrecordsperarray;
827         j = index % l->numrecordsperarray;
828         if (i >= l->numarrays || !l->arrays[i].allocflags[j])
829                 return NULL;
830         return (void *)(l->arrays[i].data + j * l->recordsize);
831 }
832
833
834 // used for temporary memory allocations around the engine, not for longterm
835 // storage, if anything in this pool stays allocated during gameplay, it is
836 // considered a leak
837 mempool_t *tempmempool;
838 // only for zone
839 mempool_t *zonemempool;
840
841 void Mem_PrintStats(void)
842 {
843         size_t count = 0, size = 0, realsize = 0;
844         mempool_t *pool;
845         memheader_t *mem;
846         Mem_CheckSentinelsGlobal();
847         for (pool = poolchain;pool;pool = pool->next)
848         {
849                 count++;
850                 size += pool->totalsize;
851                 realsize += pool->realsize;
852         }
853         Con_Printf("%lu memory pools, totalling %lu bytes (%.3fMB)\n", (unsigned long)count, (unsigned long)size, size / 1048576.0);
854         Con_Printf("total allocated size: %lu bytes (%.3fMB)\n", (unsigned long)realsize, realsize / 1048576.0);
855         for (pool = poolchain;pool;pool = pool->next)
856         {
857                 if ((pool->flags & POOLFLAG_TEMP) && pool->chain)
858                 {
859                         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);
860                         for (mem = pool->chain;mem;mem = mem->next)
861                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
862                 }
863         }
864 }
865
866 void Mem_PrintList(size_t minallocationsize)
867 {
868         mempool_t *pool;
869         memheader_t *mem;
870         Mem_CheckSentinelsGlobal();
871         Con_Print("memory pool list:\n"
872                    "size    name\n");
873         for (pool = poolchain;pool;pool = pool->next)
874         {
875                 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" : "");
876                 pool->lastchecksize = pool->totalsize;
877                 for (mem = pool->chain;mem;mem = mem->next)
878                         if (mem->size >= minallocationsize)
879                                 Con_Printf("%10lu bytes allocated at %s:%i\n", (unsigned long)mem->size, mem->filename, mem->fileline);
880         }
881 }
882
883 static void MemList_f(void)
884 {
885         switch(Cmd_Argc())
886         {
887         case 1:
888                 Mem_PrintList(1<<30);
889                 Mem_PrintStats();
890                 break;
891         case 2:
892                 Mem_PrintList(atoi(Cmd_Argv(1)) * 1024);
893                 Mem_PrintStats();
894                 break;
895         default:
896                 Con_Print("MemList_f: unrecognized options\nusage: memlist [all]\n");
897                 break;
898         }
899 }
900
901 static void MemStats_f(void)
902 {
903         Mem_CheckSentinelsGlobal();
904         R_TextureStats_Print(false, false, true);
905         GL_Mesh_ListVBOs(false);
906         Mem_PrintStats();
907 }
908
909
910 char* Mem_strdup (mempool_t *pool, const char* s)
911 {
912         char* p;
913         size_t sz;
914         if (s == NULL)
915                 return NULL;
916         sz = strlen (s) + 1;
917         p = (char*)Mem_Alloc (pool, sz);
918         strlcpy (p, s, sz);
919         return p;
920 }
921
922 /*
923 ========================
924 Memory_Init
925 ========================
926 */
927 void Memory_Init (void)
928 {
929         static union {unsigned short s;unsigned char b[2];} u;
930         u.s = 0x100;
931         mem_bigendian = u.b[0] != 0;
932
933         sentinel_seed = rand();
934         poolchain = NULL;
935         tempmempool = Mem_AllocPool("Temporary Memory", POOLFLAG_TEMP, NULL);
936         zonemempool = Mem_AllocPool("Zone", 0, NULL);
937
938         if (Thread_HasThreads())
939                 mem_mutex = Thread_CreateMutex();
940 }
941
942 void Memory_Shutdown (void)
943 {
944 //      Mem_FreePool (&zonemempool);
945 //      Mem_FreePool (&tempmempool);
946
947         if (mem_mutex)
948                 Thread_DestroyMutex(mem_mutex);
949         mem_mutex = NULL;
950 }
951
952 void Memory_Init_Commands (void)
953 {
954         Cmd_AddCommand ("memstats", MemStats_f, "prints memory system statistics");
955         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)");
956         Cvar_RegisterVariable (&developer_memory);
957         Cvar_RegisterVariable (&developer_memorydebug);
958         Cvar_RegisterVariable (&sys_memsize_physical);
959         Cvar_RegisterVariable (&sys_memsize_virtual);
960
961 #if defined(WIN32)
962 #ifdef _WIN64
963         {
964                 MEMORYSTATUSEX status;
965                 // first guess
966                 Cvar_SetValueQuick(&sys_memsize_virtual, 8388608);
967                 // then improve
968                 status.dwLength = sizeof(status);
969                 if(GlobalMemoryStatusEx(&status))
970                 {
971                         Cvar_SetValueQuick(&sys_memsize_physical, status.ullTotalPhys / 1048576.0);
972                         Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.ullTotalVirtual / 1048576.0));
973                 }
974         }
975 #else
976         {
977                 MEMORYSTATUS status;
978                 // first guess
979                 Cvar_SetValueQuick(&sys_memsize_virtual, 2048);
980                 // then improve
981                 status.dwLength = sizeof(status);
982                 GlobalMemoryStatus(&status);
983                 Cvar_SetValueQuick(&sys_memsize_physical, status.dwTotalPhys / 1048576.0);
984                 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value, status.dwTotalVirtual / 1048576.0));
985         }
986 #endif
987 #else
988         {
989                 // first guess
990                 Cvar_SetValueQuick(&sys_memsize_virtual, (sizeof(void*) == 4) ? 2048 : 268435456);
991                 // then improve
992                 {
993                         // Linux, and BSD with linprocfs mounted
994                         FILE *f = fopen("/proc/meminfo", "r");
995                         if(f)
996                         {
997                                 static char buf[1024];
998                                 while(fgets(buf, sizeof(buf), f))
999                                 {
1000                                         const char *p = buf;
1001                                         if(!COM_ParseToken_Console(&p))
1002                                                 continue;
1003                                         if(!strcmp(com_token, "MemTotal:"))
1004                                         {
1005                                                 if(!COM_ParseToken_Console(&p))
1006                                                         continue;
1007                                                 Cvar_SetValueQuick(&sys_memsize_physical, atof(com_token) / 1024.0);
1008                                         }
1009                                         if(!strcmp(com_token, "SwapTotal:"))
1010                                         {
1011                                                 if(!COM_ParseToken_Console(&p))
1012                                                         continue;
1013                                                 Cvar_SetValueQuick(&sys_memsize_virtual, min(sys_memsize_virtual.value , atof(com_token) / 1024.0 + sys_memsize_physical.value));
1014                                         }
1015                                 }
1016                                 fclose(f);
1017                         }
1018                 }
1019         }
1020 #endif
1021 }
1022