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