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